-
Notifications
You must be signed in to change notification settings - Fork 20
/
upstream.go
2492 lines (2212 loc) · 63.4 KB
/
upstream.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package soju
import (
"context"
"crypto"
"crypto/sha256"
"crypto/sha512"
"crypto/tls"
"crypto/x509"
"encoding/base64"
"encoding/hex"
"errors"
"fmt"
"io"
"math/rand"
"net"
"strconv"
"strings"
"time"
"github.com/emersion/go-sasl"
"gopkg.in/irc.v4"
"codeberg.org/emersion/soju/database"
"codeberg.org/emersion/soju/xirc"
)
// permanentUpstreamCaps is the static list of upstream capabilities always
// requested when supported.
var permanentUpstreamCaps = map[string]bool{
"account-notify": true,
"account-tag": true,
"away-notify": true,
"batch": true,
"chghost": true,
"extended-join": true,
"extended-monitor": true,
"invite-notify": true,
"labeled-response": true,
"message-tags": true,
"multi-prefix": true,
"sasl": true,
"server-time": true,
"setname": true,
"draft/account-registration": true,
"draft/extended-monitor": true,
}
// storableMessageTags is the static list of message tags that will cause
// a TAGMSG to be stored.
var storableMessageTags = map[string]bool{
"+draft/react": true,
"+react": true,
}
type registrationError struct {
*irc.Message
}
func (err registrationError) Error() string {
return fmt.Sprintf("registration error (%v): %v", err.Command, err.Reason())
}
func (err registrationError) Reason() string {
if len(err.Params) > 0 {
return err.Params[len(err.Params)-1]
}
return err.Command
}
func (err registrationError) Temporary() bool {
// Only return false if we're 100% sure that fixing the error requires a
// network configuration change
switch err.Command {
case irc.ERR_PASSWDMISMATCH, irc.ERR_ERRONEUSNICKNAME:
return false
case "FAIL":
return err.Params[1] != "ACCOUNT_REQUIRED"
default:
return true
}
}
type upstreamChannel struct {
Name string
conn *upstreamConn
Topic string
TopicWho *irc.Prefix
TopicTime time.Time
Status xirc.ChannelStatus
modes channelModes
creationTime string
Members xirc.CaseMappingMap[*xirc.MembershipSet]
complete bool
detachTimer *time.Timer
}
func (uc *upstreamChannel) updateAutoDetach(dur time.Duration) {
if uc.detachTimer != nil {
uc.detachTimer.Stop()
uc.detachTimer = nil
}
if dur == 0 {
return
}
uc.detachTimer = time.AfterFunc(dur, func() {
uc.conn.network.user.events <- eventChannelDetach{
uc: uc.conn,
name: uc.Name,
}
})
}
type upstreamBatch struct {
Type string
Params []string
Outer *upstreamBatch // if not-nil, this batch is nested in Outer
Label string
}
type upstreamUser struct {
Nickname string
Username string
Hostname string
Server string
Flags string
Account string
Realname string
}
func (uu *upstreamUser) hasWHOXFields(fields string) bool {
for i := 0; i < len(fields); i++ {
ok := false
switch fields[i] {
case 'n':
ok = uu.Nickname != ""
case 'u':
ok = uu.Username != ""
case 'h':
ok = uu.Hostname != ""
case 's':
ok = uu.Server != ""
case 'f':
ok = uu.Flags != ""
case 'a':
ok = uu.Account != ""
case 'r':
ok = uu.Realname != ""
case 't', 'c', 'i', 'd', 'l', 'o':
// we return static values for those fields, so they are always available
ok = true
}
if !ok {
return false
}
}
return true
}
func (uu *upstreamUser) updateFrom(update *upstreamUser) {
if update.Nickname != "" {
uu.Nickname = update.Nickname
}
if update.Username != "" {
uu.Username = update.Username
}
if update.Hostname != "" {
uu.Hostname = update.Hostname
}
if update.Server != "" {
uu.Server = update.Server
}
if update.Flags != "" {
uu.Flags = update.Flags
}
if update.Account != "" {
uu.Account = update.Account
}
if update.Realname != "" {
uu.Realname = update.Realname
}
}
type pendingUpstreamCommand struct {
downstreamID uint64
msg *irc.Message
sentAt time.Time
}
type upstreamConn struct {
*conn
network *network
user *user
serverPrefix *irc.Prefix
serverName string
availableUserModes string
availableChannelModes map[byte]channelModeType
availableChannelTypes string
availableStatusMsg string
availableMemberships []xirc.Membership
isupport map[string]*string
registered bool
nick string
username string
realname string
hostname string
modes userModes
channels xirc.CaseMappingMap[*upstreamChannel]
users xirc.CaseMappingMap[*upstreamUser]
caps xirc.CapRegistry
batches map[string]upstreamBatch
away bool
account string
nextLabelID uint64
monitored xirc.CaseMappingMap[bool]
saslClient sasl.Client
saslStarted bool
// Queue of commands in progress, indexed by type. The first entry has been
// sent to the server and is awaiting reply. The following entries have not
// been sent yet.
pendingCmds map[string][]pendingUpstreamCommand
pendingRegainNick string
regainNickTimer *time.Timer
regainNickBackoff *backoffer
gotMotd bool
hasDesiredNick bool
}
func connectToUpstream(ctx context.Context, network *network) (*upstreamConn, error) {
logger := &prefixLogger{network.user.logger, fmt.Sprintf("upstream %q: ", network.GetName())}
ctx, cancel := context.WithTimeout(ctx, connectTimeout)
defer cancel()
u, err := network.URL()
if err != nil {
return nil, err
}
var netConn net.Conn
switch u.Scheme {
case "ircs":
addr := u.Host
host, _, err := net.SplitHostPort(u.Host)
if err != nil {
host = u.Host
addr = u.Host + ":6697"
}
tlsConfig := &tls.Config{ServerName: host, NextProtos: []string{"irc"}}
if network.SASL.Mechanism == "EXTERNAL" {
if network.SASL.External.CertBlob == nil {
return nil, fmt.Errorf("missing certificate for authentication")
}
if network.SASL.External.PrivKeyBlob == nil {
return nil, fmt.Errorf("missing private key for authentication")
}
key, err := x509.ParsePKCS8PrivateKey(network.SASL.External.PrivKeyBlob)
if err != nil {
return nil, fmt.Errorf("failed to parse private key: %v", err)
}
tlsConfig.Certificates = []tls.Certificate{
{
Certificate: [][]byte{network.SASL.External.CertBlob},
PrivateKey: key.(crypto.PrivateKey),
},
}
logger.Printf("using TLS client certificate %x", sha256.Sum256(network.SASL.External.CertBlob))
}
if network.CertFP != "" {
tlsConfig.InsecureSkipVerify = true
tlsConfig.VerifyPeerCertificate = func(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error {
if len(rawCerts) == 0 {
return fmt.Errorf("the server didn't present any TLS certificate")
}
parts := strings.SplitN(network.CertFP, ":", 2)
algo, localCertFP := parts[0], parts[1]
for _, rawCert := range rawCerts {
var remoteCertFP string
switch algo {
case "sha-512":
sum := sha512.Sum512(rawCert)
remoteCertFP = hex.EncodeToString(sum[:])
case "sha-256":
sum := sha256.Sum256(rawCert)
remoteCertFP = hex.EncodeToString(sum[:])
}
if remoteCertFP == localCertFP {
return nil // fingerprints match
}
}
// Fingerprints don't match, let's give the user a fingerprint
// they can use to connect
sum := sha512.Sum512(rawCerts[0])
remoteCertFP := hex.EncodeToString(sum[:])
return fmt.Errorf("the configured TLS certificate fingerprint doesn't match the server's - %s", remoteCertFP)
}
}
logger.Printf("connecting to TLS server at address %q", addr)
netConn, err = dialTCP(ctx, network.user, addr)
if err != nil {
return nil, err
}
// Don't do the TLS handshake immediately, because we need to register
// the new connection with identd ASAP. See:
// https://todo.sr.ht/~emersion/soju/69#event-41859
netConn = tls.Client(netConn, tlsConfig)
case "irc+insecure":
addr := u.Host
if _, _, err := net.SplitHostPort(addr); err != nil {
addr = u.Host + ":6667"
}
logger.Printf("connecting to plain-text server at address %q", addr)
netConn, err = dialTCP(ctx, network.user, addr)
if err != nil {
return nil, err
}
case "irc+unix", "unix":
var dialer net.Dialer
logger.Printf("connecting to Unix socket at path %q", u.Path)
netConn, err = dialer.DialContext(ctx, "unix", u.Path)
if err != nil {
return nil, fmt.Errorf("failed to connect to Unix socket %q: %v", u.Path, err)
}
default:
return nil, fmt.Errorf("failed to dial %q: unknown scheme: %v", network.Addr, u.Scheme)
}
options := connOptions{
Logger: logger,
RateLimitDelay: upstreamMessageDelay,
RateLimitBurst: upstreamMessageBurst,
}
cm := stdCaseMapping
uc := &upstreamConn{
conn: newConn(network.user.srv, newNetIRCConn(netConn), &options),
network: network,
user: network.user,
channels: xirc.NewCaseMappingMap[*upstreamChannel](cm),
users: xirc.NewCaseMappingMap[*upstreamUser](cm),
caps: xirc.NewCapRegistry(),
batches: make(map[string]upstreamBatch),
serverPrefix: &irc.Prefix{Name: "*"},
availableChannelTypes: stdChannelTypes,
availableStatusMsg: "",
availableChannelModes: stdChannelModes,
availableMemberships: stdMemberships,
isupport: make(map[string]*string),
pendingCmds: make(map[string][]pendingUpstreamCommand),
monitored: xirc.NewCaseMappingMap[bool](cm),
hasDesiredNick: true,
}
return uc, nil
}
func dialTCP(ctx context.Context, user *user, addr string) (net.Conn, error) {
var dialer net.Dialer
upstreamUserIPs := user.srv.Config().UpstreamUserIPs
if len(upstreamUserIPs) > 0 {
host, port, err := net.SplitHostPort(addr)
if err != nil {
return nil, err
}
ipAddr, err := resolveIPAddr(ctx, host)
if err != nil {
return nil, fmt.Errorf("failed to resolve host %q: %v", host, err)
}
localAddr, err := user.localTCPAddr(ipAddr.IP)
if err != nil {
return nil, fmt.Errorf("failed to pick local IP for remote host %q: %v", host, err)
}
addr = net.JoinHostPort(ipAddr.String(), port)
dialer.LocalAddr = localAddr
}
return dialer.DialContext(ctx, "tcp", addr)
}
func (uc *upstreamConn) forEachDownstream(f func(*downstreamConn)) {
uc.network.forEachDownstream(f)
}
func (uc *upstreamConn) forEachDownstreamByID(id uint64, f func(*downstreamConn)) {
uc.forEachDownstream(func(dc *downstreamConn) {
if id != 0 && id != dc.id {
return
}
f(dc)
})
}
func (uc *upstreamConn) downstreamByID(id uint64) *downstreamConn {
for _, dc := range uc.user.downstreamConns {
if dc.id == id {
return dc
}
}
return nil
}
func (uc *upstreamConn) getChannel(name string) (*upstreamChannel, error) {
ch := uc.channels.Get(name)
if ch == nil {
return nil, fmt.Errorf("unknown channel %q", name)
}
return ch, nil
}
func (uc *upstreamConn) isChannel(entity string) bool {
return len(entity) > 0 && strings.ContainsRune(uc.availableChannelTypes, rune(entity[0]))
}
func (uc *upstreamConn) isOurNick(nick string) bool {
return uc.network.equalCasemap(uc.nick, nick)
}
func (uc *upstreamConn) forwardMessage(ctx context.Context, msg *irc.Message) {
uc.forEachDownstream(func(dc *downstreamConn) {
dc.SendMessage(ctx, msg)
})
}
func (uc *upstreamConn) forwardMsgByID(ctx context.Context, id uint64, msg *irc.Message) {
uc.forEachDownstreamByID(id, func(dc *downstreamConn) {
dc.SendMessage(ctx, msg)
})
}
func (uc *upstreamConn) abortPendingCommands() {
ctx := context.TODO()
for _, l := range uc.pendingCmds {
for _, pendingCmd := range l {
dc := uc.downstreamByID(pendingCmd.downstreamID)
if dc == nil {
continue
}
switch pendingCmd.msg.Command {
case "LIST":
dc.SendMessage(ctx, &irc.Message{
Command: irc.RPL_LISTEND,
Params: []string{dc.nick, "Command aborted"},
})
case "WHO":
mask := "*"
if len(pendingCmd.msg.Params) > 0 {
mask = pendingCmd.msg.Params[0]
}
dc.SendMessage(ctx, &irc.Message{
Command: irc.RPL_ENDOFWHO,
Params: []string{dc.nick, mask, "Command aborted"},
})
case "WHOIS":
nick := pendingCmd.msg.Params[len(pendingCmd.msg.Params)-1]
dc.SendMessage(ctx, &irc.Message{
Command: irc.RPL_ENDOFWHOIS,
Params: []string{dc.nick, nick, "Command aborted"},
})
case "AUTHENTICATE":
dc.endSASL(ctx, &irc.Message{
Command: irc.ERR_SASLABORTED,
Params: []string{dc.nick, "SASL authentication aborted"},
})
case "REGISTER", "VERIFY":
dc.SendMessage(ctx, &irc.Message{
Command: "FAIL",
Params: []string{pendingCmd.msg.Command, "TEMPORARILY_UNAVAILABLE", pendingCmd.msg.Params[0], "Command aborted"},
})
default:
panic(fmt.Errorf("Unsupported pending command %q", pendingCmd.msg.Command))
}
}
}
uc.pendingCmds = make(map[string][]pendingUpstreamCommand)
}
func (uc *upstreamConn) sendNextPendingCommand(cmd string) {
if len(uc.pendingCmds[cmd]) == 0 {
return
}
pendingCmd := &uc.pendingCmds[cmd][0]
uc.SendMessageLabeled(context.TODO(), pendingCmd.downstreamID, pendingCmd.msg)
pendingCmd.sentAt = time.Now()
}
func (uc *upstreamConn) enqueueCommand(dc *downstreamConn, msg *irc.Message) {
switch msg.Command {
case "LIST", "WHO", "WHOIS", "AUTHENTICATE", "REGISTER", "VERIFY":
// Supported
default:
panic(fmt.Errorf("Unsupported pending command %q", msg.Command))
}
uc.pendingCmds[msg.Command] = append(uc.pendingCmds[msg.Command], pendingUpstreamCommand{
downstreamID: dc.id,
msg: msg,
})
// If we didn't get a reply after a while, just give up
// TODO: consider sending an abort reply to downstream
if t := uc.pendingCmds[msg.Command][0].sentAt; !t.IsZero() && time.Since(t) > 30*time.Second {
copy(uc.pendingCmds[msg.Command], uc.pendingCmds[msg.Command][1:])
}
if len(uc.pendingCmds[msg.Command]) == 1 {
uc.sendNextPendingCommand(msg.Command)
}
}
func (uc *upstreamConn) currentPendingCommand(cmd string) (*downstreamConn, *irc.Message) {
if len(uc.pendingCmds[cmd]) == 0 {
return nil, nil
}
pendingCmd := uc.pendingCmds[cmd][0]
return uc.downstreamByID(pendingCmd.downstreamID), pendingCmd.msg
}
func (uc *upstreamConn) dequeueCommand(cmd string) (*downstreamConn, *irc.Message) {
dc, msg := uc.currentPendingCommand(cmd)
if len(uc.pendingCmds[cmd]) > 0 {
copy(uc.pendingCmds[cmd], uc.pendingCmds[cmd][1:])
uc.pendingCmds[cmd] = uc.pendingCmds[cmd][:len(uc.pendingCmds[cmd])-1]
}
uc.sendNextPendingCommand(cmd)
return dc, msg
}
func (uc *upstreamConn) cancelPendingCommandsByDownstreamID(downstreamID uint64) {
for cmd := range uc.pendingCmds {
// We can't cancel the currently running command stored in
// uc.pendingCmds[cmd][0]
for i := len(uc.pendingCmds[cmd]) - 1; i >= 1; i-- {
if uc.pendingCmds[cmd][i].downstreamID == downstreamID {
uc.pendingCmds[cmd] = append(uc.pendingCmds[cmd][:i], uc.pendingCmds[cmd][i+1:]...)
}
}
}
}
func (uc *upstreamConn) parseMembershipPrefix(s string) (ms xirc.MembershipSet, nick string) {
var memberships xirc.MembershipSet
i := 0
for _, m := range uc.availableMemberships {
if i >= len(s) {
break
}
if s[i] == m.Prefix {
memberships = append(memberships, m)
i++
}
}
return memberships, s[i:]
}
func (uc *upstreamConn) handleMessage(ctx context.Context, msg *irc.Message) error {
var label string
if l, ok := msg.Tags["label"]; ok {
label = l
delete(msg.Tags, "label")
}
var msgBatch *upstreamBatch
if batchName, ok := msg.Tags["batch"]; ok {
b, ok := uc.batches[batchName]
if !ok {
return fmt.Errorf("unexpected batch reference: batch was not defined: %q", batchName)
}
msgBatch = &b
if label == "" {
label = msgBatch.Label
}
delete(msg.Tags, "batch")
}
var downstreamID uint64
if label != "" {
var labelOffset uint64
n, err := fmt.Sscanf(label, "sd-%d-%d", &downstreamID, &labelOffset)
if err == nil && n < 2 {
err = errors.New("not enough arguments")
}
if err != nil {
return fmt.Errorf("unexpected message label: invalid downstream reference for label %q: %v", label, err)
}
}
if msg.Prefix == nil {
msg.Prefix = uc.serverPrefix
}
if !isNumeric(msg.Command) {
t, err := time.Parse(xirc.ServerTimeLayout, string(msg.Tags["time"]))
if err != nil {
t = time.Now()
}
msg.Tags["time"] = uc.user.FormatServerTime(t)
}
switch msg.Command {
case "PING":
uc.SendMessage(ctx, &irc.Message{
Command: "PONG",
Params: msg.Params,
})
return nil
case "NOTICE", "PRIVMSG", "TAGMSG":
var target, text string
if msg.Command != "TAGMSG" {
if err := parseMessageParams(msg, &target, &text); err != nil {
return err
}
} else {
if err := parseMessageParams(msg, &target); err != nil {
return err
}
}
// remove statusmsg sigils from target
target = strings.TrimLeft(target, uc.availableStatusMsg)
if uc.network.equalCasemap(msg.Prefix.Name, serviceNick) {
uc.logger.Printf("skipping %v from soju's service: %v", msg.Command, msg)
break
}
if uc.network.equalCasemap(target, serviceNick) {
uc.logger.Printf("skipping %v to soju's service: %v", msg.Command, msg)
break
}
if !uc.registered || uc.network.equalCasemap(msg.Prefix.Name, uc.serverPrefix.Name) || target == "*" || strings.HasPrefix(target, "$") {
// This is a server message
uc.produce("", msg, 0)
break
}
directMessage := uc.isOurNick(target)
bufferName := target
if directMessage {
bufferName = msg.Prefix.Name
}
if t, ok := msg.Tags["+draft/channel-context"]; ok {
ch := uc.channels.Get(string(t))
if ch != nil && ch.Members.Has(msg.Prefix.Name) {
bufferName = ch.Name
directMessage = false
}
}
self := uc.isOurNick(msg.Prefix.Name)
ch := uc.network.channels.Get(bufferName)
highlight := false
detached := false
if ch != nil && msg.Command != "TAGMSG" && !self {
if ch.Detached {
uc.handleDetachedMessage(ctx, ch, msg)
}
highlight = uc.network.isHighlight(msg)
if ch.DetachOn == database.FilterMessage || ch.DetachOn == database.FilterDefault || (ch.DetachOn == database.FilterHighlight && highlight) {
uc.updateChannelAutoDetach(bufferName)
}
if ch.Detached && ch.RelayDetached == database.FilterNone {
detached = true
}
}
if !self && !detached && msg.Command != "TAGMSG" && (highlight || directMessage) {
go uc.network.broadcastWebPush(msg)
if timestamp, err := time.Parse(xirc.ServerTimeLayout, string(msg.Tags["time"])); err == nil {
uc.network.pushTargets.Set(bufferName, timestamp)
}
}
uc.produce(bufferName, msg, downstreamID)
case "CAP":
var subCmd string
if err := parseMessageParams(msg, nil, &subCmd); err != nil {
return err
}
subCmd = strings.ToUpper(subCmd)
subParams := msg.Params[2:]
switch subCmd {
case "LS":
if len(subParams) < 1 {
return newNeedMoreParamsError(msg.Command)
}
caps := subParams[len(subParams)-1]
more := len(subParams) >= 2 && msg.Params[len(subParams)-2] == "*"
uc.handleSupportedCaps(caps)
if more {
break // wait to receive all capabilities
}
uc.updateCaps(ctx)
if uc.requestSASL() {
break // we'll send CAP END after authentication is completed
}
uc.SendMessage(ctx, &irc.Message{
Command: "CAP",
Params: []string{"END"},
})
case "ACK", "NAK":
if len(subParams) < 1 {
return newNeedMoreParamsError(msg.Command)
}
caps := strings.Fields(subParams[0])
for _, name := range caps {
enable := subCmd == "ACK"
if strings.HasPrefix(name, "-") {
name = strings.TrimPrefix(name, "-")
enable = false
}
if err := uc.handleCapAck(ctx, strings.ToLower(name), enable); err != nil {
return err
}
}
if uc.registered {
uc.forEachDownstream(func(dc *downstreamConn) {
dc.updateSupportedCaps(ctx)
})
}
case "NEW":
if len(subParams) < 1 {
return newNeedMoreParamsError(msg.Command)
}
uc.handleSupportedCaps(subParams[0])
uc.updateCaps(ctx)
case "DEL":
if len(subParams) < 1 {
return newNeedMoreParamsError(msg.Command)
}
caps := strings.Fields(subParams[0])
for _, c := range caps {
uc.caps.Del(c)
}
if uc.registered {
uc.forEachDownstream(func(dc *downstreamConn) {
dc.updateSupportedCaps(ctx)
})
}
default:
uc.logger.Debugf("unhandled message: %v", msg)
}
case "AUTHENTICATE":
if uc.saslClient == nil {
return fmt.Errorf("received unexpected AUTHENTICATE message")
}
// TODO: if a challenge is 400 bytes long, buffer it
var challengeStr string
if err := parseMessageParams(msg, &challengeStr); err != nil {
uc.SendMessage(ctx, &irc.Message{
Command: "AUTHENTICATE",
Params: []string{"*"},
})
return err
}
var challenge []byte
if challengeStr != "+" {
var err error
challenge, err = base64.StdEncoding.DecodeString(challengeStr)
if err != nil {
uc.SendMessage(ctx, &irc.Message{
Command: "AUTHENTICATE",
Params: []string{"*"},
})
return err
}
}
var resp []byte
var err error
if !uc.saslStarted {
_, resp, err = uc.saslClient.Start()
uc.saslStarted = true
} else {
resp, err = uc.saslClient.Next(challenge)
}
if err != nil {
uc.SendMessage(ctx, &irc.Message{
Command: "AUTHENTICATE",
Params: []string{"*"},
})
return err
}
for _, msg := range xirc.GenerateSASL(resp) {
uc.SendMessage(ctx, msg)
}
case irc.RPL_LOGGEDIN:
var rawPrefix string
if err := parseMessageParams(msg, nil, &rawPrefix, &uc.account); err != nil {
return err
}
prefix := irc.ParsePrefix(rawPrefix)
uc.username = prefix.User
uc.hostname = prefix.Host
uc.logger.Printf("logged in with account %q", uc.account)
uc.forEachDownstream(func(dc *downstreamConn) {
dc.updateAccount(ctx)
dc.updateHost(ctx)
})
case irc.RPL_LOGGEDOUT:
var rawPrefix string
if err := parseMessageParams(msg, nil, &rawPrefix); err != nil {
return err
}
uc.account = ""
prefix := irc.ParsePrefix(rawPrefix)
uc.username = prefix.User
uc.hostname = prefix.Host
uc.logger.Printf("logged out")
uc.forEachDownstream(func(dc *downstreamConn) {
dc.updateAccount(ctx)
dc.updateHost(ctx)
})
case xirc.RPL_VISIBLEHOST:
var rawHost string
if err := parseMessageParams(msg, nil, &rawHost); err != nil {
return err
}
parts := strings.SplitN(rawHost, "@", 2)
if len(parts) == 2 {
uc.username, uc.hostname = parts[0], parts[1]
} else {
uc.hostname = rawHost
}
uc.forEachDownstream(func(dc *downstreamConn) {
dc.updateHost(ctx)
})
case irc.ERR_NICKLOCKED, irc.RPL_SASLSUCCESS, irc.ERR_SASLFAIL, irc.ERR_SASLTOOLONG, irc.ERR_SASLABORTED:
var info string
if err := parseMessageParams(msg, nil, &info); err != nil {
return err
}
switch msg.Command {
case irc.ERR_NICKLOCKED:
uc.logger.Printf("invalid nick used with SASL authentication: %v", info)
case irc.ERR_SASLFAIL:
uc.logger.Printf("SASL authentication failed: %v", info)
case irc.ERR_SASLTOOLONG:
uc.logger.Printf("SASL message too long: %v", info)
}
uc.saslClient = nil
uc.saslStarted = false
if dc, _ := uc.dequeueCommand("AUTHENTICATE"); dc != nil && dc.sasl != nil {
if msg.Command == irc.RPL_SASLSUCCESS {
uc.network.autoSaveSASLPlain(ctx, dc.sasl.plain.Username, dc.sasl.plain.Password)
}
dc.endSASL(ctx, msg)
}
if !uc.registered {
uc.SendMessage(ctx, &irc.Message{
Command: "CAP",
Params: []string{"END"},
})
}
case "REGISTER", "VERIFY":
if dc, cmd := uc.dequeueCommand(msg.Command); dc != nil {
if msg.Command == "REGISTER" {
var account, password string
if err := parseMessageParams(msg, nil, &account); err != nil {
return err
}
if err := parseMessageParams(cmd, nil, nil, &password); err != nil {
return err
}
uc.network.autoSaveSASLPlain(ctx, account, password)
}
dc.SendMessage(ctx, msg)
}
case irc.RPL_WELCOME:
if err := parseMessageParams(msg, &uc.nick); err != nil {
return err
}
uc.registered = true
uc.serverPrefix = msg.Prefix
uc.logger.Printf("connection registered with nick %q", uc.nick)
if uc.network.channels.Len() > 0 {
var channels, keys []string
uc.network.channels.ForEach(func(_ string, ch *database.Channel) {
channels = append(channels, ch.Name)
keys = append(keys, ch.Key)
})
for _, msg := range xirc.GenerateJoin(channels, keys) {
uc.SendMessage(ctx, msg)
}
}
case irc.RPL_MYINFO:
if err := parseMessageParams(msg, nil, &uc.serverName, nil, &uc.availableUserModes, nil); err != nil {
return err
}
case irc.RPL_ISUPPORT:
if err := parseMessageParams(msg, nil, nil); err != nil {
return err
}
var downstreamIsupport []string
for _, token := range msg.Params[1 : len(msg.Params)-1] {
parameter := token
var negate, hasValue bool
var value string
if strings.HasPrefix(token, "-") {
negate = true
token = token[1:]
} else if i := strings.IndexByte(token, '='); i >= 0 {
parameter = token[:i]
value = token[i+1:]
hasValue = true
}
parameter = strings.ToUpper(parameter)
if hasValue {
uc.isupport[parameter] = &value
} else if !negate {
uc.isupport[parameter] = nil
} else {
delete(uc.isupport, parameter)
}
var err error
switch parameter {
case "CASEMAPPING":
casemap := xirc.ParseCaseMapping(value)
if casemap == nil {
casemap = xirc.CaseMappingRFC1459
}
uc.network.updateCasemapping(casemap)
case "CHANMODES":
if !negate {
err = uc.handleChanModes(value)
} else {
uc.availableChannelModes = stdChannelModes
}
case "CHANTYPES":
if !negate {
uc.availableChannelTypes = value
} else {
uc.availableChannelTypes = stdChannelTypes
}
case "STATUSMSG":
if !negate {
uc.availableStatusMsg = value
} else {
uc.availableStatusMsg = ""
}
case "PREFIX":