forked from PyLink/PyLink
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclasses.py
2147 lines (1786 loc) · 88.1 KB
/
classes.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
"""
classes.py - Base classes for PyLink IRC Services.
This module contains the base classes used by PyLink, including threaded IRC
connections and objects used to represent IRC servers, users, and channels.
Here be dragons.
"""
import threading
import time
import socket
import ssl
import hashlib
import ipaddress
import queue
QUEUE_FULL = queue.Full
import functools
import string
import re
import collections
import collections.abc
import textwrap
try:
import ircmatch
except ImportError:
raise ImportError("PyLink requires ircmatch to function; please install it and try again.")
from . import world, utils, structures, conf, __version__, selectdriver
from .log import *
from .utils import ProtocolError # Compatibility with PyLink 1.x
### Internal classes (users, servers, channels)
class ChannelState(structures.IRCCaseInsensitiveDict):
"""
A dictionary storing channels case insensitively. Channel objects are initialized on access.
"""
def __getitem__(self, key):
key = self._keymangle(key)
if key not in self._data:
log.debug('(%s) ChannelState: creating new channel %s in memory', self._irc.name, key)
self._data[key] = newchan = Channel(self._irc, key)
return newchan
return self._data[key]
class TSObject():
"""Base class for classes containing a type-normalized timestamp."""
def __init__(self, *args, **kwargs):
self._ts = int(time.time())
@property
def ts(self):
return self._ts
@ts.setter
def ts(self, value):
if (not isinstance(value, int)) and (not isinstance(value, float)):
log.warning('TSObject: Got bad type for TS, converting from %s to int',
type(value), stack_info=True)
value = int(value)
self._ts = value
class User(TSObject):
"""PyLink IRC user class."""
def __init__(self, irc, nick, ts, uid, server, ident='null', host='null',
realname='PyLink dummy client', realhost='null',
ip='0.0.0.0', manipulatable=False, opertype='IRC Operator'):
super().__init__()
self._nick = nick
self.lower_nick = irc.to_lower(nick)
self.ts = ts
self.uid = uid
self.ident = ident
self.host = host
self.realhost = realhost
self.ip = ip
self.realname = realname
self.modes = set() # Tracks user modes
self.server = server
self._irc = irc
# Tracks PyLink identification status
self.account = ''
# Tracks oper type (for display only)
self.opertype = opertype
# Tracks external services identification status
self.services_account = ''
# Tracks channels the user is in
self.channels = structures.IRCCaseInsensitiveSet(self._irc)
# Tracks away message status
self.away = ''
# This sets whether the client should be marked as manipulatable.
# Plugins like bots.py's commands should take caution against
# manipulating these "protected" clients, to prevent desyncs and such.
# For "serious" service clients, this should always be False.
self.manipulatable = manipulatable
# Cloaked host for IRCds that use it
self.cloaked_host = None
# Stores service bot name if applicable
self.service = None
@property
def nick(self):
return self._nick
@nick.setter
def nick(self, newnick):
oldnick = self.lower_nick
self._nick = newnick
self.lower_nick = self._irc.to_lower(newnick)
# Update the irc.users bynick index:
if oldnick in self._irc.users.bynick:
# Remove existing value -> key mappings.
self._irc.users.bynick[oldnick].remove(self.uid)
# Remove now-empty keys as well.
if not self._irc.users.bynick[oldnick]:
del self._irc.users.bynick[oldnick]
# Update the new nick.
self._irc.users.bynick.setdefault(self.lower_nick, []).append(self.uid)
def get_fields(self):
"""
Returns all template/substitution-friendly fields for the User object in a read-only dictionary.
"""
fields = self.__dict__.copy()
# These don't really make sense in text substitutions
for field in ('manipulatable', '_irc'):
del fields[field]
# Pre-format the channels list. FIXME: maybe this should be configurable somehow?
fields['channels'] = ','.join(sorted(self.channels))
# Swap SID and server name for convenience
fields['sid'] = self.server
try:
fields['server'] = self._irc.get_friendly_name(self.server)
except KeyError:
pass # Keep it as is (i.e. as the SID) if grabbing the server name fails
# Network name
fields['netname'] = self._irc.name
# Join umodes together
fields['modes'] = self._irc.join_modes(self.modes)
# Add the nick attribute; this isn't in __dict__ because it's a property
fields['nick'] = self._nick
return fields
def __repr__(self):
return 'User(%s/%s)' % (self.uid, self.nick)
IrcUser = User
# Bidirectional dict based off https://stackoverflow.com/a/21894086
class UserMapping(collections.abc.MutableMapping, structures.CopyWrapper):
"""
A mapping storing User objects by UID, as well as UIDs by nick via
the 'bynick' attribute
"""
def __init__(self, irc, data=None):
if data is not None:
assert isinstance(data, dict)
self._data = data
else:
self._data = {}
self.bynick = collections.defaultdict(list)
self._irc = irc
def __getitem__(self, key):
return self._data[key]
def __setitem__(self, key, userobj):
assert hasattr(userobj, 'lower_nick'), "Cannot add object without lower_nick attribute to UserMapping"
if key in self._data:
log.warning('(%s) Attempting to replace User object for %r: %r -> %r', self._irc.name,
key, self._data.get(key), userobj)
self._data[key] = userobj
self.bynick.setdefault(userobj.lower_nick, []).append(key)
def __delitem__(self, key):
# Remove this entry from the bynick index
if self[key].lower_nick in self.bynick:
self.bynick[self[key].lower_nick].remove(key)
if not self.bynick[self[key].lower_nick]:
del self.bynick[self[key].lower_nick]
del self._data[key]
# Generic container methods. XXX: consider abstracting this out in structures?
def __repr__(self):
return "%s(%s)" % (self.__class__.__name__, self._data)
def __iter__(self):
return iter(self._data)
def __len__(self):
return len(self._data)
def __contains__(self, key):
return self._data.__contains__(key)
def __copy__(self):
return self.__class__(self._irc, data=self._data.copy())
class PyLinkNetworkCore(structures.CamelCaseToSnakeCase):
"""Base IRC object for PyLink."""
def __init__(self, netname):
self.loghandlers = []
self.name = netname
self.conf = conf.conf
self.sid = None
self.serverdata = conf.conf['servers'][netname]
self.protoname = self.__class__.__module__.split('.')[-1] # Remove leading pylinkirc.protocols.
self.proto = self.irc = self # Backwards compat
# Protocol stuff
self.casemapping = 'rfc1459'
self.hook_map = {}
# Lists required conf keys for the server block.
self.conf_keys = {'ip', 'port', 'hostname', 'sid', 'sidrange', 'protocol', 'sendpass',
'recvpass'}
# Defines a set of PyLink protocol capabilities
self.protocol_caps = set()
# These options depend on self.serverdata from above to be set.
self.encoding = None
self.connected = threading.Event()
self._aborted = threading.Event()
self._aborted_send = threading.Event()
self._reply_lock = threading.RLock()
# Sets the multiplier for autoconnect delay (grows with time).
self.autoconnect_active_multiplier = 1
self.was_successful = False
self._init_vars()
def log_setup(self):
"""
Initializes any channel loggers defined for the current network.
"""
try:
channels = conf.conf['logging']['channels'][self.name]
except (KeyError, TypeError): # Not set up; just ignore.
return
log.debug('(%s) Setting up channel logging to channels %r', self.name,
channels)
# Only create handlers if they haven't already been set up.
if not self.loghandlers:
if not isinstance(channels, dict):
log.warning('(%s) Got invalid channel logging configuration %r; are your indentation '
'and block commenting consistent?', self.name, channels)
return
for channel, chandata in channels.items():
# Fetch the log level for this channel block.
level = None
if isinstance(chandata, dict):
level = chandata.get('loglevel')
else:
log.warning('(%s) Got invalid channel logging pair %r: %r; are your indentation '
'and block commenting consistent?', self.name, filename, config)
handler = PyLinkChannelLogger(self, channel, level=level)
self.loghandlers.append(handler)
log.addHandler(handler)
def _init_vars(self):
"""
(Re)sets an IRC object to its default state. This should be called when
an IRC object is first created, and on every reconnection to a network.
"""
self.encoding = self.serverdata.get('encoding') or 'utf-8'
# Tracks the main PyLink client's UID.
self.pseudoclient = None
# Internal variable to set the place and caller of the last command (in PM
# or in a channel), used by fantasy command support.
self.called_by = None
self.called_in = None
# Intialize the server, channel, and user indexes to be populated by
# our protocol module.
self.servers = {}
self.users = UserMapping(self)
# Two versions of the channels index exist in PyLink 2.0, and they are joined together
# - irc._channels which implicitly creates channels on access (mostly used
# in protocol modules)
# - irc.channels which does not (recommended for use by plugins)
self._channels = ChannelState(self)
self.channels = structures.IRCCaseInsensitiveDict(self, data=self._channels._data)
# This sets the list of supported channel and user modes: the default
# RFC1459 modes are implied. Named modes are used here to make
# protocol-independent code easier to write, as mode chars vary by
# IRCd.
# Protocol modules should add to and/or replace this with what their
# protocol supports. This can be a hardcoded list or something
# negotiated on connect, depending on the nature of their protocol.
self.cmodes = {'op': 'o', 'secret': 's', 'private': 'p',
'noextmsg': 'n', 'moderated': 'm', 'inviteonly': 'i',
'topiclock': 't', 'limit': 'l', 'ban': 'b',
'voice': 'v', 'key': 'k',
# This fills in the type of mode each mode character is.
# A-type modes are list modes (i.e. bans, ban exceptions, etc.),
# B-type modes require an argument to both set and unset,
# but there can only be one value at a time
# (i.e. cmode +k).
# C-type modes require an argument to set but not to unset
# (one sets "+l limit" and # "-l"),
# and D-type modes take no arguments at all.
'*A': 'b',
'*B': 'k',
'*C': 'l',
'*D': 'imnpst'}
self.umodes = {'invisible': 'i', 'snomask': 's', 'wallops': 'w',
'oper': 'o',
'*A': '', '*B': '', '*C': '', '*D': 'iosw'}
# Acting extbans such as +b m:n!u@h on InspIRCd
self.extbans_acting = {}
# Matching extbans such as R:account on InspIRCd and $a:account on TS6.
self.extbans_matching = {}
# This max nick length starts off as the config value, but may be
# overwritten later by the protocol module if such information is
# received. It defaults to 30.
self.maxnicklen = self.serverdata.get('maxnicklen', 30)
# Defines a list of supported prefix modes.
self.prefixmodes = {'o': '@', 'v': '+'}
# Defines the uplink SID (to be filled in by protocol module).
self.uplink = None
self.start_ts = int(time.time())
# Set up channel logging for the network
self.log_setup()
def __repr__(self):
return "<%s object for network %r>" % (self.__class__.__name__, self.name)
## Stubs
def validate_server_conf(self):
return
def connect(self):
raise NotImplementedError
def disconnect(self):
raise NotImplementedError
## General utility functions
def call_hooks(self, hook_args):
"""Calls a hook function with the given hook args."""
numeric, command, parsed_args = hook_args
# Always make sure TS is sent.
if 'ts' not in parsed_args:
parsed_args['ts'] = int(time.time())
hook_cmd = command
hook_map = self.hook_map
# If the hook name is present in the protocol module's hook_map, then we
# should set the hook name to the name that points to instead.
# For example, plugins will read SETHOST as CHGHOST, EOS (end of sync)
# as ENDBURST, etc.
if command in hook_map:
hook_cmd = hook_map[command]
# However, individual handlers can also return a 'parse_as' key to send
# their payload to a different hook. An example of this is "/join 0"
# being interpreted as leaving all channels (PART).
hook_cmd = parsed_args.get('parse_as') or hook_cmd
log.debug('(%s) Raw hook data: [%r, %r, %r] received from %s handler '
'(calling hook %s)', self.name, numeric, hook_cmd, parsed_args,
command, hook_cmd)
# Iterate over registered hook functions, catching errors accordingly.
for hook_pair in world.hooks[hook_cmd].copy():
hook_func = hook_pair[1]
try:
log.debug('(%s) Calling hook function %s from plugin "%s"', self.name,
hook_func, hook_func.__module__)
retcode = hook_func(self, numeric, command, parsed_args)
if retcode is False:
log.debug('(%s) Stopping hook loop for %r (command=%r)', self.name,
hook_func, command)
break
except Exception:
# We don't want plugins to crash our servers...
log.exception('(%s) Unhandled exception caught in hook %r from plugin "%s"',
self.name, hook_func, hook_func.__module__)
log.error('(%s) The offending hook data was: %s', self.name,
hook_args)
continue
def call_command(self, source, text):
"""
Calls a PyLink bot command. source is the caller's UID, and text is the
full, unparsed text of the message.
"""
world.services['pylink'].call_cmd(self, source, text)
def msg(self, target, text, notice=None, source=None, loopback=True, wrap=True):
"""Handy function to send messages/notices to clients. Source
is optional, and defaults to the main PyLink client if not specified."""
if not text:
return
if not (source or self.pseudoclient):
# No explicit source set and our main client wasn't available; abort.
return
source = source or self.pseudoclient.uid
def _msg(text):
if notice:
self.notice(source, target, text)
cmd = 'PYLINK_SELF_NOTICE'
else:
self.message(source, target, text)
cmd = 'PYLINK_SELF_PRIVMSG'
# Determines whether we should send a hook for this msg(), to forward things like services
# replies across relay.
if loopback:
self.call_hooks([source, cmd, {'target': target, 'text': text}])
# Optionally wrap the text output.
if wrap:
for line in self.wrap_message(source, target, text):
_msg(line)
else:
_msg(text)
def _reply(self, text, notice=None, source=None, private=None, force_privmsg_in_private=False,
loopback=True, wrap=True):
"""
Core of the reply() function - replies to the last caller in the right context
(channel or PM).
"""
if private is None:
# Allow using private replies as the default, if no explicit setting was given.
private = conf.conf['pylink'].get("prefer_private_replies")
# Private reply is enabled, or the caller was originally a PM
if private or (self.called_in in self.users):
if not force_privmsg_in_private:
# For private replies, the default is to override the notice=True/False argument,
# and send replies as notices regardless. This is standard behaviour for most
# IRC services, but can be disabled if force_privmsg_in_private is given.
notice = True
target = self.called_by
else:
target = self.called_in
self.msg(target, text, notice=notice, source=source, loopback=loopback, wrap=wrap)
def reply(self, *args, **kwargs):
"""
Replies to the last caller in the right context (channel or PM).
This function wraps around _reply() and can be monkey-patched in a thread-safe manner
to temporarily redirect plugin output to another target.
"""
with self._reply_lock:
self._reply(*args, **kwargs)
def error(self, text, **kwargs):
"""Replies with an error to the last caller in the right context (channel or PM)."""
# This is a stub to alias error to reply
self.reply("Error: %s" % text, **kwargs)
## Configuration-based lookup functions.
def version(self):
"""
Returns a detailed version string including the PyLink daemon version,
the protocol module in use, and the server hostname.
"""
fullversion = 'PyLink-%s. %s :[protocol:%s, encoding:%s]' % (__version__, self.hostname(), self.protoname, self.encoding)
return fullversion
def hostname(self):
"""
Returns the server hostname used by PyLink on the given server.
"""
return self.serverdata.get('hostname', world.fallback_hostname)
def get_full_network_name(self):
"""
Returns the full network name (as defined by the "netname" option), or the
short network name if that isn't defined.
"""
return self.serverdata.get('netname', self.name)
def get_service_option(self, servicename, option, default=None, global_option=None):
"""
Returns the value of the requested service bot option on the current network, or the
global value if it is not set for this network. This function queries and returns:
1) If present, the value of the config option servers::<NETNAME>::<SERVICENAME>_<OPTION>
2) If present, the value of the config option <SERVICENAME>::<GLOBAL_OPTION>, where
<GLOBAL_OPTION> is either the 'global_option' keyword argument or <OPTION>.
3) The default value given in the 'keyword' argument.
While service bot and config option names can technically be uppercase or mixed case,
the convention is to define them in all lowercase characters.
"""
netopt = self.serverdata.get('%s_%s' % (servicename, option))
if netopt is not None:
return netopt
if global_option is not None:
option = global_option
globalopt = conf.conf.get(servicename, {}).get(option)
if globalopt is not None:
return globalopt
return default
def has_cap(self, capab):
"""
Returns whether this protocol module instance has the requested capability.
"""
return capab.lower() in self.protocol_caps
## Shared helper functions
def _pre_connect(self):
"""
Implements triggers called before a network connects.
"""
self._aborted_send.clear()
self._aborted.clear()
self._init_vars()
try:
self.validate_server_conf()
except Exception as e:
log.error("(%s) Configuration error: %s", self.name, e)
raise
def _run_autoconnect(self):
"""Blocks for the autoconnect time and returns True if autoconnect is enabled."""
if world.shutting_down.is_set():
log.debug('(%s) _run_autoconnect: aborting autoconnect attempt since we are shutting down.', self.name)
return
autoconnect = self.serverdata.get('autoconnect')
# Sets the autoconnect growth multiplier (e.g. a value of 2 multiplies the autoconnect
# time by 2 on every failure, etc.)
autoconnect_multiplier = self.serverdata.get('autoconnect_multiplier', 2)
autoconnect_max = self.serverdata.get('autoconnect_max', 1800)
# These values must at least be 1.
autoconnect_multiplier = max(autoconnect_multiplier, 1)
autoconnect_max = max(autoconnect_max, 1)
log.debug('(%s) _run_autoconnect: Autoconnect delay set to %s seconds.', self.name, autoconnect)
if autoconnect is not None and autoconnect >= 1:
log.debug('(%s) _run_autoconnect: Multiplying autoconnect delay %s by %s.', self.name, autoconnect, self.autoconnect_active_multiplier)
autoconnect *= self.autoconnect_active_multiplier
# Add a cap on the max. autoconnect delay, so that we don't go on forever...
autoconnect = min(autoconnect, autoconnect_max)
log.info('(%s) _run_autoconnect: Going to auto-reconnect in %s seconds.', self.name, autoconnect)
# Continue when either self._aborted is set or the autoconnect time passes.
# Compared to time.sleep(), this allows us to stop connections quicker if we
# break while while for autoconnect.
self._aborted.clear()
self._aborted.wait(autoconnect)
# Store in the local state what the autoconnect multiplier currently is.
self.autoconnect_active_multiplier *= autoconnect_multiplier
if self not in world.networkobjects.values():
log.debug('(%s) _run_autoconnect: Stopping stale connect loop', self.name)
return
return True
else:
log.debug('(%s) _run_autoconnect: Stopping connect loop (autoconnect value %r is < 1).', self.name, autoconnect)
return
def _pre_disconnect(self):
"""
Implements triggers called before a network disconnects.
"""
self._aborted.set()
self.was_successful = self.connected.is_set()
log.debug('(%s) _pre_disconnect: got %s for was_successful state', self.name, self.was_successful)
log.debug('(%s) _pre_disconnect: Clearing self.connected state.', self.name)
self.connected.clear()
log.debug('(%s) _pre_disconnect: Removing channel logging handlers due to disconnect.', self.name)
while self.loghandlers:
log.removeHandler(self.loghandlers.pop())
def _post_disconnect(self):
"""
Implements triggers called after a network disconnects.
"""
# Internal hook signifying that a network has disconnected.
self.call_hooks([None, 'PYLINK_DISCONNECT', {'was_successful': self.was_successful}])
# Clear the to_lower cache.
self.to_lower.cache_clear()
def _remove_client(self, numeric):
"""Internal function to remove a client from our internal state."""
for c, v in self.channels.copy().items():
v.remove_user(numeric)
# Clear empty non-permanent channels.
if not (self.channels[c].users or ((self.cmodes.get('permanent'), None) in self.channels[c].modes)):
del self.channels[c]
sid = self.get_server(numeric)
try:
del self.users[numeric]
self.servers[sid].users.discard(numeric)
except KeyError:
log.debug('(%s) Skipping removing client %s that no longer exists', self.name, numeric,
exc_info=True)
else:
log.debug('(%s) Removing client %s from user + server state', self.name, numeric)
## State checking functions
def nick_to_uid(self, nick):
"""Looks up the UID of a user with the given nick, if one is present."""
nick = self.to_lower(nick)
uids = self.users.bynick.get(nick, [])
if len(uids) > 1:
log.warning('(%s) Multiple UIDs found for nick %r: %r; using the last one!', self.name, nick, uids)
try:
return uids[-1]
except IndexError:
return None
def is_internal_client(self, numeric):
"""
Returns whether the given client numeric (UID) is a PyLink client.
"""
sid = self.get_server(numeric)
if sid and self.servers[sid].internal:
return True
return False
def is_internal_server(self, sid):
"""Returns whether the given SID is an internal PyLink server."""
return (sid in self.servers and self.servers[sid].internal)
def get_server(self, numeric):
"""Finds the SID of the server a user is on."""
userobj = self.users.get(numeric)
if userobj:
return userobj.server
def is_manipulatable_client(self, uid):
"""
Returns whether the given user is marked as an internal, manipulatable
client. Usually, automatically spawned services clients should have this
set True to prevent interactions with opers (like mode changes) from
causing desyncs.
"""
return self.is_internal_client(uid) and self.users[uid].manipulatable
def get_service_bot(self, uid):
"""
Checks whether the given UID is a registered service bot. If True,
returns the cooresponding ServiceBot object.
"""
userobj = self.users.get(uid)
if not userobj:
return False
# Look for the "service" attribute in the User object,sname = userobj.service
# Warn if the service name we fetched isn't a registered service.
sname = userobj.service
if sname is not None and sname not in world.services.keys():
log.warning("(%s) User %s / %s had a service bot record to a service that doesn't "
"exist (%s)!", self.name, uid, userobj.nick, sname)
return world.services.get(sname)
structures._BLACKLISTED_COPY_TYPES.append(PyLinkNetworkCore)
class PyLinkNetworkCoreWithUtils(PyLinkNetworkCore):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# Lock for updateTS to make sure only one thread can change the channel TS at one time.
self._ts_lock = threading.Lock()
@functools.lru_cache(maxsize=8192)
def to_lower(self, text):
if not text:
return text
if self.casemapping == 'rfc1459':
text = text.replace('{', '[')
text = text.replace('}', ']')
text = text.replace('|', '\\')
text = text.replace('~', '^')
# Encode the text as bytes first, and then lowercase it so that only ASCII characters are
# changed. Unicode in channel names, etc. *is* case sensitive!
return text.encode().lower().decode()
_NICK_REGEX = r'^[A-Za-z\|\\_\[\]\{\}\^\`][A-Z0-9a-z\-\|\\_\[\]\{\}\^\`]*$'
@classmethod
def is_nick(cls, s, nicklen=None):
"""Returns whether the string given is a valid IRC nick."""
if nicklen and len(s) > nicklen:
return False
return bool(re.match(cls._NICK_REGEX, s))
@staticmethod
def is_channel(s):
"""Returns whether the string given is a valid IRC channel name."""
return str(s).startswith('#')
@staticmethod
def _isASCII(s):
"""Returns whether the given string only contains non-whitespace ASCII characters."""
chars = string.ascii_letters + string.digits + string.punctuation
return all(char in chars for char in s)
@classmethod
def is_server_name(cls, s):
"""Returns whether the string given is a valid IRC server name."""
return cls._isASCII(s) and '.' in s and not s.startswith('.')
_HOSTMASK_RE = re.compile(r'^\S+!\S+@\S+$')
@classmethod
def is_hostmask(cls, text):
"""Returns whether the given text is a valid IRC hostmask (nick!user@host)."""
# Band-aid patch here to prevent bad bans set by Janus forwarding people into invalid channels.
return bool(cls._HOSTMASK_RE.match(text) and '#' not in text)
def _parse_modes(self, args, existing, supported_modes, is_channel=False, prefixmodes=None,
ignore_missing_args=False):
"""
parse_modes() core.
args: A mode string or a mode string split by space (type list)
existing: A set or iterable of existing modes
supported_modes: a dict of PyLink supported modes (mode names mapping
to mode chars, with *ABCD keys)
prefixmodes: a dict of prefix modes (irc.prefixmodes style)
"""
prefix = ''
if isinstance(args, str):
# If the modestring was given as a string, split it into a list.
args = args.split()
assert args, 'No valid modes were supplied!'
modestring = args[0]
args = args[1:]
existing = set(existing)
res = []
for mode in modestring:
if mode in '+-':
prefix = mode
else:
if not prefix:
prefix = '+'
arg = None
log.debug('Current mode: %s%s; args left: %s', prefix, mode, args)
try:
if prefixmodes and mode in self.prefixmodes:
# We're setting a prefix mode on someone (e.g. +o user1)
log.debug('Mode %s: This mode is a prefix mode.', mode)
arg = args.pop(0)
# Convert nicks to UIDs implicitly
arg = self.nick_to_uid(arg) or arg
if arg not in self.users: # Target doesn't exist, skip it.
log.debug('(%s) Skipping setting mode "%s %s"; the '
'target doesn\'t seem to exist!', self.name,
mode, arg)
continue
elif mode in (supported_modes['*A'] + supported_modes['*B']):
# Must have parameter.
log.debug('Mode %s: This mode must have parameter.', mode)
arg = args.pop(0)
if prefix == '-':
if mode in supported_modes['*B'] and arg == '*':
# Charybdis allows unsetting +k without actually
# knowing the key by faking the argument when unsetting
# as a single "*".
# We'd need to know the real argument of +k for us to
# be able to unset the mode.
oldarg = dict(existing).get(mode)
if oldarg:
# Set the arg to the old one on the channel.
arg = oldarg
log.debug("Mode %s: coersing argument of '*' to %r.", mode, arg)
log.debug('(%s) parse_modes: checking if +%s %s is in old modes list: %s', self.name, mode, arg, existing)
if (mode, arg) not in existing:
# Ignore attempts to unset bans that don't exist.
log.debug("(%s) parse_modes(): ignoring removal of non-existent list mode +%s %s", self.name, mode, arg)
continue
elif prefix == '+' and mode in supported_modes['*C']:
# Only has parameter when setting.
log.debug('Mode %s: Only has parameter when setting.', mode)
arg = args.pop(0)
except IndexError:
logfunc = log.debug if ignore_missing_args else log.warning
logfunc('(%s) Error while parsing mode %r: mode requires an '
'argument but none was found. (modestring: %r)',
self.name, mode, modestring)
continue # Skip this mode; don't error out completely.
newmode = (prefix + mode, arg)
res.append(newmode)
# Tentatively apply the new mode to the "existing" mode list.
existing = self._apply_modes(existing, [newmode], is_channel=is_channel)
return res
def parse_modes(self, target, args, ignore_missing_args=False):
"""Parses a modestring list into a list of (mode, argument) tuples.
['+mitl-o', '3', 'person'] => [('+m', None), ('+i', None), ('+t', None), ('+l', '3'), ('-o', 'person')]
"""
# http://www.irc.org/tech_docs/005.html
# A = Mode that adds or removes a nick or address to a list. Always has a parameter.
# B = Mode that changes a setting and always has a parameter.
# C = Mode that changes a setting and only has a parameter when set.
# D = Mode that changes a setting and never has a parameter.
is_channel = self.is_channel(target)
if not is_channel:
log.debug('(%s) Using self.umodes for this query: %s', self.name, self.umodes)
if target not in self.users:
log.debug('(%s) Possible desync! Mode target %s is not in the users index.', self.name, target)
return [] # Return an empty mode list
supported_modes = self.umodes
oldmodes = self.users[target].modes
prefixmodes = None
else:
log.debug('(%s) Using self.cmodes for this query: %s', self.name, self.cmodes)
supported_modes = self.cmodes
oldmodes = self._channels[target].modes
prefixmodes = self._channels[target].prefixmodes
return self._parse_modes(args, oldmodes, supported_modes, is_channel=is_channel,
prefixmodes=prefixmodes, ignore_missing_args=ignore_missing_args)
def _apply_modes(self, old_modelist, changedmodes, is_channel=False,
prefixmodes=None):
"""
Takes a list of parsed IRC modes, and applies them onto the given target mode list.
"""
modelist = set(old_modelist)
if is_channel:
supported_modes = self.cmodes
else:
supported_modes = self.umodes
for mode in changedmodes:
# Chop off the +/- part that parse_modes gives; it's meaningless for a mode list.
try:
real_mode = (mode[0][1], mode[1])
except IndexError:
real_mode = mode
if is_channel:
if prefixmodes is not None:
# We only handle +qaohv for now. Iterate over every supported mode:
# if the IRCd supports this mode and it is the one being set, add/remove
# the person from the corresponding prefix mode list (e.g. c.prefixmodes['op']
# for ops).
for pmode, pmodelist in prefixmodes.items():
if pmode in supported_modes and real_mode[0] == supported_modes[pmode]:
if mode[0][0] == '+':
pmodelist.add(mode[1])
else:
pmodelist.discard(mode[1])
if real_mode[0] in self.prefixmodes:
# Don't add prefix modes to Channel.modes; they belong in the
# prefixmodes mapping handled above.
log.debug('(%s) Not adding mode %s to Channel.modes because '
'it\'s a prefix mode.', self.name, str(mode))
continue
if mode[0][0] != '-':
log.debug('(%s) Adding mode %r on %s', self.name, real_mode, modelist)
# We're adding a mode
existing = [m for m in modelist if m[0] == real_mode[0] and m[1] != real_mode[1]]
if existing and real_mode[1] and real_mode[0] not in supported_modes['*A']:
# The mode we're setting takes a parameter, but is not a list mode (like +beI).
# Therefore, only one version of it can exist at a time, and we must remove
# any old modepairs using the same letter. Otherwise, we'll get duplicates when,
# for example, someone sets mode "+l 30" on a channel already set "+l 25".
log.debug('(%s) Old modes for mode %r exist in %s, removing them: %s',
self.name, real_mode, modelist, str(existing))
[modelist.discard(oldmode) for oldmode in existing]
modelist.add(real_mode)
else:
log.debug('(%s) Removing mode %r from %s', self.name, real_mode, modelist)
# We're removing a mode
if real_mode[1] is None:
# We're removing a mode that only takes arguments when setting.
# Remove all mode entries that use the same letter as the one
# we're unsetting.
for oldmode in modelist.copy():
if oldmode[0] == real_mode[0]:
modelist.discard(oldmode)
else:
modelist.discard(real_mode)
log.debug('(%s) Final modelist: %s', self.name, modelist)
return modelist
def apply_modes(self, target, changedmodes):
"""Takes a list of parsed IRC modes, and applies them on the given target.
The target can be either a channel or a user; this is handled automatically."""
is_channel = self.is_channel(target)
prefixmodes = None
try:
if is_channel:
c = self._channels[target]
old_modelist = c.modes
prefixmodes = c.prefixmodes
else:
old_modelist = self.users[target].modes
except KeyError:
log.warning('(%s) Possible desync? Mode target %s is unknown.', self.name, target)
return
modelist = self._apply_modes(old_modelist, changedmodes, is_channel=is_channel,
prefixmodes=prefixmodes)
try:
if is_channel:
self._channels[target].modes = modelist
else:
self.users[target].modes = modelist
except KeyError:
log.warning("(%s) Invalid MODE target %s (is_channel=%s)", self.name, target, is_channel)
@staticmethod
def _flip(mode):
"""Flips a mode character."""
# Make it a list first; strings don't support item assignment
mode = list(mode)
if mode[0] == '-': # Query is something like "-n"
mode[0] = '+' # Change it to "+n"
elif mode[0] == '+':
mode[0] = '-'
else: # No prefix given, assume +
mode.insert(0, '-')
return ''.join(mode)
def reverse_modes(self, target, modes, oldobj=None):
"""Reverses/inverts the mode string or mode list given.
Optionally, an oldobj argument can be given to look at an earlier state of
a channel/user object, e.g. for checking the op status of a mode setter