xml_element.c 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767
  1. /*
  2. This file is part of libXMLRPC - a C library for xml-encoded function calls.
  3. Author: Dan Libby (dan@libby.com)
  4. Epinions.com may be contacted at feedback@epinions-inc.com
  5. */
  6. /*
  7. Copyright 2000 Epinions, Inc.
  8. Subject to the following 3 conditions, Epinions, Inc. permits you, free
  9. of charge, to (a) use, copy, distribute, modify, perform and display this
  10. software and associated documentation files (the "Software"), and (b)
  11. permit others to whom the Software is furnished to do so as well.
  12. 1) The above copyright notice and this permission notice shall be included
  13. without modification in all copies or substantial portions of the
  14. Software.
  15. 2) THE SOFTWARE IS PROVIDED "AS IS", WITHOUT ANY WARRANTY OR CONDITION OF
  16. ANY KIND, EXPRESS, IMPLIED OR STATUTORY, INCLUDING WITHOUT LIMITATION ANY
  17. IMPLIED WARRANTIES OF ACCURACY, MERCHANTABILITY, FITNESS FOR A PARTICULAR
  18. PURPOSE OR NONINFRINGEMENT.
  19. 3) IN NO EVENT SHALL EPINIONS, INC. BE LIABLE FOR ANY DIRECT, INDIRECT,
  20. SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES OR LOST PROFITS ARISING OUT
  21. OF OR IN CONNECTION WITH THE SOFTWARE (HOWEVER ARISING, INCLUDING
  22. NEGLIGENCE), EVEN IF EPINIONS, INC. IS AWARE OF THE POSSIBILITY OF SUCH
  23. DAMAGES.
  24. */
  25. static const char rcsid[] = "#(@) $Id$";
  26. /****h* ABOUT/xml_element
  27. * NAME
  28. * xml_element
  29. * AUTHOR
  30. * Dan Libby, aka danda (dan@libby.com)
  31. * CREATION DATE
  32. * 06/2000
  33. * HISTORY
  34. * $Log$
  35. * Revision 1.9.4.1.2.1 2008/12/09 17:22:12 iliaa
  36. *
  37. * MFH: Fixed bug #46746 (xmlrpc_decode_request outputs non-suppressable error
  38. * when given bad data).
  39. *
  40. * Revision 1.9.4.1 2006/07/30 11:34:02 tony2001
  41. * MFH: fix compile warnings (#38257)
  42. *
  43. * Revision 1.9 2005/04/22 11:06:53 jorton
  44. * Fixed bug #32797 (invalid C code in xmlrpc extension).
  45. *
  46. * Revision 1.8 2005/03/28 00:07:24 edink
  47. * Reshufle includes to make it compile on windows
  48. *
  49. * Revision 1.7 2005/03/26 03:13:58 sniper
  50. * - Made it possible to build ext/xmlrpc with libxml2
  51. *
  52. * Revision 1.6 2004/06/01 20:16:06 iliaa
  53. * Fixed bug #28597 (xmlrpc_encode_request() incorrectly encodes chars in
  54. * 200-210 range).
  55. * Patch by: fernando dot nemec at folha dot com dot br
  56. *
  57. * Revision 1.5 2003/12/16 21:00:21 sniper
  58. * Fix some compile warnings (patch by Joe Orton)
  59. *
  60. * Revision 1.4 2002/11/26 23:01:16 fmk
  61. * removing unused variables
  62. *
  63. * Revision 1.3 2002/07/05 04:43:53 danda
  64. * merged in updates from SF project. bring php repository up to date with xmlrpc-epi version 0.51
  65. *
  66. * Revision 1.9 2002/07/03 20:54:30 danda
  67. * root element should not have a parent. patch from anon SF user
  68. *
  69. * Revision 1.8 2002/05/23 17:46:51 danda
  70. * patch from mukund - fix non utf-8 encoding conversions
  71. *
  72. * Revision 1.7 2002/02/13 20:58:50 danda
  73. * patch to make source more windows friendly, contributed by Jeff Lawson
  74. *
  75. * Revision 1.6 2002/01/08 01:06:55 danda
  76. * enable <?xml version="1.0"?> format for parsers that are very picky.
  77. *
  78. * Revision 1.5 2001/09/29 21:58:05 danda
  79. * adding cvs log to history section
  80. *
  81. * 10/15/2000 -- danda -- adding robodoc documentation
  82. * TODO
  83. * Nicer external API. Get rid of macros. Make opaque types, etc.
  84. * PORTABILITY
  85. * Coded on RedHat Linux 6.2. Builds on Solaris x86. Should build on just
  86. * about anything with minor mods.
  87. * NOTES
  88. * This code incorporates ideas from expat-ensor from http://xml.ensor.org.
  89. *
  90. * It was coded primarily to act as a go-between for expat and xmlrpc. To this
  91. * end, it stores xml elements, their sub-elements, and their attributes in an
  92. * in-memory tree. When expat is done parsing, the tree can be walked, thus
  93. * retrieving the values. The code can also be used to build a tree via API then
  94. * write out the tree to a buffer, thus "serializing" the xml.
  95. *
  96. * It turns out this is useful for other purposes, such as parsing config files.
  97. * YMMV.
  98. *
  99. * Some Features:
  100. * - output option for xml escaping data. Choices include no escaping, entity escaping,
  101. * or CDATA sections.
  102. * - output option for character encoding. Defaults to (none) utf-8.
  103. * - output option for verbosity/readability. ultra-compact, newlines, pretty/level indented.
  104. *
  105. * BUGS
  106. * there must be some.
  107. ******/
  108. #include "ext/xml/expat_compat.h"
  109. #include <stdlib.h>
  110. #include <string.h>
  111. #include <ctype.h>
  112. #include "xml_element.h"
  113. #include "queue.h"
  114. #include "encodings.h"
  115. #define my_free(thing) if(thing) {efree(thing); thing = NULL;}
  116. #define XML_DECL_START "<?xml"
  117. #define XML_DECL_START_LEN sizeof(XML_DECL_START) - 1
  118. #define XML_DECL_VERSION "version=\"1.0\""
  119. #define XML_DECL_VERSION_LEN sizeof(XML_DECL_VERSION) - 1
  120. #define XML_DECL_ENCODING_ATTR "encoding"
  121. #define XML_DECL_ENCODING_ATTR_LEN sizeof(XML_DECL_ENCODING_ATTR) - 1
  122. #define XML_DECL_ENCODING_DEFAULT "utf-8"
  123. #define XML_DECL_ENCODING_DEFAULT_LEN sizeof(XML_DECL_ENCODING_DEFAULT) - 1
  124. #define XML_DECL_END "?>"
  125. #define XML_DECL_END_LEN sizeof(XML_DECL_END) - 1
  126. #define START_TOKEN_BEGIN "<"
  127. #define START_TOKEN_BEGIN_LEN sizeof(START_TOKEN_BEGIN) - 1
  128. #define START_TOKEN_END ">"
  129. #define START_TOKEN_END_LEN sizeof(START_TOKEN_END) - 1
  130. #define EMPTY_START_TOKEN_END "/>"
  131. #define EMPTY_START_TOKEN_END_LEN sizeof(EMPTY_START_TOKEN_END) - 1
  132. #define END_TOKEN_BEGIN "</"
  133. #define END_TOKEN_BEGIN_LEN sizeof(END_TOKEN_BEGIN) - 1
  134. #define END_TOKEN_END ">"
  135. #define END_TOKEN_END_LEN sizeof(END_TOKEN_END) - 1
  136. #define ATTR_DELIMITER "\""
  137. #define ATTR_DELIMITER_LEN sizeof(ATTR_DELIMITER) - 1
  138. #define CDATA_BEGIN "<![CDATA["
  139. #define CDATA_BEGIN_LEN sizeof(CDATA_BEGIN) - 1
  140. #define CDATA_END "]]>"
  141. #define CDATA_END_LEN sizeof(CDATA_END) - 1
  142. #define EQUALS "="
  143. #define EQUALS_LEN sizeof(EQUALS) - 1
  144. #define WHITESPACE " "
  145. #define WHITESPACE_LEN sizeof(WHITESPACE) - 1
  146. #define NEWLINE "\n"
  147. #define NEWLINE_LEN sizeof(NEWLINE) - 1
  148. #define MAX_VAL_BUF 144
  149. #define SCALAR_STR "SCALAR"
  150. #define SCALAR_STR_LEN sizeof(SCALAR_STR) - 1
  151. #define VECTOR_STR "VECTOR"
  152. #define VECTOR_STR_LEN sizeof(VECTOR_STR) - 1
  153. #define RESPONSE_STR "RESPONSE"
  154. #define RESPONSE_STR_LEN sizeof(RESPONSE_STR) - 1
  155. /*-----------------------------
  156. - Begin xml_element Functions -
  157. -----------------------------*/
  158. /****f* xml_element/xml_elem_free_non_recurse
  159. * NAME
  160. * xml_elem_free_non_recurse
  161. * SYNOPSIS
  162. * void xml_elem_free_non_recurse(xml_element* root)
  163. * FUNCTION
  164. * free a single xml element. child elements will not be freed.
  165. * INPUTS
  166. * root - the element to free
  167. * RESULT
  168. * void
  169. * NOTES
  170. * SEE ALSO
  171. * xml_elem_free ()
  172. * xml_elem_new ()
  173. * SOURCE
  174. */
  175. void xml_elem_free_non_recurse(xml_element* root) {
  176. if(root) {
  177. xml_element_attr* attrs = Q_Head(&root->attrs);
  178. while(attrs) {
  179. my_free(attrs->key);
  180. my_free(attrs->val);
  181. my_free(attrs);
  182. attrs = Q_Next(&root->attrs);
  183. }
  184. Q_Destroy(&root->children);
  185. Q_Destroy(&root->attrs);
  186. if(root->name) {
  187. efree((char *)root->name);
  188. root->name = NULL;
  189. }
  190. simplestring_free(&root->text);
  191. my_free(root);
  192. }
  193. }
  194. /******/
  195. /****f* xml_element/xml_elem_free
  196. * NAME
  197. * xml_elem_free
  198. * SYNOPSIS
  199. * void xml_elem_free(xml_element* root)
  200. * FUNCTION
  201. * free an xml element and all of its child elements
  202. * INPUTS
  203. * root - the root of an xml tree you would like to free
  204. * RESULT
  205. * void
  206. * NOTES
  207. * SEE ALSO
  208. * xml_elem_free_non_recurse ()
  209. * xml_elem_new ()
  210. * SOURCE
  211. */
  212. void xml_elem_free(xml_element* root) {
  213. if(root) {
  214. xml_element* kids = Q_Head(&root->children);
  215. while(kids) {
  216. xml_elem_free(kids);
  217. kids = Q_Next(&root->children);
  218. }
  219. xml_elem_free_non_recurse(root);
  220. }
  221. }
  222. /******/
  223. /****f* xml_element/xml_elem_new
  224. * NAME
  225. * xml_elem_new
  226. * SYNOPSIS
  227. * xml_element* xml_elem_new()
  228. * FUNCTION
  229. * allocates and initializes a new xml_element
  230. * INPUTS
  231. * none
  232. * RESULT
  233. * xml_element* or NULL. NULL indicates an out-of-memory condition.
  234. * NOTES
  235. * SEE ALSO
  236. * xml_elem_free ()
  237. * xml_elem_free_non_recurse ()
  238. * SOURCE
  239. */
  240. xml_element* xml_elem_new() {
  241. xml_element* elem = ecalloc(1, sizeof(xml_element));
  242. if(elem) {
  243. Q_Init(&elem->children);
  244. Q_Init(&elem->attrs);
  245. simplestring_init(&elem->text);
  246. /* init empty string in case we don't find any char data */
  247. simplestring_addn(&elem->text, "", 0);
  248. }
  249. return elem;
  250. }
  251. /******/
  252. static int xml_elem_writefunc(int (*fptr)(void *data, const char *text, int size), const char *text, void *data, int len)
  253. {
  254. return fptr && text ? fptr(data, text, len ? len : strlen(text)) : 0;
  255. }
  256. static int create_xml_escape(char *pString, unsigned char c)
  257. {
  258. int counter = 0;
  259. pString[counter++] = '&';
  260. pString[counter++] = '#';
  261. if(c >= 100) {
  262. pString[counter++] = c / 100 + '0';
  263. c = c % 100;
  264. }
  265. pString[counter++] = c / 10 + '0';
  266. c = c % 10;
  267. pString[counter++] = c + '0';
  268. pString[counter++] = ';';
  269. return counter;
  270. }
  271. #define non_ascii(c) (c > 127)
  272. #define non_print(c) (!isprint(c))
  273. #define markup(c) (c == '&' || c == '\"' || c == '>' || c == '<')
  274. #define entity_length(c) ( (c >= 100) ? 3 : ((c >= 10) ? 2 : 1) ) + 3; /* "&#" + c + ";" */
  275. /*
  276. * xml_elem_entity_escape
  277. *
  278. * Purpose:
  279. * escape reserved xml chars and non utf-8 chars as xml entities
  280. * Comments:
  281. * The return value may be a new string, or null if no
  282. * conversion was performed. In the latter case, *newlen will
  283. * be 0.
  284. * Flags (to escape)
  285. * xml_elem_no_escaping = 0x000,
  286. * xml_elem_entity_escaping = 0x002, // escape xml special chars as entities
  287. * xml_elem_non_ascii_escaping = 0x008, // escape chars above 127
  288. * xml_elem_cdata_escaping = 0x010, // wrap in cdata
  289. */
  290. static char* xml_elem_entity_escape(const char* buf, int old_len, int *newlen, XML_ELEM_ESCAPING flags) {
  291. char *pRetval = 0;
  292. int iNewBufLen=0;
  293. #define should_escape(c, flag) ( ((flag & xml_elem_markup_escaping) && markup(c)) || \
  294. ((flag & xml_elem_non_ascii_escaping) && non_ascii(c)) || \
  295. ((flag & xml_elem_non_print_escaping) && non_print(c)) )
  296. if(buf && *buf) {
  297. const unsigned char *bufcopy;
  298. char *NewBuffer;
  299. int ToBeXmlEscaped=0;
  300. int iLength;
  301. bufcopy = buf;
  302. iLength= old_len ? old_len : strlen(buf);
  303. while(*bufcopy) {
  304. if( should_escape(*bufcopy, flags) ) {
  305. /* the length will increase by length of xml escape - the character length */
  306. iLength += entity_length(*bufcopy);
  307. ToBeXmlEscaped=1;
  308. }
  309. bufcopy++;
  310. }
  311. if(ToBeXmlEscaped) {
  312. NewBuffer= emalloc(iLength+1);
  313. if(NewBuffer) {
  314. bufcopy=buf;
  315. while(*bufcopy) {
  316. if(should_escape(*bufcopy, flags)) {
  317. iNewBufLen += create_xml_escape(NewBuffer+iNewBufLen,*bufcopy);
  318. }
  319. else {
  320. NewBuffer[iNewBufLen++]=*bufcopy;
  321. }
  322. bufcopy++;
  323. }
  324. NewBuffer[iNewBufLen] = 0;
  325. pRetval = NewBuffer;
  326. }
  327. }
  328. }
  329. if(newlen) {
  330. *newlen = iNewBufLen;
  331. }
  332. return pRetval;
  333. }
  334. static void xml_element_serialize(xml_element *el, int (*fptr)(void *data, const char *text, int size), void *data, XML_ELEM_OUTPUT_OPTIONS options, int depth)
  335. {
  336. int i;
  337. static STRUCT_XML_ELEM_OUTPUT_OPTIONS default_opts = {xml_elem_pretty, xml_elem_markup_escaping | xml_elem_non_print_escaping, XML_DECL_ENCODING_DEFAULT};
  338. static char whitespace[] = " "
  339. " "
  340. " ";
  341. depth++;
  342. if(!el) {
  343. /* fprintf(stderr, "Nothing to write\n"); */
  344. return;
  345. }
  346. if(!options) {
  347. options = &default_opts;
  348. }
  349. /* print xml declaration if at root level */
  350. if(depth == 1) {
  351. xml_elem_writefunc(fptr, XML_DECL_START, data, XML_DECL_START_LEN);
  352. xml_elem_writefunc(fptr, WHITESPACE, data, WHITESPACE_LEN);
  353. xml_elem_writefunc(fptr, XML_DECL_VERSION, data, XML_DECL_VERSION_LEN);
  354. if(options->encoding && *options->encoding) {
  355. xml_elem_writefunc(fptr, WHITESPACE, data, WHITESPACE_LEN);
  356. xml_elem_writefunc(fptr, XML_DECL_ENCODING_ATTR, data, XML_DECL_ENCODING_ATTR_LEN);
  357. xml_elem_writefunc(fptr, EQUALS, data, EQUALS_LEN);
  358. xml_elem_writefunc(fptr, ATTR_DELIMITER, data, ATTR_DELIMITER_LEN);
  359. xml_elem_writefunc(fptr, options->encoding, data, 0);
  360. xml_elem_writefunc(fptr, ATTR_DELIMITER, data, ATTR_DELIMITER_LEN);
  361. }
  362. xml_elem_writefunc(fptr, XML_DECL_END, data, XML_DECL_END_LEN);
  363. if(options->verbosity != xml_elem_no_white_space) {
  364. xml_elem_writefunc(fptr, NEWLINE, data, NEWLINE_LEN);
  365. }
  366. }
  367. if(options->verbosity == xml_elem_pretty && depth > 2) {
  368. xml_elem_writefunc(fptr, whitespace, data, depth - 2);
  369. }
  370. /* begin element */
  371. xml_elem_writefunc(fptr,START_TOKEN_BEGIN, data, START_TOKEN_BEGIN_LEN);
  372. if(el->name) {
  373. xml_elem_writefunc(fptr, el->name, data, 0);
  374. /* write attrs, if any */
  375. if(Q_Size(&el->attrs)) {
  376. xml_element_attr* iter = Q_Head(&el->attrs);
  377. while( iter ) {
  378. xml_elem_writefunc(fptr, WHITESPACE, data, WHITESPACE_LEN);
  379. xml_elem_writefunc(fptr, iter->key, data, 0);
  380. xml_elem_writefunc(fptr, EQUALS, data, EQUALS_LEN);
  381. xml_elem_writefunc(fptr, ATTR_DELIMITER, data, ATTR_DELIMITER_LEN);
  382. xml_elem_writefunc(fptr, iter->val, data, 0);
  383. xml_elem_writefunc(fptr, ATTR_DELIMITER, data, ATTR_DELIMITER_LEN);
  384. iter = Q_Next(&el->attrs);
  385. }
  386. }
  387. }
  388. else {
  389. xml_elem_writefunc(fptr, "None", data, 0);
  390. }
  391. /* if no text and no children, use abbreviated form, eg: <foo/> */
  392. if(!el->text.len && !Q_Size(&el->children)) {
  393. xml_elem_writefunc(fptr, EMPTY_START_TOKEN_END, data, EMPTY_START_TOKEN_END_LEN);
  394. }
  395. /* otherwise, print element contents */
  396. else {
  397. xml_elem_writefunc(fptr, START_TOKEN_END, data, START_TOKEN_END_LEN);
  398. /* print text, if any */
  399. if(el->text.len) {
  400. char* escaped_str = el->text.str;
  401. int buflen = el->text.len;
  402. if(options->escaping && options->escaping != xml_elem_cdata_escaping) {
  403. escaped_str = xml_elem_entity_escape(el->text.str, buflen, &buflen, options->escaping );
  404. if(!escaped_str) {
  405. escaped_str = el->text.str;
  406. }
  407. }
  408. if(options->escaping & xml_elem_cdata_escaping) {
  409. xml_elem_writefunc(fptr, CDATA_BEGIN, data, CDATA_BEGIN_LEN);
  410. }
  411. xml_elem_writefunc(fptr, escaped_str, data, buflen);
  412. if(escaped_str != el->text.str) {
  413. my_free(escaped_str);
  414. }
  415. if(options->escaping & xml_elem_cdata_escaping) {
  416. xml_elem_writefunc(fptr, CDATA_END, data, CDATA_END_LEN);
  417. }
  418. }
  419. /* no text, so print child elems */
  420. else {
  421. xml_element *kids = Q_Head(&el->children);
  422. i = 0;
  423. while( kids ) {
  424. if(i++ == 0) {
  425. if(options->verbosity != xml_elem_no_white_space) {
  426. xml_elem_writefunc(fptr, NEWLINE, data, NEWLINE_LEN);
  427. }
  428. }
  429. xml_element_serialize(kids, fptr, data, options, depth);
  430. kids = Q_Next(&el->children);
  431. }
  432. if(i) {
  433. if(options->verbosity == xml_elem_pretty && depth > 2) {
  434. xml_elem_writefunc(fptr, whitespace, data, depth - 2);
  435. }
  436. }
  437. }
  438. xml_elem_writefunc(fptr, END_TOKEN_BEGIN, data, END_TOKEN_BEGIN_LEN);
  439. xml_elem_writefunc(fptr,el->name ? el->name : "None", data, 0);
  440. xml_elem_writefunc(fptr, END_TOKEN_END, data, END_TOKEN_END_LEN);
  441. }
  442. if(options->verbosity != xml_elem_no_white_space) {
  443. xml_elem_writefunc(fptr, NEWLINE, data, NEWLINE_LEN);
  444. }
  445. }
  446. /* print buf to file */
  447. static int file_out_fptr(void *f, const char *text, int size)
  448. {
  449. fputs(text, (FILE *)f);
  450. return 0;
  451. }
  452. /* print buf to simplestring */
  453. static int simplestring_out_fptr(void *f, const char *text, int size)
  454. {
  455. simplestring* buf = (simplestring*)f;
  456. if(buf) {
  457. simplestring_addn(buf, text, size);
  458. }
  459. return 0;
  460. }
  461. /****f* xml_element/xml_elem_serialize_to_string
  462. * NAME
  463. * xml_elem_serialize_to_string
  464. * SYNOPSIS
  465. * void xml_element_serialize_to_string(xml_element *el, XML_ELEM_OUTPUT_OPTIONS options, int *buf_len)
  466. * FUNCTION
  467. * writes element tree as XML into a newly allocated buffer
  468. * INPUTS
  469. * el - root element of tree
  470. * options - options determining how output is written. see XML_ELEM_OUTPUT_OPTIONS
  471. * buf_len - length of returned buffer, if not null.
  472. * RESULT
  473. * char* or NULL. Must be free'd by caller.
  474. * NOTES
  475. * SEE ALSO
  476. * xml_elem_serialize_to_stream ()
  477. * xml_elem_parse_buf ()
  478. * SOURCE
  479. */
  480. char* xml_elem_serialize_to_string(xml_element *el, XML_ELEM_OUTPUT_OPTIONS options, int *buf_len)
  481. {
  482. simplestring buf;
  483. simplestring_init(&buf);
  484. xml_element_serialize(el, simplestring_out_fptr, (void *)&buf, options, 0);
  485. if(buf_len) {
  486. *buf_len = buf.len;
  487. }
  488. return buf.str;
  489. }
  490. /******/
  491. /****f* xml_element/xml_elem_serialize_to_stream
  492. * NAME
  493. * xml_elem_serialize_to_stream
  494. * SYNOPSIS
  495. * void xml_elem_serialize_to_stream(xml_element *el, FILE *output, XML_ELEM_OUTPUT_OPTIONS options)
  496. * FUNCTION
  497. * writes element tree as XML into a stream (typically an opened file)
  498. * INPUTS
  499. * el - root element of tree
  500. * output - stream handle
  501. * options - options determining how output is written. see XML_ELEM_OUTPUT_OPTIONS
  502. * RESULT
  503. * void
  504. * NOTES
  505. * SEE ALSO
  506. * xml_elem_serialize_to_string ()
  507. * xml_elem_parse_buf ()
  508. * SOURCE
  509. */
  510. void xml_elem_serialize_to_stream(xml_element *el, FILE *output, XML_ELEM_OUTPUT_OPTIONS options)
  511. {
  512. xml_element_serialize(el, file_out_fptr, (void *)output, options, 0);
  513. }
  514. /******/
  515. /*--------------------------*
  516. * End xml_element Functions *
  517. *--------------------------*/
  518. /*----------------------
  519. * Begin Expat Handlers *
  520. *---------------------*/
  521. typedef struct _xml_elem_data {
  522. xml_element* root;
  523. xml_element* current;
  524. XML_ELEM_INPUT_OPTIONS input_options;
  525. int needs_enc_conversion;
  526. } xml_elem_data;
  527. /* expat start of element handler */
  528. static void _xmlrpc_startElement(void *userData, const char *name, const char **attrs)
  529. {
  530. xml_element *c;
  531. xml_elem_data* mydata = (xml_elem_data*)userData;
  532. const char** p = attrs;
  533. if(mydata) {
  534. c = mydata->current;
  535. mydata->current = xml_elem_new();
  536. mydata->current->name = (char*)estrdup(name);
  537. mydata->current->parent = c;
  538. /* init attrs */
  539. while(p && *p) {
  540. xml_element_attr* attr = emalloc(sizeof(xml_element_attr));
  541. if(attr) {
  542. attr->key = estrdup(*p);
  543. attr->val = estrdup(*(p+1));
  544. Q_PushTail(&mydata->current->attrs, attr);
  545. p += 2;
  546. }
  547. }
  548. }
  549. }
  550. /* expat end of element handler */
  551. static void _xmlrpc_endElement(void *userData, const char *name)
  552. {
  553. xml_elem_data* mydata = (xml_elem_data*)userData;
  554. if(mydata && mydata->current && mydata->current->parent) {
  555. Q_PushTail(&mydata->current->parent->children, mydata->current);
  556. mydata->current = mydata->current->parent;
  557. }
  558. }
  559. /* expat char data handler */
  560. static void _xmlrpc_charHandler(void *userData,
  561. const char *s,
  562. int len)
  563. {
  564. xml_elem_data* mydata = (xml_elem_data*)userData;
  565. if(mydata && mydata->current) {
  566. /* Check if we need to decode utf-8 parser output to another encoding */
  567. if(mydata->needs_enc_conversion && mydata->input_options->encoding) {
  568. int new_len = 0;
  569. char* add_text = utf8_decode(s, len, &new_len, mydata->input_options->encoding);
  570. if(add_text) {
  571. len = new_len;
  572. simplestring_addn(&mydata->current->text, add_text, len);
  573. efree(add_text);
  574. return;
  575. }
  576. }
  577. simplestring_addn(&mydata->current->text, s, len);
  578. }
  579. }
  580. /******/
  581. /*-------------------*
  582. * End Expat Handlers *
  583. *-------------------*/
  584. /*-------------------*
  585. * xml_elem_parse_buf *
  586. *-------------------*/
  587. /****f* xml_element/xml_elem_parse_buf
  588. * NAME
  589. * xml_elem_parse_buf
  590. * SYNOPSIS
  591. * xml_element* xml_elem_parse_buf(const char* in_buf, int len, XML_ELEM_INPUT_OPTIONS options, XML_ELEM_ERROR error)
  592. * FUNCTION
  593. * parse a buffer containing XML into an xml_element in-memory tree
  594. * INPUTS
  595. * in_buf - buffer containing XML document
  596. * len - length of buffer
  597. * options - input options. optional
  598. * error - error result data. optional. check if result is null.
  599. * RESULT
  600. * void
  601. * NOTES
  602. * The returned data must be free'd by caller
  603. * SEE ALSO
  604. * xml_elem_serialize_to_string ()
  605. * xml_elem_free ()
  606. * SOURCE
  607. */
  608. xml_element* xml_elem_parse_buf(const char* in_buf, int len, XML_ELEM_INPUT_OPTIONS options, XML_ELEM_ERROR error)
  609. {
  610. xml_element* xReturn = NULL;
  611. char buf[100] = "";
  612. static STRUCT_XML_ELEM_INPUT_OPTIONS default_opts = {encoding_utf_8};
  613. if(!options) {
  614. options = &default_opts;
  615. }
  616. if(in_buf) {
  617. XML_Parser parser;
  618. xml_elem_data mydata = {0};
  619. parser = XML_ParserCreate(NULL);
  620. mydata.root = xml_elem_new();
  621. mydata.current = mydata.root;
  622. mydata.input_options = options;
  623. mydata.needs_enc_conversion = options->encoding && strcmp(options->encoding, encoding_utf_8);
  624. XML_SetElementHandler(parser, (XML_StartElementHandler)_xmlrpc_startElement, (XML_EndElementHandler)_xmlrpc_endElement);
  625. XML_SetCharacterDataHandler(parser, (XML_CharacterDataHandler)_xmlrpc_charHandler);
  626. /* pass the xml_elem_data struct along */
  627. XML_SetUserData(parser, (void*)&mydata);
  628. if(!len) {
  629. len = strlen(in_buf);
  630. }
  631. /* parse the XML */
  632. if(XML_Parse(parser, in_buf, len, 1) == 0) {
  633. enum XML_Error err_code = XML_GetErrorCode(parser);
  634. int line_num = XML_GetCurrentLineNumber(parser);
  635. int col_num = XML_GetCurrentColumnNumber(parser);
  636. long byte_idx = XML_GetCurrentByteIndex(parser);
  637. /* int byte_total = XML_GetCurrentByteCount(parser); */
  638. const char * error_str = XML_ErrorString(err_code);
  639. if(byte_idx > len) {
  640. byte_idx = len;
  641. }
  642. if(byte_idx >= 0) {
  643. snprintf(buf,
  644. sizeof(buf),
  645. "\n\tdata beginning %ld before byte index: %s\n",
  646. byte_idx > 10 ? 10 : byte_idx,
  647. in_buf + (byte_idx > 10 ? byte_idx - 10 : byte_idx));
  648. }
  649. /*
  650. fprintf(stderr, "expat reports error code %i\n"
  651. "\tdescription: %s\n"
  652. "\tline: %i\n"
  653. "\tcolumn: %i\n"
  654. "\tbyte index: %ld\n"
  655. "\ttotal bytes: %i\n%s ",
  656. err_code, error_str, line_num,
  657. col_num, byte_idx, byte_total, buf);
  658. */
  659. /* error condition */
  660. if(error) {
  661. error->parser_code = (long)err_code;
  662. error->line = line_num;
  663. error->column = col_num;
  664. error->byte_index = byte_idx;
  665. error->parser_error = error_str;
  666. }
  667. }
  668. else {
  669. xReturn = (xml_element*)Q_Head(&mydata.root->children);
  670. xReturn->parent = NULL;
  671. }
  672. XML_ParserFree(parser);
  673. xml_elem_free_non_recurse(mydata.root);
  674. }
  675. return xReturn;
  676. }
  677. /******/