-
Notifications
You must be signed in to change notification settings - Fork 0
/
handlers.go
2559 lines (2199 loc) · 76.8 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 <daniel@danieloaks.net>
// Copyright (c) 2017-2018 Shivaram Lingamneni <slingamn@cs.stanford.edu>
// released under the MIT license
package irc
import (
"bytes"
"encoding/base64"
"encoding/json"
"fmt"
"net"
"os"
"runtime"
"runtime/debug"
"runtime/pprof"
"sort"
"strconv"
"strings"
"time"
"github.com/goshuirc/irc-go/ircfmt"
"github.com/goshuirc/irc-go/ircmatch"
"github.com/goshuirc/irc-go/ircmsg"
"github.com/oragono/oragono/irc/caps"
"github.com/oragono/oragono/irc/custime"
"github.com/oragono/oragono/irc/modes"
"github.com/oragono/oragono/irc/passwd"
"github.com/oragono/oragono/irc/sno"
"github.com/oragono/oragono/irc/utils"
"github.com/tidwall/buntdb"
)
// ACC [REGISTER|VERIFY] ...
func accHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
// make sure reg is enabled
if !server.AccountConfig().Registration.Enabled {
rb.Add(nil, server.name, ERR_REG_UNSPECIFIED_ERROR, client.nick, "*", client.t("Account registration is disabled"))
return false
}
subcommand := strings.ToLower(msg.Params[0])
if subcommand == "register" {
return accRegisterHandler(server, client, msg, rb)
} else if subcommand == "verify" {
return accVerifyHandler(server, client, msg, rb)
} else {
rb.Add(nil, server.name, ERR_UNKNOWNERROR, client.nick, "ACC", msg.Params[0], client.t("Unknown subcommand"))
}
return false
}
// helper function to parse ACC callbacks, e.g., mailto:person@example.com, tel:16505551234
func parseCallback(spec string, config *AccountConfig) (callbackNamespace string, callbackValue string) {
callback := strings.ToLower(spec)
if callback == "*" {
callbackNamespace = "*"
} else if strings.Contains(callback, ":") {
callbackValues := strings.SplitN(callback, ":", 2)
callbackNamespace, callbackValue = callbackValues[0], callbackValues[1]
} else {
// "the IRC server MAY choose to use mailto as a default"
callbackNamespace = "mailto"
callbackValue = callback
}
// ensure the callback namespace is valid
// need to search callback list, maybe look at using a map later?
for _, name := range config.Registration.EnabledCallbacks {
if callbackNamespace == name {
return
}
}
// error value
callbackNamespace = ""
return
}
// ACC REGISTER <accountname> [callback_namespace:]<callback> [cred_type] :<credential>
func accRegisterHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
// clients can't reg new accounts if they're already logged in
if client.LoggedIntoAccount() {
if server.AccountConfig().Registration.AllowMultiplePerConnection {
server.accounts.Logout(client)
} else {
rb.Add(nil, server.name, ERR_REG_UNSPECIFIED_ERROR, client.nick, "*", client.t("You're already logged into an account"))
return false
}
}
// get and sanitise account name
account := strings.TrimSpace(msg.Params[1])
casefoldedAccount, err := CasefoldName(account)
// probably don't need explicit check for "*" here... but let's do it anyway just to make sure
if err != nil || msg.Params[1] == "*" {
rb.Add(nil, server.name, ERR_REG_UNSPECIFIED_ERROR, client.nick, account, client.t("Account name is not valid"))
return false
}
if len(msg.Params) < 4 {
rb.Add(nil, server.name, ERR_NEEDMOREPARAMS, client.nick, msg.Command, client.t("Not enough parameters"))
return false
}
callbackSpec := msg.Params[2]
callbackNamespace, callbackValue := parseCallback(callbackSpec, server.AccountConfig())
if callbackNamespace == "" {
rb.Add(nil, server.name, ERR_REG_INVALID_CALLBACK, client.nick, account, callbackSpec, client.t("Callback namespace is not supported"))
return false
}
// get credential type/value
var credentialType, credentialValue string
if len(msg.Params) > 4 {
credentialType = strings.ToLower(msg.Params[3])
credentialValue = msg.Params[4]
} else {
// exactly 4 params
credentialType = "passphrase" // default from the spec
credentialValue = msg.Params[3]
}
// ensure the credential type is valid
var credentialValid bool
for _, name := range server.AccountConfig().Registration.EnabledCredentialTypes {
if credentialType == name {
credentialValid = true
}
}
if credentialType == "certfp" && client.certfp == "" {
rb.Add(nil, server.name, ERR_REG_INVALID_CRED_TYPE, client.nick, credentialType, callbackNamespace, client.t("You are not using a TLS certificate"))
return false
}
if !credentialValid {
rb.Add(nil, server.name, ERR_REG_INVALID_CRED_TYPE, client.nick, credentialType, callbackNamespace, client.t("Credential type is not supported"))
return false
}
var passphrase, certfp string
if credentialType == "certfp" {
certfp = client.certfp
} else if credentialType == "passphrase" {
passphrase = credentialValue
}
err = server.accounts.Register(client, account, callbackNamespace, callbackValue, passphrase, certfp)
if err != nil {
msg := "Unknown"
code := ERR_UNKNOWNERROR
if err == errCertfpAlreadyExists {
msg = "An account already exists for your certificate fingerprint"
} else if err == errAccountAlreadyRegistered {
msg = "Account already exists"
code = ERR_ACCOUNT_ALREADY_EXISTS
}
if err == errAccountAlreadyRegistered || err == errAccountCreation || err == errCertfpAlreadyExists {
msg = err.Error()
}
rb.Add(nil, server.name, code, client.nick, "ACC", "REGISTER", client.t(msg))
return false
}
// automatically complete registration
if callbackNamespace == "*" {
err := server.accounts.Verify(client, casefoldedAccount, "")
if err != nil {
return false
}
sendSuccessfulRegResponse(client, rb, false)
} else {
messageTemplate := client.t("Account created, pending verification; verification code has been sent to %s:%s")
message := fmt.Sprintf(messageTemplate, callbackNamespace, callbackValue)
rb.Add(nil, server.name, RPL_REG_VERIFICATION_REQUIRED, client.nick, casefoldedAccount, message)
}
return false
}
// helper function to dispatch messages when a client successfully registers
func sendSuccessfulRegResponse(client *Client, rb *ResponseBuffer, forNS bool) {
if forNS {
rb.Notice(client.t("Account created"))
} else {
rb.Add(nil, client.server.name, RPL_REGISTRATION_SUCCESS, client.nick, client.AccountName(), client.t("Account created"))
}
sendSuccessfulSaslAuth(client, rb, forNS)
}
// sendSuccessfulSaslAuth means that a SASL auth attempt completed successfully, and is used to dispatch messages.
func sendSuccessfulSaslAuth(client *Client, rb *ResponseBuffer, forNS bool) {
account := client.AccountName()
if forNS {
rb.Notice(fmt.Sprintf(client.t("You're now logged in as %s"), client.AccountName()))
} else {
rb.Add(nil, client.server.name, RPL_LOGGEDIN, client.nick, client.nickMaskString, account, fmt.Sprintf(client.t("You are now logged in as %s"), account))
rb.Add(nil, client.server.name, RPL_SASLSUCCESS, client.nick, client.t("Authentication successful"))
}
// dispatch account-notify
for friend := range client.Friends(caps.AccountNotify) {
friend.Send(nil, client.nickMaskString, "ACCOUNT", account)
}
client.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]]"), client.nickMaskString, account))
}
// ACC VERIFY <accountname> <auth_code>
func accVerifyHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
account := strings.TrimSpace(msg.Params[1])
err := server.accounts.Verify(client, account, msg.Params[2])
var code string
var message string
if err == errAccountVerificationInvalidCode {
code = ERR_ACCOUNT_INVALID_VERIFY_CODE
message = err.Error()
} else if err == errAccountAlreadyVerified {
code = ERR_ACCOUNT_ALREADY_VERIFIED
message = err.Error()
} else if err != nil {
code = ERR_UNKNOWNERROR
message = errAccountVerificationFailed.Error()
}
if err == nil {
sendSuccessfulRegResponse(client, rb, false)
} else {
rb.Add(nil, server.name, code, client.nick, account, client.t(message))
}
return false
}
// AUTHENTICATE [<mechanism>|<data>|*]
func authenticateHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
// sasl abort
if !server.AccountConfig().AuthenticationEnabled || len(msg.Params) == 1 && msg.Params[0] == "*" {
rb.Add(nil, server.name, ERR_SASLABORTED, client.nick, client.t("SASL authentication aborted"))
client.saslInProgress = false
client.saslMechanism = ""
client.saslValue = ""
return false
}
// start new sasl session
if !client.saslInProgress {
mechanism := strings.ToUpper(msg.Params[0])
_, mechanismIsEnabled := EnabledSaslMechanisms[mechanism]
if mechanismIsEnabled {
client.saslInProgress = true
client.saslMechanism = mechanism
rb.Add(nil, server.name, "AUTHENTICATE", "+")
} else {
rb.Add(nil, server.name, ERR_SASLFAIL, client.nick, client.t("SASL authentication failed"))
}
return false
}
// continue existing sasl session
rawData := msg.Params[0]
if len(rawData) > 400 {
rb.Add(nil, server.name, ERR_SASLTOOLONG, client.nick, client.t("SASL message too long"))
client.saslInProgress = false
client.saslMechanism = ""
client.saslValue = ""
return false
} else if len(rawData) == 400 {
client.saslValue += rawData
// allow 4 'continuation' lines before rejecting for length
if len(client.saslValue) > 400*4 {
rb.Add(nil, server.name, ERR_SASLFAIL, client.nick, client.t("SASL authentication failed: Passphrase too long"))
client.saslInProgress = false
client.saslMechanism = ""
client.saslValue = ""
return false
}
return false
}
if rawData != "+" {
client.saslValue += rawData
}
var data []byte
var err error
if client.saslValue != "+" {
data, err = base64.StdEncoding.DecodeString(client.saslValue)
if err != nil {
rb.Add(nil, server.name, ERR_SASLFAIL, client.nick, client.t("SASL authentication failed: Invalid b64 encoding"))
client.saslInProgress = false
client.saslMechanism = ""
client.saslValue = ""
return false
}
}
// call actual handler
handler, handlerExists := EnabledSaslMechanisms[client.saslMechanism]
// like 100% not required, but it's good to be safe I guess
if !handlerExists {
rb.Add(nil, server.name, ERR_SASLFAIL, client.nick, client.t("SASL authentication failed"))
client.saslInProgress = false
client.saslMechanism = ""
client.saslValue = ""
return false
}
// let the SASL handler do its thing
exiting := handler(server, client, client.saslMechanism, data, rb)
if client.LoggedIntoAccount() && server.AccountConfig().SkipServerPassword {
client.SetAuthorized(true)
}
// wait 'til SASL is done before emptying the sasl vars
client.saslInProgress = false
client.saslMechanism = ""
client.saslValue = ""
return exiting
}
// AUTHENTICATE PLAIN
func authPlainHandler(server *Server, client *Client, mechanism string, value []byte, rb *ResponseBuffer) bool {
splitValue := bytes.Split(value, []byte{'\000'})
var accountKey, authzid string
if len(splitValue) == 3 {
accountKey = string(splitValue[0])
authzid = string(splitValue[1])
if accountKey == "" {
accountKey = authzid
} else if accountKey != 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
}
password := string(splitValue[2])
err := server.accounts.AuthenticateByPassphrase(client, accountKey, password)
if err != nil {
msg := authErrorToMessage(server, err)
rb.Add(nil, server.name, ERR_SASLFAIL, client.nick, fmt.Sprintf("%s: %s", client.t("SASL authentication failed"), client.t(msg)))
return false
}
sendSuccessfulSaslAuth(client, rb, false)
return false
}
func authErrorToMessage(server *Server, err error) (msg string) {
if err == errAccountDoesNotExist || err == errAccountUnverified || err == errAccountInvalidCredentials {
msg = err.Error()
} else {
server.logger.Error("internal", fmt.Sprintf("sasl authentication failure: %v", err))
msg = "Unknown"
}
return
}
// AUTHENTICATE EXTERNAL
func authExternalHandler(server *Server, client *Client, mechanism string, value []byte, rb *ResponseBuffer) bool {
if client.certfp == "" {
rb.Add(nil, server.name, ERR_SASLFAIL, client.nick, client.t("SASL authentication failed, you are not connecting with a certificate"))
return false
}
err := server.accounts.AuthenticateByCertFP(client)
if err != nil {
msg := authErrorToMessage(server, err)
rb.Add(nil, server.name, ERR_SASLFAIL, client.nick, fmt.Sprintf("%s: %s", client.t("SASL authentication failed"), client.t(msg)))
return false
}
sendSuccessfulSaslAuth(client, rb, false)
return false
}
// AWAY [<message>]
func awayHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
var isAway bool
var text string
if len(msg.Params) > 0 {
isAway = true
text = msg.Params[0]
awayLen := server.Limits().AwayLen
if len(text) > awayLen {
text = text[:awayLen]
}
}
if isAway {
client.flags[modes.Away] = true
} else {
delete(client.flags, modes.Away)
}
client.awayMessage = text
var op modes.ModeOp
if client.flags[modes.Away] {
op = modes.Add
rb.Add(nil, server.name, RPL_NOWAWAY, client.nick, client.t("You have been marked as being away"))
} else {
op = modes.Remove
rb.Add(nil, server.name, RPL_UNAWAY, client.nick, client.t("You are no longer marked as being away"))
}
//TODO(dan): Should this be sent automagically as part of setting the flag/mode?
modech := modes.ModeChanges{modes.ModeChange{
Mode: modes.Away,
Op: op,
}}
rb.Add(nil, server.name, "MODE", client.nick, modech.String())
// dispatch away-notify
for friend := range client.Friends(caps.AwayNotify) {
if client.flags[modes.Away] {
friend.SendFromClient("", client, nil, "AWAY", client.awayMessage)
} else {
friend.SendFromClient("", client, nil, "AWAY")
}
}
return false
}
// CAP <subcmd> [<caps>]
func capHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
subCommand := strings.ToUpper(msg.Params[0])
capabilities := caps.NewSet()
var capString string
if len(msg.Params) > 1 {
capString = msg.Params[1]
strs := strings.Split(capString, " ")
for _, str := range strs {
if len(str) > 0 {
capabilities.Enable(caps.Capability(str))
}
}
}
switch subCommand {
case "LS":
if !client.registered {
client.capState = caps.NegotiatingState
}
if len(msg.Params) > 1 && msg.Params[1] == "302" {
client.capVersion = 302
}
// weechat 1.4 has a bug here where it won't accept the CAP reply unless it contains
// the server.name source... otherwise it doesn't respond to the CAP message with
// anything and just hangs on connection.
//TODO(dan): limit number of caps and send it multiline in 3.2 style as appropriate.
rb.Add(nil, server.name, "CAP", client.nick, subCommand, SupportedCapabilities.String(client.capVersion, CapValues))
case "LIST":
rb.Add(nil, server.name, "CAP", client.nick, subCommand, client.capabilities.String(caps.Cap301, CapValues)) // values not sent on LIST so force 3.1
case "REQ":
if !client.registered {
client.capState = caps.NegotiatingState
}
// make sure all capabilities actually exist
for _, capability := range capabilities.List() {
if !SupportedCapabilities.Has(capability) {
rb.Add(nil, server.name, "CAP", client.nick, "NAK", capString)
return false
}
}
client.capabilities.Enable(capabilities.List()...)
rb.Add(nil, server.name, "CAP", client.nick, "ACK", capString)
case "END":
if !client.Registered() {
client.capState = caps.NegotiatedState
}
default:
rb.Add(nil, server.name, ERR_INVALIDCAPCMD, client.nick, subCommand, client.t("Invalid CAP subcommand"))
}
return false
}
// CHANSERV [...]
func csHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
server.chanservPrivmsgHandler(client, strings.Join(msg.Params, " "), rb)
return false
}
// DEBUG <subcmd>
func debugHandler(server *Server, client *Client, msg ircmsg.IrcMessage, 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 := "oragono.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 := "oragono.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"))
}
return false
}
// DLINE [ANDKILL] [MYSELF] [duration] <ip>/<net> [ON <server>] [reason [| oper reason]]
// DLINE LIST
func dlineHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
// check oper permissions
if !client.class.Capabilities["oper:local_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 {
rb.Notice(fmt.Sprintf(client.t("Ban - %[1]s - added by %[2]s - %[3]s"), key, info.OperName, info.BanMessage("%s")))
}
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++
}
// when setting a ban that covers the oper's current connection, we require them to say
// "DLINE MYSELF" so that we're sure they really mean it.
var dlineMyself bool
if len(msg.Params) > currentArg+1 && strings.ToLower(msg.Params[currentArg]) == "myself" {
dlineMyself = true
currentArg++
}
// duration
duration, err := custime.ParseDuration(msg.Params[currentArg])
durationIsUsed := err == nil
if durationIsUsed {
currentArg++
}
// get host
if len(msg.Params) < currentArg+1 {
rb.Add(nil, server.name, ERR_NEEDMOREPARAMS, client.nick, msg.Command, client.t("Not enough parameters"))
return false
}
hostString := msg.Params[currentArg]
currentArg++
// check host
var hostAddr net.IP
var hostNet *net.IPNet
_, hostNet, err = net.ParseCIDR(hostString)
if err != nil {
hostAddr = net.ParseIP(hostString)
}
if hostAddr == nil && hostNet == nil {
rb.Add(nil, server.name, ERR_UNKNOWNERROR, client.nick, msg.Command, client.t("Could not parse IP address or CIDR network"))
return false
}
if hostNet == nil {
hostString = hostAddr.String()
if !dlineMyself && hostAddr.Equal(client.IP()) {
rb.Add(nil, server.name, ERR_UNKNOWNERROR, client.nick, msg.Command, client.t("This ban matches you. To DLINE yourself, you must use the command: /DLINE MYSELF <arguments>"))
return false
}
} else {
hostString = hostNet.String()
if !dlineMyself && hostNet.Contains(client.IP()) {
rb.Add(nil, server.name, ERR_UNKNOWNERROR, client.nick, msg.Command, client.t("This ban matches you. To DLINE yourself, you must use the command: /DLINE MYSELF <arguments>"))
return false
}
}
// check remote
if len(msg.Params) > currentArg && msg.Params[currentArg] == "ON" {
rb.Add(nil, server.name, ERR_UNKNOWNERROR, client.nick, msg.Command, client.t("Remote servers not yet supported"))
return false
}
// get comment(s)
reason := "No reason given"
operReason := "No reason given"
if len(msg.Params) > currentArg {
tempReason := strings.TrimSpace(msg.Params[currentArg])
if len(tempReason) > 0 && tempReason != "|" {
tempReasons := strings.SplitN(tempReason, "|", 2)
if tempReasons[0] != "" {
reason = tempReasons[0]
}
if len(tempReasons) > 1 && tempReasons[1] != "" {
operReason = tempReasons[1]
} else {
operReason = reason
}
}
}
operName := client.operName
if operName == "" {
operName = server.name
}
// assemble ban info
var banTime *IPRestrictTime
if durationIsUsed {
banTime = &IPRestrictTime{
Duration: duration,
Expires: time.Now().Add(duration),
}
}
info := IPBanInfo{
Reason: reason,
OperReason: operReason,
OperName: operName,
Time: banTime,
}
// save in datastore
err = server.store.Update(func(tx *buntdb.Tx) error {
dlineKey := fmt.Sprintf(keyDlineEntry, hostString)
// assemble json from ban info
b, err := json.Marshal(info)
if err != nil {
return err
}
tx.Set(dlineKey, string(b), nil)
return nil
})
if err != nil {
rb.Notice(fmt.Sprintf(client.t("Could not successfully save new D-LINE: %s"), err.Error()))
return false
}
if hostNet == nil {
server.dlines.AddIP(hostAddr, banTime, reason, operReason, operName)
} else {
server.dlines.AddNetwork(*hostNet, banTime, reason, operReason, operName)
}
var snoDescription string
if durationIsUsed {
rb.Notice(fmt.Sprintf(client.t("Added temporary (%[1]s) D-Line for %[2]s"), duration.String(), hostString))
snoDescription = fmt.Sprintf(ircfmt.Unescape("%s [%s]$r added temporary (%s) D-Line for %s"), client.nick, operName, duration.String(), hostString)
} else {
rb.Notice(fmt.Sprintf(client.t("Added D-Line for %s"), hostString))
snoDescription = fmt.Sprintf(ircfmt.Unescape("%s [%s]$r added D-Line for %s"), client.nick, operName, hostString)
}
server.snomasks.Send(sno.LocalXline, snoDescription)
var killClient bool
if andKill {
var clientsToKill []*Client
var killedClientNicks []string
var toKill bool
for _, mcl := range server.clients.AllClients() {
if hostNet == nil {
toKill = hostAddr.Equal(mcl.IP())
} else {
toKill = hostNet.Contains(mcl.IP())
}
if toKill {
clientsToKill = append(clientsToKill, mcl)
killedClientNicks = append(killedClientNicks, mcl.nick)
}
}
for _, mcl := range clientsToKill {
mcl.exitedSnomaskSent = true
mcl.Quit(fmt.Sprintf(mcl.t("You have been banned from this server (%s)"), reason))
if mcl == client {
killClient = true
} else {
// if mcl == client, we kill them below
mcl.destroy(false)
}
}
// send snomask
sort.Strings(killedClientNicks)
server.snomasks.Send(sno.LocalKills, fmt.Sprintf(ircfmt.Unescape("%s [%s] killed %d clients with a DLINE $c[grey][$r%s$c[grey]]"), client.nick, operName, len(killedClientNicks), strings.Join(killedClientNicks, ", ")))
}
return killClient
}
// HELP [<query>]
func helpHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
argument := strings.ToLower(strings.TrimSpace(strings.Join(msg.Params, " ")))
if len(argument) < 1 {
client.sendHelp("HELPOP", client.t(`HELPOP <argument>
Get an explanation of <argument>, or "index" for a list of help topics.`), rb)
return false
}
// handle index
if argument == "index" {
if client.flags[modes.Operator] {
client.sendHelp("HELP", GetHelpIndex(client.languages, HelpIndexOpers), rb)
} else {
client.sendHelp("HELP", GetHelpIndex(client.languages, HelpIndex), rb)
}
return false
}
helpHandler, exists := Help[argument]
if exists && (!helpHandler.oper || (helpHandler.oper && client.flags[modes.Operator])) {
if helpHandler.textGenerator != nil {
client.sendHelp(strings.ToUpper(argument), client.t(helpHandler.textGenerator(client)), rb)
} else {
client.sendHelp(strings.ToUpper(argument), client.t(helpHandler.text), rb)
}
} else {
args := msg.Params
args = append(args, client.t("Help not found"))
rb.Add(nil, server.name, ERR_HELPNOTFOUND, args...)
}
return false
}
// INFO
func infoHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
// we do the below so that the human-readable lines in info can be translated.
for _, line := range infoString1 {
rb.Add(nil, server.name, RPL_INFO, client.nick, line)
}
rb.Add(nil, server.name, RPL_INFO, client.nick, client.t("Oragono is released under the MIT license."))
rb.Add(nil, server.name, RPL_INFO, client.nick, "")
rb.Add(nil, server.name, RPL_INFO, client.nick, client.t("Thanks to Jeremy Latt for founding Ergonomadic, the project this is based on")+" <3")
rb.Add(nil, server.name, RPL_INFO, client.nick, "")
rb.Add(nil, server.name, RPL_INFO, client.nick, client.t("Core Developers:"))
for _, line := range infoString2 {
rb.Add(nil, server.name, RPL_INFO, client.nick, line)
}
rb.Add(nil, server.name, RPL_INFO, client.nick, client.t("Contributors and Former Developers:"))
for _, line := range infoString3 {
rb.Add(nil, server.name, RPL_INFO, client.nick, line)
}
// show translators for languages other than good ole' regular English
tlines := server.languages.Translators()
if 0 < len(tlines) {
rb.Add(nil, server.name, RPL_INFO, client.nick, client.t("Translators:"))
for _, line := range tlines {
rb.Add(nil, server.name, RPL_INFO, client.nick, " "+line)
}
rb.Add(nil, server.name, RPL_INFO, client.nick, "")
}
rb.Add(nil, server.name, RPL_ENDOFINFO, client.nick, client.t("End of /INFO"))
return false
}
// INVITE <nickname> <channel>
func inviteHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
nickname := msg.Params[0]
channelName := msg.Params[1]
casefoldedNickname, err := CasefoldName(nickname)
target := server.clients.Get(casefoldedNickname)
if err != nil || target == nil {
rb.Add(nil, server.name, ERR_NOSUCHNICK, client.nick, nickname, client.t("No such nick"))
return false
}
casefoldedChannelName, err := CasefoldChannel(channelName)
channel := server.channels.Get(casefoldedChannelName)
if err != nil || channel == nil {
rb.Add(nil, server.name, ERR_NOSUCHCHANNEL, client.nick, channelName, client.t("No such channel"))
return false
}
channel.Invite(target, client, rb)
return false
}
// ISON <nick>{ <nick>}
func isonHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
var nicks = msg.Params
var err error
var casefoldedNick string
ison := make([]string, 0)
for _, nick := range nicks {
casefoldedNick, err = CasefoldName(nick)
if err != nil {
continue
}
if iclient := server.clients.Get(casefoldedNick); iclient != nil {
ison = append(ison, iclient.nick)
}
}
rb.Add(nil, server.name, RPL_ISON, client.nick, strings.Join(nicks, " "))
return false
}
// JOIN <channel>{,<channel>} [<key>{,<key>}]
func joinHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
// kill JOIN 0 requests
if msg.Params[0] == "0" {
rb.Notice(client.t("JOIN 0 is not allowed"))
return false
}
// handle regular JOINs
channels := strings.Split(msg.Params[0], ",")
var keys []string
if len(msg.Params) > 1 {
keys = strings.Split(msg.Params[1], ",")
}
for i, name := range channels {
var key string
if len(keys) > i {
key = keys[i]
}
err := server.channels.Join(client, name, key, rb)
if err == errNoSuchChannel {
rb.Add(nil, server.name, ERR_NOSUCHCHANNEL, client.Nick(), name, client.t("No such channel"))
}
}
return false
}
// KICK <channel>{,<channel>} <user>{,<user>} [<comment>]
func kickHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
channels := strings.Split(msg.Params[0], ",")
users := strings.Split(msg.Params[1], ",")
if (len(channels) != len(users)) && (len(users) != 1) {
rb.Add(nil, server.name, ERR_NEEDMOREPARAMS, client.nick, "KICK", client.t("Not enough parameters"))
return false
}
var kicks [][]string
for index, channel := range channels {
if len(users) == 1 {
kicks = append(kicks, []string{channel, users[0]})
} else {
kicks = append(kicks, []string{channel, users[index]})
}
}
var comment string
if len(msg.Params) > 2 {
comment = msg.Params[2]
}
for _, info := range kicks {
chname := info[0]
nickname := info[1]
casefoldedChname, err := CasefoldChannel(chname)
channel := server.channels.Get(casefoldedChname)
if err != nil || channel == nil {
rb.Add(nil, server.name, ERR_NOSUCHCHANNEL, client.nick, chname, client.t("No such channel"))
continue
}
casefoldedNickname, err := CasefoldName(nickname)
target := server.clients.Get(casefoldedNickname)
if err != nil || target == nil {
rb.Add(nil, server.name, ERR_NOSUCHNICK, client.nick, nickname, client.t("No such nick"))
continue
}
if comment == "" {
comment = nickname
}
channel.Kick(client, target, comment, rb)
}
return false
}
// KILL <nickname> <comment>
func killHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
nickname := msg.Params[0]
comment := "<no reason supplied>"
if len(msg.Params) > 1 {
comment = msg.Params[1]
}
casefoldedNickname, err := CasefoldName(nickname)
target := server.clients.Get(casefoldedNickname)
if err != nil || target == nil {
rb.Add(nil, client.server.name, ERR_NOSUCHNICK, client.nick, nickname, client.t("No such nick"))
return false
}
quitMsg := fmt.Sprintf("Killed (%s (%s))", client.nick, comment)
server.snomasks.Send(sno.LocalKills, fmt.Sprintf(ircfmt.Unescape("%s$r was killed by %s $c[grey][$r%s$c[grey]]"), target.nick, client.nick, comment))
target.exitedSnomaskSent = true
target.Quit(quitMsg)
target.destroy(false)
return false
}
// KLINE [ANDKILL] [MYSELF] [duration] <mask> [ON <server>] [reason [| oper reason]]
// KLINE LIST
func klineHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool {
// check oper permissions
if !client.class.Capabilities["oper:local_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 klines
if len(msg.Params) == currentArg+1 && strings.ToLower(msg.Params[currentArg]) == "list" {
bans := server.klines.AllBans()
if len(bans) == 0 {
client.Notice("No KLINEs have been set!")
}
for key, info := range bans {
client.Notice(fmt.Sprintf(client.t("Ban - %[1]s - added by %[2]s - %[3]s"), key, info.OperName, info.BanMessage("%s")))