source: code/trunk/downstream.go@ 688

Last change on this file since 688 was 688, checked in by delthas, 4 years ago

Return an empty CHATHISTORY TARGETS batch when in multi-upstream

When on an unbound bouncer network downstream, we should return no
targets (there are none, because there are no upstreams at all).

When on a multi-upstream downstream, we should return no targets as we
don't support multi-upstream CHATHISTORY TARGETS.

Before this patch, we returned a misleading error message:
:example.com 403 :Missing network suffix in name

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