source: code/trunk/downstream.go@ 532

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

Implement the soju.im/bouncer-networks extension

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