33e480d56ae04a156f781faad0ebd12426f19202
[irker.git] / irkerd
1 #!/usr/bin/env python
2 """
3 irkerd - a simple IRC multiplexer daemon
4
5 Listens for JSON objects of the form {'to':<irc-url>, 'privmsg':<text>}
6 and relays messages to IRC channels. Each request must be followed by
7 a newline.
8
9 The <text> must be a string.  The value of the 'to' attribute can be a
10 string containing an IRC URL (e.g. 'irc://chat.freenet.net/botwar') or
11 a list of such strings; in the latter case the message is broadcast to
12 all listed channels.  Note that the channel portion of the URL need
13 *not* have a leading '#' unless the channel name itself does.
14
15 Options: -d sets the debug-message level (probably only of interest to
16 developers). -l sets a logfile to capture message traffic from
17 channels.  -n sets the nick and -p the nickserv password. The -V
18 option prints the program version and exits.
19
20 Design and code by Eric S. Raymond <esr@thyrsus.com>. See the project
21 resource page at <http://www.catb.org/~esr/irker/>.
22
23 Requires Python 2.6 or 2.5 with the simplejson library installed.
24 """
25
26 from __future__ import with_statement
27
28 # These things might need tuning
29
30 HOST = "localhost"
31 PORT = 6659
32
33 XMIT_TTL = (3 * 60 * 60)        # Time to live, seconds from last transmit
34 PING_TTL = (15 * 60)            # Time to live, seconds from last PING
35 HANDSHAKE_TTL = 60              # Time to live, seconds from nick transmit
36 CHANNEL_TTL = (3 * 60 * 60)     # Time to live, seconds from last transmit
37 DISCONNECT_TTL = (24 * 60 * 60) # Time to live, seconds from last connect
38 UNSEEN_TTL = 60                 # Time to live, seconds since first request
39 CHANNEL_MAX = 18                # Max channels open per socket (default)
40 ANTI_FLOOD_DELAY = 1.0          # Anti-flood delay after transmissions, seconds
41 ANTI_BUZZ_DELAY = 0.09          # Anti-buzz delay after queue-empty check
42 CONNECTION_MAX = 200            # To avoid hitting a thread limit
43
44 # No user-serviceable parts below this line
45
46 version = "1.20"
47
48 import sys, getopt, urlparse, time, random, socket, signal, re
49 import threading, Queue, SocketServer, select, itertools
50 import logging
51 try:
52     import simplejson as json   # Faster, also makes us Python-2.4-compatible
53 except ImportError:
54     import json
55
56 # Sketch of implementation:
57 #
58 # One Irker object manages multiple IRC sessions.  It holds a map of
59 # Dispatcher objects, one per (server, port) combination, which are
60 # responsible for routing messages to one of any number of Connection
61 # objects that do the actual socket conversations.  The reason for the
62 # Dispatcher layer is that IRC daemons limit the number of channels a
63 # client (that is, from the daemon's point of view, a socket) can be
64 # joined to, so each session to a server needs a flock of Connection
65 # instances each with its own socket.
66 #
67 # Connections are timed out and removed when either they haven't seen a
68 # PING for a while (indicating that the server may be stalled or down)
69 # or there has been no message traffic to them for a while, or
70 # even if the queue is nonempty but efforts to connect have failed for
71 # a long time.
72 #
73 # There are multiple threads. One accepts incoming traffic from all
74 # servers.  Each Connection also has a consumer thread and a
75 # thread-safe message queue.  The program main appends messages to
76 # queues as JSON requests are received; the consumer threads try to
77 # ship them to servers.  When a socket write stalls, it only blocks an
78 # individual consumer thread; if it stalls long enough, the session
79 # will be timed out. This solves the biggest problem with a
80 # single-threaded implementation, which is that you can't count on a
81 # single stalled write not hanging all other traffic - you're at the
82 # mercy of the length of the buffers in the TCP/IP layer.
83 #
84 # Message delivery is thus not reliable in the face of network stalls,
85 # but this was considered acceptable because IRC (notoriously) has the
86 # same problem - there is little point in reliable delivery to a relay
87 # that is down or unreliable.
88 #
89 # This code uses only NICK, JOIN, PART, MODE, PRIVMSG, USER, and QUIT. 
90 # It is strictly compliant to RFC1459, except for the interpretation and
91 # use of the DEAF and CHANLIMIT and (obsolete) MAXCHANNELS features.
92 #
93 # CHANLIMIT is as described in the Internet RFC draft
94 # draft-brocklesby-irc-isupport-03 at <http://www.mirc.com/isupport.html>.
95 # The ",isnick" feature is as described in
96 # <http://ftp.ics.uci.edu/pub/ietf/uri/draft-mirashi-url-irc-01.txt>.
97
98 # Historical note: the IRCClient and IRCServerConnection classes
99 # (~270LOC) replace the overweight, overcomplicated 3KLOC mass of
100 # irclib code that irker formerly used as a service library.  They
101 # still look similar to parts of irclib because I contributed to that
102 # code before giving up on it.
103
104 class IRCError(Exception):
105     "An IRC exception"
106     pass
107
108 class IRCClient():
109     "An IRC client session to one or more servers."
110     def __init__(self):
111         self.mutex = threading.RLock()
112         self.server_connections = []
113         self.event_handlers = {}
114         self.add_event_handler("ping",
115                                lambda c, e: c.ship("PONG %s" % e.target))
116
117     def newserver(self):
118         "Initialize a new server-connection object."
119         conn = IRCServerConnection(self)
120         with self.mutex:
121             self.server_connections.append(conn)
122         return conn
123
124     def spin(self, timeout=0.2):
125         "Spin processing data from connections forever."
126         # Outer loop should specifically *not* be mutex-locked.
127         # Otherwise no other thread would ever be able to change
128         # the shared state of an IRC object running this function.
129         while True:
130             with self.mutex:
131                 connected = [x for x in self.server_connections
132                              if x is not None and x.socket is not None]
133                 sockets = [x.socket for x in connected]
134                 if sockets:
135                     (insocks, _o, _e) = select.select(sockets, [], [], timeout)
136                     for s, c in itertools.product(insocks, self.server_connections):
137                         if s == c.socket:
138                             c.consume()
139
140                 else:
141                     time.sleep(timeout)
142
143     def add_event_handler(self, event, handler):
144         "Set a handler to be called later."
145         with self.mutex:
146             event_handlers = self.event_handlers.setdefault(event, [])
147             event_handlers.append(handler)
148
149     def handle_event(self, connection, event):
150         with self.mutex:
151             h = self.event_handlers
152             th = sorted(h.get("all_events", []) + h.get(event.type, []))
153             for handler in th:
154                 handler(connection, event)
155
156     def drop_connection(self, connection):
157         with self.mutex:
158             self.server_connections.remove(connection)
159
160 class LineBufferedStream():
161     "Line-buffer a read stream."
162     crlf_re = re.compile(b'\r?\n')
163
164     def __init__(self):
165         self.buffer = ''
166
167     def append(self, newbytes):
168         self.buffer += newbytes
169
170     def lines(self):
171         "Iterate over lines in the buffer."
172         lines = LineBufferedStream.crlf_re.split(self.buffer)
173         self.buffer = lines.pop()
174         return iter(lines)
175
176     def __iter__(self):
177         return self.lines()
178
179 class IRCServerConnectionError(IRCError):
180     pass
181
182 class IRCServerConnection():
183     command_re = re.compile("^(:(?P<prefix>[^ ]+) +)?(?P<command>[^ ]+)( *(?P<argument> .+))?")
184     # The full list of numeric-to-event mappings is in Perl's Net::IRC.
185     # We only need to ensure that if some ancient server throws numerics
186     # for the ones we actually want to catch, they're mapped.
187     codemap = {
188         "001": "welcome",
189         "005": "featurelist",
190         "432": "erroneusnickname",
191         "433": "nicknameinuse",
192         "436": "nickcollision",
193         "437": "unavailresource",
194     }
195
196     def __init__(self, master):
197         self.master = master
198         self.socket = None
199
200     def connect(self, server, port, nickname,
201                 password=None, username=None, ircname=None):
202         log.debug("connect(server=%r, port=%r, nickname=%r, ...)",
203                   server, port, nickname)
204         if self.socket is not None:
205             self.disconnect("Changing servers")
206
207         self.buffer = LineBufferedStream()
208         self.event_handlers = {}
209         self.real_server_name = ""
210         self.server = server
211         self.port = port
212         self.server_address = (server, port)
213         self.nickname = nickname
214         self.username = username or nickname
215         self.ircname = ircname or nickname
216         self.password = password
217         try:
218             self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
219             self.socket.bind(('', 0))
220             self.socket.connect(self.server_address)
221         except socket.error as err:
222             raise IRCServerConnectionError("Couldn't connect to socket: %s" % err)
223
224         if self.password:
225             self.ship("PASS " + self.password)
226         self.nick(self.nickname)
227         self.user(self.username, self.ircname)
228         return self
229
230     def close(self):
231         # Without this thread lock, there is a window during which
232         # select() can find a closed socket, leading to an EBADF error.
233         with self.master.mutex:
234             self.disconnect("Closing object")
235             self.master.drop_connection(self)
236
237     def consume(self):
238         try:
239             incoming = self.socket.recv(16384)
240         except socket.error:
241             # Server hung up on us.
242             self.disconnect("Connection reset by peer")
243             return
244         if not incoming:
245             # Dead air also indicates a connection reset.
246             self.disconnect("Connection reset by peer")
247             return
248
249         self.buffer.append(incoming)
250
251         for line in self.buffer:
252             log.debug("FROM: %s", line)
253
254             if not line:
255                 continue
256
257             prefix = None
258             command = None
259             arguments = None
260             self.handle_event(Event("every_raw_message",
261                                      self.real_server_name,
262                                      None,
263                                      [line]))
264
265             m = IRCServerConnection.command_re.match(line)
266             if m.group("prefix"):
267                 prefix = m.group("prefix")
268                 if not self.real_server_name:
269                     self.real_server_name = prefix
270             if m.group("command"):
271                 command = m.group("command").lower()
272             if m.group("argument"):
273                 a = m.group("argument").split(" :", 1)
274                 arguments = a[0].split()
275                 if len(a) == 2:
276                     arguments.append(a[1])
277
278             command = IRCServerConnection.codemap.get(command, command)
279             if command in ["privmsg", "notice"]:
280                 target = arguments.pop(0)
281             else:
282                 target = None
283
284                 if command == "quit":
285                     arguments = [arguments[0]]
286                 elif command == "ping":
287                     target = arguments[0]
288                 else:
289                     target = arguments[0]
290                     arguments = arguments[1:]
291
292             log.debug("command: %s, source: %s, target: %s, "
293                       "arguments: %s", command, prefix, target, arguments)
294             self.handle_event(Event(command, prefix, target, arguments))
295
296     def handle_event(self, event):
297         self.master.handle_event(self, event)
298         if event.type in self.event_handlers:
299             for fn in self.event_handlers[event.type]:
300                 fn(self, event)
301
302     def is_connected(self):
303         return self.socket is not None
304
305     def disconnect(self, message=""):
306         if self.socket is None:
307             return
308         self.quit(message)
309         try:
310             self.socket.shutdown(socket.SHUT_WR)
311             self.socket.close()
312         except socket.error:
313             pass
314         del self.socket
315         self.socket = None
316         self.handle_event(Event("disconnect", self.server, "", [message]))
317
318     def join(self, channel, key=""):
319         self.ship("JOIN %s%s" % (channel, (key and (" " + key))))
320
321     def mode(self, target, command):
322         self.ship("MODE %s %s" % (target, command))
323
324     def nick(self, newnick):
325         self.ship("NICK " + newnick)
326
327     def part(self, channel, message=""):
328         cmd_parts = ['PART', channel]
329         if message:
330             cmd_parts.append(message)
331         self.ship(' '.join(cmd_parts))
332
333     def privmsg(self, target, text):
334         self.ship("PRIVMSG %s :%s" % (target, text))
335
336     def quit(self, message=""):
337         # Triggers an error that forces a disconnect.
338         self.ship("QUIT" + (message and (" :" + message)))
339
340     def user(self, username, realname):
341         self.ship("USER %s 0 * :%s" % (username, realname))
342
343     def ship(self, string):
344         "Ship a command to the server, appending CR/LF"
345         try:
346             self.socket.send(string + b'\r\n')
347             log.debug("TO: %s", string)
348         except socket.error:
349             self.disconnect("Connection reset by peer.")
350
351 class Event(object):
352     def __init__(self, evtype, source, target, arguments=None):
353         self.type = evtype
354         self.source = source
355         self.target = target
356         if arguments is None:
357             arguments = []
358         self.arguments = arguments
359
360 def is_channel(string):
361     return string and string[0] in "#&+!"
362
363 class Connection:
364     def __init__(self, irkerd, servername, port):
365         self.irker = irkerd
366         self.servername = servername
367         self.port = port
368         self.nick_trial = None
369         self.connection = None
370         self.status = None
371         self.last_xmit = time.time()
372         self.last_ping = time.time()
373         self.channels_joined = {}
374         self.channel_limits = {}
375         # The consumer thread
376         self.queue = Queue.Queue()
377         self.thread = None
378     def nickname(self, n=None):
379         "Return a name for the nth server connection."
380         if n is None:
381             n = self.nick_trial
382         if fallback:
383             return (namestyle % n)
384         else:
385             return namestyle
386     def handle_ping(self):
387         "Register the fact that the server has pinged this connection."
388         self.last_ping = time.time()
389     def handle_welcome(self):
390         "The server says we're OK, with a non-conflicting nick."
391         self.status = "ready"
392         self.irker.debug(1, "nick %s accepted" % self.nickname())
393         if password:
394             self.connection.privmsg("nickserv", "identify %s" % password)
395     def handle_badnick(self):
396         "The server says our nick is ill-formed or has a conflict."
397         self.irker.debug(1, "nick %s rejected" % self.nickname())
398         if fallback:
399             # Randomness prevents a malicious user or bot from
400             # anticipating the next trial name in order to block us
401             # from completing the handshake.
402             self.nick_trial += random.randint(1, 3)
403             self.last_xmit = time.time()
404             self.connection.nick(self.nickname())
405         # Otherwise fall through, it might be possible to
406         # recover manually.
407     def handle_disconnect(self):
408         "Server disconnected us for flooding or some other reason."
409         self.connection = None
410         self.status = "disconnected"
411     def handle_kick(self, outof):
412         "We've been kicked."
413         self.status = "handshaking"
414         try:
415             del self.channels_joined[outof]
416         except KeyError:
417             self.irker.logerr("kicked by %s from %s that's not joined"
418                               % (self.servername, outof))
419         qcopy = []
420         while not self.queue.empty():
421             (channel, message, key) = self.queue.get()
422             if channel != outof:
423                 qcopy.append((channel, message, key))
424         for (channel, message, key) in qcopy:
425             self.queue.put((channel, message, key))
426         self.status = "ready"
427     def enqueue(self, channel, message, key):
428         "Enque a message for transmission."
429         if self.thread is None or not self.thread.is_alive():
430             self.status = "unseen"
431             self.thread = threading.Thread(target=self.dequeue)
432             self.thread.setDaemon(True)
433             self.thread.start()
434         self.queue.put((channel, message, key))
435     def dequeue(self):
436         "Try to ship pending messages from the queue."
437         try:
438             while True:
439                 # We want to be kind to the IRC servers and not hold unused
440                 # sockets open forever, so they have a time-to-live.  The
441                 # loop is coded this particular way so that we can drop
442                 # the actual server connection when its time-to-live
443                 # expires, then reconnect and resume transmission if the
444                 # queue fills up again.
445                 if self.queue.empty():
446                     # Queue is empty, at some point we want to time out
447                     # the connection rather than holding a socket open in
448                     # the server forever.
449                     now = time.time()
450                     xmit_timeout = now > self.last_xmit + XMIT_TTL
451                     ping_timeout = now > self.last_ping + PING_TTL
452                     if self.status == "disconnected":
453                         # If the queue is empty, we can drop this connection.
454                         self.status = "expired"
455                         break
456                     elif xmit_timeout or ping_timeout:
457                         self.irker.debug(1, "timing out connection to %s at %s (ping_timeout=%s, xmit_timeout=%s)" % (self.servername, time.asctime(), ping_timeout, xmit_timeout))
458                         with self.irker.irc.mutex:
459                             self.connection.context = None
460                             self.connection.quit("transmission timeout")
461                             self.connection = None
462                         self.status = "disconnected"
463                     else:
464                         # Prevent this thread from hogging the CPU by pausing
465                         # for just a little bit after the queue-empty check.
466                         # As long as this is less that the duration of a human
467                         # reflex arc it is highly unlikely any human will ever
468                         # notice.
469                         time.sleep(ANTI_BUZZ_DELAY)
470                 elif self.status == "disconnected" \
471                          and time.time() > self.last_xmit + DISCONNECT_TTL:
472                     # Queue is nonempty, but the IRC server might be
473                     # down. Letting failed connections retain queue
474                     # space forever would be a memory leak.
475                     self.status = "expired"
476                     break
477                 elif not self.connection:
478                     # Queue is nonempty but server isn't connected.
479                     with self.irker.irc.mutex:
480                         self.connection = self.irker.irc.newserver()
481                         self.connection.context = self
482                         # Try to avoid colliding with other instances
483                         self.nick_trial = random.randint(1, 990)
484                         self.channels_joined = {}
485                         try:
486                             # This will throw
487                             # IRCServerConnectionError on failure
488                             self.connection.connect(self.servername,
489                                                 self.port,
490                                                 nickname=self.nickname(),
491                                                 username="irker",
492                                                 ircname="irker relaying client")
493                             if hasattr(self.connection, "buffer"):
494                                 self.connection.buffer.errors = 'replace'
495                             self.status = "handshaking"
496                             self.irker.debug(1, "XMIT_TTL bump (%s connection) at %s" % (self.servername, time.asctime()))
497                             self.last_xmit = time.time()
498                             self.last_ping = time.time()
499                         except IRCServerConnectionError:
500                             self.status = "disconnected"
501                 elif self.status == "handshaking":
502                     if time.time() > self.last_xmit + HANDSHAKE_TTL:
503                         self.status = "expired"
504                         break
505                     else:
506                         # Don't buzz on the empty-queue test while we're
507                         # handshaking
508                         time.sleep(ANTI_BUZZ_DELAY)
509                 elif self.status == "unseen" \
510                          and time.time() > self.last_xmit + UNSEEN_TTL:
511                     # Nasty people could attempt a denial-of-service
512                     # attack by flooding us with requests with invalid
513                     # servernames. We guard against this by rapidly
514                     # expiring connections that have a nonempty queue but
515                     # have never had a successful open.
516                     self.status = "expired"
517                     break
518                 elif self.status == "ready":
519                     (channel, message, key) = self.queue.get()
520                     if channel not in self.channels_joined:
521                         self.connection.join(channel, key=key)
522                         self.irker.debug(1, "joining %s on %s." % (channel, self.servername))
523                     # An empty message might be used as a keepalive or
524                     # to join a channel for logging, so suppress the
525                     # privmsg send unless there is actual traffic.
526                     if message:
527                         for segment in message.split("\n"):
528                             # Truncate the message if it's too long,
529                             # but we're working with characters here,
530                             # not bytes, so we could be off.
531                             # 500 = 512 - CRLF - 'PRIVMSG ' - ' :'
532                             maxlength = 500 - len(channel)
533                             if len(segment) > maxlength:
534                                 segment = segment[:maxlength]
535                             try:
536                                 self.connection.privmsg(channel, segment)
537                             except ValueError as err:
538                                 self.irker.debug(1, "irclib rejected a message to %s on %s because: %s" % (channel, self.servername, str(err)))
539                             time.sleep(ANTI_FLOOD_DELAY)
540                     self.last_xmit = self.channels_joined[channel] = time.time()
541                     self.irker.debug(1, "XMIT_TTL bump (%s transmission) at %s" % (self.servername, time.asctime()))
542                     self.queue.task_done()
543         except:
544             (exc_type, _exc_value, exc_traceback) = sys.exc_info()
545             self.irker.logerr("exception %s in thread for %s" % \
546                               (exc_type, self.servername))
547
548             # Maybe this should have its own status?
549             self.status = "expired"
550
551             # This is so we can see tracebacks for errors inside the thread
552             # when we need to be able to for debugging purposes.
553             if debuglvl > 0:
554                 raise exc_type, _exc_value, exc_traceback
555         finally:
556             try:
557                 # Make sure we don't leave any zombies behind
558                 self.connection.close()
559             except:
560                 # Irclib has a habit of throwing fresh exceptions here. Ignore that
561                 pass
562     def live(self):
563         "Should this connection not be scavenged?"
564         return self.status != "expired"
565     def joined_to(self, channel):
566         "Is this connection joined to the specified channel?"
567         return channel in self.channels_joined
568     def accepting(self, channel):
569         "Can this connection accept a join of this channel?"
570         if self.channel_limits:
571             match_count = 0
572             for already in self.channels_joined:
573                 # This obscure code is because the RFCs allow separate limits
574                 # by channel type (indicated by the first character of the name)
575                 # a feature that is almost never actually used.
576                 if already[0] == channel[0]:
577                     match_count += 1
578             return match_count < self.channel_limits.get(channel[0], CHANNEL_MAX)
579         else:
580             return len(self.channels_joined) < CHANNEL_MAX
581
582 class Target():
583     "Represent a transmission target."
584     def __init__(self, url):
585         # Pre-2.6 Pythons don't recognize irc: as a valid URL prefix.
586         url = url.replace("irc://", "http://")
587         parsed = urlparse.urlparse(url)
588         irchost, _, ircport = parsed.netloc.partition(':')
589         if not ircport:
590             ircport = 6667
591         self.servername = irchost
592         # IRC channel names are case-insensitive.  If we don't smash
593         # case here we may run into problems later. There was a bug
594         # observed on irc.rizon.net where an irkerd user specified #Channel,
595         # got kicked, and irkerd crashed because the server returned
596         # "#channel" in the notification that our kick handler saw.
597         self.channel = parsed.path.lstrip('/').lower()
598         # This deals with a tweak in recent versions of urlparse.
599         if parsed.fragment:
600             self.channel += "#" + parsed.fragment
601         isnick = self.channel.endswith(",isnick")
602         if isnick:
603             self.channel = self.channel[:-7]
604         if self.channel and not isnick and self.channel[0] not in "#&+":
605             self.channel = "#" + self.channel
606         # support both channel?secret and channel?key=secret
607         self.key = ""
608         if parsed.query:
609             self.key = re.sub("^key=", "", parsed.query)
610         self.port = int(ircport)
611     def valid(self):
612         "Both components must be present for a valid target."
613         return self.servername and self.channel
614     def server(self):
615         "Return a hashable tuple representing the destination server."
616         return (self.servername, self.port)
617
618 class Dispatcher:
619     "Manage connections to a particular server-port combination."
620     def __init__(self, irkerd, servername, port):
621         self.irker = irkerd
622         self.servername = servername
623         self.port = port
624         self.connections = []
625     def dispatch(self, channel, message, key):
626         "Dispatch messages for our server-port combination."
627         # First, check if there is room for another channel
628         # on any of our existing connections.
629         connections = [x for x in self.connections if x.live()]
630         eligibles = [x for x in connections if x.joined_to(channel)] \
631                     or [x for x in connections if x.accepting(channel)]
632         if eligibles:
633             eligibles[0].enqueue(channel, message, key)
634             return
635         # All connections are full up. Look for one old enough to be
636         # scavenged.
637         ancients = []
638         for connection in connections:
639             for (chan, age) in connections.channels_joined.items():
640                 if age < time.time() - CHANNEL_TTL:
641                     ancients.append((connection, chan, age))
642         if ancients:
643             ancients.sort(key=lambda x: x[2]) 
644             (found_connection, drop_channel, _drop_age) = ancients[0]
645             found_connection.part(drop_channel, "scavenged by irkerd")
646             del found_connection.channels_joined[drop_channel]
647             #time.sleep(ANTI_FLOOD_DELAY)
648             found_connection.enqueue(channel, message, key)
649             return
650         # Didn't find any channels with no recent activity
651         newconn = Connection(self.irker,
652                              self.servername,
653                              self.port)
654         self.connections.append(newconn)
655         newconn.enqueue(channel, message, key)
656     def live(self):
657         "Does this server-port combination have any live connections?"
658         self.connections = [x for x in self.connections if x.live()]
659         return len(self.connections) > 0
660     def last_xmit(self):
661         "Return the time of the most recent transmission."
662         return max(x.last_xmit for x in self.connections)
663
664 class Irker:
665     "Persistent IRC multiplexer."
666     def __init__(self, debuglevel=0):
667         self.debuglevel = debuglevel
668         self.irc = IRCClient()
669         self.irc.add_event_handler("ping", self._handle_ping)
670         self.irc.add_event_handler("welcome", self._handle_welcome)
671         self.irc.add_event_handler("erroneusnickname", self._handle_badnick)
672         self.irc.add_event_handler("nicknameinuse", self._handle_badnick)
673         self.irc.add_event_handler("nickcollision", self._handle_badnick)
674         self.irc.add_event_handler("unavailresource", self._handle_badnick)
675         self.irc.add_event_handler("featurelist", self._handle_features)
676         self.irc.add_event_handler("disconnect", self._handle_disconnect)
677         self.irc.add_event_handler("kick", self._handle_kick)
678         self.irc.add_event_handler("every_raw_message", self._handle_every_raw_message)
679         thread = threading.Thread(target=self.irc.spin)
680         thread.setDaemon(True)
681         self.irc._thread = thread
682         thread.start()
683         self.servers = {}
684     def logerr(self, errmsg):
685         "Log a processing error."
686         sys.stderr.write("irkerd: " + errmsg + "\n")
687     def debug(self, level, errmsg):
688         "Debugging information."
689         if self.debuglevel >= level:
690             sys.stderr.write("irkerd: %s\n" % errmsg)
691     def _handle_ping(self, connection, _event):
692         "PING arrived, bump the last-received time for the connection."
693         if connection.context:
694             connection.context.handle_ping()
695     def _handle_welcome(self, connection, _event):
696         "Welcome arrived, nick accepted for this connection."
697         if connection.context:
698             connection.context.handle_welcome()
699     def _handle_badnick(self, connection, _event):
700         "Nick not accepted for this connection."
701         if connection.context:
702             connection.context.handle_badnick()
703     def _handle_features(self, connection, event):
704         "Determine if and how we can set deaf mode."
705         if connection.context:
706             cxt = connection.context
707             arguments = event.arguments
708             # irclib 5.0 compatibility, because the maintainer is a fool
709             if callable(arguments):
710                 arguments = arguments()
711             for lump in arguments:
712                 if lump.startswith("DEAF="):
713                     if not logfile:
714                         connection.mode(cxt.nickname(), "+"+lump[5:])
715                 elif lump.startswith("MAXCHANNELS="):
716                     m = int(lump[12:])
717                     for pref in "#&+":
718                         cxt.channel_limits[pref] = m
719                     self.debug(1, "%s maxchannels is %d"
720                                % (connection.server, m))
721                 elif lump.startswith("CHANLIMIT=#:"):
722                     limits = lump[10:].split(",")
723                     try:
724                         for token in limits:
725                             (prefixes, limit) = token.split(":")
726                             limit = int(limit)
727                             for c in prefixes:
728                                 cxt.channel_limits[c] = limit
729                         self.debug(1, "%s channel limit map is %s"
730                                    % (connection.server, cxt.channel_limits))
731                     except ValueError:
732                         self.logerr("ill-formed CHANLIMIT property")
733     def _handle_disconnect(self, connection, _event):
734         "Server hung up the connection."
735         self.debug(1, "server %s disconnected" % connection.server)
736         connection.close()
737         if connection.context:
738             connection.context.handle_disconnect()
739     def _handle_kick(self, connection, event):
740         "Server hung up the connection."
741         target = event.target
742         # irclib 5.0 compatibility, because the maintainer continues
743         # to be a fool.
744         if callable(target):
745             target = target()
746         self.debug(1, "irker has been kicked from %s on %s" % (target, connection.server))
747         if connection.context:
748             connection.context.handle_kick(target)
749     def _handle_every_raw_message(self, _connection, event):
750         "Log all messages when in watcher mode."
751         if logfile:
752             with open(logfile, "a") as logfp:
753                 logfp.write("%03f|%s|%s\n" % \
754                              (time.time(), event.source, event.arguments[0]))
755     def handle(self, line):
756         "Perform a JSON relay request."
757         try:
758             request = json.loads(line.strip())
759             if not isinstance(request, dict):
760                 self.logerr("request is not a JSON dictionary: %r" % request)
761             elif "to" not in request or "privmsg" not in request:
762                 self.logerr("malformed request - 'to' or 'privmsg' missing: %r" % request)
763             else:
764                 channels = request['to']
765                 message = request['privmsg']
766                 if not isinstance(channels, (list, basestring)):
767                     self.logerr("malformed request - unexpected channel type: %r" % channels)
768                 if not isinstance(message, basestring):
769                     self.logerr("malformed request - unexpected message type: %r" % message)
770                 else:
771                     if not isinstance(channels, list):
772                         channels = [channels]
773                     for url in channels:
774                         if not isinstance(url, basestring):
775                             self.logerr("malformed request - URL has unexpected type: %r" % url)
776                         else:
777                             target = Target(url)
778                             if not target.valid():
779                                 return
780                             if target.server() not in self.servers:
781                                 self.servers[target.server()] = Dispatcher(self, target.servername, target.port)
782                             self.servers[target.server()].dispatch(target.channel, message, target.key)
783                             # GC dispatchers with no active connections
784                             servernames = self.servers.keys()
785                             for servername in servernames:
786                                 if not self.servers[servername].live():
787                                     del self.servers[servername]
788                             # If we might be pushing a resource limit
789                             # even after garbage collection, remove a
790                             # session.  The goal here is to head off
791                             # DoS attacks that aim at exhausting
792                             # thread space or file descriptors.  The
793                             # cost is that attempts to DoS this
794                             # service will cause lots of join/leave
795                             # spam as we scavenge old channels after
796                             # connecting to new ones. The particular
797                             # method used for selecting a session to
798                             # be terminated doesn't matter much; we
799                             # choose the one longest idle on the
800                             # assumption that message activity is likely
801                             # to be clumpy.
802                             if len(self.servers) >= CONNECTION_MAX:
803                                 oldest = min(self.servers.keys(), key=lambda name: self.servers[name].last_xmit())
804                                 del self.servers[oldest]
805         except ValueError:
806             self.logerr("can't recognize JSON on input: %r" % line)
807         except RuntimeError:
808             self.logerr("wildly malformed JSON blew the parser stack.")
809
810 class IrkerTCPHandler(SocketServer.StreamRequestHandler):
811     def handle(self):
812         while True:
813             line = self.rfile.readline()
814             if not line:
815                 break
816             irker.handle(line.strip())
817
818 class IrkerUDPHandler(SocketServer.BaseRequestHandler):
819     def handle(self):
820         data = self.request[0].strip()
821         #socket = self.request[1]
822         irker.handle(data)
823
824 def usage():
825     sys.stdout.write("""
826 Usage:
827   irkerd [-d debuglevel] [-l logfile] [-n nick] [-p password] [-V] [-h]
828
829 Options
830   -d    set debug level
831   -l    set logfile
832   -n    set nick-style
833   -p    set nickserv password
834   -V    return irkerd version
835   -h    print this help dialog
836 """)
837
838 if __name__ == '__main__':
839     log = logging.getLogger(__name__)
840     debuglvl = 0
841     namestyle = "irker%03d"
842     password = None
843     logfile = None
844     try:
845         (options, arguments) = getopt.getopt(sys.argv[1:], "d:l:n:p:Vh")
846     except getopt.GetoptError as e:
847         sys.stderr.write("%s" % e)
848         usage()
849         sys.exit(1)
850     for (opt, val) in options:
851         if opt == '-d':         # Enable debug/progress messages
852             debuglvl = int(val)
853             if debuglvl > 1:
854                 logging.basicConfig(level=logging.DEBUG)
855         elif opt == '-l':       # Logfile mode - report traffic read in
856             logfile = val
857         elif opt == '-n':       # Force the nick
858             namestyle = val
859         elif opt == '-p':       # Set a nickserv password
860             password = val
861         elif opt == '-V':       # Emit version and exit
862             sys.stdout.write("irkerd version %s\n" % version)
863             sys.exit(0)
864         elif opt == '-h':
865             usage()
866             sys.exit(0)
867     fallback = re.search("%.*d", namestyle)
868     irker = Irker(debuglevel=debuglvl)
869     irker.debug(1, "irkerd version %s" % version)
870     try:
871         tcpserver = SocketServer.TCPServer((HOST, PORT), IrkerTCPHandler)
872         udpserver = SocketServer.UDPServer((HOST, PORT), IrkerUDPHandler)
873         for server in [tcpserver, udpserver]:
874             server = threading.Thread(target=server.serve_forever)
875             server.setDaemon(True)
876             server.start()
877         try:
878             signal.pause()
879         except KeyboardInterrupt:
880             raise SystemExit(1)
881     except socket.error, e:
882         sys.stderr.write("irkerd: server launch failed: %r\n" % e)
883
884 # end