client.py 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378
  1. # -*- coding: utf-8 -*-
  2. """
  3. Internet Relay Chat (IRC) protocol client library.
  4. This library is intended to encapsulate the IRC protocol in Python.
  5. It provides an event-driven IRC client framework. It has
  6. a fairly thorough support for the basic IRC protocol, CTCP, and DCC chat.
  7. To best understand how to make an IRC client, the reader more
  8. or less must understand the IRC specifications. They are available
  9. here: [IRC specifications].
  10. The main features of the IRC client framework are:
  11. * Abstraction of the IRC protocol.
  12. * Handles multiple simultaneous IRC server connections.
  13. * Handles server PONGing transparently.
  14. * Messages to the IRC server are done by calling methods on an IRC
  15. connection object.
  16. * Messages from an IRC server triggers events, which can be caught
  17. by event handlers.
  18. * Reading from and writing to IRC server sockets are normally done
  19. by an internal select() loop, but the select()ing may be done by
  20. an external main loop.
  21. * Functions can be registered to execute at specified times by the
  22. event-loop.
  23. * Decodes CTCP tagging correctly (hopefully); I haven't seen any
  24. other IRC client implementation that handles the CTCP
  25. specification subtilties.
  26. * A kind of simple, single-server, object-oriented IRC client class
  27. that dispatches events to instance methods is included.
  28. Current limitations:
  29. * Data is not written asynchronously to the server, i.e. the write()
  30. may block if the TCP buffers are stuffed.
  31. * DCC file transfers are not supported.
  32. * RFCs 2810, 2811, 2812, and 2813 have not been considered.
  33. Notes:
  34. * connection.quit() only sends QUIT to the server.
  35. * ERROR from the server triggers the error event and the disconnect event.
  36. * dropping of the connection triggers the disconnect event.
  37. .. [IRC specifications] http://www.irchelp.org/irchelp/rfc/
  38. """
  39. from __future__ import absolute_import, division
  40. import bisect
  41. import re
  42. import select
  43. import socket
  44. import time
  45. import struct
  46. import logging
  47. import threading
  48. import abc
  49. import collections
  50. import functools
  51. import itertools
  52. import contextlib
  53. import six
  54. from jaraco.itertools import always_iterable
  55. from jaraco.functools import Throttler
  56. try:
  57. import pkg_resources
  58. except ImportError:
  59. pass
  60. from . import connection
  61. from . import events
  62. from . import functools as irc_functools
  63. from . import buffer
  64. from . import schedule
  65. from . import features
  66. from . import ctcp
  67. from . import message
  68. log = logging.getLogger(__name__)
  69. # set the version tuple
  70. try:
  71. VERSION_STRING = pkg_resources.require('irc')[0].version
  72. VERSION = tuple(int(res) for res in re.findall('\d+', VERSION_STRING))
  73. except Exception:
  74. VERSION_STRING = 'unknown'
  75. VERSION = ()
  76. class IRCError(Exception):
  77. "An IRC exception"
  78. class InvalidCharacters(ValueError):
  79. "Invalid characters were encountered in the message"
  80. class MessageTooLong(ValueError):
  81. "Message is too long"
  82. class PrioritizedHandler(
  83. collections.namedtuple('Base', ('priority', 'callback'))):
  84. def __lt__(self, other):
  85. "when sorting prioritized handlers, only use the priority"
  86. return self.priority < other.priority
  87. class Reactor(object):
  88. """
  89. Processes events from one or more IRC server connections.
  90. This class implements a reactor in the style of the `reactor pattern
  91. <http://en.wikipedia.org/wiki/Reactor_pattern>`_.
  92. When a Reactor object has been instantiated, it can be used to create
  93. Connection objects that represent the IRC connections. The
  94. responsibility of the reactor object is to provide an event-driven
  95. framework for the connections and to keep the connections alive.
  96. It runs a select loop to poll each connection's TCP socket and
  97. hands over the sockets with incoming data for processing by the
  98. corresponding connection.
  99. The methods of most interest for an IRC client writer are server,
  100. add_global_handler, remove_global_handler, execute_at,
  101. execute_delayed, execute_every, process_once, and process_forever.
  102. This is functionally an event-loop which can either use it's own
  103. internal polling loop, or tie into an external event-loop, by
  104. having the external event-system periodically call `process_once`
  105. on the instantiated reactor class. This will allow the reactor
  106. to process any queued data and/or events.
  107. Calling `process_forever` will hand off execution to the reactor's
  108. internal event-loop, which will not return for the life of the
  109. reactor.
  110. Here is an example:
  111. client = irc.client.Reactor()
  112. server = client.server()
  113. server.connect("irc.some.where", 6667, "my_nickname")
  114. server.privmsg("a_nickname", "Hi there!")
  115. client.process_forever()
  116. This will connect to the IRC server irc.some.where on port 6667
  117. using the nickname my_nickname and send the message "Hi there!"
  118. to the nickname a_nickname.
  119. The methods of this class are thread-safe; accesses to and modifications
  120. of its internal lists of connections, handlers, and delayed commands
  121. are guarded by a mutex.
  122. """
  123. def __do_nothing(*args, **kwargs):
  124. pass
  125. def __init__(self, on_connect=__do_nothing, on_disconnect=__do_nothing,
  126. on_schedule=__do_nothing):
  127. """Constructor for Reactor objects.
  128. on_connect: optional callback invoked when a new connection
  129. is made.
  130. on_disconnect: optional callback invoked when a socket is
  131. disconnected.
  132. on_schedule: optional callback, usually supplied by an external
  133. event loop, to indicate in float seconds that the client needs to
  134. process events that many seconds in the future. An external event
  135. loop will implement this callback to schedule a call to
  136. process_timeout.
  137. The three arguments mainly exist to be able to use an external
  138. main loop (for example Tkinter's or PyGTK's main app loop)
  139. instead of calling the process_forever method.
  140. An alternative is to just call ServerConnection.process_once()
  141. once in a while.
  142. """
  143. self._on_connect = on_connect
  144. self._on_disconnect = on_disconnect
  145. self._on_schedule = on_schedule
  146. self.connections = []
  147. self.handlers = {}
  148. self.delayed_commands = [] # list of DelayedCommands
  149. # Modifications to these shared lists and dict need to be thread-safe
  150. self.mutex = threading.RLock()
  151. self.add_global_handler("ping", _ping_ponger, -42)
  152. def server(self):
  153. """Creates and returns a ServerConnection object."""
  154. c = ServerConnection(self)
  155. with self.mutex:
  156. self.connections.append(c)
  157. return c
  158. def process_data(self, sockets):
  159. """Called when there is more data to read on connection sockets.
  160. Arguments:
  161. sockets -- A list of socket objects.
  162. See documentation for Reactor.__init__.
  163. """
  164. with self.mutex:
  165. log.log(logging.DEBUG-2, "process_data()")
  166. for s, c in itertools.product(sockets, self.connections):
  167. if s == c.socket:
  168. c.process_data()
  169. def process_timeout(self):
  170. """Called when a timeout notification is due.
  171. See documentation for Reactor.__init__.
  172. """
  173. with self.mutex:
  174. while self.delayed_commands:
  175. command = self.delayed_commands[0]
  176. if not command.due():
  177. break
  178. command.function()
  179. if isinstance(command, schedule.PeriodicCommand):
  180. self._schedule_command(command.next())
  181. del self.delayed_commands[0]
  182. @property
  183. def sockets(self):
  184. with self.mutex:
  185. return [
  186. conn.socket
  187. for conn in self.connections
  188. if conn is not None
  189. and conn.socket is not None
  190. ]
  191. def process_once(self, timeout=0):
  192. """Process data from connections once.
  193. Arguments:
  194. timeout -- How long the select() call should wait if no
  195. data is available.
  196. This method should be called periodically to check and process
  197. incoming data, if there are any. If that seems boring, look
  198. at the process_forever method.
  199. """
  200. log.log(logging.DEBUG-2, "process_once()")
  201. sockets = self.sockets
  202. if sockets:
  203. (i, o, e) = select.select(sockets, [], [], timeout)
  204. self.process_data(i)
  205. else:
  206. time.sleep(timeout)
  207. self.process_timeout()
  208. def process_forever(self, timeout=0.2):
  209. """Run an infinite loop, processing data from connections.
  210. This method repeatedly calls process_once.
  211. Arguments:
  212. timeout -- Parameter to pass to process_once.
  213. """
  214. # This loop should specifically *not* be mutex-locked.
  215. # Otherwise no other thread would ever be able to change
  216. # the shared state of a Reactor object running this function.
  217. log.debug("process_forever(timeout=%s)", timeout)
  218. while 1:
  219. self.process_once(timeout)
  220. def disconnect_all(self, message=""):
  221. """Disconnects all connections."""
  222. with self.mutex:
  223. for c in self.connections:
  224. c.disconnect(message)
  225. def add_global_handler(self, event, handler, priority=0):
  226. """Adds a global handler function for a specific event type.
  227. Arguments:
  228. event -- Event type (a string). Check the values of
  229. numeric_events for possible event types.
  230. handler -- Callback function taking 'connection' and 'event'
  231. parameters.
  232. priority -- A number (the lower number, the higher priority).
  233. The handler function is called whenever the specified event is
  234. triggered in any of the connections. See documentation for
  235. the Event class.
  236. The handler functions are called in priority order (lowest
  237. number is highest priority). If a handler function returns
  238. "NO MORE", no more handlers will be called.
  239. """
  240. handler = PrioritizedHandler(priority, handler)
  241. with self.mutex:
  242. event_handlers = self.handlers.setdefault(event, [])
  243. bisect.insort(event_handlers, handler)
  244. def remove_global_handler(self, event, handler):
  245. """Removes a global handler function.
  246. Arguments:
  247. event -- Event type (a string).
  248. handler -- Callback function.
  249. Returns 1 on success, otherwise 0.
  250. """
  251. with self.mutex:
  252. if not event in self.handlers:
  253. return 0
  254. for h in self.handlers[event]:
  255. if handler == h.callback:
  256. self.handlers[event].remove(h)
  257. return 1
  258. def execute_at(self, at, function, arguments=()):
  259. """Execute a function at a specified time.
  260. Arguments:
  261. at -- Execute at this time (a standard Unix timestamp).
  262. function -- Function to call.
  263. arguments -- Arguments to give the function.
  264. """
  265. function = functools.partial(function, *arguments)
  266. command = schedule.DelayedCommand.at_time(at, function)
  267. self._schedule_command(command)
  268. def execute_delayed(self, delay, function, arguments=()):
  269. """
  270. Execute a function after a specified time.
  271. delay -- How many seconds to wait.
  272. function -- Function to call.
  273. arguments -- Arguments to give the function.
  274. """
  275. function = functools.partial(function, *arguments)
  276. command = schedule.DelayedCommand.after(delay, function)
  277. self._schedule_command(command)
  278. def execute_every(self, period, function, arguments=()):
  279. """
  280. Execute a function every 'period' seconds.
  281. period -- How often to run (always waits this long for first).
  282. function -- Function to call.
  283. arguments -- Arguments to give the function.
  284. """
  285. function = functools.partial(function, *arguments)
  286. command = schedule.PeriodicCommand.after(period, function)
  287. self._schedule_command(command)
  288. def _schedule_command(self, command):
  289. with self.mutex:
  290. bisect.insort(self.delayed_commands, command)
  291. self._on_schedule(command.delay.total_seconds())
  292. def dcc(self, dcctype="chat"):
  293. """Creates and returns a DCCConnection object.
  294. Arguments:
  295. dcctype -- "chat" for DCC CHAT connections or "raw" for
  296. DCC SEND (or other DCC types). If "chat",
  297. incoming data will be split in newline-separated
  298. chunks. If "raw", incoming data is not touched.
  299. """
  300. with self.mutex:
  301. c = DCCConnection(self, dcctype)
  302. self.connections.append(c)
  303. return c
  304. def _handle_event(self, connection, event):
  305. """
  306. Handle an Event event incoming on ServerConnection connection.
  307. """
  308. with self.mutex:
  309. h = self.handlers
  310. matching_handlers = sorted(
  311. h.get("all_events", []) +
  312. h.get(event.type, [])
  313. )
  314. for handler in matching_handlers:
  315. result = handler.callback(connection, event)
  316. if result == "NO MORE":
  317. return
  318. def _remove_connection(self, connection):
  319. """[Internal]"""
  320. with self.mutex:
  321. self.connections.remove(connection)
  322. self._on_disconnect(connection.socket)
  323. _cmd_pat = "^(@(?P<tags>[^ ]*) )?(:(?P<prefix>[^ ]+) +)?(?P<command>[^ ]+)( *(?P<argument> .+))?"
  324. _rfc_1459_command_regexp = re.compile(_cmd_pat)
  325. @six.add_metaclass(abc.ABCMeta)
  326. class Connection(object):
  327. """
  328. Base class for IRC connections.
  329. """
  330. @abc.abstractproperty
  331. def socket(self):
  332. "The socket for this connection"
  333. def __init__(self, reactor):
  334. self.reactor = reactor
  335. ##############################
  336. ### Convenience wrappers.
  337. def execute_at(self, at, function, arguments=()):
  338. self.reactor.execute_at(at, function, arguments)
  339. def execute_delayed(self, delay, function, arguments=()):
  340. self.reactor.execute_delayed(delay, function, arguments)
  341. def execute_every(self, period, function, arguments=()):
  342. self.reactor.execute_every(period, function, arguments)
  343. class ServerConnectionError(IRCError):
  344. pass
  345. class ServerNotConnectedError(ServerConnectionError):
  346. pass
  347. class ServerConnection(Connection):
  348. """
  349. An IRC server connection.
  350. ServerConnection objects are instantiated by calling the server
  351. method on a Reactor object.
  352. """
  353. buffer_class = buffer.DecodingLineBuffer
  354. socket = None
  355. def __init__(self, reactor):
  356. super(ServerConnection, self).__init__(reactor)
  357. self.connected = False
  358. self.features = features.FeatureSet()
  359. # save the method args to allow for easier reconnection.
  360. @irc_functools.save_method_args
  361. def connect(self, server, port, nickname, password=None, username=None,
  362. ircname=None, connect_factory=connection.Factory()):
  363. """Connect/reconnect to a server.
  364. Arguments:
  365. * server - Server name
  366. * port - Port number
  367. * nickname - The nickname
  368. * password - Password (if any)
  369. * username - The username
  370. * ircname - The IRC name ("realname")
  371. * server_address - The remote host/port of the server
  372. * connect_factory - A callable that takes the server address and
  373. returns a connection (with a socket interface)
  374. This function can be called to reconnect a closed connection.
  375. Returns the ServerConnection object.
  376. """
  377. log.debug("connect(server=%r, port=%r, nickname=%r, ...)", server,
  378. port, nickname)
  379. if self.connected:
  380. self.disconnect("Changing servers")
  381. self.buffer = self.buffer_class()
  382. self.handlers = {}
  383. self.real_server_name = ""
  384. self.real_nickname = nickname
  385. self.server = server
  386. self.port = port
  387. self.server_address = (server, port)
  388. self.nickname = nickname
  389. self.username = username or nickname
  390. self.ircname = ircname or nickname
  391. self.password = password
  392. self.connect_factory = connect_factory
  393. try:
  394. self.socket = self.connect_factory(self.server_address)
  395. except socket.error as ex:
  396. raise ServerConnectionError("Couldn't connect to socket: %s" % ex)
  397. self.connected = True
  398. self.reactor._on_connect(self.socket)
  399. # Log on...
  400. if self.password:
  401. self.pass_(self.password)
  402. self.nick(self.nickname)
  403. self.user(self.username, self.ircname)
  404. return self
  405. def reconnect(self):
  406. """
  407. Reconnect with the last arguments passed to self.connect()
  408. """
  409. self.connect(*self._saved_connect.args, **self._saved_connect.kwargs)
  410. def close(self):
  411. """Close the connection.
  412. This method closes the connection permanently; after it has
  413. been called, the object is unusable.
  414. """
  415. # Without this thread lock, there is a window during which
  416. # select() can find a closed socket, leading to an EBADF error.
  417. with self.reactor.mutex:
  418. self.disconnect("Closing object")
  419. self.reactor._remove_connection(self)
  420. def get_server_name(self):
  421. """Get the (real) server name.
  422. This method returns the (real) server name, or, more
  423. specifically, what the server calls itself.
  424. """
  425. return self.real_server_name or ""
  426. def get_nickname(self):
  427. """Get the (real) nick name.
  428. This method returns the (real) nickname. The library keeps
  429. track of nick changes, so it might not be the nick name that
  430. was passed to the connect() method.
  431. """
  432. return self.real_nickname
  433. @contextlib.contextmanager
  434. def as_nick(self, name):
  435. """
  436. Set the nick for the duration of the context.
  437. """
  438. orig = self.get_nickname()
  439. self.nick(name)
  440. try:
  441. yield orig
  442. finally:
  443. self.nick(orig)
  444. def process_data(self):
  445. "read and process input from self.socket"
  446. try:
  447. reader = getattr(self.socket, 'read', self.socket.recv)
  448. new_data = reader(2 ** 14)
  449. except socket.error:
  450. # The server hung up.
  451. self.disconnect("Connection reset by peer")
  452. return
  453. if not new_data:
  454. # Read nothing: connection must be down.
  455. self.disconnect("Connection reset by peer")
  456. return
  457. self.buffer.feed(new_data)
  458. # process each non-empty line after logging all lines
  459. for line in self.buffer:
  460. log.debug("FROM SERVER: %s", line)
  461. if not line: continue
  462. self._process_line(line)
  463. def _process_line(self, line):
  464. event = Event("all_raw_messages", self.get_server_name(), None,
  465. [line])
  466. self._handle_event(event)
  467. grp = _rfc_1459_command_regexp.match(line).group
  468. source = NickMask.from_group(grp("prefix"))
  469. command = self._command_from_group(grp("command"))
  470. arguments = message.Arguments.from_group(grp('argument'))
  471. tags = message.Tag.from_group(grp('tags'))
  472. if source and not self.real_server_name:
  473. self.real_server_name = source
  474. if command == "nick":
  475. if source.nick == self.real_nickname:
  476. self.real_nickname = arguments[0]
  477. elif command == "welcome":
  478. # Record the nickname in case the client changed nick
  479. # in a nicknameinuse callback.
  480. self.real_nickname = arguments[0]
  481. elif command == "featurelist":
  482. self.features.load(arguments)
  483. handler = (
  484. self._handle_message
  485. if command in ["privmsg", "notice"]
  486. else self._handle_other
  487. )
  488. handler(arguments, command, source, tags)
  489. def _handle_message(self, arguments, command, source, tags):
  490. target, msg = arguments[:2]
  491. messages = ctcp.dequote(msg)
  492. if command == "privmsg":
  493. if is_channel(target):
  494. command = "pubmsg"
  495. else:
  496. if is_channel(target):
  497. command = "pubnotice"
  498. else:
  499. command = "privnotice"
  500. for m in messages:
  501. if isinstance(m, tuple):
  502. if command in ["privmsg", "pubmsg"]:
  503. command = "ctcp"
  504. else:
  505. command = "ctcpreply"
  506. m = list(m)
  507. log.debug("command: %s, source: %s, target: %s, "
  508. "arguments: %s, tags: %s", command, source, target, m, tags)
  509. event = Event(command, source, target, m, tags)
  510. self._handle_event(event)
  511. if command == "ctcp" and m[0] == "ACTION":
  512. event = Event("action", source, target, m[1:], tags)
  513. self._handle_event(event)
  514. else:
  515. log.debug("command: %s, source: %s, target: %s, "
  516. "arguments: %s, tags: %s", command, source, target, [m], tags)
  517. event = Event(command, source, target, [m], tags)
  518. self._handle_event(event)
  519. def _handle_other(self, arguments, command, source, tags):
  520. target = None
  521. if command == "quit":
  522. arguments = [arguments[0]]
  523. elif command == "ping":
  524. target = arguments[0]
  525. else:
  526. target = arguments[0] if arguments else None
  527. arguments = arguments[1:]
  528. if command == "mode":
  529. if not is_channel(target):
  530. command = "umode"
  531. log.debug("command: %s, source: %s, target: %s, "
  532. "arguments: %s, tags: %s", command, source, target, arguments, tags)
  533. event = Event(command, source, target, arguments, tags)
  534. self._handle_event(event)
  535. @staticmethod
  536. def _command_from_group(group):
  537. command = group.lower()
  538. # Translate numerics into more readable strings.
  539. return events.numeric.get(command, command)
  540. def _handle_event(self, event):
  541. """[Internal]"""
  542. self.reactor._handle_event(self, event)
  543. if event.type in self.handlers:
  544. for fn in self.handlers[event.type]:
  545. fn(self, event)
  546. def is_connected(self):
  547. """Return connection status.
  548. Returns true if connected, otherwise false.
  549. """
  550. return self.connected
  551. def add_global_handler(self, *args):
  552. """Add global handler.
  553. See documentation for IRC.add_global_handler.
  554. """
  555. self.reactor.add_global_handler(*args)
  556. def remove_global_handler(self, *args):
  557. """Remove global handler.
  558. See documentation for IRC.remove_global_handler.
  559. """
  560. self.reactor.remove_global_handler(*args)
  561. def action(self, target, action):
  562. """Send a CTCP ACTION command."""
  563. self.ctcp("ACTION", target, action)
  564. def admin(self, server=""):
  565. """Send an ADMIN command."""
  566. self.send_raw(" ".join(["ADMIN", server]).strip())
  567. def cap(self, subcommand, *args):
  568. """
  569. Send a CAP command according to `the spec
  570. <http://ircv3.atheme.org/specification/capability-negotiation-3.1>`_.
  571. Arguments:
  572. subcommand -- LS, LIST, REQ, ACK, CLEAR, END
  573. args -- capabilities, if required for given subcommand
  574. Example:
  575. .cap('LS')
  576. .cap('REQ', 'multi-prefix', 'sasl')
  577. .cap('END')
  578. """
  579. cap_subcommands = set('LS LIST REQ ACK NAK CLEAR END'.split())
  580. client_subcommands = set(cap_subcommands) - set('NAK')
  581. assert subcommand in client_subcommands, "invalid subcommand"
  582. def _multi_parameter(args):
  583. """
  584. According to the spec::
  585. If more than one capability is named, the RFC1459 designated
  586. sentinel (:) for a multi-parameter argument must be present.
  587. It's not obvious where the sentinel should be present or if it
  588. must be omitted for a single parameter, so follow convention and
  589. only include the sentinel prefixed to the first parameter if more
  590. than one parameter is present.
  591. """
  592. if len(args) > 1:
  593. return (':' + args[0],) + args[1:]
  594. return args
  595. args = _multi_parameter(args)
  596. self.send_raw(' '.join(('CAP', subcommand) + args))
  597. def ctcp(self, ctcptype, target, parameter=""):
  598. """Send a CTCP command."""
  599. ctcptype = ctcptype.upper()
  600. tmpl = (
  601. "\001{ctcptype} {parameter}\001" if parameter else
  602. "\001{ctcptype}\001"
  603. )
  604. self.privmsg(target, tmpl.format(**vars()))
  605. def ctcp_reply(self, target, parameter):
  606. """Send a CTCP REPLY command."""
  607. self.notice(target, "\001%s\001" % parameter)
  608. def disconnect(self, message=""):
  609. """Hang up the connection.
  610. Arguments:
  611. message -- Quit message.
  612. """
  613. if not self.connected:
  614. return
  615. self.connected = 0
  616. self.quit(message)
  617. try:
  618. self.socket.shutdown(socket.SHUT_WR)
  619. self.socket.close()
  620. except socket.error:
  621. pass
  622. del self.socket
  623. self._handle_event(Event("disconnect", self.server, "", [message]))
  624. def globops(self, text):
  625. """Send a GLOBOPS command."""
  626. self.send_raw("GLOBOPS :" + text)
  627. def info(self, server=""):
  628. """Send an INFO command."""
  629. self.send_raw(" ".join(["INFO", server]).strip())
  630. def invite(self, nick, channel):
  631. """Send an INVITE command."""
  632. self.send_raw(" ".join(["INVITE", nick, channel]).strip())
  633. def ison(self, nicks):
  634. """Send an ISON command.
  635. Arguments:
  636. nicks -- List of nicks.
  637. """
  638. self.send_raw("ISON " + " ".join(nicks))
  639. def join(self, channel, key=""):
  640. """Send a JOIN command."""
  641. self.send_raw("JOIN %s%s" % (channel, (key and (" " + key))))
  642. def kick(self, channel, nick, comment=""):
  643. """Send a KICK command."""
  644. tmpl = "KICK {channel} {nick}"
  645. if comment:
  646. tmpl += " :{comment}"
  647. self.send_raw(tmpl.format(**vars()))
  648. def links(self, remote_server="", server_mask=""):
  649. """Send a LINKS command."""
  650. command = "LINKS"
  651. if remote_server:
  652. command = command + " " + remote_server
  653. if server_mask:
  654. command = command + " " + server_mask
  655. self.send_raw(command)
  656. def list(self, channels=None, server=""):
  657. """Send a LIST command."""
  658. command = "LIST"
  659. channels = ",".join(always_iterable(channels))
  660. if channels:
  661. command += ' ' + channels
  662. if server:
  663. command = command + " " + server
  664. self.send_raw(command)
  665. def lusers(self, server=""):
  666. """Send a LUSERS command."""
  667. self.send_raw("LUSERS" + (server and (" " + server)))
  668. def mode(self, target, command):
  669. """Send a MODE command."""
  670. self.send_raw("MODE %s %s" % (target, command))
  671. def motd(self, server=""):
  672. """Send an MOTD command."""
  673. self.send_raw("MOTD" + (server and (" " + server)))
  674. def names(self, channels=None):
  675. """Send a NAMES command."""
  676. tmpl = "NAMES {channels}" if channels else "NAMES"
  677. channels = ','.join(always_iterable(channels))
  678. self.send_raw(tmpl.format(channels=channels))
  679. def nick(self, newnick):
  680. """Send a NICK command."""
  681. self.send_raw("NICK " + newnick)
  682. def notice(self, target, text):
  683. """Send a NOTICE command."""
  684. # Should limit len(text) here!
  685. self.send_raw("NOTICE %s :%s" % (target, text))
  686. def oper(self, nick, password):
  687. """Send an OPER command."""
  688. self.send_raw("OPER %s %s" % (nick, password))
  689. def part(self, channels, message=""):
  690. """Send a PART command."""
  691. channels = always_iterable(channels)
  692. cmd_parts = [
  693. 'PART',
  694. ','.join(channels),
  695. ]
  696. if message: cmd_parts.append(message)
  697. self.send_raw(' '.join(cmd_parts))
  698. def pass_(self, password):
  699. """Send a PASS command."""
  700. self.send_raw("PASS " + password)
  701. def ping(self, target, target2=""):
  702. """Send a PING command."""
  703. self.send_raw("PING %s%s" % (target, target2 and (" " + target2)))
  704. def pong(self, target, target2=""):
  705. """Send a PONG command."""
  706. self.send_raw("PONG %s%s" % (target, target2 and (" " + target2)))
  707. def privmsg(self, target, text):
  708. """Send a PRIVMSG command."""
  709. self.send_raw("PRIVMSG %s :%s" % (target, text))
  710. def privmsg_many(self, targets, text):
  711. """Send a PRIVMSG command to multiple targets."""
  712. target = ','.join(targets)
  713. return self.privmsg(target, text)
  714. def quit(self, message=""):
  715. """Send a QUIT command."""
  716. # Note that many IRC servers don't use your QUIT message
  717. # unless you've been connected for at least 5 minutes!
  718. self.send_raw("QUIT" + (message and (" :" + message)))
  719. def _prep_message(self, string):
  720. # The string should not contain any carriage return other than the
  721. # one added here.
  722. if '\n' in string:
  723. msg = "Carriage returns not allowed in privmsg(text)"
  724. raise InvalidCharacters(msg)
  725. bytes = string.encode('utf-8') + b'\r\n'
  726. # According to the RFC http://tools.ietf.org/html/rfc2812#page-6,
  727. # clients should not transmit more than 512 bytes.
  728. if len(bytes) > 512:
  729. msg = "Messages limited to 512 bytes including CR/LF"
  730. raise MessageTooLong(msg)
  731. return bytes
  732. def send_raw(self, string):
  733. """Send raw string to the server.
  734. The string will be padded with appropriate CR LF.
  735. """
  736. if self.socket is None:
  737. raise ServerNotConnectedError("Not connected.")
  738. sender = getattr(self.socket, 'write', self.socket.send)
  739. try:
  740. sender(self._prep_message(string))
  741. log.debug("TO SERVER: %s", string)
  742. except socket.error:
  743. # Ouch!
  744. self.disconnect("Connection reset by peer.")
  745. def squit(self, server, comment=""):
  746. """Send an SQUIT command."""
  747. self.send_raw("SQUIT %s%s" % (server, comment and (" :" + comment)))
  748. def stats(self, statstype, server=""):
  749. """Send a STATS command."""
  750. self.send_raw("STATS %s%s" % (statstype, server and (" " + server)))
  751. def time(self, server=""):
  752. """Send a TIME command."""
  753. self.send_raw("TIME" + (server and (" " + server)))
  754. def topic(self, channel, new_topic=None):
  755. """Send a TOPIC command."""
  756. if new_topic is None:
  757. self.send_raw("TOPIC " + channel)
  758. else:
  759. self.send_raw("TOPIC %s :%s" % (channel, new_topic))
  760. def trace(self, target=""):
  761. """Send a TRACE command."""
  762. self.send_raw("TRACE" + (target and (" " + target)))
  763. def user(self, username, realname):
  764. """Send a USER command."""
  765. self.send_raw("USER %s 0 * :%s" % (username, realname))
  766. def userhost(self, nicks):
  767. """Send a USERHOST command."""
  768. self.send_raw("USERHOST " + ",".join(nicks))
  769. def users(self, server=""):
  770. """Send a USERS command."""
  771. self.send_raw("USERS" + (server and (" " + server)))
  772. def version(self, server=""):
  773. """Send a VERSION command."""
  774. self.send_raw("VERSION" + (server and (" " + server)))
  775. def wallops(self, text):
  776. """Send a WALLOPS command."""
  777. self.send_raw("WALLOPS :" + text)
  778. def who(self, target="", op=""):
  779. """Send a WHO command."""
  780. self.send_raw("WHO%s%s" % (target and (" " + target), op and (" o")))
  781. def whois(self, targets):
  782. """Send a WHOIS command."""
  783. self.send_raw("WHOIS " + ",".join(always_iterable(targets)))
  784. def whowas(self, nick, max="", server=""):
  785. """Send a WHOWAS command."""
  786. self.send_raw("WHOWAS %s%s%s" % (nick,
  787. max and (" " + max),
  788. server and (" " + server)))
  789. def set_rate_limit(self, frequency):
  790. """
  791. Set a `frequency` limit (messages per second) for this connection.
  792. Any attempts to send faster than this rate will block.
  793. """
  794. self.send_raw = Throttler(self.send_raw, frequency)
  795. def set_keepalive(self, interval):
  796. """
  797. Set a keepalive to occur every ``interval`` on this connection.
  798. """
  799. pinger = functools.partial(self.ping, 'keep-alive')
  800. self.reactor.execute_every(period=interval, function=pinger)
  801. class DCCConnectionError(IRCError):
  802. pass
  803. class DCCConnection(Connection):
  804. """
  805. A DCC (Direct Client Connection).
  806. DCCConnection objects are instantiated by calling the dcc
  807. method on a Reactor object.
  808. """
  809. socket = None
  810. def __init__(self, reactor, dcctype):
  811. super(DCCConnection, self).__init__(reactor)
  812. self.connected = 0
  813. self.passive = 0
  814. self.dcctype = dcctype
  815. self.peeraddress = None
  816. self.peerport = None
  817. def connect(self, address, port):
  818. """Connect/reconnect to a DCC peer.
  819. Arguments:
  820. address -- Host/IP address of the peer.
  821. port -- The port number to connect to.
  822. Returns the DCCConnection object.
  823. """
  824. self.peeraddress = socket.gethostbyname(address)
  825. self.peerport = port
  826. self.buffer = buffer.LineBuffer()
  827. self.handlers = {}
  828. self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  829. self.passive = 0
  830. try:
  831. self.socket.connect((self.peeraddress, self.peerport))
  832. except socket.error as x:
  833. raise DCCConnectionError("Couldn't connect to socket: %s" % x)
  834. self.connected = 1
  835. self.reactor._on_connect(self.socket)
  836. return self
  837. def listen(self):
  838. """Wait for a connection/reconnection from a DCC peer.
  839. Returns the DCCConnection object.
  840. The local IP address and port are available as
  841. self.localaddress and self.localport. After connection from a
  842. peer, the peer address and port are available as
  843. self.peeraddress and self.peerport.
  844. """
  845. self.buffer = buffer.LineBuffer()
  846. self.handlers = {}
  847. self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  848. self.passive = 1
  849. try:
  850. self.socket.bind((socket.gethostbyname(socket.gethostname()), 0))
  851. self.localaddress, self.localport = self.socket.getsockname()
  852. self.socket.listen(10)
  853. except socket.error as x:
  854. raise DCCConnectionError("Couldn't bind socket: %s" % x)
  855. return self
  856. def disconnect(self, message=""):
  857. """Hang up the connection and close the object.
  858. Arguments:
  859. message -- Quit message.
  860. """
  861. if not self.connected:
  862. return
  863. self.connected = 0
  864. try:
  865. self.socket.shutdown(socket.SHUT_WR)
  866. self.socket.close()
  867. except socket.error:
  868. pass
  869. del self.socket
  870. self.reactor._handle_event(
  871. self,
  872. Event("dcc_disconnect", self.peeraddress, "", [message]))
  873. self.reactor._remove_connection(self)
  874. def process_data(self):
  875. """[Internal]"""
  876. if self.passive and not self.connected:
  877. conn, (self.peeraddress, self.peerport) = self.socket.accept()
  878. self.socket.close()
  879. self.socket = conn
  880. self.connected = 1
  881. log.debug("DCC connection from %s:%d", self.peeraddress,
  882. self.peerport)
  883. self.reactor._handle_event(
  884. self,
  885. Event("dcc_connect", self.peeraddress, None, None))
  886. return
  887. try:
  888. new_data = self.socket.recv(2 ** 14)
  889. except socket.error:
  890. # The server hung up.
  891. self.disconnect("Connection reset by peer")
  892. return
  893. if not new_data:
  894. # Read nothing: connection must be down.
  895. self.disconnect("Connection reset by peer")
  896. return
  897. if self.dcctype == "chat":
  898. self.buffer.feed(new_data)
  899. chunks = list(self.buffer)
  900. if len(self.buffer) > 2 ** 14:
  901. # Bad peer! Naughty peer!
  902. log.info("Received >16k from a peer without a newline; "
  903. "disconnecting.")
  904. self.disconnect()
  905. return
  906. else:
  907. chunks = [new_data]
  908. command = "dccmsg"
  909. prefix = self.peeraddress
  910. target = None
  911. for chunk in chunks:
  912. log.debug("FROM PEER: %s", chunk)
  913. arguments = [chunk]
  914. log.debug("command: %s, source: %s, target: %s, arguments: %s",
  915. command, prefix, target, arguments)
  916. event = Event(command, prefix, target, arguments)
  917. self.reactor._handle_event(self, event)
  918. def privmsg(self, text):
  919. """
  920. Send text to DCC peer.
  921. The text will be padded with a newline if it's a DCC CHAT session.
  922. """
  923. if self.dcctype == 'chat':
  924. text += '\n'
  925. bytes = text.encode('utf-8')
  926. return self.send_bytes(bytes)
  927. def send_bytes(self, bytes):
  928. """
  929. Send data to DCC peer.
  930. """
  931. try:
  932. self.socket.send(bytes)
  933. log.debug("TO PEER: %r\n", bytes)
  934. except socket.error:
  935. self.disconnect("Connection reset by peer.")
  936. class SimpleIRCClient(object):
  937. """A simple single-server IRC client class.
  938. This is an example of an object-oriented wrapper of the IRC
  939. framework. A real IRC client can be made by subclassing this
  940. class and adding appropriate methods.
  941. The method on_join will be called when a "join" event is created
  942. (which is done when the server sends a JOIN messsage/command),
  943. on_privmsg will be called for "privmsg" events, and so on. The
  944. handler methods get two arguments: the connection object (same as
  945. self.connection) and the event object.
  946. Functionally, any of the event names in `events.py` my be subscribed
  947. to by prefixing them with `on_`, and creating a function of that
  948. name in the child-class of `SimpleIRCClient`. When the event of
  949. `event_name` is received, the appropriately named method will be
  950. called (if it exists) by runtime class introspection.
  951. See `_dispatcher()`, which takes the event name, postpends it to
  952. `on_`, and then attemps to look up the class member function by
  953. name and call it.
  954. Instance attributes that can be used by sub classes:
  955. reactor -- The Reactor instance.
  956. connection -- The ServerConnection instance.
  957. dcc_connections -- A list of DCCConnection instances.
  958. """
  959. reactor_class = Reactor
  960. def __init__(self):
  961. self.reactor = self.reactor_class()
  962. self.connection = self.reactor.server()
  963. self.dcc_connections = []
  964. self.reactor.add_global_handler("all_events", self._dispatcher, -10)
  965. self.reactor.add_global_handler("dcc_disconnect",
  966. self._dcc_disconnect, -10)
  967. def _dispatcher(self, connection, event):
  968. """
  969. Dispatch events to on_<event.type> method, if present.
  970. """
  971. log.debug("_dispatcher: %s", event.type)
  972. do_nothing = lambda c, e: None
  973. method = getattr(self, "on_" + event.type, do_nothing)
  974. method(connection, event)
  975. def _dcc_disconnect(self, c, e):
  976. self.dcc_connections.remove(c)
  977. def connect(self, *args, **kwargs):
  978. """Connect using the underlying connection"""
  979. self.connection.connect(*args, **kwargs)
  980. def dcc_connect(self, address, port, dcctype="chat"):
  981. """Connect to a DCC peer.
  982. Arguments:
  983. address -- IP address of the peer.
  984. port -- Port to connect to.
  985. Returns a DCCConnection instance.
  986. """
  987. dcc = self.reactor.dcc(dcctype)
  988. self.dcc_connections.append(dcc)
  989. dcc.connect(address, port)
  990. return dcc
  991. def dcc_listen(self, dcctype="chat"):
  992. """Listen for connections from a DCC peer.
  993. Returns a DCCConnection instance.
  994. """
  995. dcc = self.reactor.dcc(dcctype)
  996. self.dcc_connections.append(dcc)
  997. dcc.listen()
  998. return dcc
  999. def start(self):
  1000. """Start the IRC client."""
  1001. self.reactor.process_forever()
  1002. class Event(object):
  1003. "An IRC event."
  1004. def __init__(self, type, source, target, arguments=None, tags=None):
  1005. """
  1006. Initialize an Event.
  1007. Arguments:
  1008. type -- A string describing the event.
  1009. source -- The originator of the event (a nick mask or a server).
  1010. target -- The target of the event (a nick or a channel).
  1011. arguments -- Any event-specific arguments.
  1012. """
  1013. self.type = type
  1014. self.source = source
  1015. self.target = target
  1016. if arguments is None:
  1017. arguments = []
  1018. self.arguments = arguments
  1019. if tags is None:
  1020. tags = []
  1021. self.tags = tags
  1022. def is_channel(string):
  1023. """Check if a string is a channel name.
  1024. Returns true if the argument is a channel name, otherwise false.
  1025. """
  1026. return string and string[0] in "#&+!"
  1027. def ip_numstr_to_quad(num):
  1028. """
  1029. Convert an IP number as an integer given in ASCII
  1030. representation to an IP address string.
  1031. >>> ip_numstr_to_quad('3232235521')
  1032. '192.168.0.1'
  1033. >>> ip_numstr_to_quad(3232235521)
  1034. '192.168.0.1'
  1035. """
  1036. n = int(num)
  1037. packed = struct.pack('>L', n)
  1038. bytes = struct.unpack('BBBB', packed)
  1039. return ".".join(map(str, bytes))
  1040. def ip_quad_to_numstr(quad):
  1041. """
  1042. Convert an IP address string (e.g. '192.168.0.1') to an IP
  1043. number as a base-10 integer given in ASCII representation.
  1044. >>> ip_quad_to_numstr('192.168.0.1')
  1045. '3232235521'
  1046. """
  1047. bytes = map(int, quad.split("."))
  1048. packed = struct.pack('BBBB', *bytes)
  1049. return str(struct.unpack('>L', packed)[0])
  1050. class NickMask(six.text_type):
  1051. """
  1052. A nickmask (the source of an Event)
  1053. >>> nm = NickMask('pinky!username@example.com')
  1054. >>> nm.nick
  1055. 'pinky'
  1056. >>> nm.host
  1057. 'example.com'
  1058. >>> nm.user
  1059. 'username'
  1060. >>> isinstance(nm, six.text_type)
  1061. True
  1062. >>> nm = 'красный!red@yahoo.ru'
  1063. >>> if not six.PY3: nm = nm.decode('utf-8')
  1064. >>> nm = NickMask(nm)
  1065. >>> isinstance(nm.nick, six.text_type)
  1066. True
  1067. Some messages omit the userhost. In that case, None is returned.
  1068. >>> nm = NickMask('irc.server.net')
  1069. >>> nm.nick
  1070. 'irc.server.net'
  1071. >>> nm.userhost
  1072. >>> nm.host
  1073. >>> nm.user
  1074. """
  1075. @classmethod
  1076. def from_params(cls, nick, user, host):
  1077. return cls('{nick}!{user}@{host}'.format(**vars()))
  1078. @property
  1079. def nick(self):
  1080. nick, sep, userhost = self.partition("!")
  1081. return nick
  1082. @property
  1083. def userhost(self):
  1084. nick, sep, userhost = self.partition("!")
  1085. return userhost or None
  1086. @property
  1087. def host(self):
  1088. nick, sep, userhost = self.partition("!")
  1089. user, sep, host = userhost.partition('@')
  1090. return host or None
  1091. @property
  1092. def user(self):
  1093. nick, sep, userhost = self.partition("!")
  1094. user, sep, host = userhost.partition('@')
  1095. return user or None
  1096. @classmethod
  1097. def from_group(cls, group):
  1098. return cls(group) if group else None
  1099. def _ping_ponger(connection, event):
  1100. "A global handler for the 'ping' event"
  1101. connection.pong(event.target)