error.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  1. # -*- test-case-name: twisted.words.test.test_jabbererror -*-
  2. #
  3. # Copyright (c) Twisted Matrix Laboratories.
  4. # See LICENSE for details.
  5. """
  6. XMPP Error support.
  7. """
  8. from __future__ import absolute_import, division
  9. import copy
  10. from twisted.python.compat import unicode
  11. from twisted.words.xish import domish
  12. NS_XML = "http://www.w3.org/XML/1998/namespace"
  13. NS_XMPP_STREAMS = "urn:ietf:params:xml:ns:xmpp-streams"
  14. NS_XMPP_STANZAS = "urn:ietf:params:xml:ns:xmpp-stanzas"
  15. STANZA_CONDITIONS = {
  16. 'bad-request': {'code': '400', 'type': 'modify'},
  17. 'conflict': {'code': '409', 'type': 'cancel'},
  18. 'feature-not-implemented': {'code': '501', 'type': 'cancel'},
  19. 'forbidden': {'code': '403', 'type': 'auth'},
  20. 'gone': {'code': '302', 'type': 'modify'},
  21. 'internal-server-error': {'code': '500', 'type': 'wait'},
  22. 'item-not-found': {'code': '404', 'type': 'cancel'},
  23. 'jid-malformed': {'code': '400', 'type': 'modify'},
  24. 'not-acceptable': {'code': '406', 'type': 'modify'},
  25. 'not-allowed': {'code': '405', 'type': 'cancel'},
  26. 'not-authorized': {'code': '401', 'type': 'auth'},
  27. 'payment-required': {'code': '402', 'type': 'auth'},
  28. 'recipient-unavailable': {'code': '404', 'type': 'wait'},
  29. 'redirect': {'code': '302', 'type': 'modify'},
  30. 'registration-required': {'code': '407', 'type': 'auth'},
  31. 'remote-server-not-found': {'code': '404', 'type': 'cancel'},
  32. 'remote-server-timeout': {'code': '504', 'type': 'wait'},
  33. 'resource-constraint': {'code': '500', 'type': 'wait'},
  34. 'service-unavailable': {'code': '503', 'type': 'cancel'},
  35. 'subscription-required': {'code': '407', 'type': 'auth'},
  36. 'undefined-condition': {'code': '500', 'type': None},
  37. 'unexpected-request': {'code': '400', 'type': 'wait'},
  38. }
  39. CODES_TO_CONDITIONS = {
  40. '302': ('gone', 'modify'),
  41. '400': ('bad-request', 'modify'),
  42. '401': ('not-authorized', 'auth'),
  43. '402': ('payment-required', 'auth'),
  44. '403': ('forbidden', 'auth'),
  45. '404': ('item-not-found', 'cancel'),
  46. '405': ('not-allowed', 'cancel'),
  47. '406': ('not-acceptable', 'modify'),
  48. '407': ('registration-required', 'auth'),
  49. '408': ('remote-server-timeout', 'wait'),
  50. '409': ('conflict', 'cancel'),
  51. '500': ('internal-server-error', 'wait'),
  52. '501': ('feature-not-implemented', 'cancel'),
  53. '502': ('service-unavailable', 'wait'),
  54. '503': ('service-unavailable', 'cancel'),
  55. '504': ('remote-server-timeout', 'wait'),
  56. '510': ('service-unavailable', 'cancel'),
  57. }
  58. class BaseError(Exception):
  59. """
  60. Base class for XMPP error exceptions.
  61. @cvar namespace: The namespace of the C{error} element generated by
  62. C{getElement}.
  63. @type namespace: C{str}
  64. @ivar condition: The error condition. The valid values are defined by
  65. subclasses of L{BaseError}.
  66. @type contition: C{str}
  67. @ivar text: Optional text message to supplement the condition or application
  68. specific condition.
  69. @type text: C{unicode}
  70. @ivar textLang: Identifier of the language used for the message in C{text}.
  71. Values are as described in RFC 3066.
  72. @type textLang: C{str}
  73. @ivar appCondition: Application specific condition element, supplementing
  74. the error condition in C{condition}.
  75. @type appCondition: object providing L{domish.IElement}.
  76. """
  77. namespace = None
  78. def __init__(self, condition, text=None, textLang=None, appCondition=None):
  79. Exception.__init__(self)
  80. self.condition = condition
  81. self.text = text
  82. self.textLang = textLang
  83. self.appCondition = appCondition
  84. def __str__(self):
  85. message = "%s with condition %r" % (self.__class__.__name__,
  86. self.condition)
  87. if self.text:
  88. message += ': ' + self.text
  89. return message
  90. def getElement(self):
  91. """
  92. Get XML representation from self.
  93. The method creates an L{domish} representation of the
  94. error data contained in this exception.
  95. @rtype: L{domish.Element}
  96. """
  97. error = domish.Element((None, 'error'))
  98. error.addElement((self.namespace, self.condition))
  99. if self.text:
  100. text = error.addElement((self.namespace, 'text'),
  101. content=self.text)
  102. if self.textLang:
  103. text[(NS_XML, 'lang')] = self.textLang
  104. if self.appCondition:
  105. error.addChild(self.appCondition)
  106. return error
  107. class StreamError(BaseError):
  108. """
  109. Stream Error exception.
  110. Refer to RFC 3920, section 4.7.3, for the allowed values for C{condition}.
  111. """
  112. namespace = NS_XMPP_STREAMS
  113. def getElement(self):
  114. """
  115. Get XML representation from self.
  116. Overrides the base L{BaseError.getElement} to make sure the returned
  117. element is in the XML Stream namespace.
  118. @rtype: L{domish.Element}
  119. """
  120. from twisted.words.protocols.jabber.xmlstream import NS_STREAMS
  121. error = BaseError.getElement(self)
  122. error.uri = NS_STREAMS
  123. return error
  124. class StanzaError(BaseError):
  125. """
  126. Stanza Error exception.
  127. Refer to RFC 3920, section 9.3, for the allowed values for C{condition} and
  128. C{type}.
  129. @ivar type: The stanza error type. Gives a suggestion to the recipient
  130. of the error on how to proceed.
  131. @type type: C{str}
  132. @ivar code: A numeric identifier for the error condition for backwards
  133. compatibility with pre-XMPP Jabber implementations.
  134. """
  135. namespace = NS_XMPP_STANZAS
  136. def __init__(self, condition, type=None, text=None, textLang=None,
  137. appCondition=None):
  138. BaseError.__init__(self, condition, text, textLang, appCondition)
  139. if type is None:
  140. try:
  141. type = STANZA_CONDITIONS[condition]['type']
  142. except KeyError:
  143. pass
  144. self.type = type
  145. try:
  146. self.code = STANZA_CONDITIONS[condition]['code']
  147. except KeyError:
  148. self.code = None
  149. self.children = []
  150. self.iq = None
  151. def getElement(self):
  152. """
  153. Get XML representation from self.
  154. Overrides the base L{BaseError.getElement} to make sure the returned
  155. element has a C{type} attribute and optionally a legacy C{code}
  156. attribute.
  157. @rtype: L{domish.Element}
  158. """
  159. error = BaseError.getElement(self)
  160. error['type'] = self.type
  161. if self.code:
  162. error['code'] = self.code
  163. return error
  164. def toResponse(self, stanza):
  165. """
  166. Construct error response stanza.
  167. The C{stanza} is transformed into an error response stanza by
  168. swapping the C{to} and C{from} addresses and inserting an error
  169. element.
  170. @note: This creates a shallow copy of the list of child elements of the
  171. stanza. The child elements themselves are not copied themselves,
  172. and references to their parent element will still point to the
  173. original stanza element.
  174. The serialization of an element does not use the reference to
  175. its parent, so the typical use case of immediately sending out
  176. the constructed error response is not affected.
  177. @param stanza: the stanza to respond to
  178. @type stanza: L{domish.Element}
  179. """
  180. from twisted.words.protocols.jabber.xmlstream import toResponse
  181. response = toResponse(stanza, stanzaType='error')
  182. response.children = copy.copy(stanza.children)
  183. response.addChild(self.getElement())
  184. return response
  185. def _parseError(error, errorNamespace):
  186. """
  187. Parses an error element.
  188. @param error: The error element to be parsed
  189. @type error: L{domish.Element}
  190. @param errorNamespace: The namespace of the elements that hold the error
  191. condition and text.
  192. @type errorNamespace: C{str}
  193. @return: Dictionary with extracted error information. If present, keys
  194. C{condition}, C{text}, C{textLang} have a string value,
  195. and C{appCondition} has an L{domish.Element} value.
  196. @rtype: C{dict}
  197. """
  198. condition = None
  199. text = None
  200. textLang = None
  201. appCondition = None
  202. for element in error.elements():
  203. if element.uri == errorNamespace:
  204. if element.name == 'text':
  205. text = unicode(element)
  206. textLang = element.getAttribute((NS_XML, 'lang'))
  207. else:
  208. condition = element.name
  209. else:
  210. appCondition = element
  211. return {
  212. 'condition': condition,
  213. 'text': text,
  214. 'textLang': textLang,
  215. 'appCondition': appCondition,
  216. }
  217. def exceptionFromStreamError(element):
  218. """
  219. Build an exception object from a stream error.
  220. @param element: the stream error
  221. @type element: L{domish.Element}
  222. @return: the generated exception object
  223. @rtype: L{StreamError}
  224. """
  225. error = _parseError(element, NS_XMPP_STREAMS)
  226. exception = StreamError(error['condition'],
  227. error['text'],
  228. error['textLang'],
  229. error['appCondition'])
  230. return exception
  231. def exceptionFromStanza(stanza):
  232. """
  233. Build an exception object from an error stanza.
  234. @param stanza: the error stanza
  235. @type stanza: L{domish.Element}
  236. @return: the generated exception object
  237. @rtype: L{StanzaError}
  238. """
  239. children = []
  240. condition = text = textLang = appCondition = type = code = None
  241. for element in stanza.elements():
  242. if element.name == 'error' and element.uri == stanza.uri:
  243. code = element.getAttribute('code')
  244. type = element.getAttribute('type')
  245. error = _parseError(element, NS_XMPP_STANZAS)
  246. condition = error['condition']
  247. text = error['text']
  248. textLang = error['textLang']
  249. appCondition = error['appCondition']
  250. if not condition and code:
  251. condition, type = CODES_TO_CONDITIONS[code]
  252. text = unicode(stanza.error)
  253. else:
  254. children.append(element)
  255. if condition is None:
  256. # TODO: raise exception instead?
  257. return StanzaError(None)
  258. exception = StanzaError(condition, type, text, textLang, appCondition)
  259. exception.children = children
  260. exception.stanza = stanza
  261. return exception