forked from ergochat/ergo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathchannel.go
1654 lines (1453 loc) · 52.9 KB
/
channel.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 <[email protected]>
// released under the MIT license
package irc
import (
"fmt"
"maps"
"strconv"
"strings"
"time"
"sync"
"github.com/ergochat/irc-go/ircmsg"
"github.com/ergochat/ergo/irc/caps"
"github.com/ergochat/ergo/irc/datastore"
"github.com/ergochat/ergo/irc/history"
"github.com/ergochat/ergo/irc/modes"
"github.com/ergochat/ergo/irc/utils"
)
type ChannelSettings struct {
History HistoryStatus
QueryCutoff HistoryCutoff
}
// Channel represents a channel that clients can join.
type Channel struct {
flags modes.ModeSet
lists map[modes.Mode]*UserMaskSet
key string
forward string
members MemberSet
name string
nameCasefolded string
server *Server
createdTime time.Time
registeredFounder string
registeredTime time.Time
transferPendingTo string
topic string
topicSetBy string
topicSetTime time.Time
userLimit int
accountToUMode map[string]modes.Mode
history history.Buffer
stateMutex sync.RWMutex // tier 1
writebackLock sync.Mutex // tier 1.5
joinPartMutex sync.Mutex // tier 3
dirtyBits uint
settings ChannelSettings
uuid utils.UUID
// these caches are paired to allow iteration over channel members without holding the lock
membersCache []*Client
memberDataCache []*memberData
}
// NewChannel creates a new channel from a `Server` and a `name`
// string, which must be unique on the server.
func NewChannel(s *Server, name, casefoldedName string, registered bool, regInfo RegisteredChannel) *Channel {
config := s.Config()
channel := &Channel{
createdTime: time.Now().UTC(), // may be overwritten by applyRegInfo
members: make(MemberSet),
name: name,
nameCasefolded: casefoldedName,
server: s,
}
channel.initializeLists()
channel.history.Initialize(0, 0)
if registered {
channel.applyRegInfo(regInfo)
} else {
channel.resizeHistory(config)
for _, mode := range config.Channels.defaultModes {
channel.flags.SetMode(mode, true)
}
channel.uuid = utils.GenerateUUIDv4()
}
return channel
}
func (channel *Channel) initializeLists() {
channel.lists = map[modes.Mode]*UserMaskSet{
modes.BanMask: NewUserMaskSet(),
modes.ExceptMask: NewUserMaskSet(),
modes.InviteMask: NewUserMaskSet(),
}
channel.accountToUMode = make(map[string]modes.Mode)
}
func (channel *Channel) resizeHistory(config *Config) {
status, _, _ := channel.historyStatus(config)
if status == HistoryEphemeral {
channel.history.Resize(config.History.ChannelLength, time.Duration(config.History.AutoresizeWindow))
} else {
channel.history.Resize(0, 0)
}
}
// read in channel state that was persisted in the DB
func (channel *Channel) applyRegInfo(chanReg RegisteredChannel) {
defer channel.resizeHistory(channel.server.Config())
channel.stateMutex.Lock()
defer channel.stateMutex.Unlock()
channel.uuid = chanReg.UUID
channel.registeredFounder = chanReg.Founder
channel.registeredTime = chanReg.RegisteredAt
channel.topic = chanReg.Topic
channel.topicSetBy = chanReg.TopicSetBy
channel.topicSetTime = chanReg.TopicSetTime
channel.name = chanReg.Name
channel.createdTime = chanReg.RegisteredAt
channel.key = chanReg.Key
channel.userLimit = chanReg.UserLimit
channel.settings = chanReg.Settings
channel.forward = chanReg.Forward
for _, mode := range chanReg.Modes {
channel.flags.SetMode(mode, true)
}
for account, mode := range chanReg.AccountToUMode {
channel.accountToUMode[account] = mode
}
channel.lists[modes.BanMask].SetMasks(chanReg.Bans)
channel.lists[modes.InviteMask].SetMasks(chanReg.Invites)
channel.lists[modes.ExceptMask].SetMasks(chanReg.Excepts)
}
// obtain a consistent snapshot of the channel state that can be persisted to the DB
func (channel *Channel) ExportRegistration() (info RegisteredChannel) {
channel.stateMutex.RLock()
defer channel.stateMutex.RUnlock()
info.Name = channel.name
info.UUID = channel.uuid
info.Founder = channel.registeredFounder
info.RegisteredAt = channel.registeredTime
info.Topic = channel.topic
info.TopicSetBy = channel.topicSetBy
info.TopicSetTime = channel.topicSetTime
info.Key = channel.key
info.Forward = channel.forward
info.Modes = channel.flags.AllModes()
info.UserLimit = channel.userLimit
info.Bans = channel.lists[modes.BanMask].Masks()
info.Invites = channel.lists[modes.InviteMask].Masks()
info.Excepts = channel.lists[modes.ExceptMask].Masks()
info.AccountToUMode = maps.Clone(channel.accountToUMode)
info.Settings = channel.settings
return
}
func (channel *Channel) exportSummary() (info RegisteredChannel) {
channel.stateMutex.RLock()
defer channel.stateMutex.RUnlock()
info.Name = channel.name
info.Founder = channel.registeredFounder
info.RegisteredAt = channel.registeredTime
return
}
// begin: asynchronous database writeback implementation, modeled on irc/socket.go
// MarkDirty marks part (or all) of a channel's data as needing to be written back
// to the database, then starts a writer goroutine if necessary.
// This is the equivalent of Socket.Write().
func (channel *Channel) MarkDirty(dirtyBits uint) {
channel.stateMutex.Lock()
isRegistered := channel.registeredFounder != ""
channel.dirtyBits = channel.dirtyBits | dirtyBits
channel.stateMutex.Unlock()
if !isRegistered {
return
}
channel.wakeWriter()
}
// IsClean returns whether a channel can be safely removed from the server.
// To avoid the obvious TOCTOU race condition, it must be called while holding
// ChannelManager's lock (that way, no one can join and make the channel dirty again
// between this method exiting and the actual deletion).
func (channel *Channel) IsClean() bool {
if !channel.writebackLock.TryLock() {
// a database write (which may fail) is in progress, the channel cannot be cleaned up
return false
}
defer channel.writebackLock.Unlock()
channel.stateMutex.RLock()
defer channel.stateMutex.RUnlock()
if len(channel.members) != 0 {
return false
}
// see #1507 and #704 among others; registered channels should never be removed
return channel.registeredFounder == ""
}
func (channel *Channel) wakeWriter() {
if channel.writebackLock.TryLock() {
go channel.writeLoop()
}
}
// equivalent of Socket.send()
func (channel *Channel) writeLoop() {
defer channel.server.HandlePanic()
for {
// TODO(#357) check the error value of this and implement timed backoff
channel.performWrite(0)
channel.writebackLock.Unlock()
channel.stateMutex.RLock()
isDirty := channel.dirtyBits != 0
isEmpty := len(channel.members) == 0
channel.stateMutex.RUnlock()
if !isDirty {
if isEmpty {
channel.server.channels.Cleanup(channel)
}
return // nothing to do
} // else: isDirty, so we need to write again
if !channel.writebackLock.TryLock() {
return
}
}
}
// Store writes part (or all) of the channel's data back to the database,
// blocking until the write is complete. This is the equivalent of
// Socket.BlockingWrite.
func (channel *Channel) Store(dirtyBits uint) (err error) {
defer func() {
channel.stateMutex.Lock()
isDirty := channel.dirtyBits != 0
isEmpty := len(channel.members) == 0
channel.stateMutex.Unlock()
if isDirty {
channel.wakeWriter()
} else if isEmpty {
channel.server.channels.Cleanup(channel)
}
}()
channel.writebackLock.Lock()
defer channel.writebackLock.Unlock()
return channel.performWrite(dirtyBits)
}
// do an individual write; equivalent of Socket.send()
func (channel *Channel) performWrite(additionalDirtyBits uint) (err error) {
channel.stateMutex.Lock()
dirtyBits := channel.dirtyBits | additionalDirtyBits
channel.dirtyBits = 0
isRegistered := channel.registeredFounder != ""
channel.stateMutex.Unlock()
if !isRegistered || dirtyBits == 0 {
return
}
var success bool
info := channel.ExportRegistration()
if b, err := info.Serialize(); err == nil {
if err := channel.server.dstore.Set(datastore.TableChannels, info.UUID, b, time.Time{}); err == nil {
success = true
} else {
channel.server.logger.Error("internal", "couldn't persist channel", info.Name, err.Error())
}
} else {
channel.server.logger.Error("internal", "couldn't serialize channel", info.Name, err.Error())
}
if !success {
channel.stateMutex.Lock()
channel.dirtyBits = channel.dirtyBits | dirtyBits
channel.stateMutex.Unlock()
}
return
}
// SetRegistered registers the channel, returning an error if it was already registered.
func (channel *Channel) SetRegistered(founder string) error {
channel.stateMutex.Lock()
defer channel.stateMutex.Unlock()
if channel.registeredFounder != "" {
return errChannelAlreadyRegistered
}
channel.registeredFounder = founder
channel.registeredTime = time.Now().UTC()
channel.accountToUMode[founder] = modes.ChannelFounder
return nil
}
// SetUnregistered deletes the channel's registration information.
func (channel *Channel) SetUnregistered(expectedFounder string) {
uuid := utils.GenerateUUIDv4()
channel.stateMutex.Lock()
defer channel.stateMutex.Unlock()
if channel.registeredFounder != expectedFounder {
return
}
channel.registeredFounder = ""
var zeroTime time.Time
channel.registeredTime = zeroTime
channel.accountToUMode = make(map[string]modes.Mode)
// reset the UUID so that any re-registration will persist under
// a separate key:
channel.uuid = uuid
}
// implements `CHANSERV CLEAR #chan ACCESS` (resets bans, invites, excepts, and amodes)
func (channel *Channel) resetAccess() {
defer channel.MarkDirty(IncludeLists)
channel.stateMutex.Lock()
defer channel.stateMutex.Unlock()
channel.initializeLists()
if channel.registeredFounder != "" {
channel.accountToUMode[channel.registeredFounder] = modes.ChannelFounder
}
}
// IsRegistered returns whether the channel is registered.
func (channel *Channel) IsRegistered() bool {
channel.stateMutex.RLock()
defer channel.stateMutex.RUnlock()
return channel.registeredFounder != ""
}
type channelTransferStatus uint
const (
channelTransferComplete channelTransferStatus = iota
channelTransferPending
channelTransferCancelled
channelTransferFailed
)
// Transfer transfers ownership of a registered channel to a different account
func (channel *Channel) Transfer(client *Client, target string, hasPrivs bool) (status channelTransferStatus, err error) {
status = channelTransferFailed
defer func() {
if status == channelTransferComplete && err == nil {
channel.Store(IncludeAllAttrs)
}
}()
cftarget, err := CasefoldName(target)
if err != nil {
err = errAccountDoesNotExist
return
}
channel.stateMutex.Lock()
defer channel.stateMutex.Unlock()
if channel.registeredFounder == "" {
err = errChannelNotOwnedByAccount
return
}
if hasPrivs {
channel.transferOwnership(cftarget)
return channelTransferComplete, nil
} else {
if channel.registeredFounder == cftarget {
// transferring back to yourself cancels a pending transfer
channel.transferPendingTo = ""
return channelTransferCancelled, nil
} else {
channel.transferPendingTo = cftarget
return channelTransferPending, nil
}
}
}
func (channel *Channel) transferOwnership(newOwner string) {
delete(channel.accountToUMode, channel.registeredFounder)
channel.registeredFounder = newOwner
channel.accountToUMode[channel.registeredFounder] = modes.ChannelFounder
channel.transferPendingTo = ""
}
// AcceptTransfer implements `CS TRANSFER #chan ACCEPT`
func (channel *Channel) AcceptTransfer(client *Client) (err error) {
defer func() {
if err == nil {
channel.Store(IncludeAllAttrs)
}
}()
account := client.Account()
if account == "" {
return errAccountNotLoggedIn
}
channel.stateMutex.Lock()
defer channel.stateMutex.Unlock()
if account != channel.transferPendingTo {
return errChannelTransferNotOffered
}
channel.transferOwnership(account)
return nil
}
func (channel *Channel) regenerateMembersCache() {
channel.stateMutex.RLock()
membersCache := make([]*Client, len(channel.members))
dataCache := make([]*memberData, len(channel.members))
i := 0
for client, info := range channel.members {
membersCache[i] = client
dataCache[i] = info
i++
}
channel.stateMutex.RUnlock()
channel.stateMutex.Lock()
channel.membersCache = membersCache
channel.memberDataCache = dataCache
channel.stateMutex.Unlock()
}
// Names sends the list of users joined to the channel to the given client.
func (channel *Channel) Names(client *Client, rb *ResponseBuffer) {
channel.stateMutex.RLock()
clientData, isJoined := channel.members[client]
chname := channel.name
membersCache, memberDataCache := channel.membersCache, channel.memberDataCache
channel.stateMutex.RUnlock()
symbol := "=" // https://modern.ircdocs.horse/#rplnamreply-353
if channel.flags.HasMode(modes.Secret) {
symbol = "@"
}
isOper := client.HasRoleCapabs("sajoin")
respectAuditorium := channel.flags.HasMode(modes.Auditorium) && !isOper &&
(!isJoined || clientData.modes.HighestChannelUserMode() == modes.Mode(0))
isMultiPrefix := rb.session.capabilities.Has(caps.MultiPrefix)
isUserhostInNames := rb.session.capabilities.Has(caps.UserhostInNames)
maxNamLen := 480 - len(client.server.name) - len(client.Nick()) - len(chname)
var tl utils.TokenLineBuilder
tl.Initialize(maxNamLen, " ")
if isJoined || !channel.flags.HasMode(modes.Secret) || isOper {
for i, target := range membersCache {
if !isJoined && target.HasMode(modes.Invisible) && !isOper {
continue
}
var nick string
if isUserhostInNames {
nick = target.NickMaskString()
} else {
nick = target.Nick()
}
memberData := memberDataCache[i]
if respectAuditorium && memberData.modes.HighestChannelUserMode() == modes.Mode(0) {
continue
}
tl.AddParts(memberData.modes.Prefixes(isMultiPrefix), nick)
}
}
for _, line := range tl.Lines() {
rb.Add(nil, client.server.name, RPL_NAMREPLY, client.nick, symbol, chname, line)
}
rb.Add(nil, client.server.name, RPL_ENDOFNAMES, client.nick, chname, client.t("End of NAMES list"))
}
// does `clientMode` give you privileges to grant/remove `targetMode` to/from people,
// or to kick them?
func channelUserModeHasPrivsOver(clientMode modes.Mode, targetMode modes.Mode) bool {
switch clientMode {
case modes.ChannelFounder:
return true
case modes.ChannelAdmin, modes.ChannelOperator:
// admins cannot kick other admins, operators *can* kick other operators
return targetMode != modes.ChannelFounder && targetMode != modes.ChannelAdmin
case modes.Halfop:
// halfops cannot kick other halfops
return targetMode == modes.Voice || targetMode == modes.Mode(0)
default:
// voice and unprivileged cannot kick anyone
return false
}
}
// ClientIsAtLeast returns whether the client has at least the given channel privilege.
func (channel *Channel) ClientIsAtLeast(client *Client, permission modes.Mode) bool {
channel.stateMutex.RLock()
memberData, present := channel.members[client]
founder := channel.registeredFounder
channel.stateMutex.RUnlock()
if founder != "" && founder == client.Account() {
return true
}
if !present {
return false
}
for _, mode := range modes.ChannelUserModes {
if memberData.modes.HasMode(mode) {
return true
}
if mode == permission {
break
}
}
return false
}
func (channel *Channel) ClientPrefixes(client *Client, isMultiPrefix bool) string {
channel.stateMutex.RLock()
defer channel.stateMutex.RUnlock()
memberData, present := channel.members[client]
if !present {
return ""
} else {
return memberData.modes.Prefixes(isMultiPrefix)
}
}
func (channel *Channel) ClientStatus(client *Client) (present bool, joinTimeSecs int64, cModes modes.Modes) {
channel.stateMutex.RLock()
defer channel.stateMutex.RUnlock()
memberData, present := channel.members[client]
return present, time.Unix(0, memberData.joinTime).Unix(), memberData.modes.AllModes()
}
// helper for persisting channel-user modes for always-on clients;
// return the channel name and all channel-user modes for a client
func (channel *Channel) alwaysOnStatus(client *Client) (ok bool, chname string, status alwaysOnChannelStatus) {
channel.stateMutex.RLock()
defer channel.stateMutex.RUnlock()
chname = channel.name
data, ok := channel.members[client]
if !ok {
return
}
status.Modes = data.modes.String()
status.JoinTime = data.joinTime
return
}
// overwrite any existing channel-user modes with the stored ones
func (channel *Channel) setMemberStatus(client *Client, status alwaysOnChannelStatus) {
newModes := modes.NewModeSet()
for _, mode := range status.Modes {
newModes.SetMode(modes.Mode(mode), true)
}
channel.stateMutex.Lock()
defer channel.stateMutex.Unlock()
if mData, ok := channel.members[client]; ok {
mData.modes.Clear()
for _, mode := range status.Modes {
mData.modes.SetMode(modes.Mode(mode), true)
}
mData.joinTime = status.JoinTime
}
}
func (channel *Channel) ClientHasPrivsOver(client *Client, target *Client) bool {
channel.stateMutex.RLock()
founder := channel.registeredFounder
clientData, clientOK := channel.members[client]
targetData, targetOK := channel.members[target]
channel.stateMutex.RUnlock()
if founder != "" {
if founder == client.Account() {
return true // #950: founder can take any privileged action without actually having +q
} else if founder == target.Account() {
return false // conversely, only the founder can kick the founder
}
}
return clientOK && targetOK &&
channelUserModeHasPrivsOver(
clientData.modes.HighestChannelUserMode(),
targetData.modes.HighestChannelUserMode(),
)
}
func (channel *Channel) hasClient(client *Client) bool {
channel.stateMutex.RLock()
_, present := channel.members[client]
channel.stateMutex.RUnlock()
return present
}
// <mode> <mode params>
func (channel *Channel) modeStrings(client *Client) (result []string) {
hasPrivs := client.HasRoleCapabs("sajoin")
channel.stateMutex.RLock()
defer channel.stateMutex.RUnlock()
isMember := hasPrivs || channel.members.Has(client)
showKey := isMember && (channel.key != "")
showUserLimit := channel.userLimit > 0
showForward := channel.forward != ""
var mods strings.Builder
mods.WriteRune('+')
// flags with args
if showKey {
mods.WriteRune(rune(modes.Key))
}
if showUserLimit {
mods.WriteRune(rune(modes.UserLimit))
}
if showForward {
mods.WriteRune(rune(modes.Forward))
}
for _, m := range channel.flags.AllModes() {
mods.WriteRune(rune(m))
}
result = []string{mods.String()}
// args for flags with args: The order must match above to keep
// positional arguments in place.
if showKey {
result = append(result, channel.key)
}
if showUserLimit {
result = append(result, strconv.Itoa(channel.userLimit))
}
if showForward {
result = append(result, channel.forward)
}
return
}
func (channel *Channel) IsEmpty() bool {
channel.stateMutex.RLock()
defer channel.stateMutex.RUnlock()
return len(channel.members) == 0
}
// figure out where history is being stored: persistent, ephemeral, or neither
// target is only needed if we're doing persistent history
func (channel *Channel) historyStatus(config *Config) (status HistoryStatus, target string, restrictions HistoryCutoff) {
if !config.History.Enabled {
return HistoryDisabled, "", HistoryCutoffNone
}
channel.stateMutex.RLock()
target = channel.nameCasefolded
settings := channel.settings
registered := channel.registeredFounder != ""
channel.stateMutex.RUnlock()
restrictions = settings.QueryCutoff
if restrictions == HistoryCutoffDefault {
restrictions = config.History.Restrictions.queryCutoff
}
return channelHistoryStatus(config, registered, settings.History), target, restrictions
}
func (channel *Channel) joinTimeCutoff(client *Client) (present bool, cutoff time.Time) {
account := client.Account()
channel.stateMutex.RLock()
defer channel.stateMutex.RUnlock()
if data, ok := channel.members[client]; ok {
present = true
// report a cutoff of zero, i.e., no restriction, if the user is privileged
if !((account != "" && account == channel.registeredFounder) || data.modes.HasMode(modes.ChannelFounder) || data.modes.HasMode(modes.ChannelAdmin) || data.modes.HasMode(modes.ChannelOperator)) {
cutoff = time.Unix(0, data.joinTime)
}
}
return
}
func channelHistoryStatus(config *Config, registered bool, storedStatus HistoryStatus) (result HistoryStatus) {
if !config.History.Enabled {
return HistoryDisabled
}
// ephemeral history: either the channel owner explicitly set the ephemeral preference,
// or persistent history is disabled for unregistered channels
if registered {
return historyEnabled(config.History.Persistent.RegisteredChannels, storedStatus)
} else {
if config.History.Persistent.UnregisteredChannels {
return HistoryPersistent
} else {
return HistoryEphemeral
}
}
}
func (channel *Channel) AddHistoryItem(item history.Item, account string) (err error) {
if !itemIsStorable(&item, channel.server.Config()) {
return
}
status, target, _ := channel.historyStatus(channel.server.Config())
if status == HistoryPersistent {
err = channel.server.historyDB.AddChannelItem(target, item, account)
} else if status == HistoryEphemeral {
channel.history.Add(item)
}
return
}
// Join joins the given client to this channel (if they can be joined).
func (channel *Channel) Join(client *Client, key string, isSajoin bool, rb *ResponseBuffer) (joinErr error, forward string) {
details := client.Details()
isBot := client.HasMode(modes.Bot)
channel.stateMutex.RLock()
chname := channel.name
chcfname := channel.nameCasefolded
founder := channel.registeredFounder
createdAt := channel.createdTime
chkey := channel.key
limit := channel.userLimit
chcount := len(channel.members)
_, alreadyJoined := channel.members[client]
persistentMode := channel.accountToUMode[details.account]
forward = channel.forward
channel.stateMutex.RUnlock()
if alreadyJoined {
// no message needs to be sent
return nil, ""
}
// 0. SAJOIN always succeeds
// 1. the founder can always join (even if they disabled auto +q on join)
// 2. anyone who automatically receives halfop or higher can always join
// 3. people invited with INVITE can join
hasPrivs := isSajoin || (founder != "" && founder == details.account) ||
(persistentMode != 0 && persistentMode != modes.Voice) ||
client.CheckInvited(chcfname, createdAt)
if !hasPrivs {
if limit != 0 && chcount >= limit {
return errLimitExceeded, forward
}
if chkey != "" && !utils.SecretTokensMatch(chkey, key) {
return errWrongChannelKey, forward
}
// #1901: +h and up exempt from all restrictions, but +v additionally exempts from +i:
if channel.flags.HasMode(modes.InviteOnly) && persistentMode == 0 &&
!channel.lists[modes.InviteMask].Match(details.nickMaskCasefolded) {
return errInviteOnly, forward
}
if channel.lists[modes.BanMask].Match(details.nickMaskCasefolded) &&
!channel.lists[modes.ExceptMask].Match(details.nickMaskCasefolded) &&
!channel.lists[modes.InviteMask].Match(details.nickMaskCasefolded) {
// do not forward people who are banned:
return errBanned, ""
}
if details.account == "" &&
(channel.flags.HasMode(modes.RegisteredOnly) || channel.server.Defcon() <= 2) &&
!channel.lists[modes.InviteMask].Match(details.nickMaskCasefolded) {
return errRegisteredOnly, forward
}
}
if joinErr := client.addChannel(channel, rb == nil); joinErr != nil {
return joinErr, ""
}
client.server.logger.Debug("channels", fmt.Sprintf("%s joined channel %s", details.nick, chname))
givenMode := func() (givenMode modes.Mode) {
channel.joinPartMutex.Lock()
defer channel.joinPartMutex.Unlock()
func() {
channel.stateMutex.Lock()
defer channel.stateMutex.Unlock()
channel.members.Add(client)
firstJoin := len(channel.members) == 1
newChannel := firstJoin && channel.registeredFounder == ""
if newChannel {
givenMode = modes.ChannelOperator
} else {
givenMode = persistentMode
}
if givenMode != 0 {
channel.members[client].modes.SetMode(givenMode, true)
}
}()
channel.regenerateMembersCache()
return
}()
var message utils.SplitMessage
respectAuditorium := givenMode == modes.Mode(0) && channel.flags.HasMode(modes.Auditorium)
message = utils.MakeMessage("")
// no history item for fake persistent joins
if rb != nil && !respectAuditorium {
histItem := history.Item{
Type: history.Join,
Nick: details.nickMask,
AccountName: details.accountName,
Message: message,
IsBot: isBot,
}
histItem.Params[0] = details.realname
channel.AddHistoryItem(histItem, details.account)
}
if rb == nil {
return nil, ""
}
var modestr string
if givenMode != 0 {
modestr = fmt.Sprintf("+%v", givenMode)
}
// cache the most common case (JOIN without extended-join)
var cache MessageCache
cache.Initialize(channel.server, message.Time, message.Msgid, details.nickMask, details.accountName, isBot, nil, "JOIN", chname)
isAway, awayMessage := client.Away()
for _, member := range channel.Members() {
if respectAuditorium {
channel.stateMutex.RLock()
memberData, ok := channel.members[member]
channel.stateMutex.RUnlock()
if !ok || memberData.modes.HighestChannelUserMode() == modes.Mode(0) {
continue
}
}
for _, session := range member.Sessions() {
if session == rb.session {
continue
} else if client == session.client {
channel.playJoinForSession(session)
continue
}
if session.capabilities.Has(caps.ExtendedJoin) {
session.sendFromClientInternal(false, message.Time, message.Msgid, details.nickMask, details.accountName, isBot, nil, "JOIN", chname, details.accountName, details.realname)
} else {
cache.Send(session)
}
if givenMode != 0 {
session.Send(nil, client.server.name, "MODE", chname, modestr, details.nick)
}
if isAway && session.capabilities.Has(caps.AwayNotify) {
session.sendFromClientInternal(false, time.Time{}, "", details.nickMask, details.accountName, isBot, nil, "AWAY", awayMessage)
}
}
}
if rb.session.capabilities.Has(caps.ExtendedJoin) {
rb.AddFromClient(message.Time, message.Msgid, details.nickMask, details.accountName, isBot, nil, "JOIN", chname, details.accountName, details.realname)
} else {
rb.AddFromClient(message.Time, message.Msgid, details.nickMask, details.accountName, isBot, nil, "JOIN", chname)
}
if rb.session.capabilities.Has(caps.ReadMarker) {
rb.Add(nil, client.server.name, "MARKREAD", chname, client.GetReadMarker(chcfname))
}
if rb.session.client == client {
// don't send topic and names for a SAJOIN of a different client
channel.SendTopic(client, rb, false)
if !rb.session.capabilities.Has(caps.NoImplicitNames) {
channel.Names(client, rb)
}
} else {
// ensure that SAJOIN sends a MODE line to the originating client, if applicable
if givenMode != 0 {
rb.Add(nil, client.server.name, "MODE", chname, modestr, details.nick)
}
}
// TODO #259 can be implemented as Flush(false) (i.e., nonblocking) while holding joinPartMutex
rb.Flush(true)
channel.autoReplayHistory(client, rb, message.Msgid)
return nil, ""
}
func (channel *Channel) autoReplayHistory(client *Client, rb *ResponseBuffer, skipMsgid string) {
// autoreplay any messages as necessary
var items []history.Item
hasAutoreplayTimestamps := false
var start, end time.Time
if rb.session.zncPlaybackTimes.ValidFor(channel.NameCasefolded()) {
hasAutoreplayTimestamps = true
start, end = rb.session.zncPlaybackTimes.start, rb.session.zncPlaybackTimes.end
} else if !rb.session.autoreplayMissedSince.IsZero() {
// we already checked for history caps in `playReattachMessages`
hasAutoreplayTimestamps = true
start = time.Now().UTC()
end = rb.session.autoreplayMissedSince
}
if hasAutoreplayTimestamps {
_, seq, _ := channel.server.GetHistorySequence(channel, client, "")
if seq != nil {
zncMax := channel.server.Config().History.ZNCMax
items, _ = seq.Between(history.Selector{Time: start}, history.Selector{Time: end}, zncMax)
}
} else if !rb.session.HasHistoryCaps() {
var replayLimit int
customReplayLimit := client.AccountSettings().AutoreplayLines
if customReplayLimit != nil {
replayLimit = *customReplayLimit
maxLimit := channel.server.Config().History.ChathistoryMax
if maxLimit < replayLimit {
replayLimit = maxLimit
}
} else {
replayLimit = channel.server.Config().History.AutoreplayOnJoin
}
if 0 < replayLimit {
_, seq, _ := channel.server.GetHistorySequence(channel, client, "")
if seq != nil {
items, _ = seq.Between(history.Selector{}, history.Selector{}, replayLimit)
}
}
}
// remove the client's own JOIN line from the replay
numItems := len(items)
for i := len(items) - 1; 0 <= i; i-- {
if items[i].Message.Msgid == skipMsgid {
// zero'ed items will not be replayed because their `Type` field is not recognized
items[i] = history.Item{}
numItems--
break
}
}
if 0 < numItems {
channel.replayHistoryItems(rb, items, false)
rb.Flush(true)
}
}
// plays channel join messages (the JOIN line, topic, and names) to a session.
// this is used when attaching a new session to an existing client that already has
// channels, and also when one session of a client initiates a JOIN and the other
// sessions need to receive the state change
func (channel *Channel) playJoinForSession(session *Session) {
client := session.client
sessionRb := NewResponseBuffer(session)
details := client.Details()
chname := channel.Name()
if session.capabilities.Has(caps.ExtendedJoin) {
sessionRb.Add(nil, details.nickMask, "JOIN", chname, details.accountName, details.realname)
} else {
sessionRb.Add(nil, details.nickMask, "JOIN", chname)
}
if session.capabilities.Has(caps.ReadMarker) {
chcfname := channel.NameCasefolded()
sessionRb.Add(nil, client.server.name, "MARKREAD", chname, client.GetReadMarker(chcfname))
}
channel.SendTopic(client, sessionRb, false)
if !session.capabilities.Has(caps.NoImplicitNames) {
channel.Names(client, sessionRb)
}
sessionRb.Send(false)
}
// Part parts the given client from this channel, with the given message.
func (channel *Channel) Part(client *Client, message string, rb *ResponseBuffer) {
channel.stateMutex.RLock()
chname := channel.name
clientData, ok := channel.members[client]