-
Notifications
You must be signed in to change notification settings - Fork 176
/
client.go
1293 lines (1129 loc) · 38.8 KB
/
client.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 (
"fmt"
"net"
"runtime/debug"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/goshuirc/irc-go/ircfmt"
"github.com/goshuirc/irc-go/ircmsg"
ident "github.com/oragono/go-ident"
"github.com/oragono/oragono/irc/caps"
"github.com/oragono/oragono/irc/connection_limits"
"github.com/oragono/oragono/irc/history"
"github.com/oragono/oragono/irc/modes"
"github.com/oragono/oragono/irc/sno"
"github.com/oragono/oragono/irc/utils"
)
const (
// IdentTimeoutSeconds is how many seconds before our ident (username) check times out.
IdentTimeoutSeconds = 1.5
IRCv3TimestampFormat = "2006-01-02T15:04:05.000Z"
)
// ResumeDetails is a place to stash data at various stages of
// the resume process: when handling the RESUME command itself,
// when completing the registration, and when rejoining channels.
type ResumeDetails struct {
PresentedToken string
Timestamp time.Time
HistoryIncomplete bool
}
// Client is an IRC client.
type Client struct {
account string
accountName string // display name of the account: uncasefolded, '*' if not logged in
accountSettings AccountSettings
atime time.Time
away bool
awayMessage string
brbTimer BrbTimer
certfp string
channels ChannelSet
ctime time.Time
destroyed bool
exitedSnomaskSent bool
flags modes.ModeSet
hostname string
invitedTo map[string]bool
isTor bool
languages []string
loginThrottle connection_limits.GenericThrottle
nick string
nickCasefolded string
nickMaskCasefolded string
nickMaskString string // cache for nickmask string since it's used with lots of replies
nickTimer NickTimer
oper *Oper
preregNick string
proxiedIP net.IP // actual remote IP if using the PROXY protocol
rawHostname string
cloakedHostname string
realname string
realIP net.IP
registered bool
resumeID string
saslInProgress bool
saslMechanism string
saslValue string
sentPassCommand bool
server *Server
skeleton string
sessions []*Session
stateMutex sync.RWMutex // tier 1
username string
vhost string
history history.Buffer
}
// 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
ctime time.Time
atime time.Time
socket *Socket
realIP net.IP
proxiedIP net.IP
rawHostname string
idletimer IdleTimer
fakelag Fakelag
destroyed uint32
quitMessage string
capabilities caps.Set
maxlenRest uint32
capState caps.State
capVersion caps.Version
registrationMessages int
resumeID string
resumeDetails *ResumeDetails
zncPlaybackTimes *zncPlaybackTimes
}
// 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
}
}
// set the negotiated message length based on session capabilities
func (session *Session) SetMaxlenRest() {
maxlenRest := 512
if session.capabilities.Has(caps.MaxLine) {
maxlenRest = session.client.server.Config().Limits.LineLen.Rest
}
atomic.StoreUint32(&session.maxlenRest, uint32(maxlenRest))
}
// allow the negotiated message length limit to be read without locks; this is a convenience
// so that Session.SendRawMessage doesn't have to acquire any Client locks
func (session *Session) MaxlenRest() int {
return int(atomic.LoadUint32(&session.maxlenRest))
}
// returns whether the session was actively destroyed (for example, by ping
// timeout or NS GHOST).
// avoids a race condition between asynchronous idle-timing-out of sessions,
// and a condition that allows implicit BRB on connection errors (since
// destroy()'s socket.Close() appears to socket.Read() as a connection error)
func (session *Session) Destroyed() bool {
return atomic.LoadUint32(&session.destroyed) == 1
}
// sets the timed-out flag
func (session *Session) SetDestroyed() {
atomic.StoreUint32(&session.destroyed, 1)
}
// 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 {
// TODO the chathistory cap will go here as well
return session.capabilities.Has(caps.ZNCPlayback)
}
// 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
}
// ClientDetails is a standard set of details about a client
type ClientDetails struct {
WhoWas
nickMask string
nickMaskCasefolded string
account string
accountName string
}
// RunClient sets up a new client and runs its goroutine.
func (server *Server) RunClient(conn clientConn) {
var isBanned bool
var banMsg string
var realIP net.IP
if conn.IsTor {
realIP = utils.IPv4LoopbackAddress
isBanned, banMsg = server.checkTorLimits()
} else {
realIP = utils.AddrToIP(conn.Conn.RemoteAddr())
isBanned, banMsg = server.checkBans(realIP)
}
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.Conn.Write([]byte(fmt.Sprintf(errorMsg, banMsg)))
conn.Conn.Close()
return
}
server.logger.Info("localconnect-ip", fmt.Sprintf("Client connecting from %v", realIP))
now := time.Now().UTC()
config := server.Config()
fullLineLenLimit := ircmsg.MaxlenTagsFromClient + config.Limits.LineLen.Rest
// give them 1k of grace over the limit:
socket := NewSocket(conn.Conn, fullLineLenLimit+1024, config.Server.MaxSendQBytes)
client := &Client{
atime: now,
channels: make(ChannelSet),
ctime: now,
isTor: conn.IsTor,
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
}
client.history.Initialize(config.History.ClientLength)
client.brbTimer.Initialize(client)
session := &Session{
client: client,
socket: socket,
capVersion: caps.Cap301,
capState: caps.NoneState,
ctime: now,
atime: now,
realIP: realIP,
}
session.SetMaxlenRest()
client.sessions = []*Session{session}
if conn.IsTLS {
client.SetMode(modes.TLS, true)
// error is not useful to us here anyways so we can ignore it
client.certfp, _ = socket.CertFP()
}
if conn.IsTor {
client.SetMode(modes.TLS, true)
// cover up details of the tor proxying infrastructure (not a user privacy concern,
// but a hardening measure):
session.proxiedIP = utils.IPv4LoopbackAddress
session.rawHostname = config.Server.TorListeners.Vhost
} else {
// set the hostname for this client (may be overridden later by PROXY or WEBIRC)
session.rawHostname = utils.LookupHostname(session.realIP.String())
client.cloakedHostname = config.Server.Cloaks.ComputeCloak(session.realIP)
remoteAddr := conn.Conn.RemoteAddr()
if utils.AddrIsLocal(remoteAddr) {
// treat local connections as secure (may be overridden later by WEBIRC)
client.SetMode(modes.TLS, true)
}
if config.Server.CheckIdent && !utils.AddrIsUnix(remoteAddr) {
client.doIdentLookup(conn.Conn)
}
}
client.realIP = session.realIP
client.rawHostname = session.rawHostname
client.proxiedIP = session.proxiedIP
client.run(session)
}
func (client *Client) doIdentLookup(conn net.Conn) {
_, serverPortString, err := net.SplitHostPort(conn.LocalAddr().String())
if err != nil {
client.server.logger.Error("internal", "bad server address", err.Error())
return
}
serverPort, _ := strconv.Atoi(serverPortString)
clientHost, clientPortString, err := net.SplitHostPort(conn.RemoteAddr().String())
if err != nil {
client.server.logger.Error("internal", "bad client address", err.Error())
return
}
clientPort, _ := strconv.Atoi(clientPortString)
client.Notice(client.t("*** Looking up your username"))
resp, err := ident.Query(clientHost, serverPort, clientPort, IdentTimeoutSeconds)
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(config *Config) AuthOutcome {
saslSent := client.account != ""
// PASS requirement
if (config.Server.passwordBytes != nil) && !client.sentPassCommand && !(config.Accounts.SkipServerPassword && saslSent) {
return authFailPass
}
// Tor connections may be required to authenticate with SASL
if client.isTor && config.Server.TorListeners.RequireSasl && !saslSent {
return authFailTorSaslRequired
}
// finally, enforce require-sasl
if config.Accounts.RequireSasl.Enabled && !saslSent && !utils.IPInNets(client.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()
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 {
ip := client.IP().String()
if 0 < len(ip) && ip[0] == ':' {
ip = "0" + ip
}
return ip
}
//
// command goroutine
//
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)
}()
session.idletimer.Initialize(session)
session.resetFakelag()
isReattach := client.Registered()
if isReattach {
if session.resumeDetails != nil {
session.playResume()
session.resumeDetails = nil
client.brbTimer.Disable()
} else {
client.playReattachMessages(session)
}
} else {
// don't reset the nick timer during a reattach
client.nickTimer.Initialize(client)
}
firstLine := !isReattach
for {
maxlenRest := session.MaxlenRest()
line, err := session.socket.Read()
if err != nil {
quitMessage := "connection closed"
if err == errReadQ {
quitMessage = "readQ exceeded"
}
client.Quit(quitMessage, session)
// since the client did not actually send us a QUIT,
// give them a chance to resume if applicable:
if !session.Destroyed() {
client.brbTimer.Enable()
}
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
}
}
}
if client.registered {
session.fakelag.Touch()
} 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
}
}
msg, err := ircmsg.ParseLineStrict(line, true, maxlenRest)
if err == ircmsg.ErrorLineIsEmpty {
continue
} else if err == ircmsg.ErrorLineTooLong {
session.Send(nil, client.server.name, ERR_INPUTTOOLONG, client.Nick(), client.t("Input line too long"))
continue
} else if err != nil {
client.Quit(client.t("Received malformed line"), session)
break
}
cmd, exists := Commands[msg.Command]
if !exists {
if len(msg.Command) > 0 {
session.Send(nil, client.server.name, ERR_UNKNOWNCOMMAND, client.Nick(), msg.Command, client.t("Unknown command"))
} else {
session.Send(nil, client.server.name, ERR_UNKNOWNCOMMAND, client.Nick(), "lastcmd", client.t("No command given"))
}
continue
}
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)
for _, channel := range session.client.Channels() {
channel.playJoinForSession(session)
// clients should receive autoreplay-on-join lines, if applicable;
// 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)
}
}
//
// idle, quit, timers and timeouts
//
// Active updates when the client was last 'active' (i.e. the user should be sitting in front of their client).
func (client *Client) Active(session *Session) {
now := time.Now().UTC()
client.stateMutex.Lock()
defer client.stateMutex.Unlock()
session.atime = now
client.atime = now
}
// Ping sends the client a PING message.
func (session *Session) Ping() {
session.Send(nil, "", "PING", session.client.Nick())
}
// tryResume tries to resume if the client asked us to.
func (session *Session) tryResume() (success bool) {
var oldResumeID string
defer func() {
if success {
// "On a successful request, the server [...] terminates the old client's connection"
oldSession := session.client.GetSessionByResumeID(oldResumeID)
if oldSession != nil {
session.client.destroy(oldSession)
}
} else {
session.resumeDetails = nil
}
}()
client := session.client
server := client.server
config := server.Config()
oldClient, oldResumeID := server.resumeManager.VerifyToken(client, session.resumeDetails.PresentedToken)
if oldClient == nil {
session.Send(nil, server.name, "FAIL", "RESUME", "INVALID_TOKEN", client.t("Cannot resume connection, token is not valid"))
return
}
resumeAllowed := config.Server.AllowPlaintextResume || (oldClient.HasMode(modes.TLS) && client.HasMode(modes.TLS))
if !resumeAllowed {
session.Send(nil, server.name, "FAIL", "RESUME", "INSECURE_SESSION", client.t("Cannot resume connection, old and new clients must have TLS"))
return
}
if oldClient.isTor != client.isTor {
session.Send(nil, server.name, "FAIL", "RESUME", "INSECURE_SESSION", client.t("Cannot resume connection from Tor to non-Tor or vice versa"))
return
}
err := server.clients.Resume(oldClient, session)
if err != nil {
session.Send(nil, server.name, "FAIL", "RESUME", "CANNOT_RESUME", client.t("Cannot resume connection"))
return
}
success = true
client.server.logger.Debug("quit", fmt.Sprintf("%s is being resumed", oldClient.Nick()))
return
}
// playResume is called from the session's fresh goroutine after a resume;
// it sends notifications to friends, then plays the registration burst and replays
// stored history to the session
func (session *Session) playResume() {
client := session.client
server := client.server
friends := make(ClientSet)
oldestLostMessage := time.Now().UTC()
// work out how much time, if any, is not covered by history buffers
for _, channel := range client.Channels() {
for _, member := range channel.Members() {
friends.Add(member)
lastDiscarded := channel.history.LastDiscarded()
if lastDiscarded.Before(oldestLostMessage) {
oldestLostMessage = lastDiscarded
}
}
}
privmsgMatcher := func(item history.Item) bool {
return item.Type == history.Privmsg || item.Type == history.Notice || item.Type == history.Tagmsg
}
privmsgHistory := client.history.Match(privmsgMatcher, false, 0)
lastDiscarded := client.history.LastDiscarded()
if lastDiscarded.Before(oldestLostMessage) {
oldestLostMessage = lastDiscarded
}
for _, item := range privmsgHistory {
sender := server.clients.Get(stripMaskFromNick(item.Nick))
if sender != nil {
friends.Add(sender)
}
}
timestamp := session.resumeDetails.Timestamp
gap := lastDiscarded.Sub(timestamp)
session.resumeDetails.HistoryIncomplete = gap > 0 || timestamp.IsZero()
gapSeconds := int(gap.Seconds()) + 1 // round up to avoid confusion
details := client.Details()
oldNickmask := details.nickMask
client.SetRawHostname(session.rawHostname)
hostname := client.Hostname() // may be a vhost
timestampString := timestamp.Format(IRCv3TimestampFormat)
// send quit/resume messages to friends
for friend := range friends {
if friend == client {
continue
}
for _, fSession := range friend.Sessions() {
if fSession.capabilities.Has(caps.Resume) {
if !session.resumeDetails.HistoryIncomplete {
fSession.Send(nil, oldNickmask, "RESUMED", hostname, "ok")
} else if session.resumeDetails.HistoryIncomplete && !timestamp.IsZero() {
fSession.Send(nil, oldNickmask, "RESUMED", hostname, timestampString)
} else {
fSession.Send(nil, oldNickmask, "RESUMED", hostname)
}
} else {
if !session.resumeDetails.HistoryIncomplete {
fSession.Send(nil, oldNickmask, "QUIT", fmt.Sprintf(friend.t("Client reconnected")))
} else if session.resumeDetails.HistoryIncomplete && !timestamp.IsZero() {
fSession.Send(nil, oldNickmask, "QUIT", fmt.Sprintf(friend.t("Client reconnected (up to %d seconds of message history lost)"), gapSeconds))
} else {
fSession.Send(nil, oldNickmask, "QUIT", fmt.Sprintf(friend.t("Client reconnected (message history may have been lost)")))
}
}
}
}
if session.resumeDetails.HistoryIncomplete && !timestamp.IsZero() {
session.Send(nil, client.server.name, "WARN", "RESUME", "HISTORY_LOST", fmt.Sprintf(client.t("Resume may have lost up to %d seconds of history"), gapSeconds))
} else {
session.Send(nil, client.server.name, "WARN", "RESUME", "HISTORY_LOST", client.t("Resume may have lost some message history"))
}
session.Send(nil, client.server.name, "RESUME", "SUCCESS", details.nick)
server.playRegistrationBurst(session)
for _, channel := range client.Channels() {
channel.Resume(session, timestamp)
}
// replay direct PRIVSMG history
if !timestamp.IsZero() {
now := time.Now().UTC()
items, complete := client.history.Between(timestamp, now, false, 0)
rb := NewResponseBuffer(client.Sessions()[0])
client.replayPrivmsgHistory(rb, items, complete)
rb.Send(true)
}
session.resumeDetails = nil
}
func (client *Client) replayPrivmsgHistory(rb *ResponseBuffer, items []history.Item, complete bool) {
var batchID string
details := client.Details()
nick := details.nick
if 0 < len(items) {
batchID = rb.StartNestedHistoryBatch(nick)
}
allowTags := rb.session.capabilities.Has(caps.MessageTags)
for _, item := range items {
var command string
switch item.Type {
case history.Privmsg:
command = "PRIVMSG"
case history.Notice:
command = "NOTICE"
case history.Tagmsg:
if allowTags {
command = "TAGMSG"
} else {
continue
}
default:
continue
}
var tags map[string]string
if allowTags {
tags = item.Tags
}
if item.Params[0] == "" {
// this message was sent *to* the client from another nick
rb.AddSplitMessageFromClient(item.Nick, item.AccountName, tags, command, nick, item.Message)
} else {
// this message was sent *from* the client to another nick; the target is item.Params[0]
// substitute the client's current nickmask in case they changed nick
rb.AddSplitMessageFromClient(details.nickMask, item.AccountName, tags, command, item.Params[0], item.Message)
}
}
rb.EndNestedBatch(batchID)
if !complete {
rb.Add(nil, "HistServ", "NOTICE", nick, client.t("Some additional message history may have been lost"))
}
}
// 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.atime)
}
// 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())
}
// HasNick returns true if the client's nickname is set (used in registration).
func (client *Client) HasNick() bool {
client.stateMutex.RLock()
defer client.stateMutex.RUnlock()
return client.nick != "" && client.nick != "*"
}
// HasUsername returns true if the client's username is set (used in registration).
func (client *Client) HasUsername() bool {
client.stateMutex.RLock()
defer client.stateMutex.RUnlock()
return client.username != "" && client.username != "*"
}
// SetNames sets the client's ident and realname.
func (client *Client) SetNames(username, realname string, fromIdent bool) error {
limit := client.server.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 !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[capab] {
return false
}
}
return true
}
// ModeString returns the mode string for this client.
func (client *Client) ModeString() (str string) {
return "+" + client.flags.String()
}
// Friends refers to clients that share a channel with this client.
func (client *Client) Friends(capabs ...caps.Capability) (result map[*Session]bool) {
result = make(map[*Session]bool)
// look at the client's own sessions
for _, session := range client.Sessions() {
if session.capabilities.HasAll(capabs...) {
result[session] = true
}
}
for _, channel := range client.Channels() {
for _, member := range channel.Members() {
for _, session := range member.Sessions() {
if session.capabilities.HasAll(capabs...) {
result[session] = true
}
}
}
}
return
}
func (client *Client) SetOper(oper *Oper) {
client.stateMutex.Lock()
defer client.stateMutex.Unlock()
client.oper = oper
// operators typically get a vhost, update the nickmask
client.updateNickMaskNoMutex()
}
// XXX: CHGHOST requires prefix nickmask to have original hostname,
// this is annoying to do correctly
func (client *Client) sendChghost(oldNickMask string, vhost string) {
username := client.Username()
for fClient := range client.Friends(caps.ChgHost) {
fClient.sendFromClientInternal(false, time.Time{}, "", oldNickMask, client.AccountName(), nil, "CHGHOST", username, vhost)
}
}
// choose the correct vhost to display
func (client *Client) getVHostNoMutex() string {
// hostserv vhost OR operclass vhost OR nothing (i.e., normal rdns hostmask)
if client.vhost != "" {
return client.vhost
} else if client.oper != nil {
return client.oper.Vhost
} else {
return ""
}
}
// SetVHost updates the client's hostserv-based vhost
func (client *Client) SetVHost(vhost string) (updated bool) {
client.stateMutex.Lock()
defer client.stateMutex.Unlock()
updated = (client.vhost != vhost)
client.vhost = vhost
if updated {
client.updateNickMaskNoMutex()
}
return
}
// updateNick updates `nick` and `nickCasefolded`.
func (client *Client) updateNick(nick, nickCasefolded, skeleton string) {
client.stateMutex.Lock()
defer client.stateMutex.Unlock()
client.nick = nick
client.nickCasefolded = nickCasefolded
client.skeleton = skeleton
client.updateNickMaskNoMutex()
}
// updateNickMaskNoMutex updates the casefolded nickname and nickmask, not acquiring any mutexes.
func (client *Client) updateNickMaskNoMutex() {
client.hostname = client.getVHostNoMutex()
if client.hostname == "" {
client.hostname = client.cloakedHostname
if client.hostname == "" {
client.hostname = client.rawHostname
}
}
cfhostname, err := Casefold(client.hostname)
if err != nil {
client.server.logger.Error("internal", "hostname couldn't be casefolded", client.hostname, err.Error())
cfhostname = client.hostname // YOLO
}
client.nickMaskString = fmt.Sprintf("%s!%s@%s", client.nick, client.username, client.hostname)
client.nickMaskCasefolded = fmt.Sprintf("%s!%s@%s", client.nickCasefolded, strings.ToLower(client.username), cfhostname)
}
// AllNickmasks returns all the possible nickmasks for the client.
func (client *Client) AllNickmasks() (masks []string) {
client.stateMutex.RLock()
nick := client.nickCasefolded
username := client.username
rawHostname := client.rawHostname
cloakedHostname := client.cloakedHostname
vhost := client.getVHostNoMutex()
client.stateMutex.RUnlock()
username = strings.ToLower(username)
if len(vhost) > 0 {
cfvhost, err := Casefold(vhost)
if err == nil {
masks = append(masks, fmt.Sprintf("%s!%s@%s", nick, username, cfvhost))
}
}
var rawhostmask string
cfrawhost, err := Casefold(rawHostname)
if err == nil {
rawhostmask = fmt.Sprintf("%s!%s@%s", nick, username, cfrawhost)
masks = append(masks, rawhostmask)
}
if cloakedHostname != "" {
masks = append(masks, fmt.Sprintf("%s!%s@%s", nick, username, cloakedHostname))
}
ipmask := fmt.Sprintf("%s!%s@%s", nick, username, client.IPString())
if ipmask != rawhostmask {
masks = append(masks, ipmask)
}
return
}
// LoggedIntoAccount returns true if this client is logged into an account.
func (client *Client) LoggedIntoAccount() bool {
return client.Account() != ""
}
// RplISupport outputs our ISUPPORT lines to the client. This is used on connection and in VERSION responses.
func (client *Client) RplISupport(rb *ResponseBuffer) {
translatedISupport := client.t("are supported by this server")
nick := client.Nick()
config := client.server.Config()
for _, cachedTokenLine := range config.Server.isupport.CachedReply {
length := len(cachedTokenLine) + 2
tokenline := make([]string, length)
tokenline[0] = nick
copy(tokenline[1:], cachedTokenLine)
tokenline[length-1] = translatedISupport
rb.Add(nil, client.server.name, RPL_ISUPPORT, tokenline...)
}
}
// Quit sets the given quit message for the client.
// (You must ensure separately that destroy() is called, e.g., by returning `true` from
// the command handler or calling it yourself.)
func (client *Client) Quit(message string, session *Session) {
setFinalData := func(sess *Session) {
message := sess.quitMessage
var finalData []byte
// #364: don't send QUIT lines to unregistered clients
if client.registered {
quitMsg := ircmsg.MakeMessage(nil, client.nickMaskString, "QUIT", message)
finalData, _ = quitMsg.LineBytesStrict(false, 512)
}
errorMsg := ircmsg.MakeMessage(nil, "", "ERROR", message)
errorMsgBytes, _ := errorMsg.LineBytesStrict(false, 512)
finalData = append(finalData, errorMsgBytes...)
sess.socket.SetFinalData(finalData)
}
client.stateMutex.Lock()
defer client.stateMutex.Unlock()
var sessions []*Session
if session != nil {
sessions = []*Session{session}
} else {
sessions = client.sessions
}
for _, session := range sessions {
if session.SetQuitMessage(message) {
setFinalData(session)
}
}
}
// destroy gets rid of a client, removes them from server lists etc.
// if `session` is nil, destroys the client unconditionally, removing all sessions;
// otherwise, destroys one specific session, only destroying the client if it
// has no more sessions.
func (client *Client) destroy(session *Session) {
var sessionsToDestroy []*Session
client.stateMutex.Lock()
details := client.detailsNoMutex()
brbState := client.brbTimer.state
brbAt := client.brbTimer.brbAt
wasReattach := session != nil && session.client != client
sessionRemoved := false
var remainingSessions int
if session == nil {
sessionsToDestroy = client.sessions
client.sessions = nil
remainingSessions = 0
} else {
sessionRemoved, remainingSessions = client.removeSession(session)
if sessionRemoved {
sessionsToDestroy = []*Session{session}
}
}