Awesome IRC bot
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

1086 lines
39 KiB

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