source: code/trunk/downstream.go@ 493

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

Use BARE for internal message IDs

This allows to have shorter and more future-proof IDs. This also
guarantees the IDs will only use reasonable ASCII characters (no
spaces), removing the need to encode them for PING/PONG tokens.

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