session.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  1. ##
  2. ## XMPP server
  3. ##
  4. ## Copyright (C) 2004 Alexey "Snake" Nezhdanov
  5. ##
  6. ## This program is free software; you can redistribute it and/or modify
  7. ## it under the terms of the GNU General Public License as published by
  8. ## the Free Software Foundation; either version 2, or (at your option)
  9. ## any later version.
  10. ##
  11. ## This program is distributed in the hope that it will be useful,
  12. ## but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. ## GNU General Public License for more details.
  15. __version__="$Id"
  16. """
  17. When your handler is called it is getting the session instance as the first argument.
  18. This is the difference from xmpppy 0.1 where you got the "Client" instance.
  19. With Session class you can have "multi-session" client instead of having
  20. one client for each connection. Is is specifically important when you are
  21. writing the server.
  22. """
  23. from .protocol import *
  24. # Transport-level flags
  25. SOCKET_UNCONNECTED =0
  26. SOCKET_ALIVE =1
  27. SOCKET_DEAD =2
  28. # XML-level flags
  29. STREAM__NOT_OPENED =1
  30. STREAM__OPENED =2
  31. STREAM__CLOSING =3
  32. STREAM__CLOSED =4
  33. # XMPP-session flags
  34. SESSION_NOT_AUTHED =1
  35. SESSION_AUTHED =2
  36. SESSION_BOUND =3
  37. SESSION_OPENED =4
  38. SESSION_CLOSED =5
  39. class Session:
  40. """
  41. The Session class instance is used for storing all session-related info like
  42. credentials, socket/xml stream/session state flags, roster items (in case of
  43. client type connection) etc.
  44. Session object have no means of discovering is any info is ready to be read.
  45. Instead you should use poll() (recomended) or select() methods for this purpose.
  46. Session can be one of two types: 'server' and 'client'. 'server' session handles
  47. inbound connection and 'client' one used to create an outbound one.
  48. Session instance have multitude of internal attributes. The most imporant is the 'peer' one.
  49. It is set once the peer is authenticated (client).
  50. """
  51. def __init__(self,socket,owner,xmlns=None,peer=None):
  52. """ When the session is created it's type (client/server) is determined from the beginning.
  53. socket argument is the pre-created socket-like object.
  54. It must have the following methods: send, recv, fileno, close.
  55. owner is the 'master' instance that have Dispatcher plugged into it and generally
  56. will take care about all session events.
  57. xmlns is the stream namespace that will be used. Client must set this argument
  58. If server sets this argument than stream will be dropped if opened with some another namespace.
  59. peer is the name of peer instance. This is the flag that differentiates client session from
  60. server session. Client must set it to the name of the server that will be connected, server must
  61. leave this argument alone.
  62. """
  63. self.xmlns=xmlns
  64. if peer:
  65. self.TYP='client'
  66. self.peer=peer
  67. self._socket_state=SOCKET_UNCONNECTED
  68. else:
  69. self.TYP='server'
  70. self.peer=None
  71. self._socket_state=SOCKET_ALIVE
  72. self._sock=socket
  73. self._send=socket.send
  74. self._recv=socket.recv
  75. self.fileno=socket.fileno
  76. self._registered=0
  77. self.Dispatcher=owner.Dispatcher
  78. self.DBG_LINE='session'
  79. self.DEBUG=owner.Dispatcher.DEBUG
  80. self._expected={}
  81. self._owner=owner
  82. if self.TYP=='server': self.ID=repr(random.random())[2:]
  83. else: self.ID=None
  84. self.sendbuffer=''
  85. self._stream_pos_queued=None
  86. self._stream_pos_sent=0
  87. self.deliver_key_queue=[]
  88. self.deliver_queue_map={}
  89. self.stanza_queue=[]
  90. self._session_state=SESSION_NOT_AUTHED
  91. self.waiting_features=[]
  92. for feature in [NS_TLS,NS_SASL,NS_BIND,NS_SESSION]:
  93. if feature in owner.features: self.waiting_features.append(feature)
  94. self.features=[]
  95. self.feature_in_process=None
  96. self.slave_session=None
  97. self.StartStream()
  98. def StartStream(self):
  99. """ This method is used to initialise the internal xml expat parser
  100. and to send initial stream header (in case of client connection).
  101. Should be used after initial connection and after every stream restart."""
  102. self._stream_state=STREAM__NOT_OPENED
  103. self.Stream=simplexml.NodeBuilder()
  104. self.Stream._dispatch_depth=2
  105. self.Stream.dispatch=self._dispatch
  106. self.Parse=self.Stream.Parse
  107. self.Stream.stream_footer_received=self._stream_close
  108. if self.TYP=='client':
  109. self.Stream.stream_header_received=self._catch_stream_id
  110. self._stream_open()
  111. else:
  112. self.Stream.stream_header_received=self._stream_open
  113. def receive(self):
  114. """ Reads all pending incoming data.
  115. Raises IOError on disconnection.
  116. Blocks until at least one byte is read."""
  117. try: received = self._recv(10240)
  118. except: received = ''
  119. if len(received): # length of 0 means disconnect
  120. self.DEBUG(repr(self.fileno())+' '+received,'got')
  121. else:
  122. self.DEBUG('Socket error while receiving data','error')
  123. self.set_socket_state(SOCKET_DEAD)
  124. raise IOError("Peer disconnected")
  125. return received
  126. def sendnow(self,chunk):
  127. """ Put chunk into "immidiatedly send" queue.
  128. Should only be used for auth/TLS stuff and like.
  129. If you just want to shedule regular stanza for delivery use enqueue method.
  130. """
  131. if isinstance(chunk,Node): chunk = chunk.__str__().encode('utf-8')
  132. elif type(chunk)==type(''): chunk = chunk.encode('utf-8')
  133. self.enqueue(chunk)
  134. def enqueue(self,stanza):
  135. """ Takes Protocol instance as argument.
  136. Puts stanza into "send" fifo queue. Items into the send queue are hold until
  137. stream authenticated. After that this method is effectively the same as "sendnow" method."""
  138. if isinstance(stanza,Protocol):
  139. self.stanza_queue.append(stanza)
  140. else: self.sendbuffer+=stanza
  141. if self._socket_state>=SOCKET_ALIVE: self.push_queue()
  142. def push_queue(self,failreason=ERR_RECIPIENT_UNAVAILABLE):
  143. """ If stream is authenticated than move items from "send" queue to "immidiatedly send" queue.
  144. Else if the stream is failed then return all queued stanzas with error passed as argument.
  145. Otherwise do nothing."""
  146. # If the stream authed - convert stanza_queue into sendbuffer and set the checkpoints
  147. if self._stream_state>=STREAM__CLOSED or self._socket_state>=SOCKET_DEAD: # the stream failed. Return all stanzas that are still waiting for delivery.
  148. self._owner.deactivatesession(self)
  149. for key in self.deliver_key_queue: # Not sure. May be I
  150. self._dispatch(Error(self.deliver_queue_map[key],failreason),trusted=1) # should simply re-dispatch it?
  151. for stanza in self.stanza_queue: # But such action can invoke
  152. self._dispatch(Error(stanza,failreason),trusted=1) # Infinite loops in case of S2S connection...
  153. self.deliver_queue_map,self.deliver_key_queue,self.stanza_queue={},[],[]
  154. return
  155. elif self._session_state>=SESSION_AUTHED: # FIXME!
  156. #### LOCK_QUEUE
  157. for stanza in self.stanza_queue:
  158. txt=stanza.__str__().encode('utf-8')
  159. self.sendbuffer+=txt
  160. self._stream_pos_queued+=len(txt) # should be re-evaluated for SSL connection.
  161. self.deliver_queue_map[self._stream_pos_queued]=stanza # position of the stream when stanza will be successfully and fully sent
  162. self.deliver_key_queue.append(self._stream_pos_queued)
  163. self.stanza_queue=[]
  164. #### UNLOCK_QUEUE
  165. def flush_queue(self):
  166. """ Put the "immidiatedly send" queue content on the wire. Blocks until at least one byte sent."""
  167. if self.sendbuffer:
  168. try:
  169. # LOCK_QUEUE
  170. sent=self._send(self.sendbuffer)
  171. except:
  172. # UNLOCK_QUEUE
  173. self.set_socket_state(SOCKET_DEAD)
  174. self.DEBUG("Socket error while sending data",'error')
  175. return self.terminate_stream()
  176. self.DEBUG(repr(self.fileno())+' '+self.sendbuffer[:sent],'sent')
  177. self._stream_pos_sent+=sent
  178. self.sendbuffer=self.sendbuffer[sent:]
  179. self._stream_pos_delivered=self._stream_pos_sent # Should be acquired from socket somehow. Take SSL into account.
  180. while self.deliver_key_queue and self._stream_pos_delivered>self.deliver_key_queue[0]:
  181. del self.deliver_queue_map[self.deliver_key_queue[0]]
  182. self.deliver_key_queue.remove(self.deliver_key_queue[0])
  183. # UNLOCK_QUEUE
  184. def _dispatch(self,stanza,trusted=0):
  185. """ This is callback that is used to pass the received stanza forth to owner's dispatcher
  186. _if_ the stream is authorised. Otherwise the stanza is just dropped.
  187. The 'trusted' argument is used to emulate stanza receive.
  188. This method is used internally.
  189. """
  190. self._owner.packets+=1
  191. if self._stream_state==STREAM__OPENED or trusted: # if the server really should reject all stanzas after he is closed stream (himeself)?
  192. self.DEBUG(stanza.__str__(),'dispatch')
  193. stanza.trusted=trusted
  194. return self.Dispatcher.dispatch(stanza,self)
  195. def _catch_stream_id(self,ns=None,tag='stream',attrs={}):
  196. """ This callback is used to detect the stream namespace of incoming stream. Used internally. """
  197. if 'id' not in attrs or not attrs['id']:
  198. return self.terminate_stream(STREAM_INVALID_XML)
  199. self.ID=attrs['id']
  200. if 'version' not in attrs: self._owner.Dialback(self)
  201. def _stream_open(self,ns=None,tag='stream',attrs={}):
  202. """ This callback is used to handle opening stream tag of the incoming stream.
  203. In the case of client session it just make some validation.
  204. Server session also sends server headers and if the stream valid the features node.
  205. Used internally. """
  206. text='<?xml version="1.0" encoding="utf-8"?>\n<stream:stream'
  207. if self.TYP=='client':
  208. text+=' to="%s"'%self.peer
  209. else:
  210. text+=' id="%s"'%self.ID
  211. if 'to' not in attrs: text+=' from="%s"'%self._owner.servernames[0]
  212. else: text+=' from="%s"'%attrs['to']
  213. if 'xml:lang' in attrs: text+=' xml:lang="%s"'%attrs['xml:lang']
  214. if self.xmlns: xmlns=self.xmlns
  215. else: xmlns=NS_SERVER
  216. text+=' xmlns:db="%s" xmlns:stream="%s" xmlns="%s"'%(NS_DIALBACK,NS_STREAMS,xmlns)
  217. if 'version' in attrs or self.TYP=='client': text+=' version="1.0"'
  218. self.sendnow(text+'>')
  219. self.set_stream_state(STREAM__OPENED)
  220. if self.TYP=='client': return
  221. if tag!='stream': return self.terminate_stream(STREAM_INVALID_XML)
  222. if ns!=NS_STREAMS: return self.terminate_stream(STREAM_INVALID_NAMESPACE)
  223. if self.Stream.xmlns!=self.xmlns: return self.terminate_stream(STREAM_BAD_NAMESPACE_PREFIX)
  224. if 'to' not in attrs: return self.terminate_stream(STREAM_IMPROPER_ADDRESSING)
  225. if attrs['to'] not in self._owner.servernames: return self.terminate_stream(STREAM_HOST_UNKNOWN)
  226. self.ourname=attrs['to'].lower()
  227. if self.TYP=='server' and 'version' in attrs:
  228. # send features
  229. features=Node('stream:features')
  230. if NS_TLS in self.waiting_features:
  231. features.NT.starttls.setNamespace(NS_TLS)
  232. features.T.starttls.NT.required
  233. if NS_SASL in self.waiting_features:
  234. features.NT.mechanisms.setNamespace(NS_SASL)
  235. for mec in self._owner.SASL.mechanisms:
  236. features.T.mechanisms.NT.mechanism=mec
  237. else:
  238. if NS_BIND in self.waiting_features: features.NT.bind.setNamespace(NS_BIND)
  239. if NS_SESSION in self.waiting_features: features.NT.session.setNamespace(NS_SESSION)
  240. self.sendnow(features)
  241. def feature(self,feature):
  242. """ Declare some stream feature as activated one. """
  243. if feature not in self.features: self.features.append(feature)
  244. self.unfeature(feature)
  245. def unfeature(self,feature):
  246. """ Declare some feature as illegal. Illegal features can not be used.
  247. Example: BIND feature becomes illegal after Non-SASL auth. """
  248. if feature in self.waiting_features: self.waiting_features.remove(feature)
  249. def _stream_close(self,unregister=1):
  250. """ Write the closing stream tag and destroy the underlaying socket. Used internally. """
  251. if self._stream_state>=STREAM__CLOSED: return
  252. self.set_stream_state(STREAM__CLOSING)
  253. self.sendnow('</stream:stream>')
  254. self.set_stream_state(STREAM__CLOSED)
  255. self.push_queue() # decompose queue really since STREAM__CLOSED
  256. self._owner.flush_queues()
  257. if unregister: self._owner.unregistersession(self)
  258. self._destroy_socket()
  259. def terminate_stream(self,error=None,unregister=1):
  260. """ Notify the peer about stream closure.
  261. Ensure that xmlstream is not brokes - i.e. if the stream isn't opened yet -
  262. open it before closure.
  263. If the error condition is specified than create a stream error and send it along with
  264. closing stream tag.
  265. Emulate receiving 'unavailable' type presence just before stream closure.
  266. """
  267. if self._stream_state>=STREAM__CLOSING: return
  268. if self._stream_state<STREAM__OPENED:
  269. self.set_stream_state(STREAM__CLOSING)
  270. self._stream_open()
  271. else:
  272. self.set_stream_state(STREAM__CLOSING)
  273. p=Presence(typ='unavailable')
  274. p.setNamespace(NS_CLIENT)
  275. self._dispatch(p,trusted=1)
  276. if error:
  277. if isinstance(error,Node): self.sendnow(error)
  278. else: self.sendnow(ErrorNode(error))
  279. self._stream_close(unregister=unregister)
  280. if self.slave_session:
  281. self.slave_session.terminate_stream(STREAM_REMOTE_CONNECTION_FAILED)
  282. def _destroy_socket(self):
  283. """ Break cyclic dependancies to let python's GC free memory right now."""
  284. self.Stream.dispatch=None
  285. self.Stream.stream_footer_received=None
  286. self.Stream.stream_header_received=None
  287. self.Stream.destroy()
  288. self._sock.close()
  289. self.set_socket_state(SOCKET_DEAD)
  290. def start_feature(self,f):
  291. """ Declare some feature as "negotiating now" to prevent other features from start negotiating. """
  292. if self.feature_in_process: raise Exception("Starting feature %s over %s !"%(f,self.feature_in_process))
  293. self.feature_in_process=f
  294. def stop_feature(self,f):
  295. """ Declare some feature as "negotiated" to allow other features start negotiating. """
  296. if self.feature_in_process!=f: raise Exception("Stopping feature %s instead of %s !"%(f,self.feature_in_process))
  297. self.feature_in_process=None
  298. def set_socket_state(self,newstate):
  299. """ Change the underlaying socket state.
  300. Socket starts with SOCKET_UNCONNECTED state
  301. and then proceeds (possibly) to SOCKET_ALIVE
  302. and then to SOCKET_DEAD """
  303. if self._socket_state<newstate: self._socket_state=newstate
  304. def set_session_state(self,newstate):
  305. """ Change the session state.
  306. Session starts with SESSION_NOT_AUTHED state
  307. and then comes through
  308. SESSION_AUTHED, SESSION_BOUND, SESSION_OPENED and SESSION_CLOSED states.
  309. """
  310. if self._session_state<newstate:
  311. if self._session_state<SESSION_AUTHED and \
  312. newstate>=SESSION_AUTHED: self._stream_pos_queued=self._stream_pos_sent
  313. self._session_state=newstate
  314. def set_stream_state(self,newstate):
  315. """ Change the underlaying XML stream state
  316. Stream starts with STREAM__NOT_OPENED and then proceeds with
  317. STREAM__OPENED, STREAM__CLOSING and STREAM__CLOSED states.
  318. Note that some features (like TLS and SASL)
  319. requires stream re-start so this state can have non-linear changes. """
  320. if self._stream_state<newstate: self._stream_state=newstate