source: code/trunk/downstream.go@ 533

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

Add pass to bouncer network attributes

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