source: code/trunk/downstream.go@ 475

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

Improve ERR_NOSUCHCHANNEL error messages

References: https://todo.sr.ht/~emersion/soju/63

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