source: code/trunk/downstream.go@ 486

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

Make NickServ detection casemapping-aware

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