Dcumentation update.
[irker.git] / irkerd
1 #!/usr/bin/env python
2 from __future__ import with_statement
3 """
4 irkerd - a simple IRC multiplexer daemon
5
6 Listens for JSON objects of the form {'to':<irc-url>, 'privmsg':<text>}
7 and relays messages to IRC channels. Each request must be followed by
8 a newline.
9
10 The <text> must be a string.  The value of the 'to' attribute can be a
11 string containing an IRC URL (e.g. 'irc://chat.freenet.net/botwar') or
12 a list of such strings; in the latter case the message is broadcast to
13 all listed channels.  Note that the channel portion of the URL need
14 *not* have a leading '#' unless the channel name itself does.
15
16 Options: -d sets the debug-message level (probably only of interest to
17 developers). -l sets a logfile to capture message traffic from
18 channels.  -n sets the nick and -p the nickserv password. The -V
19 option prints the program version and exits.
20
21 Design and code by Eric S. Raymond <esr@thyrsus.com>. See the project
22 resource page at <http://www.catb.org/~esr/irker/>.
23
24 Requires Python 2.6 or 2.5 with the simplejson library installed, and
25 the irc client library at version >= 3.4 which requires 2.6: see
26
27 http://pypi.python.org/pypi/irc/
28 """
29 # These things might need tuning
30
31 HOST = "localhost"
32 PORT = 6659
33
34 XMIT_TTL = (3 * 60 * 60)        # Time to live, seconds from last transmit
35 PING_TTL = (15 * 60)            # Time to live, seconds from last PING
36 HANDSHAKE_TTL = 60              # Time to live, seconds from nick transmit
37 CHANNEL_TTL = (3 * 60 * 60)     # Time to live, seconds from last transmit
38 DISCONNECT_TTL = (24 * 60 * 60) # Time to live, seconds from last connect
39 UNSEEN_TTL = 60                 # Time to live, seconds since first request
40 CHANNEL_MAX = 18                # Max channels open per socket (default)
41 ANTI_FLOOD_DELAY = 1.0          # Anti-flood delay after transmissions, seconds
42 ANTI_BUZZ_DELAY = 0.09          # Anti-buzz delay after queue-empty check
43 CONNECTION_MAX = 200            # To avoid hitting a thread limit
44
45 # No user-serviceable parts below this line
46
47 version = "1.20"
48
49 import sys, getopt, urlparse, time, random, socket, signal, re
50 import threading, Queue, SocketServer
51 import irc.client, logging
52 try:
53     import simplejson as json   # Faster, also makes us Python-2.4-compatible
54 except ImportError:
55     import json
56
57 # Sketch of implementation:
58 #
59 # One Irker object manages multiple IRC sessions.  It holds a map of
60 # Dispatcher objects, one per (server, port) combination, which are
61 # responsible for routing messages to one of any number of Connection
62 # objects that do the actual socket conversations.  The reason for the
63 # Dispatcher layer is that IRC daemons limit the number of channels a
64 # client (that is, from the daemon's point of view, a socket) can be
65 # joined to, so each session to a server needs a flock of Connection
66 # instances each with its own socket.
67 #
68 # Connections are timed out and removed when either they haven't seen a
69 # PING for a while (indicating that the server may be stalled or down)
70 # or there has been no message traffic to them for a while, or
71 # even if the queue is nonempty but efforts to connect have failed for
72 # a long time.
73 #
74 # There are multiple threads. One accepts incoming traffic from all
75 # servers.  Each Connection also has a consumer thread and a
76 # thread-safe message queue.  The program main appends messages to
77 # queues as JSON requests are received; the consumer threads try to
78 # ship them to servers.  When a socket write stalls, it only blocks an
79 # individual consumer thread; if it stalls long enough, the session
80 # will be timed out. This solves the biggest problem with a
81 # single-threaded implementation, which is that you can't count on a
82 # single stalled write not hanging all other traffic - you're at the
83 # mercy of the length of the buffers in the TCP/IP layer.
84 #
85 # Message delivery is thus not reliable in the face of network stalls,
86 # but this was considered acceptable because IRC (notoriously) has the
87 # same problem - there is little point in reliable delivery to a relay
88 # that is down or unreliable.
89 #
90 # This code uses only NICK, JOIN, PART, MODE, and PRIVMSG. It is strictly
91 # compliant to RFC1459, except for the interpretation and use of the
92 # DEAF and CHANLIMIT and (obsolete) MAXCHANNELS features.  CHANLIMIT
93 # 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 class Connection:
99     def __init__(self, irkerd, servername, port):
100         self.irker = irkerd
101         self.servername = servername
102         self.port = port
103         self.nick_trial = None
104         self.connection = None
105         self.status = None
106         self.last_xmit = time.time()
107         self.last_ping = time.time()
108         self.channels_joined = {}
109         self.channel_limits = {}
110         # The consumer thread
111         self.queue = Queue.Queue()
112         self.thread = None
113     def nickname(self, n=None):
114         "Return a name for the nth server connection."
115         if n is None:
116             n = self.nick_trial
117         if fallback:
118             return (namestyle % n)
119         else:
120             return namestyle
121     def handle_ping(self):
122         "Register the fact that the server has pinged this connection."
123         self.last_ping = time.time()
124     def handle_welcome(self):
125         "The server says we're OK, with a non-conflicting nick."
126         self.status = "ready"
127         self.irker.debug(1, "nick %s accepted" % self.nickname())
128         if password:
129             self.connection.privmsg("nickserv", "identify %s" % password)
130     def handle_badnick(self):
131         "The server says our nick is ill-formed or has a conflict."
132         self.irker.debug(1, "nick %s rejected" % self.nickname())
133         if fallback:
134             # Randomness prevents a malicious user or bot from
135             # anticipating the next trial name in order to block us
136             # from completing the handshake.
137             self.nick_trial += random.randint(1, 3)
138             self.last_xmit = time.time()
139             self.connection.nick(self.nickname())
140         # Otherwise fall through, it might be possible to
141         # recover manually.
142     def handle_disconnect(self):
143         "Server disconnected us for flooding or some other reason."
144         self.connection = None
145         self.status = "disconnected"
146     def handle_kick(self, outof):
147         "We've been kicked."
148         self.status = "handshaking"
149         try:
150             del self.channels_joined[outof]
151         except KeyError:
152             self.irker.logerr("kicked by %s from %s that's not joined"
153                               % (self.servername, outof))
154         qcopy = []
155         while not self.queue.empty():
156             (channel, message) = self.queue.get()
157             if channel != outof:
158                 qcopy.append((channel, message))
159         for (channel, message) in qcopy:
160             self.queue.put((channel, message))
161         self.status = "ready"
162     def enqueue(self, channel, message):
163         "Enque a message for transmission."
164         if self.thread is None or not self.thread.is_alive():
165             self.status = "unseen"
166             self.thread = threading.Thread(target=self.dequeue)
167             self.thread.setDaemon(True)
168             self.thread.start()
169         self.queue.put((channel, message))
170     def dequeue(self):
171         "Try to ship pending messages from the queue."
172         try:
173             while True:
174                 # We want to be kind to the IRC servers and not hold unused
175                 # sockets open forever, so they have a time-to-live.  The
176                 # loop is coded this particular way so that we can drop
177                 # the actual server connection when its time-to-live
178                 # expires, then reconnect and resume transmission if the
179                 # queue fills up again.
180                 if self.queue.empty():
181                     # Queue is empty, at some point we want to time out
182                     # the connection rather than holding a socket open in
183                     # the server forever.
184                     now = time.time()
185                     xmit_timeout = now > self.last_xmit + XMIT_TTL
186                     ping_timeout = now > self.last_ping + PING_TTL
187                     if self.status == "disconnected":
188                         # If the queue is empty, we can drop this connection.
189                         self.status = "expired"
190                         break
191                     elif xmit_timeout or ping_timeout:
192                         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))
193                         with self.irker.irc.mutex:
194                             self.connection.context = None
195                             self.connection.quit("transmission timeout")
196                             self.connection = None
197                         self.status = "disconnected"
198                     else:
199                         # Prevent this thread from hogging the CPU by pausing
200                         # for just a little bit after the queue-empty check.
201                         # As long as this is less that the duration of a human
202                         # reflex arc it is highly unlikely any human will ever
203                         # notice.
204                         time.sleep(ANTI_BUZZ_DELAY)
205                 elif self.status == "disconnected" \
206                          and time.time() > self.last_xmit + DISCONNECT_TTL:
207                     # Queue is nonempty, but the IRC server might be
208                     # down. Letting failed connections retain queue
209                     # space forever would be a memory leak.
210                     self.status = "expired"
211                     break
212                 elif not self.connection:
213                     # Queue is nonempty but server isn't connected.
214                     with self.irker.irc.mutex:
215                         self.connection = self.irker.irc.server()
216                         self.connection.context = self
217                         # Try to avoid colliding with other instances
218                         self.nick_trial = random.randint(1, 990)
219                         self.channels_joined = {}
220                         try:
221                             # This will throw
222                             # irc.client.ServerConnectionError on failure
223                             self.connection.connect(self.servername,
224                                                 self.port,
225                                                 nickname=self.nickname(),
226                                                 username="irker",
227                                                 ircname="irker relaying client")
228                             if hasattr(self.connection, "buffer"):
229                                 self.connection.buffer.errors = 'replace'
230                             self.status = "handshaking"
231                             self.irker.debug(1, "XMIT_TTL bump (%s connection) at %s" % (self.servername, time.asctime()))
232                             self.last_xmit = time.time()
233                             self.last_ping = time.time()
234                         except irc.client.ServerConnectionError:
235                             self.status = "disconnected"
236                 elif self.status == "handshaking":
237                     if time.time() > self.last_xmit + HANDSHAKE_TTL:
238                         self.status = "expired"
239                         break
240                     else:
241                         # Don't buzz on the empty-queue test while we're
242                         # handshaking
243                         time.sleep(ANTI_BUZZ_DELAY)
244                 elif self.status == "unseen" \
245                          and time.time() > self.last_xmit + UNSEEN_TTL:
246                     # Nasty people could attempt a denial-of-service
247                     # attack by flooding us with requests with invalid
248                     # servernames. We guard against this by rapidly
249                     # expiring connections that have a nonempty queue but
250                     # have never had a successful open.
251                     self.status = "expired"
252                     break
253                 elif self.status == "ready":
254                     (channel, message) = self.queue.get()
255                     if channel not in self.channels_joined:
256                         self.connection.join(channel)
257                         self.irker.debug(1, "joining %s on %s." % (channel, self.servername))
258                     # An empty message might be used as a keepalive or
259                     # to join a channel for logging, so suppress the
260                     # privmsg send unless there is actual traffic.
261                     if message:
262                         for segment in message.split("\n"):
263                             # Truncate the message if it's too long,
264                             # but we're working with characters here,
265                             # not bytes, so we could be off.
266                             # 500 = 512 - CRLF - 'PRIVMSG ' - ' :'
267                             maxlength = 500 - len(channel)
268                             if len(segment) > maxlength:
269                                 segment = segment[:maxlength]
270                             try:
271                                 self.connection.privmsg(channel, segment)
272                             except ValueError as err:
273                                 self.irker.debug(1, "irclib rejected a message to %s on %s because: %s" % (channel, self.servername, str(err)))
274                             time.sleep(ANTI_FLOOD_DELAY)
275                     self.last_xmit = self.channels_joined[channel] = time.time()
276                     self.irker.debug(1, "XMIT_TTL bump (%s transmission) at %s" % (self.servername, time.asctime()))
277                     self.queue.task_done()
278         except:
279             (exc_type, _exc_value, exc_traceback) = sys.exc_info()
280             self.irker.logerr("exception %s in thread for %s" % \
281                               (exc_type, self.servername))
282
283             # Maybe this should have its own status?
284             self.status = "expired"
285
286             # This is so we can see tracebacks for errors inside the thread
287             # when we need to be able to for debugging purposes.
288             if debuglvl > 0:
289                 raise exc_type, _exc_value, exc_traceback
290         finally:
291             try:
292                 # Make sure we don't leave any zombies behind
293                 self.connection.close()
294             except:
295                 # Irclib has a habit of throwing fresh exceptions here. Ignore that
296                 pass
297     def live(self):
298         "Should this connection not be scavenged?"
299         return self.status != "expired"
300     def joined_to(self, channel):
301         "Is this connection joined to the specified channel?"
302         return channel in self.channels_joined
303     def accepting(self, channel):
304         "Can this connection accept a join of this channel?"
305         if self.channel_limits:
306             match_count = 0
307             for already in self.channels_joined:
308                 # This obscure code is because the RFCs allow separate limits
309                 # by channel type (indicated by the first character of the name)
310                 # a feature that is almost never actually used.
311                 if already[0] == channel[0]:
312                     match_count += 1
313             return match_count < self.channel_limits.get(channel[0], CHANNEL_MAX)
314         else:
315             return len(self.channels_joined) < CHANNEL_MAX
316
317 class Target():
318     "Represent a transmission target."
319     def __init__(self, url):
320         # Pre-2.6 Pythons don't recognize irc: as a valid URL prefix.
321         url = url.replace("irc://", "http://")
322         parsed = urlparse.urlparse(url)
323         irchost, _, ircport = parsed.netloc.partition(':')
324         if not ircport:
325             ircport = 6667
326         self.servername = irchost
327         # IRC channel names are case-insensitive.  If we don't smash
328         # case here we may run into problems later. There was a bug
329         # observed on irc.rizon.net where an irkerd user specified #Channel,
330         # got kicked, and irkerd crashed because the server returned
331         # "#channel" in the notification that our kick handler saw.
332         self.channel = parsed.path.lstrip('/').lower()
333         # This deals with a tweak in recent versions of urlparse.
334         if parsed.fragment:
335             self.channel += "#" + parsed.fragment
336         isnick = self.channel.endswith(",isnick")
337         if isnick:
338             self.channel = self.channel[:-7]
339         if self.channel and not isnick and self.channel[0] not in "#&+":
340             self.channel = "#" + self.channel
341         self.port = int(ircport)
342     def valid(self):
343         "Both components must be present for a valid target."
344         return self.servername and self.channel
345     def server(self):
346         "Return a hashable tuple representing the destination server."
347         return (self.servername, self.port)
348
349 class Dispatcher:
350     "Manage connections to a particular server-port combination."
351     def __init__(self, irkerd, servername, port):
352         self.irker = irkerd
353         self.servername = servername
354         self.port = port
355         self.connections = []
356     def dispatch(self, channel, message):
357         "Dispatch messages for our server-port combination."
358         # First, check if there is room for another channel
359         # on any of our existing connections.
360         connections = [x for x in self.connections if x.live()]
361         eligibles = [x for x in connections if x.joined_to(channel)] \
362                     or [x for x in connections if x.accepting(channel)]
363         if eligibles:
364             eligibles[0].enqueue(channel, message)
365             return
366         # All connections are full up. Look for one old enough to be
367         # scavenged.
368         ancients = []
369         for connection in connections:
370             for (chan, age) in connections.channels_joined.items():
371                 if age < time.time() - CHANNEL_TTL:
372                     ancients.append((connection, chan, age))
373         if ancients:
374             ancients.sort(key=lambda x: x[2]) 
375             (found_connection, drop_channel, _drop_age) = ancients[0]
376             found_connection.part(drop_channel, "scavenged by irkerd")
377             del found_connection.channels_joined[drop_channel]
378             #time.sleep(ANTI_FLOOD_DELAY)
379             found_connection.enqueue(channel, message)
380             return
381         # Didn't find any channels with no recent activity
382         newconn = Connection(self.irker,
383                              self.servername,
384                              self.port)
385         self.connections.append(newconn)
386         newconn.enqueue(channel, message)
387     def live(self):
388         "Does this server-port combination have any live connections?"
389         self.connections = [x for x in self.connections if x.live()]
390         return len(self.connections) > 0
391     def last_xmit(self):
392         "Return the time of the most recent transmission."
393         return max(x.last_xmit for x in self.connections)
394
395 class Irker:
396     "Persistent IRC multiplexer."
397     def __init__(self, debuglevel=0):
398         self.debuglevel = debuglevel
399         self.irc = irc.client.IRC()
400         self.irc.add_global_handler("ping", self._handle_ping)
401         self.irc.add_global_handler("welcome", self._handle_welcome)
402         self.irc.add_global_handler("erroneusnickname", self._handle_badnick)
403         self.irc.add_global_handler("nicknameinuse", self._handle_badnick)
404         self.irc.add_global_handler("nickcollision", self._handle_badnick)
405         self.irc.add_global_handler("unavailresource", self._handle_badnick)
406         self.irc.add_global_handler("featurelist", self._handle_features)
407         self.irc.add_global_handler("disconnect", self._handle_disconnect)
408         self.irc.add_global_handler("kick", self._handle_kick)
409         self.irc.add_global_handler("all_raw_messages", self._handle_all_raw_messages)
410         thread = threading.Thread(target=self.irc.process_forever)
411         thread.setDaemon(True)
412         self.irc._thread = thread
413         thread.start()
414         self.servers = {}
415     def logerr(self, errmsg):
416         "Log a processing error."
417         sys.stderr.write("irkerd: " + errmsg + "\n")
418     def debug(self, level, errmsg):
419         "Debugging information."
420         if self.debuglevel >= level:
421             sys.stderr.write("irkerd: %s\n" % errmsg)
422     def _handle_ping(self, connection, _event):
423         "PING arrived, bump the last-received time for the connection."
424         if connection.context:
425             connection.context.handle_ping()
426     def _handle_welcome(self, connection, _event):
427         "Welcome arrived, nick accepted for this connection."
428         if connection.context:
429             connection.context.handle_welcome()
430     def _handle_badnick(self, connection, _event):
431         "Nick not accepted for this connection."
432         if connection.context:
433             connection.context.handle_badnick()
434     def _handle_features(self, connection, event):
435         "Determine if and how we can set deaf mode."
436         if connection.context:
437             cxt = connection.context
438             arguments = event.arguments
439             # irclib 5.0 compatibility, because the maintainer is a fool
440             if callable(arguments):
441                 arguments = arguments()
442             for lump in arguments:
443                 if lump.startswith("DEAF="):
444                     if not logfile:
445                         connection.mode(cxt.nickname(), "+"+lump[5:])
446                 elif lump.startswith("MAXCHANNELS="):
447                     m = int(lump[12:])
448                     for pref in "#&+":
449                         cxt.channel_limits[pref] = m
450                     self.debug(1, "%s maxchannels is %d"
451                                % (connection.server, m))
452                 elif lump.startswith("CHANLIMIT=#:"):
453                     limits = lump[10:].split(",")
454                     try:
455                         for token in limits:
456                             (prefixes, limit) = token.split(":")
457                             limit = int(limit)
458                             for c in prefixes:
459                                 cxt.channel_limits[c] = limit
460                         self.debug(1, "%s channel limit map is %s"
461                                    % (connection.server, cxt.channel_limits))
462                     except ValueError:
463                         self.logerr("ill-formed CHANLIMIT property")
464     def _handle_disconnect(self, connection, _event):
465         "Server hung up the connection."
466         self.debug(1, "server %s disconnected" % connection.server)
467         connection.close()
468         if connection.context:
469             connection.context.handle_disconnect()
470     def _handle_kick(self, connection, event):
471         "Server hung up the connection."
472         target = event.target
473         # irclib 5.0 compatibility, because the maintainer continues
474         # to be a fool.
475         if callable(target):
476             target = target()
477         self.debug(1, "irker has been kicked from %s on %s" % (target, connection.server))
478         if connection.context:
479             connection.context.handle_kick(target)
480     def _handle_all_raw_messages(self, _connection, event):
481         "Log all messages when in watcher mode."
482         if logfile:
483             with open(logfile, "a") as logfp:
484                 logfp.write("%03f|%s|%s\n" % \
485                              (time.time(), event.source, event.arguments[0]))
486     def handle(self, line):
487         "Perform a JSON relay request."
488         try:
489             request = json.loads(line.strip())
490             if not isinstance(request, dict):
491                 self.logerr("request is not a JSON dictionary: %r" % request)
492             elif "to" not in request or "privmsg" not in request:
493                 self.logerr("malformed request - 'to' or 'privmsg' missing: %r" % request)
494             else:
495                 channels = request['to']
496                 message = request['privmsg']
497                 if not isinstance(channels, (list, basestring)):
498                     self.logerr("malformed request - unexpected channel type: %r" % channels)
499                 if not isinstance(message, basestring):
500                     self.logerr("malformed request - unexpected message type: %r" % message)
501                 else:
502                     if not isinstance(channels, list):
503                         channels = [channels]
504                     for url in channels:
505                         if not isinstance(url, basestring):
506                             self.logerr("malformed request - URL has unexpected type: %r" % url)
507                         else:
508                             target = Target(url)
509                             if not target.valid():
510                                 return
511                             if target.server() not in self.servers:
512                                 self.servers[target.server()] = Dispatcher(self, target.servername, target.port)
513                             self.servers[target.server()].dispatch(target.channel, message)
514                             # GC dispatchers with no active connections
515                             servernames = self.servers.keys()
516                             for servername in servernames:
517                                 if not self.servers[servername].live():
518                                     del self.servers[servername]
519                             # If we might be pushing a resource limit
520                             # even after garbage collection, remove a
521                             # session.  The goal here is to head off
522                             # DoS attacks that aim at exhausting
523                             # thread space or file descriptors.  The
524                             # cost is that attempts to DoS this
525                             # service will cause lots of join/leave
526                             # spam as we scavenge old channels after
527                             # connecting to new ones. The particular
528                             # method used for selecting a session to
529                             # be terminated doesn't matter much; we
530                             # choose the one longest idle on the
531                             # assumption that message activity is likely
532                             # to be clumpy.
533                             if len(self.servers) >= CONNECTION_MAX:
534                                 oldest = min(self.servers.keys(), key=lambda name: self.servers[name].last_xmit())
535                                 del self.servers[oldest]
536         except ValueError:
537             self.logerr("can't recognize JSON on input: %r" % line)
538         except RuntimeError:
539             self.logerr("wildly malformed JSON blew the parser stack.")
540
541 class IrkerTCPHandler(SocketServer.StreamRequestHandler):
542     def handle(self):
543         while True:
544             line = self.rfile.readline()
545             if not line:
546                 break
547             irker.handle(line.strip())
548
549 class IrkerUDPHandler(SocketServer.BaseRequestHandler):
550     def handle(self):
551         data = self.request[0].strip()
552         #socket = self.request[1]
553         irker.handle(data)
554
555 def usage():
556     sys.stdout.write("""
557 Usage:
558   irkerd [-d debuglevel] [-l logfile] [-n nick] [-p password] [-V] [-h]
559
560 Options
561   -d    set debug level
562   -l    set logfile
563   -n    set nick-style
564   -p    set nickserv password
565   -V    return irkerd version
566   -h    print this help dialog
567 """)
568
569 if __name__ == '__main__':
570     debuglvl = 0
571     namestyle = "irker%03d"
572     password = None
573     logfile = None
574     try:
575         (options, arguments) = getopt.getopt(sys.argv[1:], "d:l:n:p:Vh")
576     except getopt.GetoptError as e:
577         sys.stderr.write("%s" % e)
578         usage()
579         sys.exit(1)
580     for (opt, val) in options:
581         if opt == '-d':         # Enable debug/progress messages
582             debuglvl = int(val)
583             if debuglvl > 1:
584                 logging.basicConfig(level=logging.DEBUG)
585         elif opt == '-l':       # Logfile mode - report traffic read in
586             logfile = val
587         elif opt == '-n':       # Force the nick
588             namestyle = val
589         elif opt == '-p':       # Set a nickserv password
590             password = val
591         elif opt == '-V':       # Emit version and exit
592             sys.stdout.write("irkerd version %s\n" % version)
593             sys.exit(0)
594         elif opt == '-h':
595             usage()
596             sys.exit(0)
597     fallback = re.search("%.*d", namestyle)
598     irker = Irker(debuglevel=debuglvl)
599     irker.debug(1, "irkerd version %s" % version)
600     try:
601         tcpserver = SocketServer.TCPServer((HOST, PORT), IrkerTCPHandler)
602         udpserver = SocketServer.UDPServer((HOST, PORT), IrkerUDPHandler)
603         for server in [tcpserver, udpserver]:
604             server = threading.Thread(target=server.serve_forever)
605             server.setDaemon(True)
606             server.start()
607         try:
608             signal.pause()
609         except KeyboardInterrupt:
610             raise SystemExit(1)
611     except socket.error, e:
612         sys.stderr.write("irkerd: server launch failed: %r\n" % e)
613
614 # end