forked from ergochat/ergo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhandlers.go
4010 lines (3558 loc) · 132 KB
/
handlers.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
// Copyright (c) 2012-2014 Jeremy Latt
// Copyright (c) 2014-2015 Edmund Huber
// Copyright (c) 2016-2018 Daniel Oaks <[email protected]>
// Copyright (c) 2017-2018 Shivaram Lingamneni <[email protected]>
// released under the MIT license
package irc
import (
"bytes"
"fmt"
"net"
"os"
"runtime"
"runtime/debug"
"runtime/pprof"
"sort"
"strconv"
"strings"
"time"
"github.com/ergochat/irc-go/ircfmt"
"github.com/ergochat/irc-go/ircmsg"
"github.com/ergochat/irc-go/ircutils"
"golang.org/x/crypto/bcrypt"
"github.com/ergochat/ergo/irc/caps"
"github.com/ergochat/ergo/irc/custime"
"github.com/ergochat/ergo/irc/flatip"
"github.com/ergochat/ergo/irc/history"
"github.com/ergochat/ergo/irc/jwt"
"github.com/ergochat/ergo/irc/modes"
"github.com/ergochat/ergo/irc/oauth2"
"github.com/ergochat/ergo/irc/sno"
"github.com/ergochat/ergo/irc/utils"
)
// helper function to parse ACC callbacks, e.g., mailto:[email protected], tel:16505551234
func parseCallback(spec string, config *Config) (callbackNamespace string, callbackValue string, err error) {
// XXX if we don't require verification, ignore any callback that was passed here
// (to avoid confusion in the case where the ircd has no mail server configured)
if !config.Accounts.Registration.EmailVerification.Enabled {
callbackNamespace = "*"
return
}
callback := strings.ToLower(spec)
if colonIndex := strings.IndexByte(callback, ':'); colonIndex != -1 {
callbackNamespace, callbackValue = callback[:colonIndex], callback[colonIndex+1:]
} else {
// "If a callback namespace is not ... provided, the IRC server MUST use mailto""
callbackNamespace = "mailto"
callbackValue = callback
}
if config.Accounts.Registration.EmailVerification.Enabled {
if callbackNamespace != "mailto" {
err = errValidEmailRequired
} else if strings.IndexByte(callbackValue, '@') < 1 {
err = errValidEmailRequired
}
}
return
}
func registrationErrorToMessage(config *Config, client *Client, err error) (message string) {
if emailError := registrationCallbackErrorText(config, client, err); emailError != "" {
return emailError
}
switch err {
case errAccountAlreadyRegistered, errAccountAlreadyVerified, errAccountAlreadyUnregistered, errAccountAlreadyLoggedIn, errAccountCreation, errAccountMustHoldNick, errAccountBadPassphrase, errCertfpAlreadyExists, errFeatureDisabled, errAccountBadPassphrase, errNameReserved:
message = err.Error()
case errLimitExceeded:
message = `There have been too many registration attempts recently; try again later`
default:
// default response: let's be risk-averse about displaying internal errors
// to the clients, especially for something as sensitive as accounts
message = `Could not register`
}
return
}
func announcePendingReg(client *Client, rb *ResponseBuffer, accountName string) {
client.server.snomasks.Send(sno.LocalAccounts, fmt.Sprintf(ircfmt.Unescape("Client $c[grey][$r%s$c[grey]] attempted to register account $c[grey][$r%s$c[grey]] from IP %s, pending verification"), client.Nick(), accountName, rb.session.IP().String()))
}
// helper function to dispatch messages when a client successfully registers
func sendSuccessfulRegResponse(service *ircService, client *Client, rb *ResponseBuffer) {
details := client.Details()
if service != nil {
service.Notice(rb, client.t("Account created"))
}
client.server.snomasks.Send(sno.LocalAccounts, fmt.Sprintf(ircfmt.Unescape("Client $c[grey][$r%s$c[grey]] registered account $c[grey][$r%s$c[grey]] from IP %s"), details.nickMask, details.accountName, rb.session.IP().String()))
sendSuccessfulAccountAuth(service, client, rb, false)
}
// sendSuccessfulAccountAuth means that an account auth attempt completed successfully, and is used to dispatch messages.
func sendSuccessfulAccountAuth(service *ircService, client *Client, rb *ResponseBuffer, forSASL bool) {
details := client.Details()
if service != nil {
service.Notice(rb, fmt.Sprintf(client.t("You're now logged in as %s"), details.accountName))
} else {
//TODO(dan): some servers send this numeric even for NickServ logins iirc? to confirm and maybe do too
rb.Add(nil, client.server.name, RPL_LOGGEDIN, details.nick, details.nickMask, details.accountName, fmt.Sprintf(client.t("You are now logged in as %s"), details.accountName))
if forSASL {
rb.Add(nil, client.server.name, RPL_SASLSUCCESS, details.nick, client.t("Authentication successful"))
}
}
if client.Registered() {
// dispatch account-notify
for friend := range client.FriendsMonitors(caps.AccountNotify) {
if friend != rb.session {
friend.Send(nil, details.nickMask, "ACCOUNT", details.accountName)
}
}
if rb.session.capabilities.Has(caps.AccountNotify) {
rb.Add(nil, details.nickMask, "ACCOUNT", details.accountName)
}
client.server.sendLoginSnomask(details.nickMask, details.accountName)
}
// #1479: for Tor clients, replace the hostname with the always-on cloak here
// (for normal clients, this would discard the IP-based cloak, but with Tor
// there's no such concern)
if rb.session.isTor {
config := client.server.Config()
if config.Server.Cloaks.EnabledForAlwaysOn {
cloakedHostname := config.Server.Cloaks.ComputeAccountCloak(details.accountName)
client.setCloakedHostname(cloakedHostname)
if client.registered {
client.sendChghost(details.nickMask, client.Hostname())
}
}
}
client.server.logger.Info("accounts", "client", details.nick, "logged into account", details.accountName)
}
func (server *Server) sendLoginSnomask(nickMask, accountName string) {
server.snomasks.Send(sno.LocalAccounts, fmt.Sprintf(ircfmt.Unescape("Client $c[grey][$r%s$c[grey]] logged into account $c[grey][$r%s$c[grey]]"), nickMask, accountName))
}
// ACCEPT <nicklist>
// nicklist is a comma-delimited list of nicknames; each may be prefixed with -
// to indicate that it should be removed from the list
func acceptHandler(server *Server, client *Client, msg ircmsg.Message, rb *ResponseBuffer) bool {
for _, tNick := range strings.Split(msg.Params[0], ",") {
add := true
if strings.HasPrefix(tNick, "-") {
add = false
tNick = strings.TrimPrefix(tNick, "-")
}
target := server.clients.Get(tNick)
if target == nil {
rb.Add(nil, server.name, "FAIL", "ACCEPT", "INVALID_USER", utils.SafeErrorParam(tNick), client.t("No such user"))
continue
}
if add {
server.accepts.Accept(client, target)
} else {
server.accepts.Unaccept(client, target)
}
// https://github.com/solanum-ircd/solanum/blob/main/doc/features/modeg.txt
// Charybdis/Solanum define various error numerics that could be sent here,
// but this doesn't seem important to me. One thing to note is that we are not
// imposing an upper bound on the size of the accept list, since in our
// implementation you can only ACCEPT clients who are actually present,
// and an attacker attempting to DoS has much easier resource exhaustion
// strategies available (for example, channel history buffers).
}
return false
}
const (
saslMaxResponseLength = 8192 // implementation-defined sanity check, long enough for bearer tokens
)
// AUTHENTICATE [<mechanism>|<data>|*]
func authenticateHandler(server *Server, client *Client, msg ircmsg.Message, rb *ResponseBuffer) bool {
session := rb.session
config := server.Config()
details := client.Details()
if client.isSTSOnly {
rb.Add(nil, server.name, ERR_SASLFAIL, details.nick, client.t("SASL authentication failed"))
return false
}
if details.account != "" {
rb.Add(nil, server.name, ERR_SASLALREADY, details.nick, client.t("You're already logged into an account"))
return false
}
// sasl abort
if !config.Accounts.AuthenticationEnabled || len(msg.Params) == 1 && msg.Params[0] == "*" {
rb.Add(nil, server.name, ERR_SASLABORTED, details.nick, client.t("SASL authentication aborted"))
session.sasl.Clear()
return false
}
// start new sasl session: parameter is the authentication mechanism
if session.sasl.mechanism == "" {
mechanism := strings.ToUpper(msg.Params[0])
_, mechanismIsEnabled := EnabledSaslMechanisms[mechanism]
// The spec says: "The AUTHENTICATE command MUST be used before registration
// is complete and with the sasl capability enabled." Enforcing this universally
// would simplify the implementation somewhat, but we've never enforced it before
// and I don't want to break working clients that use PLAIN or EXTERNAL
// and violate this MUST (e.g. by sending CAP END too early).
if client.registered && !(mechanism == "PLAIN" || mechanism == "EXTERNAL") {
rb.Add(nil, server.name, ERR_SASLFAIL, details.nick, client.t("SASL is only allowed before connection registration"))
return false
}
if mechanismIsEnabled {
session.sasl.mechanism = mechanism
if !config.Server.Compatibility.SendUnprefixedSasl {
// normal behavior
rb.Add(nil, server.name, "AUTHENTICATE", "+")
} else {
// gross hack: send a raw message to ensure no tags or prefix
rb.Flush(true)
rb.session.SendRawMessage(ircmsg.MakeMessage(nil, "", "AUTHENTICATE", "+"), true)
}
} else {
rb.Add(nil, server.name, ERR_SASLFAIL, details.nick, client.t("SASL authentication failed"))
}
return false
}
// continue existing sasl session: parameter is a message chunk
done, value, err := session.sasl.value.Add(msg.Params[0])
if err == nil {
if done {
// call actual handler
handler := EnabledSaslMechanisms[session.sasl.mechanism]
return handler(server, client, session, value, rb)
} else {
return false // wait for continuation line
}
}
// else: error handling
switch err {
case ircutils.ErrSASLTooLong:
rb.Add(nil, server.name, ERR_SASLTOOLONG, details.nick, client.t("SASL message too long"))
case ircutils.ErrSASLLimitExceeded:
rb.Add(nil, server.name, ERR_SASLFAIL, details.nick, client.t("SASL authentication failed: Passphrase too long"))
default:
rb.Add(nil, server.name, ERR_SASLFAIL, details.nick, client.t("SASL authentication failed: Invalid b64 encoding"))
}
session.sasl.Clear()
return false
}
// AUTHENTICATE PLAIN
func authPlainHandler(server *Server, client *Client, session *Session, value []byte, rb *ResponseBuffer) bool {
defer session.sasl.Clear()
splitValue := bytes.Split(value, []byte{'\000'})
// PLAIN has separate "authorization ID" (which user you want to become)
// and "authentication ID" (whose password you want to use). the first is optional:
// [authzid] \x00 authcid \x00 password
var authzid, authcid string
if len(splitValue) == 3 {
authzid, authcid = string(splitValue[0]), string(splitValue[1])
if authzid != "" && authcid != authzid {
rb.Add(nil, server.name, ERR_SASLFAIL, client.Nick(), client.t("SASL authentication failed: authcid and authzid should be the same"))
return false
}
} else {
rb.Add(nil, server.name, ERR_SASLFAIL, client.Nick(), client.t("SASL authentication failed: Invalid auth blob"))
return false
}
// see #843: strip the device ID for the benefit of clients that don't
// distinguish user/ident from account name
if strudelIndex := strings.IndexByte(authcid, '@'); strudelIndex != -1 {
var deviceID string
authcid, deviceID = authcid[:strudelIndex], authcid[strudelIndex+1:]
if !client.registered {
rb.session.deviceID = deviceID
}
}
password := string(splitValue[2])
err := server.accounts.AuthenticateByPassphrase(client, authcid, password)
if err != nil {
sendAuthErrorResponse(client, rb, err)
return false
} else if !fixupNickEqualsAccount(client, rb, server.Config(), "") {
return false
}
sendSuccessfulAccountAuth(nil, client, rb, true)
return false
}
// AUTHENTICATE IRCV3BEARER
func authIRCv3BearerHandler(server *Server, client *Client, session *Session, value []byte, rb *ResponseBuffer) bool {
defer session.sasl.Clear()
// <authzid> \x00 <type> \x00 <token>
splitValue := bytes.SplitN(value, []byte{'\000'}, 3)
if len(splitValue) != 3 {
rb.Add(nil, server.name, ERR_SASLFAIL, client.Nick(), client.t("SASL authentication failed: Invalid auth blob"))
return false
}
err := server.accounts.AuthenticateByBearerToken(client, string(splitValue[1]), string(splitValue[2]))
if err != nil {
sendAuthErrorResponse(client, rb, err)
return false
}
sendSuccessfulAccountAuth(nil, client, rb, true)
return false
}
func sendAuthErrorResponse(client *Client, rb *ResponseBuffer, err error) {
msg := authErrorToMessage(client.server, err)
rb.Add(nil, client.server.name, ERR_SASLFAIL, client.nick, fmt.Sprintf("%s: %s", client.t("SASL authentication failed"), client.t(msg)))
if err == errAccountUnverified {
rb.Add(nil, client.server.name, "NOTE", "AUTHENTICATE", "VERIFICATION_REQUIRED", "*", client.t(err.Error()))
}
}
func authErrorToMessage(server *Server, err error) (msg string) {
if throttled, ok := err.(*ThrottleError); ok {
return throttled.Error()
}
switch err {
case errAccountDoesNotExist, errAccountUnverified, errAccountInvalidCredentials, errAuthzidAuthcidMismatch, errNickAccountMismatch, errAccountSuspended, oauth2.ErrInvalidToken:
return err.Error()
default:
// don't expose arbitrary error messages to the user
server.logger.Error("internal", "sasl authentication failure", err.Error())
return "Unknown"
}
}
// AUTHENTICATE EXTERNAL
func authExternalHandler(server *Server, client *Client, session *Session, value []byte, rb *ResponseBuffer) bool {
defer session.sasl.Clear()
if rb.session.certfp == "" {
rb.Add(nil, server.name, ERR_SASLFAIL, client.nick, client.t("SASL authentication failed, you are not connecting with a certificate"))
return false
}
// EXTERNAL doesn't carry an authentication ID (this is determined from the
// certificate), but does carry an optional authorization ID.
authzid := string(value)
var deviceID string
var err error
// see #843: strip the device ID for the benefit of clients that don't
// distinguish user/ident from account name
if strudelIndex := strings.IndexByte(authzid, '@'); strudelIndex != -1 {
authzid, deviceID = authzid[:strudelIndex], authzid[strudelIndex+1:]
}
if err == nil {
err = server.accounts.AuthenticateByCertificate(client, rb.session.certfp, rb.session.peerCerts, authzid)
}
if err != nil {
sendAuthErrorResponse(client, rb, err)
return false
} else if !fixupNickEqualsAccount(client, rb, server.Config(), "") {
return false
}
sendSuccessfulAccountAuth(nil, client, rb, true)
if !client.registered && deviceID != "" {
rb.session.deviceID = deviceID
}
return false
}
// AUTHENTICATE SCRAM-SHA-256
func authScramHandler(server *Server, client *Client, session *Session, value []byte, rb *ResponseBuffer) bool {
continueAuth := true
defer func() {
if !continueAuth {
session.sasl.Clear()
}
}()
// first message? if so, initialize the SCRAM conversation
if session.sasl.scramConv == nil {
if throttled, remainingTime := client.checkLoginThrottle(); throttled {
rb.Add(nil, server.name, ERR_SASLFAIL, client.Nick(),
fmt.Sprintf(client.t("Please wait at least %v and try again"), remainingTime.Round(time.Millisecond)))
continueAuth = false
return false
}
session.sasl.scramConv = server.accounts.NewScramConversation()
}
// wait for a final AUTHENTICATE + from the client to conclude authentication
if session.sasl.scramConv.Done() {
continueAuth = false
if session.sasl.scramConv.Valid() {
authcid := session.sasl.scramConv.Username()
if strudelIndex := strings.IndexByte(authcid, '@'); strudelIndex != -1 {
var deviceID string
authcid, deviceID = authcid[:strudelIndex], authcid[strudelIndex+1:]
if !client.registered {
rb.session.deviceID = deviceID
}
}
authzid := session.sasl.scramConv.AuthzID()
if authzid != "" && authzid != authcid {
rb.Add(nil, server.name, ERR_SASLFAIL, client.nick, client.t("SASL authentication failed: authcid and authzid should be the same"))
return false
}
account, err := server.accounts.LoadAccount(authcid)
if err == nil {
server.accounts.Login(client, account)
// fixupNickEqualsAccount is not needed for unregistered clients
sendSuccessfulAccountAuth(nil, client, rb, true)
} else {
server.logger.Error("internal", "SCRAM succeeded but couldn't load account", authcid, err.Error())
rb.Add(nil, server.name, ERR_SASLFAIL, client.nick, client.t("SASL authentication failed"))
}
} else {
rb.Add(nil, server.name, ERR_SASLFAIL, client.nick, client.t("SASL authentication failed"))
}
return false
}
response, err := session.sasl.scramConv.Step(string(value))
if err == nil {
sendSASLChallenge(server, rb, []byte(response))
} else {
continueAuth = false
rb.Add(nil, server.name, ERR_SASLFAIL, client.Nick(), err.Error())
return false
}
return false
}
// AUTHENTICATE OAUTHBEARER
func authOauthBearerHandler(server *Server, client *Client, session *Session, value []byte, rb *ResponseBuffer) bool {
if !server.Config().Accounts.OAuth2.Enabled {
rb.Add(nil, server.name, ERR_SASLFAIL, client.Nick(), "SASL authentication failed: mechanism not enabled")
return false
}
if session.sasl.oauthConv == nil {
session.sasl.oauthConv = oauth2.NewOAuthBearerServer(
func(opts oauth2.OAuthBearerOptions) *oauth2.OAuthBearerError {
err := server.accounts.AuthenticateByOAuthBearer(client, opts)
switch err {
case nil:
return nil
case oauth2.ErrInvalidToken:
return &oauth2.OAuthBearerError{Status: "invalid_token", Schemes: "bearer"}
case errFeatureDisabled:
return &oauth2.OAuthBearerError{Status: "invalid_request", Schemes: "bearer"}
default:
// this is probably a misconfiguration or infrastructure error so we should log it
server.logger.Error("internal", "failed to validate OAUTHBEARER token", err.Error())
// tell the client it was their fault even though it probably wasn't:
return &oauth2.OAuthBearerError{Status: "invalid_request", Schemes: "bearer"}
}
},
)
}
challenge, done, err := session.sasl.oauthConv.Next(value)
if done {
if err == nil {
sendSuccessfulAccountAuth(nil, client, rb, true)
} else {
rb.Add(nil, server.name, ERR_SASLFAIL, client.Nick(), ircutils.SanitizeText(err.Error(), 350))
}
session.sasl.Clear()
} else {
// ignore `err`, we need to relay the challenge (which may contain a JSON-encoded error)
// to the client
sendSASLChallenge(server, rb, challenge)
}
return false
}
// helper to b64 a sasl response and chunk it into 400-byte lines
// as per https://ircv3.net/specs/extensions/sasl-3.1
func sendSASLChallenge(server *Server, rb *ResponseBuffer, challenge []byte) {
for _, chunk := range ircutils.EncodeSASLResponse(challenge) {
rb.Add(nil, server.name, "AUTHENTICATE", chunk)
}
}
// AWAY [<message>]
func awayHandler(server *Server, client *Client, msg ircmsg.Message, rb *ResponseBuffer) bool {
// #1996: `AWAY :` is treated the same as `AWAY`
var awayMessage string
if len(msg.Params) > 0 {
awayMessage = msg.Params[0]
awayMessage = ircmsg.TruncateUTF8Safe(awayMessage, server.Config().Limits.AwayLen)
}
wasAway, nowAway := rb.session.SetAway(awayMessage)
if nowAway != "" {
rb.Add(nil, server.name, RPL_NOWAWAY, client.nick, client.t("You have been marked as being away"))
} else {
rb.Add(nil, server.name, RPL_UNAWAY, client.nick, client.t("You are no longer marked as being away"))
}
if client.registered && wasAway != nowAway {
dispatchAwayNotify(client, nowAway)
} // else: we'll send it (if applicable) after reattach
return false
}
func dispatchAwayNotify(client *Client, awayMessage string) {
// dispatch away-notify
details := client.Details()
isBot := client.HasMode(modes.Bot)
for session := range client.FriendsMonitors(caps.AwayNotify) {
if awayMessage != "" {
session.sendFromClientInternal(false, time.Time{}, "", details.nickMask, details.accountName, isBot, nil, "AWAY", awayMessage)
} else {
session.sendFromClientInternal(false, time.Time{}, "", details.nickMask, details.accountName, isBot, nil, "AWAY")
}
}
}
// BATCH {+,-}reference-tag type [params...]
func batchHandler(server *Server, client *Client, msg ircmsg.Message, rb *ResponseBuffer) bool {
tag := msg.Params[0]
fail := false
sendErrors := rb.session.batch.command != "NOTICE"
if len(tag) == 0 {
fail = true
} else if tag[0] == '+' {
if len(msg.Params) < 3 || msg.Params[1] != caps.MultilineBatchType {
fail = true
} else {
err := rb.session.StartMultilineBatch(tag[1:], msg.Params[2], rb.Label, msg.ClientOnlyTags())
fail = (err != nil)
if !fail {
// suppress ACK for the initial BATCH message (we'll apply the stored label later)
rb.Label = ""
}
}
} else if tag[0] == '-' {
batch, err := rb.session.EndMultilineBatch(tag[1:])
fail = (err != nil)
if !fail {
histType, err := msgCommandToHistType(batch.command)
if err != nil {
histType = history.Privmsg
batch.command = "PRIVMSG"
}
// XXX changing the label inside a handler is a bit dodgy, but it works here
// because there's no way we could have triggered a flush up to this point
rb.Label = batch.responseLabel
dispatchMessageToTarget(client, batch.tags, histType, batch.command, batch.target, batch.message, rb)
}
}
if fail {
rb.session.EndMultilineBatch("")
if sendErrors {
rb.Add(nil, server.name, "FAIL", "BATCH", "MULTILINE_INVALID", client.t("Invalid multiline batch"))
}
}
return false
}
// CAP <subcmd> [<caps>]
func capHandler(server *Server, client *Client, msg ircmsg.Message, rb *ResponseBuffer) bool {
details := client.Details()
subCommand := strings.ToUpper(msg.Params[0])
toAdd := caps.NewSet()
toRemove := caps.NewSet()
var capString string
config := server.Config()
supportedCaps := config.Server.supportedCaps
if client.isSTSOnly {
supportedCaps = stsOnlyCaps
} else if rb.session.hideSTS {
supportedCaps = config.Server.supportedCapsWithoutSTS
}
badCaps := false
if len(msg.Params) > 1 {
capString = msg.Params[1]
strs := strings.Fields(capString)
for _, str := range strs {
remove := false
if str[0] == '-' {
str = str[1:]
remove = true
}
capab, err := caps.NameToCapability(str)
if err != nil || (!remove && !supportedCaps.Has(capab)) {
badCaps = true
} else if !remove {
toAdd.Enable(capab)
} else {
toRemove.Enable(capab)
}
}
}
sendCapLines := func(cset *caps.Set, values caps.Values) {
version := rb.session.capVersion
// we're working around two bugs:
// 1. WeeChat 1.4 won't accept the CAP reply unless it contains the server.name source
// 2. old versions of Kiwi and The Lounge can't parse multiline CAP LS 302 (#661),
// so try as hard as possible to get the response to fit on one line.
// :server.name CAP nickname LS * :<tokens>\r\n
// 1 [5 ] 1 [4 ] [2 ]
maxLen := (MaxLineLen - 2) - 1 - len(server.name) - 5 - len(details.nick) - 1 - len(subCommand) - 4
capLines := cset.Strings(version, values, maxLen)
for i, capStr := range capLines {
if version >= caps.Cap302 && i < len(capLines)-1 {
rb.Add(nil, server.name, "CAP", details.nick, subCommand, "*", capStr)
} else {
rb.Add(nil, server.name, "CAP", details.nick, subCommand, capStr)
}
}
}
switch subCommand {
case "LS":
if !client.registered {
rb.session.capState = caps.NegotiatingState
}
if 1 < len(msg.Params) {
num, err := strconv.Atoi(msg.Params[1])
newVersion := caps.Version(num)
if err == nil && rb.session.capVersion < newVersion {
rb.session.capVersion = newVersion
}
}
sendCapLines(supportedCaps, config.Server.capValues)
case "LIST":
// values not sent on LIST
sendCapLines(&rb.session.capabilities, nil)
case "REQ":
if !client.registered {
rb.session.capState = caps.NegotiatingState
}
// make sure all capabilities actually exist
// #511, #521: oragono.io/nope is a fake cap to trap bad clients who blindly request
// every offered capability. during registration, requesting it produces a quit,
// otherwise just a CAP NAK
if badCaps || (toAdd.Has(caps.Nope) && client.registered) {
rb.Add(nil, server.name, "CAP", details.nick, "NAK", capString)
return false
} else if toAdd.Has(caps.Nope) && !client.registered {
client.Quit(fmt.Sprintf(client.t("Requesting the %s client capability is forbidden"), caps.Nope.Name()), rb.session)
return true
}
rb.session.capabilities.Union(toAdd)
rb.session.capabilities.Subtract(toRemove)
rb.Add(nil, server.name, "CAP", details.nick, "ACK", capString)
case "END":
if !client.registered {
rb.session.capState = caps.NegotiatedState
}
default:
rb.Add(nil, server.name, ERR_INVALIDCAPCMD, details.nick, subCommand, client.t("Invalid CAP subcommand"))
}
return false
}
// CHATHISTORY <target> <preposition> <query> [<limit>]
// e.g., CHATHISTORY #ircv3 AFTER id=ytNBbt565yt4r3err3 10
// CHATHISTORY <target> BETWEEN <query> <query> <direction> [<limit>]
// e.g., CHATHISTORY #ircv3 BETWEEN timestamp=YYYY-MM-DDThh:mm:ss.sssZ timestamp=YYYY-MM-DDThh:mm:ss.sssZ + 100
func chathistoryHandler(server *Server, client *Client, msg ircmsg.Message, rb *ResponseBuffer) (exiting bool) {
var items []history.Item
var target string
var channel *Channel
var sequence history.Sequence
var err error
var listTargets bool
var targets []history.TargetListing
defer func() {
// errors are sent either without a batch, or in a draft/labeled-response batch as usual
if err == utils.ErrInvalidParams {
rb.Add(nil, server.name, "FAIL", "CHATHISTORY", "INVALID_PARAMS", msg.Params[0], client.t("Invalid parameters"))
} else if !listTargets && sequence == nil {
rb.Add(nil, server.name, "FAIL", "CHATHISTORY", "INVALID_TARGET", msg.Params[0], utils.SafeErrorParam(target), client.t("Messages could not be retrieved"))
} else if err != nil {
rb.Add(nil, server.name, "FAIL", "CHATHISTORY", "MESSAGE_ERROR", msg.Params[0], client.t("Messages could not be retrieved"))
} else {
// successful responses are sent as a chathistory or history batch
if listTargets {
batchID := rb.StartNestedBatch(caps.ChathistoryTargetsBatchType)
defer rb.EndNestedBatch(batchID)
for _, target := range targets {
name := server.UnfoldName(target.CfName)
rb.Add(nil, server.name, "CHATHISTORY", "TARGETS", name,
target.Time.Format(IRCv3TimestampFormat))
}
} else if channel != nil {
channel.replayHistoryItems(rb, items, true)
} else {
client.replayPrivmsgHistory(rb, items, target, true)
}
}
}()
config := server.Config()
maxChathistoryLimit := config.History.ChathistoryMax
if maxChathistoryLimit == 0 {
return
}
preposition := strings.ToLower(msg.Params[0])
target = msg.Params[1]
listTargets = (preposition == "targets")
parseQueryParam := func(param string) (msgid string, timestamp time.Time, err error) {
if param == "*" && (preposition == "before" || preposition == "between") {
// XXX compatibility with kiwi, which as of February 2020 is
// using BEFORE * as a synonym for LATEST *
return
}
err = utils.ErrInvalidParams
pieces := strings.SplitN(param, "=", 2)
if len(pieces) < 2 {
return
}
identifier, value := strings.ToLower(pieces[0]), pieces[1]
if identifier == "msgid" {
msgid, err = history.NormalizeMsgid(value), nil
return
} else if identifier == "timestamp" {
timestamp, err = time.Parse(IRCv3TimestampFormat, value)
return
}
return
}
parseHistoryLimit := func(paramIndex int) (limit int) {
if len(msg.Params) < (paramIndex + 1) {
return maxChathistoryLimit
}
limit, err := strconv.Atoi(msg.Params[paramIndex])
if err != nil || limit == 0 || limit > maxChathistoryLimit {
limit = maxChathistoryLimit
}
return
}
roundUp := func(endpoint time.Time) (result time.Time) {
return endpoint.Truncate(time.Millisecond).Add(time.Millisecond)
}
paramPos := 2
var start, end history.Selector
var limit int
switch preposition {
case "targets":
// use the same selector parsing as BETWEEN,
// except that we have no target so we have one fewer parameter
paramPos = 1
fallthrough
case "between":
start.Msgid, start.Time, err = parseQueryParam(msg.Params[paramPos])
if err != nil {
return
}
end.Msgid, end.Time, err = parseQueryParam(msg.Params[paramPos+1])
if err != nil {
return
}
// XXX preserve the ordering of the two parameters, since we might be going backwards,
// but round up the chronologically first one, whichever it is, to make it exclusive
if !start.Time.IsZero() && !end.Time.IsZero() {
if start.Time.Before(end.Time) {
start.Time = roundUp(start.Time)
} else {
end.Time = roundUp(end.Time)
}
}
limit = parseHistoryLimit(paramPos + 2)
case "before", "after", "around":
start.Msgid, start.Time, err = parseQueryParam(msg.Params[2])
if err != nil {
return
}
if preposition == "after" && !start.Time.IsZero() {
start.Time = roundUp(start.Time)
}
if preposition == "before" {
end = start
start = history.Selector{}
}
limit = parseHistoryLimit(3)
case "latest":
if msg.Params[2] != "*" {
end.Msgid, end.Time, err = parseQueryParam(msg.Params[2])
if err != nil {
return
}
if !end.Time.IsZero() {
end.Time = roundUp(end.Time)
}
start.Time = time.Now().UTC()
}
limit = parseHistoryLimit(3)
default:
err = utils.ErrInvalidParams
return
}
if listTargets {
targets, err = client.listTargets(start, end, limit)
} else {
channel, sequence, err = server.GetHistorySequence(nil, client, target)
if err != nil || sequence == nil {
return
}
if preposition == "around" {
items, err = sequence.Around(start, limit)
} else {
items, err = sequence.Between(start, end, limit)
}
}
return
}
// DEBUG <subcmd>
func debugHandler(server *Server, client *Client, msg ircmsg.Message, rb *ResponseBuffer) bool {
param := strings.ToUpper(msg.Params[0])
switch param {
case "GCSTATS":
stats := debug.GCStats{
Pause: make([]time.Duration, 10),
PauseQuantiles: make([]time.Duration, 5),
}
debug.ReadGCStats(&stats)
rb.Notice(fmt.Sprintf("last GC: %s", stats.LastGC.Format(time.RFC1123)))
rb.Notice(fmt.Sprintf("num GC: %d", stats.NumGC))
rb.Notice(fmt.Sprintf("pause total: %s", stats.PauseTotal))
rb.Notice(fmt.Sprintf("pause quantiles min%%: %s", stats.PauseQuantiles[0]))
rb.Notice(fmt.Sprintf("pause quantiles 25%%: %s", stats.PauseQuantiles[1]))
rb.Notice(fmt.Sprintf("pause quantiles 50%%: %s", stats.PauseQuantiles[2]))
rb.Notice(fmt.Sprintf("pause quantiles 75%%: %s", stats.PauseQuantiles[3]))
rb.Notice(fmt.Sprintf("pause quantiles max%%: %s", stats.PauseQuantiles[4]))
case "NUMGOROUTINE":
count := runtime.NumGoroutine()
rb.Notice(fmt.Sprintf("num goroutines: %d", count))
case "PROFILEHEAP":
profFile := server.Config().getOutputPath("ergo.mprof")
file, err := os.Create(profFile)
if err != nil {
rb.Notice(fmt.Sprintf("error: %s", err))
break
}
defer file.Close()
pprof.Lookup("heap").WriteTo(file, 0)
rb.Notice(fmt.Sprintf("written to %s", profFile))
case "STARTCPUPROFILE":
profFile := server.Config().getOutputPath("ergo.prof")
file, err := os.Create(profFile)
if err != nil {
rb.Notice(fmt.Sprintf("error: %s", err))
break
}
if err := pprof.StartCPUProfile(file); err != nil {
defer file.Close()
rb.Notice(fmt.Sprintf("error: %s", err))
break
}
rb.Notice(fmt.Sprintf("CPU profile writing to %s", profFile))
case "STOPCPUPROFILE":
pprof.StopCPUProfile()
rb.Notice(fmt.Sprintf("CPU profiling stopped"))
case "CRASHSERVER":
code := utils.ConfirmationCode(server.name, server.ctime)
if len(msg.Params) == 1 || msg.Params[1] != code {
rb.Notice(fmt.Sprintf(client.t("To confirm, run this command: %s"), fmt.Sprintf("/DEBUG CRASHSERVER %s", code)))
return false
}
server.logger.Error("server", fmt.Sprintf("DEBUG CRASHSERVER executed by operator %s", client.Oper().Name))
go func() {
// intentional nil dereference on a new goroutine, bypassing recover-from-errors
var i, j *int
*i = *j
}()
default:
rb.Notice(client.t("Unrecognized DEBUG subcommand"))
}
return false
}
func defconHandler(server *Server, client *Client, msg ircmsg.Message, rb *ResponseBuffer) bool {
if len(msg.Params) > 0 {
level, err := strconv.Atoi(msg.Params[0])
if err == nil && 1 <= level && level <= 5 {
server.SetDefcon(uint32(level))
server.snomasks.Send(sno.LocalAnnouncements, fmt.Sprintf("%s [%s] set DEFCON level to %d", client.Nick(), client.Oper().Name, level))
} else {
rb.Add(nil, server.name, ERR_UNKNOWNERROR, client.Nick(), msg.Command, client.t("Invalid DEFCON parameter"))
return false
}
}
rb.Notice(fmt.Sprintf(client.t("Current DEFCON level is %d"), server.Defcon()))
return false
}
// helper for parsing the reason args to DLINE and KLINE
func getReasonsFromParams(params []string, currentArg int) (reason, operReason string) {
reason = "No reason given"
operReason = ""
if len(params) > currentArg {
reasons := strings.SplitN(strings.Join(params[currentArg:], " "), "|", 2)
if len(reasons) == 1 {
reason = strings.TrimSpace(reasons[0])
} else if len(reasons) == 2 {
reason = strings.TrimSpace(reasons[0])
operReason = strings.TrimSpace(reasons[1])
}
}
return
}
func formatBanForListing(client *Client, key string, info IPBanInfo) string {
desc := info.Reason
if info.OperReason != "" && info.OperReason != info.Reason {
desc = fmt.Sprintf("%s | %s", info.Reason, info.OperReason)
}
desc = fmt.Sprintf("%s [%s] added on [%s]", desc, info.TimeLeft(), info.TimeCreated.UTC().Format(time.RFC1123))
banType := "Ban"
if info.RequireSASL {
banType = "SASL required"
}
return fmt.Sprintf(client.t("%[1]s - %[2]s - added by %[3]s - %[4]s"), banType, key, info.OperName, desc)
}
// DLINE [ANDKILL] [MYSELF] [duration] <ip>/<net> [ON <server>] [reason [| oper reason]]
// DLINE LIST
func dlineHandler(server *Server, client *Client, msg ircmsg.Message, rb *ResponseBuffer) bool {
// check oper permissions
oper := client.Oper()
if !oper.HasRoleCapab("ban") {
rb.Add(nil, server.name, ERR_NOPRIVS, client.nick, msg.Command, client.t("Insufficient oper privs"))
return false
}
currentArg := 0
// if they say LIST, we just list the current dlines
if len(msg.Params) == currentArg+1 && strings.ToLower(msg.Params[currentArg]) == "list" {
bans := server.dlines.AllBans()
if len(bans) == 0 {
rb.Notice(client.t("No DLINEs have been set!"))
}
for key, info := range bans {
client.Notice(formatBanForListing(client, key, info))
}
return false
}
// when setting a ban, if they say "ANDKILL" we should also kill all users who match it
var andKill bool
if len(msg.Params) > currentArg+1 && strings.ToLower(msg.Params[currentArg]) == "andkill" {
andKill = true
currentArg++