forked from ergochat/ergo
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.go
More file actions
1875 lines (1638 loc) · 56.9 KB
/
client.go
File metadata and controls
1875 lines (1638 loc) · 56.9 KB
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 (
"crypto/x509"
"fmt"
"maps"
"net"
"runtime/debug"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
ident "github.com/ergochat/go-ident"
"github.com/ergochat/irc-go/ircfmt"
"github.com/ergochat/irc-go/ircmsg"
"github.com/ergochat/irc-go/ircreader"
"github.com/ergochat/irc-go/ircutils"
"github.com/xdg-go/scram"
"github.com/ergochat/ergo/irc/caps"
"github.com/ergochat/ergo/irc/connection_limits"
"github.com/ergochat/ergo/irc/flatip"
"github.com/ergochat/ergo/irc/history"
"github.com/ergochat/ergo/irc/modes"
"github.com/ergochat/ergo/irc/oauth2"
"github.com/ergochat/ergo/irc/sno"
"github.com/ergochat/ergo/irc/utils"
)
const (
// maximum IRC line length, not including tags
DefaultMaxLineLen = 512
// IdentTimeout is how long before our ident (username) check times out.
IdentTimeout = time.Second + 500*time.Millisecond
IRCv3TimestampFormat = utils.IRCv3TimestampFormat
// limit the number of device IDs a client can use, as a DoS mitigation
maxDeviceIDsPerClient = 64
// maximum total read markers that can be stored
// (writeback of read markers is controlled by lastSeen logic)
maxReadMarkers = 256
)
const (
// RegisterTimeout is how long clients have to register before we disconnect them
RegisterTimeout = time.Minute
// DefaultIdleTimeout is how long without traffic before we send the client a PING
DefaultIdleTimeout = time.Minute + 30*time.Second
// For Tor clients, we send a PING at least every 30 seconds, as a workaround for this bug
// (single-onion circuits will close unless the client sends data once every 60 seconds):
// https://bugs.torproject.org/29665
TorIdleTimeout = time.Second * 30
// This is how long a client gets without sending any message, including the PONG to our
// PING, before we disconnect them:
DefaultTotalTimeout = 2*time.Minute + 30*time.Second
// round off the ping interval by this much, see below:
PingCoalesceThreshold = time.Second
)
var (
MaxLineLen = DefaultMaxLineLen
)
// Client is an IRC client.
type Client struct {
account string
accountName string // display name of the account: uncasefolded, '*' if not logged in
accountRegDate time.Time
accountSettings AccountSettings
awayMessage string
channels ChannelSet
ctime time.Time
destroyed bool
modes modes.ModeSet
hostname string
invitedTo map[string]channelInvite
isSTSOnly bool
isKlined bool // #1941: k-line kills are special-cased to suppress some triggered notices/events
languages []string
lastActive time.Time // last time they sent a command that wasn't PONG or similar
lastSeen map[string]time.Time // maps device ID (including "") to time of last received command
readMarkers map[string]time.Time // maps casefolded target to time of last read marker
loginThrottle connection_limits.GenericThrottle
nextSessionID int64 // Incremented when a new session is established
nick string
nickCasefolded string
nickMaskCasefolded string
nickMaskString string // cache for nickmask string since it's used with lots of replies
oper *Oper
preregNick string
proxiedIP net.IP // actual remote IP if using the PROXY protocol
rawHostname string
cloakedHostname string
realname string
realIP net.IP
requireSASLMessage string
requireSASL bool
registered bool
registerCmdSent bool // already sent the draft/register command, can't send it again
dirtyTimestamps bool // lastSeen or readMarkers is dirty
registrationTimer *time.Timer
server *Server
skeleton string
sessions []*Session
stateMutex sync.RWMutex // tier 1
alwaysOn bool
username string
vhost string
history history.Buffer
dirtyBits uint
writebackLock sync.Mutex // tier 1.5
}
type saslStatus struct {
mechanism string
value ircutils.SASLBuffer
scramConv *scram.ServerConversation
oauthConv *oauth2.OAuthBearerServer
}
func (s *saslStatus) Initialize() {
s.value.Initialize(saslMaxResponseLength)
}
func (s *saslStatus) Clear() {
s.mechanism = ""
s.value.Clear()
s.scramConv = nil
s.oauthConv = nil
}
// what stage the client is at w.r.t. the PASS command:
type serverPassStatus uint
const (
serverPassUnsent serverPassStatus = iota
serverPassSuccessful
serverPassFailed
)
// Session is an individual client connection to the server (TCP connection
// and associated per-connection data, such as capabilities). There is a
// many-one relationship between sessions and clients.
type Session struct {
client *Client
deviceID string
ctime time.Time
lastActive time.Time // last non-CTCP PRIVMSG sent; updates publicly visible idle time
lastTouch time.Time // last line sent; updates timer for idle timeouts
idleTimer *time.Timer
pingSent bool // we sent PING to a putatively idle connection and we're waiting for PONG
sessionID int64
socket *Socket
realIP net.IP
proxiedIP net.IP
rawHostname string
hostnameFinalized bool
isTor bool
hideSTS bool
fakelag Fakelag
deferredFakelagCount int
certfp string
peerCerts []*x509.Certificate
sasl saslStatus
passStatus serverPassStatus
batchCounter atomic.Uint32
isupportSentPrereg bool
quitMessage string
awayMessage string
awayAt time.Time
capabilities caps.Set
capState caps.State
capVersion caps.Version
registrationMessages int
zncPlaybackTimes *zncPlaybackTimes
autoreplayMissedSince time.Time
batch MultilineBatch
}
// MultilineBatch tracks the state of a client-to-server multiline batch.
type MultilineBatch struct {
label string // this is the first param to BATCH (the "reference tag")
command string
target string
responseLabel string // this is the value of the labeled-response tag sent with BATCH
message utils.SplitMessage
lenBytes int
tags map[string]string
}
// Starts a multiline batch, failing if there's one already open
func (s *Session) StartMultilineBatch(label, target, responseLabel string, tags map[string]string) (err error) {
if s.batch.label != "" {
return errInvalidMultilineBatch
}
s.batch.label, s.batch.target, s.batch.responseLabel, s.batch.tags = label, target, responseLabel, tags
s.fakelag.Suspend()
return
}
// Closes a multiline batch unconditionally; returns the batch and whether
// it was validly terminated (pass "" as the label if you don't care about the batch)
func (s *Session) EndMultilineBatch(label string) (batch MultilineBatch, err error) {
batch = s.batch
s.batch = MultilineBatch{}
s.fakelag.Unsuspend()
// heuristics to estimate how much data they used while fakelag was suspended
fakelagBill := (batch.lenBytes / MaxLineLen) + 1
fakelagBillLines := (batch.message.LenLines() * 60) / MaxLineLen
if fakelagBill < fakelagBillLines {
fakelagBill = fakelagBillLines
}
s.deferredFakelagCount = fakelagBill
if batch.label == "" || batch.label != label || !batch.message.ValidMultiline() {
err = errInvalidMultilineBatch
return
}
batch.message.SetTime()
return
}
// sets the session quit message, if there isn't one already
func (sd *Session) setQuitMessage(message string) (set bool) {
if message == "" {
message = "Connection closed"
}
if sd.quitMessage == "" {
sd.quitMessage = message
return true
} else {
return false
}
}
func (s *Session) IP() net.IP {
if s.proxiedIP != nil {
return s.proxiedIP
}
return s.realIP
}
// returns whether the client supports a smart history replay cap,
// and therefore autoreplay-on-join and similar should be suppressed
func (session *Session) HasHistoryCaps() bool {
return session.capabilities.Has(caps.Chathistory) || session.capabilities.Has(caps.ZNCPlayback)
}
// generates a batch ID. the uniqueness requirements for this are fairly weak:
// any two batch IDs that are active concurrently (either through interleaving
// or nesting) on an individual session connection need to be unique.
// this allows ~4 billion such batches which should be fine.
func (session *Session) generateBatchID() string {
id := session.batchCounter.Add(1)
return strconv.FormatInt(int64(id), 32)
}
// WhoWas is the subset of client details needed to answer a WHOWAS query
type WhoWas struct {
nick string
nickCasefolded string
username string
hostname string
realname string
ip net.IP
// technically not required for WHOWAS:
account string
accountName string
}
// ClientDetails is a standard set of details about a client
type ClientDetails struct {
WhoWas
nickMask string
nickMaskCasefolded string
}
// RunClient sets up a new client and runs its goroutine.
func (server *Server) RunClient(conn IRCConn) {
config := server.Config()
wConn := conn.UnderlyingConn()
var isBanned, requireSASL bool
var banMsg string
realIP := utils.AddrToIP(wConn.RemoteAddr())
var proxiedIP net.IP
if wConn.Tor {
// cover up details of the tor proxying infrastructure (not a user privacy concern,
// but a hardening measure):
proxiedIP = utils.IPv4LoopbackAddress
isBanned, banMsg = server.checkTorLimits()
} else {
ipToCheck := realIP
if wConn.ProxiedIP != nil {
proxiedIP = wConn.ProxiedIP
ipToCheck = proxiedIP
}
// XXX only run the check script now if the IP cannot be replaced by PROXY or WEBIRC,
// otherwise we'll do it in ApplyProxiedIP.
checkScripts := proxiedIP != nil || !utils.IPInNets(realIP, config.Server.proxyAllowedFromNets)
isBanned, requireSASL, banMsg = server.checkBans(config, ipToCheck, checkScripts)
}
if isBanned {
// this might not show up properly on some clients,
// but our objective here is just to close the connection out before it has a load impact on us
conn.WriteLine([]byte(fmt.Sprintf(errorMsg, banMsg)))
conn.Close()
return
}
server.logger.Info("connect-ip", fmt.Sprintf("Client connecting: real IP %v, proxied IP %v", realIP, proxiedIP))
now := time.Now().UTC()
// give them 1k of grace over the limit:
socket := NewSocket(conn, config.Server.MaxSendQBytes)
client := &Client{
lastActive: now,
channels: make(ChannelSet),
ctime: now,
isSTSOnly: wConn.STSOnly,
languages: server.Languages().Default(),
loginThrottle: connection_limits.GenericThrottle{
Duration: config.Accounts.LoginThrottling.Duration,
Limit: config.Accounts.LoginThrottling.MaxAttempts,
},
server: server,
accountName: "*",
nick: "*", // * is used until actual nick is given
nickCasefolded: "*",
nickMaskString: "*", // * is used until actual nick is given
realIP: realIP,
proxiedIP: proxiedIP,
requireSASL: requireSASL,
nextSessionID: 1,
}
if requireSASL {
client.requireSASLMessage = banMsg
}
client.history.Initialize(config.History.ClientLength, time.Duration(config.History.AutoresizeWindow))
session := &Session{
client: client,
socket: socket,
capVersion: caps.Cap301,
capState: caps.NoneState,
ctime: now,
lastActive: now,
realIP: realIP,
proxiedIP: proxiedIP,
isTor: wConn.Tor,
hideSTS: wConn.Tor || wConn.HideSTS,
}
session.sasl.Initialize()
client.sessions = []*Session{session}
session.resetFakelag()
if wConn.Secure {
client.SetMode(modes.TLS, true)
}
if wConn.TLS {
// error is not useful to us here anyways so we can ignore it
session.certfp, session.peerCerts, _ = utils.GetCertFP(wConn.Conn, RegisterTimeout)
}
if session.isTor {
session.rawHostname = config.Server.TorListeners.Vhost
client.rawHostname = session.rawHostname
} else {
if config.Server.CheckIdent {
client.doIdentLookup(wConn.Conn)
}
}
client.registrationTimer = time.AfterFunc(RegisterTimeout, client.handleRegisterTimeout)
server.stats.Add()
client.run(session)
}
func (server *Server) AddAlwaysOnClient(account ClientAccount, channelToStatus map[string]alwaysOnChannelStatus, lastSeen, readMarkers map[string]time.Time, uModes modes.Modes, realname string) {
now := time.Now().UTC()
config := server.Config()
if lastSeen == nil && account.Settings.AutoreplayMissed {
lastSeen = map[string]time.Time{"": now}
}
rawHostname, cloakedHostname := server.name, ""
if config.Server.Cloaks.EnabledForAlwaysOn {
cloakedHostname = config.Server.Cloaks.ComputeAccountCloak(account.Name)
}
username := "~u"
if config.Server.CoerceIdent != "" {
username = config.Server.CoerceIdent
}
client := &Client{
lastSeen: lastSeen,
readMarkers: readMarkers,
lastActive: now,
channels: make(ChannelSet),
ctime: now,
languages: server.Languages().Default(),
server: server,
username: username,
cloakedHostname: cloakedHostname,
rawHostname: rawHostname,
realIP: utils.IPv4LoopbackAddress,
alwaysOn: true,
realname: realname,
nextSessionID: 1,
}
if client.checkAlwaysOnExpirationNoMutex(config, true) {
server.logger.Debug("accounts", "always-on client not created due to expiration", account.Name)
return
}
client.SetMode(modes.TLS, true)
for _, m := range uModes {
client.SetMode(m, true)
}
client.history.Initialize(0, 0)
server.accounts.Login(client, account)
client.resizeHistory(config)
_, err, _ := server.clients.SetNick(client, nil, account.Name, false)
if err != nil {
server.logger.Error("internal", "could not establish always-on client", account.Name, err.Error())
return
} else {
server.logger.Debug("accounts", "established always-on client", account.Name)
}
// XXX set this last to avoid confusing SetNick:
client.registered = true
for chname, status := range channelToStatus {
// XXX we're using isSajoin=true, to make these joins succeed even without channel key
// this is *probably* ok as long as the persisted memberships are accurate
server.channels.Join(client, chname, "", true, nil)
if channel := server.channels.Get(chname); channel != nil {
channel.setMemberStatus(client, status)
} else {
server.logger.Error("internal", "could not create channel", chname)
}
}
if persistenceEnabled(config.Accounts.Multiclient.AutoAway, client.accountSettings.AutoAway) {
client.setAutoAwayNoMutex(config)
}
}
func (client *Client) resizeHistory(config *Config) {
status, _ := client.historyStatus(config)
if status == HistoryEphemeral {
client.history.Resize(config.History.ClientLength, time.Duration(config.History.AutoresizeWindow))
} else {
client.history.Resize(0, 0)
}
}
// once we have the final IP address (from the connection itself or from proxy data),
// compute the various possibilities for the hostname:
// * In the default/recommended configuration, via the cloak algorithm
// * If hostname lookup is enabled, via (forward-confirmed) reverse DNS
// * If WEBIRC was used, possibly via the hostname passed on the WEBIRC line
func (client *Client) finalizeHostname(session *Session) {
// only allow this once, since registration can fail (e.g. if the nickname is in use)
if session.hostnameFinalized {
return
}
session.hostnameFinalized = true
if session.isTor {
return
}
config := client.server.Config()
ip := session.realIP
if session.proxiedIP != nil {
ip = session.proxiedIP
}
// even if cloaking is enabled, we may want to look up the real hostname to show to operators:
if session.rawHostname == "" {
var hostname string
lookupSuccessful := false
if config.Server.lookupHostnames {
session.Notice("*** Looking up your hostname...")
hostname, lookupSuccessful = utils.LookupHostname(ip, config.Server.ForwardConfirmHostnames)
if lookupSuccessful {
session.Notice("*** Found your hostname")
} else {
session.Notice("*** Couldn't look up your hostname")
}
} else {
hostname = utils.IPStringToHostname(ip.String())
}
session.rawHostname = hostname
}
// these will be discarded if this is actually a reattach:
client.rawHostname = session.rawHostname
client.cloakedHostname = config.Server.Cloaks.ComputeCloak(ip)
}
func (client *Client) doIdentLookup(conn net.Conn) {
localTCPAddr, ok := conn.LocalAddr().(*net.TCPAddr)
if !ok {
return
}
serverPort := localTCPAddr.Port
remoteTCPAddr, ok := conn.RemoteAddr().(*net.TCPAddr)
if !ok {
return
}
clientPort := remoteTCPAddr.Port
client.Notice(client.t("*** Looking up your username"))
resp, err := ident.Query(remoteTCPAddr.IP.String(), serverPort, clientPort, IdentTimeout)
if err == nil {
err := client.SetNames(resp.Identifier, "", true)
if err == nil {
client.Notice(client.t("*** Found your username"))
// we don't need to updateNickMask here since nickMask is not used for anything yet
} else {
client.Notice(client.t("*** Got a malformed username, ignoring"))
}
} else {
client.Notice(client.t("*** Could not find your username"))
}
}
type AuthOutcome uint
const (
authSuccess AuthOutcome = iota
authFailPass
authFailTorSaslRequired
authFailSaslRequired
)
func (client *Client) isAuthorized(server *Server, config *Config, session *Session, forceRequireSASL bool) AuthOutcome {
saslSent := client.account != ""
// PASS requirement
if (config.Server.passwordBytes != nil) && session.passStatus != serverPassSuccessful && !(config.Accounts.SkipServerPassword && saslSent) {
return authFailPass
}
// Tor connections may be required to authenticate with SASL
if session.isTor && !saslSent && (config.Server.TorListeners.RequireSasl || server.Defcon() <= 4) {
return authFailTorSaslRequired
}
// finally, enforce require-sasl
if !saslSent && (forceRequireSASL || config.Accounts.RequireSasl.Enabled || server.Defcon() <= 2) &&
!utils.IPInNets(session.IP(), config.Accounts.RequireSasl.exemptedNets) {
return authFailSaslRequired
}
return authSuccess
}
func (session *Session) resetFakelag() {
var flc FakelagConfig = session.client.server.Config().Fakelag
flc.Enabled = flc.Enabled && !session.client.HasRoleCapabs("nofakelag")
session.fakelag.Initialize(flc)
}
// IP returns the IP address of this client.
func (client *Client) IP() net.IP {
client.stateMutex.RLock()
defer client.stateMutex.RUnlock()
return client.getIPNoMutex()
}
func (client *Client) getIPNoMutex() net.IP {
if client.proxiedIP != nil {
return client.proxiedIP
}
return client.realIP
}
// IPString returns the IP address of this client as a string.
func (client *Client) IPString() string {
return utils.IPStringToHostname(client.IP().String())
}
// t returns the translated version of the given string, based on the languages configured by the client.
func (client *Client) t(originalString string) string {
languageManager := client.server.Config().languageManager
if !languageManager.Enabled() {
return originalString
}
return languageManager.Translate(client.Languages(), originalString)
}
// main client goroutine: read lines and execute the corresponding commands
// `proxyLine` is the PROXY-before-TLS line, if there was one
func (client *Client) run(session *Session) {
defer func() {
if r := recover(); r != nil {
client.server.logger.Error("internal",
fmt.Sprintf("Client caused panic: %v\n%s", r, debug.Stack()))
if client.server.Config().Debug.recoverFromErrors {
client.server.logger.Error("internal", "Disconnecting client and attempting to recover")
} else {
panic(r)
}
}
// ensure client connection gets closed
client.destroy(session)
}()
isReattach := client.Registered()
if isReattach {
client.Touch(session)
client.playReattachMessages(session)
}
firstLine := !isReattach
for {
var invalidUtf8 bool
line, err := session.socket.Read()
if err == errInvalidUtf8 {
invalidUtf8 = true // handle as normal, including labeling
} else if err != nil {
client.server.logger.Debug("connect-ip", "read error from client", err.Error())
var quitMessage string
switch err {
case ircreader.ErrReadQ:
quitMessage = err.Error()
default:
quitMessage = "connection closed"
}
client.Quit(quitMessage, session)
break
}
if client.server.logger.IsLoggingRawIO() {
client.server.logger.Debug("userinput", client.nick, "<- ", line)
}
// special-cased handling of PROXY protocol, see `handleProxyCommand` for details:
if firstLine {
firstLine = false
if strings.HasPrefix(line, "PROXY") {
err = handleProxyCommand(client.server, client, session, line)
if err != nil {
break
} else {
continue
}
}
}
msg, err := ircmsg.ParseLineStrict(line, true, MaxLineLen)
// XXX defer processing of command error parsing until after fakelag
if client.registered {
// apply deferred fakelag
for i := 0; i < session.deferredFakelagCount; i++ {
session.fakelag.Touch("")
}
session.deferredFakelagCount = 0
// touch for the current command
var command string
if err == nil {
command = msg.Command
}
session.fakelag.Touch(command)
} else {
// DoS hardening, #505
session.registrationMessages++
if client.server.Config().Limits.RegistrationMessages < session.registrationMessages {
client.Send(nil, client.server.name, ERR_UNKNOWNERROR, "*", client.t("You have sent too many registration messages"))
break
}
}
if err == ircmsg.ErrorLineIsEmpty {
continue
} else if err == ircmsg.ErrorTagsTooLong {
session.Send(nil, client.server.name, ERR_INPUTTOOLONG, client.Nick(), client.t("Input line contained excess tag data"))
continue
} else if err == ircmsg.ErrorBodyTooLong {
if !client.server.Config().Server.Compatibility.allowTruncation {
session.Send(nil, client.server.name, ERR_INPUTTOOLONG, client.Nick(), client.t("Input line too long"))
continue
} // else: proceed with the truncated line
} else if err != nil {
client.Quit(client.t("Received malformed line"), session)
break
}
cmd, exists := Commands[msg.Command]
if !exists {
cmd = unknownCommand
} else if invalidUtf8 {
cmd = invalidUtf8Command
}
isExiting := cmd.Run(client.server, client, session, msg)
if isExiting {
break
} else if session.client != client {
// bouncer reattach
go session.client.run(session)
break
}
}
}
func (client *Client) playReattachMessages(session *Session) {
client.server.playRegistrationBurst(session)
hasHistoryCaps := session.HasHistoryCaps()
for _, channel := range session.client.Channels() {
channel.playJoinForSession(session)
// clients should receive autoreplay-on-join lines, if applicable:
if hasHistoryCaps {
continue
}
// if they negotiated znc.in/playback or chathistory, they will receive nothing,
// because those caps disable autoreplay-on-join and they haven't sent the relevant
// *playback PRIVMSG or CHATHISTORY command yet
rb := NewResponseBuffer(session)
channel.autoReplayHistory(client, rb, "")
rb.Send(true)
}
if !session.autoreplayMissedSince.IsZero() && !hasHistoryCaps {
rb := NewResponseBuffer(session)
zncPlayPrivmsgsFromAll(client, rb, time.Now().UTC(), session.autoreplayMissedSince)
rb.Send(true)
}
session.autoreplayMissedSince = time.Time{}
}
//
// idle, quit, timers and timeouts
//
// Touch indicates that we received a line from the client (so the connection is healthy
// at this time, modulo network latency and fakelag).
func (client *Client) Touch(session *Session) {
now := time.Now().UTC()
client.stateMutex.Lock()
if client.registered {
client.updateIdleTimer(session, now)
if client.alwaysOn {
client.setLastSeen(now, session.deviceID)
client.dirtyTimestamps = true
}
}
client.stateMutex.Unlock()
}
func (client *Client) setLastSeen(now time.Time, deviceID string) {
if client.lastSeen == nil {
client.lastSeen = make(map[string]time.Time)
}
updateLRUMap(client.lastSeen, deviceID, now, maxDeviceIDsPerClient)
}
func (client *Client) updateIdleTimer(session *Session, now time.Time) {
session.lastTouch = now
session.pingSent = false
if session.idleTimer == nil {
pingTimeout := DefaultIdleTimeout
if session.isTor {
pingTimeout = TorIdleTimeout
}
session.idleTimer = time.AfterFunc(pingTimeout, session.handleIdleTimeout)
}
}
func (session *Session) handleIdleTimeout() {
totalTimeout := DefaultTotalTimeout
pingTimeout := DefaultIdleTimeout
if session.isTor {
pingTimeout = TorIdleTimeout
}
session.client.stateMutex.Lock()
now := time.Now()
timeUntilDestroy := session.lastTouch.Add(totalTimeout).Sub(now)
timeUntilPing := session.lastTouch.Add(pingTimeout).Sub(now)
shouldDestroy := session.pingSent && timeUntilDestroy <= 0
// XXX this should really be time <= 0, but let's do some hacky timer coalescing:
// a typical idling client will do nothing other than respond immediately to our pings,
// so we'll PING at t=0, they'll respond at t=0.05, then we'll wake up at t=90 and find
// that we need to PING again at t=90.05. Rather than wake up again, just send it now:
shouldSendPing := !session.pingSent && timeUntilPing <= PingCoalesceThreshold
if !shouldDestroy {
if shouldSendPing {
session.pingSent = true
}
// check in again at the minimum of these 3 possible intervals:
// 1. the ping timeout (assuming we PING and they reply immediately with PONG)
// 2. the next time we would send PING (if they don't send any more lines)
// 3. the next time we would destroy (if they don't send any more lines)
nextTimeout := pingTimeout
if PingCoalesceThreshold < timeUntilPing && timeUntilPing < nextTimeout {
nextTimeout = timeUntilPing
}
if 0 < timeUntilDestroy && timeUntilDestroy < nextTimeout {
nextTimeout = timeUntilDestroy
}
session.idleTimer.Stop()
session.idleTimer.Reset(nextTimeout)
}
session.client.stateMutex.Unlock()
if shouldDestroy {
session.client.Quit(fmt.Sprintf("Ping timeout: %v", totalTimeout), session)
session.client.destroy(session)
} else if shouldSendPing {
session.Ping()
}
}
func (session *Session) stopIdleTimer() {
session.client.stateMutex.Lock()
defer session.client.stateMutex.Unlock()
if session.idleTimer != nil {
session.idleTimer.Stop()
}
}
// Ping sends the client a PING message.
func (session *Session) Ping() {
session.Send(nil, "", "PING", session.client.Nick())
}
func (client *Client) replayPrivmsgHistory(rb *ResponseBuffer, items []history.Item, target string, chathistoryCommand bool) {
var batchID string
details := client.Details()
nick := details.nick
if target == "" {
target = nick
}
batchID = rb.StartNestedBatch("chathistory", target)
isSelfMessage := func(item *history.Item) bool {
// XXX: Params[0] is the message target. if the source of this message is an in-memory
// buffer, then it's "" for an incoming message and the recipient's nick for an outgoing
// message. if the source of the message is mysql, then mysql only sees one copy of the
// message, and it's the version with the recipient's nick filled in. so this is an
// incoming message if Params[0] (the recipient's nick) equals the client's nick:
return item.Params[0] != "" && item.Params[0] != nick
}
hasEventPlayback := rb.session.capabilities.Has(caps.EventPlayback)
hasTags := rb.session.capabilities.Has(caps.MessageTags)
for _, item := range items {
var command string
switch item.Type {
case history.Invite:
if isSelfMessage(&item) {
continue
}
if hasEventPlayback {
rb.AddFromClient(item.Message.Time, item.Message.Msgid, item.Nick, item.AccountName, item.IsBot, nil, "INVITE", nick, item.Message.Message)
} else {
rb.AddFromClient(item.Message.Time, history.HistservMungeMsgid(item.Message.Msgid), histservService.prefix, "*", false, nil, "PRIVMSG", fmt.Sprintf(client.t("%[1]s invited you to channel %[2]s"), NUHToNick(item.Nick), item.Message.Message))
}
continue
case history.Privmsg:
command = "PRIVMSG"
case history.Notice:
command = "NOTICE"
case history.Tagmsg:
if hasEventPlayback && hasTags {
command = "TAGMSG"
} else if chathistoryCommand {
// #1676: send something for TAGMSG; we can't discard it entirely
// because it'll break pagination
rb.AddFromClient(item.Message.Time, history.HistservMungeMsgid(item.Message.Msgid), histservService.prefix, "*", false, nil, "PRIVMSG", fmt.Sprintf(client.t("%[1]s sent you a TAGMSG"), NUHToNick(item.Nick)))
} else {
continue
}
default:
// see #1676, this shouldn't happen
continue
}
var tags map[string]string
if hasTags {
tags = item.Tags
}
if !isSelfMessage(&item) {
rb.AddSplitMessageFromClient(item.Nick, item.AccountName, item.IsBot, tags, command, nick, item.Message)
} else {
// this message was sent *from* the client to another nick; the target is item.Params[0]
// substitute client's current nickmask in case client changed nick
rb.AddSplitMessageFromClient(details.nickMask, item.AccountName, item.IsBot, tags, command, item.Params[0], item.Message)
}
}
rb.EndNestedBatch(batchID)
}
// IdleTime returns how long this client's been idle.
func (client *Client) IdleTime() time.Duration {
client.stateMutex.RLock()
defer client.stateMutex.RUnlock()
return time.Since(client.lastActive)
}
// SignonTime returns this client's signon time as a unix timestamp.
func (client *Client) SignonTime() int64 {
return client.ctime.Unix()
}
// IdleSeconds returns the number of seconds this client's been idle.
func (client *Client) IdleSeconds() uint64 {
return uint64(client.IdleTime().Seconds())
}
// SetNames sets the client's ident and realname.
func (client *Client) SetNames(username, realname string, fromIdent bool) error {
config := client.server.Config()
limit := config.Limits.IdentLen
if !fromIdent {
limit -= 1 // leave room for the prepended ~
}
if limit < len(username) {
username = username[:limit]
}
if !isIdent(username) {
return errInvalidUsername
}
if config.Server.CoerceIdent != "" {
username = config.Server.CoerceIdent
} else if !fromIdent {
username = "~" + username
}
client.stateMutex.Lock()
defer client.stateMutex.Unlock()
if client.username == "" {
client.username = username
}
if client.realname == "" {
client.realname = realname
}
return nil
}
// HasRoleCapabs returns true if client has the given (role) capabilities.
func (client *Client) HasRoleCapabs(capabs ...string) bool {
oper := client.Oper()
if oper == nil {
return false
}
for _, capab := range capabs {
if !oper.Class.Capabilities.Has(capab) {
return false
}
}
return true
}