-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathdownstream.go
3798 lines (3419 loc) · 98.5 KB
/
downstream.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 (
"bytes"
"context"
"crypto/tls"
"encoding/base64"
"errors"
"fmt"
"io"
"net"
"net/url"
"strconv"
"strings"
"time"
"github.com/SherClockHolmes/webpush-go"
"github.com/emersion/go-sasl"
"gopkg.in/irc.v4"
"codeberg.org/emersion/soju/auth"
"codeberg.org/emersion/soju/database"
"codeberg.org/emersion/soju/msgstore"
"codeberg.org/emersion/soju/xirc"
)
type ircError struct {
Message *irc.Message
}
func (err ircError) Error() string {
return err.Message.String()
}
func newUnknownCommandError(cmd string) ircError {
return ircError{&irc.Message{
Command: irc.ERR_UNKNOWNCOMMAND,
Params: []string{
"*",
cmd,
"Unknown command",
},
}}
}
func newUnknownIRCError(cmd, text string) ircError {
return ircError{&irc.Message{
Command: xirc.ERR_UNKNOWNERROR,
Params: []string{"*", cmd, text},
}}
}
func newNeedMoreParamsError(cmd string) ircError {
return ircError{&irc.Message{
Command: irc.ERR_NEEDMOREPARAMS,
Params: []string{
"*",
cmd,
"Not enough parameters",
},
}}
}
func newChatHistoryError(subcommand string, target string) ircError {
return ircError{&irc.Message{
Command: "FAIL",
Params: []string{"CHATHISTORY", "MESSAGE_ERROR", subcommand, target, "Messages could not be retrieved"},
}}
}
// authErrorReason returns the user-friendly reason of an authentication
// failure.
func authErrorReason(err error) string {
if authErr, ok := err.(*auth.Error); ok {
return authErr.ExternalMsg
} else {
return "Authentication failed"
}
}
func parseBouncerNetID(subcommand, s string) (int64, error) {
id, err := strconv.ParseInt(s, 10, 64)
if err != nil || id <= 0 {
return 0, ircError{&irc.Message{
Command: "FAIL",
Params: []string{"BOUNCER", "INVALID_NETID", subcommand, s, "Invalid network ID"},
}}
}
return id, nil
}
func fillNetworkAddrAttrs(attrs irc.Tags, network *database.Network) {
u, err := network.URL()
if err != nil {
return
}
hasHostPort := true
switch u.Scheme {
case "ircs":
attrs["tls"] = "1"
case "irc+insecure":
attrs["tls"] = "0"
default: // e.g. unix://
hasHostPort = false
}
if host, port, err := net.SplitHostPort(u.Host); err == nil && hasHostPort {
attrs["host"] = host
attrs["port"] = port
} else if hasHostPort {
attrs["host"] = u.Host
}
}
func getNetworkAttrs(network *network) irc.Tags {
state := "disconnected"
if uc := network.conn; uc != nil {
state = "connected"
}
attrs := irc.Tags{
"name": network.GetName(),
"state": state,
"nickname": database.GetNick(&network.user.User, &network.Network),
}
if network.Username != "" {
attrs["username"] = network.Username
}
if realname := database.GetRealname(&network.user.User, &network.Network); realname != "" {
attrs["realname"] = realname
}
if network.lastError != nil {
attrs["error"] = network.lastError.Error()
}
fillNetworkAddrAttrs(attrs, &network.Network)
return attrs
}
func networkAddrFromAttrs(attrs irc.Tags) string {
host := string(attrs["host"])
if host == "" {
return ""
}
addr := host
if port := string(attrs["port"]); port != "" {
addr += ":" + port
}
if tlsStr := string(attrs["tls"]); tlsStr == "0" {
addr = "irc+insecure://" + addr
}
return addr
}
func updateNetworkAttrs(record *database.Network, attrs irc.Tags, subcommand string) error {
addrAttrs := irc.Tags{}
fillNetworkAddrAttrs(addrAttrs, record)
updateAddr := false
for k, v := range attrs {
s := string(v)
switch k {
case "host", "port", "tls":
updateAddr = true
addrAttrs[k] = v
case "name":
record.Name = s
case "nickname":
record.Nick = s
case "username":
record.Username = s
case "realname":
record.Realname = s
case "pass":
record.Pass = s
default:
return ircError{&irc.Message{
Command: "FAIL",
Params: []string{"BOUNCER", "UNKNOWN_ATTRIBUTE", subcommand, k, "Unknown attribute"},
}}
}
}
if updateAddr {
record.Addr = networkAddrFromAttrs(addrAttrs)
if record.Addr == "" {
return ircError{&irc.Message{
Command: "FAIL",
Params: []string{"BOUNCER", "NEED_ATTRIBUTE", subcommand, "host", "Missing required host attribute"},
}}
}
}
return nil
}
// illegalNickChars is the list of characters forbidden in a nickname.
//
// - ' ' and ':' break the IRC message wire format
// - '@' and '!' break prefixes
// - '*' breaks masks and is the reserved nickname for registration
// - '?' breaks masks
// - '$' breaks server masks in PRIVMSG/NOTICE
// - ',' breaks lists
// - '.' is reserved for server names
//
// See https://modern.ircdocs.horse/#clients
const illegalNickChars = " :@!*?$,."
// illegalChanChars is the list of characters forbidden in a channel name.
//
// See https://modern.ircdocs.horse/#channels
const illegalChanChars = " ,\x07"
// permanentDownstreamCaps is the list of always-supported downstream
// capabilities.
var permanentDownstreamCaps = map[string]string{
"batch": "",
"cap-notify": "",
"echo-message": "",
"invite-notify": "",
"server-time": "",
"setname": "",
"draft/metadata-2": "before-connect,max-keys=0,max-value-bytes=1",
"draft/pre-away": "",
"draft/read-marker": "",
"draft/no-implicit-names": "",
"soju.im/account-required": "",
"soju.im/bouncer-networks": "",
"soju.im/bouncer-networks-notify": "",
"soju.im/no-implicit-names": "",
"soju.im/read": "",
"soju.im/webpush": "",
}
// needAllDownstreamCaps is the list of downstream capabilities that
// require support from all upstreams to be enabled.
var needAllDownstreamCaps = map[string]string{
"account-notify": "",
"account-tag": "",
"away-notify": "",
"chghost": "",
"extended-join": "",
"extended-monitor": "",
"message-tags": "",
"multi-prefix": "",
"draft/extended-monitor": "",
}
// permanentIsupport is the set of ISUPPORT tokens that are always passed
// to downstream clients.
var permanentIsupport = []string{
"soju.im/SAFERATE",
}
// passthroughIsupport is the set of ISUPPORT tokens that are directly passed
// through from the upstream server to downstream clients.
var passthroughIsupport = map[string]bool{
"ACCOUNTEXTBAN": true,
"AWAYLEN": true,
"BOT": true,
"CASEMAPPING": true,
"CHANLIMIT": true,
"CHANMODES": true,
"CHANNELLEN": true,
"CHANTYPES": true,
"CLIENTTAGDENY": true,
"ELIST": true,
"EXCEPTS": true,
"EXTBAN": true,
"HOSTLEN": true,
"INVEX": true,
"KICKLEN": true,
"LINELEN": true,
"MAXLIST": true,
"MAXTARGETS": true,
"MODES": true,
"MONITOR": true,
"NAMELEN": true,
"NETWORK": true,
"NICKLEN": true,
"PREFIX": true,
"SAFELIST": true,
"STATUSMSG": true,
"TARGMAX": true,
"TOPICLEN": true,
"USERLEN": true,
"UTF8ONLY": true,
"WHOX": true,
}
type saslPlain struct {
Identity, Username, Password string
}
type downstreamSASL struct {
server sasl.Server
mechanism string
plain *saslPlain
oauthBearer *sasl.OAuthBearerOptions
pendingResp bytes.Buffer
}
type downstreamRegistration struct {
nick string
username string
pass string
networkName string
networkID int64
negotiatingCaps bool
authUsername string
}
func serverSASLMechanisms(srv *Server) []string {
var l []string
if srv.Config().Auth.Plain != nil {
l = append(l, "PLAIN")
}
if srv.Config().Auth.OAuthBearer != nil {
l = append(l, "OAUTHBEARER")
}
return l
}
type downstreamConn struct {
*conn
id uint64
// These don't change after connection registration
registered bool
user *user
network *network // can be nil
clientName string
impersonating bool
nick string
nickCM string
realname string
username string
hostname string
account string // RPL_LOGGEDIN/OUT state
away *string
capVersion int
caps xirc.CapRegistry
sasl *downstreamSASL // nil unless SASL is underway
registration *downstreamRegistration // nil after RPL_WELCOME
lastBatchRef uint64
casemap xirc.CaseMapping
monitored xirc.CaseMappingMap[struct{}]
metadataSubs map[string]struct{}
}
func newDownstreamConn(srv *Server, ic ircConn, id uint64) *downstreamConn {
remoteAddr := ic.RemoteAddr().String()
logger := &prefixLogger{srv.Logger, fmt.Sprintf("downstream %q: ", remoteAddr)}
options := connOptions{Logger: logger}
cm := xirc.CaseMappingASCII
dc := &downstreamConn{
conn: newConn(srv, ic, &options),
id: id,
nick: "*",
nickCM: "*",
username: "~u",
caps: xirc.NewCapRegistry(),
casemap: cm,
monitored: xirc.NewCaseMappingMap[struct{}](cm),
metadataSubs: map[string]struct{}{},
registration: new(downstreamRegistration),
}
if host, _, err := net.SplitHostPort(remoteAddr); err == nil {
dc.hostname = host
} else {
dc.hostname = remoteAddr
}
for k, v := range permanentDownstreamCaps {
dc.caps.Available[k] = v
}
dc.caps.Available["sasl"] = strings.Join(serverSASLMechanisms(dc.srv), ",")
// TODO: this is racy, we should only enable chathistory after
// authentication and then check that user.msgStore implements
// chatHistoryMessageStore
switch srv.Config().MsgStoreDriver {
case "fs", "db":
dc.caps.Available["draft/chathistory"] = ""
dc.caps.Available["soju.im/search"] = ""
}
return dc
}
func (dc *downstreamConn) prefix() *irc.Prefix {
return &irc.Prefix{
Name: dc.nick,
User: dc.username,
Host: dc.hostname,
}
}
func (dc *downstreamConn) forEachNetwork(f func(*network)) {
if dc.network != nil {
f(dc.network)
}
}
func (dc *downstreamConn) forEachUpstream(f func(*upstreamConn)) {
if dc.network == nil {
return
}
dc.user.forEachUpstream(func(uc *upstreamConn) {
if dc.network != nil && uc.network != dc.network {
return
}
f(uc)
})
}
// upstream returns the upstream connection, if any. If there are zero upstream
// connections, it returns nil.
func (dc *downstreamConn) upstream() *upstreamConn {
if dc.network == nil {
return nil
}
return dc.network.conn
}
func (dc *downstreamConn) upstreamForCommand(cmd string) (*upstreamConn, error) {
if dc.network == nil {
return nil, newUnknownIRCError(cmd, "Cannot interact with channels and users on the bouncer connection. Did you mean to use a specific network?")
}
if dc.network.conn == nil {
return nil, newUnknownIRCError(cmd, "Disconnected from upstream network")
}
return dc.network.conn, nil
}
func isOurNick(net *network, nick string) bool {
// TODO: this doesn't account for nick changes
if net.conn != nil {
return net.conn.isOurNick(nick)
}
// We're not currently connected to the upstream connection, so we don't
// know whether this name is our nickname. Best-effort: use the network's
// configured nickname and hope it was the one being used when we were
// connected.
return net.casemap(nick) == net.casemap(database.GetNick(&net.user.User, &net.Network))
}
func (dc *downstreamConn) ReadMessage() (*irc.Message, error) {
msg, err := dc.conn.ReadMessage()
if err != nil {
return nil, err
}
dc.srv.metrics.downstreamInMessagesTotal.Inc()
return msg, nil
}
func (dc *downstreamConn) readMessages(ch chan<- event) error {
for {
msg, err := dc.ReadMessage()
if errors.Is(err, io.EOF) {
break
} else if err != nil {
return fmt.Errorf("failed to read IRC command: %v", err)
}
ch <- eventDownstreamMessage{msg, dc}
}
return nil
}
// SendMessage sends an outgoing message.
//
// This can only called from the user goroutine.
func (dc *downstreamConn) SendMessage(ctx context.Context, msg *irc.Message) {
if !dc.caps.IsEnabled("message-tags") {
if msg.Command == "TAGMSG" {
return
}
msg = msg.Copy()
for name := range msg.Tags {
supported := false
switch name {
case "time":
supported = dc.caps.IsEnabled("server-time")
case "account":
supported = dc.caps.IsEnabled("account-tag")
case "batch":
supported = dc.caps.IsEnabled("batch")
}
if !supported {
delete(msg.Tags, name)
}
}
}
if !dc.caps.IsEnabled("batch") && msg.Tags["batch"] != "" {
msg = msg.Copy()
delete(msg.Tags, "batch")
}
if msg.Command == "JOIN" && !dc.caps.IsEnabled("extended-join") {
msg = msg.Copy()
msg.Params = msg.Params[:1]
}
if msg.Command == "SETNAME" && !dc.caps.IsEnabled("setname") {
return
}
if msg.Command == "CHGHOST" && !dc.caps.IsEnabled("chghost") {
return
}
if msg.Command == "AWAY" && !dc.caps.IsEnabled("away-notify") {
return
}
if msg.Command == "ACCOUNT" && !dc.caps.IsEnabled("account-notify") {
return
}
if msg.Command == "MARKREAD" && !dc.caps.IsEnabled("draft/read-marker") {
return
}
if msg.Command == "READ" && !dc.caps.IsEnabled("soju.im/read") {
return
}
if msg.Command == "METADATA" && !dc.caps.IsEnabled("draft/metadata-2") {
return
}
if msg.Prefix != nil && msg.Prefix.Name == "*" {
// We use "*" as a sentinel value to simplify upstream message handling
msgCopy := *msg
msg = &msgCopy
msg.Prefix = nil
}
if msg.Prefix == nil && isNumeric(msg.Command) {
// Numerics must always carry a source
msgCopy := *msg
msg = &msgCopy
msg.Prefix = dc.srv.prefix()
}
dc.srv.metrics.downstreamOutMessagesTotal.Inc()
dc.conn.SendMessage(ctx, msg)
}
func (dc *downstreamConn) SendBatch(ctx context.Context, typ string, params []string, tags irc.Tags, f func(batchRef string)) {
dc.lastBatchRef++
ref := fmt.Sprintf("%v", dc.lastBatchRef)
if dc.caps.IsEnabled("batch") {
dc.SendMessage(ctx, &irc.Message{
Tags: tags,
Command: "BATCH",
Params: append([]string{"+" + ref, typ}, params...),
})
}
f(ref)
if dc.caps.IsEnabled("batch") {
dc.SendMessage(ctx, &irc.Message{
Command: "BATCH",
Params: []string{"-" + ref},
})
}
}
// sendMessageWithID sends an outgoing message with the specified internal ID.
func (dc *downstreamConn) sendMessageWithID(ctx context.Context, msg *irc.Message, id string) {
dc.SendMessage(ctx, msg)
if id == "" || !dc.messageSupportsBacklog(msg) || dc.caps.IsEnabled("draft/chathistory") {
return
}
dc.sendPing(ctx, id)
}
// advanceMessageWithID advances history to the specified message ID without
// sending a message. This is useful e.g. for self-messages when echo-message
// isn't enabled.
func (dc *downstreamConn) advanceMessageWithID(ctx context.Context, msg *irc.Message, id string) {
if id == "" || !dc.messageSupportsBacklog(msg) || dc.caps.IsEnabled("draft/chathistory") {
return
}
dc.sendPing(ctx, id)
}
// ackMsgID acknowledges that a message has been received.
func (dc *downstreamConn) ackMsgID(id string) {
netID, entity, err := msgstore.ParseMsgID(id, nil)
if err != nil {
dc.logger.Printf("failed to ACK message ID %q: %v", id, err)
return
}
network := dc.user.getNetworkByID(netID)
if network == nil {
return
}
network.delivered.StoreID(entity, dc.clientName, id)
}
func (dc *downstreamConn) sendPing(ctx context.Context, msgID string) {
token := "soju-msgid-" + msgID
dc.SendMessage(ctx, &irc.Message{
Command: "PING",
Params: []string{token},
})
}
func (dc *downstreamConn) handlePong(token string) {
if !strings.HasPrefix(token, "soju-msgid-") {
dc.logger.Printf("received unrecognized PONG token %q", token)
return
}
msgID := strings.TrimPrefix(token, "soju-msgid-")
dc.ackMsgID(msgID)
}
func (dc *downstreamConn) handleMessage(ctx context.Context, msg *irc.Message) error {
ctx, cancel := dc.conn.NewContext(ctx)
defer cancel()
ctx, cancel = context.WithTimeout(ctx, handleDownstreamMessageTimeout)
defer cancel()
switch msg.Command {
case "QUIT":
dc.conn.Shutdown(ctx)
return nil // TODO: stop handling commands
default:
if dc.registered {
return dc.handleMessageRegistered(ctx, msg)
} else {
return dc.handleMessageUnregistered(ctx, msg)
}
}
}
func (dc *downstreamConn) handleMessageUnregistered(ctx context.Context, msg *irc.Message) error {
switch msg.Command {
case "NICK":
if err := parseMessageParams(msg, &dc.registration.nick); err != nil {
return err
}
case "USER":
if err := parseMessageParams(msg, &dc.registration.username, nil, nil, nil); err != nil {
return err
}
case "PASS":
if err := parseMessageParams(msg, &dc.registration.pass); err != nil {
return err
}
case "CAP":
return dc.handleCap(ctx, msg)
case "AUTHENTICATE":
credentials, err := dc.handleAuthenticate(ctx, msg)
if err != nil {
return err
} else if credentials == nil {
break
}
var username, clientName, networkName string
var impersonating bool
switch credentials.mechanism {
case "PLAIN":
username, clientName, networkName = unmarshalUsername(credentials.plain.Username)
password := credentials.plain.Password
auth := dc.srv.Config().Auth.Plain
if auth == nil {
err = fmt.Errorf("SASL PLAIN not supported")
break
}
if err = auth.AuthPlain(ctx, dc.srv.db, username, password); err != nil {
err = fmt.Errorf("%v (username %q)", err, username)
break
}
if credentials.plain.Identity != "" && credentials.plain.Identity != credentials.plain.Username {
var u *database.User
u, err = dc.srv.db.GetUser(ctx, username)
if err != nil {
err = fmt.Errorf("%v (username %q)", err, username)
break
}
if !u.Admin {
err = fmt.Errorf("SASL impersonation only allowed for admin users")
break
}
username, clientName, networkName = unmarshalUsername(credentials.plain.Identity)
if _, err = dc.srv.db.GetUser(ctx, username); err != nil {
err = fmt.Errorf("%v (username %q)", err, username)
break
}
impersonating = true
}
case "OAUTHBEARER":
auth := dc.srv.Config().Auth.OAuthBearer
if auth == nil {
err = fmt.Errorf("SASL OAUTHBEARER not supported")
break
}
username, err = auth.AuthOAuthBearer(ctx, dc.srv.db, credentials.oauthBearer.Token)
if err != nil {
break
}
if credentials.oauthBearer.Username != "" && credentials.oauthBearer.Username != username {
err = fmt.Errorf("username mismatch (client provided %q, but server returned %q)", credentials.oauthBearer.Username, username)
break
}
default:
err = fmt.Errorf("unsupported SASL mechanism")
}
if err != nil {
dc.logger.Printf("SASL %v authentication error for nick %q: %v", credentials.mechanism, dc.registration.nick, err)
dc.endSASL(ctx, &irc.Message{
Command: irc.ERR_SASLFAIL,
Params: []string{dc.nick, authErrorReason(err)},
})
break
}
if username == "" {
panic(fmt.Errorf("username unset after SASL authentication"))
}
dc.setAuthUsername(username, clientName, networkName)
dc.impersonating = impersonating
// Technically we should send RPL_LOGGEDIN here. However we use
// RPL_LOGGEDIN to mirror the upstream connection status. Let's
// see how many clients that breaks. See:
// https://github.com/ircv3/ircv3-specifications/pull/476
dc.endSASL(ctx, nil)
case "BOUNCER":
var subcommand string
if err := parseMessageParams(msg, &subcommand); err != nil {
return err
}
switch strings.ToUpper(subcommand) {
case "BIND":
var idStr string
if err := parseMessageParams(msg, nil, &idStr); err != nil {
return err
}
if dc.registration.authUsername == "" {
return ircError{&irc.Message{
Command: "FAIL",
Params: []string{"BOUNCER", "ACCOUNT_REQUIRED", "BIND", "Authentication needed to bind to bouncer network"},
}}
}
id, err := parseBouncerNetID(subcommand, idStr)
if err != nil {
return err
}
dc.registration.networkID = id
default:
return ircError{&irc.Message{
Command: "FAIL",
Params: []string{"BOUNCER", "UNKNOWN_COMMAND", subcommand, "Unknown subcommand"},
}}
}
case "AWAY":
if len(msg.Params) > 0 {
dc.away = &msg.Params[0]
} else {
dc.away = nil
}
dc.SendMessage(ctx, generateAwayReply(dc.away != nil))
case "METADATA":
var subcommand string
if err := parseMessageParams(msg, nil, &subcommand); err != nil {
return err
}
if handled, err := dc.handleMetadataSub(ctx, msg); handled {
return err
}
return ircError{&irc.Message{
Command: "FAIL",
Params: []string{"METADATA", "INVALID_PARAMS", subcommand, "Unknown command"},
}}
default:
dc.logger.Debugf("unhandled message: %v", msg)
return newUnknownCommandError(msg.Command)
}
return nil
}
func (dc *downstreamConn) handleCap(ctx context.Context, msg *irc.Message) error {
var cmd string
if err := parseMessageParams(msg, &cmd); err != nil {
return err
}
args := msg.Params[1:]
switch cmd = strings.ToUpper(cmd); cmd {
case "LS":
if len(args) > 0 {
var err error
if dc.capVersion, err = strconv.Atoi(args[0]); err != nil {
return err
}
}
if !dc.registered && dc.capVersion >= 302 {
// Let downstream show everything it supports, and trim
// down the available capabilities when upstreams are
// known.
for k, v := range needAllDownstreamCaps {
dc.caps.Available[k] = v
}
}
caps := make([]string, 0, len(dc.caps.Available))
for k, v := range dc.caps.Available {
if dc.capVersion >= 302 && v != "" {
caps = append(caps, k+"="+v)
} else {
caps = append(caps, k)
}
}
// TODO: multi-line replies
dc.SendMessage(ctx, &irc.Message{
Prefix: dc.srv.prefix(),
Command: "CAP",
Params: []string{dc.nick, "LS", strings.Join(caps, " ")},
})
if dc.capVersion >= 302 {
// CAP version 302 implicitly enables cap-notify
dc.caps.SetEnabled("cap-notify", true)
}
if !dc.registered {
dc.registration.negotiatingCaps = true
}
case "LIST":
var caps []string
for name := range dc.caps.Enabled {
caps = append(caps, name)
}
// TODO: multi-line replies
dc.SendMessage(ctx, &irc.Message{
Prefix: dc.srv.prefix(),
Command: "CAP",
Params: []string{dc.nick, "LIST", strings.Join(caps, " ")},
})
case "REQ":
if len(args) == 0 {
return ircError{&irc.Message{
Command: xirc.ERR_INVALIDCAPCMD,
Params: []string{dc.nick, cmd, "Missing argument in CAP REQ command"},
}}
}
caps := strings.Fields(args[0])
ack := true
m := make(map[string]bool, len(caps))
for _, name := range caps {
name = strings.ToLower(name)
enable := !strings.HasPrefix(name, "-")
if !enable {
name = strings.TrimPrefix(name, "-")
}
if enable == dc.caps.IsEnabled(name) {
continue
}
if !dc.caps.IsAvailable(name) {
ack = false
break
}
if name == "cap-notify" && dc.capVersion >= 302 && !enable {
// cap-notify cannot be disabled with CAP version 302
ack = false
break
}
if name == "soju.im/account-required" {
// account-required is an informational cap
ack = false
break
}
m[name] = enable
}
// Atomically ack the whole capability set
if ack {
for name, enable := range m {
dc.caps.SetEnabled(name, enable)
}
}
reply := "NAK"
if ack {
reply = "ACK"
}
dc.SendMessage(ctx, &irc.Message{
Prefix: dc.srv.prefix(),
Command: "CAP",
Params: []string{dc.nick, reply, args[0]},
})
if !dc.registered {
dc.registration.negotiatingCaps = true
}
case "END":
if !dc.registered {
dc.registration.negotiatingCaps = false
}
default:
return ircError{&irc.Message{
Command: xirc.ERR_INVALIDCAPCMD,
Params: []string{dc.nick, cmd, "Unknown CAP command"},
}}
}
return nil
}
func (dc *downstreamConn) handleAuthenticate(ctx context.Context, msg *irc.Message) (result *downstreamSASL, err error) {
defer func() {
if err != nil {
dc.sasl = nil
}
}()
if !dc.caps.IsEnabled("sasl") {
return nil, ircError{&irc.Message{
Command: irc.ERR_SASLFAIL,
Params: []string{dc.nick, "AUTHENTICATE requires the \"sasl\" capability to be enabled"},
}}
}
if len(msg.Params) == 0 {
return nil, ircError{&irc.Message{
Command: irc.ERR_SASLFAIL,
Params: []string{dc.nick, "Missing AUTHENTICATE argument"},
}}
}
if msg.Params[0] == "*" {
return nil, ircError{&irc.Message{
Command: irc.ERR_SASLABORTED,
Params: []string{dc.nick, "SASL authentication aborted"},
}}
}
var resp []byte
if dc.sasl == nil {
mech := strings.ToUpper(msg.Params[0])
var server sasl.Server
switch mech {
case "PLAIN":
server = sasl.NewPlainServer(sasl.PlainAuthenticator(func(identity, username, password string) error {
dc.sasl.plain = &saslPlain{
Identity: identity,
Username: username,
Password: password,
}
return nil
}))
case "OAUTHBEARER":
server = sasl.NewOAuthBearerServer(sasl.OAuthBearerAuthenticator(func(options sasl.OAuthBearerOptions) *sasl.OAuthBearerError {
dc.sasl.oauthBearer = &options
return nil
}))
case "ANONYMOUS":
server = sasl.NewAnonymousServer(func(trace string) error {
return nil
})
default:
return nil, ircError{&irc.Message{
Command: irc.ERR_SASLFAIL,
Params: []string{dc.nick, "Unsupported SASL mechanism"},