source: code/trunk/downstream.go@ 463

Last change on this file since 463 was 463, checked in by contact, 4 years ago

Passthrough some ISUPPORT tokens

File size: 46.6 KB
Line 
1package soju
2
3import (
4 "crypto/tls"
5 "encoding/base64"
6 "fmt"
7 "io"
8 "net"
9 "strconv"
10 "strings"
11 "time"
12
13 "github.com/emersion/go-sasl"
14 "golang.org/x/crypto/bcrypt"
15 "gopkg.in/irc.v3"
16)
17
18type ircError struct {
19 Message *irc.Message
20}
21
22func (err ircError) Error() string {
23 return err.Message.String()
24}
25
26func newUnknownCommandError(cmd string) ircError {
27 return ircError{&irc.Message{
28 Command: irc.ERR_UNKNOWNCOMMAND,
29 Params: []string{
30 "*",
31 cmd,
32 "Unknown command",
33 },
34 }}
35}
36
37func newNeedMoreParamsError(cmd string) ircError {
38 return ircError{&irc.Message{
39 Command: irc.ERR_NEEDMOREPARAMS,
40 Params: []string{
41 "*",
42 cmd,
43 "Not enough parameters",
44 },
45 }}
46}
47
48func newChatHistoryError(subcommand string, target string) ircError {
49 return ircError{&irc.Message{
50 Command: "FAIL",
51 Params: []string{"CHATHISTORY", "MESSAGE_ERROR", subcommand, target, "Messages could not be retrieved"},
52 }}
53}
54
55var errAuthFailed = ircError{&irc.Message{
56 Command: irc.ERR_PASSWDMISMATCH,
57 Params: []string{"*", "Invalid username or password"},
58}}
59
60// ' ' and ':' break the IRC message wire format, '@' and '!' break prefixes,
61// '*' and '?' break masks
62const illegalNickChars = " :@!*?"
63
64// permanentDownstreamCaps is the list of always-supported downstream
65// capabilities.
66var permanentDownstreamCaps = map[string]string{
67 "batch": "",
68 "cap-notify": "",
69 "echo-message": "",
70 "invite-notify": "",
71 "message-tags": "",
72 "sasl": "PLAIN",
73 "server-time": "",
74}
75
76// needAllDownstreamCaps is the list of downstream capabilities that
77// require support from all upstreams to be enabled
78var needAllDownstreamCaps = map[string]string{
79 "away-notify": "",
80 "extended-join": "",
81 "multi-prefix": "",
82}
83
84// passthroughIsupport is the set of ISUPPORT tokens that are directly passed
85// through from the upstream server to downstream clients.
86//
87// This is only effective in single-upstream mode.
88var passthroughIsupport = map[string]bool{
89 "AWAYLEN": true,
90 "CHANLIMIT": true,
91 "CHANMODES": true,
92 "CHANNELLEN": true,
93 "CHANTYPES": true,
94 "EXCEPTS": true,
95 "EXTBAN": true,
96 "HOSTLEN": true,
97 "INVEX": true,
98 "KICKLEN": true,
99 "MAXLIST": true,
100 "MAXTARGETS": true,
101 "MODES": true,
102 "NETWORK": true,
103 "NICKLEN": true,
104 "PREFIX": true,
105 "SAFELIST": true,
106 "TARGMAX": true,
107 "TOPICLEN": true,
108 "USERLEN": true,
109}
110
111type downstreamConn struct {
112 conn
113
114 id uint64
115
116 registered bool
117 user *user
118 nick string
119 rawUsername string
120 networkName string
121 clientName string
122 realname string
123 hostname string
124 password string // empty after authentication
125 network *network // can be nil
126
127 negociatingCaps bool
128 capVersion int
129 supportedCaps map[string]string
130 caps map[string]bool
131
132 saslServer sasl.Server
133}
134
135func newDownstreamConn(srv *Server, ic ircConn, id uint64) *downstreamConn {
136 remoteAddr := ic.RemoteAddr().String()
137 logger := &prefixLogger{srv.Logger, fmt.Sprintf("downstream %q: ", remoteAddr)}
138 options := connOptions{Logger: logger}
139 dc := &downstreamConn{
140 conn: *newConn(srv, ic, &options),
141 id: id,
142 supportedCaps: make(map[string]string),
143 caps: make(map[string]bool),
144 }
145 dc.hostname = remoteAddr
146 if host, _, err := net.SplitHostPort(dc.hostname); err == nil {
147 dc.hostname = host
148 }
149 for k, v := range permanentDownstreamCaps {
150 dc.supportedCaps[k] = v
151 }
152 if srv.LogPath != "" {
153 dc.supportedCaps["draft/chathistory"] = ""
154 }
155 return dc
156}
157
158func (dc *downstreamConn) prefix() *irc.Prefix {
159 return &irc.Prefix{
160 Name: dc.nick,
161 User: dc.user.Username,
162 Host: dc.hostname,
163 }
164}
165
166func (dc *downstreamConn) forEachNetwork(f func(*network)) {
167 if dc.network != nil {
168 f(dc.network)
169 } else {
170 dc.user.forEachNetwork(f)
171 }
172}
173
174func (dc *downstreamConn) forEachUpstream(f func(*upstreamConn)) {
175 dc.user.forEachUpstream(func(uc *upstreamConn) {
176 if dc.network != nil && uc.network != dc.network {
177 return
178 }
179 f(uc)
180 })
181}
182
183// upstream returns the upstream connection, if any. If there are zero or if
184// there are multiple upstream connections, it returns nil.
185func (dc *downstreamConn) upstream() *upstreamConn {
186 if dc.network == nil {
187 return nil
188 }
189 return dc.network.conn
190}
191
192func isOurNick(net *network, nick string) bool {
193 // TODO: this doesn't account for nick changes
194 if net.conn != nil {
195 return nick == net.conn.nick
196 }
197 // We're not currently connected to the upstream connection, so we don't
198 // know whether this name is our nickname. Best-effort: use the network's
199 // configured nickname and hope it was the one being used when we were
200 // connected.
201 return nick == net.Nick
202}
203
204// marshalEntity converts an upstream entity name (ie. channel or nick) into a
205// downstream entity name.
206//
207// This involves adding a "/<network>" suffix if the entity isn't the current
208// user.
209func (dc *downstreamConn) marshalEntity(net *network, name string) string {
210 if isOurNick(net, name) {
211 return dc.nick
212 }
213 if dc.network != nil {
214 if dc.network != net {
215 panic("soju: tried to marshal an entity for another network")
216 }
217 return name
218 }
219 return name + "/" + net.GetName()
220}
221
222func (dc *downstreamConn) marshalUserPrefix(net *network, prefix *irc.Prefix) *irc.Prefix {
223 if isOurNick(net, prefix.Name) {
224 return dc.prefix()
225 }
226 if dc.network != nil {
227 if dc.network != net {
228 panic("soju: tried to marshal a user prefix for another network")
229 }
230 return prefix
231 }
232 return &irc.Prefix{
233 Name: prefix.Name + "/" + net.GetName(),
234 User: prefix.User,
235 Host: prefix.Host,
236 }
237}
238
239// unmarshalEntity converts a downstream entity name (ie. channel or nick) into
240// an upstream entity name.
241//
242// This involves removing the "/<network>" suffix.
243func (dc *downstreamConn) unmarshalEntity(name string) (*upstreamConn, string, error) {
244 if uc := dc.upstream(); uc != nil {
245 return uc, name, nil
246 }
247
248 var conn *upstreamConn
249 if i := strings.LastIndexByte(name, '/'); i >= 0 {
250 network := name[i+1:]
251 name = name[:i]
252
253 dc.forEachUpstream(func(uc *upstreamConn) {
254 if network != uc.network.GetName() {
255 return
256 }
257 conn = uc
258 })
259 }
260
261 if conn == nil {
262 return nil, "", ircError{&irc.Message{
263 Command: irc.ERR_NOSUCHCHANNEL,
264 Params: []string{name, "No such channel"},
265 }}
266 }
267 return conn, name, nil
268}
269
270func (dc *downstreamConn) unmarshalText(uc *upstreamConn, text string) string {
271 if dc.upstream() != nil {
272 return text
273 }
274 // TODO: smarter parsing that ignores URLs
275 return strings.ReplaceAll(text, "/"+uc.network.GetName(), "")
276}
277
278func (dc *downstreamConn) readMessages(ch chan<- event) error {
279 for {
280 msg, err := dc.ReadMessage()
281 if err == io.EOF {
282 break
283 } else if err != nil {
284 return fmt.Errorf("failed to read IRC command: %v", err)
285 }
286
287 ch <- eventDownstreamMessage{msg, dc}
288 }
289
290 return nil
291}
292
293// SendMessage sends an outgoing message.
294//
295// This can only called from the user goroutine.
296func (dc *downstreamConn) SendMessage(msg *irc.Message) {
297 if !dc.caps["message-tags"] {
298 if msg.Command == "TAGMSG" {
299 return
300 }
301 msg = msg.Copy()
302 for name := range msg.Tags {
303 supported := false
304 switch name {
305 case "time":
306 supported = dc.caps["server-time"]
307 }
308 if !supported {
309 delete(msg.Tags, name)
310 }
311 }
312 }
313 if msg.Command == "JOIN" && !dc.caps["extended-join"] {
314 msg.Params = msg.Params[:1]
315 }
316
317 dc.conn.SendMessage(msg)
318}
319
320// sendMessageWithID sends an outgoing message with the specified internal ID.
321func (dc *downstreamConn) sendMessageWithID(msg *irc.Message, id string) {
322 dc.SendMessage(msg)
323
324 if id == "" || !dc.messageSupportsHistory(msg) {
325 return
326 }
327
328 dc.sendPing(id)
329}
330
331// advanceMessageWithID advances history to the specified message ID without
332// sending a message. This is useful e.g. for self-messages when echo-message
333// isn't enabled.
334func (dc *downstreamConn) advanceMessageWithID(msg *irc.Message, id string) {
335 if id == "" || !dc.messageSupportsHistory(msg) {
336 return
337 }
338
339 dc.sendPing(id)
340}
341
342// ackMsgID acknowledges that a message has been received.
343func (dc *downstreamConn) ackMsgID(id string) {
344 netID, entity, _, err := parseMsgID(id)
345 if err != nil {
346 dc.logger.Printf("failed to ACK message ID %q: %v", id, err)
347 return
348 }
349
350 network := dc.user.getNetworkByID(netID)
351 if network == nil {
352 return
353 }
354
355 delivered, ok := network.delivered[entity]
356 if !ok {
357 return
358 }
359
360 delivered[dc.clientName] = id
361}
362
363func (dc *downstreamConn) sendPing(msgID string) {
364 token := "soju-msgid-" + base64.RawURLEncoding.EncodeToString([]byte(msgID))
365 dc.SendMessage(&irc.Message{
366 Command: "PING",
367 Params: []string{token},
368 })
369}
370
371func (dc *downstreamConn) handlePong(token string) {
372 if !strings.HasPrefix(token, "soju-msgid-") {
373 dc.logger.Printf("received unrecognized PONG token %q", token)
374 return
375 }
376 token = strings.TrimPrefix(token, "soju-msgid-")
377 b, err := base64.RawURLEncoding.DecodeString(token)
378 if err != nil {
379 dc.logger.Printf("received malformed PONG token: %v", err)
380 return
381 }
382 msgID := string(b)
383
384 dc.ackMsgID(msgID)
385}
386
387// marshalMessage re-formats a message coming from an upstream connection so
388// that it's suitable for being sent on this downstream connection. Only
389// messages that may appear in logs are supported, except MODE.
390func (dc *downstreamConn) marshalMessage(msg *irc.Message, net *network) *irc.Message {
391 msg = msg.Copy()
392 msg.Prefix = dc.marshalUserPrefix(net, msg.Prefix)
393
394 switch msg.Command {
395 case "PRIVMSG", "NOTICE", "TAGMSG":
396 msg.Params[0] = dc.marshalEntity(net, msg.Params[0])
397 case "NICK":
398 // Nick change for another user
399 msg.Params[0] = dc.marshalEntity(net, msg.Params[0])
400 case "JOIN", "PART":
401 msg.Params[0] = dc.marshalEntity(net, msg.Params[0])
402 case "KICK":
403 msg.Params[0] = dc.marshalEntity(net, msg.Params[0])
404 msg.Params[1] = dc.marshalEntity(net, msg.Params[1])
405 case "TOPIC":
406 msg.Params[0] = dc.marshalEntity(net, msg.Params[0])
407 case "QUIT":
408 // This space is intentionally left blank
409 default:
410 panic(fmt.Sprintf("unexpected %q message", msg.Command))
411 }
412
413 return msg
414}
415
416func (dc *downstreamConn) handleMessage(msg *irc.Message) error {
417 switch msg.Command {
418 case "QUIT":
419 return dc.Close()
420 default:
421 if dc.registered {
422 return dc.handleMessageRegistered(msg)
423 } else {
424 return dc.handleMessageUnregistered(msg)
425 }
426 }
427}
428
429func (dc *downstreamConn) handleMessageUnregistered(msg *irc.Message) error {
430 switch msg.Command {
431 case "NICK":
432 var nick string
433 if err := parseMessageParams(msg, &nick); err != nil {
434 return err
435 }
436 if strings.ContainsAny(nick, illegalNickChars) {
437 return ircError{&irc.Message{
438 Command: irc.ERR_ERRONEUSNICKNAME,
439 Params: []string{dc.nick, nick, "contains illegal characters"},
440 }}
441 }
442 if nick == serviceNick {
443 return ircError{&irc.Message{
444 Command: irc.ERR_NICKNAMEINUSE,
445 Params: []string{dc.nick, nick, "Nickname reserved for bouncer service"},
446 }}
447 }
448 dc.nick = nick
449 case "USER":
450 if err := parseMessageParams(msg, &dc.rawUsername, nil, nil, &dc.realname); err != nil {
451 return err
452 }
453 case "PASS":
454 if err := parseMessageParams(msg, &dc.password); err != nil {
455 return err
456 }
457 case "CAP":
458 var subCmd string
459 if err := parseMessageParams(msg, &subCmd); err != nil {
460 return err
461 }
462 if err := dc.handleCapCommand(subCmd, msg.Params[1:]); err != nil {
463 return err
464 }
465 case "AUTHENTICATE":
466 if !dc.caps["sasl"] {
467 return ircError{&irc.Message{
468 Command: irc.ERR_SASLFAIL,
469 Params: []string{"*", "AUTHENTICATE requires the \"sasl\" capability to be enabled"},
470 }}
471 }
472 if len(msg.Params) == 0 {
473 return ircError{&irc.Message{
474 Command: irc.ERR_SASLFAIL,
475 Params: []string{"*", "Missing AUTHENTICATE argument"},
476 }}
477 }
478 if dc.nick == "" {
479 return ircError{&irc.Message{
480 Command: irc.ERR_SASLFAIL,
481 Params: []string{"*", "Expected NICK command before AUTHENTICATE"},
482 }}
483 }
484
485 var resp []byte
486 if dc.saslServer == nil {
487 mech := strings.ToUpper(msg.Params[0])
488 switch mech {
489 case "PLAIN":
490 dc.saslServer = sasl.NewPlainServer(sasl.PlainAuthenticator(func(identity, username, password string) error {
491 return dc.authenticate(username, password)
492 }))
493 default:
494 return ircError{&irc.Message{
495 Command: irc.ERR_SASLFAIL,
496 Params: []string{"*", fmt.Sprintf("Unsupported SASL mechanism %q", mech)},
497 }}
498 }
499 } else if msg.Params[0] == "*" {
500 dc.saslServer = nil
501 return ircError{&irc.Message{
502 Command: irc.ERR_SASLABORTED,
503 Params: []string{"*", "SASL authentication aborted"},
504 }}
505 } else if msg.Params[0] == "+" {
506 resp = nil
507 } else {
508 // TODO: multi-line messages
509 var err error
510 resp, err = base64.StdEncoding.DecodeString(msg.Params[0])
511 if err != nil {
512 dc.saslServer = nil
513 return ircError{&irc.Message{
514 Command: irc.ERR_SASLFAIL,
515 Params: []string{"*", "Invalid base64-encoded response"},
516 }}
517 }
518 }
519
520 challenge, done, err := dc.saslServer.Next(resp)
521 if err != nil {
522 dc.saslServer = nil
523 if ircErr, ok := err.(ircError); ok && ircErr.Message.Command == irc.ERR_PASSWDMISMATCH {
524 return ircError{&irc.Message{
525 Command: irc.ERR_SASLFAIL,
526 Params: []string{"*", ircErr.Message.Params[1]},
527 }}
528 }
529 dc.SendMessage(&irc.Message{
530 Prefix: dc.srv.prefix(),
531 Command: irc.ERR_SASLFAIL,
532 Params: []string{"*", "SASL error"},
533 })
534 return fmt.Errorf("SASL authentication failed: %v", err)
535 } else if done {
536 dc.saslServer = nil
537 dc.SendMessage(&irc.Message{
538 Prefix: dc.srv.prefix(),
539 Command: irc.RPL_LOGGEDIN,
540 Params: []string{dc.nick, dc.prefix().String(), dc.user.Username, "You are now logged in"},
541 })
542 dc.SendMessage(&irc.Message{
543 Prefix: dc.srv.prefix(),
544 Command: irc.RPL_SASLSUCCESS,
545 Params: []string{dc.nick, "SASL authentication successful"},
546 })
547 } else {
548 challengeStr := "+"
549 if len(challenge) > 0 {
550 challengeStr = base64.StdEncoding.EncodeToString(challenge)
551 }
552
553 // TODO: multi-line messages
554 dc.SendMessage(&irc.Message{
555 Prefix: dc.srv.prefix(),
556 Command: "AUTHENTICATE",
557 Params: []string{challengeStr},
558 })
559 }
560 default:
561 dc.logger.Printf("unhandled message: %v", msg)
562 return newUnknownCommandError(msg.Command)
563 }
564 if dc.rawUsername != "" && dc.nick != "" && !dc.negociatingCaps {
565 return dc.register()
566 }
567 return nil
568}
569
570func (dc *downstreamConn) handleCapCommand(cmd string, args []string) error {
571 cmd = strings.ToUpper(cmd)
572
573 replyTo := dc.nick
574 if !dc.registered {
575 replyTo = "*"
576 }
577
578 switch cmd {
579 case "LS":
580 if len(args) > 0 {
581 var err error
582 if dc.capVersion, err = strconv.Atoi(args[0]); err != nil {
583 return err
584 }
585 }
586 if !dc.registered && dc.capVersion >= 302 {
587 // Let downstream show everything it supports, and trim
588 // down the available capabilities when upstreams are
589 // known.
590 for k, v := range needAllDownstreamCaps {
591 dc.supportedCaps[k] = v
592 }
593 }
594
595 caps := make([]string, 0, len(dc.supportedCaps))
596 for k, v := range dc.supportedCaps {
597 if dc.capVersion >= 302 && v != "" {
598 caps = append(caps, k+"="+v)
599 } else {
600 caps = append(caps, k)
601 }
602 }
603
604 // TODO: multi-line replies
605 dc.SendMessage(&irc.Message{
606 Prefix: dc.srv.prefix(),
607 Command: "CAP",
608 Params: []string{replyTo, "LS", strings.Join(caps, " ")},
609 })
610
611 if dc.capVersion >= 302 {
612 // CAP version 302 implicitly enables cap-notify
613 dc.caps["cap-notify"] = true
614 }
615
616 if !dc.registered {
617 dc.negociatingCaps = true
618 }
619 case "LIST":
620 var caps []string
621 for name := range dc.caps {
622 caps = append(caps, name)
623 }
624
625 // TODO: multi-line replies
626 dc.SendMessage(&irc.Message{
627 Prefix: dc.srv.prefix(),
628 Command: "CAP",
629 Params: []string{replyTo, "LIST", strings.Join(caps, " ")},
630 })
631 case "REQ":
632 if len(args) == 0 {
633 return ircError{&irc.Message{
634 Command: err_invalidcapcmd,
635 Params: []string{replyTo, cmd, "Missing argument in CAP REQ command"},
636 }}
637 }
638
639 // TODO: atomically ack/nak the whole capability set
640 caps := strings.Fields(args[0])
641 ack := true
642 for _, name := range caps {
643 name = strings.ToLower(name)
644 enable := !strings.HasPrefix(name, "-")
645 if !enable {
646 name = strings.TrimPrefix(name, "-")
647 }
648
649 if enable == dc.caps[name] {
650 continue
651 }
652
653 _, ok := dc.supportedCaps[name]
654 if !ok {
655 ack = false
656 break
657 }
658
659 if name == "cap-notify" && dc.capVersion >= 302 && !enable {
660 // cap-notify cannot be disabled with CAP version 302
661 ack = false
662 break
663 }
664
665 dc.caps[name] = enable
666 }
667
668 reply := "NAK"
669 if ack {
670 reply = "ACK"
671 }
672 dc.SendMessage(&irc.Message{
673 Prefix: dc.srv.prefix(),
674 Command: "CAP",
675 Params: []string{replyTo, reply, args[0]},
676 })
677 case "END":
678 dc.negociatingCaps = false
679 default:
680 return ircError{&irc.Message{
681 Command: err_invalidcapcmd,
682 Params: []string{replyTo, cmd, "Unknown CAP command"},
683 }}
684 }
685 return nil
686}
687
688func (dc *downstreamConn) setSupportedCap(name, value string) {
689 prevValue, hasPrev := dc.supportedCaps[name]
690 changed := !hasPrev || prevValue != value
691 dc.supportedCaps[name] = value
692
693 if !dc.caps["cap-notify"] || !changed {
694 return
695 }
696
697 replyTo := dc.nick
698 if !dc.registered {
699 replyTo = "*"
700 }
701
702 cap := name
703 if value != "" && dc.capVersion >= 302 {
704 cap = name + "=" + value
705 }
706
707 dc.SendMessage(&irc.Message{
708 Prefix: dc.srv.prefix(),
709 Command: "CAP",
710 Params: []string{replyTo, "NEW", cap},
711 })
712}
713
714func (dc *downstreamConn) unsetSupportedCap(name string) {
715 _, hasPrev := dc.supportedCaps[name]
716 delete(dc.supportedCaps, name)
717 delete(dc.caps, name)
718
719 if !dc.caps["cap-notify"] || !hasPrev {
720 return
721 }
722
723 replyTo := dc.nick
724 if !dc.registered {
725 replyTo = "*"
726 }
727
728 dc.SendMessage(&irc.Message{
729 Prefix: dc.srv.prefix(),
730 Command: "CAP",
731 Params: []string{replyTo, "DEL", name},
732 })
733}
734
735func (dc *downstreamConn) updateSupportedCaps() {
736 supportedCaps := make(map[string]bool)
737 for cap := range needAllDownstreamCaps {
738 supportedCaps[cap] = true
739 }
740 dc.forEachUpstream(func(uc *upstreamConn) {
741 for cap, supported := range supportedCaps {
742 supportedCaps[cap] = supported && uc.caps[cap]
743 }
744 })
745
746 for cap, supported := range supportedCaps {
747 if supported {
748 dc.setSupportedCap(cap, needAllDownstreamCaps[cap])
749 } else {
750 dc.unsetSupportedCap(cap)
751 }
752 }
753}
754
755func (dc *downstreamConn) updateNick() {
756 if uc := dc.upstream(); uc != nil && uc.nick != dc.nick {
757 dc.SendMessage(&irc.Message{
758 Prefix: dc.prefix(),
759 Command: "NICK",
760 Params: []string{uc.nick},
761 })
762 dc.nick = uc.nick
763 }
764}
765
766func sanityCheckServer(addr string) error {
767 dialer := net.Dialer{Timeout: 30 * time.Second}
768 conn, err := tls.DialWithDialer(&dialer, "tcp", addr, nil)
769 if err != nil {
770 return err
771 }
772 return conn.Close()
773}
774
775func unmarshalUsername(rawUsername string) (username, client, network string) {
776 username = rawUsername
777
778 i := strings.IndexAny(username, "/@")
779 j := strings.LastIndexAny(username, "/@")
780 if i >= 0 {
781 username = rawUsername[:i]
782 }
783 if j >= 0 {
784 if rawUsername[j] == '@' {
785 client = rawUsername[j+1:]
786 } else {
787 network = rawUsername[j+1:]
788 }
789 }
790 if i >= 0 && j >= 0 && i < j {
791 if rawUsername[i] == '@' {
792 client = rawUsername[i+1 : j]
793 } else {
794 network = rawUsername[i+1 : j]
795 }
796 }
797
798 return username, client, network
799}
800
801func (dc *downstreamConn) authenticate(username, password string) error {
802 username, clientName, networkName := unmarshalUsername(username)
803
804 u, err := dc.srv.db.GetUser(username)
805 if err != nil {
806 dc.logger.Printf("failed authentication for %q: user not found: %v", username, err)
807 return errAuthFailed
808 }
809
810 // Password auth disabled
811 if u.Password == "" {
812 return errAuthFailed
813 }
814
815 err = bcrypt.CompareHashAndPassword([]byte(u.Password), []byte(password))
816 if err != nil {
817 dc.logger.Printf("failed authentication for %q: wrong password: %v", username, err)
818 return errAuthFailed
819 }
820
821 dc.user = dc.srv.getUser(username)
822 if dc.user == nil {
823 dc.logger.Printf("failed authentication for %q: user not active", username)
824 return errAuthFailed
825 }
826 dc.clientName = clientName
827 dc.networkName = networkName
828 return nil
829}
830
831func (dc *downstreamConn) register() error {
832 if dc.registered {
833 return fmt.Errorf("tried to register twice")
834 }
835
836 password := dc.password
837 dc.password = ""
838 if dc.user == nil {
839 if err := dc.authenticate(dc.rawUsername, password); err != nil {
840 return err
841 }
842 }
843
844 if dc.clientName == "" && dc.networkName == "" {
845 _, dc.clientName, dc.networkName = unmarshalUsername(dc.rawUsername)
846 }
847
848 dc.registered = true
849 dc.logger.Printf("registration complete for user %q", dc.user.Username)
850 return nil
851}
852
853func (dc *downstreamConn) loadNetwork() error {
854 if dc.networkName == "" {
855 return nil
856 }
857
858 network := dc.user.getNetwork(dc.networkName)
859 if network == nil {
860 addr := dc.networkName
861 if !strings.ContainsRune(addr, ':') {
862 addr = addr + ":6697"
863 }
864
865 dc.logger.Printf("trying to connect to new network %q", addr)
866 if err := sanityCheckServer(addr); err != nil {
867 dc.logger.Printf("failed to connect to %q: %v", addr, err)
868 return ircError{&irc.Message{
869 Command: irc.ERR_PASSWDMISMATCH,
870 Params: []string{"*", fmt.Sprintf("Failed to connect to %q", dc.networkName)},
871 }}
872 }
873
874 // Some clients only allow specifying the nickname (and use the
875 // nickname as a username too). Strip the network name from the
876 // nickname when auto-saving networks.
877 nick, _, _ := unmarshalUsername(dc.nick)
878
879 dc.logger.Printf("auto-saving network %q", dc.networkName)
880 var err error
881 network, err = dc.user.createNetwork(&Network{
882 Addr: dc.networkName,
883 Nick: nick,
884 })
885 if err != nil {
886 return err
887 }
888 }
889
890 dc.network = network
891 return nil
892}
893
894func (dc *downstreamConn) welcome() error {
895 if dc.user == nil || !dc.registered {
896 panic("tried to welcome an unregistered connection")
897 }
898
899 // TODO: doing this might take some time. We should do it in dc.register
900 // instead, but we'll potentially be adding a new network and this must be
901 // done in the user goroutine.
902 if err := dc.loadNetwork(); err != nil {
903 return err
904 }
905
906 isupport := []string{
907 fmt.Sprintf("CHATHISTORY=%v", dc.srv.HistoryLimit),
908 }
909
910 if uc := dc.upstream(); uc != nil {
911 for k := range passthroughIsupport {
912 v, ok := uc.isupport[k]
913 if !ok {
914 continue
915 }
916 if v != nil {
917 isupport = append(isupport, fmt.Sprintf("%v=%v", k, *v))
918 } else {
919 isupport = append(isupport, k)
920 }
921 }
922 }
923
924 dc.SendMessage(&irc.Message{
925 Prefix: dc.srv.prefix(),
926 Command: irc.RPL_WELCOME,
927 Params: []string{dc.nick, "Welcome to soju, " + dc.nick},
928 })
929 dc.SendMessage(&irc.Message{
930 Prefix: dc.srv.prefix(),
931 Command: irc.RPL_YOURHOST,
932 Params: []string{dc.nick, "Your host is " + dc.srv.Hostname},
933 })
934 dc.SendMessage(&irc.Message{
935 Prefix: dc.srv.prefix(),
936 Command: irc.RPL_CREATED,
937 Params: []string{dc.nick, "Who cares when the server was created?"},
938 })
939 dc.SendMessage(&irc.Message{
940 Prefix: dc.srv.prefix(),
941 Command: irc.RPL_MYINFO,
942 Params: []string{dc.nick, dc.srv.Hostname, "soju", "aiwroO", "OovaimnqpsrtklbeI"},
943 })
944 for _, msg := range generateIsupport(dc.srv.prefix(), dc.nick, isupport) {
945 dc.SendMessage(msg)
946 }
947 dc.SendMessage(&irc.Message{
948 Prefix: dc.srv.prefix(),
949 Command: irc.ERR_NOMOTD,
950 Params: []string{dc.nick, "No MOTD"},
951 })
952
953 dc.updateNick()
954 dc.updateSupportedCaps()
955
956 dc.forEachUpstream(func(uc *upstreamConn) {
957 for _, ch := range uc.channels {
958 if !ch.complete {
959 continue
960 }
961 if record, ok := uc.network.channels[ch.Name]; ok && record.Detached {
962 continue
963 }
964
965 dc.SendMessage(&irc.Message{
966 Prefix: dc.prefix(),
967 Command: "JOIN",
968 Params: []string{dc.marshalEntity(ch.conn.network, ch.Name)},
969 })
970
971 forwardChannel(dc, ch)
972 }
973 })
974
975 dc.forEachNetwork(func(net *network) {
976 // Only send history if we're the first connected client with that name
977 // for the network
978 if _, ok := net.offlineClients[dc.clientName]; ok {
979 dc.sendNetworkBacklog(net)
980 delete(net.offlineClients, dc.clientName)
981 }
982
983 // Fast-forward history to last message
984 for target, delivered := range net.delivered {
985 if ch, ok := net.channels[target]; ok && ch.Detached {
986 continue
987 }
988
989 lastID, err := dc.user.msgStore.LastMsgID(net, target, time.Now())
990 if err != nil {
991 dc.logger.Printf("failed to get last message ID: %v", err)
992 continue
993 }
994 delivered[dc.clientName] = lastID
995 }
996 })
997
998 return nil
999}
1000
1001// messageSupportsHistory checks whether the provided message can be sent as
1002// part of an history batch.
1003func (dc *downstreamConn) messageSupportsHistory(msg *irc.Message) bool {
1004 // Don't replay all messages, because that would mess up client
1005 // state. For instance we just sent the list of users, sending
1006 // PART messages for one of these users would be incorrect.
1007 // TODO: add support for draft/event-playback
1008 switch msg.Command {
1009 case "PRIVMSG", "NOTICE":
1010 return true
1011 }
1012 return false
1013}
1014
1015func (dc *downstreamConn) sendNetworkBacklog(net *network) {
1016 for target := range net.delivered {
1017 dc.sendTargetBacklog(net, target)
1018 }
1019}
1020
1021func (dc *downstreamConn) sendTargetBacklog(net *network, target string) {
1022 if dc.caps["draft/chathistory"] || dc.user.msgStore == nil {
1023 return
1024 }
1025 if ch, ok := net.channels[target]; ok && ch.Detached {
1026 return
1027 }
1028 delivered, ok := net.delivered[target]
1029 if !ok {
1030 return
1031 }
1032 lastDelivered, ok := delivered[dc.clientName]
1033 if !ok {
1034 return
1035 }
1036
1037 limit := 4000
1038 history, err := dc.user.msgStore.LoadLatestID(net, target, lastDelivered, limit)
1039 if err != nil {
1040 dc.logger.Printf("failed to send implicit history for %q: %v", target, err)
1041 return
1042 }
1043
1044 batchRef := "history"
1045 if dc.caps["batch"] {
1046 dc.SendMessage(&irc.Message{
1047 Prefix: dc.srv.prefix(),
1048 Command: "BATCH",
1049 Params: []string{"+" + batchRef, "chathistory", dc.marshalEntity(net, target)},
1050 })
1051 }
1052
1053 for _, msg := range history {
1054 if !dc.messageSupportsHistory(msg) {
1055 continue
1056 }
1057
1058 if dc.caps["batch"] {
1059 msg.Tags["batch"] = irc.TagValue(batchRef)
1060 }
1061 dc.SendMessage(dc.marshalMessage(msg, net))
1062 }
1063
1064 if dc.caps["batch"] {
1065 dc.SendMessage(&irc.Message{
1066 Prefix: dc.srv.prefix(),
1067 Command: "BATCH",
1068 Params: []string{"-" + batchRef},
1069 })
1070 }
1071}
1072
1073func (dc *downstreamConn) runUntilRegistered() error {
1074 for !dc.registered {
1075 msg, err := dc.ReadMessage()
1076 if err != nil {
1077 return fmt.Errorf("failed to read IRC command: %v", err)
1078 }
1079
1080 err = dc.handleMessage(msg)
1081 if ircErr, ok := err.(ircError); ok {
1082 ircErr.Message.Prefix = dc.srv.prefix()
1083 dc.SendMessage(ircErr.Message)
1084 } else if err != nil {
1085 return fmt.Errorf("failed to handle IRC command %q: %v", msg, err)
1086 }
1087 }
1088
1089 return nil
1090}
1091
1092func (dc *downstreamConn) handleMessageRegistered(msg *irc.Message) error {
1093 switch msg.Command {
1094 case "CAP":
1095 var subCmd string
1096 if err := parseMessageParams(msg, &subCmd); err != nil {
1097 return err
1098 }
1099 if err := dc.handleCapCommand(subCmd, msg.Params[1:]); err != nil {
1100 return err
1101 }
1102 case "PING":
1103 var source, destination string
1104 if err := parseMessageParams(msg, &source); err != nil {
1105 return err
1106 }
1107 if len(msg.Params) > 1 {
1108 destination = msg.Params[1]
1109 }
1110 if destination != "" && destination != dc.srv.Hostname {
1111 return ircError{&irc.Message{
1112 Command: irc.ERR_NOSUCHSERVER,
1113 Params: []string{dc.nick, destination, "No such server"},
1114 }}
1115 }
1116 dc.SendMessage(&irc.Message{
1117 Prefix: dc.srv.prefix(),
1118 Command: "PONG",
1119 Params: []string{dc.srv.Hostname, source},
1120 })
1121 return nil
1122 case "PONG":
1123 if len(msg.Params) == 0 {
1124 return newNeedMoreParamsError(msg.Command)
1125 }
1126 token := msg.Params[len(msg.Params)-1]
1127 dc.handlePong(token)
1128 case "USER":
1129 return ircError{&irc.Message{
1130 Command: irc.ERR_ALREADYREGISTERED,
1131 Params: []string{dc.nick, "You may not reregister"},
1132 }}
1133 case "NICK":
1134 var rawNick string
1135 if err := parseMessageParams(msg, &rawNick); err != nil {
1136 return err
1137 }
1138
1139 nick := rawNick
1140 var upstream *upstreamConn
1141 if dc.upstream() == nil {
1142 uc, unmarshaledNick, err := dc.unmarshalEntity(nick)
1143 if err == nil { // NICK nick/network: NICK only on a specific upstream
1144 upstream = uc
1145 nick = unmarshaledNick
1146 }
1147 }
1148
1149 if strings.ContainsAny(nick, illegalNickChars) {
1150 return ircError{&irc.Message{
1151 Command: irc.ERR_ERRONEUSNICKNAME,
1152 Params: []string{dc.nick, rawNick, "contains illegal characters"},
1153 }}
1154 }
1155 if nick == serviceNick {
1156 return ircError{&irc.Message{
1157 Command: irc.ERR_NICKNAMEINUSE,
1158 Params: []string{dc.nick, rawNick, "Nickname reserved for bouncer service"},
1159 }}
1160 }
1161
1162 var err error
1163 dc.forEachNetwork(func(n *network) {
1164 if err != nil || (upstream != nil && upstream.network != n) {
1165 return
1166 }
1167 n.Nick = nick
1168 err = dc.srv.db.StoreNetwork(dc.user.ID, &n.Network)
1169 })
1170 if err != nil {
1171 return err
1172 }
1173
1174 dc.forEachUpstream(func(uc *upstreamConn) {
1175 if upstream != nil && upstream != uc {
1176 return
1177 }
1178 uc.SendMessageLabeled(dc.id, &irc.Message{
1179 Command: "NICK",
1180 Params: []string{nick},
1181 })
1182 })
1183
1184 if dc.upstream() == nil && dc.nick != nick {
1185 dc.SendMessage(&irc.Message{
1186 Prefix: dc.prefix(),
1187 Command: "NICK",
1188 Params: []string{nick},
1189 })
1190 dc.nick = nick
1191 }
1192 case "JOIN":
1193 var namesStr string
1194 if err := parseMessageParams(msg, &namesStr); err != nil {
1195 return err
1196 }
1197
1198 var keys []string
1199 if len(msg.Params) > 1 {
1200 keys = strings.Split(msg.Params[1], ",")
1201 }
1202
1203 for i, name := range strings.Split(namesStr, ",") {
1204 uc, upstreamName, err := dc.unmarshalEntity(name)
1205 if err != nil {
1206 return err
1207 }
1208
1209 var key string
1210 if len(keys) > i {
1211 key = keys[i]
1212 }
1213
1214 params := []string{upstreamName}
1215 if key != "" {
1216 params = append(params, key)
1217 }
1218 uc.SendMessageLabeled(dc.id, &irc.Message{
1219 Command: "JOIN",
1220 Params: params,
1221 })
1222
1223 var ch *Channel
1224 var ok bool
1225 if ch, ok = uc.network.channels[upstreamName]; ok {
1226 // Don't clear the channel key if there's one set
1227 // TODO: add a way to unset the channel key
1228 if key != "" {
1229 ch.Key = key
1230 }
1231 uc.network.attach(ch)
1232 } else {
1233 ch = &Channel{
1234 Name: upstreamName,
1235 Key: key,
1236 }
1237 uc.network.channels[upstreamName] = ch
1238 }
1239 if err := dc.srv.db.StoreChannel(uc.network.ID, ch); err != nil {
1240 dc.logger.Printf("failed to create or update channel %q: %v", upstreamName, err)
1241 }
1242 }
1243 case "PART":
1244 var namesStr string
1245 if err := parseMessageParams(msg, &namesStr); err != nil {
1246 return err
1247 }
1248
1249 var reason string
1250 if len(msg.Params) > 1 {
1251 reason = msg.Params[1]
1252 }
1253
1254 for _, name := range strings.Split(namesStr, ",") {
1255 uc, upstreamName, err := dc.unmarshalEntity(name)
1256 if err != nil {
1257 return err
1258 }
1259
1260 if strings.EqualFold(reason, "detach") {
1261 var ch *Channel
1262 var ok bool
1263 if ch, ok = uc.network.channels[upstreamName]; ok {
1264 uc.network.detach(ch)
1265 } else {
1266 ch = &Channel{
1267 Name: name,
1268 Detached: true,
1269 }
1270 uc.network.channels[upstreamName] = ch
1271 }
1272 if err := dc.srv.db.StoreChannel(uc.network.ID, ch); err != nil {
1273 dc.logger.Printf("failed to create or update channel %q: %v", upstreamName, err)
1274 }
1275 } else {
1276 params := []string{upstreamName}
1277 if reason != "" {
1278 params = append(params, reason)
1279 }
1280 uc.SendMessageLabeled(dc.id, &irc.Message{
1281 Command: "PART",
1282 Params: params,
1283 })
1284
1285 if err := uc.network.deleteChannel(upstreamName); err != nil {
1286 dc.logger.Printf("failed to delete channel %q: %v", upstreamName, err)
1287 }
1288 }
1289 }
1290 case "KICK":
1291 var channelStr, userStr string
1292 if err := parseMessageParams(msg, &channelStr, &userStr); err != nil {
1293 return err
1294 }
1295
1296 channels := strings.Split(channelStr, ",")
1297 users := strings.Split(userStr, ",")
1298
1299 var reason string
1300 if len(msg.Params) > 2 {
1301 reason = msg.Params[2]
1302 }
1303
1304 if len(channels) != 1 && len(channels) != len(users) {
1305 return ircError{&irc.Message{
1306 Command: irc.ERR_BADCHANMASK,
1307 Params: []string{dc.nick, channelStr, "Bad channel mask"},
1308 }}
1309 }
1310
1311 for i, user := range users {
1312 var channel string
1313 if len(channels) == 1 {
1314 channel = channels[0]
1315 } else {
1316 channel = channels[i]
1317 }
1318
1319 ucChannel, upstreamChannel, err := dc.unmarshalEntity(channel)
1320 if err != nil {
1321 return err
1322 }
1323
1324 ucUser, upstreamUser, err := dc.unmarshalEntity(user)
1325 if err != nil {
1326 return err
1327 }
1328
1329 if ucChannel != ucUser {
1330 return ircError{&irc.Message{
1331 Command: irc.ERR_USERNOTINCHANNEL,
1332 Params: []string{dc.nick, user, channel, "They are on another network"},
1333 }}
1334 }
1335 uc := ucChannel
1336
1337 params := []string{upstreamChannel, upstreamUser}
1338 if reason != "" {
1339 params = append(params, reason)
1340 }
1341 uc.SendMessageLabeled(dc.id, &irc.Message{
1342 Command: "KICK",
1343 Params: params,
1344 })
1345 }
1346 case "MODE":
1347 var name string
1348 if err := parseMessageParams(msg, &name); err != nil {
1349 return err
1350 }
1351
1352 var modeStr string
1353 if len(msg.Params) > 1 {
1354 modeStr = msg.Params[1]
1355 }
1356
1357 if name == dc.nick {
1358 if modeStr != "" {
1359 dc.forEachUpstream(func(uc *upstreamConn) {
1360 uc.SendMessageLabeled(dc.id, &irc.Message{
1361 Command: "MODE",
1362 Params: []string{uc.nick, modeStr},
1363 })
1364 })
1365 } else {
1366 dc.SendMessage(&irc.Message{
1367 Prefix: dc.srv.prefix(),
1368 Command: irc.RPL_UMODEIS,
1369 Params: []string{dc.nick, ""}, // TODO
1370 })
1371 }
1372 return nil
1373 }
1374
1375 uc, upstreamName, err := dc.unmarshalEntity(name)
1376 if err != nil {
1377 return err
1378 }
1379
1380 if !uc.isChannel(upstreamName) {
1381 return ircError{&irc.Message{
1382 Command: irc.ERR_USERSDONTMATCH,
1383 Params: []string{dc.nick, "Cannot change mode for other users"},
1384 }}
1385 }
1386
1387 if modeStr != "" {
1388 params := []string{upstreamName, modeStr}
1389 params = append(params, msg.Params[2:]...)
1390 uc.SendMessageLabeled(dc.id, &irc.Message{
1391 Command: "MODE",
1392 Params: params,
1393 })
1394 } else {
1395 ch, ok := uc.channels[upstreamName]
1396 if !ok {
1397 return ircError{&irc.Message{
1398 Command: irc.ERR_NOSUCHCHANNEL,
1399 Params: []string{dc.nick, name, "No such channel"},
1400 }}
1401 }
1402
1403 if ch.modes == nil {
1404 // we haven't received the initial RPL_CHANNELMODEIS yet
1405 // ignore the request, we will broadcast the modes later when we receive RPL_CHANNELMODEIS
1406 return nil
1407 }
1408
1409 modeStr, modeParams := ch.modes.Format()
1410 params := []string{dc.nick, name, modeStr}
1411 params = append(params, modeParams...)
1412
1413 dc.SendMessage(&irc.Message{
1414 Prefix: dc.srv.prefix(),
1415 Command: irc.RPL_CHANNELMODEIS,
1416 Params: params,
1417 })
1418 if ch.creationTime != "" {
1419 dc.SendMessage(&irc.Message{
1420 Prefix: dc.srv.prefix(),
1421 Command: rpl_creationtime,
1422 Params: []string{dc.nick, name, ch.creationTime},
1423 })
1424 }
1425 }
1426 case "TOPIC":
1427 var channel string
1428 if err := parseMessageParams(msg, &channel); err != nil {
1429 return err
1430 }
1431
1432 uc, upstreamChannel, err := dc.unmarshalEntity(channel)
1433 if err != nil {
1434 return err
1435 }
1436
1437 if len(msg.Params) > 1 { // setting topic
1438 topic := msg.Params[1]
1439 uc.SendMessageLabeled(dc.id, &irc.Message{
1440 Command: "TOPIC",
1441 Params: []string{upstreamChannel, topic},
1442 })
1443 } else { // getting topic
1444 ch, ok := uc.channels[upstreamChannel]
1445 if !ok {
1446 return ircError{&irc.Message{
1447 Command: irc.ERR_NOSUCHCHANNEL,
1448 Params: []string{dc.nick, upstreamChannel, "No such channel"},
1449 }}
1450 }
1451 sendTopic(dc, ch)
1452 }
1453 case "LIST":
1454 // TODO: support ELIST when supported by all upstreams
1455
1456 pl := pendingLIST{
1457 downstreamID: dc.id,
1458 pendingCommands: make(map[int64]*irc.Message),
1459 }
1460 var upstream *upstreamConn
1461 var upstreamChannels map[int64][]string
1462 if len(msg.Params) > 0 {
1463 uc, upstreamMask, err := dc.unmarshalEntity(msg.Params[0])
1464 if err == nil && upstreamMask == "*" { // LIST */network: send LIST only to one network
1465 upstream = uc
1466 } else {
1467 upstreamChannels = make(map[int64][]string)
1468 channels := strings.Split(msg.Params[0], ",")
1469 for _, channel := range channels {
1470 uc, upstreamChannel, err := dc.unmarshalEntity(channel)
1471 if err != nil {
1472 return err
1473 }
1474 upstreamChannels[uc.network.ID] = append(upstreamChannels[uc.network.ID], upstreamChannel)
1475 }
1476 }
1477 }
1478
1479 dc.user.pendingLISTs = append(dc.user.pendingLISTs, pl)
1480 dc.forEachUpstream(func(uc *upstreamConn) {
1481 if upstream != nil && upstream != uc {
1482 return
1483 }
1484 var params []string
1485 if upstreamChannels != nil {
1486 if channels, ok := upstreamChannels[uc.network.ID]; ok {
1487 params = []string{strings.Join(channels, ",")}
1488 } else {
1489 return
1490 }
1491 }
1492 pl.pendingCommands[uc.network.ID] = &irc.Message{
1493 Command: "LIST",
1494 Params: params,
1495 }
1496 uc.trySendLIST(dc.id)
1497 })
1498 case "NAMES":
1499 if len(msg.Params) == 0 {
1500 dc.SendMessage(&irc.Message{
1501 Prefix: dc.srv.prefix(),
1502 Command: irc.RPL_ENDOFNAMES,
1503 Params: []string{dc.nick, "*", "End of /NAMES list"},
1504 })
1505 return nil
1506 }
1507
1508 channels := strings.Split(msg.Params[0], ",")
1509 for _, channel := range channels {
1510 uc, upstreamChannel, err := dc.unmarshalEntity(channel)
1511 if err != nil {
1512 return err
1513 }
1514
1515 ch, ok := uc.channels[upstreamChannel]
1516 if ok {
1517 sendNames(dc, ch)
1518 } else {
1519 // NAMES on a channel we have not joined, ask upstream
1520 uc.SendMessageLabeled(dc.id, &irc.Message{
1521 Command: "NAMES",
1522 Params: []string{upstreamChannel},
1523 })
1524 }
1525 }
1526 case "WHO":
1527 if len(msg.Params) == 0 {
1528 // TODO: support WHO without parameters
1529 dc.SendMessage(&irc.Message{
1530 Prefix: dc.srv.prefix(),
1531 Command: irc.RPL_ENDOFWHO,
1532 Params: []string{dc.nick, "*", "End of /WHO list"},
1533 })
1534 return nil
1535 }
1536
1537 // TODO: support WHO masks
1538 entity := msg.Params[0]
1539
1540 if entity == dc.nick {
1541 // TODO: support AWAY (H/G) in self WHO reply
1542 dc.SendMessage(&irc.Message{
1543 Prefix: dc.srv.prefix(),
1544 Command: irc.RPL_WHOREPLY,
1545 Params: []string{dc.nick, "*", dc.user.Username, dc.hostname, dc.srv.Hostname, dc.nick, "H", "0 " + dc.realname},
1546 })
1547 dc.SendMessage(&irc.Message{
1548 Prefix: dc.srv.prefix(),
1549 Command: irc.RPL_ENDOFWHO,
1550 Params: []string{dc.nick, dc.nick, "End of /WHO list"},
1551 })
1552 return nil
1553 }
1554 if entity == serviceNick {
1555 dc.SendMessage(&irc.Message{
1556 Prefix: dc.srv.prefix(),
1557 Command: irc.RPL_WHOREPLY,
1558 Params: []string{serviceNick, "*", servicePrefix.User, servicePrefix.Host, dc.srv.Hostname, serviceNick, "H", "0 " + serviceRealname},
1559 })
1560 dc.SendMessage(&irc.Message{
1561 Prefix: dc.srv.prefix(),
1562 Command: irc.RPL_ENDOFWHO,
1563 Params: []string{dc.nick, serviceNick, "End of /WHO list"},
1564 })
1565 return nil
1566 }
1567
1568 uc, upstreamName, err := dc.unmarshalEntity(entity)
1569 if err != nil {
1570 return err
1571 }
1572
1573 var params []string
1574 if len(msg.Params) == 2 {
1575 params = []string{upstreamName, msg.Params[1]}
1576 } else {
1577 params = []string{upstreamName}
1578 }
1579
1580 uc.SendMessageLabeled(dc.id, &irc.Message{
1581 Command: "WHO",
1582 Params: params,
1583 })
1584 case "WHOIS":
1585 if len(msg.Params) == 0 {
1586 return ircError{&irc.Message{
1587 Command: irc.ERR_NONICKNAMEGIVEN,
1588 Params: []string{dc.nick, "No nickname given"},
1589 }}
1590 }
1591
1592 var target, mask string
1593 if len(msg.Params) == 1 {
1594 target = ""
1595 mask = msg.Params[0]
1596 } else {
1597 target = msg.Params[0]
1598 mask = msg.Params[1]
1599 }
1600 // TODO: support multiple WHOIS users
1601 if i := strings.IndexByte(mask, ','); i >= 0 {
1602 mask = mask[:i]
1603 }
1604
1605 if mask == dc.nick {
1606 dc.SendMessage(&irc.Message{
1607 Prefix: dc.srv.prefix(),
1608 Command: irc.RPL_WHOISUSER,
1609 Params: []string{dc.nick, dc.nick, dc.user.Username, dc.hostname, "*", dc.realname},
1610 })
1611 dc.SendMessage(&irc.Message{
1612 Prefix: dc.srv.prefix(),
1613 Command: irc.RPL_WHOISSERVER,
1614 Params: []string{dc.nick, dc.nick, dc.srv.Hostname, "soju"},
1615 })
1616 dc.SendMessage(&irc.Message{
1617 Prefix: dc.srv.prefix(),
1618 Command: irc.RPL_ENDOFWHOIS,
1619 Params: []string{dc.nick, dc.nick, "End of /WHOIS list"},
1620 })
1621 return nil
1622 }
1623
1624 // TODO: support WHOIS masks
1625 uc, upstreamNick, err := dc.unmarshalEntity(mask)
1626 if err != nil {
1627 return err
1628 }
1629
1630 var params []string
1631 if target != "" {
1632 if target == mask { // WHOIS nick nick
1633 params = []string{upstreamNick, upstreamNick}
1634 } else {
1635 params = []string{target, upstreamNick}
1636 }
1637 } else {
1638 params = []string{upstreamNick}
1639 }
1640
1641 uc.SendMessageLabeled(dc.id, &irc.Message{
1642 Command: "WHOIS",
1643 Params: params,
1644 })
1645 case "PRIVMSG":
1646 var targetsStr, text string
1647 if err := parseMessageParams(msg, &targetsStr, &text); err != nil {
1648 return err
1649 }
1650 tags := copyClientTags(msg.Tags)
1651
1652 for _, name := range strings.Split(targetsStr, ",") {
1653 if name == serviceNick {
1654 if dc.caps["echo-message"] {
1655 echoTags := tags.Copy()
1656 echoTags["time"] = irc.TagValue(time.Now().UTC().Format(serverTimeLayout))
1657 dc.SendMessage(&irc.Message{
1658 Tags: echoTags,
1659 Prefix: dc.prefix(),
1660 Command: "PRIVMSG",
1661 Params: []string{name, text},
1662 })
1663 }
1664 handleServicePRIVMSG(dc, text)
1665 continue
1666 }
1667
1668 uc, upstreamName, err := dc.unmarshalEntity(name)
1669 if err != nil {
1670 return err
1671 }
1672
1673 if upstreamName == "NickServ" {
1674 dc.handleNickServPRIVMSG(uc, text)
1675 }
1676
1677 unmarshaledText := text
1678 if uc.isChannel(upstreamName) {
1679 unmarshaledText = dc.unmarshalText(uc, text)
1680 }
1681 uc.SendMessageLabeled(dc.id, &irc.Message{
1682 Tags: tags,
1683 Command: "PRIVMSG",
1684 Params: []string{upstreamName, unmarshaledText},
1685 })
1686
1687 echoTags := tags.Copy()
1688 echoTags["time"] = irc.TagValue(time.Now().UTC().Format(serverTimeLayout))
1689 echoMsg := &irc.Message{
1690 Tags: echoTags,
1691 Prefix: &irc.Prefix{
1692 Name: uc.nick,
1693 User: uc.username,
1694 },
1695 Command: "PRIVMSG",
1696 Params: []string{upstreamName, text},
1697 }
1698 uc.produce(upstreamName, echoMsg, dc)
1699
1700 uc.updateChannelAutoDetach(upstreamName)
1701 }
1702 case "NOTICE":
1703 var targetsStr, text string
1704 if err := parseMessageParams(msg, &targetsStr, &text); err != nil {
1705 return err
1706 }
1707 tags := copyClientTags(msg.Tags)
1708
1709 for _, name := range strings.Split(targetsStr, ",") {
1710 uc, upstreamName, err := dc.unmarshalEntity(name)
1711 if err != nil {
1712 return err
1713 }
1714
1715 unmarshaledText := text
1716 if uc.isChannel(upstreamName) {
1717 unmarshaledText = dc.unmarshalText(uc, text)
1718 }
1719 uc.SendMessageLabeled(dc.id, &irc.Message{
1720 Tags: tags,
1721 Command: "NOTICE",
1722 Params: []string{upstreamName, unmarshaledText},
1723 })
1724
1725 uc.updateChannelAutoDetach(upstreamName)
1726 }
1727 case "TAGMSG":
1728 var targetsStr string
1729 if err := parseMessageParams(msg, &targetsStr); err != nil {
1730 return err
1731 }
1732 tags := copyClientTags(msg.Tags)
1733
1734 for _, name := range strings.Split(targetsStr, ",") {
1735 uc, upstreamName, err := dc.unmarshalEntity(name)
1736 if err != nil {
1737 return err
1738 }
1739 if _, ok := uc.caps["message-tags"]; !ok {
1740 continue
1741 }
1742
1743 uc.SendMessageLabeled(dc.id, &irc.Message{
1744 Tags: tags,
1745 Command: "TAGMSG",
1746 Params: []string{upstreamName},
1747 })
1748
1749 uc.updateChannelAutoDetach(upstreamName)
1750 }
1751 case "INVITE":
1752 var user, channel string
1753 if err := parseMessageParams(msg, &user, &channel); err != nil {
1754 return err
1755 }
1756
1757 ucChannel, upstreamChannel, err := dc.unmarshalEntity(channel)
1758 if err != nil {
1759 return err
1760 }
1761
1762 ucUser, upstreamUser, err := dc.unmarshalEntity(user)
1763 if err != nil {
1764 return err
1765 }
1766
1767 if ucChannel != ucUser {
1768 return ircError{&irc.Message{
1769 Command: irc.ERR_USERNOTINCHANNEL,
1770 Params: []string{dc.nick, user, channel, "They are on another network"},
1771 }}
1772 }
1773 uc := ucChannel
1774
1775 uc.SendMessageLabeled(dc.id, &irc.Message{
1776 Command: "INVITE",
1777 Params: []string{upstreamUser, upstreamChannel},
1778 })
1779 case "CHATHISTORY":
1780 var subcommand string
1781 if err := parseMessageParams(msg, &subcommand); err != nil {
1782 return err
1783 }
1784 var target, criteria, limitStr string
1785 if err := parseMessageParams(msg, nil, &target, &criteria, &limitStr); err != nil {
1786 return ircError{&irc.Message{
1787 Command: "FAIL",
1788 Params: []string{"CHATHISTORY", "NEED_MORE_PARAMS", subcommand, "Missing parameters"},
1789 }}
1790 }
1791
1792 store, ok := dc.user.msgStore.(chatHistoryMessageStore)
1793 if !ok {
1794 return ircError{&irc.Message{
1795 Command: irc.ERR_UNKNOWNCOMMAND,
1796 Params: []string{dc.nick, "CHATHISTORY", "Unknown command"},
1797 }}
1798 }
1799
1800 uc, entity, err := dc.unmarshalEntity(target)
1801 if err != nil {
1802 return err
1803 }
1804
1805 // TODO: support msgid criteria
1806 criteriaParts := strings.SplitN(criteria, "=", 2)
1807 if len(criteriaParts) != 2 || criteriaParts[0] != "timestamp" {
1808 return ircError{&irc.Message{
1809 Command: "FAIL",
1810 Params: []string{"CHATHISTORY", "INVALID_PARAMS", subcommand, criteria, "Unknown criteria"},
1811 }}
1812 }
1813
1814 timestamp, err := time.Parse(serverTimeLayout, criteriaParts[1])
1815 if err != nil {
1816 return ircError{&irc.Message{
1817 Command: "FAIL",
1818 Params: []string{"CHATHISTORY", "INVALID_PARAMS", subcommand, criteria, "Invalid criteria"},
1819 }}
1820 }
1821
1822 limit, err := strconv.Atoi(limitStr)
1823 if err != nil || limit < 0 || limit > dc.srv.HistoryLimit {
1824 return ircError{&irc.Message{
1825 Command: "FAIL",
1826 Params: []string{"CHATHISTORY", "INVALID_PARAMS", subcommand, limitStr, "Invalid limit"},
1827 }}
1828 }
1829
1830 var history []*irc.Message
1831 switch subcommand {
1832 case "BEFORE":
1833 history, err = store.LoadBeforeTime(uc.network, entity, timestamp, limit)
1834 case "AFTER":
1835 history, err = store.LoadAfterTime(uc.network, entity, timestamp, limit)
1836 default:
1837 // TODO: support LATEST, BETWEEN
1838 return ircError{&irc.Message{
1839 Command: "FAIL",
1840 Params: []string{"CHATHISTORY", "UNKNOWN_COMMAND", subcommand, "Unknown command"},
1841 }}
1842 }
1843 if err != nil {
1844 dc.logger.Printf("failed parsing log messages for chathistory: %v", err)
1845 return newChatHistoryError(subcommand, target)
1846 }
1847
1848 batchRef := "history"
1849 dc.SendMessage(&irc.Message{
1850 Prefix: dc.srv.prefix(),
1851 Command: "BATCH",
1852 Params: []string{"+" + batchRef, "chathistory", target},
1853 })
1854
1855 for _, msg := range history {
1856 msg.Tags["batch"] = irc.TagValue(batchRef)
1857 dc.SendMessage(dc.marshalMessage(msg, uc.network))
1858 }
1859
1860 dc.SendMessage(&irc.Message{
1861 Prefix: dc.srv.prefix(),
1862 Command: "BATCH",
1863 Params: []string{"-" + batchRef},
1864 })
1865 default:
1866 dc.logger.Printf("unhandled message: %v", msg)
1867 return newUnknownCommandError(msg.Command)
1868 }
1869 return nil
1870}
1871
1872func (dc *downstreamConn) handleNickServPRIVMSG(uc *upstreamConn, text string) {
1873 username, password, ok := parseNickServCredentials(text, uc.nick)
1874 if !ok {
1875 return
1876 }
1877
1878 // User may have e.g. EXTERNAL mechanism configured. We do not want to
1879 // automatically erase the key pair or any other credentials.
1880 if uc.network.SASL.Mechanism != "" && uc.network.SASL.Mechanism != "PLAIN" {
1881 return
1882 }
1883
1884 dc.logger.Printf("auto-saving NickServ credentials with username %q", username)
1885 n := uc.network
1886 n.SASL.Mechanism = "PLAIN"
1887 n.SASL.Plain.Username = username
1888 n.SASL.Plain.Password = password
1889 if err := dc.srv.db.StoreNetwork(dc.user.ID, &n.Network); err != nil {
1890 dc.logger.Printf("failed to save NickServ credentials: %v", err)
1891 }
1892}
1893
1894func parseNickServCredentials(text, nick string) (username, password string, ok bool) {
1895 fields := strings.Fields(text)
1896 if len(fields) < 2 {
1897 return "", "", false
1898 }
1899 cmd := strings.ToUpper(fields[0])
1900 params := fields[1:]
1901 switch cmd {
1902 case "REGISTER":
1903 username = nick
1904 password = params[0]
1905 case "IDENTIFY":
1906 if len(params) == 1 {
1907 username = nick
1908 password = params[0]
1909 } else {
1910 username = params[0]
1911 password = params[1]
1912 }
1913 case "SET":
1914 if len(params) == 2 && strings.EqualFold(params[0], "PASSWORD") {
1915 username = nick
1916 password = params[1]
1917 }
1918 default:
1919 return "", "", false
1920 }
1921 return username, password, true
1922}
Note: See TracBrowser for help on using the repository browser.