xmlstream.py 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170
  1. # -*- test-case-name: twisted.words.test.test_jabberxmlstream -*-
  2. #
  3. # Copyright (c) Twisted Matrix Laboratories.
  4. # See LICENSE for details.
  5. """
  6. XMPP XML Streams
  7. Building blocks for setting up XML Streams, including helping classes for
  8. doing authentication on either client or server side, and working with XML
  9. Stanzas.
  10. @var STREAM_AUTHD_EVENT: Token dispatched by L{Authenticator} when the
  11. stream has been completely initialized
  12. @type STREAM_AUTHD_EVENT: L{str}.
  13. @var INIT_FAILED_EVENT: Token dispatched by L{Authenticator} when the
  14. stream has failed to be initialized
  15. @type INIT_FAILED_EVENT: L{str}.
  16. @var Reset: Token to signal that the XML stream has been reset.
  17. @type Reset: Basic object.
  18. """
  19. from __future__ import absolute_import, division
  20. from binascii import hexlify
  21. from hashlib import sha1
  22. from zope.interface import directlyProvides, implementer
  23. from twisted.internet import defer, protocol
  24. from twisted.internet.error import ConnectionLost
  25. from twisted.python import failure, log, randbytes
  26. from twisted.python.compat import intern, iteritems, itervalues, unicode
  27. from twisted.words.protocols.jabber import error, ijabber, jid
  28. from twisted.words.xish import domish, xmlstream
  29. from twisted.words.xish.xmlstream import STREAM_CONNECTED_EVENT
  30. from twisted.words.xish.xmlstream import STREAM_START_EVENT
  31. from twisted.words.xish.xmlstream import STREAM_END_EVENT
  32. from twisted.words.xish.xmlstream import STREAM_ERROR_EVENT
  33. try:
  34. from twisted.internet import ssl
  35. except ImportError:
  36. ssl = None
  37. if ssl and not ssl.supported:
  38. ssl = None
  39. STREAM_AUTHD_EVENT = intern("//event/stream/authd")
  40. INIT_FAILED_EVENT = intern("//event/xmpp/initfailed")
  41. NS_STREAMS = 'http://etherx.jabber.org/streams'
  42. NS_XMPP_TLS = 'urn:ietf:params:xml:ns:xmpp-tls'
  43. Reset = object()
  44. def hashPassword(sid, password):
  45. """
  46. Create a SHA1-digest string of a session identifier and password.
  47. @param sid: The stream session identifier.
  48. @type sid: C{unicode}.
  49. @param password: The password to be hashed.
  50. @type password: C{unicode}.
  51. """
  52. if not isinstance(sid, unicode):
  53. raise TypeError("The session identifier must be a unicode object")
  54. if not isinstance(password, unicode):
  55. raise TypeError("The password must be a unicode object")
  56. input = u"%s%s" % (sid, password)
  57. return sha1(input.encode('utf-8')).hexdigest()
  58. class Authenticator:
  59. """
  60. Base class for business logic of initializing an XmlStream
  61. Subclass this object to enable an XmlStream to initialize and authenticate
  62. to different types of stream hosts (such as clients, components, etc.).
  63. Rules:
  64. 1. The Authenticator MUST dispatch a L{STREAM_AUTHD_EVENT} when the
  65. stream has been completely initialized.
  66. 2. The Authenticator SHOULD reset all state information when
  67. L{associateWithStream} is called.
  68. 3. The Authenticator SHOULD override L{streamStarted}, and start
  69. initialization there.
  70. @type xmlstream: L{XmlStream}
  71. @ivar xmlstream: The XmlStream that needs authentication
  72. @note: the term authenticator is historical. Authenticators perform
  73. all steps required to prepare the stream for the exchange
  74. of XML stanzas.
  75. """
  76. def __init__(self):
  77. self.xmlstream = None
  78. def connectionMade(self):
  79. """
  80. Called by the XmlStream when the underlying socket connection is
  81. in place.
  82. This allows the Authenticator to send an initial root element, if it's
  83. connecting, or wait for an inbound root from the peer if it's accepting
  84. the connection.
  85. Subclasses can use self.xmlstream.send() to send any initial data to
  86. the peer.
  87. """
  88. def streamStarted(self, rootElement):
  89. """
  90. Called by the XmlStream when the stream has started.
  91. A stream is considered to have started when the start tag of the root
  92. element has been received.
  93. This examines C{rootElement} to see if there is a version attribute.
  94. If absent, C{0.0} is assumed per RFC 3920. Subsequently, the
  95. minimum of the version from the received stream header and the
  96. value stored in L{xmlstream} is taken and put back in L{xmlstream}.
  97. Extensions of this method can extract more information from the
  98. stream header and perform checks on them, optionally sending
  99. stream errors and closing the stream.
  100. """
  101. if rootElement.hasAttribute("version"):
  102. version = rootElement["version"].split(".")
  103. try:
  104. version = (int(version[0]), int(version[1]))
  105. except (IndexError, ValueError):
  106. version = (0, 0)
  107. else:
  108. version = (0, 0)
  109. self.xmlstream.version = min(self.xmlstream.version, version)
  110. def associateWithStream(self, xmlstream):
  111. """
  112. Called by the XmlStreamFactory when a connection has been made
  113. to the requested peer, and an XmlStream object has been
  114. instantiated.
  115. The default implementation just saves a handle to the new
  116. XmlStream.
  117. @type xmlstream: L{XmlStream}
  118. @param xmlstream: The XmlStream that will be passing events to this
  119. Authenticator.
  120. """
  121. self.xmlstream = xmlstream
  122. class ConnectAuthenticator(Authenticator):
  123. """
  124. Authenticator for initiating entities.
  125. """
  126. namespace = None
  127. def __init__(self, otherHost):
  128. self.otherHost = otherHost
  129. def connectionMade(self):
  130. self.xmlstream.namespace = self.namespace
  131. self.xmlstream.otherEntity = jid.internJID(self.otherHost)
  132. self.xmlstream.sendHeader()
  133. def initializeStream(self):
  134. """
  135. Perform stream initialization procedures.
  136. An L{XmlStream} holds a list of initializer objects in its
  137. C{initializers} attribute. This method calls these initializers in
  138. order and dispatches the L{STREAM_AUTHD_EVENT} event when the list has
  139. been successfully processed. Otherwise it dispatches the
  140. C{INIT_FAILED_EVENT} event with the failure.
  141. Initializers may return the special L{Reset} object to halt the
  142. initialization processing. It signals that the current initializer was
  143. successfully processed, but that the XML Stream has been reset. An
  144. example is the TLSInitiatingInitializer.
  145. """
  146. def remove_first(result):
  147. self.xmlstream.initializers.pop(0)
  148. return result
  149. def do_next(result):
  150. """
  151. Take the first initializer and process it.
  152. On success, the initializer is removed from the list and
  153. then next initializer will be tried.
  154. """
  155. if result is Reset:
  156. return None
  157. try:
  158. init = self.xmlstream.initializers[0]
  159. except IndexError:
  160. self.xmlstream.dispatch(self.xmlstream, STREAM_AUTHD_EVENT)
  161. return None
  162. else:
  163. d = defer.maybeDeferred(init.initialize)
  164. d.addCallback(remove_first)
  165. d.addCallback(do_next)
  166. return d
  167. d = defer.succeed(None)
  168. d.addCallback(do_next)
  169. d.addErrback(self.xmlstream.dispatch, INIT_FAILED_EVENT)
  170. def streamStarted(self, rootElement):
  171. """
  172. Called by the XmlStream when the stream has started.
  173. This extends L{Authenticator.streamStarted} to extract further stream
  174. headers from C{rootElement}, optionally wait for stream features being
  175. received and then call C{initializeStream}.
  176. """
  177. Authenticator.streamStarted(self, rootElement)
  178. self.xmlstream.sid = rootElement.getAttribute("id")
  179. if rootElement.hasAttribute("from"):
  180. self.xmlstream.otherEntity = jid.internJID(rootElement["from"])
  181. # Setup observer for stream features, if applicable
  182. if self.xmlstream.version >= (1, 0):
  183. def onFeatures(element):
  184. features = {}
  185. for feature in element.elements():
  186. features[(feature.uri, feature.name)] = feature
  187. self.xmlstream.features = features
  188. self.initializeStream()
  189. self.xmlstream.addOnetimeObserver('/features[@xmlns="%s"]' %
  190. NS_STREAMS,
  191. onFeatures)
  192. else:
  193. self.initializeStream()
  194. class ListenAuthenticator(Authenticator):
  195. """
  196. Authenticator for receiving entities.
  197. """
  198. namespace = None
  199. def associateWithStream(self, xmlstream):
  200. """
  201. Called by the XmlStreamFactory when a connection has been made.
  202. Extend L{Authenticator.associateWithStream} to set the L{XmlStream}
  203. to be non-initiating.
  204. """
  205. Authenticator.associateWithStream(self, xmlstream)
  206. self.xmlstream.initiating = False
  207. def streamStarted(self, rootElement):
  208. """
  209. Called by the XmlStream when the stream has started.
  210. This extends L{Authenticator.streamStarted} to extract further
  211. information from the stream headers from C{rootElement}.
  212. """
  213. Authenticator.streamStarted(self, rootElement)
  214. self.xmlstream.namespace = rootElement.defaultUri
  215. if rootElement.hasAttribute("to"):
  216. self.xmlstream.thisEntity = jid.internJID(rootElement["to"])
  217. self.xmlstream.prefixes = {}
  218. for prefix, uri in iteritems(rootElement.localPrefixes):
  219. self.xmlstream.prefixes[uri] = prefix
  220. self.xmlstream.sid = hexlify(randbytes.secureRandom(8)).decode('ascii')
  221. class FeatureNotAdvertized(Exception):
  222. """
  223. Exception indicating a stream feature was not advertized, while required by
  224. the initiating entity.
  225. """
  226. @implementer(ijabber.IInitiatingInitializer)
  227. class BaseFeatureInitiatingInitializer(object):
  228. """
  229. Base class for initializers with a stream feature.
  230. This assumes the associated XmlStream represents the initiating entity
  231. of the connection.
  232. @cvar feature: tuple of (uri, name) of the stream feature root element.
  233. @type feature: tuple of (C{str}, C{str})
  234. @ivar required: whether the stream feature is required to be advertized
  235. by the receiving entity.
  236. @type required: C{bool}
  237. """
  238. feature = None
  239. def __init__(self, xs, required=False):
  240. self.xmlstream = xs
  241. self.required = required
  242. def initialize(self):
  243. """
  244. Initiate the initialization.
  245. Checks if the receiving entity advertizes the stream feature. If it
  246. does, the initialization is started. If it is not advertized, and the
  247. C{required} instance variable is C{True}, it raises
  248. L{FeatureNotAdvertized}. Otherwise, the initialization silently
  249. succeeds.
  250. """
  251. if self.feature in self.xmlstream.features:
  252. return self.start()
  253. elif self.required:
  254. raise FeatureNotAdvertized
  255. else:
  256. return None
  257. def start(self):
  258. """
  259. Start the actual initialization.
  260. May return a deferred for asynchronous initialization.
  261. """
  262. class TLSError(Exception):
  263. """
  264. TLS base exception.
  265. """
  266. class TLSFailed(TLSError):
  267. """
  268. Exception indicating failed TLS negotiation
  269. """
  270. class TLSRequired(TLSError):
  271. """
  272. Exception indicating required TLS negotiation.
  273. This exception is raised when the receiving entity requires TLS
  274. negotiation and the initiating does not desire to negotiate TLS.
  275. """
  276. class TLSNotSupported(TLSError):
  277. """
  278. Exception indicating missing TLS support.
  279. This exception is raised when the initiating entity wants and requires to
  280. negotiate TLS when the OpenSSL library is not available.
  281. """
  282. class TLSInitiatingInitializer(BaseFeatureInitiatingInitializer):
  283. """
  284. TLS stream initializer for the initiating entity.
  285. It is strongly required to include this initializer in the list of
  286. initializers for an XMPP stream. By default it will try to negotiate TLS.
  287. An XMPP server may indicate that TLS is required. If TLS is not desired,
  288. set the C{wanted} attribute to False instead of removing it from the list
  289. of initializers, so a proper exception L{TLSRequired} can be raised.
  290. @ivar wanted: indicates if TLS negotiation is wanted.
  291. @type wanted: C{bool}
  292. """
  293. feature = (NS_XMPP_TLS, 'starttls')
  294. wanted = True
  295. _deferred = None
  296. _configurationForTLS = None
  297. def __init__(self, xs, required=True, configurationForTLS=None):
  298. """
  299. @param configurationForTLS: An object which creates appropriately
  300. configured TLS connections. This is passed to C{startTLS} on the
  301. transport and is preferably created using
  302. L{twisted.internet.ssl.optionsForClientTLS}. If C{None}, the
  303. default is to verify the server certificate against the trust roots
  304. as provided by the platform. See
  305. L{twisted.internet._sslverify.platformTrust}.
  306. @type configurationForTLS: L{IOpenSSLClientConnectionCreator} or
  307. C{None}
  308. """
  309. super(TLSInitiatingInitializer, self).__init__(
  310. xs, required=required)
  311. self._configurationForTLS = configurationForTLS
  312. def onProceed(self, obj):
  313. """
  314. Proceed with TLS negotiation and reset the XML stream.
  315. """
  316. self.xmlstream.removeObserver('/failure', self.onFailure)
  317. if self._configurationForTLS:
  318. ctx = self._configurationForTLS
  319. else:
  320. ctx = ssl.optionsForClientTLS(self.xmlstream.otherEntity.host)
  321. self.xmlstream.transport.startTLS(ctx)
  322. self.xmlstream.reset()
  323. self.xmlstream.sendHeader()
  324. self._deferred.callback(Reset)
  325. def onFailure(self, obj):
  326. self.xmlstream.removeObserver('/proceed', self.onProceed)
  327. self._deferred.errback(TLSFailed())
  328. def start(self):
  329. """
  330. Start TLS negotiation.
  331. This checks if the receiving entity requires TLS, the SSL library is
  332. available and uses the C{required} and C{wanted} instance variables to
  333. determine what to do in the various different cases.
  334. For example, if the SSL library is not available, and wanted and
  335. required by the user, it raises an exception. However if it is not
  336. required by both parties, initialization silently succeeds, moving
  337. on to the next step.
  338. """
  339. if self.wanted:
  340. if ssl is None:
  341. if self.required:
  342. return defer.fail(TLSNotSupported())
  343. else:
  344. return defer.succeed(None)
  345. else:
  346. pass
  347. elif self.xmlstream.features[self.feature].required:
  348. return defer.fail(TLSRequired())
  349. else:
  350. return defer.succeed(None)
  351. self._deferred = defer.Deferred()
  352. self.xmlstream.addOnetimeObserver("/proceed", self.onProceed)
  353. self.xmlstream.addOnetimeObserver("/failure", self.onFailure)
  354. self.xmlstream.send(domish.Element((NS_XMPP_TLS, "starttls")))
  355. return self._deferred
  356. class XmlStream(xmlstream.XmlStream):
  357. """
  358. XMPP XML Stream protocol handler.
  359. @ivar version: XML stream version as a tuple (major, minor). Initially,
  360. this is set to the minimally supported version. Upon
  361. receiving the stream header of the peer, it is set to the
  362. minimum of that value and the version on the received
  363. header.
  364. @type version: (C{int}, C{int})
  365. @ivar namespace: default namespace URI for stream
  366. @type namespace: C{unicode}
  367. @ivar thisEntity: JID of this entity
  368. @type thisEntity: L{JID}
  369. @ivar otherEntity: JID of the peer entity
  370. @type otherEntity: L{JID}
  371. @ivar sid: session identifier
  372. @type sid: C{unicode}
  373. @ivar initiating: True if this is the initiating stream
  374. @type initiating: C{bool}
  375. @ivar features: map of (uri, name) to stream features element received from
  376. the receiving entity.
  377. @type features: C{dict} of (C{unicode}, C{unicode}) to L{domish.Element}.
  378. @ivar prefixes: map of URI to prefixes that are to appear on stream
  379. header.
  380. @type prefixes: C{dict} of C{unicode} to C{unicode}
  381. @ivar initializers: list of stream initializer objects
  382. @type initializers: C{list} of objects that provide L{IInitializer}
  383. @ivar authenticator: associated authenticator that uses C{initializers} to
  384. initialize the XML stream.
  385. """
  386. version = (1, 0)
  387. namespace = 'invalid'
  388. thisEntity = None
  389. otherEntity = None
  390. sid = None
  391. initiating = True
  392. _headerSent = False # True if the stream header has been sent
  393. def __init__(self, authenticator):
  394. xmlstream.XmlStream.__init__(self)
  395. self.prefixes = {NS_STREAMS: 'stream'}
  396. self.authenticator = authenticator
  397. self.initializers = []
  398. self.features = {}
  399. # Reset the authenticator
  400. authenticator.associateWithStream(self)
  401. def _callLater(self, *args, **kwargs):
  402. from twisted.internet import reactor
  403. return reactor.callLater(*args, **kwargs)
  404. def reset(self):
  405. """
  406. Reset XML Stream.
  407. Resets the XML Parser for incoming data. This is to be used after
  408. successfully negotiating a new layer, e.g. TLS and SASL. Note that
  409. registered event observers will continue to be in place.
  410. """
  411. self._headerSent = False
  412. self._initializeStream()
  413. def onStreamError(self, errelem):
  414. """
  415. Called when a stream:error element has been received.
  416. Dispatches a L{STREAM_ERROR_EVENT} event with the error element to
  417. allow for cleanup actions and drops the connection.
  418. @param errelem: The received error element.
  419. @type errelem: L{domish.Element}
  420. """
  421. self.dispatch(failure.Failure(error.exceptionFromStreamError(errelem)),
  422. STREAM_ERROR_EVENT)
  423. self.transport.loseConnection()
  424. def sendHeader(self):
  425. """
  426. Send stream header.
  427. """
  428. # set up optional extra namespaces
  429. localPrefixes = {}
  430. for uri, prefix in iteritems(self.prefixes):
  431. if uri != NS_STREAMS:
  432. localPrefixes[prefix] = uri
  433. rootElement = domish.Element((NS_STREAMS, 'stream'), self.namespace,
  434. localPrefixes=localPrefixes)
  435. if self.otherEntity:
  436. rootElement['to'] = self.otherEntity.userhost()
  437. if self.thisEntity:
  438. rootElement['from'] = self.thisEntity.userhost()
  439. if not self.initiating and self.sid:
  440. rootElement['id'] = self.sid
  441. if self.version >= (1, 0):
  442. rootElement['version'] = "%d.%d" % self.version
  443. self.send(rootElement.toXml(prefixes=self.prefixes, closeElement=0))
  444. self._headerSent = True
  445. def sendFooter(self):
  446. """
  447. Send stream footer.
  448. """
  449. self.send('</stream:stream>')
  450. def sendStreamError(self, streamError):
  451. """
  452. Send stream level error.
  453. If we are the receiving entity, and haven't sent the header yet,
  454. we sent one first.
  455. After sending the stream error, the stream is closed and the transport
  456. connection dropped.
  457. @param streamError: stream error instance
  458. @type streamError: L{error.StreamError}
  459. """
  460. if not self._headerSent and not self.initiating:
  461. self.sendHeader()
  462. if self._headerSent:
  463. self.send(streamError.getElement())
  464. self.sendFooter()
  465. self.transport.loseConnection()
  466. def send(self, obj):
  467. """
  468. Send data over the stream.
  469. This overrides L{xmlstream.XmlStream.send} to use the default namespace
  470. of the stream header when serializing L{domish.IElement}s. It is
  471. assumed that if you pass an object that provides L{domish.IElement},
  472. it represents a direct child of the stream's root element.
  473. """
  474. if domish.IElement.providedBy(obj):
  475. obj = obj.toXml(prefixes=self.prefixes,
  476. defaultUri=self.namespace,
  477. prefixesInScope=list(self.prefixes.values()))
  478. xmlstream.XmlStream.send(self, obj)
  479. def connectionMade(self):
  480. """
  481. Called when a connection is made.
  482. Notifies the authenticator when a connection has been made.
  483. """
  484. xmlstream.XmlStream.connectionMade(self)
  485. self.authenticator.connectionMade()
  486. def onDocumentStart(self, rootElement):
  487. """
  488. Called when the stream header has been received.
  489. Extracts the header's C{id} and C{version} attributes from the root
  490. element. The C{id} attribute is stored in our C{sid} attribute and the
  491. C{version} attribute is parsed and the minimum of the version we sent
  492. and the parsed C{version} attribute is stored as a tuple (major, minor)
  493. in this class' C{version} attribute. If no C{version} attribute was
  494. present, we assume version 0.0.
  495. If appropriate (we are the initiating stream and the minimum of our and
  496. the other party's version is at least 1.0), a one-time observer is
  497. registered for getting the stream features. The registered function is
  498. C{onFeatures}.
  499. Ultimately, the authenticator's C{streamStarted} method will be called.
  500. @param rootElement: The root element.
  501. @type rootElement: L{domish.Element}
  502. """
  503. xmlstream.XmlStream.onDocumentStart(self, rootElement)
  504. # Setup observer for stream errors
  505. self.addOnetimeObserver("/error[@xmlns='%s']" % NS_STREAMS,
  506. self.onStreamError)
  507. self.authenticator.streamStarted(rootElement)
  508. class XmlStreamFactory(xmlstream.XmlStreamFactory):
  509. """
  510. Factory for Jabber XmlStream objects as a reconnecting client.
  511. Note that this differs from L{xmlstream.XmlStreamFactory} in that
  512. it generates Jabber specific L{XmlStream} instances that have
  513. authenticators.
  514. """
  515. protocol = XmlStream
  516. def __init__(self, authenticator):
  517. xmlstream.XmlStreamFactory.__init__(self, authenticator)
  518. self.authenticator = authenticator
  519. class XmlStreamServerFactory(xmlstream.BootstrapMixin,
  520. protocol.ServerFactory):
  521. """
  522. Factory for Jabber XmlStream objects as a server.
  523. @since: 8.2.
  524. @ivar authenticatorFactory: Factory callable that takes no arguments, to
  525. create a fresh authenticator to be associated
  526. with the XmlStream.
  527. """
  528. protocol = XmlStream
  529. def __init__(self, authenticatorFactory):
  530. xmlstream.BootstrapMixin.__init__(self)
  531. self.authenticatorFactory = authenticatorFactory
  532. def buildProtocol(self, addr):
  533. """
  534. Create an instance of XmlStream.
  535. A new authenticator instance will be created and passed to the new
  536. XmlStream. Registered bootstrap event observers are installed as well.
  537. """
  538. authenticator = self.authenticatorFactory()
  539. xs = self.protocol(authenticator)
  540. xs.factory = self
  541. self.installBootstraps(xs)
  542. return xs
  543. class TimeoutError(Exception):
  544. """
  545. Exception raised when no IQ response has been received before the
  546. configured timeout.
  547. """
  548. def upgradeWithIQResponseTracker(xs):
  549. """
  550. Enhances an XmlStream for iq response tracking.
  551. This makes an L{XmlStream} object provide L{IIQResponseTracker}. When a
  552. response is an error iq stanza, the deferred has its errback invoked with a
  553. failure that holds a L{StanzaError<error.StanzaError>} that is
  554. easier to examine.
  555. """
  556. def callback(iq):
  557. """
  558. Handle iq response by firing associated deferred.
  559. """
  560. if getattr(iq, 'handled', False):
  561. return
  562. try:
  563. d = xs.iqDeferreds[iq["id"]]
  564. except KeyError:
  565. pass
  566. else:
  567. del xs.iqDeferreds[iq["id"]]
  568. iq.handled = True
  569. if iq['type'] == 'error':
  570. d.errback(error.exceptionFromStanza(iq))
  571. else:
  572. d.callback(iq)
  573. def disconnected(_):
  574. """
  575. Make sure deferreds do not linger on after disconnect.
  576. This errbacks all deferreds of iq's for which no response has been
  577. received with a L{ConnectionLost} failure. Otherwise, the deferreds
  578. will never be fired.
  579. """
  580. iqDeferreds = xs.iqDeferreds
  581. xs.iqDeferreds = {}
  582. for d in itervalues(iqDeferreds):
  583. d.errback(ConnectionLost())
  584. xs.iqDeferreds = {}
  585. xs.iqDefaultTimeout = getattr(xs, 'iqDefaultTimeout', None)
  586. xs.addObserver(xmlstream.STREAM_END_EVENT, disconnected)
  587. xs.addObserver('/iq[@type="result"]', callback)
  588. xs.addObserver('/iq[@type="error"]', callback)
  589. directlyProvides(xs, ijabber.IIQResponseTracker)
  590. class IQ(domish.Element):
  591. """
  592. Wrapper for an iq stanza.
  593. Iq stanzas are used for communications with a request-response behaviour.
  594. Each iq request is associated with an XML stream and has its own unique id
  595. to be able to track the response.
  596. @ivar timeout: if set, a timeout period after which the deferred returned
  597. by C{send} will have its errback called with a
  598. L{TimeoutError} failure.
  599. @type timeout: C{float}
  600. """
  601. timeout = None
  602. def __init__(self, xmlstream, stanzaType="set"):
  603. """
  604. @type xmlstream: L{xmlstream.XmlStream}
  605. @param xmlstream: XmlStream to use for transmission of this IQ
  606. @type stanzaType: C{str}
  607. @param stanzaType: IQ type identifier ('get' or 'set')
  608. """
  609. domish.Element.__init__(self, (None, "iq"))
  610. self.addUniqueId()
  611. self["type"] = stanzaType
  612. self._xmlstream = xmlstream
  613. def send(self, to=None):
  614. """
  615. Send out this iq.
  616. Returns a deferred that is fired when an iq response with the same id
  617. is received. Result responses will be passed to the deferred callback.
  618. Error responses will be transformed into a
  619. L{StanzaError<error.StanzaError>} and result in the errback of the
  620. deferred being invoked.
  621. @rtype: L{defer.Deferred}
  622. """
  623. if to is not None:
  624. self["to"] = to
  625. if not ijabber.IIQResponseTracker.providedBy(self._xmlstream):
  626. upgradeWithIQResponseTracker(self._xmlstream)
  627. d = defer.Deferred()
  628. self._xmlstream.iqDeferreds[self['id']] = d
  629. timeout = self.timeout or self._xmlstream.iqDefaultTimeout
  630. if timeout is not None:
  631. def onTimeout():
  632. del self._xmlstream.iqDeferreds[self['id']]
  633. d.errback(TimeoutError("IQ timed out"))
  634. call = self._xmlstream._callLater(timeout, onTimeout)
  635. def cancelTimeout(result):
  636. if call.active():
  637. call.cancel()
  638. return result
  639. d.addBoth(cancelTimeout)
  640. self._xmlstream.send(self)
  641. return d
  642. def toResponse(stanza, stanzaType=None):
  643. """
  644. Create a response stanza from another stanza.
  645. This takes the addressing and id attributes from a stanza to create a (new,
  646. empty) response stanza. The addressing attributes are swapped and the id
  647. copied. Optionally, the stanza type of the response can be specified.
  648. @param stanza: the original stanza
  649. @type stanza: L{domish.Element}
  650. @param stanzaType: optional response stanza type
  651. @type stanzaType: C{str}
  652. @return: the response stanza.
  653. @rtype: L{domish.Element}
  654. """
  655. toAddr = stanza.getAttribute('from')
  656. fromAddr = stanza.getAttribute('to')
  657. stanzaID = stanza.getAttribute('id')
  658. response = domish.Element((None, stanza.name))
  659. if toAddr:
  660. response['to'] = toAddr
  661. if fromAddr:
  662. response['from'] = fromAddr
  663. if stanzaID:
  664. response['id'] = stanzaID
  665. if stanzaType:
  666. response['type'] = stanzaType
  667. return response
  668. @implementer(ijabber.IXMPPHandler)
  669. class XMPPHandler(object):
  670. """
  671. XMPP protocol handler.
  672. Classes derived from this class implement (part of) one or more XMPP
  673. extension protocols, and are referred to as a subprotocol implementation.
  674. """
  675. def __init__(self):
  676. self.parent = None
  677. self.xmlstream = None
  678. def setHandlerParent(self, parent):
  679. self.parent = parent
  680. self.parent.addHandler(self)
  681. def disownHandlerParent(self, parent):
  682. self.parent.removeHandler(self)
  683. self.parent = None
  684. def makeConnection(self, xs):
  685. self.xmlstream = xs
  686. self.connectionMade()
  687. def connectionMade(self):
  688. """
  689. Called after a connection has been established.
  690. Can be overridden to perform work before stream initialization.
  691. """
  692. def connectionInitialized(self):
  693. """
  694. The XML stream has been initialized.
  695. Can be overridden to perform work after stream initialization, e.g. to
  696. set up observers and start exchanging XML stanzas.
  697. """
  698. def connectionLost(self, reason):
  699. """
  700. The XML stream has been closed.
  701. This method can be extended to inspect the C{reason} argument and
  702. act on it.
  703. """
  704. self.xmlstream = None
  705. def send(self, obj):
  706. """
  707. Send data over the managed XML stream.
  708. @note: The stream manager maintains a queue for data sent using this
  709. method when there is no current initialized XML stream. This
  710. data is then sent as soon as a new stream has been established
  711. and initialized. Subsequently, L{connectionInitialized} will be
  712. called again. If this queueing is not desired, use C{send} on
  713. C{self.xmlstream}.
  714. @param obj: data to be sent over the XML stream. This is usually an
  715. object providing L{domish.IElement}, or serialized XML. See
  716. L{xmlstream.XmlStream} for details.
  717. """
  718. self.parent.send(obj)
  719. @implementer(ijabber.IXMPPHandlerCollection)
  720. class XMPPHandlerCollection(object):
  721. """
  722. Collection of XMPP subprotocol handlers.
  723. This allows for grouping of subprotocol handlers, but is not an
  724. L{XMPPHandler} itself, so this is not recursive.
  725. @ivar handlers: List of protocol handlers.
  726. @type handlers: C{list} of objects providing
  727. L{IXMPPHandler}
  728. """
  729. def __init__(self):
  730. self.handlers = []
  731. def __iter__(self):
  732. """
  733. Act as a container for handlers.
  734. """
  735. return iter(self.handlers)
  736. def addHandler(self, handler):
  737. """
  738. Add protocol handler.
  739. Protocol handlers are expected to provide L{ijabber.IXMPPHandler}.
  740. """
  741. self.handlers.append(handler)
  742. def removeHandler(self, handler):
  743. """
  744. Remove protocol handler.
  745. """
  746. self.handlers.remove(handler)
  747. class StreamManager(XMPPHandlerCollection):
  748. """
  749. Business logic representing a managed XMPP connection.
  750. This maintains a single XMPP connection and provides facilities for packet
  751. routing and transmission. Business logic modules are objects providing
  752. L{ijabber.IXMPPHandler} (like subclasses of L{XMPPHandler}), and added
  753. using L{addHandler}.
  754. @ivar xmlstream: currently managed XML stream
  755. @type xmlstream: L{XmlStream}
  756. @ivar logTraffic: if true, log all traffic.
  757. @type logTraffic: C{bool}
  758. @ivar _initialized: Whether the stream represented by L{xmlstream} has
  759. been initialized. This is used when caching outgoing
  760. stanzas.
  761. @type _initialized: C{bool}
  762. @ivar _packetQueue: internal buffer of unsent data. See L{send} for details.
  763. @type _packetQueue: C{list}
  764. """
  765. logTraffic = False
  766. def __init__(self, factory):
  767. XMPPHandlerCollection.__init__(self)
  768. self.xmlstream = None
  769. self._packetQueue = []
  770. self._initialized = False
  771. factory.addBootstrap(STREAM_CONNECTED_EVENT, self._connected)
  772. factory.addBootstrap(STREAM_AUTHD_EVENT, self._authd)
  773. factory.addBootstrap(INIT_FAILED_EVENT, self.initializationFailed)
  774. factory.addBootstrap(STREAM_END_EVENT, self._disconnected)
  775. self.factory = factory
  776. def addHandler(self, handler):
  777. """
  778. Add protocol handler.
  779. When an XML stream has already been established, the handler's
  780. C{connectionInitialized} will be called to get it up to speed.
  781. """
  782. XMPPHandlerCollection.addHandler(self, handler)
  783. # get protocol handler up to speed when a connection has already
  784. # been established
  785. if self.xmlstream and self._initialized:
  786. handler.makeConnection(self.xmlstream)
  787. handler.connectionInitialized()
  788. def _connected(self, xs):
  789. """
  790. Called when the transport connection has been established.
  791. Here we optionally set up traffic logging (depending on L{logTraffic})
  792. and call each handler's C{makeConnection} method with the L{XmlStream}
  793. instance.
  794. """
  795. def logDataIn(buf):
  796. log.msg("RECV: %r" % buf)
  797. def logDataOut(buf):
  798. log.msg("SEND: %r" % buf)
  799. if self.logTraffic:
  800. xs.rawDataInFn = logDataIn
  801. xs.rawDataOutFn = logDataOut
  802. self.xmlstream = xs
  803. for e in self:
  804. e.makeConnection(xs)
  805. def _authd(self, xs):
  806. """
  807. Called when the stream has been initialized.
  808. Send out cached stanzas and call each handler's
  809. C{connectionInitialized} method.
  810. """
  811. # Flush all pending packets
  812. for p in self._packetQueue:
  813. xs.send(p)
  814. self._packetQueue = []
  815. self._initialized = True
  816. # Notify all child services which implement
  817. # the IService interface
  818. for e in self:
  819. e.connectionInitialized()
  820. def initializationFailed(self, reason):
  821. """
  822. Called when stream initialization has failed.
  823. Stream initialization has halted, with the reason indicated by
  824. C{reason}. It may be retried by calling the authenticator's
  825. C{initializeStream}. See the respective authenticators for details.
  826. @param reason: A failure instance indicating why stream initialization
  827. failed.
  828. @type reason: L{failure.Failure}
  829. """
  830. def _disconnected(self, reason):
  831. """
  832. Called when the stream has been closed.
  833. From this point on, the manager doesn't interact with the
  834. L{XmlStream} anymore and notifies each handler that the connection
  835. was lost by calling its C{connectionLost} method.
  836. """
  837. self.xmlstream = None
  838. self._initialized = False
  839. # Notify all child services which implement
  840. # the IService interface
  841. for e in self:
  842. e.connectionLost(reason)
  843. def send(self, obj):
  844. """
  845. Send data over the XML stream.
  846. When there is no established XML stream, the data is queued and sent
  847. out when a new XML stream has been established and initialized.
  848. @param obj: data to be sent over the XML stream. See
  849. L{xmlstream.XmlStream.send} for details.
  850. """
  851. if self._initialized:
  852. self.xmlstream.send(obj)
  853. else:
  854. self._packetQueue.append(obj)
  855. __all__ = ['Authenticator', 'BaseFeatureInitiatingInitializer',
  856. 'ConnectAuthenticator', 'FeatureNotAdvertized',
  857. 'INIT_FAILED_EVENT', 'IQ', 'ListenAuthenticator', 'NS_STREAMS',
  858. 'NS_XMPP_TLS', 'Reset', 'STREAM_AUTHD_EVENT',
  859. 'STREAM_CONNECTED_EVENT', 'STREAM_END_EVENT', 'STREAM_ERROR_EVENT',
  860. 'STREAM_START_EVENT', 'StreamManager', 'TLSError', 'TLSFailed',
  861. 'TLSInitiatingInitializer', 'TLSNotSupported', 'TLSRequired',
  862. 'TimeoutError', 'XMPPHandler', 'XMPPHandlerCollection', 'XmlStream',
  863. 'XmlStreamFactory', 'XmlStreamServerFactory', 'hashPassword',
  864. 'toResponse', 'upgradeWithIQResponseTracker']