dispatcher.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377
  1. ## transports.py
  2. ##
  3. ## Copyright (C) 2003-2005 Alexey "Snake" Nezhdanov
  4. ##
  5. ## This program is free software; you can redistribute it and/or modify
  6. ## it under the terms of the GNU General Public License as published by
  7. ## the Free Software Foundation; either version 2, or (at your option)
  8. ## any later version.
  9. ##
  10. ## This program is distributed in the hope that it will be useful,
  11. ## but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. ## GNU General Public License for more details.
  14. # $Id$
  15. """
  16. Main xmpppy mechanism. Provides library with methods to assign different handlers
  17. to different XMPP stanzas.
  18. Contains one tunable attribute: DefaultTimeout (25 seconds by default). It defines time that
  19. Dispatcher.SendAndWaitForResponce method will wait for reply stanza before giving up.
  20. """
  21. import time,sys
  22. from . import simplexml
  23. from .protocol import *
  24. from .client import PlugIn
  25. DefaultTimeout=25
  26. ID=0
  27. class Dispatcher(PlugIn):
  28. """ Ancestor of PlugIn class. Handles XMPP stream, i.e. aware of stream headers.
  29. Can be plugged out/in to restart these headers (used for SASL f.e.). """
  30. def __init__(self):
  31. PlugIn.__init__(self)
  32. DBG_LINE='dispatcher'
  33. self.handlers={}
  34. self._expected={}
  35. self._defaultHandler=None
  36. self._pendingExceptions=[]
  37. self._eventHandler=None
  38. self._cycleHandlers=[]
  39. self._exported_methods=[self.Process,self.RegisterHandler,self.RegisterDefaultHandler,\
  40. self.RegisterEventHandler,self.UnregisterCycleHandler,self.RegisterCycleHandler,\
  41. self.RegisterHandlerOnce,self.UnregisterHandler,self.RegisterProtocol,\
  42. self.WaitForResponse,self.SendAndWaitForResponse,self.send,self.disconnect,\
  43. self.SendAndCallForResponse, ]
  44. def dumpHandlers(self):
  45. """ Return set of user-registered callbacks in it's internal format.
  46. Used within the library to carry user handlers set over Dispatcher replugins. """
  47. return self.handlers
  48. def restoreHandlers(self,handlers):
  49. """ Restores user-registered callbacks structure from dump previously obtained via dumpHandlers.
  50. Used within the library to carry user handlers set over Dispatcher replugins. """
  51. self.handlers=handlers
  52. def _init(self):
  53. """ Registers default namespaces/protocols/handlers. Used internally. """
  54. self.RegisterNamespace('unknown')
  55. self.RegisterNamespace(NS_STREAMS)
  56. self.RegisterNamespace(self._owner.defaultNamespace)
  57. self.RegisterProtocol('iq',Iq)
  58. self.RegisterProtocol('presence',Presence)
  59. self.RegisterProtocol('message',Message)
  60. self.RegisterDefaultHandler(self.returnStanzaHandler)
  61. self.RegisterHandler('error',self.streamErrorHandler,xmlns=NS_STREAMS)
  62. def plugin(self, owner):
  63. """ Plug the Dispatcher instance into Client class instance and send initial stream header. Used internally."""
  64. self._init()
  65. for method in self._old_owners_methods:
  66. if method.__name__=='send': self._owner_send=method; break
  67. self._owner.lastErrNode=None
  68. self._owner.lastErr=None
  69. self._owner.lastErrCode=None
  70. self.StreamInit()
  71. def plugout(self):
  72. """ Prepares instance to be destructed. """
  73. self.Stream.dispatch=None
  74. self.Stream.DEBUG=None
  75. self.Stream.features=None
  76. self.Stream.destroy()
  77. def StreamInit(self):
  78. """ Send an initial stream header. """
  79. self.Stream=simplexml.NodeBuilder()
  80. self.Stream._dispatch_depth=2
  81. self.Stream.dispatch=self.dispatch
  82. self.Stream.stream_header_received=self._check_stream_start
  83. self._owner.debug_flags.append(simplexml.DBG_NODEBUILDER)
  84. self.Stream.DEBUG=self._owner.DEBUG
  85. self.Stream.features=None
  86. self._metastream=Node('stream:stream')
  87. self._metastream.setNamespace(self._owner.Namespace)
  88. self._metastream.setAttr('version','1.0')
  89. self._metastream.setAttr('xmlns:stream',NS_STREAMS)
  90. self._metastream.setAttr('to',self._owner.Server)
  91. self._owner.send("<?xml version='1.0'?>%s>"%str(self._metastream)[:-2])
  92. def _check_stream_start(self,ns,tag,attrs):
  93. if ns!=NS_STREAMS or tag!='stream':
  94. raise ValueError('Incorrect stream start: (%s,%s). Terminating.'%(tag,ns))
  95. def Process(self, timeout=0):
  96. """ Check incoming stream for data waiting. If "timeout" is positive - block for as max. this time.
  97. Returns:
  98. 1) length of processed data if some data were processed;
  99. 2) '0' string if no data were processed but link is alive;
  100. 3) 0 (zero) if underlying connection is closed.
  101. Take note that in case of disconnection detect during Process() call
  102. disconnect handlers are called automatically.
  103. """
  104. for handler in self._cycleHandlers: handler(self)
  105. if len(self._pendingExceptions) > 0:
  106. _pendingException = self._pendingExceptions.pop()
  107. raise _pendingException[0](_pendingException[1]).with_traceback(_pendingException[2])
  108. if self._owner.Connection.pending_data(timeout):
  109. try: data=self._owner.Connection.receive()
  110. except IOError: return
  111. self.Stream.Parse(data)
  112. if len(self._pendingExceptions) > 0:
  113. _pendingException = self._pendingExceptions.pop()
  114. ex = _pendingException[0](_pendingException[1])
  115. if hasattr(ex, "with_traceback"):
  116. ex = ex.with_traceback(_pendingException[2])
  117. raise ex
  118. if data: return len(data)
  119. return '0' # It means that nothing is received but link is alive.
  120. def RegisterNamespace(self,xmlns,order='info'):
  121. """ Creates internal structures for newly registered namespace.
  122. You can register handlers for this namespace afterwards. By default one namespace
  123. already registered (jabber:client or jabber:component:accept depending on context. """
  124. self.DEBUG('Registering namespace "%s"'%xmlns,order)
  125. self.handlers[xmlns]={}
  126. self.RegisterProtocol('unknown',Protocol,xmlns=xmlns)
  127. self.RegisterProtocol('default',Protocol,xmlns=xmlns)
  128. def RegisterProtocol(self,tag_name,Proto,xmlns=None,order='info'):
  129. """ Used to declare some top-level stanza name to dispatcher.
  130. Needed to start registering handlers for such stanzas.
  131. Iq, message and presence protocols are registered by default. """
  132. if not xmlns: xmlns=self._owner.defaultNamespace
  133. self.DEBUG('Registering protocol "%s" as %s(%s)'%(tag_name,Proto,xmlns), order)
  134. self.handlers[xmlns][tag_name]={type:Proto, 'default':[]}
  135. def RegisterNamespaceHandler(self,xmlns,handler,typ='',ns='', makefirst=0, system=0):
  136. """ Register handler for processing all stanzas for specified namespace. """
  137. self.RegisterHandler('default', handler, typ, ns, xmlns, makefirst, system)
  138. def RegisterHandler(self,name,handler,typ='',ns='',xmlns=None, makefirst=0, system=0):
  139. """Register user callback as stanzas handler of declared type. Callback must take
  140. (if chained, see later) arguments: dispatcher instance (for replying), incomed
  141. return of previous handlers.
  142. The callback must raise xmpp.NodeProcessed just before return if it want preven
  143. callbacks to be called with the same stanza as argument _and_, more importantly
  144. library from returning stanza to sender with error set (to be enabled in 0.2 ve
  145. Arguments:
  146. "name" - name of stanza. F.e. "iq".
  147. "handler" - user callback.
  148. "typ" - value of stanza's "type" attribute. If not specified any value match
  149. "ns" - namespace of child that stanza must contain.
  150. "chained" - chain together output of several handlers.
  151. "makefirst" - insert handler in the beginning of handlers list instead of
  152. adding it to the end. Note that more common handlers (i.e. w/o "typ" and "
  153. will be called first nevertheless.
  154. "system" - call handler even if NodeProcessed Exception were raised already.
  155. """
  156. if not xmlns: xmlns=self._owner.defaultNamespace
  157. self.DEBUG('Registering handler %s for "%s" type->%s ns->%s(%s)'%(handler,name,typ,ns,xmlns), 'info')
  158. if not typ and not ns: typ='default'
  159. if xmlns not in self.handlers: self.RegisterNamespace(xmlns,'warn')
  160. if name not in self.handlers[xmlns]: self.RegisterProtocol(name,Protocol,xmlns,'warn')
  161. if typ+ns not in self.handlers[xmlns][name]: self.handlers[xmlns][name][typ+ns]=[]
  162. if makefirst: self.handlers[xmlns][name][typ+ns].insert(0,{'func':handler,'system':system})
  163. else: self.handlers[xmlns][name][typ+ns].append({'func':handler,'system':system})
  164. def RegisterHandlerOnce(self,name,handler,typ='',ns='',xmlns=None,makefirst=0, system=0):
  165. """ Unregister handler after first call (not implemented yet). """
  166. if not xmlns: xmlns=self._owner.defaultNamespace
  167. self.RegisterHandler(name, handler, typ, ns, xmlns, makefirst, system)
  168. def UnregisterHandler(self,name,handler,typ='',ns='',xmlns=None):
  169. """ Unregister handler. "typ" and "ns" must be specified exactly the same as with registering."""
  170. if not xmlns: xmlns=self._owner.defaultNamespace
  171. if xmlns not in self.handlers: return
  172. if not typ and not ns: typ='default'
  173. for pack in self.handlers[xmlns][name][typ+ns]:
  174. if handler==pack['func']: break
  175. else: pack=None
  176. try: self.handlers[xmlns][name][typ+ns].remove(pack)
  177. except ValueError: pass
  178. def RegisterDefaultHandler(self,handler):
  179. """ Specify the handler that will be used if no NodeProcessed exception were raised.
  180. This is returnStanzaHandler by default. """
  181. self._defaultHandler=handler
  182. def RegisterEventHandler(self,handler):
  183. """ Register handler that will process events. F.e. "FILERECEIVED" event. """
  184. self._eventHandler=handler
  185. def returnStanzaHandler(self,conn,stanza):
  186. """ Return stanza back to the sender with <feature-not-implemennted/> error set. """
  187. if stanza.getType() in ['get','set']:
  188. conn.send(Error(stanza,ERR_FEATURE_NOT_IMPLEMENTED))
  189. def streamErrorHandler(self,conn,error):
  190. name,text='error',error.getData()
  191. for tag in error.getChildren():
  192. if tag.getNamespace()==NS_XMPP_STREAMS:
  193. if tag.getName()=='text': text=tag.getData()
  194. else: name=tag.getName()
  195. if name in list(stream_exceptions.keys()): exc=stream_exceptions[name]
  196. else: exc=StreamError
  197. raise exc((name,text))
  198. def RegisterCycleHandler(self,handler):
  199. """ Register handler that will be called on every Dispatcher.Process() call. """
  200. if handler not in self._cycleHandlers: self._cycleHandlers.append(handler)
  201. def UnregisterCycleHandler(self,handler):
  202. """ Unregister handler that will is called on every Dispatcher.Process() call."""
  203. if handler in self._cycleHandlers: self._cycleHandlers.remove(handler)
  204. def Event(self,realm,event,data):
  205. """ Raise some event. Takes three arguments:
  206. 1) "realm" - scope of event. Usually a namespace.
  207. 2) "event" - the event itself. F.e. "SUCESSFULL SEND".
  208. 3) data that comes along with event. Depends on event."""
  209. if self._eventHandler: self._eventHandler(realm,event,data)
  210. def dispatch(self,stanza,session=None,direct=0):
  211. """ Main procedure that performs XMPP stanza recognition and calling apppropriate handlers for it.
  212. Called internally. """
  213. if not session: session=self
  214. session.Stream._mini_dom=None
  215. name=stanza.getName()
  216. if not direct and self._owner._route:
  217. if name == 'route':
  218. if stanza.getAttr('error') == None:
  219. if len(stanza.getChildren()) == 1:
  220. stanza = stanza.getChildren()[0]
  221. name=stanza.getName()
  222. else:
  223. for each in stanza.getChildren():
  224. self.dispatch(each,session,direct=1)
  225. return
  226. elif name == 'presence':
  227. return
  228. elif name in ('features','bind'):
  229. pass
  230. else:
  231. raise UnsupportedStanzaType(name)
  232. if name=='features': session.Stream.features=stanza
  233. xmlns=stanza.getNamespace()
  234. if xmlns not in self.handlers:
  235. self.DEBUG("Unknown namespace: " + xmlns,'warn')
  236. xmlns='unknown'
  237. if name not in self.handlers[xmlns]:
  238. self.DEBUG("Unknown stanza: " + name,'warn')
  239. name='unknown'
  240. else:
  241. self.DEBUG("Got %s/%s stanza"%(xmlns,name), 'ok')
  242. if stanza.__class__.__name__=='Node': stanza=self.handlers[xmlns][name][type](node=stanza)
  243. typ=stanza.getType()
  244. if not typ: typ=''
  245. stanza.props=stanza.getProperties()
  246. ID=stanza.getID()
  247. session.DEBUG("Dispatching %s stanza with type->%s props->%s id->%s"%(name,typ,stanza.props,ID),'ok')
  248. list=['default'] # we will use all handlers:
  249. if typ in self.handlers[xmlns][name]: list.append(typ) # from very common...
  250. for prop in stanza.props:
  251. if prop in self.handlers[xmlns][name]: list.append(prop)
  252. if typ and typ+prop in self.handlers[xmlns][name]: list.append(typ+prop) # ...to very particular
  253. chain=self.handlers[xmlns]['default']['default']
  254. for key in list:
  255. if key: chain = chain + self.handlers[xmlns][name][key]
  256. output=''
  257. if ID in session._expected:
  258. user=0
  259. if type(session._expected[ID])==type(()):
  260. cb,args=session._expected[ID]
  261. session.DEBUG("Expected stanza arrived. Callback %s(%s) found!"%(cb,args),'ok')
  262. try: cb(session,stanza,**args)
  263. except Exception as typ:
  264. if typ.__class__.__name__!='NodeProcessed': raise
  265. else:
  266. session.DEBUG("Expected stanza arrived!",'ok')
  267. session._expected[ID]=stanza
  268. else: user=1
  269. for handler in chain:
  270. if user or handler['system']:
  271. try:
  272. handler['func'](session,stanza)
  273. except Exception as typ:
  274. if typ.__class__.__name__!='NodeProcessed':
  275. self._pendingExceptions.insert(0, sys.exc_info())
  276. return
  277. user=0
  278. if user and self._defaultHandler: self._defaultHandler(session,stanza)
  279. def WaitForResponse(self, ID, timeout=DefaultTimeout):
  280. """ Block and wait until stanza with specific "id" attribute will come.
  281. If no such stanza is arrived within timeout, return None.
  282. If operation failed for some reason then owner's attributes
  283. lastErrNode, lastErr and lastErrCode are set accordingly. """
  284. self._expected[ID]=None
  285. has_timed_out=0
  286. abort_time=time.time() + timeout
  287. self.DEBUG("Waiting for ID:%s with timeout %s..." % (ID,timeout),'wait')
  288. while not self._expected[ID]:
  289. if not self.Process(0.04):
  290. self._owner.lastErr="Disconnect"
  291. return None
  292. if time.time() > abort_time:
  293. self._owner.lastErr="Timeout"
  294. return None
  295. response=self._expected[ID]
  296. del self._expected[ID]
  297. if response.getErrorCode():
  298. self._owner.lastErrNode=response
  299. self._owner.lastErr=response.getError()
  300. self._owner.lastErrCode=response.getErrorCode()
  301. return response
  302. def SendAndWaitForResponse(self, stanza, timeout=DefaultTimeout):
  303. """ Put stanza on the wire and wait for recipient's response to it. """
  304. return self.WaitForResponse(self.send(stanza),timeout)
  305. def SendAndCallForResponse(self, stanza, func, args={}):
  306. """ Put stanza on the wire and call back when recipient replies.
  307. Additional callback arguments can be specified in args. """
  308. self._expected[self.send(stanza)]=(func,args)
  309. def send(self,stanza):
  310. """ Serialise stanza and put it on the wire. Assign an unique ID to it before send.
  311. Returns assigned ID."""
  312. if type(stanza) in [type(''), type('')]: return self._owner_send(stanza)
  313. if not isinstance(stanza,Protocol): _ID=None
  314. elif not stanza.getID():
  315. global ID
  316. ID+=1
  317. _ID=repr(ID)
  318. stanza.setID(_ID)
  319. else: _ID=stanza.getID()
  320. if self._owner._registered_name and not stanza.getAttr('from'): stanza.setAttr('from',self._owner._registered_name)
  321. if self._owner._route and stanza.getName()!='bind':
  322. to=self._owner.Server
  323. if stanza.getTo() and stanza.getTo().getDomain():
  324. to=stanza.getTo().getDomain()
  325. frm=stanza.getFrom()
  326. if frm.getDomain():
  327. frm=frm.getDomain()
  328. route=Protocol('route',to=to,frm=frm,payload=[stanza])
  329. stanza=route
  330. stanza.setNamespace(self._owner.Namespace)
  331. stanza.setParent(self._metastream)
  332. self._owner_send(stanza)
  333. return _ID
  334. def disconnect(self):
  335. """ Send a stream terminator and and handle all incoming stanzas before stream closure. """
  336. self._owner_send('</stream:stream>')
  337. while self.Process(1): pass