-
-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathplugin.py
4876 lines (4601 loc) · 236 KB
/
plugin.py
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) 2013, Nicolas Coevoet
# Copyright (c) 2010, Daniel Folkinshteyn - taken some ideas about threading database (MessageParser)
# Copyright (c) 2004, Jeremiah Fincher - taken duration parser from plugin Time
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions, and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions, and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the author of this software nor the name of
# contributors to this software may be used to endorse or promote products
# derived from this software without specific prior written consent.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
###
import os, re, sqlite3, socket, threading
import collections, random, time
from operator import itemgetter
from ipaddress import ip_address as IPAddress
from ipaddress import ip_network as IPNetwork
from supybot.commands import *
from supybot import utils, ircutils, ircmsgs, ircdb, plugins, callbacks
from supybot import conf, registry, log, schedule, world
from . import server
# due to more kind of pattern checked, increase size
ircutils._hostmaskPatternEqualCache = utils.structures.CacheDict(10000)
cache = utils.structures.CacheDict(10000)
mcidr = re.compile(r'^(\d{1,3}\.){0,3}\d{1,3}/\d{1,2}$')
m6cidr = re.compile(r'^([0-9a-f]{0,4}:){2,7}[0-9a-f]{0,4}/\d{1,3}$')
def checkAddressed(irc, text, channel):
if irc.isChannel(channel):
if text[0] in str(conf.supybot.reply.whenAddressedBy.chars.get(channel)):
return True
elif text[0] in conf.supybot.reply.whenAddressedBy.chars():
return True
return False
def isCommand(cbs, args):
for c in cbs:
if c.isCommandMethod(args[0]):
return True
if args[0] == c.name().lower() and len(args) > 1 \
and isCommand([c], args[1:]):
return True
if isCommand(c.cbs, args):
return True
def compareString(a, b):
"""return 0 to 1 float percent of similarity (0.85 seems to be a good average)"""
if a == b:
return 1
sa, sb = set(a), set(b)
n = len(sa.intersection(sb))
if float(len(sa) + len(sb) - n) == 0:
return 0
jacc = n / float(len(sa) + len(sb) - n)
return jacc
repetr = re.compile(r"(.+?)\1+")
def repetitions(s):
for match in repetr.finditer(s):
yield (match.group(1), len(match.group(0))/len(match.group(1)))
def largestString(s1, s2):
"""return largest pattern available in 2 strings"""
# From https://en.wikibooks.org/wiki/Algorithm_Implementation/Strings/Longest_common_substring#Python2
# License: CC BY-SA
m = [[0] * (1 + len(s2)) for i in range(1 + len(s1))]
longest, x_longest = 0, 0
for x in range(1, 1 + len(s1)):
for y in range(1, 1 + len(s2)):
if s1[x - 1] == s2[y - 1]:
m[x][y] = m[x - 1][y - 1] + 1
if m[x][y] > longest:
longest = m[x][y]
x_longest = x
else:
m[x][y] = 0
return s1[x_longest - longest: x_longest]
def findPattern(text, minimalCount, minimalLength, minimalPercent):
items = list(repetitions(text))
size = len(text)
candidates = []
for item in items:
(pattern, count) = item
percent = (len(pattern) * count) / size
if len(pattern) > minimalLength:
if count > minimalCount or percent > minimalPercent:
candidates.append(pattern)
candidates.sort(key=len, reverse=True)
return None if len(candidates) == 0 else candidates[0]
def matchHostmask(pattern, n, resolve):
# return the matched pattern for Nick
if not (n.prefix and ircutils.isUserHostmask(n.prefix)):
return None
(nick, ident, host) = ircutils.splitHostmask(n.prefix)
if n.ip is not None and '@' in pattern and n.ip.find('*') == -1 \
and mcidr.match(pattern.split('@')[1]):
address = IPAddress('%s' % n.ip)
try:
network = IPNetwork(u'%s' % pattern.split('@')[1], strict=False)
if address in network:
return '%s!%s@%s' % (nick, ident, n.ip)
except:
return None
elif n.ip is not None and '@' in pattern and n.ip.find('*') == -1 \
and m6cidr.match(pattern.split('@')[1]):
address = IPAddress('%s' % n.ip)
try:
network = IPNetwork(u'%s' % pattern.split('@')[1], strict=False)
if address in network:
return '%s!%s@%s' % (nick, ident, n.ip)
except:
return None
if ircutils.isUserHostmask(pattern):
if n.ip is not None and ircutils.hostmaskPatternEqual(pattern, '%s!%s@%s' % (
nick, ident, n.ip)):
return '%s!%s@%s' % (nick, ident, n.ip)
if ircutils.hostmaskPatternEqual(pattern, n.prefix):
return n.prefix
return None
def matchAccount(pattern, pat, negate, n, extprefix):
# for $a, $~a, $a: extended pattern
result = None
if negate:
if not len(pat) and n.account is None:
result = n.prefix
else:
if len(pat):
if n.account is not None and ircutils.hostmaskPatternEqual(
'*!*@%s' % pat, '*!*@%s' % n.account):
result = '%sa:%s' % (extprefix, n.account)
else:
if n.account is not None:
result = '%sa:%s' % (extprefix, n.account)
return result
def matchRealname(pattern, pat, negate, n, extprefix):
# for $~r $r: extended pattern
if n.realname is None:
return None
if negate:
if len(pat) and not ircutils.hostmaskPatternEqual('*!*@%s' % pat, '*!*@%s' % n.realname):
return '%sr:%s' % (extprefix, n.realname.replace(' ', '?'))
else:
if len(pat) and ircutils.hostmaskPatternEqual('*!*@%s' % pat, '*!*@%s' % n.realname):
return '%sr:%s' % (extprefix, n.realname.replace(' ', '?'))
return None
def matchGecos(pattern, pat, negate, n, extprefix):
# for $~x, $x: extended pattern
if n.realname is None:
return None
tests = []
(nick, ident, host) = ircutils.splitHostmask(n.prefix)
tests.append(n.prefix)
if n.ip is not None:
tests.append('%s!%s@%s' % (nick, ident, n.ip))
for test in tests:
test = '%s#%s' % (test, n.realname.replace(' ', '?'))
if negate:
if not ircutils.hostmaskPatternEqual(pat, test):
return test
else:
if ircutils.hostmaskPatternEqual(pat, test):
return test
return None
def match(pattern, n, irc, resolve):
if not pattern:
return None
if not n.prefix:
return None
# check if given pattern match an Nick
key = '%s :: %s' % (pattern, n)
if key in cache:
return cache[key]
#cache[key] = None
extprefix = ''
extmodes = ''
if 'extban' in irc.state.supported:
ext = irc.state.supported['extban']
extprefix = ext.split(',')[0]
extmodes = ext.split(',')[1]
if pattern.startswith(extprefix):
p = pattern[1:]
negate = not p[0] in extmodes
if negate:
p = p[1:]
t = p[0]
p = p[1:]
if len(p):
# remove ':'
p = p[1:]
if extprefix in p and not p.endswith(extprefix):
# forward
p = p.split(extprefix)[0]
#p = p[(p.rfind(extprefix)+1):]
if t == 'a':
cache[key] = matchAccount(pattern, p, negate, n, extprefix)
elif t == 'r':
cache[key] = matchRealname(pattern, p, negate, n, extprefix)
elif t == 'x':
cache[key] = matchGecos(pattern, p, negate, n, extprefix)
elif t == 'z':
return None
else:
# bug if ipv6 is used..
k = pattern[(pattern.rfind(':')+1):]
cache[key] = matchHostmask(k, n, resolve)
else:
p = pattern
if extprefix in p:
p = p.split(extprefix)[0]
cache[key] = matchHostmask(p, n, resolve)
return cache[key]
def getBestPattern(n, irc, useIp=False, resolve=True):
# return best pattern for a given Nick
if not (n.prefix and ircutils.isUserHostmask(n.prefix)):
return []
match(n.prefix, n, irc, resolve)
results = []
(nick, ident, host) = ircutils.splitHostmask(n.prefix)
if host.startswith(('gateway/tor-sasl/', 'gateway/vpn/', 'user/')) \
or ident.startswith('~') or (n.realname and
n.realname.startswith('[https://web.libera.chat]')):
ident = '*'
if n.ip is not None:
if len(n.ip.split(':')) > 4:
# large ipv6, for now, use the full ipv6
#a = n.ip.split(':')
#m = a[0]+':'+a[1]+':'+a[2]+':'+a[3]+':*'
results.append('*!%s@%s' % (ident, n.ip))
else:
if useIp:
results.append('*!%s@*%s' % (ident, n.ip))
else:
results.append('*!%s@%s' % (ident, n.ip))
if '/' in host:
# cloaks
if host.startswith('gateway/'):
h = host.split('/')
if 'x-' in host and not 'vpn/' in host:
# gateway/type/(domain|account) [?/random]
p = ''
if len(h) > 3:
p = '/*'
h = h[:3]
host = '%s%s' % ('/'.join(h), p)
elif host.startswith('nat/'):
h = host.replace('nat/', '')
if '/' in h:
host = 'nat/%s/*' % h.split('/')[0]
k = '*!%s@%s' % (ident, host)
if k not in results:
results.append(k)
extprefix = ''
extmodes = ''
if 'extban' in irc.state.supported:
ext = irc.state.supported['extban']
extprefix = ext.split(',')[0]
extmodes = ext.split(',')[1]
if n.account:
results.append('%sa:%s' % (extprefix, n.account))
if n.realname:
results.append('%sr:%s' % (extprefix, n.realname.replace(' ', '?')))
return results
def clearExtendedBanPattern(pattern, irc):
# a little method to cleanup extended pattern
extprefix = ''
extmodes = ''
if 'extban' in irc.state.supported:
ext = irc.state.supported['extban']
extprefix = ext.split(',')[0]
extmodes = ext.split(',')[1]
if pattern.startswith(extprefix):
pattern = pattern[1:]
if pattern.startswith('~'):
pattern = pattern[1:]
pattern = pattern[1:]
if pattern.startswith(':'):
pattern = pattern[1:]
return pattern
def floatToGMT(t):
f = None
try:
f = float(t)
except:
return None
return time.strftime('%Y-%m-%d %H:%M:%S GMT', time.gmtime(f))
class Ircd(object):
__slots__ = ('irc', 'name', 'channels', 'nicks', 'queue',
'lowQueue', 'logsSize', 'askedItems', 'whoxpending')
# define an ircd, keeps Chan and Nick items
def __init__(self, irc, logsSize):
object.__init__(self)
self.irc = irc
self.name = irc.network
self.channels = ircutils.IrcDict()
self.nicks = ircutils.IrcDict()
# contains IrcMsg, kicks, modes, etc
self.queue = utils.structures.smallqueue()
# contains less important IrcMsgs (sync, logChannel)
self.lowQueue = utils.structures.smallqueue()
self.logsSize = logsSize
self.whoxpending = False
self.askedItems = {}
def getChan(self, irc, channel):
if not (channel and irc):
return None
self.irc = irc
if channel not in self.channels:
self.channels[channel] = Chan(self, channel)
return self.channels[channel]
def getNick(self, irc, nick, raw=False):
if not (nick and irc):
return None
self.irc = irc
if nick not in self.nicks:
self.nicks[nick] = Nick(self.logsSize)
if not (self.nicks[nick].prefix or raw):
try:
self.nicks[nick].setPrefix(irc.state.nickToHostmask(nick))
except:
pass
return self.nicks[nick]
def getItem(self, irc, uid):
# return active item
if not (irc and uid):
return None
for channel in list(self.channels.keys()):
chan = self.getChan(irc, channel)
items = chan.getItems()
for type in list(items.keys()):
for value in items[type]:
item = items[type][value]
if item.uid == uid:
return item
# TODO: maybe uid under modes that need op to be shown ?
return None
def info(self, irc, uid, prefix, db):
# return mode changes summary
if not (uid and prefix):
return []
c = db.cursor()
c.execute("""SELECT channel,oper,kind,mask,begin_at,end_at,removed_at,removed_by
FROM bans WHERE id=? LIMIT 1""", (uid,))
L = c.fetchall()
if not len(L):
c.close()
return []
(channel, oper, kind, mask, begin_at, end_at, removed_at, removed_by) = L[0]
if not ircdb.checkCapability(prefix, '%s,op' % channel):
c.close()
return []
results = []
current = time.time()
results.append([channel, '[%s] [%s] %s sets +%s %s' % (
channel, floatToGMT(begin_at), oper, kind, mask)])
if not removed_at:
if begin_at == end_at:
results.append([channel, 'is set forever'])
else:
s = 'set for %s,' % utils.timeElapsed(end_at-begin_at)
remaining = end_at - current
if remaining >= 0:
s += ' with %s more,' % utils.timeElapsed(remaining)
s += ' and ends at [%s]' % floatToGMT(end_at)
else:
s += ' expired %s,' % utils.timeElapsed(remaining)
s += ' and ended at [%s]' % floatToGMT(end_at)
results.append([channel, s])
else:
s = 'was active %s and ended on [%s]' % (
utils.timeElapsed(removed_at-begin_at), floatToGMT(removed_at))
if end_at != begin_at:
s += ', initially for %s' % utils.timeElapsed(end_at-begin_at)
s += ', removed by %s' % removed_by
results.append([channel, s])
c.execute("""SELECT oper,comment FROM comments WHERE ban_id=?""", (uid,))
L = c.fetchall()
if len(L):
for com in L:
(oper, comment) = com
results.append([channel,'"%s" by %s' % (comment, oper)])
c.execute("""SELECT full,log FROM nicks WHERE ban_id=?""", (uid,))
L = c.fetchall()
if len(L) == 1:
for affected in L:
(full, log) = affected
message = ""
for line in log.split('\n'):
message = '%s' % line
break
results.append([channel,message])
elif len(L) > 1:
results.append([channel,'affects %s users' % len(L)])
# if len(L):
# for affected in L:
# (full, log) = affected
# message = full
# for line in log.split('\n'):
# message = '[%s]' % line
# break
# results.append(message)
c.close()
return results
def pending(self, irc, channel, mode, prefix, pattern, db, never, ids, duration):
# returns active items for a channel mode
if not (channel and mode and prefix):
return []
chan = self.getChan(irc, channel)
results = []
r = []
c = db.cursor()
t = time.time()
for m in mode:
items = chan.getItemsFor(m)
if len(items):
for item in items:
item = items[item]
if never:
if item.when == item.expire or not item.expire:
r.append([item.uid, item.mode, item.value,
item.by, item.when, item.expire])
else:
if duration > 0:
#log.debug('%s -> %s : %s' % (duration,item.when,(t-item.when)))
if (t - item.when) > duration:
r.append([item.uid, item.mode, item.value,
item.by, item.when, item.expire])
else:
r.append([item.uid, item.mode, item.value,
item.by, item.when, item.expire])
r.sort(reverse=True)
if len(r):
for item in r:
(uid, mode, value, by, when, expire) = item
if not (pattern is None or ircutils.hostmaskPatternEqual(pattern, by)):
continue
c.execute("""SELECT oper,comment FROM comments WHERE ban_id=?
ORDER BY at DESC LIMIT 1""", (uid,))
L = c.fetchall()
if len(L):
(oper, comment) = L[0]
message = ' "%s"' % comment
else:
message = ''
if ids:
results.append('%s' % uid)
elif expire and expire != when:
results.append('[#%s +%s %s by %s expires at %s]%s' % (
uid, mode, value, by, floatToGMT(expire), message))
else:
results.append('[#%s +%s %s by %s on %s]%s' % (
uid, mode, value, by, floatToGMT(when), message))
c.close()
return results
def against(self, irc, channel, n, prefix, db, ct):
# returns active items that match n
if not (channel and n and db):
return []
chan = self.getChan(irc, channel)
results = []
r = []
c = db.cursor()
channels = []
for k in list(chan.getItems()):
items = chan.getItemsFor(k)
if len(items):
for item in items:
item = items[item]
if match(item.value, n, irc, ct.registryValue('resolveIp')):
r.append([item.uid, item.mode, item.value,
item.by, item.when, item.expire])
elif item.value.find('$j:') == 0:
channels.append(item.value.replace('$j:', ''))
if len(channels):
for ch in channels:
cha = self.getChan(irc, ch)
for k in list(cha.getItems()):
items = cha.getItemsFor(k)
if len(items):
for item in items:
item = items[item]
if match(item.value, n, irc, ct.registryValue('resolveIp')):
r.append([item.uid, item.mode, item.value,
item.by, item.when, item.expire])
r.sort(reverse=True)
if len(r):
for item in r:
(uid, mode, value, by, when, expire) = item
c.execute("""SELECT oper,comment FROM comments WHERE ban_id=?
ORDER BY at DESC LIMIT 1""", (uid,))
L = c.fetchall()
if len(L):
(oper, comment) = L[0]
message = ' "%s"' % comment
else:
message = ''
if expire and expire != when:
results.append('[#%s +%s %s by %s expires at %s]%s' % (
uid, mode, value, by, floatToGMT(expire), message))
else:
results.append('[#%s +%s %s by %s on %s]%s' % (
uid, mode, value, by, floatToGMT(when), message))
c.close()
return results
def log(self, irc, uid, prefix, db):
# return log of users affected by a mode change
if not (uid and prefix):
return []
c = db.cursor()
c.execute("""SELECT channel FROM bans WHERE id=?""", (uid,))
L = c.fetchall()
if not len(L):
c.close()
return []
(channel,) = L[0]
if not ircdb.checkCapability(prefix, '%s,op' % channel):
c.close()
return []
results = []
# c.execute("""SELECT oper,comment,at FROM comments WHERE ban_id=?
# ORDER BY at DESC""", (uid,))
# L = c.fetchall()
# if len(L):
# for com in L:
# (oper, comment, at) = com
# results.append('"%s" by %s on %s' % (comment, oper, floatToGMT(at)))
c.execute("""SELECT full,log FROM nicks WHERE ban_id=?""", (uid,))
L = c.fetchall()
if len(L):
for item in L:
(full, log) = item
results.append('For [%s]' % full)
for line in log.split('\n'):
results.append(line)
else:
results.append('no log found')
c.close()
return results
def search(self, irc, pattern, prefix, db, deep, active, never, channel, ids):
# deep search inside database,
# results filtered depending prefix capability
c = db.cursor()
bans = set([])
results = []
isOwner = ircdb.checkCapability(prefix, 'owner') or prefix == irc.prefix
glob = '*%s*' % pattern
like = '%%%s%%' % pattern
if pattern.startswith('$'):
pattern = clearExtendedBanPattern(pattern, irc)
glob = '*%s*' % pattern
like = '%%%s%%' % pattern
elif ircutils.isUserHostmask(pattern):
(n, i, h) = ircutils.splitHostmask(pattern)
if n == '*':
n = None
if i == '*':
i = None
if h == '*':
h = None
items = [n, i, h]
subpattern = ''
for item in items:
if item:
subpattern += '*%s' % item
glob = '*%s*' % subpattern
like = '%%%s%%' % subpattern
c.execute("""SELECT id,mask FROM bans ORDER BY id DESC""")
items = c.fetchall()
if len(items):
for item in items:
(uid, mask) = item
if ircutils.hostmaskPatternEqual(pattern, mask):
bans.add(uid)
c.execute("""SELECT ban_id,full FROM nicks ORDER BY ban_id DESC""")
items = c.fetchall()
if len(items):
for item in items:
(uid, full) = item
if ircutils.hostmaskPatternEqual(pattern, full):
bans.add(uid)
if deep:
c.execute("""SELECT ban_id,full FROM nicks WHERE full GLOB ? OR full LIKE ?
OR log GLOB ? OR log LIKE ? ORDER BY ban_id DESC""", (glob, like, glob, like))
else:
c.execute("""SELECT ban_id,full FROM nicks WHERE full GLOB ? OR full LIKE ?
ORDER BY ban_id DESC""", (glob, like))
items = c.fetchall()
if len(items):
for item in items:
(uid, full) = item
bans.add(uid)
c.execute("""SELECT id,mask FROM bans WHERE mask GLOB ? OR mask LIKE ?
ORDER BY id DESC""", (glob, like))
items = c.fetchall()
if len(items):
for item in items:
(uid, mask) = item
bans.add(uid)
c.execute("""SELECT ban_id,comment FROM comments WHERE comment GLOB ? OR comment LIKE ?
ORDER BY ban_id DESC""", (glob, like))
items = c.fetchall()
if len(items):
for item in items:
(uid, comment) = item
bans.add(uid)
if len(bans):
for uid in bans:
c.execute("""SELECT id,mask,kind,channel,begin_at,end_at,removed_at
FROM bans WHERE id=? ORDER BY id DESC LIMIT 1""", (uid,))
items = c.fetchall()
for item in items:
(uid, mask, kind, chan, begin_at, end_at, removed_at) = item
if isOwner or ircdb.checkCapability(prefix, '%s,op' % chan):
if (never or active) and removed_at:
continue
if never and begin_at != end_at:
continue
if channel and chan != channel:
continue
results.append([uid, mask, kind, chan])
if len(results):
results.sort(reverse=True)
i = 0
msgs = []
while i < len(results):
(uid, mask, kind, chan) = results[i]
if ids:
msgs.append('%s' % uid)
elif channel and len(channel):
msgs.append('[#%s +%s %s]' % (uid, kind, mask))
else:
msgs.append('[#%s +%s %s in %s]' % (uid, kind, mask, chan))
i += 1
c.close()
return msgs
c.close()
return []
def affect(self, irc, uid, prefix, db):
# return users affected by a mode change
if not (uid and prefix):
return []
c = db.cursor()
c.execute("""SELECT channel FROM bans WHERE id=?""", (uid,))
L = c.fetchall()
if not len(L):
c.close()
return []
(channel,) = L[0]
if not ircdb.checkCapability(prefix, '%s,op' % channel):
c.close()
return []
results = []
c.execute("""SELECT full,log FROM nicks WHERE ban_id=?""", (uid,))
L = c.fetchall()
if len(L):
for item in L:
(full, log) = item
message = full
for line in log.split('\n'):
message = '[%s]' % line
break
results.append(message)
else:
results.append('nobody affected')
c.close()
return results
def markremoved(self, irc, uid, message, prefix, db, ct):
# won't use channel,mode,value, because Item may be removed already
# it's a duplicate of mark, only used to compute logChannel on a removed item
if not (prefix and message):
return False
c = db.cursor()
c.execute("""SELECT id,channel,kind,mask FROM bans WHERE id=?""", (uid,))
L = c.fetchall()
b = False
if len(L):
(uid, channel, kind, mask) = L[0]
if not (ircdb.checkCapability(prefix, '%s,op' % channel)
or prefix == irc.prefix):
c.close()
return False
current = time.time()
c.execute("""INSERT INTO comments VALUES (?, ?, ?, ?)""", (uid, prefix, current, message))
db.commit()
f = None
if (prefix != irc.prefix and ct.registryValue('announceMark', channel=channel, network=irc.network)) \
or (prefix == irc.prefix and ct.registryValue('announceBotMark', channel=channel, network=irc.network)):
f = ct._logChan
if f:
if ct.registryValue('useColorForAnnounces', channel=channel, network=irc.network):
f(irc, channel, '[%s] [#%s %s %s] marked by %s: %s' % (
ircutils.bold(channel), ircutils.mircColor(uid, 'yellow', 'black'),
ircutils.bold(ircutils.mircColor('+%s' % kind, 'red')),
ircutils.mircColor(mask, 'light blue'), prefix.split('!')[0], message))
else:
f(irc, channel, '[%s] [#%s +%s %s] marked by %s: %s' % (
channel, uid, kind, mask, prefix.split('!')[0], message))
b = True
c.close()
return b
def mark(self, irc, uid, message, prefix, db, logFunction, ct):
# won't use channel,mode,value, because Item may be removed already
if not (prefix and message):
return False
c = db.cursor()
c.execute("""SELECT id,channel,kind,mask FROM bans WHERE id=?""", (uid,))
L = c.fetchall()
b = False
if len(L):
(uid, channel, kind, mask) = L[0]
if not (ircdb.checkCapability(prefix, '%s,op' % channel)
or prefix == irc.prefix):
c.close()
return False
current = time.time()
c.execute("""INSERT INTO comments VALUES (?, ?, ?, ?)""", (uid, prefix, current, message))
db.commit()
if logFunction:
key = '%s|%s' % (kind, mask)
if key in ct.smartLog and ct.smartLog[key]:
if 'edited by' in ct.smartLog[key][-1]:
message = 'and marked: %s' % message
else:
message = 'marked by %s: %s' % (prefix.split('!')[0], message)
message = '; '.join(ct.smartLog[key] + [message])
del ct.smartLog[key]
elif ct.registryValue('useColorForAnnounces', channel=channel, network=irc.network):
message = '[%s] [#%s %s %s] marked by %s: %s' % (
ircutils.bold(channel), ircutils.mircColor(uid, 'yellow', 'black'),
ircutils.bold(ircutils.mircColor('+%s' % kind, 'red')),
ircutils.mircColor(mask, 'light blue'), prefix.split('!')[0], message)
else:
message = '[%s] [#%s +%s %s] marked by %s: %s' % (
channel, uid, kind, mask, prefix.split('!')[0], message)
logFunction(irc, channel, message)
b = True
c.close()
return b
def submark(self, irc, channel, mode, value, message, prefix, db, logFunction, ct):
# add mark to an item that is not already in lists
if not (channel and mode and value and prefix):
return False
if not (ircdb.checkCapability(prefix, '%s,op' % channel)
or prefix == irc.prefix):
return False
c = db.cursor()
c.execute("""SELECT id,oper FROM bans WHERE channel=? AND kind=? AND mask=?
AND removed_at is NULL ORDER BY id LIMIT 1""", (channel, mode, value))
L = c.fetchall()
c.close()
if len(L):
# item exists
(uid, oper) = L[0]
# should not happen, but..
return self.mark(irc, uid, message, prefix, db, logFunction, ct)
elif channel in self.channels:
chan = self.getChan(irc, channel)
item = chan.getItem(mode, value)
if not item:
# prepare item update after being set (we don't have id yet)
key = '%s|%s' % (mode, value)
chan.mark[key] = [mode, value, message, prefix]
return True
return False
def add(self, irc, channel, mode, value, seconds, autoexpire, prefix, db):
# add new eIqb item
if channel not in self.channels:
return False
if not (channel and mode and value and prefix):
return False
if not (ircdb.checkCapability(prefix, '%s,op' % channel)
or prefix == irc.prefix):
return False
c = db.cursor()
c.execute("""SELECT id,oper FROM bans WHERE channel=? AND kind=? AND mask=?
AND removed_at is NULL ORDER BY id LIMIT 1""", (channel, mode, value))
L = c.fetchall()
c.close()
chan = self.getChan(irc, channel)
# prepare item update after being set (we don't have id yet)
key = '%s|%s' % (mode, value)
if seconds is not None:
chan.update[key] = [mode, value, seconds, prefix]
else:
chan.update[key] = [mode, value, autoexpire, irc.prefix]
if not len(L):
# enqueue mode changes
chan.queue.enqueue(('+%s' % mode, value))
return True
def remove(self, uid, db):
c = db.cursor()
c.execute("""SELECT id,channel,kind,mask FROM bans WHERE id=? LIMIT 1""", (uid,))
L = c.fetchall()
if len(L):
c.execute("""DELETE FROM bans WHERE id=? LIMIT 1""", (uid,))
c.execute("""DELETE FROM comments WHERE ban_id=?""", (uid,))
c.execute("""DELETE FROM nicks WHERE ban_id=?""", (uid,))
db.commit()
c.close()
return True
c.close()
return False
def edit(self, irc, channel, mode, value, seconds, prefix, db, scheduleFunction, logFunction, ct):
# edit eIqb duration
if not (channel and mode and value and prefix):
return False
if not (ircdb.checkCapability(prefix, '%s,op' % channel)
or prefix == irc.prefix):
return False
c = db.cursor()
c.execute("""SELECT id,channel,kind,mask,begin_at,end_at FROM bans WHERE channel=? AND kind=?
AND mask=? AND removed_at is NULL ORDER BY id LIMIT 1""", (channel, mode, value))
L = c.fetchall()
b = False
if len(L):
(uid, channel, kind, mask, begin_at, end_at) = L[0]
chan = self.getChan(irc, channel)
current = time.time()
if begin_at == end_at:
if seconds < 0:
c.close()
return True
text = 'was set forever'
else:
text = 'ended [%s] for %s' % (
floatToGMT(end_at), utils.timeElapsed(end_at-begin_at))
if seconds < 0:
newEnd = begin_at
expires = 'expires never'
elif seconds == 0:
newEnd = current # force expires on next tickle
expires = 'expires at [%s], for %s in total' % (
floatToGMT(newEnd), utils.timeElapsed(newEnd-begin_at))
else:
newEnd = current + seconds
expires = 'expires at [%s], for %s in total' % (
floatToGMT(newEnd), utils.timeElapsed(newEnd-begin_at))
text = '%s, now %s' % (text, expires)
c.execute("""INSERT INTO comments VALUES (?, ?, ?, ?)""", (uid, prefix, current, text))
c.execute("""UPDATE bans SET end_at=? WHERE id=?""", (newEnd, int(uid)))
db.commit()
i = chan.getItem(kind, mask)
if i:
if newEnd == begin_at:
i.expire = None
else:
i.expire = newEnd
if scheduleFunction and newEnd != current:
scheduleFunction(irc, newEnd, prefix != irc.prefix)
if logFunction:
key = '%s|%s' % (kind, mask)
if key in ct.smartLog and ct.smartLog[key]:
message = 'edited by %s: %s' % (prefix.split('!')[0], expires)
elif ct.registryValue('useColorForAnnounces', channel=channel, network=irc.network):
message = '[%s] [#%s %s %s] edited by %s: %s' % (
ircutils.bold(channel), ircutils.mircColor(uid, 'yellow', 'black'),
ircutils.bold(ircutils.mircColor('+%s' % kind, 'red')),
ircutils.mircColor(mask, 'light blue'), prefix.split('!')[0], expires)
else:
message = '[%s] [#%s +%s %s] edited by %s: %s' % (
channel, uid, kind, mask, prefix.split('!')[0], expires)
if key in ct.smartLog:
ct.smartLog[key].append(message)
else:
logFunction(irc, channel, message)
b = True
c.close()
return b
def resync(self, irc, channel, mode, db, logFunction, ct):
# sync mode lists; if items were removed when bot was offline, mark records as removed
c = db.cursor()
c.execute("""SELECT id,channel,mask FROM bans WHERE channel=? AND kind=?
AND removed_at is NULL ORDER BY id""", (channel, mode))
L = c.fetchall()
current = time.time()
commits = 0
msgs = []
if len(L):
current = time.time()
if channel in irc.state.channels:
chan = self.getChan(irc, channel)
if mode in chan.dones:
for record in L:
(uid, channel, mask) = record
item = chan.getItem(mode, mask)
if not item:
c.execute("""UPDATE bans SET removed_at=?, removed_by=? WHERE id=?""",
(current, 'offline!offline@offline', int(uid)))
commits += 1
if ct.registryValue('useColorForAnnounces', channel=channel, network=irc.network):
msgs.append('[#%s %s]' % (ircutils.mircColor(uid, 'yellow', 'black'),
ircutils.mircColor(mask, 'light blue')))
else:
msgs.append('[#%s %s]' % (uid, mask))
self.verifyRemoval(irc, channel, mode, mask, db, ct, uid)
if commits > 0:
db.commit()
if logFunction:
if ct.registryValue('useColorForAnnounces', channel=channel, network=irc.network):
logFunction(irc, channel, '[%s] [%s] %s removed: %s' % (ircutils.bold(
channel), ircutils.bold(ircutils.mircColor(mode, 'green')),
commits, ' '.join(msgs)))
else:
logFunction(irc, channel, '[%s] [%s] %s removed: %s' % (
channel, mode, commits, ' '.join(msgs)))
# TODO: restore patterns
c.execute("""SELECT id,pattern,regexp,trigger,life,mode,duration
FROM patterns WHERE channel=? ORDER BY id""", (channel,))
L = c.fetchall()
if len(L):
if channel in irc.state.channels:
chan = self.getChan(irc, channel)
for record in L:
(uid, pattern, regexp, trigger, life, mode, duration) = record
chan.patterns[uid] = Pattern(uid, pattern,
int(regexp) == 1, trigger, life, mode, duration)
c.close()
def verifyRemoval (self, irc, channel, mode, value, db, ct, uid):
if ct.registryValue('autoRemoveUnregisteredQuiets', channel=channel, network=irc.network) and mode == 'q' and value == '$~a':
self.remove(uid, db)
class Chan(object):
__slots__ = ('ircd', 'name', '_lists', 'queue', 'update', 'mark', 'action', 'dones', 'syn', 'opAsked',
'deopAsked', 'deopPending', 'spam', 'repeatLogs', 'nicks', 'netsplit', 'attacked', 'patterns')
# in memory and in database stores +eIqb list -ov
# no user action from here, only ircd messages
def __init__(self, ircd, name):
object.__init__(self)
self.ircd = ircd