View source with raw comments or as raw
    1/*  Part of SWI-Prolog
    2
    3    Author:        Jan Wielemaker and Matt Lilley
    4    E-mail:        J.Wielemaker@vu.nl
    5    WWW:           http://www.swi-prolog.org
    6    Copyright (c)  2016, CWI Amsterdam
    7    All rights reserved.
    8
    9    Redistribution and use in source and binary forms, with or without
   10    modification, are permitted provided that the following conditions
   11    are met:
   12
   13    1. Redistributions of source code must retain the above copyright
   14       notice, this list of conditions and the following disclaimer.
   15
   16    2. Redistributions in binary form must reproduce the above copyright
   17       notice, this list of conditions and the following disclaimer in
   18       the documentation and/or other materials provided with the
   19       distribution.
   20
   21    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
   22    "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
   23    LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
   24    FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
   25    COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
   26    INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
   27    BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
   28    LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
   29    CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
   30    LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
   31    ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
   32    POSSIBILITY OF SUCH DAMAGE.
   33*/
   34
   35:- module(c14n2,
   36          [ xml_write_canonical/3       % +Stream, +Term, +Options
   37          ]).   38:- autoload(library(apply),
   39            [partition/4,maplist/3,foldl/4,include/3]).   40:- autoload(library(error),
   41            [instantiation_error/1,must_be/2,existence_error/2]).   42:- autoload(library(lists),[member/2,append/3]).   43:- autoload(library(option),[option/3]).   44:- autoload(library(pairs),[pairs_values/2]).   45:- autoload(library(sgml_write),[xml_write/3]).

C14n2 canonical XML documents

C14n2 specifies a canonical XML document. This library writes such a document from an XML DOM as returned by the XML (or SGML) parser. The process takes two steps:

 xml_write_canonical(+Stream, +DOM, +Options) is det
Write an XML DOM using the canonical conventions as defined by C14n2. Namespace declarations in the canonical document depend on the original namespace declarations. For this reason the input document must be parsed (see load_structure/3) using the dialect xmlns and the option keep_prefix(true). Options:
method(+URI)
One of `http://www.w3.org/TR/2001/REC-xml-c14n-20010315` (inclusive, default), `http://www.w3.org/2006/12/xml-c14n11` (handled as inclusive) or `http://www.w3.org/2001/10/xml-exc-c14n#` (exclusive).
   71xml_write_canonical(Stream, DOM, Options) :-
   72    option(method(Method), Options,
   73           'http://www.w3.org/TR/2001/REC-xml-c14n-20010315'),
   74    method_mode(Method, Mode),
   75    xml_canonical_dom(DOM, CDOM, ctx(Mode, ns{}, ns{})),
   76    xml_write(Stream, CDOM,
   77              [ header(false),
   78                layout(false),
   79                net(false)
   80              ]).
   81
   82method_mode('http://www.w3.org/TR/2001/REC-xml-c14n-20010315', inclusive).
   83method_mode('http://www.w3.org/2006/12/xml-c14n11', inclusive).
   84method_mode('http://www.w3.org/2001/10/xml-exc-c14n#', exclusive).
 xml_canonical_dom(+DOM, -CDOM, +Context)
Context is a term ctx(Mode, InScope, Rendered), where InScope is a dict mapping prefixes to namespace URIs that are in scope and Rendered is a dict mapping the prefixes that are declared by the output ancestors. The default namespace uses the prefix ''.

