Prototype UDP based IRC Emulator

I have hacked up a very simple IRC server written in python that broadcasts messages via UDP to a list of other servers of the same type.
The original IRC server is from this Shithub. I made this mostly just to experiment with UDP and learn something about the IRC protocol.

At the moment all it will do is share PRIVMSGs between servers. It doesn't handle pretty much anything else, such as for example JOIN/PART messages.

1 #! /usr/bin/env python
2
3 VERSION = "1.1"
4
5 import os
6 import re
7 import select
8 import socket
9 import string
10 import sys
11 import tempfile
12 import time
13 from datetime import datetime
14 from optparse import OptionParser
15
16
17 def create_directory(path):
18 if not os.path.isdir(path):
19 os.makedirs(path)
20
21
22 class Channel(object):
23 def __init__(self, server, name):
24 self.server = server
25 self.name = name
26 self.members = set()
27 self._topic = ""
28 self._key = None
29 if self.server.statedir:
30 self._state_path = "%s/%s" % (
31 self.server.statedir,
32 name.replace("_", "__").replace("/", "_"))
33 self._read_state()
34 else:
35 self._state_path = None
36
37 def add_member(self, client):
38 self.members.add(client)
39
40 def get_topic(self):
41 return self._topic
42
43 def set_topic(self, value):
44 self._topic = value
45 self._write_state()
46
47 topic = property(get_topic, set_topic)
48
49 def get_key(self):
50 return self._key
51
52 def set_key(self, value):
53 self._key = value
54 self._write_state()
55
56 key = property(get_key, set_key)
57
58 def remove_client(self, client):
59 self.members.discard(client)
60 if not self.members:
61 self.server.remove_channel(self)
62
63 def _read_state(self):
64 if not (self._state_path and os.path.exists(self._state_path)):
65 return
66 data = {}
67 exec(open(self._state_path), {}, data)
68 self._topic = data.get("topic", "")
69 self._key = data.get("key")
70
71 def _write_state(self):
72 if not self._state_path:
73 return
74 (fd, path) = tempfile.mkstemp(dir=os.path.dirname(self._state_path))
75 fp = os.fdopen(fd, "w")
76 fp.write("topic = %r\n" % self.topic)
77 fp.write("key = %r\n" % self.key)
78 fp.close()
79 os.rename(path, self._state_path)
80
81
82 class Client(object):
83 __linesep_regexp = re.compile(r"\r?\n")
84 # The RFC limit for nicknames is 9 characters, but what the heck.
85 __valid_nickname_regexp = re.compile(
86 r"^[][\`_^{|}A-Za-z][][\`_^{|}A-Za-z0-9-]{0,50}$")
87 __valid_channelname_regexp = re.compile(
88 r"^[&#+!][^\x00\x07\x0a\x0d ,:]{0,50}$")
89
90 def __init__(self, server, socket):
91 self.server = server
92 self.socket = socket
93 self.channels = {} # irc_lower(Channel name) --> Channel
94 self.nickname = None
95 self.user = None
96 self.realname = None
97 (self.host, self.port) = socket.getpeername()
98 self.__timestamp = time.time()
99 self.__readbuffer = ""
100 self.__writebuffer = ""
101 self.__sent_ping = False
102 if self.server.password:
103 self.__handle_command = self.__pass_handler
104 else:
105 self.__handle_command = self.__registration_handler
106
107 def get_prefix(self):
108 return "%s!%s@%s" % (self.nickname, self.user, self.host)
109 prefix = property(get_prefix)
110
111 def check_aliveness(self):
112 now = time.time()
113 if self.__timestamp + 180 < now:
114 self.disconnect("ping timeout")
115 return
116 if not self.__sent_ping and self.__timestamp + 90 < now:
117 if self.__handle_command == self.__command_handler:
118 # Registered.
119 self.message("PING :%s" % self.server.name)
120 self.__sent_ping = True
121 else:
122 # Not registered.
123 self.disconnect("ping timeout")
124
125 def write_queue_size(self):
126 return len(self.__writebuffer)
127
128 def __parse_read_buffer(self):
129 lines = self.__linesep_regexp.split(self.__readbuffer)
130 self.__readbuffer = lines[-1]
131 lines = lines[:-1]
132 for line in lines:
133 if not line:
134 # Empty line. Ignore.
135 continue
136 x = line.split(" ", 1)
137 command = x[0].upper()
138 if len(x) == 1:
139 arguments = []
140 else:
141 if len(x[1]) > 0 and x[1][0] == ":":
142 arguments = \[x\[1][1:\]\]
143 else:
144 y = string.split(x[1], " :", 1)
145 arguments = string.split(y[0])
146 if len(y) == 2:
147 arguments.append(y[1])
148 self.__handle_command(command, arguments)
149
150 def __pass_handler(self, command, arguments):
151 server = self.server
152 if command == "PASS":
153 if len(arguments) == 0:
154 self.reply_461("PASS")
155 else:
156 if arguments[0].lower() == server.password:
157 self.__handle_command = self.__registration_handler
158 else:
159 self.reply("464 :Password incorrect")
160 elif command == "QUIT":
161 self.disconnect("Client quit")
162 return
163
164 def __registration_handler(self, command, arguments):
165 server = self.server
166 if command == "NICK":
167 if len(arguments) < 1:
168 self.reply("431 :No nickname given")
169 return
170 nick = arguments[0]
171 if server.get_client(nick):
172 self.reply("433 * %s :Nickname is already in use" % nick)
173 elif not self.__valid_nickname_regexp.match(nick):
174 self.reply("432 * %s :Erroneous nickname" % nick)
175 else:
176 self.nickname = nick
177 server.client_changed_nickname(self, None)
178 elif command == "USER":
179 if len(arguments) < 4:
180 self.reply_461("USER")
181 return
182 self.user = arguments[0]
183 self.realname = arguments[3]
184 elif command == "QUIT":
185 self.disconnect("Client quit")
186 return
187 if self.nickname and self.user:
188 self.reply("001 %s :Hi, welcome to IRC" % self.nickname)
189 self.reply("002 %s :Your host is %s, running version miniircd-%s"
190 % (self.nickname, server.name, VERSION))
191 self.reply("003 %s :This server was created sometime"
192 % self.nickname)
193 self.reply("004 %s :%s miniircd-%s o o"
194 % (self.nickname, server.name, VERSION))
195 self.send_lusers()
196 self.send_motd()
197 self.__handle_command = self.__command_handler
198
199 def __command_handler(self, command, arguments):
200 def away_handler():
201 pass
202
203 def ison_handler():
204 if len(arguments) < 1:
205 self.reply_461("ISON")
206 return
207 nicks = arguments
208 online = [n for n in nicks if server.get_client(n)]
209 self.reply("303 %s :%s" % (self.nickname, " ".join(online)))
210
211 def join_handler():
212 if len(arguments) < 1:
213 self.reply_461("JOIN")
214 return
215 if arguments[0] == "0":
216 for (channelname, channel) in self.channels.items():
217 self.message_channel(channel, "PART", channelname, True)
218 self.channel_log(channel, "left", meta=True)
219 server.remove_member_from_channel(self, channelname)
220 self.channels = {}
221 return
222 channelnames = arguments[0].split(",")
223 if len(arguments) > 1:
224 keys = arguments[1].split(",")
225 else:
226 keys = []
227 keys.extend((len(channelnames) - len(keys)) * [None])
228 for (i, channelname) in enumerate(channelnames):
229 if irc_lower(channelname) in self.channels:
230 continue
231 if not valid_channel_re.match(channelname):
232 self.reply_403(channelname)
233 continue
234 channel = server.get_channel(channelname)
235 if channel.key is not None and channel.key != keys[i]:
236 self.reply(
237 "475 %s %s :Cannot join channel (+k) - bad key"
238 % (self.nickname, channelname))
239 continue
240 channel.add_member(self)
241 self.channels[irc_lower(channelname)] = channel
242 self.message_channel(channel, "JOIN", channelname, True)
243 self.channel_log(channel, "joined", meta=True)
244 if channel.topic:
245 self.reply("332 %s %s :%s"
246 % (self.nickname, channel.name, channel.topic))
247 else:
248 self.reply("331 %s %s :No topic is set"
249 % (self.nickname, channel.name))
250 self.reply("353 %s = %s :%s"
251 % (self.nickname,
252 channelname,
253 " ".join(sorted(x.nickname
254 for x in channel.members))))
255 self.reply("366 %s %s :End of NAMES list"
256 % (self.nickname, channelname))
257
258 def list_handler():
259 if len(arguments) < 1:
260 channels = server.channels.values()
261 else:
262 channels = []
263 for channelname in arguments[0].split(","):
264 if server.has_channel(channelname):
265 channels.append(server.get_channel(channelname))
266 channels.sort(key=lambda x: x.name)
267 for channel in channels:
268 self.reply("322 %s %s %d :%s"
269 % (self.nickname, channel.name,
270 len(channel.members), channel.topic))
271 self.reply("323 %s :End of LIST" % self.nickname)
272
273 def lusers_handler():
274 self.send_lusers()
275
276 def mode_handler():
277 if len(arguments) < 1:
278 self.reply_461("MODE")
279 return
280 targetname = arguments[0]
281 if server.has_channel(targetname):
282 channel = server.get_channel(targetname)
283 if len(arguments) < 2:
284 if channel.key:
285 modes = "+k"
286 if irc_lower(channel.name) in self.channels:
287 modes += " %s" % channel.key
288 else:
289 modes = "+"
290 self.reply("324 %s %s %s"
291 % (self.nickname, targetname, modes))
292 return
293 flag = arguments[1]
294 if flag == "+k":
295 if len(arguments) < 3:
296 self.reply_461("MODE")
297 return
298 key = arguments[2]
299 if irc_lower(channel.name) in self.channels:
300 channel.key = key
301 self.message_channel(
302 channel, "MODE", "%s +k %s" % (channel.name, key),
303 True)
304 self.channel_log(
305 channel, "set channel key to %s" % key, meta=True)
306 else:
307 self.reply("442 %s :You're not on that channel"
308 % targetname)
309 elif flag == "-k":
310 if irc_lower(channel.name) in self.channels:
311 channel.key = None
312 self.message_channel(
313 channel, "MODE", "%s -k" % channel.name,
314 True)
315 self.channel_log(
316 channel, "removed channel key", meta=True)
317 else:
318 self.reply("442 %s :You're not on that channel"
319 % targetname)
320 else:
321 self.reply("472 %s %s :Unknown MODE flag"
322 % (self.nickname, flag))
323 elif targetname == self.nickname:
324 if len(arguments) == 1:
325 self.reply("221 %s +" % self.nickname)
326 else:
327 self.reply("501 %s :Unknown MODE flag" % self.nickname)
328 else:
329 self.reply_403(targetname)
330
331 def motd_handler():
332 self.send_motd()
333
334 def nick_handler():
335 if len(arguments) < 1:
336 self.reply("431 :No nickname given")
337 return
338 newnick = arguments[0]
339 client = server.get_client(newnick)
340 if newnick == self.nickname:
341 pass
342 elif client and client is not self:
343 self.reply("433 %s %s :Nickname is already in use"
344 % (self.nickname, newnick))
345 elif not self.__valid_nickname_regexp.match(newnick):
346 self.reply("432 %s %s :Erroneous Nickname"
347 % (self.nickname, newnick))
348 else:
349 for x in self.channels.values():
350 self.channel_log(
351 x, "changed nickname to %s" % newnick, meta=True)
352 oldnickname = self.nickname
353 self.nickname = newnick
354 server.client_changed_nickname(self, oldnickname)
355 self.message_related(
356 ":%s!%s@%s NICK %s"
357 % (oldnickname, self.user, self.host, self.nickname),
358 True)
359
360 def notice_and_privmsg_handler():
361 if len(arguments) == 0:
362 self.reply("411 %s :No recipient given (%s)"
363 % (self.nickname, command))
364 return
365 if len(arguments) == 1:
366 self.reply("412 %s :No text to send" % self.nickname)
367 return
368 targetname = arguments[0]
369 message = arguments[1]
370 client = server.get_client(targetname)
371
372 if client:
373 client.message(":%s %s %s :%s"
374 % (self.prefix, command, targetname, message))
375 elif server.has_channel(targetname):
376 channel = server.get_channel(targetname)
377 self.message_channel(
378 channel, command, "%s :%s" % (channel.name, message))
379 self.channel_log(channel, message)
380 else:
381 self.reply("401 %s %s :No such nick/channel"
382 % (self.nickname, targetname))
383
384 def part_handler():
385 if len(arguments) < 1:
386 self.reply_461("PART")
387 return
388 if len(arguments) > 1:
389 partmsg = arguments[1]
390 else:
391 partmsg = self.nickname
392 for channelname in arguments[0].split(","):
393 if not valid_channel_re.match(channelname):
394 self.reply_403(channelname)
395 elif not irc_lower(channelname) in self.channels:
396 self.reply("442 %s %s :You're not on that channel"
397 % (self.nickname, channelname))
398 else:
399 channel = self.channels[irc_lower(channelname)]
400 self.message_channel(
401 channel, "PART", "%s :%s" % (channelname, partmsg),
402 True)
403 self.channel_log(channel, "left (%s)" % partmsg, meta=True)
404 del self.channels[irc_lower(channelname)]
405 server.remove_member_from_channel(self, channelname)
406
407 def ping_handler():
408 if len(arguments) < 1:
409 self.reply("409 %s :No origin specified" % self.nickname)
410 return
411 self.reply("PONG %s :%s" % (server.name, arguments[0]))
412
413 def pong_handler():
414 pass
415
416 def quit_handler():
417 if len(arguments) < 1:
418 quitmsg = self.nickname
419 else:
420 quitmsg = arguments[0]
421 self.disconnect(quitmsg)
422
423 def topic_handler():
424 if len(arguments) < 1:
425 self.reply_461("TOPIC")
426 return
427 channelname = arguments[0]
428 channel = self.channels.get(irc_lower(channelname))
429 if channel:
430 if len(arguments) > 1:
431 newtopic = arguments[1]
432 channel.topic = newtopic
433 self.message_channel(
434 channel, "TOPIC", "%s :%s" % (channelname, newtopic),
435 True)
436 self.channel_log(
437 channel, "set topic to %r" % newtopic, meta=True)
438 else:
439 if channel.topic:
440 self.reply("332 %s %s :%s"
441 % (self.nickname, channel.name,
442 channel.topic))
443 else:
444 self.reply("331 %s %s :No topic is set"
445 % (self.nickname, channel.name))
446 else:
447 self.reply("442 %s :You're not on that channel" % channelname)
448
449 def wallops_handler():
450 if len(arguments) < 1:
451 self.reply_461(command)
452 message = arguments[0]
453 for client in server.clients.values():
454 client.message(":%s NOTICE %s :Global notice: %s"
455 % (self.prefix, client.nickname, message))
456
457 def who_handler():
458 if len(arguments) < 1:
459 return
460 targetname = arguments[0]
461 if server.has_channel(targetname):
462 channel = server.get_channel(targetname)
463 for member in channel.members:
464 self.reply("352 %s %s %s %s %s %s H :0 %s"
465 % (self.nickname, targetname, member.user,
466 member.host, server.name, member.nickname,
467 member.realname))
468 self.reply("315 %s %s :End of WHO list"
469 % (self.nickname, targetname))
470
471 def whois_handler():
472 if len(arguments) < 1:
473 return
474 username = arguments[0]
475 user = server.get_client(username)
476 if user:
477 self.reply("311 %s %s %s %s * :%s"
478 % (self.nickname, user.nickname, user.user,
479 user.host, user.realname))
480 self.reply("312 %s %s %s :%s"
481 % (self.nickname, user.nickname, server.name,
482 server.name))
483 self.reply("319 %s %s :%s"
484 % (self.nickname, user.nickname,
485 " ".join(user.channels)))
486 self.reply("318 %s %s :End of WHOIS list"
487 % (self.nickname, user.nickname))
488 else:
489 self.reply("401 %s %s :No such nick"
490 % (self.nickname, username))
491
492 handler_table = {
493 "AWAY": away_handler,
494 "ISON": ison_handler,
495 "JOIN": join_handler,
496 "LIST": list_handler,
497 "LUSERS": lusers_handler,
498 "MODE": mode_handler,
499 "MOTD": motd_handler,
500 "NICK": nick_handler,
501 "NOTICE": notice_and_privmsg_handler,
502 "PART": part_handler,
503 "PING": ping_handler,
504 "PONG": pong_handler,
505 "PRIVMSG": notice_and_privmsg_handler,
506 "QUIT": quit_handler,
507 "TOPIC": topic_handler,
508 "WALLOPS": wallops_handler,
509 "WHO": who_handler,
510 "WHOIS": whois_handler,
511 }
512 server = self.server
513 valid_channel_re = self.__valid_channelname_regexp
514 try:
515 handler_table[command]()
516 except KeyError:
517 self.reply("421 %s %s :Unknown command" % (self.nickname, command))
518
519 def udp_data_received(self, data):
520 if data:
521 self.message(data)
522
523 def socket_readable_notification(self):
524 try:
525 data = self.socket.recv(2 ** 10)
526 self.server.print_debug(
527 "[%s:%d] -> %r" % (self.host, self.port, data))
528 quitmsg = "EOT"
529 except socket.error as x:
530 data = ""
531 quitmsg = x
532 if data:
533 self.__readbuffer += data
534 self.__parse_read_buffer()
535 self.__timestamp = time.time()
536 self.__sent_ping = False
537 for peer in self.server.peers:
538 peer.send(self, data)
539 else:
540 self.disconnect(quitmsg)
541
542 def socket_writable_notification(self):
543 try:
544 print("socket_writable_notification: %s" % self.__writebuffer)
545 sent = self.socket.send(self.__writebuffer)
546 self.server.print_debug(
547 "[%s:%d] <- %r" % (
548 self.host, self.port, self.__writebuffer[:sent]))
549 self.__writebuffer = self.__writebuffer[sent:]
550 except socket.error as x:
551 self.disconnect(x)
552
553 def disconnect(self, quitmsg):
554 self.message("ERROR :%s" % quitmsg)
555 self.server.print_info(
556 "Disconnected connection from %s:%s (%s)." % (
557 self.host, self.port, quitmsg))
558 self.socket.close()
559 self.server.remove_client(self, quitmsg)
560
561 def message(self, msg):
562 self.__writebuffer += msg + "\r\n"
563
564 def reply(self, msg):
565 self.message(":%s %s" % (self.server.name, msg))
566
567 def reply_403(self, channel):
568 self.reply("403 %s %s :No such channel" % (self.nickname, channel))
569
570 def reply_461(self, command):
571 nickname = self.nickname or "*"
572 self.reply("461 %s %s :Not enough parameters" % (nickname, command))
573
574 def message_channel(self, channel, command, message, include_self=False):
575 line = ":%s %s %s" % (self.prefix, command, message)
576 for client in channel.members:
577 if client != self or include_self:
578 client.message(line)
579
580 def channel_log(self, channel, message, meta=False):
581 if not self.server.logdir:
582 return
583 if meta:
584 format = "[%s] * %s %s\n"
585 else:
586 format = "[%s] <%s> %s\n"
587 timestamp = datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S UTC")
588 logname = channel.name.replace("_", "__").replace("/", "_")
589 fp = open("%s/%s.log" % (self.server.logdir, logname), "a")
590 fp.write(format % (timestamp, self.nickname, message))
591 fp.close()
592
593 def message_related(self, msg, include_self=False):
594 clients = set()
595 if include_self:
596 clients.add(self)
597 for channel in self.channels.values():
598 clients |= channel.members
599 if not include_self:
600 clients.discard(self)
601 for client in clients:
602 client.message(msg)
603
604 def send_lusers(self):
605 self.reply("251 %s :There are %d users and 0 services on 1 server"
606 % (self.nickname, len(self.server.clients)))
607
608 def send_motd(self):
609 server = self.server
610 motdlines = server.get_motd_lines()
611 if motdlines:
612 self.reply("375 %s :- %s Message of the day -"
613 % (self.nickname, server.name))
614 for line in motdlines:
615 self.reply("372 %s :- %s" % (self.nickname, line.rstrip()))
616 self.reply("376 %s :End of /MOTD command" % self.nickname)
617 else:
618 self.reply("422 %s :MOTD File is missing" % self.nickname)
619
620 class Peer(object):
621 def __init__(self, address):
622 self.address = address
623 self.socket = socket.socket(family=socket.AF_INET, type=socket.SOCK_DGRAM)
624
625 def send(self, client, msg):
626 print(client)
627 print(":%s %s" % (client.nickname, msg))
628 self.socket.sendto(str.encode(":%s %s" % (client.nickname, msg)), (self.address, 7778))
629
630 class Server(object):
631 def __init__(self, options):
632 self.ports = options.ports
633 self.peers = options.peers
634 self.udp_port = options.udp_port
635 self.password = options.password
636 self.ssl_pem_file = options.ssl_pem_file
637 self.motdfile = options.motd
638 self.verbose = options.verbose
639 self.debug = options.debug
640 self.logdir = options.logdir
641 self.chroot = options.chroot
642 self.setuid = options.setuid
643 self.statedir = options.statedir
644
645 if options.listen:
646 self.address = socket.gethostbyname(options.listen)
647 else:
648 self.address = ""
649 server_name_limit = 63 # From the RFC.
650 self.name = socket.getfqdn(self.address)[:server_name_limit]
651
652 self.channels = {} # irc_lower(Channel name) --> Channel instance.
653 self.clients = {} # Socket --> Client instance..peers = ""
654 self.nicknames = {} # irc_lower(Nickname) --> Client instance.
655 if self.logdir:
656 create_directory(self.logdir)
657 if self.statedir:
658 create_directory(self.statedir)
659
660 def daemonize(self):
661 try:
662 pid = os.fork()
663 if pid > 0:
664 sys.exit(0)
665 except OSError:
666 sys.exit(1)
667 os.setsid()
668 try:
669 pid = os.fork()
670 if pid > 0:
671 self.print_info("PID: %d" % pid)
672 sys.exit(0)
673 except OSError:
674 sys.exit(1)
675 os.chdir("/")
676 os.umask(0)
677 dev_null = open("/dev/null", "r+")
678 os.dup2(dev_null.fileno(), sys.stdout.fileno())
679 os.dup2(dev_null.fileno(), sys.stderr.fileno())
680 os.dup2(dev_null.fileno(), sys.stdin.fileno())
681
682 def get_client(self, nickname):
683 return self.nicknames.get(irc_lower(nickname))
684
685 def has_channel(self, name):
686 return irc_lower(name) in self.channels
687
688 def get_channel(self, channelname):
689 if irc_lower(channelname) in self.channels:
690 channel = self.channels[irc_lower(channelname)]
691 else:
692 channel = Channel(self, channelname)
693 self.channels[irc_lower(channelname)] = channel
694 return channel
695
696 def get_motd_lines(self):
697 if self.motdfile:
698 try:
699 return open(self.motdfile).readlines()
700 except IOError:
701 return ["Could not read MOTD file %r." % self.motdfile]
702 else:
703 return []
704
705 def print_info(self, msg):
706 if self.verbose:
707 print(msg)
708 sys.stdout.flush()
709
710 def print_debug(self, msg):
711 if self.debug:
712 print(msg)
713 sys.stdout.flush()
714
715 def print_error(self, msg):
716 sys.stderr.write("%s\n" % msg)
717
718 def client_changed_nickname(self, client, oldnickname):
719 if oldnickname:
720 del self.nicknames[irc_lower(oldnickname)]
721 self.nicknames[irc_lower(client.nickname)] = client
722
723 def remove_member_from_channel(self, client, channelname):
724 if irc_lower(channelname) in self.channels:
725 channel = self.channels[irc_lower(channelname)]
726 channel.remove_client(client)
727
728 def remove_client(self, client, quitmsg):
729 client.message_related(":%s QUIT :%s" % (client.prefix, quitmsg))
730 for x in client.channels.values():
731 client.channel_log(x, "quit (%s)" % quitmsg, meta=True)
732 x.remove_client(client)
733 if client.nickname \
734 and irc_lower(client.nickname) in self.nicknames:
735 del self.nicknames[irc_lower(client.nickname)]
736 del self.clients[client.socket]
737
738 def remove_channel(self, channel):
739 del self.channels[irc_lower(channel.name)]
740
741 def start(self):
742 # Setup UDP first
743 udp_server_socket = socket.socket(family=socket.AF_INET, type=socket.SOCK_DGRAM)
744 udp_server_socket.bind((self.address, self.udp_port))
745
746 serversockets = []
747 for port in self.ports:
748 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
749 s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
750 try:
751 s.bind((self.address, port))
752 except socket.error as e:
753 self.print_error("Could not bind port %s: %s." % (port, e))
754 sys.exit(1)
755 s.listen(5)
756 serversockets.append(s)
757 del s
758 self.print_info("Listening on port %d." % port)
759 if self.chroot:
760 os.chdir(self.chroot)
761 os.chroot(self.chroot)
762 self.print_info("Changed root directory to %s" % self.chroot)
763 if self.setuid:
764 os.setgid(self.setuid[1])
765 os.setuid(self.setuid[0])
766 self.print_info("Setting uid:gid to %s:%s"
767 % (self.setuid[0], self.setuid[1]))
768 last_aliveness_check = time.time()
769 while True:
770 (inputready,outputready,exceptready) = select.select([udp_server_socket],[],[],0)
771 (iwtd, owtd, ewtd) = select.select(
772 serversockets + [x.socket for x in self.clients.values()],
773 [x.socket for x in self.clients.values()
774 if x.write_queue_size() > 0],
775 [],
776 0)
777 for x in inputready:
778 if x == udp_server_socket:
779 bytes_address_pair = udp_server_socket.recvfrom(1024)
780 message = bytes_address_pair[0]
781 address = bytes_address_pair[1]
782 print message
783 for c in self.clients:
784 self.clients[c].udp_data_received(message)
785 for x in iwtd:
786 if x in self.clients:
787 self.clients[x].socket_readable_notification()
788 else:
789 (conn, addr) = x.accept()
790 if self.ssl_pem_file:
791 import ssl
792 try:
793 conn = ssl.wrap_socket(
794 conn,
795 server_side=True,
796 certfile=self.ssl_pem_file,
797 keyfile=self.ssl_pem_file)
798 except ssl.SSLError as e:
799 self.print_error(
800 "SSL error for connection from %s:%s: %s" % (
801 addr[0], addr[1], e))
802 continue
803 self.clients[conn] = Client(self, conn)
804 self.print_info("Accepted connection from %s:%s." % (
805 addr[0], addr[1]))
806 for x in owtd:
807 if x in self.clients: # client may have been disconnected
808 self.clients[x].socket_writable_notification()
809 now = time.time()
810 if last_aliveness_check + 10 < now:
811 for client in self.clients.values():
812 client.check_aliveness()
813 last_aliveness_check = now
814
815 _maketrans = str.maketrans if sys.version_info[0] == 3 else string.maketrans
816 _ircstring_translation = _maketrans(
817 string.ascii_lowercase.upper() + "[]\\^",
818 string.ascii_lowercase + "{}|~")
819
820
821 def irc_lower(s):
822 return string.translate(s, _ircstring_translation)
823
824
825 def main(argv):
826 op = OptionParser(
827 version=VERSION,
828 description="miniircd is a small and limited IRC server.")
829 op.add_option(
830 "-d", "--daemon",
831 action="store_true",
832 help="fork and become a daemon")
833 op.add_option(
834 "--debug",
835 action="store_true",
836 help="print debug messages to stdout")
837 op.add_option(
838 "--listen",
839 metavar="X",
840 help="listen on specific IP address X")
841 op.add_option(
842 "--logdir",
843 metavar="X",
844 help="store channel log in directory X")
845 op.add_option(
846 "--motd",
847 metavar="X",
848 help="display file X as message of the day")
849 op.add_option(
850 "-s", "--ssl-pem-file",
851 metavar="FILE",
852 help="enable SSL and use FILE as the .pem certificate+key")
853 op.add_option(
854 "-p", "--password",
855 metavar="X",
856 help="require connection password X; default: no password")
857 op.add_option(
858 "--ports",
859 metavar="X",
860 help="listen to ports X (a list separated by comma or whitespace);"
861 " default: 6667 or 6697 if SSL is enabled")
862 op.add_option(
863 "--udp-port",
864 metavar="X",
865 help="listen for UDP packets on X;"
866 " default: 7778")
867 op.add_option(
868 "--peers",
869 metavar="X",
870 help="Broadcast to X (a list of IP addresses separated by comma or whitespace)")
871 op.add_option(
872 "--statedir",
873 metavar="X",
874 help="save persistent channel state (topic, key) in directory X")
875 op.add_option(
876 "--verbose",
877 action="store_true",
878 help="be verbose (print some progress messages to stdout)")
879 if os.name == "posix":
880 op.add_option(
881 "--chroot",
882 metavar="X",
883 help="change filesystem root to directory X after startup"
884 " (requires root)")
885 op.add_option(
886 "--setuid",
887 metavar="U[:G]",
888 help="change process user (and optionally group) after startup"
889 " (requires root)")
890
891 (options, args) = op.parse_args(argv[1:])
892 if options.debug:
893 options.verbose = True
894 if options.ports is None:
895 if options.ssl_pem_file is None:
896 options.ports = "6667"
897 else:
898 options.ports = "6697"
899 if options.peers is None:
900 options.peers = ""
901 if options.udp_port is None:
902 options.udp_port = 7778
903 else:
904 options.udp_port = int(options.udp_port)
905 if options.chroot:
906 if os.getuid() != 0:
907 op.error("Must be root to use --chroot")
908 if options.setuid:
909 from pwd import getpwnam
910 from grp import getgrnam
911 if os.getuid() != 0:
912 op.error("Must be root to use --setuid")
913 matches = options.setuid.split(":")
914 if len(matches) == 2:
915 options.setuid = (getpwnam(matches[0]).pw_uid,
916 getgrnam(matches[1]).gr_gid)
917 elif len(matches) == 1:
918 options.setuid = (getpwnam(matches[0]).pw_uid,
919 getpwnam(matches[0]).pw_gid)
920 else:
921 op.error("Specify a user, or user and group separated by a colon,"
922 " e.g. --setuid daemon, --setuid nobody:nobody")
923 if (os.getuid() == 0 or os.getgid() == 0) and not options.setuid:
924 op.error("Running this service as root is not recommended. Use the"
925 " --setuid option to switch to an unprivileged account after"
926 " startup. If you really intend to run as root, use"
927 " \"--setuid root\".")
928
929 ports = []
930 for port in re.split(r"[,\s]+", options.ports):
931 try:
932 ports.append(int(port))
933 except ValueError:
934 op.error("bad port: %r" % port)
935 options.ports = ports
936 peers = []
937 for peer in re.split(r"[,\s]+", options.peers):
938 try:
939 peers.append(Peer(peer))
940 except ValueError:
941 op.error("bad peer ip: %r" % peer)
942 options.peers = peers
943 server = Server(options)
944 if options.daemon:
945 server.daemonize()
946 try:
947 server.start()
948 except KeyboardInterrupt:
949 server.print_error("Interrupted.")
950
951
952 main(sys.argv)
953
954

3 Responses to “Prototype UDP based IRC Emulator”

  1. whaack says:

    I'd like to try this out but the paste of your code is a a bit borked Maybe host it as a separate file on your server?

  2. PeterL says:

    Maybe I am missing it, but is there a way to add peers once this is running, or is it only at startup that you can choose peers?

  3. thimbronion says:

    You can only add peers at start up.

Leave a Reply