Advertisement
Guest User

Untitled

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