For inclusive canonicalization, an element declares each in-scope namespace that is not declared with the same URI by its output ancestors. For exclusive canonicalization, it only does so for the namespaces that are visibly utilized by the element name and its attributes. Namespace declarations are ordered by prefix, the default namespace first. Attributes are ordered by namespace URI and local name, attributes without a namespace first.

  101xml_canonical_dom(Var, _, _) :-
  102    var(Var),
  103    !,
  104    instantiation_error(Var).
  105xml_canonical_dom(DOM, CDOM, Ctx) :-
  106    is_list(DOM),
  107    !,
  108    xml_canonical_list(DOM, CDOM, Ctx).
  109xml_canonical_dom(element(Name, Attrs, Content),
  110                  element(CName, CAttrs, CContent),
  111                  ctx(Mode, InScope0, Rendered0)) :-
  112    !,
  113    must_be(list, Attrs),
  114    must_be(list, Content),
  115    partition(ns_decl, Attrs, Decls, Attrs1),
  116    foldl(add_decl, Decls, InScope0, InScope),
  117    element_name(Name, InScope, EPrefix, ELocal, EURI),
  118    maplist(attribute_parts(InScope), Attrs1, AttrParts),
  119    utilized(EPrefix-EURI, AttrParts, Utilized),
  120    (   Mode == inclusive
  121    ->  dict_pairs(InScope, _, InScopePairs),
  122        append(Utilized, InScopePairs, Candidates0) % Utilized has priority
  123    ;   Candidates0 = Utilized
  124    ),
  125    sort(1, @<, Candidates0, Candidates),
  126    include(must_render(Rendered0), Candidates, Render),
  127    foldl(add_decl_pair, Render, Rendered0, Rendered),
  128    maplist(ns_attr, Render, NSAttrs),
  129    sort(1, @<, AttrParts, SortedAttrParts),
  130    pairs_values(SortedAttrParts, CAttrs1),
  131    append(NSAttrs, CAttrs1, CAttrs),
  132    qname(EPrefix, ELocal, CName),
  133    xml_canonical_list(Content, CContent, ctx(Mode, InScope, Rendered)).
  134xml_canonical_dom(CDATA, CDATA, _) :-
  135    atomic(CDATA),
  136    !.
  137xml_canonical_dom(Node, Node, _).
  138
  139xml_canonical_list([], [], _).
  140xml_canonical_list([H0|T0], [H|T], Ctx) :-
  141    xml_canonical_dom(H0, H, Ctx),
  142    xml_canonical_list(T0, T, Ctx).
  143
  144%   ns_decl(+Attribute) is semidet.
  145%   add_decl(+Attribute, +InScope0, -InScope) is det.
  146
  147ns_decl(Attr) :-
  148    xml_ns(Attr, _, _).
  149
  150add_decl(Attr, InScope0, InScope) :-
  151    xml_ns(Attr, Prefix, URI),
  152    InScope = InScope0.put(Prefix, URI).
  153
  154add_decl_pair(Prefix-URI, Dict0, Dict) :-
  155    Dict = Dict0.put(Prefix, URI).
  156
  157xml_ns(ns('', xmlns):NS=URL, NS, URL) :- !.
  158xml_ns(ns(xmlns, _):NS=URL, NS, URL) :- !.
  159xml_ns(xmlns=URL, '', URL) :- !.
  160xml_ns(xmlns:NS=URL, NS, URL) :- !.
  161xml_ns(Name=URL, NS, URL) :-
  162    atom(Name),
  163    atom_concat('xmlns:', NS, Name).
  164
  165%   element_name(+Name, +InScope, -Prefix, -Local, -URI) is det.
  166%   attribute_parts(+InScope, +Attribute, -Key-CAttribute) is det.
  167%
  168%   Find the prefix, local name and namespace URI.  Key is URI-Local,
  169%   used for sorting the attributes.
  170
  171element_name(Name, InScope, Prefix, Local, URI) :-
  172    name_parts(Name, element, InScope, Prefix, Local, URI).
  173
  174attribute_parts(InScope, Name=Value, (URI-Local)-(QName=Value)) :-
  175    name_parts(Name, attribute, InScope, Prefix, Local, URI),
  176    qname(Prefix, Local, QName).
  177
  178name_parts(ns(P, URI0):Local, _, _, Prefix, Local, URI) :-
  179    !,
  180    (   (P == xml ; URI0 == xml)
  181    ->  Prefix = xml,
  182        xml_namespace(URI)
  183    ;   Prefix = P,
  184        URI = URI0
  185    ).
  186name_parts(URI:Local, Type, InScope, Prefix, Local, URI) :-
  187    !,
  188    (   URI == xml
  189    ->  Prefix = xml
  190    ;   dict_pairs(InScope, _, Pairs),
  191        (   Type == element,
  192            memberchk(''-URI, Pairs)
  193        ->  Prefix = ''
  194        ;   member(Prefix-URI, Pairs),
  195            Prefix \== ''
  196        ->  true
  197        ;   existence_error(namespace_prefix, URI)
  198        )
  199    ).
  200name_parts(Name, Type, InScope, Prefix, Local, URI) :-
  201    must_be(atom, Name),
  202    (   sub_atom(Name, B, _, A, :)
  203    ->  sub_atom(Name, 0, B, _, Prefix),
  204        sub_atom(Name, _, A, 0, Local),
  205        (   Prefix == xml
  206        ->  xml_namespace(URI)
  207        ;   URI = InScope.get(Prefix)
  208        ->  true
  209        ;   existence_error(namespace_prefix, Prefix)
  210        )
  211    ;   Prefix = '',
  212        Local = Name,
  213        (   Type == element
  214        ->  URI = InScope.get('', '')
  215        ;   URI = ''
  216        )
  217    ).
  218
  219xml_namespace('http://www.w3.org/XML/1998/namespace').
  220
  221qname('', Local, Local) :- !.
  222qname(Prefix, Local, QName) :-
  223    atomic_list_concat([Prefix, Local], :, QName).
  224
  225%   utilized(+ElementPrefix-URI, +AttrParts, -PrefixURIPairs)
  226%
  227%   The namespaces that are visibly utilized by an element.
  228
  229utilized(Element, AttrParts, [Element|AttrNS]) :-
  230    findall(Prefix-URI,
  231            ( member((URI-_)-(QName=_), AttrParts),
  232              sub_atom(QName, B, _, _, :),
  233              sub_atom(QName, 0, B, _, Prefix)
  234            ), AttrNS).
  235
  236%   must_render(+Rendered, +Prefix-URI) is semidet.
  237
  238must_render(_, xml-_) :-
  239    !,
  240    fail.
  241must_render(Rendered, ''-URI) :-
  242    !,
  243    URI \== Rendered.get('', '').
  244must_render(Rendered, Prefix-URI) :-
  245    \+ URI == Rendered.get(Prefix).
  246
  247ns_attr(''-URI, xmlns=URI) :- !.
  248ns_attr(Prefix-URI, QName=URI) :-
  249    atom_concat('xmlns:', Prefix, QName)