c14n.c 69 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226
  1. /*
  2. * "Canonical XML" implementation
  3. * http://www.w3.org/TR/xml-c14n
  4. *
  5. * "Exclusive XML Canonicalization" implementation
  6. * http://www.w3.org/TR/xml-exc-c14n
  7. *
  8. * See Copyright for the status of this software.
  9. *
  10. * Author: Aleksey Sanin <aleksey@aleksey.com>
  11. */
  12. #define IN_LIBXML
  13. #include "libxml.h"
  14. #ifdef LIBXML_C14N_ENABLED
  15. #include <stdlib.h>
  16. #include <string.h>
  17. #include <libxml/tree.h>
  18. #include <libxml/parser.h>
  19. #include <libxml/uri.h>
  20. #include <libxml/xmlerror.h>
  21. #include <libxml/xpathInternals.h>
  22. #include <libxml/c14n.h>
  23. #include "private/buf.h"
  24. #include "private/error.h"
  25. /************************************************************************
  26. * *
  27. * Some declaration better left private ATM *
  28. * *
  29. ************************************************************************/
  30. typedef enum {
  31. XMLC14N_BEFORE_DOCUMENT_ELEMENT = 0,
  32. XMLC14N_INSIDE_DOCUMENT_ELEMENT = 1,
  33. XMLC14N_AFTER_DOCUMENT_ELEMENT = 2
  34. } xmlC14NPosition;
  35. typedef struct _xmlC14NVisibleNsStack {
  36. int nsCurEnd; /* number of nodes in the set */
  37. int nsPrevStart; /* the beginning of the stack for previous visible node */
  38. int nsPrevEnd; /* the end of the stack for previous visible node */
  39. int nsMax; /* size of the array as allocated */
  40. xmlNsPtr *nsTab; /* array of ns in no particular order */
  41. xmlNodePtr *nodeTab; /* array of nodes in no particular order */
  42. } xmlC14NVisibleNsStack, *xmlC14NVisibleNsStackPtr;
  43. typedef struct _xmlC14NCtx {
  44. /* input parameters */
  45. xmlDocPtr doc;
  46. xmlC14NIsVisibleCallback is_visible_callback;
  47. void* user_data;
  48. int with_comments;
  49. xmlOutputBufferPtr buf;
  50. /* position in the XML document */
  51. xmlC14NPosition pos;
  52. int parent_is_doc;
  53. xmlC14NVisibleNsStackPtr ns_rendered;
  54. /* C14N mode */
  55. xmlC14NMode mode;
  56. /* exclusive canonicalization */
  57. xmlChar **inclusive_ns_prefixes;
  58. /* error number */
  59. int error;
  60. } xmlC14NCtx, *xmlC14NCtxPtr;
  61. static xmlC14NVisibleNsStackPtr xmlC14NVisibleNsStackCreate (void);
  62. static void xmlC14NVisibleNsStackDestroy (xmlC14NVisibleNsStackPtr cur);
  63. static void xmlC14NVisibleNsStackAdd (xmlC14NVisibleNsStackPtr cur,
  64. xmlNsPtr ns,
  65. xmlNodePtr node);
  66. static void xmlC14NVisibleNsStackSave (xmlC14NVisibleNsStackPtr cur,
  67. xmlC14NVisibleNsStackPtr state);
  68. static void xmlC14NVisibleNsStackRestore (xmlC14NVisibleNsStackPtr cur,
  69. xmlC14NVisibleNsStackPtr state);
  70. static void xmlC14NVisibleNsStackShift (xmlC14NVisibleNsStackPtr cur);
  71. static int xmlC14NVisibleNsStackFind (xmlC14NVisibleNsStackPtr cur,
  72. xmlNsPtr ns);
  73. static int xmlExcC14NVisibleNsStackFind (xmlC14NVisibleNsStackPtr cur,
  74. xmlNsPtr ns,
  75. xmlC14NCtxPtr ctx);
  76. static int xmlC14NIsNodeInNodeset (void *user_data,
  77. xmlNodePtr node,
  78. xmlNodePtr parent);
  79. static int xmlC14NProcessNode(xmlC14NCtxPtr ctx, xmlNodePtr cur);
  80. static int xmlC14NProcessNodeList(xmlC14NCtxPtr ctx, xmlNodePtr cur);
  81. typedef enum {
  82. XMLC14N_NORMALIZE_ATTR = 0,
  83. XMLC14N_NORMALIZE_COMMENT = 1,
  84. XMLC14N_NORMALIZE_PI = 2,
  85. XMLC14N_NORMALIZE_TEXT = 3
  86. } xmlC14NNormalizationMode;
  87. static xmlChar *xmlC11NNormalizeString(const xmlChar * input,
  88. xmlC14NNormalizationMode mode);
  89. #define xmlC11NNormalizeAttr( a ) \
  90. xmlC11NNormalizeString((a), XMLC14N_NORMALIZE_ATTR)
  91. #define xmlC11NNormalizeComment( a ) \
  92. xmlC11NNormalizeString((a), XMLC14N_NORMALIZE_COMMENT)
  93. #define xmlC11NNormalizePI( a ) \
  94. xmlC11NNormalizeString((a), XMLC14N_NORMALIZE_PI)
  95. #define xmlC11NNormalizeText( a ) \
  96. xmlC11NNormalizeString((a), XMLC14N_NORMALIZE_TEXT)
  97. #define xmlC14NIsVisible( ctx, node, parent ) \
  98. (((ctx)->is_visible_callback != NULL) ? \
  99. (ctx)->is_visible_callback((ctx)->user_data, \
  100. (xmlNodePtr)(node), (xmlNodePtr)(parent)) : 1)
  101. #define xmlC14NIsExclusive( ctx ) \
  102. ( (ctx)->mode == XML_C14N_EXCLUSIVE_1_0 )
  103. /************************************************************************
  104. * *
  105. * Some factorized error routines *
  106. * *
  107. ************************************************************************/
  108. /**
  109. * xmlC14NErrMemory:
  110. * @extra: extra information
  111. *
  112. * Handle a redefinition of memory error
  113. */
  114. static void
  115. xmlC14NErrMemory(const char *extra)
  116. {
  117. __xmlRaiseError(NULL, NULL, NULL, NULL, NULL, XML_FROM_C14N,
  118. XML_ERR_NO_MEMORY, XML_ERR_ERROR, NULL, 0, extra,
  119. NULL, NULL, 0, 0,
  120. "Memory allocation failed : %s\n", extra);
  121. }
  122. /**
  123. * xmlC14NErrParam:
  124. * @extra: extra information
  125. *
  126. * Handle a redefinition of param error
  127. */
  128. static void
  129. xmlC14NErrParam(const char *extra)
  130. {
  131. __xmlRaiseError(NULL, NULL, NULL, NULL, NULL, XML_FROM_C14N,
  132. XML_ERR_INTERNAL_ERROR, XML_ERR_ERROR, NULL, 0, extra,
  133. NULL, NULL, 0, 0,
  134. "Invalid parameter : %s\n", extra);
  135. }
  136. /**
  137. * xmlC14NErrInternal:
  138. * @extra: extra information
  139. *
  140. * Handle a redefinition of internal error
  141. */
  142. static void
  143. xmlC14NErrInternal(const char *extra)
  144. {
  145. __xmlRaiseError(NULL, NULL, NULL, NULL, NULL, XML_FROM_C14N,
  146. XML_ERR_INTERNAL_ERROR, XML_ERR_ERROR, NULL, 0, extra,
  147. NULL, NULL, 0, 0,
  148. "Internal error : %s\n", extra);
  149. }
  150. /**
  151. * xmlC14NErrInvalidNode:
  152. * @extra: extra information
  153. *
  154. * Handle a redefinition of invalid node error
  155. */
  156. static void
  157. xmlC14NErrInvalidNode(const char *node_type, const char *extra)
  158. {
  159. __xmlRaiseError(NULL, NULL, NULL, NULL, NULL, XML_FROM_C14N,
  160. XML_C14N_INVALID_NODE, XML_ERR_ERROR, NULL, 0, extra,
  161. NULL, NULL, 0, 0,
  162. "Node %s is invalid here : %s\n", node_type, extra);
  163. }
  164. /**
  165. * xmlC14NErrUnknownNode:
  166. * @extra: extra information
  167. *
  168. * Handle a redefinition of unknown node error
  169. */
  170. static void
  171. xmlC14NErrUnknownNode(int node_type, const char *extra)
  172. {
  173. __xmlRaiseError(NULL, NULL, NULL, NULL, NULL, XML_FROM_C14N,
  174. XML_C14N_UNKNOW_NODE, XML_ERR_ERROR, NULL, 0, extra,
  175. NULL, NULL, 0, 0,
  176. "Unknown node type %d found : %s\n", node_type, extra);
  177. }
  178. /**
  179. * xmlC14NErrRelativeNamespace:
  180. * @extra: extra information
  181. *
  182. * Handle a redefinition of relative namespace error
  183. */
  184. static void
  185. xmlC14NErrRelativeNamespace(const char *ns_uri)
  186. {
  187. __xmlRaiseError(NULL, NULL, NULL, NULL, NULL, XML_FROM_C14N,
  188. XML_C14N_RELATIVE_NAMESPACE, XML_ERR_ERROR, NULL, 0, NULL,
  189. NULL, NULL, 0, 0,
  190. "Relative namespace UR is invalid here : %s\n", ns_uri);
  191. }
  192. /**
  193. * xmlC14NErr:
  194. * @ctxt: a C14N evaluation context
  195. * @node: the context node
  196. * @error: the error code
  197. * @msg: the message
  198. * @extra: extra information
  199. *
  200. * Handle a redefinition of attribute error
  201. */
  202. static void
  203. xmlC14NErr(xmlC14NCtxPtr ctxt, xmlNodePtr node, int error,
  204. const char * msg)
  205. {
  206. if (ctxt != NULL)
  207. ctxt->error = error;
  208. __xmlRaiseError(NULL, NULL, NULL,
  209. ctxt, node, XML_FROM_C14N, error,
  210. XML_ERR_ERROR, NULL, 0,
  211. NULL, NULL, NULL, 0, 0, "%s", msg);
  212. }
  213. /************************************************************************
  214. * *
  215. * The implementation internals *
  216. * *
  217. ************************************************************************/
  218. #define XML_NAMESPACES_DEFAULT 16
  219. static int
  220. xmlC14NIsNodeInNodeset(void *user_data, xmlNodePtr node, xmlNodePtr parent) {
  221. xmlNodeSetPtr nodes = (xmlNodeSetPtr) user_data;
  222. if((nodes != NULL) && (node != NULL)) {
  223. if(node->type != XML_NAMESPACE_DECL) {
  224. return(xmlXPathNodeSetContains(nodes, node));
  225. } else {
  226. xmlNs ns;
  227. memcpy(&ns, node, sizeof(ns));
  228. /* this is a libxml hack! check xpath.c for details */
  229. if((parent != NULL) && (parent->type == XML_ATTRIBUTE_NODE)) {
  230. ns.next = (xmlNsPtr)parent->parent;
  231. } else {
  232. ns.next = (xmlNsPtr)parent;
  233. }
  234. /*
  235. * If the input is an XPath node-set, then the node-set must explicitly
  236. * contain every node to be rendered to the canonical form.
  237. */
  238. return(xmlXPathNodeSetContains(nodes, (xmlNodePtr)&ns));
  239. }
  240. }
  241. return(1);
  242. }
  243. static xmlC14NVisibleNsStackPtr
  244. xmlC14NVisibleNsStackCreate(void) {
  245. xmlC14NVisibleNsStackPtr ret;
  246. ret = (xmlC14NVisibleNsStackPtr) xmlMalloc(sizeof(xmlC14NVisibleNsStack));
  247. if (ret == NULL) {
  248. xmlC14NErrMemory("creating namespaces stack");
  249. return(NULL);
  250. }
  251. memset(ret, 0, sizeof(xmlC14NVisibleNsStack));
  252. return(ret);
  253. }
  254. static void
  255. xmlC14NVisibleNsStackDestroy(xmlC14NVisibleNsStackPtr cur) {
  256. if(cur == NULL) {
  257. xmlC14NErrParam("destroying namespaces stack");
  258. return;
  259. }
  260. if(cur->nsTab != NULL) {
  261. memset(cur->nsTab, 0, cur->nsMax * sizeof(xmlNsPtr));
  262. xmlFree(cur->nsTab);
  263. }
  264. if(cur->nodeTab != NULL) {
  265. memset(cur->nodeTab, 0, cur->nsMax * sizeof(xmlNodePtr));
  266. xmlFree(cur->nodeTab);
  267. }
  268. memset(cur, 0, sizeof(xmlC14NVisibleNsStack));
  269. xmlFree(cur);
  270. }
  271. static void
  272. xmlC14NVisibleNsStackAdd(xmlC14NVisibleNsStackPtr cur, xmlNsPtr ns, xmlNodePtr node) {
  273. if((cur == NULL) ||
  274. ((cur->nsTab == NULL) && (cur->nodeTab != NULL)) ||
  275. ((cur->nsTab != NULL) && (cur->nodeTab == NULL))) {
  276. xmlC14NErrParam("adding namespace to stack");
  277. return;
  278. }
  279. if ((cur->nsTab == NULL) && (cur->nodeTab == NULL)) {
  280. cur->nsTab = (xmlNsPtr*) xmlMalloc(XML_NAMESPACES_DEFAULT * sizeof(xmlNsPtr));
  281. cur->nodeTab = (xmlNodePtr*) xmlMalloc(XML_NAMESPACES_DEFAULT * sizeof(xmlNodePtr));
  282. if ((cur->nsTab == NULL) || (cur->nodeTab == NULL)) {
  283. xmlC14NErrMemory("adding node to stack");
  284. return;
  285. }
  286. memset(cur->nsTab, 0 , XML_NAMESPACES_DEFAULT * sizeof(xmlNsPtr));
  287. memset(cur->nodeTab, 0 , XML_NAMESPACES_DEFAULT * sizeof(xmlNodePtr));
  288. cur->nsMax = XML_NAMESPACES_DEFAULT;
  289. } else if(cur->nsMax == cur->nsCurEnd) {
  290. void *tmp;
  291. int tmpSize;
  292. tmpSize = 2 * cur->nsMax;
  293. tmp = xmlRealloc(cur->nsTab, tmpSize * sizeof(xmlNsPtr));
  294. if (tmp == NULL) {
  295. xmlC14NErrMemory("adding node to stack");
  296. return;
  297. }
  298. cur->nsTab = (xmlNsPtr*)tmp;
  299. tmp = xmlRealloc(cur->nodeTab, tmpSize * sizeof(xmlNodePtr));
  300. if (tmp == NULL) {
  301. xmlC14NErrMemory("adding node to stack");
  302. return;
  303. }
  304. cur->nodeTab = (xmlNodePtr*)tmp;
  305. cur->nsMax = tmpSize;
  306. }
  307. cur->nsTab[cur->nsCurEnd] = ns;
  308. cur->nodeTab[cur->nsCurEnd] = node;
  309. ++cur->nsCurEnd;
  310. }
  311. static void
  312. xmlC14NVisibleNsStackSave(xmlC14NVisibleNsStackPtr cur, xmlC14NVisibleNsStackPtr state) {
  313. if((cur == NULL) || (state == NULL)) {
  314. xmlC14NErrParam("saving namespaces stack");
  315. return;
  316. }
  317. state->nsCurEnd = cur->nsCurEnd;
  318. state->nsPrevStart = cur->nsPrevStart;
  319. state->nsPrevEnd = cur->nsPrevEnd;
  320. }
  321. static void
  322. xmlC14NVisibleNsStackRestore(xmlC14NVisibleNsStackPtr cur, xmlC14NVisibleNsStackPtr state) {
  323. if((cur == NULL) || (state == NULL)) {
  324. xmlC14NErrParam("restoring namespaces stack");
  325. return;
  326. }
  327. cur->nsCurEnd = state->nsCurEnd;
  328. cur->nsPrevStart = state->nsPrevStart;
  329. cur->nsPrevEnd = state->nsPrevEnd;
  330. }
  331. static void
  332. xmlC14NVisibleNsStackShift(xmlC14NVisibleNsStackPtr cur) {
  333. if(cur == NULL) {
  334. xmlC14NErrParam("shifting namespaces stack");
  335. return;
  336. }
  337. cur->nsPrevStart = cur->nsPrevEnd;
  338. cur->nsPrevEnd = cur->nsCurEnd;
  339. }
  340. static int
  341. xmlC14NStrEqual(const xmlChar *str1, const xmlChar *str2) {
  342. if (str1 == str2) return(1);
  343. if (str1 == NULL) return((*str2) == '\0');
  344. if (str2 == NULL) return((*str1) == '\0');
  345. do {
  346. if (*str1++ != *str2) return(0);
  347. } while (*str2++);
  348. return(1);
  349. }
  350. /**
  351. * xmlC14NVisibleNsStackFind:
  352. * @ctx: the C14N context
  353. * @ns: the namespace to check
  354. *
  355. * Checks whether the given namespace was already rendered or not
  356. *
  357. * Returns 1 if we already wrote this namespace or 0 otherwise
  358. */
  359. static int
  360. xmlC14NVisibleNsStackFind(xmlC14NVisibleNsStackPtr cur, xmlNsPtr ns)
  361. {
  362. int i;
  363. const xmlChar *prefix;
  364. const xmlChar *href;
  365. int has_empty_ns;
  366. if(cur == NULL) {
  367. xmlC14NErrParam("searching namespaces stack (c14n)");
  368. return (0);
  369. }
  370. /*
  371. * if the default namespace xmlns="" is not defined yet then
  372. * we do not want to print it out
  373. */
  374. prefix = ((ns == NULL) || (ns->prefix == NULL)) ? BAD_CAST "" : ns->prefix;
  375. href = ((ns == NULL) || (ns->href == NULL)) ? BAD_CAST "" : ns->href;
  376. has_empty_ns = (xmlC14NStrEqual(prefix, NULL) && xmlC14NStrEqual(href, NULL));
  377. if (cur->nsTab != NULL) {
  378. int start = (has_empty_ns) ? 0 : cur->nsPrevStart;
  379. for (i = cur->nsCurEnd - 1; i >= start; --i) {
  380. xmlNsPtr ns1 = cur->nsTab[i];
  381. if(xmlC14NStrEqual(prefix, (ns1 != NULL) ? ns1->prefix : NULL)) {
  382. return(xmlC14NStrEqual(href, (ns1 != NULL) ? ns1->href : NULL));
  383. }
  384. }
  385. }
  386. return(has_empty_ns);
  387. }
  388. static int
  389. xmlExcC14NVisibleNsStackFind(xmlC14NVisibleNsStackPtr cur, xmlNsPtr ns, xmlC14NCtxPtr ctx) {
  390. int i;
  391. const xmlChar *prefix;
  392. const xmlChar *href;
  393. int has_empty_ns;
  394. if(cur == NULL) {
  395. xmlC14NErrParam("searching namespaces stack (exc c14n)");
  396. return (0);
  397. }
  398. /*
  399. * if the default namespace xmlns="" is not defined yet then
  400. * we do not want to print it out
  401. */
  402. prefix = ((ns == NULL) || (ns->prefix == NULL)) ? BAD_CAST "" : ns->prefix;
  403. href = ((ns == NULL) || (ns->href == NULL)) ? BAD_CAST "" : ns->href;
  404. has_empty_ns = (xmlC14NStrEqual(prefix, NULL) && xmlC14NStrEqual(href, NULL));
  405. if (cur->nsTab != NULL) {
  406. int start = 0;
  407. for (i = cur->nsCurEnd - 1; i >= start; --i) {
  408. xmlNsPtr ns1 = cur->nsTab[i];
  409. if(xmlC14NStrEqual(prefix, (ns1 != NULL) ? ns1->prefix : NULL)) {
  410. if(xmlC14NStrEqual(href, (ns1 != NULL) ? ns1->href : NULL)) {
  411. return(xmlC14NIsVisible(ctx, ns1, cur->nodeTab[i]));
  412. } else {
  413. return(0);
  414. }
  415. }
  416. }
  417. }
  418. return(has_empty_ns);
  419. }
  420. /**
  421. * xmlC14NIsXmlNs:
  422. * @ns: the namespace to check
  423. *
  424. * Checks whether the given namespace is a default "xml:" namespace
  425. * with href="http://www.w3.org/XML/1998/namespace"
  426. *
  427. * Returns 1 if the node is default or 0 otherwise
  428. */
  429. /* todo: make it a define? */
  430. static int
  431. xmlC14NIsXmlNs(xmlNsPtr ns)
  432. {
  433. return ((ns != NULL) &&
  434. (xmlStrEqual(ns->prefix, BAD_CAST "xml")) &&
  435. (xmlStrEqual(ns->href, XML_XML_NAMESPACE)));
  436. }
  437. /**
  438. * xmlC14NNsCompare:
  439. * @ns1: the pointer to first namespace
  440. * @ns2: the pointer to second namespace
  441. *
  442. * Compares the namespaces by names (prefixes).
  443. *
  444. * Returns -1 if ns1 < ns2, 0 if ns1 == ns2 or 1 if ns1 > ns2.
  445. */
  446. static int
  447. xmlC14NNsCompare(const void *data1, const void *data2)
  448. {
  449. const xmlNsPtr ns1 = (const xmlNsPtr) data1;
  450. const xmlNsPtr ns2 = (const xmlNsPtr) data2;
  451. if (ns1 == ns2)
  452. return (0);
  453. if (ns1 == NULL)
  454. return (-1);
  455. if (ns2 == NULL)
  456. return (1);
  457. return (xmlStrcmp(ns1->prefix, ns2->prefix));
  458. }
  459. /**
  460. * xmlC14NPrintNamespaces:
  461. * @ns: the pointer to namespace
  462. * @ctx: the C14N context
  463. *
  464. * Prints the given namespace to the output buffer from C14N context.
  465. *
  466. * Returns 1 on success or 0 on fail.
  467. */
  468. static int
  469. xmlC14NPrintNamespaces(const xmlNsPtr ns, xmlC14NCtxPtr ctx)
  470. {
  471. if ((ns == NULL) || (ctx == NULL)) {
  472. xmlC14NErrParam("writing namespaces");
  473. return 0;
  474. }
  475. if (ns->prefix != NULL) {
  476. xmlOutputBufferWriteString(ctx->buf, " xmlns:");
  477. xmlOutputBufferWriteString(ctx->buf, (const char *) ns->prefix);
  478. xmlOutputBufferWriteString(ctx->buf, "=");
  479. } else {
  480. xmlOutputBufferWriteString(ctx->buf, " xmlns=");
  481. }
  482. if(ns->href != NULL) {
  483. xmlBufWriteQuotedString(ctx->buf->buffer, ns->href);
  484. } else {
  485. xmlOutputBufferWriteString(ctx->buf, "\"\"");
  486. }
  487. return (1);
  488. }
  489. static int
  490. xmlC14NPrintNamespacesWalker(const void *ns, void *ctx) {
  491. return xmlC14NPrintNamespaces((const xmlNsPtr) ns, (xmlC14NCtxPtr) ctx);
  492. }
  493. /**
  494. * xmlC14NProcessNamespacesAxis:
  495. * @ctx: the C14N context
  496. * @node: the current node
  497. *
  498. * Prints out canonical namespace axis of the current node to the
  499. * buffer from C14N context as follows
  500. *
  501. * Canonical XML v 1.0 (http://www.w3.org/TR/xml-c14n)
  502. *
  503. * Namespace Axis
  504. * Consider a list L containing only namespace nodes in the
  505. * axis and in the node-set in lexicographic order (ascending). To begin
  506. * processing L, if the first node is not the default namespace node (a node
  507. * with no namespace URI and no local name), then generate a space followed
  508. * by xmlns="" if and only if the following conditions are met:
  509. * - the element E that owns the axis is in the node-set
  510. * - The nearest ancestor element of E in the node-set has a default
  511. * namespace node in the node-set (default namespace nodes always
  512. * have non-empty values in XPath)
  513. * The latter condition eliminates unnecessary occurrences of xmlns="" in
  514. * the canonical form since an element only receives an xmlns="" if its
  515. * default namespace is empty and if it has an immediate parent in the
  516. * canonical form that has a non-empty default namespace. To finish
  517. * processing L, simply process every namespace node in L, except omit
  518. * namespace node with local name xml, which defines the xml prefix,
  519. * if its string value is http://www.w3.org/XML/1998/namespace.
  520. *
  521. * Exclusive XML Canonicalization v 1.0 (http://www.w3.org/TR/xml-exc-c14n)
  522. * Canonical XML applied to a document subset requires the search of the
  523. * ancestor nodes of each orphan element node for attributes in the xml
  524. * namespace, such as xml:lang and xml:space. These are copied into the
  525. * element node except if a declaration of the same attribute is already
  526. * in the attribute axis of the element (whether or not it is included in
  527. * the document subset). This search and copying are omitted from the
  528. * Exclusive XML Canonicalization method.
  529. *
  530. * Returns 0 on success or -1 on fail.
  531. */
  532. static int
  533. xmlC14NProcessNamespacesAxis(xmlC14NCtxPtr ctx, xmlNodePtr cur, int visible)
  534. {
  535. xmlNodePtr n;
  536. xmlNsPtr ns, tmp;
  537. xmlListPtr list;
  538. int already_rendered;
  539. int has_empty_ns = 0;
  540. if ((ctx == NULL) || (cur == NULL) || (cur->type != XML_ELEMENT_NODE)) {
  541. xmlC14NErrParam("processing namespaces axis (c14n)");
  542. return (-1);
  543. }
  544. /*
  545. * Create a sorted list to store element namespaces
  546. */
  547. list = xmlListCreate(NULL, xmlC14NNsCompare);
  548. if (list == NULL) {
  549. xmlC14NErrInternal("creating namespaces list (c14n)");
  550. return (-1);
  551. }
  552. /* check all namespaces */
  553. for(n = cur; n != NULL; n = n->parent) {
  554. for(ns = n->nsDef; ns != NULL; ns = ns->next) {
  555. tmp = xmlSearchNs(cur->doc, cur, ns->prefix);
  556. if((tmp == ns) && !xmlC14NIsXmlNs(ns) && xmlC14NIsVisible(ctx, ns, cur)) {
  557. already_rendered = xmlC14NVisibleNsStackFind(ctx->ns_rendered, ns);
  558. if(visible) {
  559. xmlC14NVisibleNsStackAdd(ctx->ns_rendered, ns, cur);
  560. }
  561. if(!already_rendered) {
  562. xmlListInsert(list, ns);
  563. }
  564. if(xmlStrlen(ns->prefix) == 0) {
  565. has_empty_ns = 1;
  566. }
  567. }
  568. }
  569. }
  570. /**
  571. * if the first node is not the default namespace node (a node with no
  572. * namespace URI and no local name), then generate a space followed by
  573. * xmlns="" if and only if the following conditions are met:
  574. * - the element E that owns the axis is in the node-set
  575. * - the nearest ancestor element of E in the node-set has a default
  576. * namespace node in the node-set (default namespace nodes always
  577. * have non-empty values in XPath)
  578. */
  579. if(visible && !has_empty_ns) {
  580. static xmlNs ns_default;
  581. memset(&ns_default, 0, sizeof(ns_default));
  582. if(!xmlC14NVisibleNsStackFind(ctx->ns_rendered, &ns_default)) {
  583. xmlC14NPrintNamespaces(&ns_default, ctx);
  584. }
  585. }
  586. /*
  587. * print out all elements from list
  588. */
  589. xmlListWalk(list, xmlC14NPrintNamespacesWalker, (void *) ctx);
  590. /*
  591. * Cleanup
  592. */
  593. xmlListDelete(list);
  594. return (0);
  595. }
  596. /**
  597. * xmlExcC14NProcessNamespacesAxis:
  598. * @ctx: the C14N context
  599. * @node: the current node
  600. *
  601. * Prints out exclusive canonical namespace axis of the current node to the
  602. * buffer from C14N context as follows
  603. *
  604. * Exclusive XML Canonicalization
  605. * http://www.w3.org/TR/xml-exc-c14n
  606. *
  607. * If the element node is in the XPath subset then output the node in
  608. * accordance with Canonical XML except for namespace nodes which are
  609. * rendered as follows:
  610. *
  611. * 1. Render each namespace node iff:
  612. * * it is visibly utilized by the immediate parent element or one of
  613. * its attributes, or is present in InclusiveNamespaces PrefixList, and
  614. * * its prefix and value do not appear in ns_rendered. ns_rendered is
  615. * obtained by popping the state stack in order to obtain a list of
  616. * prefixes and their values which have already been rendered by
  617. * an output ancestor of the namespace node's parent element.
  618. * 2. Append the rendered namespace node to the list ns_rendered of namespace
  619. * nodes rendered by output ancestors. Push ns_rendered on state stack and
  620. * recurse.
  621. * 3. After the recursion returns, pop thestate stack.
  622. *
  623. *
  624. * Returns 0 on success or -1 on fail.
  625. */
  626. static int
  627. xmlExcC14NProcessNamespacesAxis(xmlC14NCtxPtr ctx, xmlNodePtr cur, int visible)
  628. {
  629. xmlNsPtr ns;
  630. xmlListPtr list;
  631. xmlAttrPtr attr;
  632. int already_rendered;
  633. int has_empty_ns = 0;
  634. int has_visibly_utilized_empty_ns = 0;
  635. int has_empty_ns_in_inclusive_list = 0;
  636. if ((ctx == NULL) || (cur == NULL) || (cur->type != XML_ELEMENT_NODE)) {
  637. xmlC14NErrParam("processing namespaces axis (exc c14n)");
  638. return (-1);
  639. }
  640. if(!xmlC14NIsExclusive(ctx)) {
  641. xmlC14NErrParam("processing namespaces axis (exc c14n)");
  642. return (-1);
  643. }
  644. /*
  645. * Create a sorted list to store element namespaces
  646. */
  647. list = xmlListCreate(NULL, xmlC14NNsCompare);
  648. if (list == NULL) {
  649. xmlC14NErrInternal("creating namespaces list (exc c14n)");
  650. return (-1);
  651. }
  652. /*
  653. * process inclusive namespaces:
  654. * All namespace nodes appearing on inclusive ns list are
  655. * handled as provided in Canonical XML
  656. */
  657. if(ctx->inclusive_ns_prefixes != NULL) {
  658. xmlChar *prefix;
  659. int i;
  660. for (i = 0; ctx->inclusive_ns_prefixes[i] != NULL; ++i) {
  661. prefix = ctx->inclusive_ns_prefixes[i];
  662. /*
  663. * Special values for namespace with empty prefix
  664. */
  665. if (xmlStrEqual(prefix, BAD_CAST "#default")
  666. || xmlStrEqual(prefix, BAD_CAST "")) {
  667. prefix = NULL;
  668. has_empty_ns_in_inclusive_list = 1;
  669. }
  670. ns = xmlSearchNs(cur->doc, cur, prefix);
  671. if((ns != NULL) && !xmlC14NIsXmlNs(ns) && xmlC14NIsVisible(ctx, ns, cur)) {
  672. already_rendered = xmlC14NVisibleNsStackFind(ctx->ns_rendered, ns);
  673. if(visible) {
  674. xmlC14NVisibleNsStackAdd(ctx->ns_rendered, ns, cur);
  675. }
  676. if(!already_rendered) {
  677. xmlListInsert(list, ns);
  678. }
  679. if(xmlStrlen(ns->prefix) == 0) {
  680. has_empty_ns = 1;
  681. }
  682. }
  683. }
  684. }
  685. /* add node namespace */
  686. if(cur->ns != NULL) {
  687. ns = cur->ns;
  688. } else {
  689. ns = xmlSearchNs(cur->doc, cur, NULL);
  690. has_visibly_utilized_empty_ns = 1;
  691. }
  692. if((ns != NULL) && !xmlC14NIsXmlNs(ns)) {
  693. if(visible && xmlC14NIsVisible(ctx, ns, cur)) {
  694. if(!xmlExcC14NVisibleNsStackFind(ctx->ns_rendered, ns, ctx)) {
  695. xmlListInsert(list, ns);
  696. }
  697. }
  698. if(visible) {
  699. xmlC14NVisibleNsStackAdd(ctx->ns_rendered, ns, cur);
  700. }
  701. if(xmlStrlen(ns->prefix) == 0) {
  702. has_empty_ns = 1;
  703. }
  704. }
  705. /* add attributes */
  706. for(attr = cur->properties; attr != NULL; attr = attr->next) {
  707. /*
  708. * we need to check that attribute is visible and has non
  709. * default namespace (XML Namespaces: "default namespaces
  710. * do not apply directly to attributes")
  711. */
  712. if((attr->ns != NULL) && !xmlC14NIsXmlNs(attr->ns) && xmlC14NIsVisible(ctx, attr, cur)) {
  713. already_rendered = xmlExcC14NVisibleNsStackFind(ctx->ns_rendered, attr->ns, ctx);
  714. xmlC14NVisibleNsStackAdd(ctx->ns_rendered, attr->ns, cur);
  715. if(!already_rendered && visible) {
  716. xmlListInsert(list, attr->ns);
  717. }
  718. if(xmlStrlen(attr->ns->prefix) == 0) {
  719. has_empty_ns = 1;
  720. }
  721. } else if((attr->ns != NULL) && (xmlStrlen(attr->ns->prefix) == 0) && (xmlStrlen(attr->ns->href) == 0)) {
  722. has_visibly_utilized_empty_ns = 1;
  723. }
  724. }
  725. /*
  726. * Process xmlns=""
  727. */
  728. if(visible && has_visibly_utilized_empty_ns &&
  729. !has_empty_ns && !has_empty_ns_in_inclusive_list) {
  730. static xmlNs ns_default;
  731. memset(&ns_default, 0, sizeof(ns_default));
  732. already_rendered = xmlExcC14NVisibleNsStackFind(ctx->ns_rendered, &ns_default, ctx);
  733. if(!already_rendered) {
  734. xmlC14NPrintNamespaces(&ns_default, ctx);
  735. }
  736. } else if(visible && !has_empty_ns && has_empty_ns_in_inclusive_list) {
  737. static xmlNs ns_default;
  738. memset(&ns_default, 0, sizeof(ns_default));
  739. if(!xmlC14NVisibleNsStackFind(ctx->ns_rendered, &ns_default)) {
  740. xmlC14NPrintNamespaces(&ns_default, ctx);
  741. }
  742. }
  743. /*
  744. * print out all elements from list
  745. */
  746. xmlListWalk(list, xmlC14NPrintNamespacesWalker, (void *) ctx);
  747. /*
  748. * Cleanup
  749. */
  750. xmlListDelete(list);
  751. return (0);
  752. }
  753. /**
  754. * xmlC14NIsXmlAttr:
  755. * @attr: the attr to check
  756. *
  757. * Checks whether the given attribute is a default "xml:" namespace
  758. * with href="http://www.w3.org/XML/1998/namespace"
  759. *
  760. * Returns 1 if the node is default or 0 otherwise
  761. */
  762. /* todo: make it a define? */
  763. static int
  764. xmlC14NIsXmlAttr(xmlAttrPtr attr)
  765. {
  766. return ((attr->ns != NULL) &&
  767. (xmlC14NIsXmlNs(attr->ns) != 0));
  768. }
  769. /**
  770. * xmlC14NAttrsCompare:
  771. * @attr1: the pointer tls o first attr
  772. * @attr2: the pointer to second attr
  773. *
  774. * Prints the given attribute to the output buffer from C14N context.
  775. *
  776. * Returns -1 if attr1 < attr2, 0 if attr1 == attr2 or 1 if attr1 > attr2.
  777. */
  778. static int
  779. xmlC14NAttrsCompare(const void *data1, const void *data2)
  780. {
  781. const xmlAttrPtr attr1 = (const xmlAttrPtr) data1;
  782. const xmlAttrPtr attr2 = (const xmlAttrPtr) data2;
  783. int ret = 0;
  784. /*
  785. * Simple cases
  786. */
  787. if (attr1 == attr2)
  788. return (0);
  789. if (attr1 == NULL)
  790. return (-1);
  791. if (attr2 == NULL)
  792. return (1);
  793. if (attr1->ns == attr2->ns) {
  794. return (xmlStrcmp(attr1->name, attr2->name));
  795. }
  796. /*
  797. * Attributes in the default namespace are first
  798. * because the default namespace is not applied to
  799. * unqualified attributes
  800. */
  801. if (attr1->ns == NULL)
  802. return (-1);
  803. if (attr2->ns == NULL)
  804. return (1);
  805. if (attr1->ns->prefix == NULL)
  806. return (-1);
  807. if (attr2->ns->prefix == NULL)
  808. return (1);
  809. ret = xmlStrcmp(attr1->ns->href, attr2->ns->href);
  810. if (ret == 0) {
  811. ret = xmlStrcmp(attr1->name, attr2->name);
  812. }
  813. return (ret);
  814. }
  815. /**
  816. * xmlC14NPrintAttrs:
  817. * @attr: the pointer to attr
  818. * @ctx: the C14N context
  819. *
  820. * Prints out canonical attribute urrent node to the
  821. * buffer from C14N context as follows
  822. *
  823. * Canonical XML v 1.0 (http://www.w3.org/TR/xml-c14n)
  824. *
  825. * Returns 1 on success or 0 on fail.
  826. */
  827. static int
  828. xmlC14NPrintAttrs(const void *data, void *user)
  829. {
  830. const xmlAttrPtr attr = (const xmlAttrPtr) data;
  831. xmlC14NCtxPtr ctx = (xmlC14NCtxPtr) user;
  832. xmlChar *value;
  833. xmlChar *buffer;
  834. if ((attr == NULL) || (ctx == NULL)) {
  835. xmlC14NErrParam("writing attributes");
  836. return (0);
  837. }
  838. xmlOutputBufferWriteString(ctx->buf, " ");
  839. if (attr->ns != NULL && xmlStrlen(attr->ns->prefix) > 0) {
  840. xmlOutputBufferWriteString(ctx->buf,
  841. (const char *) attr->ns->prefix);
  842. xmlOutputBufferWriteString(ctx->buf, ":");
  843. }
  844. xmlOutputBufferWriteString(ctx->buf, (const char *) attr->name);
  845. xmlOutputBufferWriteString(ctx->buf, "=\"");
  846. value = xmlNodeListGetString(ctx->doc, attr->children, 1);
  847. /* todo: should we log an error if value==NULL ? */
  848. if (value != NULL) {
  849. buffer = xmlC11NNormalizeAttr(value);
  850. xmlFree(value);
  851. if (buffer != NULL) {
  852. xmlOutputBufferWriteString(ctx->buf, (const char *) buffer);
  853. xmlFree(buffer);
  854. } else {
  855. xmlC14NErrInternal("normalizing attributes axis");
  856. return (0);
  857. }
  858. }
  859. xmlOutputBufferWriteString(ctx->buf, "\"");
  860. return (1);
  861. }
  862. /**
  863. * xmlC14NFindHiddenParentAttr:
  864. *
  865. * Finds an attribute in a hidden parent node.
  866. *
  867. * Returns a pointer to the attribute node (if found) or NULL otherwise.
  868. */
  869. static xmlAttrPtr
  870. xmlC14NFindHiddenParentAttr(xmlC14NCtxPtr ctx, xmlNodePtr cur, const xmlChar * name, const xmlChar * ns)
  871. {
  872. xmlAttrPtr res;
  873. while((cur != NULL) && (!xmlC14NIsVisible(ctx, cur, cur->parent))) {
  874. res = xmlHasNsProp(cur, name, ns);
  875. if(res != NULL) {
  876. return res;
  877. }
  878. cur = cur->parent;
  879. }
  880. return NULL;
  881. }
  882. /**
  883. * xmlC14NFixupBaseAttr:
  884. *
  885. * Fixes up the xml:base attribute
  886. *
  887. * Returns the newly created attribute or NULL
  888. */
  889. static xmlAttrPtr
  890. xmlC14NFixupBaseAttr(xmlC14NCtxPtr ctx, xmlAttrPtr xml_base_attr)
  891. {
  892. xmlChar * res = NULL;
  893. xmlNodePtr cur;
  894. xmlAttrPtr attr;
  895. xmlChar * tmp_str;
  896. xmlChar * tmp_str2;
  897. int tmp_str_len;
  898. if ((ctx == NULL) || (xml_base_attr == NULL) || (xml_base_attr->parent == NULL)) {
  899. xmlC14NErrParam("processing xml:base attribute");
  900. return (NULL);
  901. }
  902. /* start from current value */
  903. res = xmlNodeListGetString(ctx->doc, xml_base_attr->children, 1);
  904. if(res == NULL) {
  905. xmlC14NErrInternal("processing xml:base attribute - can't get attr value");
  906. return (NULL);
  907. }
  908. /* go up the stack until we find a node that we rendered already */
  909. cur = xml_base_attr->parent->parent;
  910. while((cur != NULL) && (!xmlC14NIsVisible(ctx, cur, cur->parent))) {
  911. attr = xmlHasNsProp(cur, BAD_CAST "base", XML_XML_NAMESPACE);
  912. if(attr != NULL) {
  913. /* get attr value */
  914. tmp_str = xmlNodeListGetString(ctx->doc, attr->children, 1);
  915. if(tmp_str == NULL) {
  916. xmlFree(res);
  917. xmlC14NErrInternal("processing xml:base attribute - can't get attr value");
  918. return (NULL);
  919. }
  920. /* we need to add '/' if our current base uri ends with '..' or '.'
  921. to ensure that we are forced to go "up" all the time */
  922. tmp_str_len = xmlStrlen(tmp_str);
  923. if(tmp_str_len > 1 && tmp_str[tmp_str_len - 2] == '.') {
  924. tmp_str2 = xmlStrcat(tmp_str, BAD_CAST "/");
  925. if(tmp_str2 == NULL) {
  926. xmlFree(tmp_str);
  927. xmlFree(res);
  928. xmlC14NErrInternal("processing xml:base attribute - can't modify uri");
  929. return (NULL);
  930. }
  931. tmp_str = tmp_str2;
  932. }
  933. /* build uri */
  934. tmp_str2 = xmlBuildURI(res, tmp_str);
  935. if(tmp_str2 == NULL) {
  936. xmlFree(tmp_str);
  937. xmlFree(res);
  938. xmlC14NErrInternal("processing xml:base attribute - can't construct uri");
  939. return (NULL);
  940. }
  941. /* cleanup and set the new res */
  942. xmlFree(tmp_str);
  943. xmlFree(res);
  944. res = tmp_str2;
  945. }
  946. /* next */
  947. cur = cur->parent;
  948. }
  949. /* check if result uri is empty or not */
  950. if((res == NULL) || xmlStrEqual(res, BAD_CAST "")) {
  951. xmlFree(res);
  952. return (NULL);
  953. }
  954. /* create and return the new attribute node */
  955. attr = xmlNewNsProp(NULL, xml_base_attr->ns, BAD_CAST "base", res);
  956. if(attr == NULL) {
  957. xmlFree(res);
  958. xmlC14NErrInternal("processing xml:base attribute - can't construct attribute");
  959. return (NULL);
  960. }
  961. /* done */
  962. xmlFree(res);
  963. return (attr);
  964. }
  965. /**
  966. * xmlC14NProcessAttrsAxis:
  967. * @ctx: the C14N context
  968. * @cur: the current node
  969. * @parent_visible: the visibility of parent node
  970. * @all_parents_visible: the visibility of all parent nodes
  971. *
  972. * Prints out canonical attribute axis of the current node to the
  973. * buffer from C14N context as follows
  974. *
  975. * Canonical XML v 1.0 (http://www.w3.org/TR/xml-c14n)
  976. *
  977. * Attribute Axis
  978. * In lexicographic order (ascending), process each node that
  979. * is in the element's attribute axis and in the node-set.
  980. *
  981. * The processing of an element node E MUST be modified slightly
  982. * when an XPath node-set is given as input and the element's
  983. * parent is omitted from the node-set.
  984. *
  985. *
  986. * Exclusive XML Canonicalization v 1.0 (http://www.w3.org/TR/xml-exc-c14n)
  987. *
  988. * Canonical XML applied to a document subset requires the search of the
  989. * ancestor nodes of each orphan element node for attributes in the xml
  990. * namespace, such as xml:lang and xml:space. These are copied into the
  991. * element node except if a declaration of the same attribute is already
  992. * in the attribute axis of the element (whether or not it is included in
  993. * the document subset). This search and copying are omitted from the
  994. * Exclusive XML Canonicalization method.
  995. *
  996. * Returns 0 on success or -1 on fail.
  997. */
  998. static int
  999. xmlC14NProcessAttrsAxis(xmlC14NCtxPtr ctx, xmlNodePtr cur, int parent_visible)
  1000. {
  1001. xmlAttrPtr attr;
  1002. xmlListPtr list;
  1003. xmlAttrPtr attrs_to_delete = NULL;
  1004. /* special processing for 1.1 spec */
  1005. xmlAttrPtr xml_base_attr = NULL;
  1006. xmlAttrPtr xml_lang_attr = NULL;
  1007. xmlAttrPtr xml_space_attr = NULL;
  1008. if ((ctx == NULL) || (cur == NULL) || (cur->type != XML_ELEMENT_NODE)) {
  1009. xmlC14NErrParam("processing attributes axis");
  1010. return (-1);
  1011. }
  1012. /*
  1013. * Create a sorted list to store element attributes
  1014. */
  1015. list = xmlListCreate(NULL, xmlC14NAttrsCompare);
  1016. if (list == NULL) {
  1017. xmlC14NErrInternal("creating attributes list");
  1018. return (-1);
  1019. }
  1020. switch(ctx->mode) {
  1021. case XML_C14N_1_0:
  1022. /* The processing of an element node E MUST be modified slightly when an XPath node-set is
  1023. * given as input and the element's parent is omitted from the node-set. The method for processing
  1024. * the attribute axis of an element E in the node-set is enhanced. All element nodes along E's
  1025. * ancestor axis are examined for nearest occurrences of attributes in the xml namespace, such
  1026. * as xml:lang and xml:space (whether or not they are in the node-set). From this list of attributes,
  1027. * remove any that are in E's attribute axis (whether or not they are in the node-set). Then,
  1028. * lexicographically merge this attribute list with the nodes of E's attribute axis that are in
  1029. * the node-set. The result of visiting the attribute axis is computed by processing the attribute
  1030. * nodes in this merged attribute list.
  1031. */
  1032. /*
  1033. * Add all visible attributes from current node.
  1034. */
  1035. attr = cur->properties;
  1036. while (attr != NULL) {
  1037. /* check that attribute is visible */
  1038. if (xmlC14NIsVisible(ctx, attr, cur)) {
  1039. xmlListInsert(list, attr);
  1040. }
  1041. attr = attr->next;
  1042. }
  1043. /*
  1044. * Handle xml attributes
  1045. */
  1046. if (parent_visible && (cur->parent != NULL) &&
  1047. (!xmlC14NIsVisible(ctx, cur->parent, cur->parent->parent)))
  1048. {
  1049. xmlNodePtr tmp;
  1050. /*
  1051. * If XPath node-set is not specified then the parent is always
  1052. * visible!
  1053. */
  1054. tmp = cur->parent;
  1055. while (tmp != NULL) {
  1056. attr = tmp->properties;
  1057. while (attr != NULL) {
  1058. if (xmlC14NIsXmlAttr(attr) != 0) {
  1059. if (xmlListSearch(list, attr) == NULL) {
  1060. xmlListInsert(list, attr);
  1061. }
  1062. }
  1063. attr = attr->next;
  1064. }
  1065. tmp = tmp->parent;
  1066. }
  1067. }
  1068. /* done */
  1069. break;
  1070. case XML_C14N_EXCLUSIVE_1_0:
  1071. /* attributes in the XML namespace, such as xml:lang and xml:space
  1072. * are not imported into orphan nodes of the document subset
  1073. */
  1074. /*
  1075. * Add all visible attributes from current node.
  1076. */
  1077. attr = cur->properties;
  1078. while (attr != NULL) {
  1079. /* check that attribute is visible */
  1080. if (xmlC14NIsVisible(ctx, attr, cur)) {
  1081. xmlListInsert(list, attr);
  1082. }
  1083. attr = attr->next;
  1084. }
  1085. /* do nothing special for xml attributes */
  1086. break;
  1087. case XML_C14N_1_1:
  1088. /* The processing of an element node E MUST be modified slightly when an XPath node-set is
  1089. * given as input and some of the element's ancestors are omitted from the node-set.
  1090. *
  1091. * Simple inheritable attributes are attributes that have a value that requires at most a simple
  1092. * redeclaration. This redeclaration is done by supplying a new value in the child axis. The
  1093. * redeclaration of a simple inheritable attribute A contained in one of E's ancestors is done
  1094. * by supplying a value to an attribute Ae inside E with the same name. Simple inheritable attributes
  1095. * are xml:lang and xml:space.
  1096. *
  1097. * The method for processing the attribute axis of an element E in the node-set is hence enhanced.
  1098. * All element nodes along E's ancestor axis are examined for the nearest occurrences of simple
  1099. * inheritable attributes in the xml namespace, such as xml:lang and xml:space (whether or not they
  1100. * are in the node-set). From this list of attributes, any simple inheritable attributes that are
  1101. * already in E's attribute axis (whether or not they are in the node-set) are removed. Then,
  1102. * lexicographically merge this attribute list with the nodes of E's attribute axis that are in
  1103. * the node-set. The result of visiting the attribute axis is computed by processing the attribute
  1104. * nodes in this merged attribute list.
  1105. *
  1106. * The xml:id attribute is not a simple inheritable attribute and no processing of these attributes is
  1107. * performed.
  1108. *
  1109. * The xml:base attribute is not a simple inheritable attribute and requires special processing beyond
  1110. * a simple redeclaration.
  1111. *
  1112. * Attributes in the XML namespace other than xml:base, xml:id, xml:lang, and xml:space MUST be processed
  1113. * as ordinary attributes.
  1114. */
  1115. /*
  1116. * Add all visible attributes from current node.
  1117. */
  1118. attr = cur->properties;
  1119. while (attr != NULL) {
  1120. /* special processing for XML attribute kiks in only when we have invisible parents */
  1121. if ((!parent_visible) || (xmlC14NIsXmlAttr(attr) == 0)) {
  1122. /* check that attribute is visible */
  1123. if (xmlC14NIsVisible(ctx, attr, cur)) {
  1124. xmlListInsert(list, attr);
  1125. }
  1126. } else {
  1127. int matched = 0;
  1128. /* check for simple inheritance attributes */
  1129. if((!matched) && (xml_lang_attr == NULL) && xmlStrEqual(attr->name, BAD_CAST "lang")) {
  1130. xml_lang_attr = attr;
  1131. matched = 1;
  1132. }
  1133. if((!matched) && (xml_space_attr == NULL) && xmlStrEqual(attr->name, BAD_CAST "space")) {
  1134. xml_space_attr = attr;
  1135. matched = 1;
  1136. }
  1137. /* check for base attr */
  1138. if((!matched) && (xml_base_attr == NULL) && xmlStrEqual(attr->name, BAD_CAST "base")) {
  1139. xml_base_attr = attr;
  1140. matched = 1;
  1141. }
  1142. /* otherwise, it is a normal attribute, so just check if it is visible */
  1143. if((!matched) && xmlC14NIsVisible(ctx, attr, cur)) {
  1144. xmlListInsert(list, attr);
  1145. }
  1146. }
  1147. /* move to the next one */
  1148. attr = attr->next;
  1149. }
  1150. /* special processing for XML attribute kiks in only when we have invisible parents */
  1151. if ((parent_visible)) {
  1152. /* simple inheritance attributes - copy */
  1153. if(xml_lang_attr == NULL) {
  1154. xml_lang_attr = xmlC14NFindHiddenParentAttr(ctx, cur->parent, BAD_CAST "lang", XML_XML_NAMESPACE);
  1155. }
  1156. if(xml_lang_attr != NULL) {
  1157. xmlListInsert(list, xml_lang_attr);
  1158. }
  1159. if(xml_space_attr == NULL) {
  1160. xml_space_attr = xmlC14NFindHiddenParentAttr(ctx, cur->parent, BAD_CAST "space", XML_XML_NAMESPACE);
  1161. }
  1162. if(xml_space_attr != NULL) {
  1163. xmlListInsert(list, xml_space_attr);
  1164. }
  1165. /* base uri attribute - fix up */
  1166. if(xml_base_attr == NULL) {
  1167. /* if we don't have base uri attribute, check if we have a "hidden" one above */
  1168. xml_base_attr = xmlC14NFindHiddenParentAttr(ctx, cur->parent, BAD_CAST "base", XML_XML_NAMESPACE);
  1169. }
  1170. if(xml_base_attr != NULL) {
  1171. xml_base_attr = xmlC14NFixupBaseAttr(ctx, xml_base_attr);
  1172. if(xml_base_attr != NULL) {
  1173. xmlListInsert(list, xml_base_attr);
  1174. /* note that we MUST delete returned attr node ourselves! */
  1175. xml_base_attr->next = attrs_to_delete;
  1176. attrs_to_delete = xml_base_attr;
  1177. }
  1178. }
  1179. }
  1180. /* done */
  1181. break;
  1182. }
  1183. /*
  1184. * print out all elements from list
  1185. */
  1186. xmlListWalk(list, xmlC14NPrintAttrs, (void *) ctx);
  1187. /*
  1188. * Cleanup
  1189. */
  1190. xmlFreePropList(attrs_to_delete);
  1191. xmlListDelete(list);
  1192. return (0);
  1193. }
  1194. /**
  1195. * xmlC14NCheckForRelativeNamespaces:
  1196. * @ctx: the C14N context
  1197. * @cur: the current element node
  1198. *
  1199. * Checks that current element node has no relative namespaces defined
  1200. *
  1201. * Returns 0 if the node has no relative namespaces or -1 otherwise.
  1202. */
  1203. static int
  1204. xmlC14NCheckForRelativeNamespaces(xmlC14NCtxPtr ctx, xmlNodePtr cur)
  1205. {
  1206. xmlNsPtr ns;
  1207. if ((ctx == NULL) || (cur == NULL) || (cur->type != XML_ELEMENT_NODE)) {
  1208. xmlC14NErrParam("checking for relative namespaces");
  1209. return (-1);
  1210. }
  1211. ns = cur->nsDef;
  1212. while (ns != NULL) {
  1213. if (xmlStrlen(ns->href) > 0) {
  1214. xmlURIPtr uri;
  1215. uri = xmlParseURI((const char *) ns->href);
  1216. if (uri == NULL) {
  1217. xmlC14NErrInternal("parsing namespace uri");
  1218. return (-1);
  1219. }
  1220. if (xmlStrlen((const xmlChar *) uri->scheme) == 0) {
  1221. xmlC14NErrRelativeNamespace(uri->scheme);
  1222. xmlFreeURI(uri);
  1223. return (-1);
  1224. }
  1225. xmlFreeURI(uri);
  1226. }
  1227. ns = ns->next;
  1228. }
  1229. return (0);
  1230. }
  1231. /**
  1232. * xmlC14NProcessElementNode:
  1233. * @ctx: the pointer to C14N context object
  1234. * @cur: the node to process
  1235. * @visible: this node is visible
  1236. * @all_parents_visible: whether all the parents of this node are visible
  1237. *
  1238. * Canonical XML v 1.0 (http://www.w3.org/TR/xml-c14n)
  1239. *
  1240. * Element Nodes
  1241. * If the element is not in the node-set, then the result is obtained
  1242. * by processing the namespace axis, then the attribute axis, then
  1243. * processing the child nodes of the element that are in the node-set
  1244. * (in document order). If the element is in the node-set, then the result
  1245. * is an open angle bracket (<), the element QName, the result of
  1246. * processing the namespace axis, the result of processing the attribute
  1247. * axis, a close angle bracket (>), the result of processing the child
  1248. * nodes of the element that are in the node-set (in document order), an
  1249. * open angle bracket, a forward slash (/), the element QName, and a close
  1250. * angle bracket.
  1251. *
  1252. * Returns non-negative value on success or negative value on fail
  1253. */
  1254. static int
  1255. xmlC14NProcessElementNode(xmlC14NCtxPtr ctx, xmlNodePtr cur, int visible)
  1256. {
  1257. int ret;
  1258. xmlC14NVisibleNsStack state;
  1259. int parent_is_doc = 0;
  1260. if ((ctx == NULL) || (cur == NULL) || (cur->type != XML_ELEMENT_NODE)) {
  1261. xmlC14NErrParam("processing element node");
  1262. return (-1);
  1263. }
  1264. /*
  1265. * Check relative relative namespaces:
  1266. * implementations of XML canonicalization MUST report an operation
  1267. * failure on documents containing relative namespace URIs.
  1268. */
  1269. if (xmlC14NCheckForRelativeNamespaces(ctx, cur) < 0) {
  1270. xmlC14NErrInternal("checking for relative namespaces");
  1271. return (-1);
  1272. }
  1273. /*
  1274. * Save ns_rendered stack position
  1275. */
  1276. memset(&state, 0, sizeof(state));
  1277. xmlC14NVisibleNsStackSave(ctx->ns_rendered, &state);
  1278. if (visible) {
  1279. if (ctx->parent_is_doc) {
  1280. /* save this flag into the stack */
  1281. parent_is_doc = ctx->parent_is_doc;
  1282. ctx->parent_is_doc = 0;
  1283. ctx->pos = XMLC14N_INSIDE_DOCUMENT_ELEMENT;
  1284. }
  1285. xmlOutputBufferWriteString(ctx->buf, "<");
  1286. if ((cur->ns != NULL) && (xmlStrlen(cur->ns->prefix) > 0)) {
  1287. xmlOutputBufferWriteString(ctx->buf,
  1288. (const char *) cur->ns->prefix);
  1289. xmlOutputBufferWriteString(ctx->buf, ":");
  1290. }
  1291. xmlOutputBufferWriteString(ctx->buf, (const char *) cur->name);
  1292. }
  1293. if (!xmlC14NIsExclusive(ctx)) {
  1294. ret = xmlC14NProcessNamespacesAxis(ctx, cur, visible);
  1295. } else {
  1296. ret = xmlExcC14NProcessNamespacesAxis(ctx, cur, visible);
  1297. }
  1298. if (ret < 0) {
  1299. xmlC14NErrInternal("processing namespaces axis");
  1300. return (-1);
  1301. }
  1302. /* todo: shouldn't this go to "visible only"? */
  1303. if(visible) {
  1304. xmlC14NVisibleNsStackShift(ctx->ns_rendered);
  1305. }
  1306. ret = xmlC14NProcessAttrsAxis(ctx, cur, visible);
  1307. if (ret < 0) {
  1308. xmlC14NErrInternal("processing attributes axis");
  1309. return (-1);
  1310. }
  1311. if (visible) {
  1312. xmlOutputBufferWriteString(ctx->buf, ">");
  1313. }
  1314. if (cur->children != NULL) {
  1315. ret = xmlC14NProcessNodeList(ctx, cur->children);
  1316. if (ret < 0) {
  1317. xmlC14NErrInternal("processing childrens list");
  1318. return (-1);
  1319. }
  1320. }
  1321. if (visible) {
  1322. xmlOutputBufferWriteString(ctx->buf, "</");
  1323. if ((cur->ns != NULL) && (xmlStrlen(cur->ns->prefix) > 0)) {
  1324. xmlOutputBufferWriteString(ctx->buf,
  1325. (const char *) cur->ns->prefix);
  1326. xmlOutputBufferWriteString(ctx->buf, ":");
  1327. }
  1328. xmlOutputBufferWriteString(ctx->buf, (const char *) cur->name);
  1329. xmlOutputBufferWriteString(ctx->buf, ">");
  1330. if (parent_is_doc) {
  1331. /* restore this flag from the stack for next node */
  1332. ctx->parent_is_doc = parent_is_doc;
  1333. ctx->pos = XMLC14N_AFTER_DOCUMENT_ELEMENT;
  1334. }
  1335. }
  1336. /*
  1337. * Restore ns_rendered stack position
  1338. */
  1339. xmlC14NVisibleNsStackRestore(ctx->ns_rendered, &state);
  1340. return (0);
  1341. }
  1342. /**
  1343. * xmlC14NProcessNode:
  1344. * @ctx: the pointer to C14N context object
  1345. * @cur: the node to process
  1346. *
  1347. * Processes the given node
  1348. *
  1349. * Returns non-negative value on success or negative value on fail
  1350. */
  1351. static int
  1352. xmlC14NProcessNode(xmlC14NCtxPtr ctx, xmlNodePtr cur)
  1353. {
  1354. int ret = 0;
  1355. int visible;
  1356. if ((ctx == NULL) || (cur == NULL)) {
  1357. xmlC14NErrParam("processing node");
  1358. return (-1);
  1359. }
  1360. visible = xmlC14NIsVisible(ctx, cur, cur->parent);
  1361. switch (cur->type) {
  1362. case XML_ELEMENT_NODE:
  1363. ret = xmlC14NProcessElementNode(ctx, cur, visible);
  1364. break;
  1365. case XML_CDATA_SECTION_NODE:
  1366. case XML_TEXT_NODE:
  1367. /*
  1368. * Text Nodes
  1369. * the string value, except all ampersands are replaced
  1370. * by &amp;, all open angle brackets (<) are replaced by &lt;, all closing
  1371. * angle brackets (>) are replaced by &gt;, and all #xD characters are
  1372. * replaced by &#xD;.
  1373. */
  1374. /* cdata sections are processed as text nodes */
  1375. /* todo: verify that cdata sections are included in XPath nodes set */
  1376. if ((visible) && (cur->content != NULL)) {
  1377. xmlChar *buffer;
  1378. buffer = xmlC11NNormalizeText(cur->content);
  1379. if (buffer != NULL) {
  1380. xmlOutputBufferWriteString(ctx->buf,
  1381. (const char *) buffer);
  1382. xmlFree(buffer);
  1383. } else {
  1384. xmlC14NErrInternal("normalizing text node");
  1385. return (-1);
  1386. }
  1387. }
  1388. break;
  1389. case XML_PI_NODE:
  1390. /*
  1391. * Processing Instruction (PI) Nodes-
  1392. * The opening PI symbol (<?), the PI target name of the node,
  1393. * a leading space and the string value if it is not empty, and
  1394. * the closing PI symbol (?>). If the string value is empty,
  1395. * then the leading space is not added. Also, a trailing #xA is
  1396. * rendered after the closing PI symbol for PI children of the
  1397. * root node with a lesser document order than the document
  1398. * element, and a leading #xA is rendered before the opening PI
  1399. * symbol of PI children of the root node with a greater document
  1400. * order than the document element.
  1401. */
  1402. if (visible) {
  1403. if (ctx->pos == XMLC14N_AFTER_DOCUMENT_ELEMENT) {
  1404. xmlOutputBufferWriteString(ctx->buf, "\x0A<?");
  1405. } else {
  1406. xmlOutputBufferWriteString(ctx->buf, "<?");
  1407. }
  1408. xmlOutputBufferWriteString(ctx->buf,
  1409. (const char *) cur->name);
  1410. if ((cur->content != NULL) && (*(cur->content) != '\0')) {
  1411. xmlChar *buffer;
  1412. xmlOutputBufferWriteString(ctx->buf, " ");
  1413. /* todo: do we need to normalize pi? */
  1414. buffer = xmlC11NNormalizePI(cur->content);
  1415. if (buffer != NULL) {
  1416. xmlOutputBufferWriteString(ctx->buf,
  1417. (const char *) buffer);
  1418. xmlFree(buffer);
  1419. } else {
  1420. xmlC14NErrInternal("normalizing pi node");
  1421. return (-1);
  1422. }
  1423. }
  1424. if (ctx->pos == XMLC14N_BEFORE_DOCUMENT_ELEMENT) {
  1425. xmlOutputBufferWriteString(ctx->buf, "?>\x0A");
  1426. } else {
  1427. xmlOutputBufferWriteString(ctx->buf, "?>");
  1428. }
  1429. }
  1430. break;
  1431. case XML_COMMENT_NODE:
  1432. /*
  1433. * Comment Nodes
  1434. * Nothing if generating canonical XML without comments. For
  1435. * canonical XML with comments, generate the opening comment
  1436. * symbol (<!--), the string value of the node, and the
  1437. * closing comment symbol (-->). Also, a trailing #xA is rendered
  1438. * after the closing comment symbol for comment children of the
  1439. * root node with a lesser document order than the document
  1440. * element, and a leading #xA is rendered before the opening
  1441. * comment symbol of comment children of the root node with a
  1442. * greater document order than the document element. (Comment
  1443. * children of the root node represent comments outside of the
  1444. * top-level document element and outside of the document type
  1445. * declaration).
  1446. */
  1447. if (visible && ctx->with_comments) {
  1448. if (ctx->pos == XMLC14N_AFTER_DOCUMENT_ELEMENT) {
  1449. xmlOutputBufferWriteString(ctx->buf, "\x0A<!--");
  1450. } else {
  1451. xmlOutputBufferWriteString(ctx->buf, "<!--");
  1452. }
  1453. if (cur->content != NULL) {
  1454. xmlChar *buffer;
  1455. /* todo: do we need to normalize comment? */
  1456. buffer = xmlC11NNormalizeComment(cur->content);
  1457. if (buffer != NULL) {
  1458. xmlOutputBufferWriteString(ctx->buf,
  1459. (const char *) buffer);
  1460. xmlFree(buffer);
  1461. } else {
  1462. xmlC14NErrInternal("normalizing comment node");
  1463. return (-1);
  1464. }
  1465. }
  1466. if (ctx->pos == XMLC14N_BEFORE_DOCUMENT_ELEMENT) {
  1467. xmlOutputBufferWriteString(ctx->buf, "-->\x0A");
  1468. } else {
  1469. xmlOutputBufferWriteString(ctx->buf, "-->");
  1470. }
  1471. }
  1472. break;
  1473. case XML_DOCUMENT_NODE:
  1474. case XML_DOCUMENT_FRAG_NODE: /* should be processed as document? */
  1475. #ifdef LIBXML_HTML_ENABLED
  1476. case XML_HTML_DOCUMENT_NODE: /* should be processed as document? */
  1477. #endif
  1478. if (cur->children != NULL) {
  1479. ctx->pos = XMLC14N_BEFORE_DOCUMENT_ELEMENT;
  1480. ctx->parent_is_doc = 1;
  1481. ret = xmlC14NProcessNodeList(ctx, cur->children);
  1482. }
  1483. break;
  1484. case XML_ATTRIBUTE_NODE:
  1485. xmlC14NErrInvalidNode("XML_ATTRIBUTE_NODE", "processing node");
  1486. return (-1);
  1487. case XML_NAMESPACE_DECL:
  1488. xmlC14NErrInvalidNode("XML_NAMESPACE_DECL", "processing node");
  1489. return (-1);
  1490. case XML_ENTITY_REF_NODE:
  1491. xmlC14NErrInvalidNode("XML_ENTITY_REF_NODE", "processing node");
  1492. return (-1);
  1493. case XML_ENTITY_NODE:
  1494. xmlC14NErrInvalidNode("XML_ENTITY_NODE", "processing node");
  1495. return (-1);
  1496. case XML_DOCUMENT_TYPE_NODE:
  1497. case XML_NOTATION_NODE:
  1498. case XML_DTD_NODE:
  1499. case XML_ELEMENT_DECL:
  1500. case XML_ATTRIBUTE_DECL:
  1501. case XML_ENTITY_DECL:
  1502. #ifdef LIBXML_XINCLUDE_ENABLED
  1503. case XML_XINCLUDE_START:
  1504. case XML_XINCLUDE_END:
  1505. #endif
  1506. /*
  1507. * should be ignored according to "W3C Canonical XML"
  1508. */
  1509. break;
  1510. default:
  1511. xmlC14NErrUnknownNode(cur->type, "processing node");
  1512. return (-1);
  1513. }
  1514. return (ret);
  1515. }
  1516. /**
  1517. * xmlC14NProcessNodeList:
  1518. * @ctx: the pointer to C14N context object
  1519. * @cur: the node to start from
  1520. *
  1521. * Processes all nodes in the row starting from cur.
  1522. *
  1523. * Returns non-negative value on success or negative value on fail
  1524. */
  1525. static int
  1526. xmlC14NProcessNodeList(xmlC14NCtxPtr ctx, xmlNodePtr cur)
  1527. {
  1528. int ret;
  1529. if (ctx == NULL) {
  1530. xmlC14NErrParam("processing node list");
  1531. return (-1);
  1532. }
  1533. for (ret = 0; cur != NULL && ret >= 0; cur = cur->next) {
  1534. ret = xmlC14NProcessNode(ctx, cur);
  1535. }
  1536. return (ret);
  1537. }
  1538. /**
  1539. * xmlC14NFreeCtx:
  1540. * @ctx: the pointer to C14N context object
  1541. *
  1542. * Cleanups the C14N context object.
  1543. */
  1544. static void
  1545. xmlC14NFreeCtx(xmlC14NCtxPtr ctx)
  1546. {
  1547. if (ctx == NULL) {
  1548. xmlC14NErrParam("freeing context");
  1549. return;
  1550. }
  1551. if (ctx->ns_rendered != NULL) {
  1552. xmlC14NVisibleNsStackDestroy(ctx->ns_rendered);
  1553. }
  1554. xmlFree(ctx);
  1555. }
  1556. /**
  1557. * xmlC14NNewCtx:
  1558. * @doc: the XML document for canonization
  1559. * @is_visible_callback:the function to use to determine is node visible
  1560. * or not
  1561. * @user_data: the first parameter for @is_visible_callback function
  1562. * (in most cases, it is nodes set)
  1563. * @mode: the c14n mode (see @xmlC14NMode)
  1564. * @inclusive_ns_prefixe the list of inclusive namespace prefixes
  1565. * ended with a NULL or NULL if there is no
  1566. * inclusive namespaces (only for `
  1567. * canonicalization)
  1568. * @with_comments: include comments in the result (!=0) or not (==0)
  1569. * @buf: the output buffer to store canonical XML; this
  1570. * buffer MUST have encoder==NULL because C14N requires
  1571. * UTF-8 output
  1572. *
  1573. * Creates new C14N context object to store C14N parameters.
  1574. *
  1575. * Returns pointer to newly created object (success) or NULL (fail)
  1576. */
  1577. static xmlC14NCtxPtr
  1578. xmlC14NNewCtx(xmlDocPtr doc,
  1579. xmlC14NIsVisibleCallback is_visible_callback, void* user_data,
  1580. xmlC14NMode mode, xmlChar ** inclusive_ns_prefixes,
  1581. int with_comments, xmlOutputBufferPtr buf)
  1582. {
  1583. xmlC14NCtxPtr ctx = NULL;
  1584. if ((doc == NULL) || (buf == NULL)) {
  1585. xmlC14NErrParam("creating new context");
  1586. return (NULL);
  1587. }
  1588. /*
  1589. * Validate the encoding output buffer encoding
  1590. */
  1591. if (buf->encoder != NULL) {
  1592. xmlC14NErr(ctx, (xmlNodePtr) doc, XML_C14N_REQUIRES_UTF8,
  1593. "xmlC14NNewCtx: output buffer encoder != NULL but C14N requires UTF8 output\n");
  1594. return (NULL);
  1595. }
  1596. /*
  1597. * Allocate a new xmlC14NCtxPtr and fill the fields.
  1598. */
  1599. ctx = (xmlC14NCtxPtr) xmlMalloc(sizeof(xmlC14NCtx));
  1600. if (ctx == NULL) {
  1601. xmlC14NErrMemory("creating context");
  1602. return (NULL);
  1603. }
  1604. memset(ctx, 0, sizeof(xmlC14NCtx));
  1605. /*
  1606. * initialize C14N context
  1607. */
  1608. ctx->doc = doc;
  1609. ctx->with_comments = with_comments;
  1610. ctx->is_visible_callback = is_visible_callback;
  1611. ctx->user_data = user_data;
  1612. ctx->buf = buf;
  1613. ctx->parent_is_doc = 1;
  1614. ctx->pos = XMLC14N_BEFORE_DOCUMENT_ELEMENT;
  1615. ctx->ns_rendered = xmlC14NVisibleNsStackCreate();
  1616. if(ctx->ns_rendered == NULL) {
  1617. xmlC14NErr(ctx, (xmlNodePtr) doc, XML_C14N_CREATE_STACK,
  1618. "xmlC14NNewCtx: xmlC14NVisibleNsStackCreate failed\n");
  1619. xmlC14NFreeCtx(ctx);
  1620. return (NULL);
  1621. }
  1622. /*
  1623. * Set "mode" flag and remember list of inclusive prefixes
  1624. * for exclusive c14n
  1625. */
  1626. ctx->mode = mode;
  1627. if(xmlC14NIsExclusive(ctx)) {
  1628. ctx->inclusive_ns_prefixes = inclusive_ns_prefixes;
  1629. }
  1630. return (ctx);
  1631. }
  1632. /**
  1633. * xmlC14NExecute:
  1634. * @doc: the XML document for canonization
  1635. * @is_visible_callback:the function to use to determine is node visible
  1636. * or not
  1637. * @user_data: the first parameter for @is_visible_callback function
  1638. * (in most cases, it is nodes set)
  1639. * @mode: the c14n mode (see @xmlC14NMode)
  1640. * @inclusive_ns_prefixes: the list of inclusive namespace prefixes
  1641. * ended with a NULL or NULL if there is no
  1642. * inclusive namespaces (only for exclusive
  1643. * canonicalization, ignored otherwise)
  1644. * @with_comments: include comments in the result (!=0) or not (==0)
  1645. * @buf: the output buffer to store canonical XML; this
  1646. * buffer MUST have encoder==NULL because C14N requires
  1647. * UTF-8 output
  1648. *
  1649. * Dumps the canonized image of given XML document into the provided buffer.
  1650. * For details see "Canonical XML" (http://www.w3.org/TR/xml-c14n) or
  1651. * "Exclusive XML Canonicalization" (http://www.w3.org/TR/xml-exc-c14n)
  1652. *
  1653. * Returns non-negative value on success or a negative value on fail
  1654. */
  1655. int
  1656. xmlC14NExecute(xmlDocPtr doc, xmlC14NIsVisibleCallback is_visible_callback,
  1657. void* user_data, int mode, xmlChar **inclusive_ns_prefixes,
  1658. int with_comments, xmlOutputBufferPtr buf) {
  1659. xmlC14NCtxPtr ctx;
  1660. xmlC14NMode c14n_mode = XML_C14N_1_0;
  1661. int ret;
  1662. if ((buf == NULL) || (doc == NULL)) {
  1663. xmlC14NErrParam("executing c14n");
  1664. return (-1);
  1665. }
  1666. /* for backward compatibility, we have to have "mode" as "int"
  1667. and here we check that user gives valid value */
  1668. switch(mode) {
  1669. case XML_C14N_1_0:
  1670. case XML_C14N_EXCLUSIVE_1_0:
  1671. case XML_C14N_1_1:
  1672. c14n_mode = (xmlC14NMode)mode;
  1673. break;
  1674. default:
  1675. xmlC14NErrParam("invalid mode for executing c14n");
  1676. return (-1);
  1677. }
  1678. /*
  1679. * Validate the encoding output buffer encoding
  1680. */
  1681. if (buf->encoder != NULL) {
  1682. xmlC14NErr(NULL, (xmlNodePtr) doc, XML_C14N_REQUIRES_UTF8,
  1683. "xmlC14NExecute: output buffer encoder != NULL but C14N requires UTF8 output\n");
  1684. return (-1);
  1685. }
  1686. ctx = xmlC14NNewCtx(doc, is_visible_callback, user_data,
  1687. c14n_mode, inclusive_ns_prefixes,
  1688. with_comments, buf);
  1689. if (ctx == NULL) {
  1690. xmlC14NErr(NULL, (xmlNodePtr) doc, XML_C14N_CREATE_CTXT,
  1691. "xmlC14NExecute: unable to create C14N context\n");
  1692. return (-1);
  1693. }
  1694. /*
  1695. * Root Node
  1696. * The root node is the parent of the top-level document element. The
  1697. * result of processing each of its child nodes that is in the node-set
  1698. * in document order. The root node does not generate a byte order mark,
  1699. * XML declaration, nor anything from within the document type
  1700. * declaration.
  1701. */
  1702. if (doc->children != NULL) {
  1703. ret = xmlC14NProcessNodeList(ctx, doc->children);
  1704. if (ret < 0) {
  1705. xmlC14NErrInternal("processing docs children list");
  1706. xmlC14NFreeCtx(ctx);
  1707. return (-1);
  1708. }
  1709. }
  1710. /*
  1711. * Flush buffer to get number of bytes written
  1712. */
  1713. ret = xmlOutputBufferFlush(buf);
  1714. if (ret < 0) {
  1715. xmlC14NErrInternal("flushing output buffer");
  1716. xmlC14NFreeCtx(ctx);
  1717. return (-1);
  1718. }
  1719. /*
  1720. * Cleanup
  1721. */
  1722. xmlC14NFreeCtx(ctx);
  1723. return (ret);
  1724. }
  1725. /**
  1726. * xmlC14NDocSaveTo:
  1727. * @doc: the XML document for canonization
  1728. * @nodes: the nodes set to be included in the canonized image
  1729. * or NULL if all document nodes should be included
  1730. * @mode: the c14n mode (see @xmlC14NMode)
  1731. * @inclusive_ns_prefixes: the list of inclusive namespace prefixes
  1732. * ended with a NULL or NULL if there is no
  1733. * inclusive namespaces (only for exclusive
  1734. * canonicalization, ignored otherwise)
  1735. * @with_comments: include comments in the result (!=0) or not (==0)
  1736. * @buf: the output buffer to store canonical XML; this
  1737. * buffer MUST have encoder==NULL because C14N requires
  1738. * UTF-8 output
  1739. *
  1740. * Dumps the canonized image of given XML document into the provided buffer.
  1741. * For details see "Canonical XML" (http://www.w3.org/TR/xml-c14n) or
  1742. * "Exclusive XML Canonicalization" (http://www.w3.org/TR/xml-exc-c14n)
  1743. *
  1744. * Returns non-negative value on success or a negative value on fail
  1745. */
  1746. int
  1747. xmlC14NDocSaveTo(xmlDocPtr doc, xmlNodeSetPtr nodes,
  1748. int mode, xmlChar ** inclusive_ns_prefixes,
  1749. int with_comments, xmlOutputBufferPtr buf) {
  1750. return(xmlC14NExecute(doc,
  1751. xmlC14NIsNodeInNodeset,
  1752. nodes,
  1753. mode,
  1754. inclusive_ns_prefixes,
  1755. with_comments,
  1756. buf));
  1757. }
  1758. /**
  1759. * xmlC14NDocDumpMemory:
  1760. * @doc: the XML document for canonization
  1761. * @nodes: the nodes set to be included in the canonized image
  1762. * or NULL if all document nodes should be included
  1763. * @mode: the c14n mode (see @xmlC14NMode)
  1764. * @inclusive_ns_prefixes: the list of inclusive namespace prefixes
  1765. * ended with a NULL or NULL if there is no
  1766. * inclusive namespaces (only for exclusive
  1767. * canonicalization, ignored otherwise)
  1768. * @with_comments: include comments in the result (!=0) or not (==0)
  1769. * @doc_txt_ptr: the memory pointer for allocated canonical XML text;
  1770. * the caller of this functions is responsible for calling
  1771. * xmlFree() to free allocated memory
  1772. *
  1773. * Dumps the canonized image of given XML document into memory.
  1774. * For details see "Canonical XML" (http://www.w3.org/TR/xml-c14n) or
  1775. * "Exclusive XML Canonicalization" (http://www.w3.org/TR/xml-exc-c14n)
  1776. *
  1777. * Returns the number of bytes written on success or a negative value on fail
  1778. */
  1779. int
  1780. xmlC14NDocDumpMemory(xmlDocPtr doc, xmlNodeSetPtr nodes,
  1781. int mode, xmlChar ** inclusive_ns_prefixes,
  1782. int with_comments, xmlChar ** doc_txt_ptr)
  1783. {
  1784. int ret;
  1785. xmlOutputBufferPtr buf;
  1786. if (doc_txt_ptr == NULL) {
  1787. xmlC14NErrParam("dumping doc to memory");
  1788. return (-1);
  1789. }
  1790. *doc_txt_ptr = NULL;
  1791. /*
  1792. * create memory buffer with UTF8 (default) encoding
  1793. */
  1794. buf = xmlAllocOutputBuffer(NULL);
  1795. if (buf == NULL) {
  1796. xmlC14NErrMemory("creating output buffer");
  1797. return (-1);
  1798. }
  1799. /*
  1800. * canonize document and write to buffer
  1801. */
  1802. ret = xmlC14NDocSaveTo(doc, nodes, mode, inclusive_ns_prefixes,
  1803. with_comments, buf);
  1804. if (ret < 0) {
  1805. xmlC14NErrInternal("saving doc to output buffer");
  1806. (void) xmlOutputBufferClose(buf);
  1807. return (-1);
  1808. }
  1809. ret = xmlBufUse(buf->buffer);
  1810. if (ret >= 0) {
  1811. *doc_txt_ptr = xmlStrndup(xmlBufContent(buf->buffer), ret);
  1812. }
  1813. (void) xmlOutputBufferClose(buf);
  1814. if ((*doc_txt_ptr == NULL) && (ret >= 0)) {
  1815. xmlC14NErrMemory("copying canonicalized document");
  1816. return (-1);
  1817. }
  1818. return (ret);
  1819. }
  1820. /**
  1821. * xmlC14NDocSave:
  1822. * @doc: the XML document for canonization
  1823. * @nodes: the nodes set to be included in the canonized image
  1824. * or NULL if all document nodes should be included
  1825. * @mode: the c14n mode (see @xmlC14NMode)
  1826. * @inclusive_ns_prefixes: the list of inclusive namespace prefixes
  1827. * ended with a NULL or NULL if there is no
  1828. * inclusive namespaces (only for exclusive
  1829. * canonicalization, ignored otherwise)
  1830. * @with_comments: include comments in the result (!=0) or not (==0)
  1831. * @filename: the filename to store canonical XML image
  1832. * @compression: the compression level (zlib required):
  1833. * -1 - libxml default,
  1834. * 0 - uncompressed,
  1835. * >0 - compression level
  1836. *
  1837. * Dumps the canonized image of given XML document into the file.
  1838. * For details see "Canonical XML" (http://www.w3.org/TR/xml-c14n) or
  1839. * "Exclusive XML Canonicalization" (http://www.w3.org/TR/xml-exc-c14n)
  1840. *
  1841. * Returns the number of bytes written success or a negative value on fail
  1842. */
  1843. int
  1844. xmlC14NDocSave(xmlDocPtr doc, xmlNodeSetPtr nodes,
  1845. int mode, xmlChar ** inclusive_ns_prefixes,
  1846. int with_comments, const char *filename, int compression)
  1847. {
  1848. xmlOutputBufferPtr buf;
  1849. int ret;
  1850. if (filename == NULL) {
  1851. xmlC14NErrParam("saving doc");
  1852. return (-1);
  1853. }
  1854. #ifdef LIBXML_ZLIB_ENABLED
  1855. if (compression < 0)
  1856. compression = xmlGetCompressMode();
  1857. #endif
  1858. /*
  1859. * save the content to a temp buffer, use default UTF8 encoding.
  1860. */
  1861. buf = xmlOutputBufferCreateFilename(filename, NULL, compression);
  1862. if (buf == NULL) {
  1863. xmlC14NErrInternal("creating temporary filename");
  1864. return (-1);
  1865. }
  1866. /*
  1867. * canonize document and write to buffer
  1868. */
  1869. ret = xmlC14NDocSaveTo(doc, nodes, mode, inclusive_ns_prefixes,
  1870. with_comments, buf);
  1871. if (ret < 0) {
  1872. xmlC14NErrInternal("canonize document to buffer");
  1873. (void) xmlOutputBufferClose(buf);
  1874. return (-1);
  1875. }
  1876. /*
  1877. * get the numbers of bytes written
  1878. */
  1879. ret = xmlOutputBufferClose(buf);
  1880. return (ret);
  1881. }
  1882. /*
  1883. * Macro used to grow the current buffer.
  1884. */
  1885. #define growBufferReentrant() { \
  1886. buffer_size *= 2; \
  1887. buffer = (xmlChar *) \
  1888. xmlRealloc(buffer, buffer_size); \
  1889. if (buffer == NULL) { \
  1890. xmlC14NErrMemory("growing buffer"); \
  1891. return(NULL); \
  1892. } \
  1893. }
  1894. /**
  1895. * xmlC11NNormalizeString:
  1896. * @input: the input string
  1897. * @mode: the normalization mode (attribute, comment, PI or text)
  1898. *
  1899. * Converts a string to a canonical (normalized) format. The code is stolen
  1900. * from xmlEncodeEntitiesReentrant(). Added normalization of \x09, \x0a, \x0A
  1901. * and the @mode parameter
  1902. *
  1903. * Returns a normalized string (caller is responsible for calling xmlFree())
  1904. * or NULL if an error occurs
  1905. */
  1906. static xmlChar *
  1907. xmlC11NNormalizeString(const xmlChar * input,
  1908. xmlC14NNormalizationMode mode)
  1909. {
  1910. const xmlChar *cur = input;
  1911. xmlChar *buffer = NULL;
  1912. xmlChar *out = NULL;
  1913. int buffer_size = 0;
  1914. if (input == NULL)
  1915. return (NULL);
  1916. /*
  1917. * allocate an translation buffer.
  1918. */
  1919. buffer_size = 1000;
  1920. buffer = (xmlChar *) xmlMallocAtomic(buffer_size);
  1921. if (buffer == NULL) {
  1922. xmlC14NErrMemory("allocating buffer");
  1923. return (NULL);
  1924. }
  1925. out = buffer;
  1926. while (*cur != '\0') {
  1927. if ((out - buffer) > (buffer_size - 10)) {
  1928. int indx = out - buffer;
  1929. growBufferReentrant();
  1930. out = &buffer[indx];
  1931. }
  1932. if ((*cur == '<') && ((mode == XMLC14N_NORMALIZE_ATTR) ||
  1933. (mode == XMLC14N_NORMALIZE_TEXT))) {
  1934. *out++ = '&';
  1935. *out++ = 'l';
  1936. *out++ = 't';
  1937. *out++ = ';';
  1938. } else if ((*cur == '>') && (mode == XMLC14N_NORMALIZE_TEXT)) {
  1939. *out++ = '&';
  1940. *out++ = 'g';
  1941. *out++ = 't';
  1942. *out++ = ';';
  1943. } else if ((*cur == '&') && ((mode == XMLC14N_NORMALIZE_ATTR) ||
  1944. (mode == XMLC14N_NORMALIZE_TEXT))) {
  1945. *out++ = '&';
  1946. *out++ = 'a';
  1947. *out++ = 'm';
  1948. *out++ = 'p';
  1949. *out++ = ';';
  1950. } else if ((*cur == '"') && (mode == XMLC14N_NORMALIZE_ATTR)) {
  1951. *out++ = '&';
  1952. *out++ = 'q';
  1953. *out++ = 'u';
  1954. *out++ = 'o';
  1955. *out++ = 't';
  1956. *out++ = ';';
  1957. } else if ((*cur == '\x09') && (mode == XMLC14N_NORMALIZE_ATTR)) {
  1958. *out++ = '&';
  1959. *out++ = '#';
  1960. *out++ = 'x';
  1961. *out++ = '9';
  1962. *out++ = ';';
  1963. } else if ((*cur == '\x0A') && (mode == XMLC14N_NORMALIZE_ATTR)) {
  1964. *out++ = '&';
  1965. *out++ = '#';
  1966. *out++ = 'x';
  1967. *out++ = 'A';
  1968. *out++ = ';';
  1969. } else if ((*cur == '\x0D') && ((mode == XMLC14N_NORMALIZE_ATTR) ||
  1970. (mode == XMLC14N_NORMALIZE_TEXT) ||
  1971. (mode == XMLC14N_NORMALIZE_COMMENT) ||
  1972. (mode == XMLC14N_NORMALIZE_PI))) {
  1973. *out++ = '&';
  1974. *out++ = '#';
  1975. *out++ = 'x';
  1976. *out++ = 'D';
  1977. *out++ = ';';
  1978. } else {
  1979. /*
  1980. * Works because on UTF-8, all extended sequences cannot
  1981. * result in bytes in the ASCII range.
  1982. */
  1983. *out++ = *cur;
  1984. }
  1985. cur++;
  1986. }
  1987. *out = 0;
  1988. return (buffer);
  1989. }
  1990. #endif /* LIBXML_C14N_ENABLED */