-
Notifications
You must be signed in to change notification settings - Fork 181
/
server.go
2048 lines (1792 loc) · 61.1 KB
/
server.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-2017 Daniel Oaks <daniel@danieloaks.net>
// released under the MIT license
package irc
import (
"bufio"
"crypto/tls"
"encoding/base64"
"errors"
"fmt"
"log"
"math/rand"
"net"
"net/http"
"os"
"os/signal"
"strconv"
"strings"
"sync"
"syscall"
"time"
"github.com/DanielOaks/girc-go/ircfmt"
"github.com/DanielOaks/girc-go/ircmsg"
"github.com/DanielOaks/oragono/irc/logger"
"github.com/DanielOaks/oragono/irc/sno"
"github.com/tidwall/buntdb"
)
var (
// cached because this may be used lots
tooManyClientsMsg = ircmsg.MakeMessage(nil, "", "ERROR", "Too many clients from your network")
tooManyClientsBytes, _ = tooManyClientsMsg.Line()
bannedFromServerMsg = ircmsg.MakeMessage(nil, "", "ERROR", "You are banned from this server (%s)")
bannedFromServerBytes, _ = bannedFromServerMsg.Line()
errDbOutOfDate = errors.New("Database schema is old")
)
// Limits holds the maximum limits for various things such as topic lengths.
type Limits struct {
AwayLen int
ChannelLen int
KickLen int
MonitorEntries int
NickLen int
TopicLen int
ChanListModes int
LineLen LineLenLimits
}
// LineLenLimits holds the maximum limits for IRC lines.
type LineLenLimits struct {
Tags int
Rest int
}
// ListenerInterface represents an interface for a listener.
type ListenerInterface struct {
Listener net.Listener
Events chan ListenerEvent
}
const (
// DestroyListener instructs the listener to destroy itself.
DestroyListener ListenerEventType = iota
// UpdateListener instructs the listener to update itself (grab new certs, etc).
UpdateListener = iota
)
// ListenerEventType is the type of event this is.
type ListenerEventType int
// ListenerEvent is an event that's passed to the listener.
type ListenerEvent struct {
Type ListenerEventType
NewConfig *tls.Config
}
// Server is the main Oragono server.
type Server struct {
accountAuthenticationEnabled bool
accountRegistration *AccountRegistration
accounts map[string]*ClientAccount
channelRegistrationEnabled bool
channels ChannelNameMap
channelJoinPartMutex sync.Mutex // used when joining/parting channels to prevent stomping over each others' access and all
checkIdent bool
clients *ClientLookupSet
commands chan Command
configFilename string
connectionLimits *ConnectionLimits
connectionLimitsMutex sync.Mutex // used when affecting the connection limiter, to make sure rehashing doesn't make things go out-of-whack
connectionThrottle *ConnectionThrottle
connectionThrottleMutex sync.Mutex // used when affecting the connection limiter, to make sure rehashing doesn't make things go out-of-whack
ctime time.Time
currentOpers map[*Client]bool
dlines *DLineManager
isupport *ISupportList
klines *KLineManager
limits Limits
listenerEventActMutex sync.Mutex
listeners map[string]ListenerInterface
listenerUpdateMutex sync.Mutex
logger *logger.Manager
MaxSendQBytes uint64
monitoring map[string][]*Client
motdLines []string
name string
nameCasefolded string
networkName string
newConns chan clientConn
operators map[string]Oper
operclasses map[string]OperClass
password []byte
passwords *PasswordManager
registeredChannels map[string]*RegisteredChannel
registeredChannelsMutex sync.RWMutex
rehashMutex sync.Mutex
rehashSignal chan os.Signal
restAPI *RestAPIConfig
signals chan os.Signal
snomasks *SnoManager
store *buntdb.DB
stsEnabled bool
whoWas *WhoWasList
}
var (
// ServerExitSignals are the signals the server will exit on.
ServerExitSignals = []os.Signal{
syscall.SIGINT,
syscall.SIGTERM,
syscall.SIGQUIT,
}
)
type clientConn struct {
Conn net.Conn
IsTLS bool
}
// NewServer returns a new Oragono server.
func NewServer(configFilename string, config *Config, logger *logger.Manager) (*Server, error) {
casefoldedName, err := Casefold(config.Server.Name)
if err != nil {
return nil, fmt.Errorf("Server name isn't valid [%s]: %s", config.Server.Name, err.Error())
}
// startup check that we have HELP entries for every command
for name := range Commands {
_, exists := Help[strings.ToLower(name)]
if !exists {
return nil, fmt.Errorf("Help entry does not exist for command %s", name)
}
}
// generate help indexes
HelpIndex = GenerateHelpIndex(false)
HelpIndexOpers = GenerateHelpIndex(true)
if config.Accounts.AuthenticationEnabled {
SupportedCapabilities[SASL] = true
}
if config.Server.STS.Enabled {
SupportedCapabilities[STS] = true
CapValues[STS] = config.Server.STS.Value()
}
if config.Limits.LineLen.Tags > 512 || config.Limits.LineLen.Rest > 512 {
SupportedCapabilities[MaxLine] = true
CapValues[MaxLine] = fmt.Sprintf("%d,%d", config.Limits.LineLen.Tags, config.Limits.LineLen.Rest)
}
operClasses, err := config.OperatorClasses()
if err != nil {
return nil, fmt.Errorf("Error loading oper classes: %s", err.Error())
}
opers, err := config.Operators(operClasses)
if err != nil {
return nil, fmt.Errorf("Error loading operators: %s", err.Error())
}
connectionLimits, err := NewConnectionLimits(config.Server.ConnectionLimits)
if err != nil {
return nil, fmt.Errorf("Error loading connection limits: %s", err.Error())
}
connectionThrottle, err := NewConnectionThrottle(config.Server.ConnectionThrottle)
if err != nil {
return nil, fmt.Errorf("Error loading connection throttler: %s", err.Error())
}
server := &Server{
accountAuthenticationEnabled: config.Accounts.AuthenticationEnabled,
accounts: make(map[string]*ClientAccount),
channelRegistrationEnabled: config.Channels.Registration.Enabled,
channels: *NewChannelNameMap(),
checkIdent: config.Server.CheckIdent,
clients: NewClientLookupSet(),
commands: make(chan Command),
configFilename: configFilename,
connectionLimits: connectionLimits,
connectionThrottle: connectionThrottle,
ctime: time.Now(),
currentOpers: make(map[*Client]bool),
limits: Limits{
AwayLen: int(config.Limits.AwayLen),
ChannelLen: int(config.Limits.ChannelLen),
KickLen: int(config.Limits.KickLen),
MonitorEntries: int(config.Limits.MonitorEntries),
NickLen: int(config.Limits.NickLen),
TopicLen: int(config.Limits.TopicLen),
ChanListModes: int(config.Limits.ChanListModes),
LineLen: LineLenLimits{
Tags: config.Limits.LineLen.Tags,
Rest: config.Limits.LineLen.Rest,
},
},
listeners: make(map[string]ListenerInterface),
logger: logger,
MaxSendQBytes: config.Server.MaxSendQBytes,
monitoring: make(map[string][]*Client),
name: config.Server.Name,
nameCasefolded: casefoldedName,
networkName: config.Network.Name,
newConns: make(chan clientConn),
operators: opers,
operclasses: *operClasses,
registeredChannels: make(map[string]*RegisteredChannel),
rehashSignal: make(chan os.Signal, 1),
restAPI: &config.Server.RestAPI,
signals: make(chan os.Signal, len(ServerExitSignals)),
snomasks: NewSnoManager(),
stsEnabled: config.Server.STS.Enabled,
whoWas: NewWhoWasList(config.Limits.WhowasEntries),
}
// open data store
server.logger.Debug("startup", "Opening datastore")
db, err := buntdb.Open(config.Datastore.Path)
if err != nil {
return nil, fmt.Errorf("Failed to open datastore: %s", err.Error())
}
server.store = db
// check db version
err = server.store.View(func(tx *buntdb.Tx) error {
version, _ := tx.Get(keySchemaVersion)
if version != latestDbSchema {
logger.Error("startup", "server", fmt.Sprintf("Database must be updated. Expected schema v%s, got v%s.", latestDbSchema, version))
return errDbOutOfDate
}
return nil
})
if err != nil {
// close the db
db.Close()
return nil, errDbOutOfDate
}
// load *lines
server.logger.Debug("startup", "Loading D/Klines")
server.loadDLines()
server.loadKLines()
// load password manager
server.logger.Debug("startup", "Loading passwords")
err = server.store.View(func(tx *buntdb.Tx) error {
saltString, err := tx.Get(keySalt)
if err != nil {
return fmt.Errorf("Could not retrieve salt string: %s", err.Error())
}
salt, err := base64.StdEncoding.DecodeString(saltString)
if err != nil {
return err
}
pwm := NewPasswordManager(salt)
server.passwords = &pwm
return nil
})
if err != nil {
return nil, fmt.Errorf("Could not load salt: %s", err.Error())
}
server.logger.Debug("startup", "Loading MOTD")
if config.Server.MOTD != "" {
file, err := os.Open(config.Server.MOTD)
if err == nil {
defer file.Close()
reader := bufio.NewReader(file)
for {
line, err := reader.ReadString('\n')
if err != nil {
break
}
line = strings.TrimRight(line, "\r\n")
// "- " is the required prefix for MOTD, we just add it here to make
// bursting it out to clients easier
line = fmt.Sprintf("- %s", line)
server.motdLines = append(server.motdLines, line)
}
}
}
if config.Server.Password != "" {
server.password = config.Server.PasswordBytes()
}
for _, addr := range config.Server.Listen {
server.createListener(addr, config.TLSListeners())
}
if config.Server.Wslisten != "" {
server.wslisten(config.Server.Wslisten, config.Server.TLSListeners)
}
// registration
accountReg := NewAccountRegistration(config.Accounts.Registration)
server.accountRegistration = &accountReg
// Attempt to clean up when receiving these signals.
signal.Notify(server.signals, ServerExitSignals...)
signal.Notify(server.rehashSignal, syscall.SIGHUP)
server.setISupport()
// start API if enabled
if server.restAPI.Enabled {
logger.Info("startup", "server", fmt.Sprintf("%s rest API started on %s.", server.name, server.restAPI.Listen))
server.startRestAPI()
}
return server, nil
}
// setISupport sets up our RPL_ISUPPORT reply.
func (server *Server) setISupport() {
maxTargetsString := strconv.Itoa(maxTargets)
// add RPL_ISUPPORT tokens
server.isupport = NewISupportList()
server.isupport.Add("AWAYLEN", strconv.Itoa(server.limits.AwayLen))
server.isupport.Add("CASEMAPPING", casemappingName)
server.isupport.Add("CHANMODES", strings.Join([]string{Modes{BanMask, ExceptMask, InviteMask}.String(), "", Modes{UserLimit, Key}.String(), Modes{InviteOnly, Moderated, NoOutside, OpOnlyTopic, ChanRoleplaying, Secret}.String()}, ","))
server.isupport.Add("CHANNELLEN", strconv.Itoa(server.limits.ChannelLen))
server.isupport.Add("CHANTYPES", "#")
server.isupport.Add("EXCEPTS", "")
server.isupport.Add("INVEX", "")
server.isupport.Add("KICKLEN", strconv.Itoa(server.limits.KickLen))
server.isupport.Add("MAXLIST", fmt.Sprintf("beI:%s", strconv.Itoa(server.limits.ChanListModes)))
server.isupport.Add("MAXTARGETS", maxTargetsString)
server.isupport.Add("MODES", "")
server.isupport.Add("MONITOR", strconv.Itoa(server.limits.MonitorEntries))
server.isupport.Add("NETWORK", server.networkName)
server.isupport.Add("NICKLEN", strconv.Itoa(server.limits.NickLen))
server.isupport.Add("PREFIX", "(qaohv)~&@%+")
server.isupport.Add("RPCHAN", "E")
server.isupport.Add("RPUSER", "E")
server.isupport.Add("STATUSMSG", "~&@%+")
server.isupport.Add("TARGMAX", fmt.Sprintf("NAMES:1,LIST:1,KICK:1,WHOIS:1,USERHOST:10,PRIVMSG:%s,TAGMSG:%s,NOTICE:%s,MONITOR:", maxTargetsString, maxTargetsString, maxTargetsString))
server.isupport.Add("TOPICLEN", strconv.Itoa(server.limits.TopicLen))
// account registration
if server.accountRegistration.Enabled {
// 'none' isn't shown in the REGCALLBACKS vars
var enabledCallbacks []string
for _, name := range server.accountRegistration.EnabledCallbacks {
if name != "*" {
enabledCallbacks = append(enabledCallbacks, name)
}
}
server.isupport.Add("REGCOMMANDS", "CREATE,VERIFY")
server.isupport.Add("REGCALLBACKS", strings.Join(enabledCallbacks, ","))
server.isupport.Add("REGCREDTYPES", "passphrase,certfp")
}
server.isupport.RegenerateCachedReply()
}
func loadChannelList(channel *Channel, list string, maskMode Mode) {
if list == "" {
return
}
channel.lists[maskMode].AddAll(strings.Split(list, " "))
}
// Shutdown shuts down the server.
func (server *Server) Shutdown() {
//TODO(dan): Make sure we disallow new nicks
server.clients.ByNickMutex.RLock()
for _, client := range server.clients.ByNick {
client.Notice("Server is shutting down")
}
server.clients.ByNickMutex.RUnlock()
if err := server.store.Close(); err != nil {
server.logger.Error("shutdown", fmt.Sprintln("Could not close datastore:", err))
}
}
// Run starts the server.
func (server *Server) Run() {
// defer closing db/store
defer server.store.Close()
done := false
for !done {
select {
case <-server.signals:
server.Shutdown()
done = true
case <-server.rehashSignal:
server.logger.Info("rehash", "Rehashing due to SIGHUP")
err := server.rehash()
if err != nil {
server.logger.Error("rehash", fmt.Sprintln("Failed to rehash:", err.Error()))
}
case conn := <-server.newConns:
// check connection limits
ipaddr := net.ParseIP(IPString(conn.Conn.RemoteAddr()))
if ipaddr != nil {
// check DLINEs
isBanned, info := server.dlines.CheckIP(ipaddr)
if isBanned {
banMessage := fmt.Sprintf(bannedFromServerBytes, info.Reason)
if info.Time != nil {
banMessage += fmt.Sprintf(" [%s]", info.Time.Duration.String())
}
conn.Conn.Write([]byte(banMessage))
conn.Conn.Close()
continue
}
// check connection limits
server.connectionLimitsMutex.Lock()
err := server.connectionLimits.AddClient(ipaddr, false)
server.connectionLimitsMutex.Unlock()
if err != nil {
// too many connections from one client, tell the client and close the connection
// this might not show up properly on some clients, but our objective here is just to close it out before it has a load impact on us
conn.Conn.Write([]byte(tooManyClientsBytes))
conn.Conn.Close()
continue
}
// check connection throttle
server.connectionThrottleMutex.Lock()
err = server.connectionThrottle.AddClient(ipaddr)
server.connectionThrottleMutex.Unlock()
if err != nil {
// too many connections too quickly from client, tell them and close the connection
length := &IPRestrictTime{
Duration: server.connectionThrottle.BanDuration,
Expires: time.Now().Add(server.connectionThrottle.BanDuration),
}
server.dlines.AddIP(ipaddr, length, server.connectionThrottle.BanMessage, "Exceeded automated connection throttle")
// reset ban on connectionThrottle
server.connectionThrottle.ResetFor(ipaddr)
// this might not show up properly on some clients, but our objective here is just to close it out before it has a load impact on us
conn.Conn.Write([]byte(server.connectionThrottle.BanMessageBytes))
conn.Conn.Close()
continue
}
server.logger.Debug("localconnect-ip", fmt.Sprintf("Client connecting from %v", ipaddr))
// prolly don't need to alert snomasks on this, only on connection reg
go NewClient(server, conn.Conn, conn.IsTLS)
continue
}
}
}
}
//
// IRC protocol listeners
//
// createListener starts the given listeners.
func (server *Server) createListener(addr string, tlsMap map[string]*tls.Config) {
config, listenTLS := tlsMap[addr]
_, alreadyExists := server.listeners[addr]
if alreadyExists {
log.Fatal(server, "listener already exists:", addr)
}
// make listener event channel
listenerEventChannel := make(chan ListenerEvent, 1)
// make listener
listener, err := net.Listen("tcp", addr)
if err != nil {
log.Fatal(server, "listen error: ", err)
}
tlsString := "plaintext"
if listenTLS {
config.ClientAuth = tls.RequestClientCert
listener = tls.NewListener(listener, config)
tlsString = "TLS"
}
// throw our details to the server so we can be modified/killed later
li := ListenerInterface{
Events: listenerEventChannel,
Listener: listener,
}
server.listeners[addr] = li
// start listening
server.logger.Info("listeners", fmt.Sprintf("listening on %s using %s.", addr, tlsString))
// setup accept goroutine
go func() {
for {
conn, err := listener.Accept()
if err == nil {
newConn := clientConn{
Conn: conn,
IsTLS: listenTLS,
}
server.newConns <- newConn
}
select {
case event := <-server.listeners[addr].Events:
// this is used to confirm that whoever passed us this event has closed the existing listener correctly (in an attempt to get us to notice the event).
// this is required to keep REHASH from having a very small race possibility of killing the primary listener
server.listenerEventActMutex.Lock()
server.listenerEventActMutex.Unlock()
if event.Type == DestroyListener {
// listener should already be closed, this is just for safety
listener.Close()
return
} else if event.Type == UpdateListener {
// close old listener
listener.Close()
// make new listener
listener, err = net.Listen("tcp", addr)
if err != nil {
log.Fatal(server, "listen error: ", err)
}
tlsString := "plaintext"
if event.NewConfig != nil {
config = event.NewConfig
config.ClientAuth = tls.RequestClientCert
listener = tls.NewListener(listener, config)
tlsString = "TLS"
}
// update server ListenerInterface
li.Listener = listener
server.listenerUpdateMutex.Lock()
server.listeners[addr] = li
server.listenerUpdateMutex.Unlock()
// print notice
server.logger.Info("listeners", fmt.Sprintf("updated listener %s using %s.", addr, tlsString))
}
default:
// no events waiting for us, fall-through and continue
}
}
}()
}
//
// websocket listen goroutine
//
func (server *Server) wslisten(addr string, tlsMap map[string]*TLSListenConfig) {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
if r.Method != "GET" {
server.logger.Error("ws", addr, fmt.Sprintf("%s method not allowed", r.Method))
return
}
// We don't have any subprotocols, so if someone attempts to `new
// WebSocket(server, "subprotocol")` they'll break here, instead of
// getting the default, ambiguous, response from gorilla.
if v, ok := r.Header["Sec-Websocket-Protocol"]; ok {
http.Error(w, fmt.Sprintf("WebSocket subprocotols (e.g. %s) not supported", v), 400)
}
ws, err := upgrader.Upgrade(w, r, nil)
if err != nil {
server.logger.Error("ws", addr, fmt.Sprintf("%s websocket upgrade error: %s", server.name, err))
return
}
newConn := clientConn{
Conn: WSContainer{ws},
IsTLS: false, //TODO(dan): track TLS or not here properly
}
server.newConns <- newConn
})
go func() {
config, listenTLS := tlsMap[addr]
tlsString := "plaintext"
var err error
if listenTLS {
tlsString = "TLS"
}
server.logger.Info("listeners", fmt.Sprintf("websocket listening on %s using %s.", addr, tlsString))
if listenTLS {
err = http.ListenAndServeTLS(addr, config.Cert, config.Key, nil)
} else {
err = http.ListenAndServe(addr, nil)
}
if err != nil {
server.logger.Error("listeners", fmt.Sprintf("listenAndServe error [%s]: %s", tlsString, err))
}
}()
}
// generateMessageID returns a network-unique message ID.
func (server *Server) generateMessageID() string {
return fmt.Sprintf("%s-%s", strconv.FormatInt(time.Now().UTC().UnixNano(), 10), strconv.FormatInt(rand.Int63(), 10))
}
//
// server functionality
//
func (server *Server) tryRegister(c *Client) {
if c.registered || !c.HasNick() || !c.HasUsername() ||
(c.capState == CapNegotiating) {
return
}
// check KLINEs
isBanned, info := server.klines.CheckMasks(c.AllNickmasks()...)
if isBanned {
reason := info.Reason
if info.Time != nil {
reason += fmt.Sprintf(" [%s]", info.Time.Duration.String())
}
c.Send(nil, "", "ERROR", fmt.Sprintf("You are banned from this server (%s)", reason))
c.quitMessageSent = true
c.destroy()
return
}
// continue registration
server.logger.Debug("localconnect", fmt.Sprintf("Client registered [%s] [u:%s] [r:%s]", c.nick, c.username, c.realname))
server.snomasks.Send(sno.LocalConnects, fmt.Sprintf(ircfmt.Unescape("Client registered $c[grey][$r%s$c[grey]] [u:$r%s$c[grey]] [h:$r%s$c[grey]] [r:$r%s$c[grey]]"), c.nick, c.username, c.rawHostname, c.realname))
c.Register()
// send welcome text
//NOTE(dan): we specifically use the NICK here instead of the nickmask
// see http://modern.ircdocs.horse/#rplwelcome-001 for details on why we avoid using the nickmask
c.Send(nil, server.name, RPL_WELCOME, c.nick, fmt.Sprintf("Welcome to the Internet Relay Network %s", c.nick))
c.Send(nil, server.name, RPL_YOURHOST, c.nick, fmt.Sprintf("Your host is %s, running version %s", server.name, Ver))
c.Send(nil, server.name, RPL_CREATED, c.nick, fmt.Sprintf("This server was created %s", server.ctime.Format(time.RFC1123)))
//TODO(dan): Look at adding last optional [<channel modes with a parameter>] parameter
c.Send(nil, server.name, RPL_MYINFO, c.nick, server.name, Ver, supportedUserModesString, supportedChannelModesString)
c.RplISupport()
server.MOTD(c)
c.Send(nil, c.nickMaskString, RPL_UMODEIS, c.nick, c.ModeString())
if server.logger.DumpingRawInOut {
c.Notice("This server is in debug mode and is logging all user I/O. If you do not wish for everything you send to be readable by the server owner(s), please disconnect.")
}
}
// MOTD serves the Message of the Day.
func (server *Server) MOTD(client *Client) {
if len(server.motdLines) < 1 {
client.Send(nil, server.name, ERR_NOMOTD, client.nick, "MOTD File is missing")
return
}
client.Send(nil, server.name, RPL_MOTDSTART, client.nick, fmt.Sprintf("- %s Message of the day - ", server.name))
for _, line := range server.motdLines {
client.Send(nil, server.name, RPL_MOTD, client.nick, line)
}
client.Send(nil, server.name, RPL_ENDOFMOTD, client.nick, "End of MOTD command")
}
//
// registration commands
//
// PASS <password>
func passHandler(server *Server, client *Client, msg ircmsg.IrcMessage) bool {
if client.registered {
client.Send(nil, server.name, ERR_ALREADYREGISTRED, client.nick, "You may not reregister")
return false
}
// if no password exists, skip checking
if len(server.password) == 0 {
client.authorized = true
return false
}
// check the provided password
password := []byte(msg.Params[0])
if ComparePassword(server.password, password) != nil {
client.Send(nil, server.name, ERR_PASSWDMISMATCH, client.nick, "Password incorrect")
client.Send(nil, server.name, "ERROR", "Password incorrect")
return true
}
client.authorized = true
return false
}
// USER <username> * 0 <realname>
func userHandler(server *Server, client *Client, msg ircmsg.IrcMessage) bool {
if client.registered {
client.Send(nil, server.name, ERR_ALREADYREGISTRED, client.nick, "You may not reregister")
return false
}
if !client.authorized {
client.Quit("Bad password")
return true
}
if client.username != "" && client.realname != "" {
return false
}
// confirm that username is valid
//
_, err := CasefoldName(msg.Params[0])
if err != nil {
client.Send(nil, "", "ERROR", "Malformed username")
return true
}
if !client.HasUsername() {
client.username = "~" + msg.Params[0]
// don't bother updating nickmask here, it's not valid anyway
}
if client.realname == "" {
client.realname = msg.Params[3]
}
server.tryRegister(client)
return false
}
// QUIT [<reason>]
func quitHandler(server *Server, client *Client, msg ircmsg.IrcMessage) bool {
reason := "Quit"
if len(msg.Params) > 0 {
reason += ": " + msg.Params[0]
}
client.Quit(reason)
return true
}
//
// normal commands
//
// PING <server1> [<server2>]
func pingHandler(server *Server, client *Client, msg ircmsg.IrcMessage) bool {
client.Send(nil, server.name, "PONG", msg.Params...)
return false
}
// PONG <server> [ <server2> ]
func pongHandler(server *Server, client *Client, msg ircmsg.IrcMessage) bool {
// client gets touched when they send this command, so we don't need to do anything
return false
}
// JOIN <channel>{,<channel>} [<key>{,<key>}]
// JOIN 0
func joinHandler(server *Server, client *Client, msg ircmsg.IrcMessage) bool {
// handle JOIN 0
if msg.Params[0] == "0" {
for channel := range client.channels {
channel.Part(client, client.nickCasefolded)
}
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], ",")
}
// get lock
server.channelJoinPartMutex.Lock()
defer server.channelJoinPartMutex.Unlock()
for i, name := range channels {
casefoldedName, err := CasefoldChannel(name)
if err != nil {
if len(name) > 0 {
client.Send(nil, server.name, ERR_NOSUCHCHANNEL, client.nick, name, "No such channel")
}
continue
}
channel := server.channels.Get(casefoldedName)
if channel == nil {
if len(casefoldedName) > server.limits.ChannelLen {
client.Send(nil, server.name, ERR_NOSUCHCHANNEL, client.nick, name, "No such channel")
continue
}
channel = NewChannel(server, name, true)
}
var key string
if len(keys) > i {
key = keys[i]
}
channel.Join(client, key)
}
return false
}
// PART <channel>{,<channel>} [<reason>]
func partHandler(server *Server, client *Client, msg ircmsg.IrcMessage) bool {
channels := strings.Split(msg.Params[0], ",")
var reason string //TODO(dan): if this isn't supplied here, make sure the param doesn't exist in the PART message sent to other users
if len(msg.Params) > 1 {
reason = msg.Params[1]
}
// get lock
server.channelJoinPartMutex.Lock()
defer server.channelJoinPartMutex.Unlock()
for _, chname := range channels {
casefoldedChannelName, err := CasefoldChannel(chname)
channel := server.channels.Get(casefoldedChannelName)
if err != nil || channel == nil {
if len(chname) > 0 {
client.Send(nil, server.name, ERR_NOSUCHCHANNEL, client.nick, chname, "No such channel")
}
continue
}
channel.Part(client, reason)
}
return false
}
// TOPIC <channel> [<topic>]
func topicHandler(server *Server, client *Client, msg ircmsg.IrcMessage) bool {
name, err := CasefoldChannel(msg.Params[0])
channel := server.channels.Get(name)
if err != nil || channel == nil {
if len(msg.Params[0]) > 0 {
client.Send(nil, server.name, ERR_NOSUCHCHANNEL, client.nick, msg.Params[0], "No such channel")
}
return false
}
if len(msg.Params) > 1 {
channel.SetTopic(client, msg.Params[1])
} else {
channel.GetTopic(client)
}
return false
}
// wordWrap wraps the given text into a series of lines that don't exceed lineWidth characters.
func wordWrap(text string, lineWidth int) []string {
var lines []string
var cacheLine, cacheWord string
for _, char := range text {
if char == '\r' {
continue
} else if char == '\n' {
cacheLine += cacheWord
lines = append(lines, cacheLine)
cacheWord = ""
cacheLine = ""
} else if (char == ' ' || char == '-') && len(cacheLine)+len(cacheWord)+1 < lineWidth {
// natural word boundary
cacheLine += cacheWord + string(char)
cacheWord = ""
} else if lineWidth <= len(cacheLine)+len(cacheWord)+1 {
// time to wrap to next line
if len(cacheLine) < (lineWidth / 2) {
// this word takes up more than half a line... just split in the middle of the word
cacheLine += cacheWord + string(char)
cacheWord = ""
} else {
cacheWord += string(char)
}
lines = append(lines, cacheLine)
cacheLine = ""
} else {
// normal character
cacheWord += string(char)
}
}
if 0 < len(cacheWord) {
cacheLine += cacheWord
}
if 0 < len(cacheLine) {
lines = append(lines, cacheLine)
}
return lines
}
// SplitMessage represents a message that's been split for sending.
type SplitMessage struct {
For512 []string
ForMaxLine string
}
func (server *Server) splitMessage(original string, origIs512 bool) SplitMessage {
var newSplit SplitMessage
newSplit.ForMaxLine = original
if !origIs512 {
newSplit.For512 = wordWrap(original, 400)
} else {
newSplit.For512 = []string{original}
}
return newSplit
}
// PRIVMSG <target>{,<target>} <message>
func privmsgHandler(server *Server, client *Client, msg ircmsg.IrcMessage) bool {
clientOnlyTags := GetClientOnlyTags(msg.Tags)
targets := strings.Split(msg.Params[0], ",")
message := msg.Params[1]
// split privmsg
splitMsg := server.splitMessage(message, !client.capabilities[MaxLine])
for i, targetString := range targets {
// max of four targets per privmsg
if i > maxTargets-1 {
break
}
prefixes, targetString := SplitChannelMembershipPrefixes(targetString)
lowestPrefix := GetLowestChannelModePrefix(prefixes)
// eh, no need to notify them
if len(targetString) < 1 {
continue
}
target, err := CasefoldChannel(targetString)
if err == nil {
channel := server.channels.Get(target)
if channel == nil {
client.Send(nil, server.name, ERR_NOSUCHCHANNEL, client.nick, targetString, "No such channel")
continue
}
if !channel.CanSpeak(client) {
client.Send(nil, client.server.name, ERR_CANNOTSENDTOCHAN, channel.name, "Cannot send to channel")
continue
}
msgid := server.generateMessageID()
channel.SplitPrivMsg(msgid, lowestPrefix, clientOnlyTags, client, splitMsg)
} else {
target, err = CasefoldName(targetString)
if target == "chanserv" {
server.chanservReceivePrivmsg(client, message)
continue
} else if target == "nickserv" {
server.nickservReceivePrivmsg(client, message)
continue
}
user := server.clients.Get(target)
if err != nil || user == nil {
if len(target) > 0 {
client.Send(nil, server.name, ERR_NOSUCHNICK, target, "No such nick")
}