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