00001 """
00002 XML utilities.
00003
00004 $Id: xml_utils.py 2583 2009-07-06 14:07:05Z sra $
00005
00006 Copyright (C) 2009 Internet Systems Consortium ("ISC")
00007
00008 Permission to use, copy, modify, and distribute this software for any
00009 purpose with or without fee is hereby granted, provided that the above
00010 copyright notice and this permission notice appear in all copies.
00011
00012 THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
00013 REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
00014 AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
00015 INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
00016 LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
00017 OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
00018 PERFORMANCE OF THIS SOFTWARE.
00019
00020 Portions copyright (C) 2007--2008 American Registry for Internet Numbers ("ARIN")
00021
00022 Permission to use, copy, modify, and distribute this software for any
00023 purpose with or without fee is hereby granted, provided that the above
00024 copyright notice and this permission notice appear in all copies.
00025
00026 THE SOFTWARE IS PROVIDED "AS IS" AND ARIN DISCLAIMS ALL WARRANTIES WITH
00027 REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
00028 AND FITNESS. IN NO EVENT SHALL ARIN BE LIABLE FOR ANY SPECIAL, DIRECT,
00029 INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
00030 LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
00031 OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
00032 PERFORMANCE OF THIS SOFTWARE.
00033 """
00034
00035 import xml.sax, lxml.sax, lxml.etree, base64
00036 import rpki.exceptions
00037
00038 class sax_handler(xml.sax.handler.ContentHandler):
00039 """
00040 SAX handler for RPKI protocols.
00041
00042 This class provides some basic amenities for parsing protocol XML of
00043 the kind we use in the RPKI protocols, including whacking all the
00044 protocol element text into US-ASCII, simplifying accumulation of
00045 text fields, and hiding some of the fun relating to XML namespaces.
00046
00047 General assumption: by the time this parsing code gets invoked, the
00048 XML has already passed RelaxNG validation, so we only have to check
00049 for errors that the schema can't catch, and we don't have to play as
00050 many XML namespace games.
00051 """
00052
00053 def __init__(self):
00054 """
00055 Initialize SAX handler.
00056 """
00057 xml.sax.handler.ContentHandler.__init__(self)
00058 self.text = ""
00059 self.stack = []
00060
00061 def startElementNS(self, name, qname, attrs):
00062 """Redirect startElementNS() events to startElement()."""
00063 return self.startElement(name[1], attrs)
00064
00065 def endElementNS(self, name, qname):
00066 """Redirect endElementNS() events to endElement()."""
00067 return self.endElement(name[1])
00068
00069 def characters(self, content):
00070 """Accumulate a chuck of element content (text)."""
00071 self.text += content
00072
00073 def startElement(self, name, attrs):
00074 """
00075 Handle startElement() events.
00076
00077 We maintain a stack of nested elements under construction so that
00078 we can feed events directly to the current element rather than
00079 having to pass them through all the nesting elements.
00080
00081 If the stack is empty, this event is for the outermost element, so
00082 we call a virtual method to create the corresponding object and
00083 that's the object we'll be returning as our final result.
00084 """
00085
00086 a = dict()
00087 for k, v in attrs.items():
00088 if isinstance(k, tuple):
00089 if k == ("http://www.w3.org/XML/1998/namespace", "lang"):
00090 k = "xml:lang"
00091 else:
00092 assert k[0] is None
00093 k = k[1]
00094 a[k.encode("ascii")] = v.encode("ascii")
00095 if len(self.stack) == 0:
00096 assert not hasattr(self, "result")
00097 self.result = self.create_top_level(name, a)
00098 self.stack.append(self.result)
00099 self.stack[-1].startElement(self.stack, name, a)
00100
00101 def endElement(self, name):
00102 """
00103 Handle endElement() events. Mostly this means handling any
00104 accumulated element text.
00105 """
00106 text = self.text.encode("ascii").strip()
00107 self.text = ""
00108 self.stack[-1].endElement(self.stack, name, text)
00109
00110 @classmethod
00111 def saxify(cls, elt):
00112 """
00113 Create a one-off SAX parser, parse an ETree, return the result.
00114 """
00115 self = cls()
00116 lxml.sax.saxify(elt, self)
00117 return self.result
00118
00119 def create_top_level(self, name, attrs):
00120 """
00121 Handle top-level PDU for this protocol.
00122 """
00123 assert name == self.name and attrs["version"] == self.version
00124 return self.pdu()
00125
00126 class base_elt(object):
00127 """
00128 Virtual base class for XML message elements. The left-right and
00129 publication protocols use this. At least for now, the up-down
00130 protocol does not, due to different design assumptions.
00131 """
00132
00133
00134
00135 attributes = ()
00136
00137
00138
00139 elements = ()
00140
00141
00142
00143 booleans = ()
00144
00145 def startElement(self, stack, name, attrs):
00146 """
00147 Default startElement() handler: just process attributes.
00148 """
00149 if name not in self.elements:
00150 assert name == self.element_name, "Unexpected name %s, stack %s" % (name, stack)
00151 self.read_attrs(attrs)
00152
00153 def endElement(self, stack, name, text):
00154 """
00155 Default endElement() handler: just pop the stack.
00156 """
00157 assert name == self.element_name, "Unexpected name %s, stack %s" % (name, stack)
00158 stack.pop()
00159
00160 def toXML(self):
00161 """
00162 Default toXML() element generator.
00163 """
00164 return self.make_elt()
00165
00166 def read_attrs(self, attrs):
00167 """
00168 Template-driven attribute reader.
00169 """
00170 for key in self.attributes:
00171 val = attrs.get(key, None)
00172 if isinstance(val, str) and val.isdigit():
00173 val = long(val)
00174 setattr(self, key, val)
00175 for key in self.booleans:
00176 setattr(self, key, attrs.get(key, False))
00177
00178 def make_elt(self):
00179 """
00180 XML element constructor.
00181 """
00182 elt = lxml.etree.Element("{%s}%s" % (self.xmlns, self.element_name), nsmap = self.nsmap)
00183 for key in self.attributes:
00184 val = getattr(self, key, None)
00185 if val is not None:
00186 elt.set(key, str(val))
00187 for key in self.booleans:
00188 if getattr(self, key, False):
00189 elt.set(key, "yes")
00190 return elt
00191
00192 def make_b64elt(self, elt, name, value = None):
00193 """
00194 Constructor for Base64-encoded subelement.
00195 """
00196 if value is None:
00197 value = getattr(self, name, None)
00198 if value is not None:
00199 lxml.etree.SubElement(elt, "{%s}%s" % (self.xmlns, name), nsmap = self.nsmap).text = base64.b64encode(value)
00200
00201 def __str__(self):
00202 """
00203 Convert a base_elt object to string format.
00204 """
00205 lxml.etree.tostring(self.toXML(), pretty_print = True, encoding = "us-ascii")
00206
00207 @classmethod
00208 def make_pdu(cls, **kargs):
00209 """
00210 Generic PDU constructor.
00211 """
00212 self = cls()
00213 for k, v in kargs.items():
00214 if isinstance(v, bool):
00215 v = 1 if v else 0
00216 setattr(self, k, v)
00217 return self
00218
00219 class data_elt(base_elt):
00220 """
00221 Virtual base class for PDUs that map to SQL objects. These objects
00222 all implement the create/set/get/list/destroy action attribute.
00223 """
00224
00225 def endElement(self, stack, name, text):
00226 """
00227 Default endElement handler for SQL-based objects. This assumes
00228 that sub-elements are Base64-encoded using the sql_template
00229 mechanism.
00230 """
00231 if name in self.elements:
00232 elt_type = self.sql_template.map.get(name)
00233 assert elt_type is not None, "Couldn't find element type for %s, stack %s" % (name, stack)
00234 setattr(self, name, elt_type(Base64 = text))
00235 else:
00236 assert name == self.element_name, "Unexpected name %s, stack %s" % (name, stack)
00237 stack.pop()
00238
00239 def toXML(self):
00240 """
00241 Default element generator for SQL-based objects. This assumes
00242 that sub-elements are Base64-encoded DER objects.
00243 """
00244 elt = self.make_elt()
00245 for i in self.elements:
00246 x = getattr(self, i, None)
00247 if x and not x.empty():
00248 self.make_b64elt(elt, i, x.get_DER())
00249 return elt
00250
00251 def make_reply(self, r_pdu = None):
00252 """
00253 Construct a reply PDU.
00254 """
00255 if r_pdu is None:
00256 r_pdu = self.__class__()
00257 self.make_reply_clone_hook(r_pdu)
00258 handle_name = self.element_name + "_handle"
00259 setattr(r_pdu, handle_name, getattr(self, handle_name, None))
00260 else:
00261 self.make_reply_clone_hook(r_pdu)
00262 for b in r_pdu.booleans:
00263 setattr(r_pdu, b, False)
00264 r_pdu.action = self.action
00265 r_pdu.tag = self.tag
00266 return r_pdu
00267
00268 def make_reply_clone_hook(self, r_pdu):
00269 """Overridable hook."""
00270 pass
00271
00272 def serve_fetch_one(self):
00273 """
00274 Find the object on which a get, set, or destroy method should
00275 operate.
00276 """
00277 r = self.serve_fetch_one_maybe()
00278 if r is None:
00279 raise rpki.exceptions.NotFound
00280 return r
00281
00282 def serve_pre_save_hook(self, q_pdu, r_pdu, cb, eb):
00283 """Overridable hook."""
00284 cb()
00285
00286 def serve_post_save_hook(self, q_pdu, r_pdu, cb, eb):
00287 """Overridable hook."""
00288 cb()
00289
00290 def serve_create(self, r_msg, cb, eb):
00291 """
00292 Handle a create action.
00293 """
00294
00295 r_pdu = self.make_reply()
00296
00297 def one():
00298 self.sql_store()
00299 setattr(r_pdu, self.sql_template.index, getattr(self, self.sql_template.index))
00300 self.serve_post_save_hook(self, r_pdu, two, eb)
00301
00302 def two():
00303 r_msg.append(r_pdu)
00304 cb()
00305
00306 if self.serve_fetch_one_maybe() is not None:
00307 raise rpki.exceptions.DuplicateObject
00308
00309 self.serve_pre_save_hook(self, r_pdu, one, eb)
00310
00311 def serve_set(self, r_msg, cb, eb):
00312 """
00313 Handle a set action.
00314 """
00315
00316 db_pdu = self.serve_fetch_one()
00317 r_pdu = self.make_reply()
00318 for a in db_pdu.sql_template.columns[1:]:
00319 v = getattr(self, a, None)
00320 if v is not None:
00321 setattr(db_pdu, a, v)
00322 db_pdu.sql_mark_dirty()
00323
00324 def one():
00325 db_pdu.sql_store()
00326 db_pdu.serve_post_save_hook(self, r_pdu, two, eb)
00327
00328 def two():
00329 r_msg.append(r_pdu)
00330 cb()
00331
00332 db_pdu.serve_pre_save_hook(self, r_pdu, one, eb)
00333
00334 def serve_get(self, r_msg, cb, eb):
00335 """
00336 Handle a get action.
00337 """
00338 r_pdu = self.serve_fetch_one()
00339 self.make_reply(r_pdu)
00340 r_msg.append(r_pdu)
00341 cb()
00342
00343 def serve_list(self, r_msg, cb, eb):
00344 """
00345 Handle a list action for non-self objects.
00346 """
00347 for r_pdu in self.serve_fetch_all():
00348 self.make_reply(r_pdu)
00349 r_msg.append(r_pdu)
00350 cb()
00351
00352 def serve_destroy(self, r_msg, cb, eb):
00353 """
00354 Handle a destroy action.
00355 """
00356 db_pdu = self.serve_fetch_one()
00357 db_pdu.sql_delete()
00358 r_msg.append(self.make_reply())
00359 cb()
00360
00361 def serve_dispatch(self, r_msg, cb, eb):
00362 """
00363 Action dispatch handler.
00364 """
00365 dispatch = { "create" : self.serve_create,
00366 "set" : self.serve_set,
00367 "get" : self.serve_get,
00368 "list" : self.serve_list,
00369 "destroy" : self.serve_destroy }
00370 if self.action not in dispatch:
00371 raise rpki.exceptions.BadQuery, "Unexpected query: action %s" % self.action
00372 dispatch[self.action](r_msg, cb, eb)
00373
00374 def unimplemented_control(self, *controls):
00375 """
00376 Uniform handling for unimplemented control operations.
00377 """
00378 unimplemented = [x for x in controls if getattr(self, x, False)]
00379 if unimplemented:
00380 raise rpki.exceptions.NotImplementedYet, "Unimplemented control %s" % ", ".join(unimplemented)
00381
00382 class msg(list):
00383 """
00384 Generic top-level PDU.
00385 """
00386
00387 def startElement(self, stack, name, attrs):
00388 """
00389 Handle top-level PDU.
00390 """
00391 if name == "msg":
00392 assert self.version == int(attrs["version"])
00393 self.type = attrs["type"]
00394 else:
00395 elt = self.pdus[name]()
00396 self.append(elt)
00397 stack.append(elt)
00398 elt.startElement(stack, name, attrs)
00399
00400 def endElement(self, stack, name, text):
00401 """
00402 Handle top-level PDU.
00403 """
00404 assert name == "msg", "Unexpected name %s, stack %s" % (name, stack)
00405 assert len(stack) == 1
00406 stack.pop()
00407
00408 def __str__(self):
00409 """Convert msg object to string."""
00410 lxml.etree.tostring(self.toXML(), pretty_print = True, encoding = "us-ascii")
00411
00412 def toXML(self):
00413 """
00414 Generate top-level PDU.
00415 """
00416 elt = lxml.etree.Element("{%s}msg" % (self.xmlns), nsmap = self.nsmap, version = str(self.version), type = self.type)
00417 elt.extend([i.toXML() for i in self])
00418 return elt
00419
00420 @classmethod
00421 def query(cls, *args):
00422 """Create a query PDU."""
00423 self = cls(*args)
00424 self.type = "query"
00425 return self
00426
00427 @classmethod
00428 def reply(cls, *args):
00429 """Create a reply PDU."""
00430 self = cls(*args)
00431 self.type = "reply"
00432 return self
00433
00434 def is_query(self):
00435 """Is this msg a query?"""
00436 return self.type == "query"
00437
00438 def is_reply(self):
00439 """Is this msg a reply?"""
00440 return self.type == "reply"