source: code/trunk/downstream.go@ 703

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

Introduce conn.NewContext

This function wraps a parent context, and returns a new context
cancelled when the connection is closed. This will make it so
operations started from downstreamConn.handleMessage will be
cancelled when the connection is closed.

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