Package nbxmpp :: Module c14n

[hide private]
[frames] | no frames]

# Source Code for Module nbxmpp.c14n

     1  # -*- coding:utf-8 -*-
     2  ## c14n.py
     3  ##
     4  ## Copyright (C) 2007-2008 Brendan Taylor <whateley AT gmail.com>
     5  ##
     6  ## This file is part of Gajim.
     7  ##
     8  ## Gajim is free software; you can redistribute it and/or modify
     9  ## it under the terms of the GNU General Public License as published
    10  ## by the Free Software Foundation; version 3 only.
    11  ##
    12  ## Gajim is distributed in the hope that it will be useful,
    13  ## but WITHOUT ANY WARRANTY; without even the implied warranty of
    14  ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    15  ## GNU General Public License for more details.
    16  ##
    17  ## You should have received a copy of the GNU General Public License
    18  ## along with Gajim. If not, see <http://www.gnu.org/licenses/>.
    19  ##
    20
    21  """
    22  XML canonicalisation methods (for XEP-0116)
    23  """
    24
    25  from simplexml import ustr
    26
    27 -def c14n(node, is_buggy):
    28      s = "<" + node.name
    29      if node.namespace:
    30          if not node.parent or node.parent.namespace != node.namespace:
    31              s = s + ' xmlns="%s"' % node.namespace
    32
    33      sorted_attrs = sorted(node.attrs.keys())
    34      for key in sorted_attrs:
    35          if not is_buggy and key == 'xmlns':
    36              continue
    37          val = ustr(node.attrs[key])
    38          # like XMLescape() but with whitespace and without &gt;
    39          s = s + ' %s="%s"' % ( key, normalise_attr(val) )
    40      s = s + ">"
    41      cnt = 0
    42      if node.kids:
    43          for a in node.kids:
    44              if (len(node.data)-1) >= cnt:
    45                  s = s + normalise_text(node.data[cnt])
    46              s = s + c14n(a, is_buggy)
    47              cnt=cnt+1
    48      if (len(node.data)-1) >= cnt: s = s + normalise_text(node.data[cnt])
    49      if not node.kids and s.endswith('>'):
    50          s=s[:-1]+' />'
    51      else:
    52          s = s + "</" + node.name + ">"
    53      return s.encode('utf-8')
    54
    55 -def normalise_attr(val):
    56      return val.replace('&', '&amp;').replace('<', '&lt;').replace('"', '&quot;').replace('\t', '&#x9;').replace('\n', '&#xA;').replace('\r', '&#xD;')
    57
    58 -def normalise_text(val):
    59      return val.replace('&', '&amp;').replace('<', '&lt;').replace('>', '&gt;').replace('\r', '&#xD;')
    60