source: code/trunk/downstream.go@ 484

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

Ensure targets are case-mapped before being passed to messageStore

messageStore isn't aware of the network's case-mapping. We need
to canonicalize the names before passing them to messageStore.

File size: 47.5 KB
Line 
1package soju
2
3import (
4 "crypto/tls"
5 "encoding/base64"
6 "fmt"
7 "io"
8 "net"
9 "strconv"
10 "strings"
11 "time"
12
13 "github.com/emersion/go-sasl"
14 "golang.org/x/crypto/bcrypt"
15 "gopkg.in/irc.v3"
16)
17
18type ircError struct {
19 Message *irc.Message
20}
21
22func (err ircError) Error() string {
23 return err.Message.String()
24}
25
26func newUnknownCommandError(cmd string) ircError {
27 return ircError{&irc.Message{
28 Command: irc.ERR_UNKNOWNCOMMAND,
29 Params: []string{
30 "*",
31 cmd,
32 "Unknown command",
33 },
34 }}
35}
36
37func newNeedMoreParamsError(cmd string) ircError {
38 return ircError{&irc.Message{
39 Command: irc.ERR_NEEDMOREPARAMS,
40 Params: []string{
41 "*",
42 cmd,
43 "Not enough parameters",
44 },
45 }}
46}
47
48func newChatHistoryError(subcommand string, target string) ircError {
49 return ircError{&irc.Message{
50 Command: "FAIL",
51 Params: []string{"CHATHISTORY", "MESSAGE_ERROR", subcommand, target, "Messages could not be retrieved"},
52 }}
53}
54
55var errAuthFailed = ircError{&irc.Message{
56 Command: irc.ERR_PASSWDMISMATCH,
57 Params: []string{"*", "Invalid username or password"},
58}}
59
60// ' ' and ':' break the IRC message wire format, '@' and '!' break prefixes,
61// '*' and '?' break masks
62const illegalNickChars = " :@!*?"
63
64// permanentDownstreamCaps is the list of always-supported downstream
65// capabilities.
66var permanentDownstreamCaps = map[string]string{
67 "batch": "",
68 "cap-notify": "",
69 "echo-message": "",
70 "invite-notify": "",
71 "message-tags": "",
72 "sasl": "PLAIN",
73 "server-time": "",
74}
75
76// needAllDownstreamCaps is the list of downstream capabilities that
77// require support from all upstreams to be enabled
78var needAllDownstreamCaps = map[string]string{
79 "away-notify": "",
80 "extended-join": "",
81 "multi-prefix": "",
82}
83
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
111type downstreamConn struct {
112 conn
113
114 id uint64
115
116 registered bool
117 user *user
118 nick string
119 nickCM string
120 rawUsername string
121 networkName string
122 clientName string
123 realname string
124 hostname string
125 password string // empty after authentication
126 network *network // can be nil
127
128 negociatingCaps bool
129 capVersion int
130 supportedCaps map[string]string
131 caps map[string]bool
132
133 saslServer sasl.Server
134}
135
136func newDownstreamConn(srv *Server, ic ircConn, id uint64) *downstreamConn {
137 remoteAddr := ic.RemoteAddr().String()
138 logger := &prefixLogger{srv.Logger, fmt.Sprintf("downstream %q: ", remoteAddr)}
139 options := connOptions{Logger: logger}
140 dc := &downstreamConn{
141 conn: *newConn(srv, ic, &options),
142 id: id,
143 supportedCaps: make(map[string]string),
144 caps: make(map[string]bool),
145 }
146 dc.hostname = remoteAddr
147 if host, _, err := net.SplitHostPort(dc.hostname); err == nil {
148 dc.hostname = host
149 }
150 for k, v := range permanentDownstreamCaps {
151 dc.supportedCaps[k] = v
152 }
153 if srv.LogPath != "" {
154 dc.supportedCaps["draft/chathistory"] = ""
155 }
156 return dc
157}
158
159func (dc *downstreamConn) prefix() *irc.Prefix {
160 return &irc.Prefix{
161 Name: dc.nick,
162 User: dc.user.Username,
163 Host: dc.hostname,
164 }
165}
166
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
175func (dc *downstreamConn) forEachUpstream(f func(*upstreamConn)) {
176 dc.user.forEachUpstream(func(uc *upstreamConn) {
177 if dc.network != nil && uc.network != dc.network {
178 return
179 }
180 f(uc)
181 })
182}
183
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 }
190 return dc.network.conn
191}
192
193func isOurNick(net *network, nick string) bool {
194 // TODO: this doesn't account for nick changes
195 if net.conn != nil {
196 return net.casemap(nick) == net.conn.nickCM
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.
202 return net.casemap(nick) == net.casemap(net.Nick)
203}
204
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.
210func (dc *downstreamConn) marshalEntity(net *network, name string) string {
211 if isOurNick(net, name) {
212 return dc.nick
213 }
214 name = partialCasemap(net.casemap, name)
215 if dc.network != nil {
216 if dc.network != net {
217 panic("soju: tried to marshal an entity for another network")
218 }
219 return name
220 }
221 return name + "/" + net.GetName()
222}
223
224func (dc *downstreamConn) marshalUserPrefix(net *network, prefix *irc.Prefix) *irc.Prefix {
225 if isOurNick(net, prefix.Name) {
226 return dc.prefix()
227 }
228 prefix.Name = partialCasemap(net.casemap, prefix.Name)
229 if dc.network != nil {
230 if dc.network != net {
231 panic("soju: tried to marshal a user prefix for another network")
232 }
233 return prefix
234 }
235 return &irc.Prefix{
236 Name: prefix.Name + "/" + net.GetName(),
237 User: prefix.User,
238 Host: prefix.Host,
239 }
240}
241
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.
246func (dc *downstreamConn) unmarshalEntity(name string) (*upstreamConn, string, error) {
247 if uc := dc.upstream(); uc != nil {
248 return uc, name, nil
249 }
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 }
256
257 var conn *upstreamConn
258 if i := strings.LastIndexByte(name, '/'); i >= 0 {
259 network := name[i+1:]
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
270 if conn == nil {
271 return nil, "", ircError{&irc.Message{
272 Command: irc.ERR_NOSUCHCHANNEL,
273 Params: []string{name, "Missing network suffix in channel name"},
274 }}
275 }
276 return conn, name, nil
277}
278
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
287func (dc *downstreamConn) readMessages(ch chan<- event) error {
288 for {
289 msg, err := dc.ReadMessage()
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
296 ch <- eventDownstreamMessage{msg, dc}
297 }
298
299 return nil
300}
301
302// SendMessage sends an outgoing message.
303//
304// This can only called from the user goroutine.
305func (dc *downstreamConn) SendMessage(msg *irc.Message) {
306 if !dc.caps["message-tags"] {
307 if msg.Command == "TAGMSG" {
308 return
309 }
310 msg = msg.Copy()
311 for name := range msg.Tags {
312 supported := false
313 switch name {
314 case "time":
315 supported = dc.caps["server-time"]
316 }
317 if !supported {
318 delete(msg.Tags, name)
319 }
320 }
321 }
322 if msg.Command == "JOIN" && !dc.caps["extended-join"] {
323 msg.Params = msg.Params[:1]
324 }
325
326 dc.conn.SendMessage(msg)
327}
328
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) {
353 netID, entity, _, err := parseMsgID(id)
354 if err != nil {
355 dc.logger.Printf("failed to ACK message ID %q: %v", id, err)
356 return
357 }
358
359 network := dc.user.getNetworkByID(netID)
360 if network == nil {
361 return
362 }
363
364 delivered := network.delivered.Value(entity)
365 if delivered == nil {
366 return
367 }
368
369 delivered[dc.clientName] = id
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
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
398// messages that may appear in logs are supported, except MODE.
399func (dc *downstreamConn) marshalMessage(msg *irc.Message, net *network) *irc.Message {
400 msg = msg.Copy()
401 msg.Prefix = dc.marshalUserPrefix(net, msg.Prefix)
402
403 switch msg.Command {
404 case "PRIVMSG", "NOTICE", "TAGMSG":
405 msg.Params[0] = dc.marshalEntity(net, msg.Params[0])
406 case "NICK":
407 // Nick change for another user
408 msg.Params[0] = dc.marshalEntity(net, msg.Params[0])
409 case "JOIN", "PART":
410 msg.Params[0] = dc.marshalEntity(net, msg.Params[0])
411 case "KICK":
412 msg.Params[0] = dc.marshalEntity(net, msg.Params[0])
413 msg.Params[1] = dc.marshalEntity(net, msg.Params[1])
414 case "TOPIC":
415 msg.Params[0] = dc.marshalEntity(net, msg.Params[0])
416 case "QUIT":
417 // This space is intentionally left blank
418 default:
419 panic(fmt.Sprintf("unexpected %q message", msg.Command))
420 }
421
422 return msg
423}
424
425func (dc *downstreamConn) handleMessage(msg *irc.Message) error {
426 switch msg.Command {
427 case "QUIT":
428 return dc.Close()
429 default:
430 if dc.registered {
431 return dc.handleMessageRegistered(msg)
432 } else {
433 return dc.handleMessageUnregistered(msg)
434 }
435 }
436}
437
438func (dc *downstreamConn) handleMessageUnregistered(msg *irc.Message) error {
439 switch msg.Command {
440 case "NICK":
441 var nick string
442 if err := parseMessageParams(msg, &nick); err != nil {
443 return err
444 }
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 }
451 nickCM := casemapASCII(nick)
452 if nickCM == serviceNickCM {
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
459 dc.nickCM = nickCM
460 case "USER":
461 if err := parseMessageParams(msg, &dc.rawUsername, nil, nil, &dc.realname); err != nil {
462 return err
463 }
464 case "PASS":
465 if err := parseMessageParams(msg, &dc.password); err != nil {
466 return err
467 }
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 }
476 case "AUTHENTICATE":
477 if !dc.caps["sasl"] {
478 return ircError{&irc.Message{
479 Command: irc.ERR_SASLFAIL,
480 Params: []string{"*", "AUTHENTICATE requires the \"sasl\" capability to be enabled"},
481 }}
482 }
483 if len(msg.Params) == 0 {
484 return ircError{&irc.Message{
485 Command: irc.ERR_SASLFAIL,
486 Params: []string{"*", "Missing AUTHENTICATE argument"},
487 }}
488 }
489 if dc.nick == "" {
490 return ircError{&irc.Message{
491 Command: irc.ERR_SASLFAIL,
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{
506 Command: irc.ERR_SASLFAIL,
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{
513 Command: irc.ERR_SASLABORTED,
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{
525 Command: irc.ERR_SASLFAIL,
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{
536 Command: irc.ERR_SASLFAIL,
537 Params: []string{"*", ircErr.Message.Params[1]},
538 }}
539 }
540 dc.SendMessage(&irc.Message{
541 Prefix: dc.srv.prefix(),
542 Command: irc.ERR_SASLFAIL,
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(),
550 Command: irc.RPL_LOGGEDIN,
551 Params: []string{dc.nick, dc.prefix().String(), dc.user.Username, "You are now logged in"},
552 })
553 dc.SendMessage(&irc.Message{
554 Prefix: dc.srv.prefix(),
555 Command: irc.RPL_SASLSUCCESS,
556 Params: []string{dc.nick, "SASL authentication successful"},
557 })
558 } else {
559 challengeStr := "+"
560 if len(challenge) > 0 {
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 }
571 default:
572 dc.logger.Printf("unhandled message: %v", msg)
573 return newUnknownCommandError(msg.Command)
574 }
575 if dc.rawUsername != "" && dc.nick != "" && !dc.negociatingCaps {
576 return dc.register()
577 }
578 return nil
579}
580
581func (dc *downstreamConn) handleCapCommand(cmd string, args []string) error {
582 cmd = strings.ToUpper(cmd)
583
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 }
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 }
605
606 caps := make([]string, 0, len(dc.supportedCaps))
607 for k, v := range dc.supportedCaps {
608 if dc.capVersion >= 302 && v != "" {
609 caps = append(caps, k+"="+v)
610 } else {
611 caps = append(caps, k)
612 }
613 }
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
622 if dc.capVersion >= 302 {
623 // CAP version 302 implicitly enables cap-notify
624 dc.caps["cap-notify"] = true
625 }
626
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
650 // TODO: atomically ack/nak the whole capability set
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
660 if enable == dc.caps[name] {
661 continue
662 }
663
664 _, ok := dc.supportedCaps[name]
665 if !ok {
666 ack = false
667 break
668 }
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
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
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
746func (dc *downstreamConn) updateSupportedCaps() {
747 supportedCaps := make(map[string]bool)
748 for cap := range needAllDownstreamCaps {
749 supportedCaps[cap] = true
750 }
751 dc.forEachUpstream(func(uc *upstreamConn) {
752 for cap, supported := range supportedCaps {
753 supportedCaps[cap] = supported && uc.caps[cap]
754 }
755 })
756
757 for cap, supported := range supportedCaps {
758 if supported {
759 dc.setSupportedCap(cap, needAllDownstreamCaps[cap])
760 } else {
761 dc.unsetSupportedCap(cap)
762 }
763 }
764}
765
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
774 dc.nickCM = casemapASCII(dc.nick)
775 }
776}
777
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
787func unmarshalUsername(rawUsername string) (username, client, network string) {
788 username = rawUsername
789
790 i := strings.IndexAny(username, "/@")
791 j := strings.LastIndexAny(username, "/@")
792 if i >= 0 {
793 username = rawUsername[:i]
794 }
795 if j >= 0 {
796 if rawUsername[j] == '@' {
797 client = rawUsername[j+1:]
798 } else {
799 network = rawUsername[j+1:]
800 }
801 }
802 if i >= 0 && j >= 0 && i < j {
803 if rawUsername[i] == '@' {
804 client = rawUsername[i+1 : j]
805 } else {
806 network = rawUsername[i+1 : j]
807 }
808 }
809
810 return username, client, network
811}
812
813func (dc *downstreamConn) authenticate(username, password string) error {
814 username, clientName, networkName := unmarshalUsername(username)
815
816 u, err := dc.srv.db.GetUser(username)
817 if err != nil {
818 dc.logger.Printf("failed authentication for %q: user not found: %v", username, err)
819 return errAuthFailed
820 }
821
822 // Password auth disabled
823 if u.Password == "" {
824 return errAuthFailed
825 }
826
827 err = bcrypt.CompareHashAndPassword([]byte(u.Password), []byte(password))
828 if err != nil {
829 dc.logger.Printf("failed authentication for %q: wrong password: %v", username, err)
830 return errAuthFailed
831 }
832
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 }
838 dc.clientName = clientName
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
856 if dc.clientName == "" && dc.networkName == "" {
857 _, dc.clientName, dc.networkName = unmarshalUsername(dc.rawUsername)
858 }
859
860 dc.registered = true
861 dc.logger.Printf("registration complete for user %q", dc.user.Username)
862 return nil
863}
864
865func (dc *downstreamConn) loadNetwork() error {
866 if dc.networkName == "" {
867 return nil
868 }
869
870 network := dc.user.getNetwork(dc.networkName)
871 if network == nil {
872 addr := dc.networkName
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,
882 Params: []string{"*", fmt.Sprintf("Failed to connect to %q", dc.networkName)},
883 }}
884 }
885
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
891 dc.logger.Printf("auto-saving network %q", dc.networkName)
892 var err error
893 network, err = dc.user.createNetwork(&Network{
894 Addr: dc.networkName,
895 Nick: nick,
896 })
897 if err != nil {
898 return err
899 }
900 }
901
902 dc.network = network
903 return nil
904}
905
906func (dc *downstreamConn) welcome() error {
907 if dc.user == nil || !dc.registered {
908 panic("tried to welcome an unregistered connection")
909 }
910
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
916 }
917
918 isupport := []string{
919 fmt.Sprintf("CHATHISTORY=%v", dc.srv.HistoryLimit),
920 "CASEMAPPING=ascii",
921 }
922
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 }
935 }
936
937 dc.SendMessage(&irc.Message{
938 Prefix: dc.srv.prefix(),
939 Command: irc.RPL_WELCOME,
940 Params: []string{dc.nick, "Welcome to soju, " + dc.nick},
941 })
942 dc.SendMessage(&irc.Message{
943 Prefix: dc.srv.prefix(),
944 Command: irc.RPL_YOURHOST,
945 Params: []string{dc.nick, "Your host is " + dc.srv.Hostname},
946 })
947 dc.SendMessage(&irc.Message{
948 Prefix: dc.srv.prefix(),
949 Command: irc.RPL_CREATED,
950 Params: []string{dc.nick, "Who cares when the server was created?"},
951 })
952 dc.SendMessage(&irc.Message{
953 Prefix: dc.srv.prefix(),
954 Command: irc.RPL_MYINFO,
955 Params: []string{dc.nick, dc.srv.Hostname, "soju", "aiwroO", "OovaimnqpsrtklbeI"},
956 })
957 for _, msg := range generateIsupport(dc.srv.prefix(), dc.nick, isupport) {
958 dc.SendMessage(msg)
959 }
960 dc.SendMessage(&irc.Message{
961 Prefix: dc.srv.prefix(),
962 Command: irc.ERR_NOMOTD,
963 Params: []string{dc.nick, "No MOTD"},
964 })
965
966 dc.updateNick()
967 dc.updateSupportedCaps()
968
969 dc.forEachUpstream(func(uc *upstreamConn) {
970 for _, entry := range uc.channels.innerMap {
971 ch := entry.value.(*upstreamChannel)
972 if !ch.complete {
973 continue
974 }
975 record := uc.network.channels.Value(ch.Name)
976 if record != nil && record.Detached {
977 continue
978 }
979
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)
987 }
988 })
989
990 dc.forEachNetwork(func(net *network) {
991 // Only send history if we're the first connected client with that name
992 // for the network
993 firstClient := true
994 dc.user.forEachDownstream(func(c *downstreamConn) {
995 if c != dc && c.clientName == dc.clientName && c.network == dc.network {
996 firstClient = false
997 }
998 })
999 if firstClient {
1000 dc.sendNetworkBacklog(net)
1001 }
1002
1003 // Fast-forward history to last message
1004 for targetCM, entry := range net.delivered.innerMap {
1005 delivered := entry.value.(deliveredClientMap)
1006 ch := net.channels.Value(targetCM)
1007 if ch != nil && ch.Detached {
1008 continue
1009 }
1010
1011 lastID, err := dc.user.msgStore.LastMsgID(net, targetCM, time.Now())
1012 if err != nil {
1013 dc.logger.Printf("failed to get last message ID: %v", err)
1014 continue
1015 }
1016 delivered[dc.clientName] = lastID
1017 }
1018 })
1019
1020 return nil
1021}
1022
1023// messageSupportsHistory checks whether the provided message can be sent as
1024// part of an history batch.
1025func (dc *downstreamConn) messageSupportsHistory(msg *irc.Message) bool {
1026 // Don't replay all messages, because that would mess up client
1027 // state. For instance we just sent the list of users, sending
1028 // PART messages for one of these users would be incorrect.
1029 // TODO: add support for draft/event-playback
1030 switch msg.Command {
1031 case "PRIVMSG", "NOTICE":
1032 return true
1033 }
1034 return false
1035}
1036
1037func (dc *downstreamConn) sendNetworkBacklog(net *network) {
1038 for _, entry := range net.delivered.innerMap {
1039 target := entry.originalKey
1040 dc.sendTargetBacklog(net, target)
1041 }
1042}
1043
1044func (dc *downstreamConn) sendTargetBacklog(net *network, target string) {
1045 if dc.caps["draft/chathistory"] || dc.user.msgStore == nil {
1046 return
1047 }
1048 if ch := net.channels.Value(target); ch != nil && ch.Detached {
1049 return
1050 }
1051 delivered := net.delivered.Value(target)
1052 if delivered == nil {
1053 return
1054 }
1055 lastDelivered, ok := delivered[dc.clientName]
1056 if !ok {
1057 return
1058 }
1059
1060 limit := 4000
1061 targetCM := net.casemap(target)
1062 history, err := dc.user.msgStore.LoadLatestID(net, targetCM, lastDelivered, limit)
1063 if err != nil {
1064 dc.logger.Printf("failed to send implicit history for %q: %v", target, err)
1065 return
1066 }
1067
1068 batchRef := "history"
1069 if dc.caps["batch"] {
1070 dc.SendMessage(&irc.Message{
1071 Prefix: dc.srv.prefix(),
1072 Command: "BATCH",
1073 Params: []string{"+" + batchRef, "chathistory", dc.marshalEntity(net, target)},
1074 })
1075 }
1076
1077 for _, msg := range history {
1078 if !dc.messageSupportsHistory(msg) {
1079 continue
1080 }
1081
1082 if dc.caps["batch"] {
1083 msg.Tags["batch"] = irc.TagValue(batchRef)
1084 }
1085 dc.SendMessage(dc.marshalMessage(msg, net))
1086 }
1087
1088 if dc.caps["batch"] {
1089 dc.SendMessage(&irc.Message{
1090 Prefix: dc.srv.prefix(),
1091 Command: "BATCH",
1092 Params: []string{"-" + batchRef},
1093 })
1094 }
1095}
1096
1097func (dc *downstreamConn) runUntilRegistered() error {
1098 for !dc.registered {
1099 msg, err := dc.ReadMessage()
1100 if err != nil {
1101 return fmt.Errorf("failed to read IRC command: %v", err)
1102 }
1103
1104 err = dc.handleMessage(msg)
1105 if ircErr, ok := err.(ircError); ok {
1106 ircErr.Message.Prefix = dc.srv.prefix()
1107 dc.SendMessage(ircErr.Message)
1108 } else if err != nil {
1109 return fmt.Errorf("failed to handle IRC command %q: %v", msg, err)
1110 }
1111 }
1112
1113 return nil
1114}
1115
1116func (dc *downstreamConn) handleMessageRegistered(msg *irc.Message) error {
1117 switch msg.Command {
1118 case "CAP":
1119 var subCmd string
1120 if err := parseMessageParams(msg, &subCmd); err != nil {
1121 return err
1122 }
1123 if err := dc.handleCapCommand(subCmd, msg.Params[1:]); err != nil {
1124 return err
1125 }
1126 case "PING":
1127 var source, destination string
1128 if err := parseMessageParams(msg, &source); err != nil {
1129 return err
1130 }
1131 if len(msg.Params) > 1 {
1132 destination = msg.Params[1]
1133 }
1134 if destination != "" && destination != dc.srv.Hostname {
1135 return ircError{&irc.Message{
1136 Command: irc.ERR_NOSUCHSERVER,
1137 Params: []string{dc.nick, destination, "No such server"},
1138 }}
1139 }
1140 dc.SendMessage(&irc.Message{
1141 Prefix: dc.srv.prefix(),
1142 Command: "PONG",
1143 Params: []string{dc.srv.Hostname, source},
1144 })
1145 return nil
1146 case "PONG":
1147 if len(msg.Params) == 0 {
1148 return newNeedMoreParamsError(msg.Command)
1149 }
1150 token := msg.Params[len(msg.Params)-1]
1151 dc.handlePong(token)
1152 case "USER":
1153 return ircError{&irc.Message{
1154 Command: irc.ERR_ALREADYREGISTERED,
1155 Params: []string{dc.nick, "You may not reregister"},
1156 }}
1157 case "NICK":
1158 var rawNick string
1159 if err := parseMessageParams(msg, &rawNick); err != nil {
1160 return err
1161 }
1162
1163 nick := rawNick
1164 var upstream *upstreamConn
1165 if dc.upstream() == nil {
1166 uc, unmarshaledNick, err := dc.unmarshalEntity(nick)
1167 if err == nil { // NICK nick/network: NICK only on a specific upstream
1168 upstream = uc
1169 nick = unmarshaledNick
1170 }
1171 }
1172
1173 if strings.ContainsAny(nick, illegalNickChars) {
1174 return ircError{&irc.Message{
1175 Command: irc.ERR_ERRONEUSNICKNAME,
1176 Params: []string{dc.nick, rawNick, "contains illegal characters"},
1177 }}
1178 }
1179 if casemapASCII(nick) == serviceNickCM {
1180 return ircError{&irc.Message{
1181 Command: irc.ERR_NICKNAMEINUSE,
1182 Params: []string{dc.nick, rawNick, "Nickname reserved for bouncer service"},
1183 }}
1184 }
1185
1186 var err error
1187 dc.forEachNetwork(func(n *network) {
1188 if err != nil || (upstream != nil && upstream.network != n) {
1189 return
1190 }
1191 n.Nick = nick
1192 err = dc.srv.db.StoreNetwork(dc.user.ID, &n.Network)
1193 })
1194 if err != nil {
1195 return err
1196 }
1197
1198 dc.forEachUpstream(func(uc *upstreamConn) {
1199 if upstream != nil && upstream != uc {
1200 return
1201 }
1202 uc.SendMessageLabeled(dc.id, &irc.Message{
1203 Command: "NICK",
1204 Params: []string{nick},
1205 })
1206 })
1207
1208 if dc.upstream() == nil && dc.nick != nick {
1209 dc.SendMessage(&irc.Message{
1210 Prefix: dc.prefix(),
1211 Command: "NICK",
1212 Params: []string{nick},
1213 })
1214 dc.nick = nick
1215 dc.nickCM = casemapASCII(dc.nick)
1216 }
1217 case "JOIN":
1218 var namesStr string
1219 if err := parseMessageParams(msg, &namesStr); err != nil {
1220 return err
1221 }
1222
1223 var keys []string
1224 if len(msg.Params) > 1 {
1225 keys = strings.Split(msg.Params[1], ",")
1226 }
1227
1228 for i, name := range strings.Split(namesStr, ",") {
1229 uc, upstreamName, err := dc.unmarshalEntity(name)
1230 if err != nil {
1231 return err
1232 }
1233
1234 var key string
1235 if len(keys) > i {
1236 key = keys[i]
1237 }
1238
1239 params := []string{upstreamName}
1240 if key != "" {
1241 params = append(params, key)
1242 }
1243 uc.SendMessageLabeled(dc.id, &irc.Message{
1244 Command: "JOIN",
1245 Params: params,
1246 })
1247
1248 ch := uc.network.channels.Value(upstreamName)
1249 if ch != nil {
1250 // Don't clear the channel key if there's one set
1251 // TODO: add a way to unset the channel key
1252 if key != "" {
1253 ch.Key = key
1254 }
1255 uc.network.attach(ch)
1256 } else {
1257 ch = &Channel{
1258 Name: upstreamName,
1259 Key: key,
1260 }
1261 uc.network.channels.SetValue(upstreamName, ch)
1262 }
1263 if err := dc.srv.db.StoreChannel(uc.network.ID, ch); err != nil {
1264 dc.logger.Printf("failed to create or update channel %q: %v", upstreamName, err)
1265 }
1266 }
1267 case "PART":
1268 var namesStr string
1269 if err := parseMessageParams(msg, &namesStr); err != nil {
1270 return err
1271 }
1272
1273 var reason string
1274 if len(msg.Params) > 1 {
1275 reason = msg.Params[1]
1276 }
1277
1278 for _, name := range strings.Split(namesStr, ",") {
1279 uc, upstreamName, err := dc.unmarshalEntity(name)
1280 if err != nil {
1281 return err
1282 }
1283
1284 if strings.EqualFold(reason, "detach") {
1285 ch := uc.network.channels.Value(upstreamName)
1286 if ch != nil {
1287 uc.network.detach(ch)
1288 } else {
1289 ch = &Channel{
1290 Name: name,
1291 Detached: true,
1292 }
1293 uc.network.channels.SetValue(upstreamName, ch)
1294 }
1295 if err := dc.srv.db.StoreChannel(uc.network.ID, ch); err != nil {
1296 dc.logger.Printf("failed to create or update channel %q: %v", upstreamName, err)
1297 }
1298 } else {
1299 params := []string{upstreamName}
1300 if reason != "" {
1301 params = append(params, reason)
1302 }
1303 uc.SendMessageLabeled(dc.id, &irc.Message{
1304 Command: "PART",
1305 Params: params,
1306 })
1307
1308 if err := uc.network.deleteChannel(upstreamName); err != nil {
1309 dc.logger.Printf("failed to delete channel %q: %v", upstreamName, err)
1310 }
1311 }
1312 }
1313 case "KICK":
1314 var channelStr, userStr string
1315 if err := parseMessageParams(msg, &channelStr, &userStr); err != nil {
1316 return err
1317 }
1318
1319 channels := strings.Split(channelStr, ",")
1320 users := strings.Split(userStr, ",")
1321
1322 var reason string
1323 if len(msg.Params) > 2 {
1324 reason = msg.Params[2]
1325 }
1326
1327 if len(channels) != 1 && len(channels) != len(users) {
1328 return ircError{&irc.Message{
1329 Command: irc.ERR_BADCHANMASK,
1330 Params: []string{dc.nick, channelStr, "Bad channel mask"},
1331 }}
1332 }
1333
1334 for i, user := range users {
1335 var channel string
1336 if len(channels) == 1 {
1337 channel = channels[0]
1338 } else {
1339 channel = channels[i]
1340 }
1341
1342 ucChannel, upstreamChannel, err := dc.unmarshalEntity(channel)
1343 if err != nil {
1344 return err
1345 }
1346
1347 ucUser, upstreamUser, err := dc.unmarshalEntity(user)
1348 if err != nil {
1349 return err
1350 }
1351
1352 if ucChannel != ucUser {
1353 return ircError{&irc.Message{
1354 Command: irc.ERR_USERNOTINCHANNEL,
1355 Params: []string{dc.nick, user, channel, "They are on another network"},
1356 }}
1357 }
1358 uc := ucChannel
1359
1360 params := []string{upstreamChannel, upstreamUser}
1361 if reason != "" {
1362 params = append(params, reason)
1363 }
1364 uc.SendMessageLabeled(dc.id, &irc.Message{
1365 Command: "KICK",
1366 Params: params,
1367 })
1368 }
1369 case "MODE":
1370 var name string
1371 if err := parseMessageParams(msg, &name); err != nil {
1372 return err
1373 }
1374
1375 var modeStr string
1376 if len(msg.Params) > 1 {
1377 modeStr = msg.Params[1]
1378 }
1379
1380 if casemapASCII(name) == dc.nickCM {
1381 if modeStr != "" {
1382 dc.forEachUpstream(func(uc *upstreamConn) {
1383 uc.SendMessageLabeled(dc.id, &irc.Message{
1384 Command: "MODE",
1385 Params: []string{uc.nick, modeStr},
1386 })
1387 })
1388 } else {
1389 dc.SendMessage(&irc.Message{
1390 Prefix: dc.srv.prefix(),
1391 Command: irc.RPL_UMODEIS,
1392 Params: []string{dc.nick, ""}, // TODO
1393 })
1394 }
1395 return nil
1396 }
1397
1398 uc, upstreamName, err := dc.unmarshalEntity(name)
1399 if err != nil {
1400 return err
1401 }
1402
1403 if !uc.isChannel(upstreamName) {
1404 return ircError{&irc.Message{
1405 Command: irc.ERR_USERSDONTMATCH,
1406 Params: []string{dc.nick, "Cannot change mode for other users"},
1407 }}
1408 }
1409
1410 if modeStr != "" {
1411 params := []string{upstreamName, modeStr}
1412 params = append(params, msg.Params[2:]...)
1413 uc.SendMessageLabeled(dc.id, &irc.Message{
1414 Command: "MODE",
1415 Params: params,
1416 })
1417 } else {
1418 ch := uc.channels.Value(upstreamName)
1419 if ch == nil {
1420 return ircError{&irc.Message{
1421 Command: irc.ERR_NOSUCHCHANNEL,
1422 Params: []string{dc.nick, name, "No such channel"},
1423 }}
1424 }
1425
1426 if ch.modes == nil {
1427 // we haven't received the initial RPL_CHANNELMODEIS yet
1428 // ignore the request, we will broadcast the modes later when we receive RPL_CHANNELMODEIS
1429 return nil
1430 }
1431
1432 modeStr, modeParams := ch.modes.Format()
1433 params := []string{dc.nick, name, modeStr}
1434 params = append(params, modeParams...)
1435
1436 dc.SendMessage(&irc.Message{
1437 Prefix: dc.srv.prefix(),
1438 Command: irc.RPL_CHANNELMODEIS,
1439 Params: params,
1440 })
1441 if ch.creationTime != "" {
1442 dc.SendMessage(&irc.Message{
1443 Prefix: dc.srv.prefix(),
1444 Command: rpl_creationtime,
1445 Params: []string{dc.nick, name, ch.creationTime},
1446 })
1447 }
1448 }
1449 case "TOPIC":
1450 var channel string
1451 if err := parseMessageParams(msg, &channel); err != nil {
1452 return err
1453 }
1454
1455 uc, upstreamName, err := dc.unmarshalEntity(channel)
1456 if err != nil {
1457 return err
1458 }
1459
1460 if len(msg.Params) > 1 { // setting topic
1461 topic := msg.Params[1]
1462 uc.SendMessageLabeled(dc.id, &irc.Message{
1463 Command: "TOPIC",
1464 Params: []string{upstreamName, topic},
1465 })
1466 } else { // getting topic
1467 ch := uc.channels.Value(upstreamName)
1468 if ch == nil {
1469 return ircError{&irc.Message{
1470 Command: irc.ERR_NOSUCHCHANNEL,
1471 Params: []string{dc.nick, upstreamName, "No such channel"},
1472 }}
1473 }
1474 sendTopic(dc, ch)
1475 }
1476 case "LIST":
1477 // TODO: support ELIST when supported by all upstreams
1478
1479 pl := pendingLIST{
1480 downstreamID: dc.id,
1481 pendingCommands: make(map[int64]*irc.Message),
1482 }
1483 var upstream *upstreamConn
1484 var upstreamChannels map[int64][]string
1485 if len(msg.Params) > 0 {
1486 uc, upstreamMask, err := dc.unmarshalEntity(msg.Params[0])
1487 if err == nil && upstreamMask == "*" { // LIST */network: send LIST only to one network
1488 upstream = uc
1489 } else {
1490 upstreamChannels = make(map[int64][]string)
1491 channels := strings.Split(msg.Params[0], ",")
1492 for _, channel := range channels {
1493 uc, upstreamChannel, err := dc.unmarshalEntity(channel)
1494 if err != nil {
1495 return err
1496 }
1497 upstreamChannels[uc.network.ID] = append(upstreamChannels[uc.network.ID], upstreamChannel)
1498 }
1499 }
1500 }
1501
1502 dc.user.pendingLISTs = append(dc.user.pendingLISTs, pl)
1503 dc.forEachUpstream(func(uc *upstreamConn) {
1504 if upstream != nil && upstream != uc {
1505 return
1506 }
1507 var params []string
1508 if upstreamChannels != nil {
1509 if channels, ok := upstreamChannels[uc.network.ID]; ok {
1510 params = []string{strings.Join(channels, ",")}
1511 } else {
1512 return
1513 }
1514 }
1515 pl.pendingCommands[uc.network.ID] = &irc.Message{
1516 Command: "LIST",
1517 Params: params,
1518 }
1519 uc.trySendLIST(dc.id)
1520 })
1521 case "NAMES":
1522 if len(msg.Params) == 0 {
1523 dc.SendMessage(&irc.Message{
1524 Prefix: dc.srv.prefix(),
1525 Command: irc.RPL_ENDOFNAMES,
1526 Params: []string{dc.nick, "*", "End of /NAMES list"},
1527 })
1528 return nil
1529 }
1530
1531 channels := strings.Split(msg.Params[0], ",")
1532 for _, channel := range channels {
1533 uc, upstreamName, err := dc.unmarshalEntity(channel)
1534 if err != nil {
1535 return err
1536 }
1537
1538 ch := uc.channels.Value(upstreamName)
1539 if ch != nil {
1540 sendNames(dc, ch)
1541 } else {
1542 // NAMES on a channel we have not joined, ask upstream
1543 uc.SendMessageLabeled(dc.id, &irc.Message{
1544 Command: "NAMES",
1545 Params: []string{upstreamName},
1546 })
1547 }
1548 }
1549 case "WHO":
1550 if len(msg.Params) == 0 {
1551 // TODO: support WHO without parameters
1552 dc.SendMessage(&irc.Message{
1553 Prefix: dc.srv.prefix(),
1554 Command: irc.RPL_ENDOFWHO,
1555 Params: []string{dc.nick, "*", "End of /WHO list"},
1556 })
1557 return nil
1558 }
1559
1560 // TODO: support WHO masks
1561 entity := msg.Params[0]
1562 entityCM := casemapASCII(entity)
1563
1564 if entityCM == dc.nickCM {
1565 // TODO: support AWAY (H/G) in self WHO reply
1566 dc.SendMessage(&irc.Message{
1567 Prefix: dc.srv.prefix(),
1568 Command: irc.RPL_WHOREPLY,
1569 Params: []string{dc.nick, "*", dc.user.Username, dc.hostname, dc.srv.Hostname, dc.nick, "H", "0 " + dc.realname},
1570 })
1571 dc.SendMessage(&irc.Message{
1572 Prefix: dc.srv.prefix(),
1573 Command: irc.RPL_ENDOFWHO,
1574 Params: []string{dc.nick, dc.nick, "End of /WHO list"},
1575 })
1576 return nil
1577 }
1578 if entityCM == serviceNickCM {
1579 dc.SendMessage(&irc.Message{
1580 Prefix: dc.srv.prefix(),
1581 Command: irc.RPL_WHOREPLY,
1582 Params: []string{serviceNick, "*", servicePrefix.User, servicePrefix.Host, dc.srv.Hostname, serviceNick, "H", "0 " + serviceRealname},
1583 })
1584 dc.SendMessage(&irc.Message{
1585 Prefix: dc.srv.prefix(),
1586 Command: irc.RPL_ENDOFWHO,
1587 Params: []string{dc.nick, serviceNick, "End of /WHO list"},
1588 })
1589 return nil
1590 }
1591
1592 uc, upstreamName, err := dc.unmarshalEntity(entity)
1593 if err != nil {
1594 return err
1595 }
1596
1597 var params []string
1598 if len(msg.Params) == 2 {
1599 params = []string{upstreamName, msg.Params[1]}
1600 } else {
1601 params = []string{upstreamName}
1602 }
1603
1604 uc.SendMessageLabeled(dc.id, &irc.Message{
1605 Command: "WHO",
1606 Params: params,
1607 })
1608 case "WHOIS":
1609 if len(msg.Params) == 0 {
1610 return ircError{&irc.Message{
1611 Command: irc.ERR_NONICKNAMEGIVEN,
1612 Params: []string{dc.nick, "No nickname given"},
1613 }}
1614 }
1615
1616 var target, mask string
1617 if len(msg.Params) == 1 {
1618 target = ""
1619 mask = msg.Params[0]
1620 } else {
1621 target = msg.Params[0]
1622 mask = msg.Params[1]
1623 }
1624 // TODO: support multiple WHOIS users
1625 if i := strings.IndexByte(mask, ','); i >= 0 {
1626 mask = mask[:i]
1627 }
1628
1629 if casemapASCII(mask) == dc.nickCM {
1630 dc.SendMessage(&irc.Message{
1631 Prefix: dc.srv.prefix(),
1632 Command: irc.RPL_WHOISUSER,
1633 Params: []string{dc.nick, dc.nick, dc.user.Username, dc.hostname, "*", dc.realname},
1634 })
1635 dc.SendMessage(&irc.Message{
1636 Prefix: dc.srv.prefix(),
1637 Command: irc.RPL_WHOISSERVER,
1638 Params: []string{dc.nick, dc.nick, dc.srv.Hostname, "soju"},
1639 })
1640 dc.SendMessage(&irc.Message{
1641 Prefix: dc.srv.prefix(),
1642 Command: irc.RPL_ENDOFWHOIS,
1643 Params: []string{dc.nick, dc.nick, "End of /WHOIS list"},
1644 })
1645 return nil
1646 }
1647
1648 // TODO: support WHOIS masks
1649 uc, upstreamNick, err := dc.unmarshalEntity(mask)
1650 if err != nil {
1651 return err
1652 }
1653
1654 var params []string
1655 if target != "" {
1656 if target == mask { // WHOIS nick nick
1657 params = []string{upstreamNick, upstreamNick}
1658 } else {
1659 params = []string{target, upstreamNick}
1660 }
1661 } else {
1662 params = []string{upstreamNick}
1663 }
1664
1665 uc.SendMessageLabeled(dc.id, &irc.Message{
1666 Command: "WHOIS",
1667 Params: params,
1668 })
1669 case "PRIVMSG":
1670 var targetsStr, text string
1671 if err := parseMessageParams(msg, &targetsStr, &text); err != nil {
1672 return err
1673 }
1674 tags := copyClientTags(msg.Tags)
1675
1676 for _, name := range strings.Split(targetsStr, ",") {
1677 if name == serviceNick {
1678 if dc.caps["echo-message"] {
1679 echoTags := tags.Copy()
1680 echoTags["time"] = irc.TagValue(time.Now().UTC().Format(serverTimeLayout))
1681 dc.SendMessage(&irc.Message{
1682 Tags: echoTags,
1683 Prefix: dc.prefix(),
1684 Command: "PRIVMSG",
1685 Params: []string{name, text},
1686 })
1687 }
1688 handleServicePRIVMSG(dc, text)
1689 continue
1690 }
1691
1692 uc, upstreamName, err := dc.unmarshalEntity(name)
1693 if err != nil {
1694 return err
1695 }
1696
1697 if upstreamName == "NickServ" {
1698 dc.handleNickServPRIVMSG(uc, text)
1699 }
1700
1701 unmarshaledText := text
1702 if uc.isChannel(upstreamName) {
1703 unmarshaledText = dc.unmarshalText(uc, text)
1704 }
1705 uc.SendMessageLabeled(dc.id, &irc.Message{
1706 Tags: tags,
1707 Command: "PRIVMSG",
1708 Params: []string{upstreamName, unmarshaledText},
1709 })
1710
1711 echoTags := tags.Copy()
1712 echoTags["time"] = irc.TagValue(time.Now().UTC().Format(serverTimeLayout))
1713 echoMsg := &irc.Message{
1714 Tags: echoTags,
1715 Prefix: &irc.Prefix{
1716 Name: uc.nick,
1717 User: uc.username,
1718 },
1719 Command: "PRIVMSG",
1720 Params: []string{upstreamName, text},
1721 }
1722 uc.produce(upstreamName, echoMsg, dc)
1723
1724 uc.updateChannelAutoDetach(upstreamName)
1725 }
1726 case "NOTICE":
1727 var targetsStr, text string
1728 if err := parseMessageParams(msg, &targetsStr, &text); err != nil {
1729 return err
1730 }
1731 tags := copyClientTags(msg.Tags)
1732
1733 for _, name := range strings.Split(targetsStr, ",") {
1734 uc, upstreamName, err := dc.unmarshalEntity(name)
1735 if err != nil {
1736 return err
1737 }
1738
1739 unmarshaledText := text
1740 if uc.isChannel(upstreamName) {
1741 unmarshaledText = dc.unmarshalText(uc, text)
1742 }
1743 uc.SendMessageLabeled(dc.id, &irc.Message{
1744 Tags: tags,
1745 Command: "NOTICE",
1746 Params: []string{upstreamName, unmarshaledText},
1747 })
1748
1749 uc.updateChannelAutoDetach(upstreamName)
1750 }
1751 case "TAGMSG":
1752 var targetsStr string
1753 if err := parseMessageParams(msg, &targetsStr); err != nil {
1754 return err
1755 }
1756 tags := copyClientTags(msg.Tags)
1757
1758 for _, name := range strings.Split(targetsStr, ",") {
1759 uc, upstreamName, err := dc.unmarshalEntity(name)
1760 if err != nil {
1761 return err
1762 }
1763 if _, ok := uc.caps["message-tags"]; !ok {
1764 continue
1765 }
1766
1767 uc.SendMessageLabeled(dc.id, &irc.Message{
1768 Tags: tags,
1769 Command: "TAGMSG",
1770 Params: []string{upstreamName},
1771 })
1772
1773 uc.updateChannelAutoDetach(upstreamName)
1774 }
1775 case "INVITE":
1776 var user, channel string
1777 if err := parseMessageParams(msg, &user, &channel); err != nil {
1778 return err
1779 }
1780
1781 ucChannel, upstreamChannel, err := dc.unmarshalEntity(channel)
1782 if err != nil {
1783 return err
1784 }
1785
1786 ucUser, upstreamUser, err := dc.unmarshalEntity(user)
1787 if err != nil {
1788 return err
1789 }
1790
1791 if ucChannel != ucUser {
1792 return ircError{&irc.Message{
1793 Command: irc.ERR_USERNOTINCHANNEL,
1794 Params: []string{dc.nick, user, channel, "They are on another network"},
1795 }}
1796 }
1797 uc := ucChannel
1798
1799 uc.SendMessageLabeled(dc.id, &irc.Message{
1800 Command: "INVITE",
1801 Params: []string{upstreamUser, upstreamChannel},
1802 })
1803 case "CHATHISTORY":
1804 var subcommand string
1805 if err := parseMessageParams(msg, &subcommand); err != nil {
1806 return err
1807 }
1808 var target, criteria, limitStr string
1809 if err := parseMessageParams(msg, nil, &target, &criteria, &limitStr); err != nil {
1810 return ircError{&irc.Message{
1811 Command: "FAIL",
1812 Params: []string{"CHATHISTORY", "NEED_MORE_PARAMS", subcommand, "Missing parameters"},
1813 }}
1814 }
1815
1816 store, ok := dc.user.msgStore.(chatHistoryMessageStore)
1817 if !ok {
1818 return ircError{&irc.Message{
1819 Command: irc.ERR_UNKNOWNCOMMAND,
1820 Params: []string{dc.nick, "CHATHISTORY", "Unknown command"},
1821 }}
1822 }
1823
1824 uc, entity, err := dc.unmarshalEntity(target)
1825 if err != nil {
1826 return err
1827 }
1828 entity = uc.network.casemap(entity)
1829
1830 // TODO: support msgid criteria
1831 criteriaParts := strings.SplitN(criteria, "=", 2)
1832 if len(criteriaParts) != 2 || criteriaParts[0] != "timestamp" {
1833 return ircError{&irc.Message{
1834 Command: "FAIL",
1835 Params: []string{"CHATHISTORY", "INVALID_PARAMS", subcommand, criteria, "Unknown criteria"},
1836 }}
1837 }
1838
1839 timestamp, err := time.Parse(serverTimeLayout, criteriaParts[1])
1840 if err != nil {
1841 return ircError{&irc.Message{
1842 Command: "FAIL",
1843 Params: []string{"CHATHISTORY", "INVALID_PARAMS", subcommand, criteria, "Invalid criteria"},
1844 }}
1845 }
1846
1847 limit, err := strconv.Atoi(limitStr)
1848 if err != nil || limit < 0 || limit > dc.srv.HistoryLimit {
1849 return ircError{&irc.Message{
1850 Command: "FAIL",
1851 Params: []string{"CHATHISTORY", "INVALID_PARAMS", subcommand, limitStr, "Invalid limit"},
1852 }}
1853 }
1854
1855 var history []*irc.Message
1856 switch subcommand {
1857 case "BEFORE":
1858 history, err = store.LoadBeforeTime(uc.network, entity, timestamp, limit)
1859 case "AFTER":
1860 history, err = store.LoadAfterTime(uc.network, entity, timestamp, limit)
1861 default:
1862 // TODO: support LATEST, BETWEEN
1863 return ircError{&irc.Message{
1864 Command: "FAIL",
1865 Params: []string{"CHATHISTORY", "UNKNOWN_COMMAND", subcommand, "Unknown command"},
1866 }}
1867 }
1868 if err != nil {
1869 dc.logger.Printf("failed parsing log messages for chathistory: %v", err)
1870 return newChatHistoryError(subcommand, target)
1871 }
1872
1873 batchRef := "history"
1874 dc.SendMessage(&irc.Message{
1875 Prefix: dc.srv.prefix(),
1876 Command: "BATCH",
1877 Params: []string{"+" + batchRef, "chathistory", target},
1878 })
1879
1880 for _, msg := range history {
1881 msg.Tags["batch"] = irc.TagValue(batchRef)
1882 dc.SendMessage(dc.marshalMessage(msg, uc.network))
1883 }
1884
1885 dc.SendMessage(&irc.Message{
1886 Prefix: dc.srv.prefix(),
1887 Command: "BATCH",
1888 Params: []string{"-" + batchRef},
1889 })
1890 default:
1891 dc.logger.Printf("unhandled message: %v", msg)
1892 return newUnknownCommandError(msg.Command)
1893 }
1894 return nil
1895}
1896
1897func (dc *downstreamConn) handleNickServPRIVMSG(uc *upstreamConn, text string) {
1898 username, password, ok := parseNickServCredentials(text, uc.nick)
1899 if !ok {
1900 return
1901 }
1902
1903 // User may have e.g. EXTERNAL mechanism configured. We do not want to
1904 // automatically erase the key pair or any other credentials.
1905 if uc.network.SASL.Mechanism != "" && uc.network.SASL.Mechanism != "PLAIN" {
1906 return
1907 }
1908
1909 dc.logger.Printf("auto-saving NickServ credentials with username %q", username)
1910 n := uc.network
1911 n.SASL.Mechanism = "PLAIN"
1912 n.SASL.Plain.Username = username
1913 n.SASL.Plain.Password = password
1914 if err := dc.srv.db.StoreNetwork(dc.user.ID, &n.Network); err != nil {
1915 dc.logger.Printf("failed to save NickServ credentials: %v", err)
1916 }
1917}
1918
1919func parseNickServCredentials(text, nick string) (username, password string, ok bool) {
1920 fields := strings.Fields(text)
1921 if len(fields) < 2 {
1922 return "", "", false
1923 }
1924 cmd := strings.ToUpper(fields[0])
1925 params := fields[1:]
1926 switch cmd {
1927 case "REGISTER":
1928 username = nick
1929 password = params[0]
1930 case "IDENTIFY":
1931 if len(params) == 1 {
1932 username = nick
1933 password = params[0]
1934 } else {
1935 username = params[0]
1936 password = params[1]
1937 }
1938 case "SET":
1939 if len(params) == 2 && strings.EqualFold(params[0], "PASSWORD") {
1940 username = nick
1941 password = params[1]
1942 }
1943 default:
1944 return "", "", false
1945 }
1946 return username, password, true
1947}
Note: See TracBrowser for help on using the repository browser.