xmlstream.py 71 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819
  1. """
  2. sleekxmpp.xmlstream.xmlstream
  3. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  4. This module provides the module for creating and
  5. interacting with generic XML streams, along with
  6. the necessary eventing infrastructure.
  7. Part of SleekXMPP: The Sleek XMPP Library
  8. :copyright: (c) 2011 Nathanael C. Fritz
  9. :license: MIT, see LICENSE for more details
  10. """
  11. from __future__ import with_statement, unicode_literals
  12. import base64
  13. import copy
  14. import logging
  15. import signal
  16. import socket as Socket
  17. import ssl
  18. import sys
  19. import threading
  20. import time
  21. import random
  22. import weakref
  23. import uuid
  24. import errno
  25. from xml.parsers.expat import ExpatError
  26. import sleekxmpp
  27. from sleekxmpp.util import Queue, QueueEmpty, safedict
  28. from sleekxmpp.thirdparty.statemachine import StateMachine
  29. from sleekxmpp.xmlstream import Scheduler, tostring, cert
  30. from sleekxmpp.xmlstream.stanzabase import StanzaBase, ET, ElementBase
  31. from sleekxmpp.xmlstream.handler import Waiter, XMLCallback
  32. from sleekxmpp.xmlstream.matcher import MatchXMLMask
  33. from sleekxmpp.xmlstream.resolver import resolve, default_resolver
  34. # In Python 2.x, file socket objects are broken. A patched socket
  35. # wrapper is provided for this case in filesocket.py.
  36. if sys.version_info < (3, 0):
  37. from sleekxmpp.xmlstream.filesocket import FileSocket, Socket26
  38. #: The time in seconds to wait before timing out waiting for response stanzas.
  39. RESPONSE_TIMEOUT = 30
  40. #: The time in seconds to wait for events from the event queue, and also the
  41. #: time between checks for the process stop signal.
  42. WAIT_TIMEOUT = 1.0
  43. #: The number of threads to use to handle XML stream events. This is not the
  44. #: same as the number of custom event handling threads.
  45. #: :data:`HANDLER_THREADS` must be at least 1. For Python implementations
  46. #: with a GIL, this should be left at 1, but for implemetnations without
  47. #: a GIL increasing this value can provide better performance.
  48. HANDLER_THREADS = 1
  49. #: The time in seconds to delay between attempts to resend data
  50. #: after an SSL error.
  51. SSL_RETRY_DELAY = 0.5
  52. #: The maximum number of times to attempt resending data due to
  53. #: an SSL error.
  54. SSL_RETRY_MAX = 10
  55. #: Maximum time to delay between connection attempts is one hour.
  56. RECONNECT_MAX_DELAY = 600
  57. #: Maximum number of attempts to connect to the server before quitting
  58. #: and raising a 'connect_failed' event. Setting this to ``None`` will
  59. #: allow infinite reconnection attempts, and using ``0`` will disable
  60. #: reconnections. Defaults to ``None``.
  61. RECONNECT_MAX_ATTEMPTS = None
  62. log = logging.getLogger(__name__)
  63. class RestartStream(Exception):
  64. """
  65. Exception to restart stream processing, including
  66. resending the stream header.
  67. """
  68. class XMLStream(object):
  69. """
  70. An XML stream connection manager and event dispatcher.
  71. The XMLStream class abstracts away the issues of establishing a
  72. connection with a server and sending and receiving XML "stanzas".
  73. A stanza is a complete XML element that is a direct child of a root
  74. document element. Two streams are used, one for each communication
  75. direction, over the same socket. Once the connection is closed, both
  76. streams should be complete and valid XML documents.
  77. Three types of events are provided to manage the stream:
  78. :Stream: Triggered based on received stanzas, similar in concept
  79. to events in a SAX XML parser.
  80. :Custom: Triggered manually.
  81. :Scheduled: Triggered based on time delays.
  82. Typically, stanzas are first processed by a stream event handler which
  83. will then trigger custom events to continue further processing,
  84. especially since custom event handlers may run in individual threads.
  85. :param socket: Use an existing socket for the stream. Defaults to
  86. ``None`` to generate a new socket.
  87. :param string host: The name of the target server.
  88. :param int port: The port to use for the connection. Defaults to 0.
  89. """
  90. def __init__(self, socket=None, host='', port=0, certfile=None,
  91. keyfile=None, ca_certs=None, **kwargs):
  92. #: Most XMPP servers support TLSv1, but OpenFire in particular
  93. #: does not work well with it. For OpenFire, set
  94. #: :attr:`ssl_version` to use ``SSLv23``::
  95. #:
  96. #: import ssl
  97. #: xmpp.ssl_version = ssl.PROTOCOL_SSLv23
  98. self.ssl_version = ssl.PROTOCOL_TLSv1
  99. #: The list of accepted ciphers, in OpenSSL Format.
  100. #: It might be useful to override it for improved security
  101. #: over the python defaults.
  102. self.ciphers = None
  103. #: Path to a file containing certificates for verifying the
  104. #: server SSL certificate. A non-``None`` value will trigger
  105. #: certificate checking.
  106. #:
  107. #: .. note::
  108. #:
  109. #: On Mac OS X, certificates in the system keyring will
  110. #: be consulted, even if they are not in the provided file.
  111. self.ca_certs = ca_certs
  112. #: Path to a file containing a client certificate to use for
  113. #: authenticating via SASL EXTERNAL. If set, there must also
  114. #: be a corresponding `:attr:keyfile` value.
  115. self.certfile = certfile
  116. #: Path to a file containing the private key for the selected
  117. #: client certificate to use for authenticating via SASL EXTERNAL.
  118. self.keyfile = keyfile
  119. self._der_cert = None
  120. #: The time in seconds to wait for events from the event queue,
  121. #: and also the time between checks for the process stop signal.
  122. self.wait_timeout = WAIT_TIMEOUT
  123. #: The time in seconds to wait before timing out waiting
  124. #: for response stanzas.
  125. self.response_timeout = RESPONSE_TIMEOUT
  126. #: The current amount to time to delay attempting to reconnect.
  127. #: This value doubles (with some jitter) with each failed
  128. #: connection attempt up to :attr:`reconnect_max_delay` seconds.
  129. self.reconnect_delay = None
  130. #: Maximum time to delay between connection attempts is one hour.
  131. self.reconnect_max_delay = RECONNECT_MAX_DELAY
  132. #: Maximum number of attempts to connect to the server before
  133. #: quitting and raising a 'connect_failed' event. Setting to
  134. #: ``None`` allows infinite reattempts, while setting it to ``0``
  135. #: will disable reconnection attempts. Defaults to ``None``.
  136. self.reconnect_max_attempts = RECONNECT_MAX_ATTEMPTS
  137. #: The time in seconds to delay between attempts to resend data
  138. #: after an SSL error.
  139. self.ssl_retry_max = SSL_RETRY_MAX
  140. #: The maximum number of times to attempt resending data due to
  141. #: an SSL error.
  142. self.ssl_retry_delay = SSL_RETRY_DELAY
  143. #: The connection state machine tracks if the stream is
  144. #: ``'connected'`` or ``'disconnected'``.
  145. self.state = StateMachine(('disconnected', 'connected'))
  146. self.state._set_state('disconnected')
  147. #: The default port to return when querying DNS records.
  148. self.default_port = int(port)
  149. #: The domain to try when querying DNS records.
  150. self.default_domain = ''
  151. #: The expected name of the server, for validation.
  152. self._expected_server_name = ''
  153. self._service_name = ''
  154. #: The desired, or actual, address of the connected server.
  155. self.address = (host, int(port))
  156. #: A file-like wrapper for the socket for use with the
  157. #: :mod:`~xml.etree.ElementTree` module.
  158. self.filesocket = None
  159. self.set_socket(socket)
  160. if sys.version_info < (3, 0):
  161. self.socket_class = Socket26
  162. else:
  163. self.socket_class = Socket.socket
  164. #: Enable connecting to the server directly over SSL, in
  165. #: particular when the service provides two ports: one for
  166. #: non-SSL traffic and another for SSL traffic.
  167. self.use_ssl = False
  168. #: Enable connecting to the service without using SSL
  169. #: immediately, but allow upgrading the connection later
  170. #: to use SSL.
  171. self.use_tls = False
  172. #: If set to ``True``, attempt to connect through an HTTP
  173. #: proxy based on the settings in :attr:`proxy_config`.
  174. self.use_proxy = False
  175. #: If set to ``True``, attempt to use IPv6.
  176. self.use_ipv6 = True
  177. #: If set to ``True``, allow using the ``dnspython`` DNS library
  178. #: if available. If set to ``False``, the builtin DNS resolver
  179. #: will be used, even if ``dnspython`` is installed.
  180. self.use_dnspython = True
  181. #: Use CDATA for escaping instead of XML entities. Defaults
  182. #: to ``False``.
  183. self.use_cdata = False
  184. #: An optional dictionary of proxy settings. It may provide:
  185. #: :host: The host offering proxy services.
  186. #: :port: The port for the proxy service.
  187. #: :username: Optional username for accessing the proxy.
  188. #: :password: Optional password for accessing the proxy.
  189. self.proxy_config = {}
  190. #: The default namespace of the stream content, not of the
  191. #: stream wrapper itself.
  192. self.default_ns = ''
  193. self.default_lang = None
  194. self.peer_default_lang = None
  195. #: The namespace of the enveloping stream element.
  196. self.stream_ns = ''
  197. #: The default opening tag for the stream element.
  198. self.stream_header = "<stream>"
  199. #: The default closing tag for the stream element.
  200. self.stream_footer = "</stream>"
  201. #: If ``True``, periodically send a whitespace character over the
  202. #: wire to keep the connection alive. Mainly useful for connections
  203. #: traversing NAT.
  204. self.whitespace_keepalive = True
  205. #: The default interval between keepalive signals when
  206. #: :attr:`whitespace_keepalive` is enabled.
  207. self.whitespace_keepalive_interval = 300
  208. #: An :class:`~threading.Event` to signal that the application
  209. #: is stopping, and that all threads should shutdown.
  210. self.stop = threading.Event()
  211. #: An :class:`~threading.Event` to signal receiving a closing
  212. #: stream tag from the server.
  213. self.stream_end_event = threading.Event()
  214. self.stream_end_event.set()
  215. #: An :class:`~threading.Event` to signal the start of a stream
  216. #: session. Until this event fires, the send queue is not used
  217. #: and data is sent immediately over the wire.
  218. self.session_started_event = threading.Event()
  219. #: The default time in seconds to wait for a session to start
  220. #: after connecting before reconnecting and trying again.
  221. self.session_timeout = 45
  222. #: Flag for controlling if the session can be considered ended
  223. #: if the connection is terminated.
  224. self.end_session_on_disconnect = True
  225. #: A queue of stream, custom, and scheduled events to be processed.
  226. self.event_queue = Queue()
  227. #: A queue of string data to be sent over the stream.
  228. self.send_queue = Queue(maxsize=256)
  229. self.send_queue_lock = threading.Lock()
  230. self.send_lock = threading.RLock()
  231. #: A :class:`~sleekxmpp.xmlstream.scheduler.Scheduler` instance for
  232. #: executing callbacks in the future based on time delays.
  233. self.scheduler = Scheduler(self.stop)
  234. self.__failed_send_stanza = None
  235. #: A mapping of XML namespaces to well-known prefixes.
  236. self.namespace_map = {StanzaBase.xml_ns: 'xml'}
  237. self.__thread = {}
  238. self.__root_stanza = []
  239. self.__handlers = []
  240. self.__event_handlers = {}
  241. self.__event_handlers_lock = threading.Lock()
  242. self.__filters = {'in': [], 'out': [], 'out_sync': []}
  243. self.__thread_count = 0
  244. self.__thread_cond = threading.Condition()
  245. self.__active_threads = set()
  246. self._use_daemons = False
  247. self._disconnect_wait_for_threads = True
  248. self._id = 0
  249. self._id_lock = threading.Lock()
  250. #: We use an ID prefix to ensure that all ID values are unique.
  251. self._id_prefix = '%s-' % uuid.uuid4()
  252. #: The :attr:`auto_reconnnect` setting controls whether or not
  253. #: the stream will be restarted in the event of an error.
  254. self.auto_reconnect = True
  255. #: The :attr:`disconnect_wait` setting is the default value
  256. #: for controlling if the system waits for the send queue to
  257. #: empty before ending the stream. This may be overridden by
  258. #: passing ``wait=True`` or ``wait=False`` to :meth:`disconnect`.
  259. #: The default :attr:`disconnect_wait` value is ``False``.
  260. self.disconnect_wait = False
  261. #: A list of DNS results that have not yet been tried.
  262. self.dns_answers = []
  263. #: The service name to check with DNS SRV records. For
  264. #: example, setting this to ``'xmpp-client'`` would query the
  265. #: ``_xmpp-client._tcp`` service.
  266. self.dns_service = None
  267. self.add_event_handler('connected', self._session_timeout_check)
  268. self.add_event_handler('disconnected', self._remove_schedules)
  269. self.add_event_handler('session_start', self._start_keepalive)
  270. self.add_event_handler('session_start', self._cert_expiration)
  271. def use_signals(self, signals=None):
  272. """Register signal handlers for ``SIGHUP`` and ``SIGTERM``.
  273. By using signals, a ``'killed'`` event will be raised when the
  274. application is terminated.
  275. If a signal handler already existed, it will be executed first,
  276. before the ``'killed'`` event is raised.
  277. :param list signals: A list of signal names to be monitored.
  278. Defaults to ``['SIGHUP', 'SIGTERM']``.
  279. """
  280. if signals is None:
  281. signals = ['SIGHUP', 'SIGTERM']
  282. existing_handlers = {}
  283. for sig_name in signals:
  284. if hasattr(signal, sig_name):
  285. sig = getattr(signal, sig_name)
  286. handler = signal.getsignal(sig)
  287. if handler:
  288. existing_handlers[sig] = handler
  289. def handle_kill(signum, frame):
  290. """
  291. Capture kill event and disconnect cleanly after first
  292. spawning the ``'killed'`` event.
  293. """
  294. if signum in existing_handlers and \
  295. existing_handlers[signum] != handle_kill:
  296. existing_handlers[signum](signum, frame)
  297. self.event("killed", direct=True)
  298. self.disconnect()
  299. try:
  300. for sig_name in signals:
  301. if hasattr(signal, sig_name):
  302. sig = getattr(signal, sig_name)
  303. signal.signal(sig, handle_kill)
  304. self.__signals_installed = True
  305. except:
  306. log.debug("Can not set interrupt signal handlers. " + \
  307. "SleekXMPP is not running from a main thread.")
  308. def new_id(self):
  309. """Generate and return a new stream ID in hexadecimal form.
  310. Many stanzas, handlers, or matchers may require unique
  311. ID values. Using this method ensures that all new ID values
  312. are unique in this stream.
  313. """
  314. with self._id_lock:
  315. self._id += 1
  316. return self.get_id()
  317. def get_id(self):
  318. """Return the current unique stream ID in hexadecimal form."""
  319. return "%s%X" % (self._id_prefix, self._id)
  320. def connect(self, host='', port=0, use_ssl=False,
  321. use_tls=True, reattempt=True):
  322. """Create a new socket and connect to the server.
  323. Setting ``reattempt`` to ``True`` will cause connection
  324. attempts to be made with an exponential backoff delay (max of
  325. :attr:`reconnect_max_delay` which defaults to 10 minute) until a
  326. successful connection is established.
  327. :param host: The name of the desired server for the connection.
  328. :param port: Port to connect to on the server.
  329. :param use_ssl: Flag indicating if SSL should be used by connecting
  330. directly to a port using SSL.
  331. :param use_tls: Flag indicating if TLS should be used, allowing for
  332. connecting to a port without using SSL immediately and
  333. later upgrading the connection.
  334. :param reattempt: Flag indicating if the socket should reconnect
  335. after disconnections.
  336. """
  337. self.stop.clear()
  338. if host and port:
  339. self.address = (host, int(port))
  340. try:
  341. Socket.inet_aton(self.address[0])
  342. except (Socket.error, ssl.SSLError):
  343. self.default_domain = self.address[0]
  344. # Respect previous SSL and TLS usage directives.
  345. if use_ssl is not None:
  346. self.use_ssl = use_ssl
  347. if use_tls is not None:
  348. self.use_tls = use_tls
  349. # Repeatedly attempt to connect until a successful connection
  350. # is established.
  351. attempts = self.reconnect_max_attempts
  352. connected = self.state.transition('disconnected', 'connected',
  353. func=self._connect,
  354. args=(reattempt,))
  355. while reattempt and not connected and not self.stop.is_set():
  356. connected = self.state.transition('disconnected', 'connected',
  357. func=self._connect)
  358. if not connected:
  359. if attempts is not None:
  360. attempts -= 1
  361. if attempts <= 0:
  362. self.event('connection_failed', direct=True)
  363. return False
  364. return connected
  365. def _connect(self, reattempt=True):
  366. self.scheduler.remove('Session timeout check')
  367. if self.reconnect_delay is None:
  368. delay = 1.0
  369. self.reconnect_delay = delay
  370. if reattempt:
  371. delay = min(self.reconnect_delay * 2, self.reconnect_max_delay)
  372. delay = random.normalvariate(delay, delay * 0.1)
  373. log.debug('Waiting %s seconds before connecting.', delay)
  374. elapsed = 0
  375. try:
  376. while elapsed < delay and not self.stop.is_set():
  377. time.sleep(0.1)
  378. elapsed += 0.1
  379. except KeyboardInterrupt:
  380. self.set_stop()
  381. return False
  382. except SystemExit:
  383. self.set_stop()
  384. return False
  385. if self.default_domain:
  386. try:
  387. host, address, port = self.pick_dns_answer(self.default_domain,
  388. self.address[1])
  389. self.address = (address, port)
  390. self._service_name = host
  391. except StopIteration:
  392. log.debug("No remaining DNS records to try.")
  393. self.dns_answers = None
  394. if reattempt:
  395. self.reconnect_delay = delay
  396. return False
  397. af = Socket.AF_INET
  398. proto = 'IPv4'
  399. if ':' in self.address[0]:
  400. af = Socket.AF_INET6
  401. proto = 'IPv6'
  402. try:
  403. self.socket = self.socket_class(af, Socket.SOCK_STREAM)
  404. except Socket.error:
  405. log.debug("Could not connect using %s", proto)
  406. return False
  407. self.configure_socket()
  408. if self.use_proxy:
  409. connected = self._connect_proxy()
  410. if not connected:
  411. if reattempt:
  412. self.reconnect_delay = delay
  413. return False
  414. if self.use_ssl:
  415. log.debug("Socket Wrapped for SSL")
  416. if self.ca_certs is None:
  417. cert_policy = ssl.CERT_NONE
  418. else:
  419. cert_policy = ssl.CERT_REQUIRED
  420. ssl_args = safedict({
  421. 'certfile': self.certfile,
  422. 'keyfile': self.keyfile,
  423. 'ca_certs': self.ca_certs,
  424. 'cert_reqs': cert_policy,
  425. 'do_handshake_on_connect': False,
  426. "ssl_version": self.ssl_version
  427. })
  428. if sys.version_info >= (2, 7):
  429. ssl_args['ciphers'] = self.ciphers
  430. ssl_socket = ssl.wrap_socket(self.socket, **ssl_args)
  431. if hasattr(self.socket, 'socket'):
  432. # We are using a testing socket, so preserve the top
  433. # layer of wrapping.
  434. self.socket.socket = ssl_socket
  435. else:
  436. self.socket = ssl_socket
  437. try:
  438. if not self.use_proxy:
  439. domain = self.address[0]
  440. if ':' in domain:
  441. domain = '[%s]' % domain
  442. log.debug("Connecting to %s:%s", domain, self.address[1])
  443. self.socket.connect(self.address)
  444. if self.use_ssl:
  445. try:
  446. self.socket.do_handshake()
  447. except (Socket.error, ssl.SSLError):
  448. log.error('CERT: Invalid certificate trust chain.')
  449. if not self.event_handled('ssl_invalid_chain'):
  450. self.disconnect(self.auto_reconnect,
  451. send_close=False)
  452. else:
  453. self.event('ssl_invalid_chain', direct=True)
  454. return False
  455. self._der_cert = self.socket.getpeercert(binary_form=True)
  456. pem_cert = ssl.DER_cert_to_PEM_cert(self._der_cert)
  457. log.debug('CERT: %s', pem_cert)
  458. self.event('ssl_cert', pem_cert, direct=True)
  459. try:
  460. cert.verify(self._expected_server_name, self._der_cert)
  461. except cert.CertificateError as err:
  462. if not self.event_handled('ssl_invalid_cert'):
  463. log.error(err)
  464. self.disconnect(send_close=False)
  465. else:
  466. self.event('ssl_invalid_cert',
  467. pem_cert,
  468. direct=True)
  469. self.set_socket(self.socket, ignore=True)
  470. #this event is where you should set your application state
  471. self.event('connected', direct=True)
  472. return True
  473. except (Socket.error, ssl.SSLError) as serr:
  474. error_msg = "Could not connect to %s:%s. Socket Error #%s: %s"
  475. self.event('socket_error', serr, direct=True)
  476. domain = self.address[0]
  477. if ':' in domain:
  478. domain = '[%s]' % domain
  479. log.error(error_msg, domain, self.address[1],
  480. serr.errno, serr.strerror)
  481. return False
  482. def _connect_proxy(self):
  483. """Attempt to connect using an HTTP Proxy."""
  484. # Extract the proxy address, and optional credentials
  485. address = (self.proxy_config['host'], int(self.proxy_config['port']))
  486. cred = None
  487. if self.proxy_config['username']:
  488. username = self.proxy_config['username']
  489. password = self.proxy_config['password']
  490. cred = '%s:%s' % (username, password)
  491. if sys.version_info < (3, 0):
  492. cred = bytes(cred)
  493. else:
  494. cred = bytes(cred, 'utf-8')
  495. cred = base64.b64encode(cred).decode('utf-8')
  496. # Build the HTTP headers for connecting to the XMPP server
  497. headers = ['CONNECT %s:%s HTTP/1.0' % self.address,
  498. 'Host: %s:%s' % self.address,
  499. 'Proxy-Connection: Keep-Alive',
  500. 'Pragma: no-cache',
  501. 'User-Agent: SleekXMPP/%s' % sleekxmpp.__version__]
  502. if cred:
  503. headers.append('Proxy-Authorization: Basic %s' % cred)
  504. headers = '\r\n'.join(headers) + '\r\n\r\n'
  505. try:
  506. log.debug("Connecting to proxy: %s:%s", *address)
  507. self.socket.connect(address)
  508. self.send_raw(headers, now=True)
  509. resp = ''
  510. while '\r\n\r\n' not in resp and not self.stop.is_set():
  511. resp += self.socket.recv(1024).decode('utf-8')
  512. log.debug('RECV: %s', resp)
  513. lines = resp.split('\r\n')
  514. if '200' not in lines[0]:
  515. self.event('proxy_error', resp)
  516. self.event('connection_failed', direct=True)
  517. log.error('Proxy Error: %s', lines[0])
  518. return False
  519. # Proxy connection established, continue connecting
  520. # with the XMPP server.
  521. return True
  522. except (Socket.error, ssl.SSLError) as serr:
  523. error_msg = "Could not connect to %s:%s. Socket Error #%s: %s"
  524. self.event('socket_error', serr, direct=True)
  525. log.error(error_msg, self.address[0], self.address[1],
  526. serr.errno, serr.strerror)
  527. return False
  528. def _session_timeout_check(self, event=None):
  529. """
  530. Add check to ensure that a session is established within
  531. a reasonable amount of time.
  532. """
  533. def _handle_session_timeout():
  534. if not self.session_started_event.is_set():
  535. log.debug("Session start has taken more " + \
  536. "than %d seconds", self.session_timeout)
  537. self.disconnect(reconnect=self.auto_reconnect)
  538. self.schedule("Session timeout check",
  539. self.session_timeout,
  540. _handle_session_timeout)
  541. def disconnect(self, reconnect=False, wait=None, send_close=True):
  542. """Terminate processing and close the XML streams.
  543. Optionally, the connection may be reconnected and
  544. resume processing afterwards.
  545. If the disconnect should take place after all items
  546. in the send queue have been sent, use ``wait=True``.
  547. .. warning::
  548. If you are constantly adding items to the queue
  549. such that it is never empty, then the disconnect will
  550. not occur and the call will continue to block.
  551. :param reconnect: Flag indicating if the connection
  552. and processing should be restarted.
  553. Defaults to ``False``.
  554. :param wait: Flag indicating if the send queue should
  555. be emptied before disconnecting, overriding
  556. :attr:`disconnect_wait`.
  557. :param send_close: Flag indicating if the stream footer
  558. should be sent before terminating the
  559. connection. Setting this to ``False``
  560. prevents error loops when trying to
  561. disconnect after a socket error.
  562. """
  563. self.state.transition('connected', 'disconnected',
  564. wait=2.0,
  565. func=self._disconnect,
  566. args=(reconnect, wait, send_close))
  567. def _disconnect(self, reconnect=False, wait=None, send_close=True):
  568. if not reconnect:
  569. self.auto_reconnect = False
  570. if self.end_session_on_disconnect or send_close:
  571. self.event('session_end', direct=True)
  572. # Wait for the send queue to empty.
  573. if wait is not None:
  574. if wait:
  575. self.send_queue.join()
  576. elif self.disconnect_wait:
  577. self.send_queue.join()
  578. # Clearing this event will pause the send loop.
  579. self.session_started_event.clear()
  580. self.__failed_send_stanza = None
  581. # Send the end of stream marker.
  582. if send_close:
  583. self.send_raw(self.stream_footer, now=True)
  584. # Wait for confirmation that the stream was
  585. # closed in the other direction. If we didn't
  586. # send a stream footer we don't need to wait
  587. # since the server won't know to respond.
  588. if send_close:
  589. log.info('Waiting for %s from server', self.stream_footer)
  590. self.stream_end_event.wait(4)
  591. else:
  592. self.stream_end_event.set()
  593. if not self.auto_reconnect:
  594. self.set_stop()
  595. if self._disconnect_wait_for_threads:
  596. self._wait_for_threads()
  597. try:
  598. self.socket.shutdown(Socket.SHUT_RDWR)
  599. self.socket.close()
  600. self.filesocket.close()
  601. except (Socket.error, ssl.SSLError) as serr:
  602. self.event('socket_error', serr, direct=True)
  603. finally:
  604. #clear your application state
  605. self.event('disconnected', direct=True)
  606. return True
  607. def abort(self):
  608. self.session_started_event.clear()
  609. self.set_stop()
  610. if self._disconnect_wait_for_threads:
  611. self._wait_for_threads()
  612. try:
  613. self.socket.shutdown(Socket.SHUT_RDWR)
  614. self.socket.close()
  615. self.filesocket.close()
  616. except Socket.error:
  617. pass
  618. self.state.transition_any(['connected', 'disconnected'], 'disconnected', func=lambda: True)
  619. self.event("killed", direct=True)
  620. def reconnect(self, reattempt=True, wait=False, send_close=True):
  621. """Reset the stream's state and reconnect to the server."""
  622. log.debug("reconnecting...")
  623. if self.state.ensure('connected'):
  624. self.state.transition('connected', 'disconnected',
  625. wait=2.0,
  626. func=self._disconnect,
  627. args=(True, wait, send_close))
  628. attempts = self.reconnect_max_attempts
  629. log.debug("connecting...")
  630. connected = self.state.transition('disconnected', 'connected',
  631. wait=2.0,
  632. func=self._connect,
  633. args=(reattempt,))
  634. while reattempt and not connected and not self.stop.is_set():
  635. connected = self.state.transition('disconnected', 'connected',
  636. wait=2.0, func=self._connect)
  637. connected = connected or self.state.ensure('connected')
  638. if not connected:
  639. if attempts is not None:
  640. attempts -= 1
  641. if attempts <= 0:
  642. self.event('connection_failed', direct=True)
  643. return False
  644. return connected
  645. def set_socket(self, socket, ignore=False):
  646. """Set the socket to use for the stream.
  647. The filesocket will be recreated as well.
  648. :param socket: The new socket object to use.
  649. :param bool ignore: If ``True``, don't set the connection
  650. state to ``'connected'``.
  651. """
  652. self.socket = socket
  653. if socket is not None:
  654. # ElementTree.iterparse requires a file.
  655. # 0 buffer files have to be binary.
  656. # Use the correct fileobject type based on the Python
  657. # version to work around a broken implementation in
  658. # Python 2.x.
  659. if sys.version_info < (3, 0):
  660. self.filesocket = FileSocket(self.socket)
  661. else:
  662. self.filesocket = self.socket.makefile('rb', 0)
  663. if not ignore:
  664. self.state._set_state('connected')
  665. def configure_socket(self):
  666. """Set timeout and other options for self.socket.
  667. Meant to be overridden.
  668. """
  669. self.socket.settimeout(None)
  670. def configure_dns(self, resolver, domain=None, port=None):
  671. """
  672. Configure and set options for a :class:`~dns.resolver.Resolver`
  673. instance, and other DNS related tasks. For example, you
  674. can also check :meth:`~socket.socket.getaddrinfo` to see
  675. if you need to call out to ``libresolv.so.2`` to
  676. run ``res_init()``.
  677. Meant to be overridden.
  678. :param resolver: A :class:`~dns.resolver.Resolver` instance
  679. or ``None`` if ``dnspython`` is not installed.
  680. :param domain: The initial domain under consideration.
  681. :param port: The initial port under consideration.
  682. """
  683. pass
  684. def start_tls(self):
  685. """Perform handshakes for TLS.
  686. If the handshake is successful, the XML stream will need
  687. to be restarted.
  688. """
  689. log.info("Negotiating TLS")
  690. log.info(
  691. "Using SSL version: %s",
  692. ssl.get_protocol_name(self.ssl_version).replace('PROTOCOL_', '', 1)
  693. )
  694. if self.ca_certs is None:
  695. cert_policy = ssl.CERT_NONE
  696. else:
  697. cert_policy = ssl.CERT_REQUIRED
  698. ssl_args = safedict({
  699. 'certfile': self.certfile,
  700. 'keyfile': self.keyfile,
  701. 'ca_certs': self.ca_certs,
  702. 'cert_reqs': cert_policy,
  703. 'do_handshake_on_connect': False,
  704. "ssl_version": self.ssl_version
  705. })
  706. if sys.version_info >= (2, 7):
  707. ssl_args['ciphers'] = self.ciphers
  708. ssl_socket = ssl.wrap_socket(self.socket, **ssl_args)
  709. if hasattr(self.socket, 'socket'):
  710. # We are using a testing socket, so preserve the top
  711. # layer of wrapping.
  712. self.socket.socket = ssl_socket
  713. else:
  714. self.socket = ssl_socket
  715. try:
  716. self.socket.do_handshake()
  717. except (Socket.error, ssl.SSLError):
  718. log.error('CERT: Invalid certificate trust chain.')
  719. if not self.event_handled('ssl_invalid_chain'):
  720. self.disconnect(self.auto_reconnect, send_close=False)
  721. else:
  722. self._der_cert = self.socket.getpeercert(binary_form=True)
  723. self.event('ssl_invalid_chain', direct=True)
  724. return False
  725. self._der_cert = self.socket.getpeercert(binary_form=True)
  726. pem_cert = ssl.DER_cert_to_PEM_cert(self._der_cert)
  727. log.debug('CERT: %s', pem_cert)
  728. self.event('ssl_cert', pem_cert, direct=True)
  729. try:
  730. cert.verify(self._expected_server_name, self._der_cert)
  731. except cert.CertificateError as err:
  732. if not self.event_handled('ssl_invalid_cert'):
  733. log.error(err)
  734. self.disconnect(self.auto_reconnect, send_close=False)
  735. else:
  736. self.event('ssl_invalid_cert', pem_cert, direct=True)
  737. self.set_socket(self.socket)
  738. return True
  739. def _cert_expiration(self, event):
  740. """Schedule an event for when the TLS certificate expires."""
  741. if not self.use_tls and not self.use_ssl:
  742. return
  743. if not self._der_cert:
  744. log.warn("TLS or SSL was enabled, but no certificate was found.")
  745. return
  746. def restart():
  747. if not self.event_handled('ssl_expired_cert'):
  748. log.warn("The server certificate has expired. Restarting.")
  749. self.reconnect()
  750. else:
  751. pem_cert = ssl.DER_cert_to_PEM_cert(self._der_cert)
  752. self.event('ssl_expired_cert', pem_cert)
  753. cert_ttl = cert.get_ttl(self._der_cert)
  754. if cert_ttl is None:
  755. return
  756. if cert_ttl.days < 0:
  757. log.warn('CERT: Certificate has expired.')
  758. restart()
  759. try:
  760. total_seconds = cert_ttl.total_seconds()
  761. except AttributeError:
  762. # for Python < 2.7
  763. total_seconds = (cert_ttl.microseconds + (cert_ttl.seconds + cert_ttl.days * 24 * 3600) * 10**6) / 10**6
  764. log.info('CERT: Time until certificate expiration: %s' % cert_ttl)
  765. self.schedule('Certificate Expiration',
  766. total_seconds,
  767. restart)
  768. def _start_keepalive(self, event):
  769. """Begin sending whitespace periodically to keep the connection alive.
  770. May be disabled by setting::
  771. self.whitespace_keepalive = False
  772. The keepalive interval can be set using::
  773. self.whitespace_keepalive_interval = 300
  774. """
  775. if self.whitespace_keepalive:
  776. self.schedule('Whitespace Keepalive',
  777. self.whitespace_keepalive_interval,
  778. self.send_raw,
  779. args=(' ',),
  780. kwargs={'now': True},
  781. repeat=True)
  782. def _remove_schedules(self, event):
  783. """Remove whitespace keepalive and certificate expiration schedules."""
  784. self.scheduler.remove('Whitespace Keepalive')
  785. self.scheduler.remove('Certificate Expiration')
  786. def start_stream_handler(self, xml):
  787. """Perform any initialization actions, such as handshakes,
  788. once the stream header has been sent.
  789. Meant to be overridden.
  790. """
  791. pass
  792. def register_stanza(self, stanza_class):
  793. """Add a stanza object class as a known root stanza.
  794. A root stanza is one that appears as a direct child of the stream's
  795. root element.
  796. Stanzas that appear as substanzas of a root stanza do not need to
  797. be registered here. That is done using register_stanza_plugin() from
  798. sleekxmpp.xmlstream.stanzabase.
  799. Stanzas that are not registered will not be converted into
  800. stanza objects, but may still be processed using handlers and
  801. matchers.
  802. :param stanza_class: The top-level stanza object's class.
  803. """
  804. self.__root_stanza.append(stanza_class)
  805. def remove_stanza(self, stanza_class):
  806. """Remove a stanza from being a known root stanza.
  807. A root stanza is one that appears as a direct child of the stream's
  808. root element.
  809. Stanzas that are not registered will not be converted into
  810. stanza objects, but may still be processed using handlers and
  811. matchers.
  812. """
  813. self.__root_stanza.remove(stanza_class)
  814. def add_filter(self, mode, handler, order=None):
  815. """Add a filter for incoming or outgoing stanzas.
  816. These filters are applied before incoming stanzas are
  817. passed to any handlers, and before outgoing stanzas
  818. are put in the send queue.
  819. Each filter must accept a single stanza, and return
  820. either a stanza or ``None``. If the filter returns
  821. ``None``, then the stanza will be dropped from being
  822. processed for events or from being sent.
  823. :param mode: One of ``'in'`` or ``'out'``.
  824. :param handler: The filter function.
  825. :param int order: The position to insert the filter in
  826. the list of active filters.
  827. """
  828. if order:
  829. self.__filters[mode].insert(order, handler)
  830. else:
  831. self.__filters[mode].append(handler)
  832. def del_filter(self, mode, handler):
  833. """Remove an incoming or outgoing filter."""
  834. self.__filters[mode].remove(handler)
  835. def add_handler(self, mask, pointer, name=None, disposable=False,
  836. threaded=False, filter=False, instream=False):
  837. """A shortcut method for registering a handler using XML masks.
  838. The use of :meth:`register_handler()` is preferred.
  839. :param mask: An XML snippet matching the structure of the
  840. stanzas that will be passed to this handler.
  841. :param pointer: The handler function itself.
  842. :parm name: A unique name for the handler. A name will
  843. be generated if one is not provided.
  844. :param disposable: Indicates if the handler should be discarded
  845. after one use.
  846. :param threaded: **DEPRECATED**.
  847. Remains for backwards compatibility.
  848. :param filter: **DEPRECATED**.
  849. Remains for backwards compatibility.
  850. :param instream: Indicates if the handler should execute during
  851. stream processing and not during normal event
  852. processing.
  853. """
  854. # To prevent circular dependencies, we must load the matcher
  855. # and handler classes here.
  856. if name is None:
  857. name = 'add_handler_%s' % self.new_id()
  858. self.register_handler(
  859. XMLCallback(name,
  860. MatchXMLMask(mask, self.default_ns),
  861. pointer,
  862. once=disposable,
  863. instream=instream))
  864. def register_handler(self, handler, before=None, after=None):
  865. """Add a stream event handler that will be executed when a matching
  866. stanza is received.
  867. :param handler:
  868. The :class:`~sleekxmpp.xmlstream.handler.base.BaseHandler`
  869. derived object to execute.
  870. """
  871. if handler.stream is None:
  872. self.__handlers.append(handler)
  873. handler.stream = weakref.ref(self)
  874. def remove_handler(self, name):
  875. """Remove any stream event handlers with the given name.
  876. :param name: The name of the handler.
  877. """
  878. idx = 0
  879. for handler in self.__handlers:
  880. if handler.name == name:
  881. self.__handlers.pop(idx)
  882. return True
  883. idx += 1
  884. return False
  885. def get_dns_records(self, domain, port=None):
  886. """Get the DNS records for a domain.
  887. :param domain: The domain in question.
  888. :param port: If the results don't include a port, use this one.
  889. """
  890. if port is None:
  891. port = self.default_port
  892. resolver = default_resolver()
  893. self.configure_dns(resolver, domain=domain, port=port)
  894. return resolve(domain, port, service=self.dns_service,
  895. resolver=resolver,
  896. use_ipv6=self.use_ipv6,
  897. use_dnspython=self.use_dnspython)
  898. def pick_dns_answer(self, domain, port=None):
  899. """Pick a server and port from DNS answers.
  900. Gets DNS answers if none available.
  901. Removes used answer from available answers.
  902. :param domain: The domain in question.
  903. :param port: If the results don't include a port, use this one.
  904. """
  905. if not self.dns_answers:
  906. self.dns_answers = self.get_dns_records(domain, port)
  907. if sys.version_info < (3, 0):
  908. return self.dns_answers.next()
  909. else:
  910. return next(self.dns_answers)
  911. def add_event_handler(self, name, pointer,
  912. threaded=False, disposable=False):
  913. """Add a custom event handler that will be executed whenever
  914. its event is manually triggered.
  915. :param name: The name of the event that will trigger
  916. this handler.
  917. :param pointer: The function to execute.
  918. :param threaded: If set to ``True``, the handler will execute
  919. in its own thread. Defaults to ``False``.
  920. :param disposable: If set to ``True``, the handler will be
  921. discarded after one use. Defaults to ``False``.
  922. """
  923. if not name in self.__event_handlers:
  924. self.__event_handlers[name] = []
  925. self.__event_handlers[name].append((pointer, threaded, disposable))
  926. def del_event_handler(self, name, pointer):
  927. """Remove a function as a handler for an event.
  928. :param name: The name of the event.
  929. :param pointer: The function to remove as a handler.
  930. """
  931. if not name in self.__event_handlers:
  932. return
  933. # Need to keep handlers that do not use
  934. # the given function pointer
  935. def filter_pointers(handler):
  936. return handler[0] != pointer
  937. self.__event_handlers[name] = list(filter(
  938. filter_pointers,
  939. self.__event_handlers[name]))
  940. def event_handled(self, name):
  941. """Returns the number of registered handlers for an event.
  942. :param name: The name of the event to check.
  943. """
  944. return len(self.__event_handlers.get(name, []))
  945. def event(self, name, data=None, direct=False):
  946. """Manually trigger a custom event.
  947. :param name: The name of the event to trigger.
  948. :param data: Data that will be passed to each event handler.
  949. Defaults to an empty dictionary, but is usually
  950. a stanza object.
  951. :param direct: Runs the event directly if True, skipping the
  952. event queue. All event handlers will run in the
  953. same thread.
  954. """
  955. if not data:
  956. data = {}
  957. log.debug("Event triggered: " + name)
  958. handlers = self.__event_handlers.get(name, [])
  959. for handler in handlers:
  960. #TODO: Data should not be copied, but should be read only,
  961. # but this might break current code so it's left for future.
  962. out_data = copy.copy(data) if len(handlers) > 1 else data
  963. old_exception = getattr(data, 'exception', None)
  964. if direct:
  965. try:
  966. handler[0](out_data)
  967. except Exception as e:
  968. error_msg = 'Error processing event handler: %s'
  969. log.exception(error_msg, str(handler[0]))
  970. if old_exception:
  971. old_exception(e)
  972. else:
  973. self.exception(e)
  974. else:
  975. self.event_queue.put(('event', handler, out_data))
  976. if handler[2]:
  977. # If the handler is disposable, we will go ahead and
  978. # remove it now instead of waiting for it to be
  979. # processed in the queue.
  980. with self.__event_handlers_lock:
  981. try:
  982. h_index = self.__event_handlers[name].index(handler)
  983. self.__event_handlers[name].pop(h_index)
  984. except:
  985. pass
  986. def schedule(self, name, seconds, callback, args=None,
  987. kwargs=None, repeat=False):
  988. """Schedule a callback function to execute after a given delay.
  989. :param name: A unique name for the scheduled callback.
  990. :param seconds: The time in seconds to wait before executing.
  991. :param callback: A pointer to the function to execute.
  992. :param args: A tuple of arguments to pass to the function.
  993. :param kwargs: A dictionary of keyword arguments to pass to
  994. the function.
  995. :param repeat: Flag indicating if the scheduled event should
  996. be reset and repeat after executing.
  997. """
  998. self.scheduler.add(name, seconds, callback, args, kwargs,
  999. repeat, qpointer=self.event_queue)
  1000. def incoming_filter(self, xml):
  1001. """Filter incoming XML objects before they are processed.
  1002. Possible uses include remapping namespaces, or correcting elements
  1003. from sources with incorrect behavior.
  1004. Meant to be overridden.
  1005. """
  1006. return xml
  1007. def send(self, data, mask=None, timeout=None, now=False, use_filters=True):
  1008. """A wrapper for :meth:`send_raw()` for sending stanza objects.
  1009. May optionally block until an expected response is received.
  1010. :param data: The :class:`~sleekxmpp.xmlstream.stanzabase.ElementBase`
  1011. stanza to send on the stream.
  1012. :param mask: **DEPRECATED**
  1013. An XML string snippet matching the structure
  1014. of the expected response. Execution will block
  1015. in this thread until the response is received
  1016. or a timeout occurs.
  1017. :param int timeout: Time in seconds to wait for a response before
  1018. continuing. Defaults to :attr:`response_timeout`.
  1019. :param bool now: Indicates if the send queue should be skipped,
  1020. sending the stanza immediately. Useful mainly
  1021. for stream initialization stanzas.
  1022. Defaults to ``False``.
  1023. :param bool use_filters: Indicates if outgoing filters should be
  1024. applied to the given stanza data. Disabling
  1025. filters is useful when resending stanzas.
  1026. Defaults to ``True``.
  1027. """
  1028. if timeout is None:
  1029. timeout = self.response_timeout
  1030. if hasattr(mask, 'xml'):
  1031. mask = mask.xml
  1032. if isinstance(data, ElementBase):
  1033. if use_filters:
  1034. for filter in self.__filters['out']:
  1035. data = filter(data)
  1036. if data is None:
  1037. return
  1038. if mask is not None:
  1039. log.warning("Use of send mask waiters is deprecated.")
  1040. wait_for = Waiter("SendWait_%s" % self.new_id(),
  1041. MatchXMLMask(mask))
  1042. self.register_handler(wait_for)
  1043. if isinstance(data, ElementBase):
  1044. with self.send_queue_lock:
  1045. if use_filters:
  1046. for filter in self.__filters['out_sync']:
  1047. data = filter(data)
  1048. if data is None:
  1049. return
  1050. str_data = tostring(data.xml, xmlns=self.default_ns,
  1051. stream=self,
  1052. top_level=True)
  1053. self.send_raw(str_data, now)
  1054. else:
  1055. self.send_raw(data, now)
  1056. if mask is not None:
  1057. return wait_for.wait(timeout)
  1058. def send_xml(self, data, mask=None, timeout=None, now=False):
  1059. """Send an XML object on the stream, and optionally wait
  1060. for a response.
  1061. :param data: The :class:`~xml.etree.ElementTree.Element` XML object
  1062. to send on the stream.
  1063. :param mask: **DEPRECATED**
  1064. An XML string snippet matching the structure
  1065. of the expected response. Execution will block
  1066. in this thread until the response is received
  1067. or a timeout occurs.
  1068. :param int timeout: Time in seconds to wait for a response before
  1069. continuing. Defaults to :attr:`response_timeout`.
  1070. :param bool now: Indicates if the send queue should be skipped,
  1071. sending the stanza immediately. Useful mainly
  1072. for stream initialization stanzas.
  1073. Defaults to ``False``.
  1074. """
  1075. if timeout is None:
  1076. timeout = self.response_timeout
  1077. return self.send(tostring(data), mask, timeout, now)
  1078. def send_raw(self, data, now=False, reconnect=None):
  1079. """Send raw data across the stream.
  1080. :param string data: Any string value.
  1081. :param bool reconnect: Indicates if the stream should be
  1082. restarted if there is an error sending
  1083. the stanza. Used mainly for testing.
  1084. Defaults to :attr:`auto_reconnect`.
  1085. """
  1086. if now:
  1087. log.debug("SEND (IMMED): %s", data)
  1088. try:
  1089. data = data.encode('utf-8')
  1090. total = len(data)
  1091. sent = 0
  1092. count = 0
  1093. tries = 0
  1094. with self.send_lock:
  1095. while sent < total and not self.stop.is_set():
  1096. try:
  1097. sent += self.socket.send(data[sent:])
  1098. count += 1
  1099. except ssl.SSLError as serr:
  1100. if tries >= self.ssl_retry_max:
  1101. log.debug('SSL error: max retries reached')
  1102. self.exception(serr)
  1103. log.warning("Failed to send %s", data)
  1104. if reconnect is None:
  1105. reconnect = self.auto_reconnect
  1106. if not self.stop.is_set():
  1107. self.disconnect(reconnect,
  1108. send_close=False)
  1109. log.warning('SSL write error: retrying')
  1110. if not self.stop.is_set():
  1111. time.sleep(self.ssl_retry_delay)
  1112. tries += 1
  1113. except Socket.error as serr:
  1114. if serr.errno != errno.EINTR:
  1115. raise
  1116. if count > 1:
  1117. log.debug('SENT: %d chunks', count)
  1118. except (Socket.error, ssl.SSLError) as serr:
  1119. self.event('socket_error', serr, direct=True)
  1120. log.warning("Failed to send %s", data)
  1121. if reconnect is None:
  1122. reconnect = self.auto_reconnect
  1123. if not self.stop.is_set():
  1124. self.disconnect(reconnect, send_close=False)
  1125. else:
  1126. self.send_queue.put(data)
  1127. return True
  1128. def _start_thread(self, name, target, track=True):
  1129. self.__thread[name] = threading.Thread(name=name, target=target)
  1130. self.__thread[name].daemon = self._use_daemons
  1131. self.__thread[name].start()
  1132. if track:
  1133. self.__active_threads.add(name)
  1134. with self.__thread_cond:
  1135. self.__thread_count += 1
  1136. def _end_thread(self, name, early=False):
  1137. with self.__thread_cond:
  1138. curr_thread = threading.current_thread().name
  1139. if curr_thread in self.__active_threads:
  1140. self.__thread_count -= 1
  1141. self.__active_threads.remove(curr_thread)
  1142. if early:
  1143. log.debug('Threading deadlock prevention!')
  1144. log.debug(("Marked %s thread as ended due to " + \
  1145. "disconnect() call. %s threads remain.") % (
  1146. name, self.__thread_count))
  1147. else:
  1148. log.debug("Stopped %s thread. %s threads remain." % (
  1149. name, self.__thread_count))
  1150. else:
  1151. log.debug(("Finished exiting %s thread after early " + \
  1152. "termination from disconnect() call. " + \
  1153. "%s threads remain.") % (
  1154. name, self.__thread_count))
  1155. if self.__thread_count == 0:
  1156. self.__thread_cond.notify()
  1157. def set_stop(self):
  1158. self.stop.set()
  1159. # Unlock queues
  1160. self.event_queue.put(None)
  1161. self.send_queue.put(None)
  1162. def _wait_for_threads(self):
  1163. with self.__thread_cond:
  1164. if self.__thread_count != 0:
  1165. log.debug("Waiting for %s threads to exit." %
  1166. self.__thread_count)
  1167. name = threading.current_thread().name
  1168. if name in self.__thread:
  1169. self._end_thread(name, early=True)
  1170. self.__thread_cond.wait(4)
  1171. if self.__thread_count != 0:
  1172. log.error("Hanged threads: %s" % threading.enumerate())
  1173. log.error("This may be due to calling disconnect() " + \
  1174. "from a non-threaded event handler. Be " + \
  1175. "sure that event handlers that call " + \
  1176. "disconnect() are registered using: " + \
  1177. "add_event_handler(..., threaded=True)")
  1178. def process(self, **kwargs):
  1179. """Initialize the XML streams and begin processing events.
  1180. The number of threads used for processing stream events is determined
  1181. by :data:`HANDLER_THREADS`.
  1182. :param bool block: If ``False``, then event dispatcher will run
  1183. in a separate thread, allowing for the stream to be
  1184. used in the background for another application.
  1185. Otherwise, ``process(block=True)`` blocks the current
  1186. thread. Defaults to ``False``.
  1187. :param bool threaded: **DEPRECATED**
  1188. If ``True``, then event dispatcher will run
  1189. in a separate thread, allowing for the stream to be
  1190. used in the background for another application.
  1191. Defaults to ``True``. This does **not** mean that no
  1192. threads are used at all if ``threaded=False``.
  1193. Regardless of these threading options, these threads will
  1194. always exist:
  1195. - The event queue processor
  1196. - The send queue processor
  1197. - The scheduler
  1198. """
  1199. if 'threaded' in kwargs and 'block' in kwargs:
  1200. raise ValueError("process() called with both " + \
  1201. "block and threaded arguments")
  1202. elif 'block' in kwargs:
  1203. threaded = not(kwargs.get('block', False))
  1204. else:
  1205. threaded = kwargs.get('threaded', True)
  1206. for t in range(0, HANDLER_THREADS):
  1207. log.debug("Starting HANDLER THREAD")
  1208. self._start_thread('event_thread_%s' % t, self._event_runner)
  1209. self._start_thread('send_thread', self._send_thread)
  1210. self._start_thread('scheduler_thread', self._scheduler_thread)
  1211. if threaded:
  1212. # Run the XML stream in the background for another application.
  1213. self._start_thread('read_thread', self._process, track=False)
  1214. else:
  1215. self._process()
  1216. def _process(self):
  1217. """Start processing the XML streams.
  1218. Processing will continue after any recoverable errors
  1219. if reconnections are allowed.
  1220. """
  1221. # The body of this loop will only execute once per connection.
  1222. # Additional passes will be made only if an error occurs and
  1223. # reconnecting is permitted.
  1224. while True:
  1225. shutdown = False
  1226. try:
  1227. # The call to self.__read_xml will block and prevent
  1228. # the body of the loop from running until a disconnect
  1229. # occurs. After any reconnection, the stream header will
  1230. # be resent and processing will resume.
  1231. while not self.stop.is_set():
  1232. # Only process the stream while connected to the server
  1233. if not self.state.ensure('connected', wait=0.1):
  1234. break
  1235. # Ensure the stream header is sent for any
  1236. # new connections.
  1237. if not self.session_started_event.is_set():
  1238. self.send_raw(self.stream_header, now=True)
  1239. if not self.__read_xml():
  1240. # If the server terminated the stream, end processing
  1241. break
  1242. except KeyboardInterrupt:
  1243. log.debug("Keyboard Escape Detected in _process")
  1244. self.event('killed', direct=True)
  1245. shutdown = True
  1246. except SystemExit:
  1247. log.debug("SystemExit in _process")
  1248. shutdown = True
  1249. except (SyntaxError, ExpatError) as e:
  1250. log.error("Error reading from XML stream.")
  1251. self.exception(e)
  1252. except (Socket.error, ssl.SSLError) as serr:
  1253. self.event('socket_error', serr, direct=True)
  1254. log.error('Socket Error #%s: %s', serr.errno, serr.strerror)
  1255. except ValueError as e:
  1256. msg = e.message if hasattr(e, 'message') else e.args[0]
  1257. if 'I/O operation on closed file' in msg:
  1258. log.error('Can not read from closed socket.')
  1259. else:
  1260. self.exception(e)
  1261. except Exception as e:
  1262. if not self.stop.is_set():
  1263. log.error('Connection error.')
  1264. self.exception(e)
  1265. if not shutdown and not self.stop.is_set() \
  1266. and self.auto_reconnect:
  1267. self.reconnect()
  1268. else:
  1269. self.disconnect()
  1270. break
  1271. def __read_xml(self):
  1272. """Parse the incoming XML stream
  1273. Stream events are raised for each received stanza.
  1274. """
  1275. depth = 0
  1276. root = None
  1277. for event, xml in ET.iterparse(self.filesocket, (b'end', b'start')):
  1278. if event == b'start':
  1279. if depth == 0:
  1280. # We have received the start of the root element.
  1281. root = xml
  1282. log.debug('RECV: %s', tostring(root, xmlns=self.default_ns,
  1283. stream=self,
  1284. top_level=True,
  1285. open_only=True))
  1286. # Perform any stream initialization actions, such
  1287. # as handshakes.
  1288. self.stream_end_event.clear()
  1289. self.start_stream_handler(root)
  1290. # We have a successful stream connection, so reset
  1291. # exponential backoff for new reconnect attempts.
  1292. self.reconnect_delay = 1.0
  1293. depth += 1
  1294. if event == b'end':
  1295. depth -= 1
  1296. if depth == 0:
  1297. # The stream's root element has closed,
  1298. # terminating the stream.
  1299. log.debug("End of stream recieved")
  1300. self.stream_end_event.set()
  1301. return False
  1302. elif depth == 1:
  1303. # We only raise events for stanzas that are direct
  1304. # children of the root element.
  1305. try:
  1306. self.__spawn_event(xml)
  1307. except RestartStream:
  1308. return True
  1309. if root is not None:
  1310. # Keep the root element empty of children to
  1311. # save on memory use.
  1312. root.clear()
  1313. log.debug("Ending read XML loop")
  1314. def _build_stanza(self, xml, default_ns=None):
  1315. """Create a stanza object from a given XML object.
  1316. If a specialized stanza type is not found for the XML, then
  1317. a generic :class:`~sleekxmpp.xmlstream.stanzabase.StanzaBase`
  1318. stanza will be returned.
  1319. :param xml: The :class:`~xml.etree.ElementTree.Element` XML object
  1320. to convert into a stanza object.
  1321. :param default_ns: Optional default namespace to use instead of the
  1322. stream's current default namespace.
  1323. """
  1324. if default_ns is None:
  1325. default_ns = self.default_ns
  1326. stanza_type = StanzaBase
  1327. for stanza_class in self.__root_stanza:
  1328. if xml.tag == "{%s}%s" % (default_ns, stanza_class.name) or \
  1329. xml.tag == stanza_class.tag_name():
  1330. stanza_type = stanza_class
  1331. break
  1332. stanza = stanza_type(self, xml)
  1333. if stanza['lang'] is None and self.peer_default_lang:
  1334. stanza['lang'] = self.peer_default_lang
  1335. return stanza
  1336. def __spawn_event(self, xml):
  1337. """
  1338. Analyze incoming XML stanzas and convert them into stanza
  1339. objects if applicable and queue stream events to be processed
  1340. by matching handlers.
  1341. :param xml: The :class:`~sleekxmpp.xmlstream.stanzabase.ElementBase`
  1342. stanza to analyze.
  1343. """
  1344. # Apply any preprocessing filters.
  1345. xml = self.incoming_filter(xml)
  1346. # Convert the raw XML object into a stanza object. If no registered
  1347. # stanza type applies, a generic StanzaBase stanza will be used.
  1348. stanza = self._build_stanza(xml)
  1349. for filter in self.__filters['in']:
  1350. if stanza is not None:
  1351. stanza = filter(stanza)
  1352. if stanza is None:
  1353. return
  1354. log.debug("RECV: %s", stanza)
  1355. # Match the stanza against registered handlers. Handlers marked
  1356. # to run "in stream" will be executed immediately; the rest will
  1357. # be queued.
  1358. unhandled = True
  1359. matched_handlers = [h for h in self.__handlers if h.match(stanza)]
  1360. for handler in matched_handlers:
  1361. if len(matched_handlers) > 1:
  1362. stanza_copy = copy.copy(stanza)
  1363. else:
  1364. stanza_copy = stanza
  1365. handler.prerun(stanza_copy)
  1366. self.event_queue.put(('stanza', handler, stanza_copy))
  1367. try:
  1368. if handler.check_delete():
  1369. self.__handlers.remove(handler)
  1370. except:
  1371. pass # not thread safe
  1372. unhandled = False
  1373. # Some stanzas require responses, such as Iq queries. A default
  1374. # handler will be executed immediately for this case.
  1375. if unhandled:
  1376. stanza.unhandled()
  1377. def _threaded_event_wrapper(self, func, args):
  1378. """Capture exceptions for event handlers that run
  1379. in individual threads.
  1380. :param func: The event handler to execute.
  1381. :param args: Arguments to the event handler.
  1382. """
  1383. # this is always already copied before this is invoked
  1384. orig = args[0]
  1385. try:
  1386. func(*args)
  1387. except Exception as e:
  1388. error_msg = 'Error processing event handler: %s'
  1389. log.exception(error_msg, str(func))
  1390. if hasattr(orig, 'exception'):
  1391. orig.exception(e)
  1392. else:
  1393. self.exception(e)
  1394. def _event_runner(self):
  1395. """Process the event queue and execute handlers.
  1396. The number of event runner threads is controlled by HANDLER_THREADS.
  1397. Stream event handlers will all execute in this thread. Custom event
  1398. handlers may be spawned in individual threads.
  1399. """
  1400. log.debug("Loading event runner")
  1401. try:
  1402. while not self.stop.is_set():
  1403. event = self.event_queue.get()
  1404. if event is None:
  1405. continue
  1406. etype, handler = event[0:2]
  1407. args = event[2:]
  1408. orig = copy.copy(args[0])
  1409. if etype == 'stanza':
  1410. try:
  1411. handler.run(args[0])
  1412. except Exception as e:
  1413. error_msg = 'Error processing stream handler: %s'
  1414. log.exception(error_msg, handler.name)
  1415. orig.exception(e)
  1416. elif etype == 'schedule':
  1417. name = args[2]
  1418. try:
  1419. log.debug('Scheduled event: %s: %s', name, args[0])
  1420. handler(*args[0], **args[1])
  1421. except Exception as e:
  1422. log.exception('Error processing scheduled task')
  1423. self.exception(e)
  1424. elif etype == 'event':
  1425. func, threaded, disposable = handler
  1426. try:
  1427. if threaded:
  1428. x = threading.Thread(
  1429. name="Event_%s" % str(func),
  1430. target=self._threaded_event_wrapper,
  1431. args=(func, args))
  1432. x.daemon = self._use_daemons
  1433. x.start()
  1434. else:
  1435. func(*args)
  1436. except Exception as e:
  1437. error_msg = 'Error processing event handler: %s'
  1438. log.exception(error_msg, str(func))
  1439. if hasattr(orig, 'exception'):
  1440. orig.exception(e)
  1441. else:
  1442. self.exception(e)
  1443. elif etype == 'quit':
  1444. log.debug("Quitting event runner thread")
  1445. break
  1446. except KeyboardInterrupt:
  1447. log.debug("Keyboard Escape Detected in _event_runner")
  1448. self.event('killed', direct=True)
  1449. self.disconnect()
  1450. except SystemExit:
  1451. self.disconnect()
  1452. self.event_queue.put(('quit', None, None))
  1453. self._end_thread('event runner')
  1454. def _send_thread(self):
  1455. """Extract stanzas from the send queue and send them on the stream."""
  1456. try:
  1457. while not self.stop.is_set():
  1458. while not self.stop.is_set() and \
  1459. not self.session_started_event.is_set():
  1460. self.session_started_event.wait(timeout=0.1) # Wait for session start
  1461. if self.__failed_send_stanza is not None:
  1462. data = self.__failed_send_stanza
  1463. self.__failed_send_stanza = None
  1464. else:
  1465. data = self.send_queue.get() # Wait for data to send
  1466. if data is None:
  1467. continue
  1468. log.debug("SEND: %s", data)
  1469. enc_data = data.encode('utf-8')
  1470. total = len(enc_data)
  1471. sent = 0
  1472. count = 0
  1473. tries = 0
  1474. try:
  1475. with self.send_lock:
  1476. while sent < total and not self.stop.is_set() and \
  1477. self.session_started_event.is_set():
  1478. try:
  1479. sent += self.socket.send(enc_data[sent:])
  1480. count += 1
  1481. except ssl.SSLError as serr:
  1482. if tries >= self.ssl_retry_max:
  1483. log.debug('SSL error: max retries reached')
  1484. self.exception(serr)
  1485. log.warning("Failed to send %s", data)
  1486. if not self.stop.is_set():
  1487. self.disconnect(self.auto_reconnect,
  1488. send_close=False)
  1489. log.warning('SSL write error: retrying')
  1490. if not self.stop.is_set():
  1491. time.sleep(self.ssl_retry_delay)
  1492. tries += 1
  1493. except Socket.error as serr:
  1494. if serr.errno != errno.EINTR:
  1495. raise
  1496. if count > 1:
  1497. log.debug('SENT: %d chunks', count)
  1498. self.send_queue.task_done()
  1499. except (Socket.error, ssl.SSLError) as serr:
  1500. self.event('socket_error', serr, direct=True)
  1501. log.warning("Failed to send %s", data)
  1502. if not self.stop.is_set():
  1503. self.__failed_send_stanza = data
  1504. self._end_thread('send')
  1505. self.disconnect(self.auto_reconnect, send_close=False)
  1506. return
  1507. except Exception as ex:
  1508. log.exception('Unexpected error in send thread: %s', ex)
  1509. self.exception(ex)
  1510. if not self.stop.is_set():
  1511. self._end_thread('send')
  1512. self.disconnect(self.auto_reconnect)
  1513. return
  1514. self._end_thread('send')
  1515. def _scheduler_thread(self):
  1516. self.scheduler.process(threaded=False)
  1517. self._end_thread('scheduler')
  1518. def exception(self, exception):
  1519. """Process an unknown exception.
  1520. Meant to be overridden.
  1521. :param exception: An unhandled exception object.
  1522. """
  1523. pass
  1524. # To comply with PEP8, method names now use underscores.
  1525. # Deprecated method names are re-mapped for backwards compatibility.
  1526. XMLStream.startTLS = XMLStream.start_tls
  1527. XMLStream.registerStanza = XMLStream.register_stanza
  1528. XMLStream.removeStanza = XMLStream.remove_stanza
  1529. XMLStream.registerHandler = XMLStream.register_handler
  1530. XMLStream.removeHandler = XMLStream.remove_handler
  1531. XMLStream.setSocket = XMLStream.set_socket
  1532. XMLStream.sendRaw = XMLStream.send_raw
  1533. XMLStream.getId = XMLStream.get_id
  1534. XMLStream.getNewId = XMLStream.new_id
  1535. XMLStream.sendXML = XMLStream.send_xml