-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathirc.py
More file actions
3745 lines (3211 loc) · 164 KB
/
irc.py
File metadata and controls
3745 lines (3211 loc) · 164 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/python
from threading import Thread, Condition, currentThread
from threading import RLock as Lock
import re
import time
import sys
import string
import socket
import os
import platform
import traceback
import ssl
import glob
from collections import deque, OrderedDict
import chardet
import codecs
import new
import inspect
import warnings
import random
import data
__all__ = ["Connection", "Channel", "ChanList",
"User", "UserList", "Config", "timestamp"]
def autodecode(s):
try:
return s.decode("utf8")
except UnicodeDecodeError:
# Attempt to figure encoding
detected = chardet.detect(s)
try:
if detected['encoding'] is not None:
return s.decode(detected['encoding'])
else:
return s.decode("utf8", "replace")
except UnicodeDecodeError:
return s.decode("utf8", "replace")
except LookupError:
return s.decode("utf8", "replace")
class AddonWarning(Warning):
pass
class ConnectionWarning(Warning):
pass
class AddonError(BaseException):
pass
class InvalidName(BaseException):
"""Raised when an invalid string is passed of as a nickname."""
pass
class InvalidPrefix(BaseException):
"""Raised when an string with an invalid prefix is passed of as a channel name."""
pass
class InvalidCharacter(BaseException):
pass
class ConnectionTimedOut(BaseException):
"""Raised when the connection times out during a blocked Channel.join() or Channel.part() call."""
pass
class ConnectionClosed(BaseException):
pass
class RequestTimedOut(BaseException):
"""Raised when a timeout is reached during a blocked Channel.join() or Channel.part() call."""
pass
class NotConnected(BaseException):
"""Raised when attempting to send data to a server when not connected."""
pass
class BannedFromChannel(BaseException):
"""Raised in a blocked Channel.join() call when server returns a 474 reply (Banned from Channel)."""
pass
class RedirectedJoin(BaseException):
"""Raised in a blocked Channel.join() call when server returns a 470 reply (Channel redirect)."""
pass
class ChannelFull(BaseException):
pass
class InviteOnly(BaseException):
pass
class NotOnChannel(BaseException):
pass
class NoSuchChannel(BaseException):
pass
class BadChannelKey(BaseException):
pass
class BadChannelMask(BaseException):
pass
class TooManyChannels(BaseException):
pass
class Unavailable(BaseException):
pass
class Cbaned(BaseException):
pass
class ActionAlreadyRequested(BaseException):
pass
class OpersOnly(BaseException):
pass
class OperCreateOnly(BaseException):
pass
class SSLOnly(BaseException):
pass
class AlreadyJoined(BaseException):
pass
class AlreadyConnected(BaseException):
pass
class RegistrationRequired(BaseException):
pass
class RejoinDelay(BaseException):
pass
_rfc1459casemapping = string.maketrans(string.ascii_uppercase + r'\[]~',
string.ascii_lowercase + r'|{}^').decode("ISO-8859-2")
# The IRC RFC does not permit the first character in a nickname to be a
# numeral. However, this is not always adhered to.
_nickmatch = r"^[A-Za-z0-9\-\^\`\\\|\_\{\}\[\]]+$"
_intmatch = r"^\d+$"
_chanmatch = r"^[%%s][^%s\s\n]*$" % re.escape("\x07,")
_targchanmatch = r"^([%%s]?)([%%s][^%s\s\n]*)$" % re.escape("\x07,")
_usermatch = r"^[A-Za-z0-9\-\^\`\\\|\_\{\}\[\]]+$"
_realnamematch = r"^[^\n]*$"
_ircmatch = r"^(?::(.+?)(?:!(.+?)@(.+?))?\s+)?([A-Za-z0-9]+?)\s*(?:\s+(.+?)(?:\s+(.+?))??)??(?:\s+:(.*))?$"
_ctcpmatch = "^\x01(.*?)(?:\\s+(.*?)\\s*)?\x01$"
_prefixmatch = r"\((.*)\)(.*)"
_defaultchanmodes = u"b,k,l,imnpst".split(",")
_defaultprefix = ("ov", "@+")
_defaultchantypes = "&#+!"
_capmodifiers = "~=-"
_privmodeeventnames = dict(q=("Owner", "Deowner"), a=("Admin", "Deadmin"), o=(
"Op", "Deop"), h=("Halfop", "Dehalfop"), v=("Voice", "Devoice"))
_maskmodeeventnames = dict(b=("Ban", "Unban"), e=(
"BanExcept", "UnbanExcept"), I=("Invite", "Uninvite"))
exceptcodes = {489: SSLOnly, 384: Cbaned, 403: NoSuchChannel, 405: TooManyChannels, 442: NotOnChannel, 470: RedirectedJoin, 471: ChannelFull, 473: InviteOnly, 474:
BannedFromChannel, 475: BadChannelKey, 476: BadChannelMask, 520: OpersOnly, 437: Unavailable, 477: RegistrationRequired, 495: RejoinDelay, 530: OperCreateOnly}
_lock = Lock()
_networks = {}
def timestamp():
t = time.time()
ms = 1000 * t % 1000
ymdhms = time.localtime(t)
tz = time.altzone if ymdhms.tm_isdst else time.timezone
sgn = "-" if tz >= 0 else "+"
return "%04d-%02d-%02d %02d:%02d:%02d.%03d%s%02d:%02d" % (ymdhms[:6] + (1000 * t % 1000, sgn, abs(tz) / 3600, abs(tz) / 60 % 60))
class Connection(object):
__doc__ = "Manages a connection to an IRC network. Includes support for addons."
__name__ = "pyIRC"
__version__ = "2.1"
__author__ = "Brian Sherson"
__date__ = "February 21, 2014"
def __init__(
self, server, port=None, ipvers=(socket.AF_INET6, socket.AF_INET), secure=False, passwd=None,
nick="ircbot", username="python", realname="Python IRC Library",
requestcaps=[], starttls=False, protoctl=[],
autoreconnect=True, retrysleep=5, maxretries=15, label=None,
timeout=300, quietpingpong=True, pinginterval=60, addons=[], autostart=False):
"""__init__(server[, ...])
Constructor for the Connection class.
Arguments:
server: Server name. Can provide host name or IP address.
port: Port to use, or automatically selected if port=None.
ipvers: Tuple of IP protocols to try.
secure: Use SSL.
passwd: Password to be sent with PASS during registration process, or None.
nick: A nickname, or list of nicknames.
username: Username that is requested with USER command during registration process.
realname: Desired GECOS.
requestcaps: List of capabilities to request on connect.
protoctl: Protocols to request when support is detected in 005 response.
autoreconnect: Reconnect automatically when disconnected unexpectedly.
retrysleep: Number of seconds to wait between connection attempts.
maxretries: Number of connection attempts before giving up, or -1 to try indefinitely.
timeout: Read timeout.
quietpingpong: Suppress logging and events on PING and PONG events.
pinginterval: Amount of time of not receiving data from a server aftr which a ping request is to be sent.
addons: List of addons that should be initialized with this instance. Items of this list are either instances of addons or dict objects
containing keyword arguments to be used to configure addons.
autostart: Automatically start connection to IRC server upon initialization.
"""
if port is None or (type(port) == int and 0 < port < 65536):
self.port = port
else:
raise ValueError, "Invalid value for 'port'"
if re.match(_nickmatch, nick) if isinstance(nick, (str, unicode)) else all([re.match(_nickmatch, n) for n in nick]) if isinstance(nick, (list, tuple)) else False:
self.nick = nick
else:
raise ValueError, "Invalid value for 'nick'"
if re.match(_realnamematch, realname):
self.realname = realname
else:
raise InvalidCharacter
if re.match(_usermatch, username):
self.username = username
else:
raise InvalidCharacter
if passwd == None or "\n" not in passwd:
self.passwd = passwd
else:
raise InvalidCharacter
self.server = server
self.secure = secure
self.ipvers = ipvers if type(ipvers) == tuple else (ipvers,)
self.protoctl = protoctl
if type(autoreconnect) == bool:
self.autoreconnect = autoreconnect
else:
raise ValueError, "Invalid value for 'autoreconnect'"
if isinstance(maxretries, (int, long)):
self.maxretries = maxretries
else:
raise ValueError, "Invalid value for 'maxretries'"
if isinstance(timeout, (int, long)):
self.timeout = timeout
else:
raise ValueError, "Invalid value for 'timeout'"
if isinstance(retrysleep, (int, long, float)) and retrysleep >= 0:
self.retrysleep = retrysleep
else:
raise ValueError, "Invalid value for 'retrysleep'"
if type(quietpingpong) == bool:
self.quietpingpong = quietpingpong
else:
raise ValueError, "Invalid value for 'quietpingpong'"
if type(starttls) == bool:
if starttls and secure:
warnings.warn(
"Cannot use STARTTLS when secure=True", ConnectionWarning)
self.starttls = starttls
else:
raise ValueError, "Invalid value for 'starttls'"
if isinstance(requestcaps, (list, tuple)):
self.requestcaps = list(requestcaps)
else:
raise ValueError, "Invalid value for 'requestcaps'"
if type(pinginterval) in (int, long):
self.pinginterval = pinginterval
else:
raise ValueError, "Invalid value for 'pinginterval'"
self._quitexpected = False
self.log = sys.stdout
self.lock = Lock()
self._loglock = Lock()
self._outlock = Lock()
self._sendline = Condition(self._outlock)
self._connecting = Condition(self.lock)
self._disconnecting = Condition(self.lock)
self._outgoing = deque()
self._sendhandlerthread = None
self._recvhandlerthread = None
# Initialize IRC environment variables
self.users = UserList(context=self, withdict=True)
self.channels = ChanList(context=self, withdict=True)
# We are going to try something different, to try to make searching quicker.
# self.users={}
# self.channels={}
self.servers = ServerList(context=self)
self.addons = []
self._label = None
self.label = label
self._init()
for conf in addons:
try:
if type(conf) == dict:
self.addAddon(**conf)
else:
self.addAddon(conf)
except:
pass
if autostart:
self.connect()
def _init(self):
self.data = data.Data(self)
self.ipver = None
self.addr = None
self._connected = False
self._registered = False
self._connection = None
self._starttls = False
self.trynick = 0
self.identity = None
self.serv = None
self.welcome = None
self.hostinfo = None
self.servcreated = None
self.servinfo = None
self.serv005 = None
self.supports = {}
self.throttledata = []
self.throttled = False
self.enabledcaps = []
self.supportedcaps = []
self._requestedcaps = []
self._caplsrequested = False
@property
def label(self):
with self.lock, _lock:
return self._label
@label.setter
def label(self, label):
with self.lock, _lock:
if label == self._label:
return ### What's the point?
if label is None and self._label in _networks.keys():
self._event(self.getalladdons(), [
("onLabelRemove", dict(newlabel=label), False)])
del _networks[self._label]
self._label = label
return
if label in _networks.keys():
raise KeyError, "Label already exists!"
self._event(self.getalladdons(), [
("onLabelChange", dict(newlabel=label), False)])
if self._label in _networks.keys():
del _networks[self._label]
_networks[label] = self
self._label = label
@property
def motdgreet(self):
return self.identity.server.motdgreet
@property
def motd(self):
return self.identity.server.motd
@property
def motdend(self):
return self.identity.server.motdend
@property
def connected(self):
return self._connected
@property
def registered(self):
return self._registered
def logwrite(self, *lines):
"""logwrite(*lines)
Writes one or more line to the log file, signed with a timestamp."""
with self._loglock:
ts = timestamp()
for line in lines:
print >>self.log, u"%s %s" % (ts, line)
self.log.flush()
def logerror(self, *lines):
"""logerror(*lines)
Prints lines and traceback sys.stderr and to the log file."""
exc, excmsg, tb = sys.exc_info()
lines = lines + tuple(traceback.format_exc().split("\n"))
# Print to log AND stderr
self.logwrite(*[u"!!! {line}".format(**vars()) for line in lines])
for line in lines:
print >>sys.stderr, line
def logopen(self, filename, encoding="utf8"):
"""logopen(filename[, encoding])
Sets the log file to 'filename.'"""
with self._loglock:
ts = timestamp()
newlog = codecs.open(filename, "a", encoding=encoding)
if isinstance(self.log, codecs.StreamReaderWriter) and not self.log.closed:
if self.log not in (sys.stdout, sys.stderr):
print >>self.log, "%s ### Log file closed" % (ts)
self.log.close()
self.log = newlog
print >>self.log, "%s ### Log file opened" % (ts)
self.log.flush()
def fireEvent(self, events):
self._event(self.getalladdons(), events)
# Used to call event handlers on all attached addons, when applicable.
def _event(self, addons, events, line=None, data=None, exceptions=False):
handled = []
unhandled = []
errors = []
for k, addon in enumerate(addons + [self]):
if addon in addons and addons.index(addon) < k:
# Duplicate
continue
if type(addon) == Config:
addon = addon.addon
fellback = False # Switch this to True when a fallback is used so that we only call onOther once.
# Iterate through all events.
for (method, args, fallback) in events:
try:
f = getattr(addon, method)
except AttributeError:
if fallback and not fellback and data:
try:
f = getattr(addon, "onOther")
except AttributeError:
unhandled.append(addon)
continue
args = dict(line=line, **data)
fellback = True
else:
unhandled.append(addon)
continue
if type(f) == new.instancemethod:
argspec = inspect.getargspec(f.im_func)
else:
argspec = inspect.getargspec(f)
if argspec.keywords == None:
args = {
arg: val for arg, val in args.items() if arg in argspec.args}
try:
f(self, **args)
except:
# print f, args
exc, excmsg, tb = sys.exc_info()
errors.append((addon, exc, excmsg, tb))
self.logerror(u"Exception in addon {addon}".format(
**vars()), u"Function: %s" % f, u"Arguments: %s" % args)
if exceptions: # If set to true, we raise the exception.
raise
else:
handled.append(addon)
return (handled, unhandled, errors)
def validateAddon(self, addon):
"""validateAddon(addon)
Checks the addon's methods and issues warnings when a method's arguments do not line up with what is expected."""
supported = self.eventsupports()
keys = supported.keys()
for fname in dir(addon):
if fname in keys:
supportedargs = supported[fname]
elif re.match(r"^on(?:Send)?[A-Z]+$", fname):
supportedargs = (
"line", "origin", "target", "targetprefix", "params", "extinfo")
elif re.match(r"^on\d{3}$", fname):
supportedargs = (
"line", "origin", "target", "params", "extinfo")
else:
continue
func = getattr(addon, fname)
argspec = inspect.getargspec(func)
if type(func) == new.instancemethod:
funcargs = argspec.args[1:]
if argspec.defaults:
requiredargs = funcargs[:-len(argspec.defaults)]
else:
requiredargs = funcargs
contextarg = funcargs[0]
unsupported = [
arg for arg in requiredargs[1:] if arg not in supportedargs]
if len(unsupported):
warnings.warn(
"Function '%s' requires unsupported arguments: %s" %
(func.__name__, ", ".join(unsupported)), AddonWarning)
self.logwrite(
"!!! AddonWarning: Function '%s' requires unsupported arguments: %s" %
(func.__name__, ", ".join(unsupported)))
if argspec.keywords == None:
unsupported = [
arg for arg in supportedargs if arg not in funcargs[1:]]
if len(unsupported):
warnings.warn(
"Function '%s' does not accept supported arguments: %s" %
(func.__name__, ", ".join(unsupported)), AddonWarning)
self.logwrite(
"!!! AddonWarning: Function '%s' does not accept supported arguments: %s" %
(func.__name__, ", ".join(unsupported)))
def addAddon(self, addon, **params):
"""addAddon(addon[, ...])
Configures and appends addon to self.addons.
Additional keyword arguments are passed onto addon.onAddonAdd whenever the method exists."""
self.validateAddon(addon)
with self.lock:
addoninstances = [
conf.addon if type(conf) == Config else conf for conf in self.addons]
if addon in addoninstances:
raise AddonError, "Addon already added."
conf = self._configureAddon(addon, **params)
self.addons.append(conf)
self.logwrite("*** Addon %s added." % repr(addon))
def insertAddon(self, index, addon, **params):
"""insertAddon(index, addon[, ...])
The 'list.insert' version of addAddon."""
self.validateAddon(addon)
with self.lock:
addoninstances = [
conf.addon if type(conf) == Config else conf for conf in self.addons]
if addon in addoninstances:
raise AddonError, "Addon already added."
conf = self._configureAddon(addon, **params)
self.addons.insert(index, conf)
self.logwrite("*** Addon %s inserted into index %d." %
(repr(addon), index))
# Configures an addon by calling the addon's onAddonAdd instance (if it
# exists) and returns the appropriate config object (or just the addon
# instance if no config) to put into self.addons
def _configureAddon(self, addon, **params):
if hasattr(addon, "onAddonAdd") and callable(addon.onAddonAdd):
try:
conf = addon.onAddonAdd(self, **params)
except:
self.logerror(
u"An exception has occurred while trying to configure addon {addon}.".format(**vars()))
raise
if conf is None:
return addon
return conf
elif params:
return Config(addon, **params)
else:
return addon
# Removes addon from self.addons
def rmAddon(self, addon):
"""rmAddon(addon)
Removes addon from self.addons."""
with self.lock:
addoninstances = [
conf.addon if type(conf) == Config else conf for conf in self.addons]
del self.addons[addoninstances.index(addon)]
self.logwrite("*** Addon %s removed." % repr(addon))
if hasattr(addon, "onAddonRem") and callable(addon.onAddonAdd):
try:
addon.onAddonRem(self)
except:
self.logerror(
u"An exception has occurred while trying to configure addon {addon}.".format(**vars()))
def connect(self, server=None, port=None, secure=None, ipvers=None, forcereconnect=False, blocking=False):
"""connect([...])
Starts connection to the IRC server. Optional arguments server, port, secure, and ipvers can be
provided to override the current settings.
Use 'forcereconnect=True' to quit existing connection if already connected.
Use 'blocking=True' to wait until connection is established (or maxretries is exhausted)."""
if ipvers != None:
ipvers = ipvers if type(ipvers) == tuple else (ipvers,)
else:
ipvers = self.ipvers
server = server if server else self.server
port = port if port else self.port
secure = secure if secure != None else self.secure
with self._connecting:
if self.isAlive():
if forcereconnect:
self.quit("Changing server...", blocking=True)
else:
raise AlreadyConnected
with self._sendline:
self._outgoing.clear()
self._recvhandlerthread = Thread(target=self._recvhandler, name="Receive Handler", kwargs=dict(
server=server, port=port, secure=secure, ipvers=ipvers))
self._sendhandlerthread = Thread(
target=self._sendhandler, name="Send Handler")
self._recvhandlerthread.start()
self._sendhandlerthread.start()
if blocking:
self._connecting.wait()
if not self.connected:
raise NotConnected
def _connect(self, addr, ipver, secure, hostname=None):
"""Makes a single attempt to connect to server."""
with self.lock:
if self._connected:
raise AlreadyConnected
if hostname:
if ipver == socket.AF_INET6:
addrstr = "{hostname} ([{addr[0]}]:{addr[1]})".format(
**vars())
else:
addrstr = "{hostname} ({addr[0]}:{addr[1]})".format(
**vars())
else:
if ipver == socket.AF_INET6:
addrstr = "[{addr[0]}]:{addr[1]}".format(**vars())
else:
addrstr = "{addr[0]}:{addr[1]}".format(**vars())
self.logwrite(
"*** Attempting connection to {addrstr}.".format(**vars()))
self._event(self.getalladdons(), [
("onConnectAttempt", dict(), False)])
try:
connection = socket.socket(ipver, socket.SOCK_STREAM)
if secure:
connection.settimeout(self.timeout)
self._connection = ssl.wrap_socket(
connection, cert_reqs=ssl.CERT_NONE)
else:
self._connection = connection
self._connection.settimeout(self.timeout)
self._connection.connect(addr)
except socket.error:
exc, excmsg, tb = sys.exc_info()
self.logwrite(
"*** Connection to {addrstr} failed: {excmsg}.".format(**vars()))
with self.lock:
self._event(self.getalladdons(), [
("onConnectFail", dict(exc=exc, excmsg=excmsg, tb=tb), False)])
raise
else:
# Run onConnect on all addons to signal connection was established.
self._connected = True
with self.lock:
self._event(
self.getalladdons(), [("onConnect", dict(), False)])
self.logwrite(
"*** Connection to {addrstr} established.".format(**vars()))
self.addr = addr
with self._connecting:
self._connecting.notifyAll()
def _tryaddrs(self, server, addrs, ipver, secure):
"""Iterates through addrs until a connection is successful, returning True, or returning False when no connections are made.
Raises an exception when it detects Network is unreachable (e.g., IPv6 network is not available)."""
for addr in addrs:
try:
if server == addr[0]:
self._connect(addr=addr, secure=secure, ipver=ipver)
else:
self._connect(
hostname=server, addr=addr, secure=secure, ipver=ipver)
except socket.error, msg:
if self._quitexpected:
sys.exit()
if msg.errno == 101: # Network is unreachable, will pass the exception on.
raise
if self.retrysleep > 0:
time.sleep(self.retrysleep)
if self._quitexpected:
sys.exit()
else:
return True
return False
def _tryipver(self, server, port, ipver, secure):
"""Attempts to resolve 'server' to a one or more IP addresses, then tries to establish a connection."""
if ipver == socket.AF_INET6:
self.logwrite(
"*** Attempting to resolve {server} to an IPv6 address...".format(**vars()))
else:
self.logwrite(
"*** Attempting to resolve {server}...".format(**vars()))
try:
addrs = socket.getaddrinfo(
server, port if port is not None else 6697 if self.secure else 6667, ipver)
except socket.gaierror, msg:
self.logwrite("*** Resolution failed: {msg}.".format(**vars()))
raise
# Weed out duplicates
addrs = list(
set([sockaddr for family, socktype, proto, canonname, sockaddr in addrs if family == ipver]))
n = len(addrs)
if n == 1:
addr = addrs[0]
self.logwrite(
"*** Name {server} resolves to {addr[0]}.".format(**vars()))
else:
self.logwrite(
"*** Name {server} resolves to {n} addresses, choosing one at random until success.".format(**vars()))
random.shuffle(addrs)
return self._tryaddrs(server, addrs, ipver, secure)
def _tryipvers(self, server, port, ipvers, secure):
"""Attempts to try a connection for each IP version in ipvers until a connection is successful."""
for ipver in ipvers:
try:
ret = self._tryipver(server, port, ipver, secure)
except socket.gaierror, msg:
if msg.errno == -2: # Name or service not known. Again, just try next ipver.
continue
else:
raise
except socket.error, msg:
if msg.errno == 101: # Don't err out, just try next ipver.
continue
else:
raise
else:
if ret:
self.ipver = ipver
return True
return False
def _procrecvline(self, line):
"""Called whenever a line of data is received from the IRC server."""
matches = re.findall(_ircmatch, line)
# We have a match!
if len(matches):
(origin, username, host, cmd, target, params, extinfo) = matches[0]
unhandled = []
if re.match(_intmatch, cmd):
cmd = int(cmd) # Code is a numerical response
else:
cmd = cmd.upper()
if cmd not in ("PING", "PONG") or not self.quietpingpong:
self.logwrite("<<< %s" % line)
if origin == "" and cmd == "PING":
self.send(u"PONG :%s" % extinfo)
with self.lock:
data = dict(origin=origin, cmd=cmd, target=target,
targetprefix=None, params=params, extinfo=extinfo)
if username and host and self._registered:
nickname = origin
origin = self.user(origin)
if origin.nick != nickname:
# Origin nickname case has changed
origin.user = nickname
if origin.username != username:
# Origin username has changed
origin.username = username
if origin.host != host:
# Origin host has changed
origin.host = host
else:
origin = self.getserver(origin)
# Check to see if target matches a channel (optionally with
# prefix)
prefix = self.supports.get("PREFIX", _defaultprefix)
chantypes = self.supports.get("CHANTYPES", _defaultchantypes)
chanmatch = re.findall(
_targchanmatch % (re.escape(prefix[1]), re.escape(chantypes)), target)
if chanmatch:
targetprefix, channame = chanmatch[0]
target = self.channel(channame)
if target.name != channame:
# Target channel name has changed case
target.name = channame
# Check to see if target matches a valid nickname. Do NOT
# convert target to User instance if cmd is NICK.
elif re.match(_nickmatch, target) and cmd in ("PRIVMSG", "NOTICE", "MODE", "INVITE", "KILL") and self._registered:
targetprefix = ""
target = self.user(target)
# Otherwise, target is just left as a string
else:
targetprefix = ""
data = dict(origin=origin, cmd=cmd, target=target,
targetprefix=targetprefix, params=params, extinfo=extinfo)
# Parse
# Takes the given data and runs it through a parse method to determine what addon methods should be called later, and prepares the arguments
# to be passed to each of these methods.
# This part does not update the IRC state.
parsename = (
"parse%03d" if type(cmd) == int else "parse%s") % cmd
# This is the case that there is a parse method specific to the
# given cmd.
if hasattr(self, parsename) and callable(getattr(self, parsename)):
parsemethod = getattr(self, parsename)
try:
ret = parsemethod(
origin, target, targetprefix, params, extinfo)
addons, events = ret if ret is not None else (
self.addons, [])
except:
self.logerror(
u"There was an error in parsing the following line:", line)
return
else:
addons = self.addons
if type(cmd) == int:
events = [
("on%03d" % cmd, dict(line=line, origin=origin, target=target, params=params, extinfo=extinfo), True)]
else:
events = [
("on%s" % cmd.upper(), dict(line=line, origin=origin, target=target, targetprefix=targetprefix, params=params, extinfo=extinfo), True)]
# Suppress pings and pongs if self.quietpingpong is set to True
if cmd in ("PING", "PONG") and self.quietpingpong:
return
# Send parsed data to addons having onRecv method first
self._event(
addons, [("onRecv", dict(line=line, **data), False)], line, data)
# Support for further addon events is taken care of here. We also treat the irc.Connection instance itself as an addon for the purpose of
# tracking the IRC state, and should be invoked *last*.
self._event(addons, events, line, data)
def _recvhandler(self, server, port, ipvers, secure):
"""Function that is run as a separate thread, both managing the connection and handling data coming from the IRC server."""
if currentThread() != self._recvhandlerthread: # Enforce that this function must only be run from within self._sendhandlerthread.
raise RuntimeError, "This function is designed to run in its own thread."
try:
with self.lock:
self._event(self.getalladdons(), [
("onSessionOpen", dict(), False)])
self.logwrite("### Session started")
ipvers = ipvers if type(ipvers) == tuple else (ipvers,)
# Autoreconnect loop
while True:
attempt = 1
# Autoretry loop
while True:
servisip = False
for ipver in ipvers: # Check to see if address is a valid ip address instead of host name
try:
socket.inet_pton(ipver, server)
except socket.error:
continue # Not a valid ip address under this ipver.
# Is a valid ip address under this ipver.
if ipver == socket.AF_INET6:
self._tryaddrs(
server, [(server, port, 0, 0)], ipver, secure)
else:
ret = self._tryaddrs(
server, [(server, port)], ipver, secure)
servisip = True
break
# Otherwise, we assume server is a hostname
if not servisip:
ret = self._tryipvers(server, port, ipvers, secure)
if ret:
self.server = server
self.port = port
self.ipvers = ipvers
self.secure = secure
break
if self._quitexpected:
sys.exit()
if self.retrysleep > 0:
time.sleep(self.retrysleep)
if self._quitexpected:
sys.exit()
if attempt < self.maxretries or self.maxretries < 0:
if self._quitexpected:
sys.exit()
attempt += 1
else:
self.logwrite(
"*** Maximum number of attempts reached. Giving up. (%(server)s:%(port)s)" % vars())
with self._connecting:
self._connecting.notifyAll()
sys.exit()
# Connection succeeded
try:
pingreq = None
with self._sendline:
self._sendline.notify()
# Attempt initial registration.
# nick=self.nick[0]
# if self.passwd:
#self.send(u"PASS %s" % self.passwd)
# self._trynick()
# Initialize buffers
linebuf = []
readbuf = ""
while True: # Main loop of IRC connection.