-
Notifications
You must be signed in to change notification settings - Fork 0
/
irc.py
4176 lines (3300 loc) · 127 KB
/
irc.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
# -*- test-case-name: twisted.words.test.test_irc -*-
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
"""
Internet Relay Chat protocol for client and server.
Future Plans
============
The way the IRCClient class works here encourages people to implement
IRC clients by subclassing the ephemeral protocol class, and it tends
to end up with way more state than it should for an object which will
be destroyed as soon as the TCP transport drops. Someone oughta do
something about that, ya know?
The DCC support needs to have more hooks for the client for it to be
able to ask the user things like "Do you want to accept this session?"
and "Transfer #2 is 67% done." and otherwise manage the DCC sessions.
Test coverage needs to be better.
@var MAX_COMMAND_LENGTH: The maximum length of a command, as defined by RFC
2812 section 2.3.
@var attributes: Singleton instance of L{_CharacterAttributes}, used for
constructing formatted text information.
@author: Kevin Turner
@see: RFC 1459: Internet Relay Chat Protocol
@see: RFC 2812: Internet Relay Chat: Client Protocol
@see: U{The Client-To-Client-Protocol
<http://www.irchelp.org/irchelp/rfc/ctcpspec.html>}
"""
import errno, os, random, re, stat, struct, sys, time, traceback
import operator
import string, socket
import textwrap
import shlex
from functools import reduce, partial
from os import path
from base64 import b64encode, b64decode
from twisted.internet import reactor, protocol, task
from twisted.persisted import styles
from twisted.protocols import basic
from twisted.python import log, reflect, _textattributes
from twisted.python.compat import unicode, range
NUL = chr(0)
CR = chr(0o15)
NL = chr(0o12)
LF = NL
SPC = chr(0o40)
# This includes the CRLF terminator characters.
MAX_COMMAND_LENGTH = 512
CHANNEL_PREFIXES = '&#!+'
irclowertranslations = { #modification by inhahe
"ascii": str.maketrans(string.ascii_uppercase,
string.ascii_lowercase),
"rfc1549": str.maketrans(string.ascii_uppercase + "\x7B\x7C\x7D\x7E",
string.ascii_lowercase + "\x5B\x5C\x5E\x5F"),
"strict-rfc1549": str.maketrans(string.ascii_uppercase + "\x7B\x7C\x7D",
string.ascii_lowercase + "\x5B\x5C\x5E")
}
def irclower(text):
trans = irclowertranslations["rfc1549"] #modification by inhahe
return text.translate(trans)
usersplit = re.compile("(?P<nick>.*?)!(?P<ident>.*?)@(?P<host>.*)").match #modification by inhahe
class IRCBadMessage(Exception):
pass
class IRCPasswordMismatch(Exception):
pass
class IRCBadModes(ValueError):
"""
A malformed mode was encountered while attempting to parse a mode string.
"""
def parsemsg(s):
"""
Breaks a message from an IRC server into its prefix, command, and
arguments.
@param s: The message to break.
@type s: L{bytes}
@return: A tuple of (prefix, command, args).
@rtype: L{tuple}
"""
prefix = ''
trailing = []
if not s:
raise IRCBadMessage("Empty line.")
if s[0:1] == ':':
prefix, s = s[1:].split(' ', 1)
if s.find(' :') != -1:
s, trailing = s.split(' :', 1)
args = s.split()
args.append(trailing)
else:
args = s.split()
command = args.pop(0)
return prefix, command, args
def split(str, length=80):
"""
Split a string into multiple lines.
Whitespace near C{str[length]} will be preferred as a breaking point.
C{"\\n"} will also be used as a breaking point.
@param str: The string to split.
@type str: C{str}
@param length: The maximum length which will be allowed for any string in
the result.
@type length: C{int}
@return: C{list} of C{str}
"""
#str = str.decode("ascii") #modification by inhahe
return [chunk
for line in str.split('\n')
for chunk in textwrap.wrap(line, length)]
def _intOrDefault(value, default=None):
"""
Convert a value to an integer if possible.
@rtype: C{int} or type of L{default}
@return: An integer when C{value} can be converted to an integer,
otherwise return C{default}
"""
if value:
try:
return int(value)
except (TypeError, ValueError):
pass
return default
class UnhandledCommand(RuntimeError):
"""
A command dispatcher could not locate an appropriate command handler.
"""
class _CommandDispatcherMixin(object):
"""
Dispatch commands to handlers based on their name.
Command handler names should be of the form C{prefix_commandName},
where C{prefix} is the value specified by L{prefix}, and must
accept the parameters as given to L{dispatch}.
Attempting to mix this in more than once for a single class will cause
strange behaviour, due to L{prefix} being overwritten.
@type prefix: C{str}
@ivar prefix: Command handler prefix, used to locate handler attributes
"""
prefix = None
def dispatch(self, commandName, *args):
"""
Perform actual command dispatch.
"""
def _getMethodName(command):
return '%s_%s' % (self.prefix, command)
def _getMethod(name):
return getattr(self, _getMethodName(name), None)
method = _getMethod(commandName)
if method is not None:
return method(*args)
method = _getMethod('unknown')
if method is None:
raise UnhandledCommand("No handler for %r could be found" % (_getMethodName(commandName),))
return method(commandName, *args)
def parseModes(modes, params, paramModes=('', '')):
"""
Parse an IRC mode string.
The mode string is parsed into two lists of mode changes (added and
removed), with each mode change represented as C{(mode, param)} where mode
is the mode character, and param is the parameter passed for that mode, or
L{None} if no parameter is required.
@type modes: C{str}
@param modes: Modes string to parse.
@type params: C{list}
@param params: Parameters specified along with L{modes}.
@type paramModes: C{(str, str)}
@param paramModes: A pair of strings (C{(add, remove)}) that indicate which modes take
parameters when added or removed.
@returns: Two lists of mode changes, one for modes added and the other for
modes removed respectively, mode changes in each list are represented as
C{(mode, param)}.
"""
if len(modes) == 0:
raise IRCBadModes('Empty mode string')
if modes[0] not in '+-':
raise IRCBadModes('Malformed modes string: %r' % (modes,))
changes = ([], [])
direction = None
count = -1
for ch in modes:
if ch in '+-':
if count == 0:
raise IRCBadModes('Empty mode sequence: %r' % (modes,))
direction = '+-'.index(ch)
count = 0
else:
param = None
if ch in paramModes[direction]:
try:
param = params.pop(0)
except IndexError:
raise IRCBadModes('Not enough parameters: %r' % (ch,))
changes[direction].append((ch, param))
count += 1
if len(params) > 0:
raise IRCBadModes('Too many parameters: %r %r' % (modes, params))
if count == 0:
raise IRCBadModes('Empty mode sequence: %r' % (modes,))
return changes
class IRC(protocol.Protocol):
"""
Internet Relay Chat server protocol.
"""
buffer = ""
hostname = None
encoding = None
def connectionMade(self):
self.channels = []
if self.hostname is None:
self.hostname = socket.getfqdn()
def sendLine(self, line):
line = line + CR + LF
if isinstance(line, unicode):
useEncoding = self.encoding if self.encoding else "utf-8"
line = line.encode(useEncoding)
self.transport.write(line)
def sendMessage(self, command, *parameter_list, **prefix):
"""
Send a line formatted as an IRC message.
First argument is the command, all subsequent arguments are parameters
to that command. If a prefix is desired, it may be specified with the
keyword argument 'prefix'.
The L{sendCommand} method is generally preferred over this one.
Notably, this method does not support sending message tags, while the
L{sendCommand} method does.
"""
if not command:
raise ValueError("IRC message requires a command.")
if ' ' in command or command[0] == ':':
# Not the ONLY way to screw up, but provides a little
# sanity checking to catch likely dumb mistakes.
raise ValueError("Somebody screwed up, 'cuz this doesn't" \
" look like a command to me: %s" % command)
line = ' '.join([command] + list(parameter_list))
if 'prefix' in prefix:
line = ":%s %s" % (prefix['prefix'], line)
self.sendLine(line)
if len(parameter_list) > 15:
log.msg("Message has %d parameters (RFC allows 15):\n%s" %
(len(parameter_list), line))
def sendCommand(self, command, parameters, prefix=None, tags=None):
"""
Send to the remote peer a line formatted as an IRC message.
@param command: The command or numeric to send.
@type command: L{unicode}
@param parameters: The parameters to send with the command.
@type parameters: A L{tuple} or L{list} of L{unicode} parameters
@param prefix: The prefix to send with the command. If not
given, no prefix is sent.
@type prefix: L{unicode}
@param tags: A dict of message tags. If not given, no message
tags are sent. The dict key should be the name of the tag
to send as a string; the value should be the unescaped value
to send with the tag, or either None or "" if no value is to
be sent with the tag.
@type tags: L{dict} of tags (L{unicode}) => values (L{unicode})
@see: U{https://ircv3.net/specs/core/message-tags-3.2.html}
"""
if not command:
raise ValueError("IRC message requires a command.")
if " " in command or command[0] == ":":
# Not the ONLY way to screw up, but provides a little
# sanity checking to catch likely dumb mistakes.
raise ValueError('Invalid command: "%s"' % (command,))
if tags is None:
tags = {}
line = " ".join([command] + list(parameters))
if prefix:
line = ":%s %s" % (prefix, line)
if tags:
tagStr = self._stringTags(tags)
line = "@%s %s" % (tagStr, line)
self.sendLine(line)
if len(parameters) > 15:
log.msg("Message has %d parameters (RFC allows 15):\n%s" %
(len(parameters), line))
def _stringTags(self, tags):
"""
Converts a tag dictionary to a string.
@param tags: The tag dict passed to sendMsg.
@rtype: L{unicode}
@return: IRCv3-format tag string
"""
self._validateTags(tags)
tagStrings = []
for tag, value in tags.items():
if value:
tagStrings.append("%s=%s" % (tag, self._escapeTagValue(value)))
else:
tagStrings.append(tag)
return ";".join(tagStrings)
def _validateTags(self, tags):
"""
Checks the tag dict for errors and raises L{ValueError} if an
error is found.
@param tags: The tag dict passed to sendMsg.
"""
for tag, value in tags.items():
if not tag:
raise ValueError("A tag name is required.")
for char in tag:
if not char.isalnum() and char not in ("-", "/", "."):
raise ValueError("Tag contains invalid characters.")
def _escapeTagValue(self, value):
"""
Escape the given tag value according to U{escaping rules in IRCv3
<https://ircv3.net/specs/core/message-tags-3.2.html>}.
@param value: The string value to escape.
@type value: L{str}
@return: The escaped string for sending as a message value
@rtype: L{str}
"""
return (value.replace("\\", "\\\\")
.replace(";", "\\:")
.replace(" ", "\\s")
.replace("\r", "\\r")
.replace("\n", "\\n")
)
def dataReceived(self, data):
"""
This hack is to support mIRC, which sends LF only, even though the RFC
says CRLF. (Also, the flexibility of LineReceiver to turn "line mode"
on and off was not required.)
"""
if isinstance(data, bytes):
data = data.decode("utf-8")
lines = (self.buffer + data).split(LF)
# Put the (possibly empty) element after the last LF back in the
# buffer
self.buffer = lines.pop()
for line in lines:
if len(line) <= 2:
# This is a blank line, at best.
continue
if line[-1] == CR:
line = line[:-1]
prefix, command, params = parsemsg(line)
# mIRC is a big pile of doo-doo
command = command.upper()
# DEBUG: log.msg( "%s %s %s" % (prefix, command, params))
self.handleCommand(command, prefix, params)
def handleCommand(self, command, prefix, params):
"""
Determine the function to call for the given command and call it with
the given arguments.
@param command: The IRC command to determine the function for.
@type command: L{bytes}
@param prefix: The prefix of the IRC message (as returned by
L{parsemsg}).
@type prefix: L{bytes}
@param params: A list of parameters to call the function with.
@type params: L{list}
"""
self.IRCcommand(command, pnefix, params) #modification by inhahe
method = getattr(self, "irc_%s" % command, None)
try:
if method is not None:
method(prefix, params)
else:
self.irc_unknown(prefix, command, params)
except:
log.deferr()
def irc_unknown(self, prefix, command, params):
"""
Called by L{handleCommand} on a command that doesn't have a defined
handler. Subclasses should override this method.
"""
raise NotImplementedError(command, prefix, params)
# Helper methods
def privmsg(self, sender, recip, message):
"""
Send a message to a channel or user
@type sender: C{str} or C{unicode}
@param sender: Who is sending this message. Should be of the form
username!ident@hostmask (unless you know better!).
@type recip: C{str} or C{unicode}
@param recip: The recipient of this message. If a channel, it must
start with a channel prefix.
@type message: C{str} or C{unicode}
@param message: The message being sent.
"""
self.sendCommand("PRIVMSG", (recip, ":%s" % (lowQuote(message),)), sender)
def notice(self, sender, recip, message):
"""
Send a "notice" to a channel or user.
Notices differ from privmsgs in that the RFC claims they are different.
Robots are supposed to send notices and not respond to them. Clients
typically display notices differently from privmsgs.
@type sender: C{str} or C{unicode}
@param sender: Who is sending this message. Should be of the form
username!ident@hostmask (unless you know better!).
@type recip: C{str} or C{unicode}
@param recip: The recipient of this message. If a channel, it must
start with a channel prefix.
@type message: C{str} or C{unicode}
@param message: The message being sent.
"""
self.sendCommand("NOTICE", (recip, ":%s" % (message,)), sender)
def action(self, sender, recip, message):
"""
Send an action to a channel or user.
@type sender: C{str} or C{unicode}
@param sender: Who is sending this message. Should be of the form
username!ident@hostmask (unless you know better!).
@type recip: C{str} or C{unicode}
@param recip: The recipient of this message. If a channel, it must
start with a channel prefix.
@type message: C{str} or C{unicode}
@param message: The action being sent.
"""
self.sendLine(":%s ACTION %s :%s" % (sender, recip, message))
def topic(self, user, channel, topic, author=None):
"""
Send the topic to a user.
@type user: C{str} or C{unicode}
@param user: The user receiving the topic. Only their nickname, not
the full hostmask.
@type channel: C{str} or C{unicode}
@param channel: The channel for which this is the topic.
@type topic: C{str} or C{unicode} or L{None}
@param topic: The topic string, unquoted, or None if there is no topic.
@type author: C{str} or C{unicode}
@param author: If the topic is being changed, the full username and
hostmask of the person changing it.
"""
if author is None:
if topic is None:
self.sendLine(':%s %s %s %s :%s' % (
self.hostname, RPL_NOTOPIC, user, channel, 'No topic is set.'))
else:
self.sendLine(":%s %s %s %s :%s" % (
self.hostname, RPL_TOPIC, user, channel, lowQuote(topic)))
else:
self.sendLine(":%s TOPIC %s :%s" % (author, channel, lowQuote(topic)))
def topicAuthor(self, user, channel, author, date):
"""
Send the author of and time at which a topic was set for the given
channel.
This sends a 333 reply message, which is not part of the IRC RFC.
@type user: C{str} or C{unicode}
@param user: The user receiving the topic. Only their nickname, not
the full hostmask.
@type channel: C{str} or C{unicode}
@param channel: The channel for which this information is relevant.
@type author: C{str} or C{unicode}
@param author: The nickname (without hostmask) of the user who last set
the topic.
@type date: C{int}
@param date: A POSIX timestamp (number of seconds since the epoch) at
which the topic was last set.
"""
self.sendLine(':%s %d %s %s %s %d' % (
self.hostname, 333, user, channel, author, date))
def names(self, user, channel, names):
"""
Send the names of a channel's participants to a user.
@type user: C{str} or C{unicode}
@param user: The user receiving the name list. Only their nickname,
not the full hostmask.
@type channel: C{str} or C{unicode}
@param channel: The channel for which this is the namelist.
@type names: C{list} of C{str} or C{unicode}
@param names: The names to send.
"""
# XXX If unicode is given, these limits are not quite correct
prefixLength = len(channel) + len(user) + 10
namesLength = 512 - prefixLength
L = []
count = 0
for n in names:
if count + len(n) + 1 > namesLength:
self.sendLine(":%s %s %s = %s :%s" % (
self.hostname, RPL_NAMREPLY, user, channel, ' '.join(L)))
L = [n]
count = len(n)
else:
L.append(n)
count += len(n) + 1
if L:
self.sendLine(":%s %s %s = %s :%s" % (
self.hostname, RPL_NAMREPLY, user, channel, ' '.join(L)))
self.sendLine(":%s %s %s %s :End of /NAMES list" % (
self.hostname, RPL_ENDOFNAMES, user, channel))
def who(self, user, channel, memberInfo):
"""
Send a list of users participating in a channel.
@type user: C{str} or C{unicode}
@param user: The user receiving this member information. Only their
nickname, not the full hostmask.
@type channel: C{str} or C{unicode}
@param channel: The channel for which this is the member information.
@type memberInfo: C{list} of C{tuples}
@param memberInfo: For each member of the given channel, a 7-tuple
containing their username, their hostmask, the server to which they
are connected, their nickname, the letter "H" or "G" (standing for
"Here" or "Gone"), the hopcount from C{user} to this member, and
this member's real name.
"""
for info in memberInfo:
(username, hostmask, server, nickname, flag, hops, realName) = info
assert flag in ("H", "G")
self.sendLine(":%s %s %s %s %s %s %s %s %s :%d %s" % (
self.hostname, RPL_WHOREPLY, user, channel,
username, hostmask, server, nickname, flag, hops, realName))
self.sendLine(":%s %s %s %s :End of /WHO list." % (
self.hostname, RPL_ENDOFWHO, user, channel))
def whois(self, user, nick, username, hostname, realName, server, serverInfo, oper, idle, signOn, channels):
"""
Send information about the state of a particular user.
@type user: C{str} or C{unicode}
@param user: The user receiving this information. Only their nickname,
not the full hostmask.
@type nick: C{str} or C{unicode}
@param nick: The nickname of the user this information describes.
@type username: C{str} or C{unicode}
@param username: The user's username (eg, ident response)
@type hostname: C{str}
@param hostname: The user's hostmask
@type realName: C{str} or C{unicode}
@param realName: The user's real name
@type server: C{str} or C{unicode}
@param server: The name of the server to which the user is connected
@type serverInfo: C{str} or C{unicode}
@param serverInfo: A descriptive string about that server
@type oper: C{bool}
@param oper: Indicates whether the user is an IRC operator
@type idle: C{int}
@param idle: The number of seconds since the user last sent a message
@type signOn: C{int}
@param signOn: A POSIX timestamp (number of seconds since the epoch)
indicating the time the user signed on
@type channels: C{list} of C{str} or C{unicode}
@param channels: A list of the channels which the user is participating in
"""
self.sendLine(":%s %s %s %s %s %s * :%s" % (
self.hostname, RPL_WHOISUSER, user, nick, username, hostname, realName))
self.sendLine(":%s %s %s %s %s :%s" % (
self.hostname, RPL_WHOISSERVER, user, nick, server, serverInfo))
if oper:
self.sendLine(":%s %s %s %s :is an IRC operator" % (
self.hostname, RPL_WHOISOPERATOR, user, nick))
self.sendLine(":%s %s %s %s %d %d :seconds idle, signon time" % (
self.hostname, RPL_WHOISIDLE, user, nick, idle, signOn))
self.sendLine(":%s %s %s %s :%s" % (
self.hostname, RPL_WHOISCHANNELS, user, nick, ' '.join(channels)))
self.sendLine(":%s %s %s %s :End of WHOIS list." % (
self.hostname, RPL_ENDOFWHOIS, user, nick))
def join(self, who, where):
"""
Send a join message.
@type who: C{str} or C{unicode}
@param who: The name of the user joining. Should be of the form
username!ident@hostmask (unless you know better!).
@type where: C{str} or C{unicode}
@param where: The channel the user is joining.
"""
self.sendLine(":%s JOIN %s" % (who, where))
def part(self, who, where, reason=None):
"""
Send a part message.
@type who: C{str} or C{unicode}
@param who: The name of the user joining. Should be of the form
username!ident@hostmask (unless you know better!).
@type where: C{str} or C{unicode}
@param where: The channel the user is joining.
@type reason: C{str} or C{unicode}
@param reason: A string describing the misery which caused this poor
soul to depart.
"""
if reason:
self.sendLine(":%s PART %s :%s" % (who, where, reason))
else:
self.sendLine(":%s PART %s" % (who, where))
def channelMode(self, user, channel, mode, *args):
"""
Send information about the mode of a channel.
@type user: C{str} or C{unicode}
@param user: The user receiving the name list. Only their nickname,
not the full hostmask.
@type channel: C{str} or C{unicode}
@param channel: The channel for which this is the namelist.
@type mode: C{str}
@param mode: A string describing this channel's modes.
@param args: Any additional arguments required by the modes.
"""
self.sendLine(":%s %s %s %s %s %s" % (
self.hostname, RPL_CHANNELMODEIS, user, channel, mode, ' '.join(args)))
class ServerSupportedFeatures(_CommandDispatcherMixin):
"""
Handle ISUPPORT messages.
Feature names match those in the ISUPPORT RFC draft identically.
Information regarding the specifics of ISUPPORT was gleaned from
<http://www.irc.org/tech_docs/draft-brocklesby-irc-isupport-03.txt>.
"""
prefix = 'isupport'
def __init__(self):
self._features = {
'CHANNELLEN': 200,
'CHANTYPES': tuple('#&'),
'MODES': 3,
'NICKLEN': 9,
'PREFIX': self._parsePrefixParam('(ovh)@+%'),
# The ISUPPORT draft explicitly says that there is no default for
# CHANMODES, but we're defaulting it here to handle the case where
# the IRC server doesn't send us any ISUPPORT information, since
# IRCClient.getChannelModeParams relies on this value.
'CHANMODES': self._parseChanModesParam(['b', '', 'lk', ''])}
@classmethod
def _splitParamArgs(cls, params, valueProcessor=None):
"""
Split ISUPPORT parameter arguments.
Values can optionally be processed by C{valueProcessor}.
For example::
>>> ServerSupportedFeatures._splitParamArgs(['A:1', 'B:2'])
(('A', '1'), ('B', '2'))
@type params: C{iterable} of C{str}
@type valueProcessor: C{callable} taking {str}
@param valueProcessor: Callable to process argument values, or L{None}
to perform no processing
@rtype: C{list} of C{(str, object)}
@return: Sequence of C{(name, processedValue)}
"""
if valueProcessor is None:
valueProcessor = lambda x: x
def _parse():
for param in params:
if ':' not in param:
param += ':'
a, b = param.split(':', 1)
yield a, valueProcessor(b)
return list(_parse())
@classmethod
def _unescapeParamValue(cls, value):
"""
Unescape an ISUPPORT parameter.
The only form of supported escape is C{\\xHH}, where HH must be a valid
2-digit hexadecimal number.
@rtype: C{str}
"""
def _unescape():
parts = value.split('\\x')
# The first part can never be preceded by the escape.
yield parts.pop(0)
for s in parts:
octet, rest = s[:2], s[2:]
try:
octet = int(octet, 16)
except ValueError:
raise ValueError('Invalid hex octet: %r' % (octet,))
yield chr(octet) + rest
if '\\x' not in value:
return value
return ''.join(_unescape())
@classmethod
def _splitParam(cls, param):
"""
Split an ISUPPORT parameter.
@type param: C{str}
@rtype: C{(str, list)}
@return C{(key, arguments)}
"""
if '=' not in param:
param += '='
key, value = param.split('=', 1)
return key, [cls._unescapeParamValue(v) for v in value.split(',')]
@classmethod
def _parsePrefixParam(cls, prefix):
"""
Parse the ISUPPORT "PREFIX" parameter.
The order in which the parameter arguments appear is significant, the
earlier a mode appears the more privileges it gives.
@rtype: C{dict} mapping C{str} to C{(str, int)}
@return: A dictionary mapping a mode character to a two-tuple of
C({symbol, priority)}, the lower a priority (the lowest being
C{0}) the more privileges it gives
"""
if not prefix:
return None
if prefix[0] != '(' and ')' not in prefix:
raise ValueError('Malformed PREFIX parameter')
modes, symbols = prefix.split(')', 1)
symbols = zip(symbols, range(len(symbols)))
modes = modes[1:]
return dict(zip(modes, symbols))
@classmethod
def _parseChanModesParam(self, params):
"""
Parse the ISUPPORT "CHANMODES" parameter.
See L{isupport_CHANMODES} for a detailed explanation of this parameter.
"""
names = ('addressModes', 'param', 'setParam', 'noParam')
if len(params) > len(names):
raise ValueError(
'Expecting a maximum of %d channel mode parameters, got %d' % (
len(names), len(params)))
items = map(lambda key, value: (key, value or ''), names, params)
return dict(items)
def getFeature(self, feature, default=None):
"""
Get a server supported feature's value.
A feature with the value L{None} is equivalent to the feature being
unsupported.
@type feature: C{str}
@param feature: Feature name
@type default: C{object}
@param default: The value to default to, assuming that C{feature}
is not supported
@return: Feature value
"""
return self._features.get(feature, default)
def hasFeature(self, feature):
"""
Determine whether a feature is supported or not.
@rtype: C{bool}
"""
return self.getFeature(feature) is not None
def parse(self, params):
"""
Parse ISUPPORT parameters.
If an unknown parameter is encountered, it is simply added to the
dictionary, keyed by its name, as a tuple of the parameters provided.
@type params: C{iterable} of C{str}
@param params: Iterable of ISUPPORT parameters to parse
"""
for param in params:
key, value = self._splitParam(param)
if key.startswith('-'):
self._features.pop(key[1:], None)
else:
self._features[key] = self.dispatch(key, value)
def isupport_unknown(self, command, params):
"""
Unknown ISUPPORT parameter.
"""
return tuple(params)
def isupport_CHANLIMIT(self, params):
"""
The maximum number of each channel type a user may join.
"""
return self._splitParamArgs(params, _intOrDefault)
def isupport_CHANMODES(self, params):
"""
Available channel modes.
There are 4 categories of channel mode::
addressModes - Modes that add or remove an address to or from a
list, these modes always take a parameter.
param - Modes that change a setting on a channel, these modes
always take a parameter.
setParam - Modes that change a setting on a channel, these modes
only take a parameter when being set.
noParam - Modes that change a setting on a channel, these modes
never take a parameter.
"""
try:
return self._parseChanModesParam(params)
except ValueError:
return self.getFeature('CHANMODES')
def isupport_CHANNELLEN(self, params):
"""
Maximum length of a channel name a client may create.