source: code/trunk/downstream.go@ 498

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

Skip backlog logic in downstreamConn.welcome on chathistory

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