source: code/trunk/upstream.go@ 532

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

Don't forward label tags

We don't want to have the label tag when calling uc.produce, otherwise
downstream will end up with junk labels.

File size: 45.2 KB
RevLine 
[98]1package soju
[13]2
3import (
[307]4 "crypto"
5 "crypto/sha256"
[13]6 "crypto/tls"
[307]7 "crypto/x509"
[95]8 "encoding/base64"
[155]9 "errors"
[13]10 "fmt"
11 "io"
12 "net"
[19]13 "strconv"
[17]14 "strings"
[19]15 "time"
[13]16
[95]17 "github.com/emersion/go-sasl"
[13]18 "gopkg.in/irc.v3"
19)
20
[282]21// permanentUpstreamCaps is the static list of upstream capabilities always
22// requested when supported.
23var permanentUpstreamCaps = map[string]bool{
24 "away-notify": true,
25 "batch": true,
[419]26 "extended-join": true,
[448]27 "invite-notify": true,
[282]28 "labeled-response": true,
29 "message-tags": true,
[292]30 "multi-prefix": true,
[282]31 "server-time": true,
32}
33
[399]34type registrationError string
35
36func (err registrationError) Error() string {
37 return fmt.Sprintf("registration error: %v", string(err))
38}
39
[19]40type upstreamChannel struct {
[162]41 Name string
42 conn *upstreamConn
43 Topic string
[405]44 TopicWho *irc.Prefix
[162]45 TopicTime time.Time
46 Status channelStatus
47 modes channelModes
48 creationTime string
[478]49 Members membershipsCasemapMap
[162]50 complete bool
[435]51 detachTimer *time.Timer
[19]52}
53
[435]54func (uc *upstreamChannel) updateAutoDetach(dur time.Duration) {
55 if uc.detachTimer != nil {
56 uc.detachTimer.Stop()
57 uc.detachTimer = nil
58 }
59
60 if dur == 0 {
61 return
62 }
63
64 uc.detachTimer = time.AfterFunc(dur, func() {
65 uc.conn.network.user.events <- eventChannelDetach{
66 uc: uc.conn,
67 name: uc.Name,
68 }
69 })
70}
71
[13]72type upstreamConn struct {
[210]73 conn
[16]74
[210]75 network *network
76 user *user
77
[16]78 serverName string
79 availableUserModes string
[139]80 availableChannelModes map[byte]channelModeType
81 availableChannelTypes string
82 availableMemberships []membership
[460]83 isupport map[string]*string
[19]84
[277]85 registered bool
86 nick string
[478]87 nickCM string
[277]88 username string
89 realname string
90 modes userModes
[478]91 channels upstreamChannelCasemapMap
[277]92 supportedCaps map[string]string
[278]93 caps map[string]bool
[277]94 batches map[string]batch
95 away bool
[278]96 nextLabelID uint64
[95]97
98 saslClient sasl.Client
99 saslStarted bool
[177]100
[478]101 casemapIsSet bool
102
[177]103 // set of LIST commands in progress, per downstream
104 pendingLISTDownstreamSet map[uint64]struct{}
[13]105}
106
[77]107func connectToUpstream(network *network) (*upstreamConn, error) {
[502]108 logger := &prefixLogger{network.user.logger, fmt.Sprintf("upstream %q: ", network.GetName())}
[33]109
[352]110 dialer := net.Dialer{Timeout: connectTimeout}
[269]111
[457]112 u, err := network.URL()
[352]113 if err != nil {
[457]114 return nil, err
[352]115 }
[206]116
[269]117 var netConn net.Conn
[352]118 switch u.Scheme {
[269]119 case "ircs":
[352]120 addr := u.Host
[381]121 host, _, err := net.SplitHostPort(u.Host)
122 if err != nil {
123 host = u.Host
124 addr = u.Host + ":6697"
[269]125 }
126
127 logger.Printf("connecting to TLS server at address %q", addr)
[307]128
[455]129 tlsConfig := &tls.Config{ServerName: host, NextProtos: []string{"irc"}}
[307]130 if network.SASL.Mechanism == "EXTERNAL" {
131 if network.SASL.External.CertBlob == nil {
132 return nil, fmt.Errorf("missing certificate for authentication")
133 }
134 if network.SASL.External.PrivKeyBlob == nil {
135 return nil, fmt.Errorf("missing private key for authentication")
136 }
137 key, err := x509.ParsePKCS8PrivateKey(network.SASL.External.PrivKeyBlob)
138 if err != nil {
139 return nil, fmt.Errorf("failed to parse private key: %v", err)
140 }
[381]141 tlsConfig.Certificates = []tls.Certificate{
142 {
143 Certificate: [][]byte{network.SASL.External.CertBlob},
144 PrivateKey: key.(crypto.PrivateKey),
[307]145 },
146 }
147 logger.Printf("using TLS client certificate %x", sha256.Sum256(network.SASL.External.CertBlob))
148 }
149
[381]150 netConn, err = dialer.Dial("tcp", addr)
[352]151 if err != nil {
152 return nil, fmt.Errorf("failed to dial %q: %v", addr, err)
153 }
[381]154
155 // Don't do the TLS handshake immediately, because we need to register
156 // the new connection with identd ASAP. See:
157 // https://todo.sr.ht/~emersion/soju/69#event-41859
158 netConn = tls.Client(netConn, tlsConfig)
[270]159 case "irc+insecure":
[352]160 addr := u.Host
[351]161 if _, _, err := net.SplitHostPort(addr); err != nil {
[270]162 addr = addr + ":6667"
163 }
164
165 logger.Printf("connecting to plain-text server at address %q", addr)
166 netConn, err = dialer.Dial("tcp", addr)
[352]167 if err != nil {
168 return nil, fmt.Errorf("failed to dial %q: %v", addr, err)
169 }
[369]170 case "irc+unix", "unix":
[353]171 logger.Printf("connecting to Unix socket at path %q", u.Path)
172 netConn, err = dialer.Dial("unix", u.Path)
173 if err != nil {
174 return nil, fmt.Errorf("failed to connect to Unix socket %q: %v", u.Path, err)
175 }
[269]176 default:
[352]177 return nil, fmt.Errorf("failed to dial %q: unknown scheme: %v", network.Addr, u.Scheme)
[269]178 }
[33]179
[398]180 options := connOptions{
[402]181 Logger: logger,
[398]182 RateLimitDelay: upstreamMessageDelay,
183 RateLimitBurst: upstreamMessageBurst,
184 }
185
[55]186 uc := &upstreamConn{
[398]187 conn: *newConn(network.user.srv, newNetIRCConn(netConn), &options),
[177]188 network: network,
189 user: network.user,
[478]190 channels: upstreamChannelCasemapMap{newCasemapMap(0)},
[277]191 supportedCaps: make(map[string]string),
[278]192 caps: make(map[string]bool),
[177]193 batches: make(map[string]batch),
194 availableChannelTypes: stdChannelTypes,
195 availableChannelModes: stdChannelModes,
196 availableMemberships: stdMemberships,
[460]197 isupport: make(map[string]*string),
[177]198 pendingLISTDownstreamSet: make(map[uint64]struct{}),
[33]199 }
[55]200 return uc, nil
[33]201}
202
[73]203func (uc *upstreamConn) forEachDownstream(f func(*downstreamConn)) {
[218]204 uc.network.forEachDownstream(f)
[73]205}
206
[161]207func (uc *upstreamConn) forEachDownstreamByID(id uint64, f func(*downstreamConn)) {
[155]208 uc.forEachDownstream(func(dc *downstreamConn) {
209 if id != 0 && id != dc.id {
210 return
211 }
212 f(dc)
213 })
214}
215
[55]216func (uc *upstreamConn) getChannel(name string) (*upstreamChannel, error) {
[478]217 ch := uc.channels.Value(name)
218 if ch == nil {
[19]219 return nil, fmt.Errorf("unknown channel %q", name)
220 }
221 return ch, nil
222}
223
[129]224func (uc *upstreamConn) isChannel(entity string) bool {
[454]225 return strings.ContainsRune(uc.availableChannelTypes, rune(entity[0]))
[129]226}
227
[478]228func (uc *upstreamConn) isOurNick(nick string) bool {
229 return uc.nickCM == uc.network.casemap(nick)
230}
231
[181]232func (uc *upstreamConn) getPendingLIST() *pendingLIST {
[177]233 for _, pl := range uc.user.pendingLISTs {
234 if _, ok := pl.pendingCommands[uc.network.ID]; !ok {
235 continue
236 }
237 return &pl
238 }
239 return nil
240}
241
[181]242func (uc *upstreamConn) endPendingLISTs(all bool) (found bool) {
[177]243 found = false
244 for i := 0; i < len(uc.user.pendingLISTs); i++ {
245 pl := uc.user.pendingLISTs[i]
246 if _, ok := pl.pendingCommands[uc.network.ID]; !ok {
247 continue
248 }
249 delete(pl.pendingCommands, uc.network.ID)
250 if len(pl.pendingCommands) == 0 {
251 uc.user.pendingLISTs = append(uc.user.pendingLISTs[:i], uc.user.pendingLISTs[i+1:]...)
252 i--
253 uc.forEachDownstreamByID(pl.downstreamID, func(dc *downstreamConn) {
254 dc.SendMessage(&irc.Message{
255 Prefix: dc.srv.prefix(),
256 Command: irc.RPL_LISTEND,
257 Params: []string{dc.nick, "End of /LIST"},
258 })
259 })
260 }
261 found = true
262 if !all {
263 delete(uc.pendingLISTDownstreamSet, pl.downstreamID)
264 uc.user.forEachUpstream(func(uc *upstreamConn) {
[181]265 uc.trySendLIST(pl.downstreamID)
[177]266 })
267 return
268 }
269 }
270 return
271}
272
[181]273func (uc *upstreamConn) trySendLIST(downstreamID uint64) {
[177]274 if _, ok := uc.pendingLISTDownstreamSet[downstreamID]; ok {
275 // a LIST command is already pending
276 // we will try again when that command is completed
277 return
278 }
279
280 for _, pl := range uc.user.pendingLISTs {
281 if pl.downstreamID != downstreamID {
282 continue
283 }
284 // this is the first pending LIST command list of the downstream
285 listCommand, ok := pl.pendingCommands[uc.network.ID]
286 if !ok {
287 // there is no command for this upstream in these LIST commands
288 // do not send anything
289 continue
290 }
291 // there is a command for this upstream in these LIST commands
292 // send it now
293
294 uc.SendMessageLabeled(downstreamID, listCommand)
295
296 uc.pendingLISTDownstreamSet[downstreamID] = struct{}{}
297 return
298 }
299}
300
[292]301func (uc *upstreamConn) parseMembershipPrefix(s string) (ms *memberships, nick string) {
302 memberships := make(memberships, 0, 4)
303 i := 0
[139]304 for _, m := range uc.availableMemberships {
[292]305 if i >= len(s) {
306 break
[139]307 }
[292]308 if s[i] == m.Prefix {
309 memberships = append(memberships, m)
310 i++
311 }
[139]312 }
[292]313 return &memberships, s[i:]
[139]314}
315
[55]316func (uc *upstreamConn) handleMessage(msg *irc.Message) error {
[155]317 var label string
318 if l, ok := msg.GetTag("label"); ok {
319 label = l
[526]320 delete(msg.Tags, "label")
[155]321 }
322
[153]323 var msgBatch *batch
324 if batchName, ok := msg.GetTag("batch"); ok {
325 b, ok := uc.batches[batchName]
326 if !ok {
327 return fmt.Errorf("unexpected batch reference: batch was not defined: %q", batchName)
328 }
329 msgBatch = &b
[155]330 if label == "" {
331 label = msgBatch.Label
332 }
[443]333 delete(msg.Tags, "batch")
[153]334 }
335
[161]336 var downstreamID uint64 = 0
[155]337 if label != "" {
338 var labelOffset uint64
[161]339 n, err := fmt.Sscanf(label, "sd-%d-%d", &downstreamID, &labelOffset)
[155]340 if err == nil && n < 2 {
341 err = errors.New("not enough arguments")
342 }
343 if err != nil {
344 return fmt.Errorf("unexpected message label: invalid downstream reference for label %q: %v", label, err)
345 }
346 }
347
[216]348 if _, ok := msg.Tags["time"]; !ok {
[240]349 msg.Tags["time"] = irc.TagValue(time.Now().UTC().Format(serverTimeLayout))
[216]350 }
351
[13]352 switch msg.Command {
353 case "PING":
[60]354 uc.SendMessage(&irc.Message{
[13]355 Command: "PONG",
[68]356 Params: msg.Params,
[60]357 })
[33]358 return nil
[303]359 case "NOTICE", "PRIVMSG", "TAGMSG":
[273]360 if msg.Prefix == nil {
361 return fmt.Errorf("expected a prefix")
362 }
363
[286]364 var entity, text string
[303]365 if msg.Command != "TAGMSG" {
366 if err := parseMessageParams(msg, &entity, &text); err != nil {
367 return err
368 }
369 } else {
370 if err := parseMessageParams(msg, &entity); err != nil {
371 return err
372 }
[286]373 }
374
375 if msg.Prefix.Name == serviceNick {
376 uc.logger.Printf("skipping %v from soju's service: %v", msg.Command, msg)
377 break
378 }
379 if entity == serviceNick {
380 uc.logger.Printf("skipping %v to soju's service: %v", msg.Command, msg)
381 break
382 }
383
[171]384 if msg.Prefix.User == "" && msg.Prefix.Host == "" { // server message
[239]385 uc.produce("", msg, nil)
[303]386 } else { // regular user message
[217]387 target := entity
[478]388 if uc.isOurNick(target) {
[178]389 target = msg.Prefix.Name
390 }
[287]391
[478]392 ch := uc.network.channels.Value(target)
[505]393 if ch != nil && msg.Command != "TAGMSG" {
[435]394 if ch.Detached {
[499]395 uc.handleDetachedMessage(ch, msg)
[435]396 }
397
[499]398 highlight := uc.network.isHighlight(msg)
[435]399 if ch.DetachOn == FilterMessage || ch.DetachOn == FilterDefault || (ch.DetachOn == FilterHighlight && highlight) {
400 uc.updateChannelAutoDetach(target)
401 }
[287]402 }
[435]403
404 uc.produce(target, msg, nil)
[171]405 }
[92]406 case "CAP":
[95]407 var subCmd string
408 if err := parseMessageParams(msg, nil, &subCmd); err != nil {
409 return err
[92]410 }
[95]411 subCmd = strings.ToUpper(subCmd)
412 subParams := msg.Params[2:]
413 switch subCmd {
414 case "LS":
415 if len(subParams) < 1 {
416 return newNeedMoreParamsError(msg.Command)
417 }
[281]418 caps := subParams[len(subParams)-1]
[95]419 more := len(subParams) >= 2 && msg.Params[len(subParams)-2] == "*"
[92]420
[281]421 uc.handleSupportedCaps(caps)
[92]422
[95]423 if more {
424 break // wait to receive all capabilities
425 }
426
[281]427 uc.requestCaps()
[152]428
[95]429 if uc.requestSASL() {
430 break // we'll send CAP END after authentication is completed
431 }
432
[92]433 uc.SendMessage(&irc.Message{
434 Command: "CAP",
435 Params: []string{"END"},
436 })
[95]437 case "ACK", "NAK":
438 if len(subParams) < 1 {
439 return newNeedMoreParamsError(msg.Command)
440 }
441 caps := strings.Fields(subParams[0])
442
443 for _, name := range caps {
444 if err := uc.handleCapAck(strings.ToLower(name), subCmd == "ACK"); err != nil {
445 return err
446 }
447 }
448
[281]449 if uc.registered {
450 uc.forEachDownstream(func(dc *downstreamConn) {
451 dc.updateSupportedCaps()
452 })
453 }
454 case "NEW":
455 if len(subParams) < 1 {
456 return newNeedMoreParamsError(msg.Command)
457 }
458 uc.handleSupportedCaps(subParams[0])
459 uc.requestCaps()
460 case "DEL":
461 if len(subParams) < 1 {
462 return newNeedMoreParamsError(msg.Command)
463 }
464 caps := strings.Fields(subParams[0])
465
466 for _, c := range caps {
467 delete(uc.supportedCaps, c)
468 delete(uc.caps, c)
469 }
470
471 if uc.registered {
472 uc.forEachDownstream(func(dc *downstreamConn) {
473 dc.updateSupportedCaps()
474 })
475 }
[95]476 default:
477 uc.logger.Printf("unhandled message: %v", msg)
[92]478 }
[95]479 case "AUTHENTICATE":
480 if uc.saslClient == nil {
481 return fmt.Errorf("received unexpected AUTHENTICATE message")
482 }
483
484 // TODO: if a challenge is 400 bytes long, buffer it
485 var challengeStr string
486 if err := parseMessageParams(msg, &challengeStr); err != nil {
487 uc.SendMessage(&irc.Message{
488 Command: "AUTHENTICATE",
489 Params: []string{"*"},
490 })
491 return err
492 }
493
494 var challenge []byte
495 if challengeStr != "+" {
496 var err error
497 challenge, err = base64.StdEncoding.DecodeString(challengeStr)
498 if err != nil {
499 uc.SendMessage(&irc.Message{
500 Command: "AUTHENTICATE",
501 Params: []string{"*"},
502 })
503 return err
504 }
505 }
506
507 var resp []byte
508 var err error
509 if !uc.saslStarted {
510 _, resp, err = uc.saslClient.Start()
511 uc.saslStarted = true
512 } else {
513 resp, err = uc.saslClient.Next(challenge)
514 }
515 if err != nil {
516 uc.SendMessage(&irc.Message{
517 Command: "AUTHENTICATE",
518 Params: []string{"*"},
519 })
520 return err
521 }
522
523 // TODO: send response in multiple chunks if >= 400 bytes
524 var respStr = "+"
[318]525 if len(resp) != 0 {
[95]526 respStr = base64.StdEncoding.EncodeToString(resp)
527 }
528
529 uc.SendMessage(&irc.Message{
530 Command: "AUTHENTICATE",
531 Params: []string{respStr},
532 })
[125]533 case irc.RPL_LOGGEDIN:
[95]534 var account string
535 if err := parseMessageParams(msg, nil, nil, &account); err != nil {
536 return err
537 }
538 uc.logger.Printf("logged in with account %q", account)
[125]539 case irc.RPL_LOGGEDOUT:
[95]540 uc.logger.Printf("logged out")
[125]541 case irc.ERR_NICKLOCKED, irc.RPL_SASLSUCCESS, irc.ERR_SASLFAIL, irc.ERR_SASLTOOLONG, irc.ERR_SASLABORTED:
[95]542 var info string
543 if err := parseMessageParams(msg, nil, &info); err != nil {
544 return err
545 }
546 switch msg.Command {
[125]547 case irc.ERR_NICKLOCKED:
[95]548 uc.logger.Printf("invalid nick used with SASL authentication: %v", info)
[125]549 case irc.ERR_SASLFAIL:
[95]550 uc.logger.Printf("SASL authentication failed: %v", info)
[125]551 case irc.ERR_SASLTOOLONG:
[95]552 uc.logger.Printf("SASL message too long: %v", info)
553 }
554
555 uc.saslClient = nil
556 uc.saslStarted = false
557
558 uc.SendMessage(&irc.Message{
559 Command: "CAP",
560 Params: []string{"END"},
561 })
[14]562 case irc.RPL_WELCOME:
[55]563 uc.registered = true
564 uc.logger.Printf("connection registered")
[19]565
[478]566 if uc.network.channels.Len() > 0 {
[350]567 var channels, keys []string
[478]568 for _, entry := range uc.network.channels.innerMap {
569 ch := entry.value.(*Channel)
[350]570 channels = append(channels, ch.Name)
[310]571 keys = append(keys, ch.Key)
572 }
[350]573
574 for _, msg := range join(channels, keys) {
575 uc.SendMessage(msg)
576 }
[19]577 }
[16]578 case irc.RPL_MYINFO:
[139]579 if err := parseMessageParams(msg, nil, &uc.serverName, nil, &uc.availableUserModes, nil); err != nil {
[43]580 return err
[16]581 }
[139]582 case irc.RPL_ISUPPORT:
583 if err := parseMessageParams(msg, nil, nil); err != nil {
584 return err
[16]585 }
[463]586
587 var downstreamIsupport []string
[139]588 for _, token := range msg.Params[1 : len(msg.Params)-1] {
589 parameter := token
[460]590 var negate, hasValue bool
591 var value string
[139]592 if strings.HasPrefix(token, "-") {
593 negate = true
594 token = token[1:]
[459]595 } else if i := strings.IndexByte(token, '='); i >= 0 {
596 parameter = token[:i]
597 value = token[i+1:]
[460]598 hasValue = true
[139]599 }
[460]600
601 if hasValue {
602 uc.isupport[parameter] = &value
603 } else if !negate {
604 uc.isupport[parameter] = nil
605 } else {
606 delete(uc.isupport, parameter)
607 }
608
[462]609 var err error
610 switch parameter {
[478]611 case "CASEMAPPING":
612 casemap, ok := parseCasemappingToken(value)
613 if !ok {
614 casemap = casemapRFC1459
615 }
616 uc.network.updateCasemapping(casemap)
617 uc.nickCM = uc.network.casemap(uc.nick)
618 uc.casemapIsSet = true
[462]619 case "CHANMODES":
620 if !negate {
621 err = uc.handleChanModes(value)
622 } else {
623 uc.availableChannelModes = stdChannelModes
624 }
625 case "CHANTYPES":
626 if !negate {
[139]627 uc.availableChannelTypes = value
[462]628 } else {
629 uc.availableChannelTypes = stdChannelTypes
[139]630 }
[462]631 case "PREFIX":
632 if !negate {
633 err = uc.handleMemberships(value)
634 } else {
635 uc.availableMemberships = stdMemberships
636 }
[139]637 }
[462]638 if err != nil {
639 return err
640 }
[463]641
642 if passthroughIsupport[parameter] {
643 downstreamIsupport = append(downstreamIsupport, token)
644 }
[139]645 }
[463]646
647 uc.forEachDownstream(func(dc *downstreamConn) {
648 if dc.network == nil {
649 return
650 }
651 msgs := generateIsupport(dc.srv.prefix(), dc.nick, downstreamIsupport)
652 for _, msg := range msgs {
653 dc.SendMessage(msg)
654 }
655 })
[478]656 case irc.ERR_NOMOTD, irc.RPL_ENDOFMOTD:
657 if !uc.casemapIsSet {
658 // upstream did not send any CASEMAPPING token, thus
659 // we assume it implements the old RFCs with rfc1459.
660 uc.casemapIsSet = true
661 uc.network.updateCasemapping(casemapRFC1459)
662 uc.nickCM = uc.network.casemap(uc.nick)
663 }
[153]664 case "BATCH":
665 var tag string
666 if err := parseMessageParams(msg, &tag); err != nil {
667 return err
668 }
669
670 if strings.HasPrefix(tag, "+") {
671 tag = tag[1:]
672 if _, ok := uc.batches[tag]; ok {
673 return fmt.Errorf("unexpected BATCH reference tag: batch was already defined: %q", tag)
674 }
675 var batchType string
676 if err := parseMessageParams(msg, nil, &batchType); err != nil {
677 return err
678 }
[155]679 label := label
680 if label == "" && msgBatch != nil {
681 label = msgBatch.Label
682 }
[153]683 uc.batches[tag] = batch{
684 Type: batchType,
685 Params: msg.Params[2:],
686 Outer: msgBatch,
[155]687 Label: label,
[153]688 }
689 } else if strings.HasPrefix(tag, "-") {
690 tag = tag[1:]
691 if _, ok := uc.batches[tag]; !ok {
692 return fmt.Errorf("unknown BATCH reference tag: %q", tag)
693 }
694 delete(uc.batches, tag)
695 } else {
696 return fmt.Errorf("unexpected BATCH reference tag: missing +/- prefix: %q", tag)
697 }
[42]698 case "NICK":
[83]699 if msg.Prefix == nil {
700 return fmt.Errorf("expected a prefix")
701 }
702
[43]703 var newNick string
704 if err := parseMessageParams(msg, &newNick); err != nil {
705 return err
[42]706 }
707
[244]708 me := false
[478]709 if uc.isOurNick(msg.Prefix.Name) {
[55]710 uc.logger.Printf("changed nick from %q to %q", uc.nick, newNick)
[244]711 me = true
[55]712 uc.nick = newNick
[478]713 uc.nickCM = uc.network.casemap(uc.nick)
[42]714 }
715
[478]716 for _, entry := range uc.channels.innerMap {
717 ch := entry.value.(*upstreamChannel)
718 memberships := ch.Members.Value(msg.Prefix.Name)
719 if memberships != nil {
720 ch.Members.Delete(msg.Prefix.Name)
721 ch.Members.SetValue(newNick, memberships)
[215]722 uc.appendLog(ch.Name, msg)
[42]723 }
724 }
[82]725
[244]726 if !me {
[82]727 uc.forEachDownstream(func(dc *downstreamConn) {
[261]728 dc.SendMessage(dc.marshalMessage(msg, uc.network))
[82]729 })
[296]730 } else {
731 uc.forEachDownstream(func(dc *downstreamConn) {
732 dc.updateNick()
733 })
[82]734 }
[69]735 case "JOIN":
736 if msg.Prefix == nil {
737 return fmt.Errorf("expected a prefix")
738 }
[42]739
[43]740 var channels string
741 if err := parseMessageParams(msg, &channels); err != nil {
742 return err
[19]743 }
[34]744
[43]745 for _, ch := range strings.Split(channels, ",") {
[478]746 if uc.isOurNick(msg.Prefix.Name) {
[55]747 uc.logger.Printf("joined channel %q", ch)
[478]748 members := membershipsCasemapMap{newCasemapMap(0)}
749 members.casemap = uc.network.casemap
750 uc.channels.SetValue(ch, &upstreamChannel{
[34]751 Name: ch,
[55]752 conn: uc,
[478]753 Members: members,
754 })
[435]755 uc.updateChannelAutoDetach(ch)
[139]756
757 uc.SendMessage(&irc.Message{
758 Command: "MODE",
759 Params: []string{ch},
760 })
[34]761 } else {
[55]762 ch, err := uc.getChannel(ch)
[34]763 if err != nil {
764 return err
765 }
[478]766 ch.Members.SetValue(msg.Prefix.Name, &memberships{})
[19]767 }
[69]768
[245]769 chMsg := msg.Copy()
770 chMsg.Params[0] = ch
771 uc.produce(ch, chMsg, nil)
[19]772 }
[69]773 case "PART":
774 if msg.Prefix == nil {
775 return fmt.Errorf("expected a prefix")
776 }
[34]777
[43]778 var channels string
779 if err := parseMessageParams(msg, &channels); err != nil {
780 return err
[34]781 }
782
[43]783 for _, ch := range strings.Split(channels, ",") {
[478]784 if uc.isOurNick(msg.Prefix.Name) {
[55]785 uc.logger.Printf("parted channel %q", ch)
[478]786 uch := uc.channels.Value(ch)
787 if uch != nil {
788 uc.channels.Delete(ch)
[435]789 uch.updateAutoDetach(0)
790 }
[34]791 } else {
[55]792 ch, err := uc.getChannel(ch)
[34]793 if err != nil {
794 return err
795 }
[478]796 ch.Members.Delete(msg.Prefix.Name)
[34]797 }
[69]798
[245]799 chMsg := msg.Copy()
800 chMsg.Params[0] = ch
801 uc.produce(ch, chMsg, nil)
[34]802 }
[159]803 case "KICK":
804 if msg.Prefix == nil {
805 return fmt.Errorf("expected a prefix")
806 }
807
808 var channel, user string
809 if err := parseMessageParams(msg, &channel, &user); err != nil {
810 return err
811 }
812
[478]813 if uc.isOurNick(user) {
[159]814 uc.logger.Printf("kicked from channel %q by %s", channel, msg.Prefix.Name)
[478]815 uc.channels.Delete(channel)
[159]816 } else {
817 ch, err := uc.getChannel(channel)
818 if err != nil {
819 return err
820 }
[478]821 ch.Members.Delete(user)
[159]822 }
823
[245]824 uc.produce(channel, msg, nil)
[83]825 case "QUIT":
826 if msg.Prefix == nil {
827 return fmt.Errorf("expected a prefix")
828 }
829
[478]830 if uc.isOurNick(msg.Prefix.Name) {
[83]831 uc.logger.Printf("quit")
832 }
833
[478]834 for _, entry := range uc.channels.innerMap {
835 ch := entry.value.(*upstreamChannel)
836 if ch.Members.Has(msg.Prefix.Name) {
837 ch.Members.Delete(msg.Prefix.Name)
[178]838
[215]839 uc.appendLog(ch.Name, msg)
[178]840 }
[83]841 }
842
843 if msg.Prefix.Name != uc.nick {
844 uc.forEachDownstream(func(dc *downstreamConn) {
[261]845 dc.SendMessage(dc.marshalMessage(msg, uc.network))
[83]846 })
847 }
[19]848 case irc.RPL_TOPIC, irc.RPL_NOTOPIC:
[43]849 var name, topic string
850 if err := parseMessageParams(msg, nil, &name, &topic); err != nil {
851 return err
[19]852 }
[55]853 ch, err := uc.getChannel(name)
[19]854 if err != nil {
855 return err
856 }
857 if msg.Command == irc.RPL_TOPIC {
[43]858 ch.Topic = topic
[19]859 } else {
860 ch.Topic = ""
861 }
862 case "TOPIC":
[405]863 if msg.Prefix == nil {
864 return fmt.Errorf("expected a prefix")
865 }
866
[43]867 var name string
[74]868 if err := parseMessageParams(msg, &name); err != nil {
[43]869 return err
[19]870 }
[55]871 ch, err := uc.getChannel(name)
[19]872 if err != nil {
873 return err
874 }
875 if len(msg.Params) > 1 {
876 ch.Topic = msg.Params[1]
[405]877 ch.TopicWho = msg.Prefix.Copy()
878 ch.TopicTime = time.Now() // TODO use msg.Tags["time"]
[19]879 } else {
880 ch.Topic = ""
881 }
[245]882 uc.produce(ch.Name, msg, nil)
[139]883 case "MODE":
884 var name, modeStr string
885 if err := parseMessageParams(msg, &name, &modeStr); err != nil {
886 return err
887 }
888
889 if !uc.isChannel(name) { // user mode change
890 if name != uc.nick {
891 return fmt.Errorf("received MODE message for unknown nick %q", name)
892 }
893 return uc.modes.Apply(modeStr)
894 // TODO: notify downstreams about user mode change?
895 } else { // channel mode change
896 ch, err := uc.getChannel(name)
897 if err != nil {
898 return err
899 }
900
[293]901 needMarshaling, err := applyChannelModes(ch, modeStr, msg.Params[2:])
902 if err != nil {
903 return err
[139]904 }
905
[293]906 uc.appendLog(ch.Name, msg)
907
[478]908 c := uc.network.channels.Value(name)
909 if c == nil || !c.Detached {
[338]910 uc.forEachDownstream(func(dc *downstreamConn) {
911 params := make([]string, len(msg.Params))
912 params[0] = dc.marshalEntity(uc.network, name)
913 params[1] = modeStr
914
915 copy(params[2:], msg.Params[2:])
916 for i, modeParam := range params[2:] {
917 if _, ok := needMarshaling[i]; ok {
918 params[2+i] = dc.marshalEntity(uc.network, modeParam)
919 }
[293]920 }
921
[338]922 dc.SendMessage(&irc.Message{
923 Prefix: dc.marshalUserPrefix(uc.network, msg.Prefix),
924 Command: "MODE",
925 Params: params,
926 })
[293]927 })
[338]928 }
[139]929 }
930 case irc.RPL_UMODEIS:
931 if err := parseMessageParams(msg, nil); err != nil {
932 return err
933 }
934 modeStr := ""
935 if len(msg.Params) > 1 {
936 modeStr = msg.Params[1]
937 }
938
939 uc.modes = ""
940 if err := uc.modes.Apply(modeStr); err != nil {
941 return err
942 }
943 // TODO: send RPL_UMODEIS to downstream connections when applicable
944 case irc.RPL_CHANNELMODEIS:
945 var channel string
946 if err := parseMessageParams(msg, nil, &channel); err != nil {
947 return err
948 }
949 modeStr := ""
950 if len(msg.Params) > 2 {
951 modeStr = msg.Params[2]
952 }
953
954 ch, err := uc.getChannel(channel)
955 if err != nil {
956 return err
957 }
958
959 firstMode := ch.modes == nil
960 ch.modes = make(map[byte]string)
[293]961 if _, err := applyChannelModes(ch, modeStr, msg.Params[3:]); err != nil {
[139]962 return err
963 }
964 if firstMode {
[478]965 c := uc.network.channels.Value(channel)
966 if c == nil || !c.Detached {
[338]967 modeStr, modeParams := ch.modes.Format()
[139]968
[338]969 uc.forEachDownstream(func(dc *downstreamConn) {
970 params := []string{dc.nick, dc.marshalEntity(uc.network, channel), modeStr}
971 params = append(params, modeParams...)
[139]972
[338]973 dc.SendMessage(&irc.Message{
974 Prefix: dc.srv.prefix(),
975 Command: irc.RPL_CHANNELMODEIS,
976 Params: params,
977 })
[139]978 })
[338]979 }
[139]980 }
[162]981 case rpl_creationtime:
982 var channel, creationTime string
983 if err := parseMessageParams(msg, nil, &channel, &creationTime); err != nil {
984 return err
985 }
986
987 ch, err := uc.getChannel(channel)
988 if err != nil {
989 return err
990 }
991
992 firstCreationTime := ch.creationTime == ""
993 ch.creationTime = creationTime
994 if firstCreationTime {
995 uc.forEachDownstream(func(dc *downstreamConn) {
996 dc.SendMessage(&irc.Message{
997 Prefix: dc.srv.prefix(),
998 Command: rpl_creationtime,
[403]999 Params: []string{dc.nick, dc.marshalEntity(uc.network, ch.Name), creationTime},
[162]1000 })
1001 })
1002 }
[19]1003 case rpl_topicwhotime:
[43]1004 var name, who, timeStr string
1005 if err := parseMessageParams(msg, nil, &name, &who, &timeStr); err != nil {
1006 return err
[19]1007 }
[55]1008 ch, err := uc.getChannel(name)
[19]1009 if err != nil {
1010 return err
1011 }
[405]1012 firstTopicWhoTime := ch.TopicWho == nil
1013 ch.TopicWho = irc.ParsePrefix(who)
[43]1014 sec, err := strconv.ParseInt(timeStr, 10, 64)
[19]1015 if err != nil {
1016 return fmt.Errorf("failed to parse topic time: %v", err)
1017 }
1018 ch.TopicTime = time.Unix(sec, 0)
[405]1019 if firstTopicWhoTime {
1020 uc.forEachDownstream(func(dc *downstreamConn) {
1021 topicWho := dc.marshalUserPrefix(uc.network, ch.TopicWho)
1022 dc.SendMessage(&irc.Message{
1023 Prefix: dc.srv.prefix(),
1024 Command: rpl_topicwhotime,
1025 Params: []string{
1026 dc.nick,
1027 dc.marshalEntity(uc.network, ch.Name),
1028 topicWho.String(),
1029 timeStr,
1030 },
1031 })
1032 })
1033 }
[177]1034 case irc.RPL_LIST:
1035 var channel, clients, topic string
1036 if err := parseMessageParams(msg, nil, &channel, &clients, &topic); err != nil {
1037 return err
1038 }
1039
[181]1040 pl := uc.getPendingLIST()
[177]1041 if pl == nil {
1042 return fmt.Errorf("unexpected RPL_LIST: no matching pending LIST")
1043 }
1044
1045 uc.forEachDownstreamByID(pl.downstreamID, func(dc *downstreamConn) {
1046 dc.SendMessage(&irc.Message{
1047 Prefix: dc.srv.prefix(),
1048 Command: irc.RPL_LIST,
[260]1049 Params: []string{dc.nick, dc.marshalEntity(uc.network, channel), clients, topic},
[177]1050 })
1051 })
1052 case irc.RPL_LISTEND:
[181]1053 ok := uc.endPendingLISTs(false)
[177]1054 if !ok {
1055 return fmt.Errorf("unexpected RPL_LISTEND: no matching pending LIST")
1056 }
[19]1057 case irc.RPL_NAMREPLY:
[43]1058 var name, statusStr, members string
1059 if err := parseMessageParams(msg, nil, &statusStr, &name, &members); err != nil {
1060 return err
[19]1061 }
[140]1062
[478]1063 ch := uc.channels.Value(name)
1064 if ch == nil {
[140]1065 // NAMES on a channel we have not joined, forward to downstream
[161]1066 uc.forEachDownstreamByID(downstreamID, func(dc *downstreamConn) {
[260]1067 channel := dc.marshalEntity(uc.network, name)
[174]1068 members := splitSpace(members)
[140]1069 for i, member := range members {
[292]1070 memberships, nick := uc.parseMembershipPrefix(member)
1071 members[i] = memberships.Format(dc) + dc.marshalEntity(uc.network, nick)
[140]1072 }
1073 memberStr := strings.Join(members, " ")
1074
1075 dc.SendMessage(&irc.Message{
1076 Prefix: dc.srv.prefix(),
1077 Command: irc.RPL_NAMREPLY,
1078 Params: []string{dc.nick, statusStr, channel, memberStr},
1079 })
1080 })
1081 return nil
[19]1082 }
1083
[43]1084 status, err := parseChannelStatus(statusStr)
[19]1085 if err != nil {
1086 return err
1087 }
1088 ch.Status = status
1089
[174]1090 for _, s := range splitSpace(members) {
[292]1091 memberships, nick := uc.parseMembershipPrefix(s)
[478]1092 ch.Members.SetValue(nick, memberships)
[19]1093 }
1094 case irc.RPL_ENDOFNAMES:
[43]1095 var name string
1096 if err := parseMessageParams(msg, nil, &name); err != nil {
1097 return err
[25]1098 }
[140]1099
[478]1100 ch := uc.channels.Value(name)
1101 if ch == nil {
[140]1102 // NAMES on a channel we have not joined, forward to downstream
[161]1103 uc.forEachDownstreamByID(downstreamID, func(dc *downstreamConn) {
[260]1104 channel := dc.marshalEntity(uc.network, name)
[140]1105
1106 dc.SendMessage(&irc.Message{
1107 Prefix: dc.srv.prefix(),
1108 Command: irc.RPL_ENDOFNAMES,
1109 Params: []string{dc.nick, channel, "End of /NAMES list"},
1110 })
1111 })
1112 return nil
[25]1113 }
1114
[34]1115 if ch.complete {
1116 return fmt.Errorf("received unexpected RPL_ENDOFNAMES")
1117 }
[25]1118 ch.complete = true
[27]1119
[478]1120 c := uc.network.channels.Value(name)
1121 if c == nil || !c.Detached {
[338]1122 uc.forEachDownstream(func(dc *downstreamConn) {
1123 forwardChannel(dc, ch)
1124 })
1125 }
[127]1126 case irc.RPL_WHOREPLY:
1127 var channel, username, host, server, nick, mode, trailing string
1128 if err := parseMessageParams(msg, nil, &channel, &username, &host, &server, &nick, &mode, &trailing); err != nil {
1129 return err
1130 }
1131
1132 parts := strings.SplitN(trailing, " ", 2)
1133 if len(parts) != 2 {
1134 return fmt.Errorf("received malformed RPL_WHOREPLY: wrong trailing parameter: %s", trailing)
1135 }
1136 realname := parts[1]
1137 hops, err := strconv.Atoi(parts[0])
1138 if err != nil {
1139 return fmt.Errorf("received malformed RPL_WHOREPLY: wrong hop count: %s", parts[0])
1140 }
1141 hops++
1142
1143 trailing = strconv.Itoa(hops) + " " + realname
1144
[161]1145 uc.forEachDownstreamByID(downstreamID, func(dc *downstreamConn) {
[127]1146 channel := channel
1147 if channel != "*" {
[260]1148 channel = dc.marshalEntity(uc.network, channel)
[127]1149 }
[260]1150 nick := dc.marshalEntity(uc.network, nick)
[127]1151 dc.SendMessage(&irc.Message{
1152 Prefix: dc.srv.prefix(),
1153 Command: irc.RPL_WHOREPLY,
1154 Params: []string{dc.nick, channel, username, host, server, nick, mode, trailing},
1155 })
1156 })
1157 case irc.RPL_ENDOFWHO:
1158 var name string
1159 if err := parseMessageParams(msg, nil, &name); err != nil {
1160 return err
1161 }
1162
[161]1163 uc.forEachDownstreamByID(downstreamID, func(dc *downstreamConn) {
[127]1164 name := name
1165 if name != "*" {
1166 // TODO: support WHO masks
[260]1167 name = dc.marshalEntity(uc.network, name)
[127]1168 }
1169 dc.SendMessage(&irc.Message{
1170 Prefix: dc.srv.prefix(),
1171 Command: irc.RPL_ENDOFWHO,
[142]1172 Params: []string{dc.nick, name, "End of /WHO list"},
[127]1173 })
1174 })
[128]1175 case irc.RPL_WHOISUSER:
1176 var nick, username, host, realname string
1177 if err := parseMessageParams(msg, nil, &nick, &username, &host, nil, &realname); err != nil {
1178 return err
1179 }
1180
[161]1181 uc.forEachDownstreamByID(downstreamID, func(dc *downstreamConn) {
[260]1182 nick := dc.marshalEntity(uc.network, nick)
[128]1183 dc.SendMessage(&irc.Message{
1184 Prefix: dc.srv.prefix(),
1185 Command: irc.RPL_WHOISUSER,
1186 Params: []string{dc.nick, nick, username, host, "*", realname},
1187 })
1188 })
1189 case irc.RPL_WHOISSERVER:
1190 var nick, server, serverInfo string
1191 if err := parseMessageParams(msg, nil, &nick, &server, &serverInfo); err != nil {
1192 return err
1193 }
1194
[161]1195 uc.forEachDownstreamByID(downstreamID, func(dc *downstreamConn) {
[260]1196 nick := dc.marshalEntity(uc.network, nick)
[128]1197 dc.SendMessage(&irc.Message{
1198 Prefix: dc.srv.prefix(),
1199 Command: irc.RPL_WHOISSERVER,
1200 Params: []string{dc.nick, nick, server, serverInfo},
1201 })
1202 })
1203 case irc.RPL_WHOISOPERATOR:
1204 var nick string
1205 if err := parseMessageParams(msg, nil, &nick); err != nil {
1206 return err
1207 }
1208
[161]1209 uc.forEachDownstreamByID(downstreamID, func(dc *downstreamConn) {
[260]1210 nick := dc.marshalEntity(uc.network, nick)
[128]1211 dc.SendMessage(&irc.Message{
1212 Prefix: dc.srv.prefix(),
1213 Command: irc.RPL_WHOISOPERATOR,
1214 Params: []string{dc.nick, nick, "is an IRC operator"},
1215 })
1216 })
1217 case irc.RPL_WHOISIDLE:
1218 var nick string
1219 if err := parseMessageParams(msg, nil, &nick, nil); err != nil {
1220 return err
1221 }
1222
[161]1223 uc.forEachDownstreamByID(downstreamID, func(dc *downstreamConn) {
[260]1224 nick := dc.marshalEntity(uc.network, nick)
[128]1225 params := []string{dc.nick, nick}
1226 params = append(params, msg.Params[2:]...)
1227 dc.SendMessage(&irc.Message{
1228 Prefix: dc.srv.prefix(),
1229 Command: irc.RPL_WHOISIDLE,
1230 Params: params,
1231 })
1232 })
1233 case irc.RPL_WHOISCHANNELS:
1234 var nick, channelList string
1235 if err := parseMessageParams(msg, nil, &nick, &channelList); err != nil {
1236 return err
1237 }
[174]1238 channels := splitSpace(channelList)
[128]1239
[161]1240 uc.forEachDownstreamByID(downstreamID, func(dc *downstreamConn) {
[260]1241 nick := dc.marshalEntity(uc.network, nick)
[128]1242 channelList := make([]string, len(channels))
1243 for i, channel := range channels {
[139]1244 prefix, channel := uc.parseMembershipPrefix(channel)
[260]1245 channel = dc.marshalEntity(uc.network, channel)
[292]1246 channelList[i] = prefix.Format(dc) + channel
[128]1247 }
1248 channels := strings.Join(channelList, " ")
1249 dc.SendMessage(&irc.Message{
1250 Prefix: dc.srv.prefix(),
1251 Command: irc.RPL_WHOISCHANNELS,
1252 Params: []string{dc.nick, nick, channels},
1253 })
1254 })
1255 case irc.RPL_ENDOFWHOIS:
1256 var nick string
1257 if err := parseMessageParams(msg, nil, &nick); err != nil {
1258 return err
1259 }
1260
[161]1261 uc.forEachDownstreamByID(downstreamID, func(dc *downstreamConn) {
[260]1262 nick := dc.marshalEntity(uc.network, nick)
[128]1263 dc.SendMessage(&irc.Message{
1264 Prefix: dc.srv.prefix(),
1265 Command: irc.RPL_ENDOFWHOIS,
[142]1266 Params: []string{dc.nick, nick, "End of /WHOIS list"},
[128]1267 })
1268 })
[115]1269 case "INVITE":
[273]1270 var nick, channel string
[115]1271 if err := parseMessageParams(msg, &nick, &channel); err != nil {
1272 return err
1273 }
1274
[478]1275 weAreInvited := uc.isOurNick(nick)
[448]1276
[115]1277 uc.forEachDownstream(func(dc *downstreamConn) {
[448]1278 if !weAreInvited && !dc.caps["invite-notify"] {
1279 return
1280 }
[115]1281 dc.SendMessage(&irc.Message{
[260]1282 Prefix: dc.marshalUserPrefix(uc.network, msg.Prefix),
[115]1283 Command: "INVITE",
[260]1284 Params: []string{dc.marshalEntity(uc.network, nick), dc.marshalEntity(uc.network, channel)},
[115]1285 })
1286 })
[163]1287 case irc.RPL_INVITING:
[273]1288 var nick, channel string
[304]1289 if err := parseMessageParams(msg, nil, &nick, &channel); err != nil {
[163]1290 return err
1291 }
1292
1293 uc.forEachDownstreamByID(downstreamID, func(dc *downstreamConn) {
1294 dc.SendMessage(&irc.Message{
1295 Prefix: dc.srv.prefix(),
1296 Command: irc.RPL_INVITING,
[260]1297 Params: []string{dc.nick, dc.marshalEntity(uc.network, nick), dc.marshalEntity(uc.network, channel)},
[163]1298 })
1299 })
[272]1300 case irc.RPL_AWAY:
1301 var nick, reason string
1302 if err := parseMessageParams(msg, nil, &nick, &reason); err != nil {
1303 return err
1304 }
1305
[274]1306 uc.forEachDownstream(func(dc *downstreamConn) {
[272]1307 dc.SendMessage(&irc.Message{
1308 Prefix: dc.srv.prefix(),
1309 Command: irc.RPL_AWAY,
1310 Params: []string{dc.nick, dc.marshalEntity(uc.network, nick), reason},
1311 })
1312 })
[276]1313 case "AWAY":
1314 if msg.Prefix == nil {
1315 return fmt.Errorf("expected a prefix")
1316 }
1317
1318 uc.forEachDownstream(func(dc *downstreamConn) {
1319 if !dc.caps["away-notify"] {
1320 return
1321 }
1322 dc.SendMessage(&irc.Message{
1323 Prefix: dc.marshalUserPrefix(uc.network, msg.Prefix),
1324 Command: "AWAY",
1325 Params: msg.Params,
1326 })
1327 })
[300]1328 case irc.RPL_BANLIST, irc.RPL_INVITELIST, irc.RPL_EXCEPTLIST:
1329 var channel, mask string
1330 if err := parseMessageParams(msg, nil, &channel, &mask); err != nil {
1331 return err
1332 }
1333 var addNick, addTime string
1334 if len(msg.Params) >= 5 {
1335 addNick = msg.Params[3]
1336 addTime = msg.Params[4]
1337 }
1338
1339 uc.forEachDownstreamByID(downstreamID, func(dc *downstreamConn) {
1340 channel := dc.marshalEntity(uc.network, channel)
1341
1342 var params []string
1343 if addNick != "" && addTime != "" {
1344 addNick := dc.marshalEntity(uc.network, addNick)
1345 params = []string{dc.nick, channel, mask, addNick, addTime}
1346 } else {
1347 params = []string{dc.nick, channel, mask}
1348 }
1349
1350 dc.SendMessage(&irc.Message{
1351 Prefix: dc.srv.prefix(),
1352 Command: msg.Command,
1353 Params: params,
1354 })
1355 })
1356 case irc.RPL_ENDOFBANLIST, irc.RPL_ENDOFINVITELIST, irc.RPL_ENDOFEXCEPTLIST:
1357 var channel, trailing string
1358 if err := parseMessageParams(msg, nil, &channel, &trailing); err != nil {
1359 return err
1360 }
1361
1362 uc.forEachDownstreamByID(downstreamID, func(dc *downstreamConn) {
1363 upstreamChannel := dc.marshalEntity(uc.network, channel)
1364 dc.SendMessage(&irc.Message{
1365 Prefix: dc.srv.prefix(),
1366 Command: msg.Command,
1367 Params: []string{dc.nick, upstreamChannel, trailing},
1368 })
1369 })
[302]1370 case irc.ERR_UNKNOWNCOMMAND, irc.RPL_TRYAGAIN:
1371 var command, reason string
1372 if err := parseMessageParams(msg, nil, &command, &reason); err != nil {
1373 return err
1374 }
1375
1376 if command == "LIST" {
1377 ok := uc.endPendingLISTs(false)
1378 if !ok {
1379 return fmt.Errorf("unexpected response for LIST: %q: no matching pending LIST", msg.Command)
1380 }
1381 }
1382
[355]1383 uc.forEachDownstreamByID(downstreamID, func(dc *downstreamConn) {
1384 dc.SendMessage(&irc.Message{
1385 Prefix: uc.srv.prefix(),
1386 Command: msg.Command,
1387 Params: []string{dc.nick, command, reason},
[302]1388 })
[355]1389 })
[155]1390 case "ACK":
1391 // Ignore
[198]1392 case irc.RPL_NOWAWAY, irc.RPL_UNAWAY:
1393 // Ignore
[16]1394 case irc.RPL_YOURHOST, irc.RPL_CREATED:
[14]1395 // Ignore
1396 case irc.RPL_LUSERCLIENT, irc.RPL_LUSEROP, irc.RPL_LUSERUNKNOWN, irc.RPL_LUSERCHANNELS, irc.RPL_LUSERME:
1397 // Ignore
[478]1398 case irc.RPL_MOTDSTART, irc.RPL_MOTD:
[14]1399 // Ignore
[177]1400 case irc.RPL_LISTSTART:
1401 // Ignore
[14]1402 case rpl_localusers, rpl_globalusers:
1403 // Ignore
[96]1404 case irc.RPL_STATSVLINE, rpl_statsping, irc.RPL_STATSBLINE, irc.RPL_STATSDLINE:
[14]1405 // Ignore
[390]1406 case "ERROR":
1407 var text string
1408 if err := parseMessageParams(msg, &text); err != nil {
1409 return err
1410 }
1411 return fmt.Errorf("fatal server error: %v", text)
[389]1412 case irc.ERR_PASSWDMISMATCH, irc.ERR_ERRONEUSNICKNAME, irc.ERR_NICKNAMEINUSE, irc.ERR_NICKCOLLISION, irc.ERR_UNAVAILRESOURCE, irc.ERR_NOPERMFORHOST, irc.ERR_YOUREBANNEDCREEP:
[342]1413 if !uc.registered {
[399]1414 text := msg.Params[len(msg.Params)-1]
1415 return registrationError(text)
[342]1416 }
1417 fallthrough
[13]1418 default:
[95]1419 uc.logger.Printf("unhandled message: %v", msg)
[355]1420
1421 uc.forEachDownstreamByID(downstreamID, func(dc *downstreamConn) {
1422 // best effort marshaling for unknown messages, replies and errors:
1423 // most numerics start with the user nick, marshal it if that's the case
1424 // otherwise, conservately keep the params without marshaling
1425 params := msg.Params
1426 if _, err := strconv.Atoi(msg.Command); err == nil { // numeric
1427 if len(msg.Params) > 0 && isOurNick(uc.network, msg.Params[0]) {
1428 params[0] = dc.nick
[302]1429 }
[355]1430 }
1431 dc.SendMessage(&irc.Message{
1432 Prefix: uc.srv.prefix(),
1433 Command: msg.Command,
1434 Params: params,
[302]1435 })
[355]1436 })
[13]1437 }
[14]1438 return nil
[13]1439}
1440
[499]1441func (uc *upstreamConn) handleDetachedMessage(ch *Channel, msg *irc.Message) {
1442 if uc.network.detachedMessageNeedsRelay(ch, msg) {
[435]1443 uc.forEachDownstream(func(dc *downstreamConn) {
[499]1444 dc.relayDetachedMessage(uc.network, msg)
[435]1445 })
1446 }
[499]1447 if ch.ReattachOn == FilterMessage || (ch.ReattachOn == FilterHighlight && uc.network.isHighlight(msg)) {
[435]1448 uc.network.attach(ch)
1449 if err := uc.srv.db.StoreChannel(uc.network.ID, ch); err != nil {
1450 uc.logger.Printf("failed to update channel %q: %v", ch.Name, err)
1451 }
1452 }
1453}
1454
[458]1455func (uc *upstreamConn) handleChanModes(s string) error {
1456 parts := strings.SplitN(s, ",", 5)
1457 if len(parts) < 4 {
1458 return fmt.Errorf("malformed ISUPPORT CHANMODES value: %v", s)
1459 }
1460 modes := make(map[byte]channelModeType)
1461 for i, mt := range []channelModeType{modeTypeA, modeTypeB, modeTypeC, modeTypeD} {
1462 for j := 0; j < len(parts[i]); j++ {
1463 mode := parts[i][j]
1464 modes[mode] = mt
1465 }
1466 }
1467 uc.availableChannelModes = modes
1468 return nil
1469}
1470
1471func (uc *upstreamConn) handleMemberships(s string) error {
1472 if s == "" {
1473 uc.availableMemberships = nil
1474 return nil
1475 }
1476
1477 if s[0] != '(' {
1478 return fmt.Errorf("malformed ISUPPORT PREFIX value: %v", s)
1479 }
1480 sep := strings.IndexByte(s, ')')
1481 if sep < 0 || len(s) != sep*2 {
1482 return fmt.Errorf("malformed ISUPPORT PREFIX value: %v", s)
1483 }
1484 memberships := make([]membership, len(s)/2-1)
1485 for i := range memberships {
1486 memberships[i] = membership{
1487 Mode: s[i+1],
1488 Prefix: s[sep+i+1],
1489 }
1490 }
1491 uc.availableMemberships = memberships
1492 return nil
1493}
1494
[281]1495func (uc *upstreamConn) handleSupportedCaps(capsStr string) {
1496 caps := strings.Fields(capsStr)
1497 for _, s := range caps {
1498 kv := strings.SplitN(s, "=", 2)
1499 k := strings.ToLower(kv[0])
1500 var v string
1501 if len(kv) == 2 {
1502 v = kv[1]
1503 }
1504 uc.supportedCaps[k] = v
1505 }
1506}
1507
1508func (uc *upstreamConn) requestCaps() {
1509 var requestCaps []string
[282]1510 for c := range permanentUpstreamCaps {
[281]1511 if _, ok := uc.supportedCaps[c]; ok && !uc.caps[c] {
1512 requestCaps = append(requestCaps, c)
1513 }
1514 }
1515
1516 if uc.requestSASL() && !uc.caps["sasl"] {
1517 requestCaps = append(requestCaps, "sasl")
1518 }
1519
[282]1520 if len(requestCaps) == 0 {
1521 return
1522 }
1523
1524 uc.SendMessage(&irc.Message{
1525 Command: "CAP",
1526 Params: []string{"REQ", strings.Join(requestCaps, " ")},
1527 })
1528}
1529
1530func (uc *upstreamConn) requestSASL() bool {
1531 if uc.network.SASL.Mechanism == "" {
1532 return false
1533 }
1534
1535 v, ok := uc.supportedCaps["sasl"]
1536 if !ok {
1537 return false
1538 }
1539 if v != "" {
1540 mechanisms := strings.Split(v, ",")
1541 found := false
1542 for _, mech := range mechanisms {
1543 if strings.EqualFold(mech, uc.network.SASL.Mechanism) {
1544 found = true
1545 break
1546 }
1547 }
1548 if !found {
1549 return false
1550 }
1551 }
1552
1553 return true
1554}
1555
1556func (uc *upstreamConn) handleCapAck(name string, ok bool) error {
1557 uc.caps[name] = ok
1558
1559 switch name {
1560 case "sasl":
1561 if !ok {
1562 uc.logger.Printf("server refused to acknowledge the SASL capability")
1563 return nil
1564 }
1565
1566 auth := &uc.network.SASL
1567 switch auth.Mechanism {
1568 case "PLAIN":
1569 uc.logger.Printf("starting SASL PLAIN authentication with username %q", auth.Plain.Username)
1570 uc.saslClient = sasl.NewPlainClient("", auth.Plain.Username, auth.Plain.Password)
[307]1571 case "EXTERNAL":
1572 uc.logger.Printf("starting SASL EXTERNAL authentication")
1573 uc.saslClient = sasl.NewExternalClient("")
[282]1574 default:
1575 return fmt.Errorf("unsupported SASL mechanism %q", name)
1576 }
1577
[281]1578 uc.SendMessage(&irc.Message{
[282]1579 Command: "AUTHENTICATE",
1580 Params: []string{auth.Mechanism},
[281]1581 })
[282]1582 default:
1583 if permanentUpstreamCaps[name] {
1584 break
1585 }
1586 uc.logger.Printf("received CAP ACK/NAK for a cap we don't support: %v", name)
[281]1587 }
[282]1588 return nil
[281]1589}
1590
[174]1591func splitSpace(s string) []string {
1592 return strings.FieldsFunc(s, func(r rune) bool {
1593 return r == ' '
1594 })
1595}
1596
[55]1597func (uc *upstreamConn) register() {
[77]1598 uc.nick = uc.network.Nick
[478]1599 uc.nickCM = uc.network.casemap(uc.nick)
[457]1600 uc.username = uc.network.GetUsername()
1601 uc.realname = uc.network.GetRealname()
[77]1602
[60]1603 uc.SendMessage(&irc.Message{
[92]1604 Command: "CAP",
1605 Params: []string{"LS", "302"},
1606 })
1607
[93]1608 if uc.network.Pass != "" {
1609 uc.SendMessage(&irc.Message{
1610 Command: "PASS",
1611 Params: []string{uc.network.Pass},
1612 })
1613 }
1614
[92]1615 uc.SendMessage(&irc.Message{
[13]1616 Command: "NICK",
[69]1617 Params: []string{uc.nick},
[60]1618 })
1619 uc.SendMessage(&irc.Message{
[13]1620 Command: "USER",
[77]1621 Params: []string{uc.username, "0", "*", uc.realname},
[60]1622 })
[44]1623}
[13]1624
[197]1625func (uc *upstreamConn) runUntilRegistered() error {
1626 for !uc.registered {
[212]1627 msg, err := uc.ReadMessage()
[197]1628 if err != nil {
1629 return fmt.Errorf("failed to read message: %v", err)
1630 }
1631
1632 if err := uc.handleMessage(msg); err != nil {
[399]1633 if _, ok := err.(registrationError); ok {
1634 return err
1635 } else {
1636 msg.Tags = nil // prevent message tags from cluttering logs
1637 return fmt.Errorf("failed to handle message %q: %v", msg, err)
1638 }
[197]1639 }
1640 }
1641
[263]1642 for _, command := range uc.network.ConnectCommands {
1643 m, err := irc.ParseMessage(command)
1644 if err != nil {
1645 uc.logger.Printf("failed to parse connect command %q: %v", command, err)
1646 } else {
1647 uc.SendMessage(m)
1648 }
1649 }
1650
[197]1651 return nil
1652}
1653
[165]1654func (uc *upstreamConn) readMessages(ch chan<- event) error {
[13]1655 for {
[210]1656 msg, err := uc.ReadMessage()
[13]1657 if err == io.EOF {
1658 break
1659 } else if err != nil {
1660 return fmt.Errorf("failed to read IRC command: %v", err)
1661 }
1662
[165]1663 ch <- eventUpstreamMessage{msg, uc}
[13]1664 }
1665
[45]1666 return nil
[13]1667}
[60]1668
[303]1669func (uc *upstreamConn) SendMessage(msg *irc.Message) {
1670 if !uc.caps["message-tags"] {
1671 msg = msg.Copy()
1672 msg.Tags = nil
1673 }
1674
1675 uc.conn.SendMessage(msg)
1676}
1677
[176]1678func (uc *upstreamConn) SendMessageLabeled(downstreamID uint64, msg *irc.Message) {
[278]1679 if uc.caps["labeled-response"] {
[155]1680 if msg.Tags == nil {
1681 msg.Tags = make(map[string]irc.TagValue)
1682 }
[176]1683 msg.Tags["label"] = irc.TagValue(fmt.Sprintf("sd-%d-%d", downstreamID, uc.nextLabelID))
[161]1684 uc.nextLabelID++
[155]1685 }
1686 uc.SendMessage(msg)
1687}
[178]1688
[428]1689// appendLog appends a message to the log file.
1690//
1691// The internal message ID is returned. If the message isn't recorded in the
1692// log file, an empty string is returned.
1693func (uc *upstreamConn) appendLog(entity string, msg *irc.Message) (msgID string) {
[423]1694 if uc.user.msgStore == nil {
[428]1695 return ""
[178]1696 }
[486]1697
1698 entityCM := uc.network.casemap(entity)
1699 if entityCM == "nickserv" {
[468]1700 // The messages sent/received from NickServ may contain
1701 // security-related information (like passwords). Don't store these.
1702 return ""
1703 }
[215]1704
[485]1705 if !uc.network.delivered.HasTarget(entity) {
[482]1706 // This is the first message we receive from this target. Save the last
1707 // message ID in delivery receipts, so that we can send the new message
1708 // in the backlog if an offline client reconnects.
[478]1709 lastID, err := uc.user.msgStore.LastMsgID(uc.network, entityCM, time.Now())
[409]1710 if err != nil {
1711 uc.logger.Printf("failed to log message: failed to get last message ID: %v", err)
[428]1712 return ""
[409]1713 }
1714
[489]1715 uc.network.delivered.ForEachClient(func(clientName string) {
[485]1716 uc.network.delivered.StoreID(entity, clientName, lastID)
[489]1717 })
[253]1718 }
1719
[478]1720 msgID, err := uc.user.msgStore.Append(uc.network, entityCM, msg)
[409]1721 if err != nil {
1722 uc.logger.Printf("failed to log message: %v", err)
[428]1723 return ""
[409]1724 }
[406]1725
[428]1726 return msgID
[253]1727}
1728
[409]1729// produce appends a message to the logs and forwards it to connected downstream
1730// connections.
[245]1731//
1732// If origin is not nil and origin doesn't support echo-message, the message is
1733// forwarded to all connections except origin.
[239]1734func (uc *upstreamConn) produce(target string, msg *irc.Message, origin *downstreamConn) {
[428]1735 var msgID string
[239]1736 if target != "" {
[428]1737 msgID = uc.appendLog(target, msg)
[239]1738 }
1739
[284]1740 // Don't forward messages if it's a detached channel
[478]1741 ch := uc.network.channels.Value(target)
[499]1742 detached := ch != nil && ch.Detached
[284]1743
[227]1744 uc.forEachDownstream(func(dc *downstreamConn) {
[499]1745 if !detached && (dc != origin || dc.caps["echo-message"]) {
[428]1746 dc.sendMessageWithID(dc.marshalMessage(msg, uc.network), msgID)
1747 } else {
1748 dc.advanceMessageWithID(msg, msgID)
[238]1749 }
[227]1750 })
[226]1751}
1752
[198]1753func (uc *upstreamConn) updateAway() {
1754 away := true
1755 uc.forEachDownstream(func(*downstreamConn) {
1756 away = false
1757 })
1758 if away == uc.away {
1759 return
1760 }
1761 if away {
1762 uc.SendMessage(&irc.Message{
1763 Command: "AWAY",
1764 Params: []string{"Auto away"},
1765 })
1766 } else {
1767 uc.SendMessage(&irc.Message{
1768 Command: "AWAY",
1769 })
1770 }
1771 uc.away = away
1772}
[435]1773
1774func (uc *upstreamConn) updateChannelAutoDetach(name string) {
[478]1775 uch := uc.channels.Value(name)
1776 if uch == nil {
1777 return
[435]1778 }
[478]1779 ch := uc.network.channels.Value(name)
1780 if ch == nil || ch.Detached {
1781 return
1782 }
1783 uch.updateAutoDetach(ch.DetachAfter)
[435]1784}
Note: See TracBrowser for help on using the repository browser.