source: code/trunk/downstream.go@ 481

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

Introduce deliveredClientMap

Adds more semantics to map[string]string. Simplifies the complicated
mapStringStringCasemapMap type.

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