1 //==========================================================================
7 //==========================================================================
8 //####ECOSGPLCOPYRIGHTBEGIN####
9 // -------------------------------------------
10 // This file is part of eCos, the Embedded Configurable Operating System.
11 // Copyright (C) 2005 eCosCentric Ltd
13 // eCos is free software; you can redistribute it and/or modify it under
14 // the terms of the GNU General Public License as published by the Free
15 // Software Foundation; either version 2 or (at your option) any later version.
17 // eCos is distributed in the hope that it will be useful, but WITHOUT ANY
18 // WARRANTY; without even the implied warranty of MERCHANTABILITY or
19 // FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
22 // You should have received a copy of the GNU General Public License along
23 // with eCos; if not, write to the Free Software Foundation, Inc.,
24 // 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
26 // As a special exception, if other files instantiate templates or use macros
27 // or inline functions from this file, or you compile this file and link it
28 // with other works to produce a work based on this file, this file does not
29 // by itself cause the resulting work to be covered by the GNU General Public
30 // License. However the source code for this file must still be made available
31 // in accordance with section (3) of the GNU General Public License.
33 // This exception does not invalidate any other reasons why a work based on
34 // this file might be covered by the GNU General Public License.
36 // Alternative licenses for eCos may be arranged by contacting Red Hat, Inc.
37 // at http://sources.redhat.com/ecos/ecos-license/
38 // -------------------------------------------
39 //####ECOSGPLCOPYRIGHTEND####
40 //==========================================================================
41 //#####DESCRIPTIONBEGIN####
43 // Author(s): Aaron Voisine
44 // Contributors: Matt Jerdonek
49 // This code is part of eCos (tm).
51 //####DESCRIPTIONEND####
53 //==========================================================================
57 * Copyright 2004, 2005 Aaron Voisine <aaron@voisine.org>
59 * Permission is hereby granted, free of charge, to any person obtaining
60 * a copy of this software and associated documentation files (the
61 * "Software"), to deal in the Software without restriction, including
62 * without limitation the rights to use, copy, modify, merge, publish,
63 * distribute, sublicense, and/or sell copies of the Software, and to
64 * permit persons to whom the Software is furnished to do so, subject to
65 * the following conditions:
67 * The above copyright notice and this permission notice shall be included
68 * in all copies or substantial portions of the Software.
70 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
71 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
72 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
73 * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
74 * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
75 * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
76 * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
79 #define EZXML_NOMMAP // no mmap on eCos
87 #include <sys/types.h>
90 #endif // EZXML_NOMMAP
94 #include <pkgconf/system.h>
96 #define EZXML_WS "\t\r\n " // whitespace
97 #define EZXML_ERRL 128 // maximum error string length
99 typedef struct ezxml_root *ezxml_root_t;
100 struct ezxml_root { // additional data for the root tag
101 struct ezxml xml; // is a super-struct built on top of ezxml struct
102 ezxml_t cur; // current xml tree insertion point
103 char *m; // original xml string
104 size_t len; // length of allocated memory for mmap, -1 for malloc
105 char *u; // UTF-8 conversion of string if original was UTF-16
106 char *s; // start of work area
107 char *e; // end of work area
108 char **ent; // general entities (ampersand sequences)
109 char ***attr; // default attributes
110 char ***pi; // processing instructions
111 short standalone; // non-zero if <?xml standalone="yes"?>
112 char err[EZXML_ERRL]; // error string
115 char *EZXML_NIL[] = { NULL }; // empty, null terminated array of strings
117 // returns the first child tag with the given name or NULL if not found
118 ezxml_t ezxml_child(ezxml_t xml, const char *name)
120 xml = (xml) ? xml->child : NULL;
121 while (xml && strcmp(name, xml->name)) xml = xml->sibling;
125 // returns the Nth tag with the same name in the same subsection or NULL if not
127 ezxml_t ezxml_idx(ezxml_t xml, int idx)
129 for (; xml && idx; idx--) xml = xml->next;
133 // returns the value of the requested tag attribute or NULL if not found
134 const char *ezxml_attr(ezxml_t xml, const char *attr)
137 ezxml_root_t root = (ezxml_root_t)xml;
139 if (! xml || ! xml->attr) return NULL;
140 while (xml->attr[i] && strcmp(attr, xml->attr[i])) i += 2;
141 if (xml->attr[i]) return xml->attr[i + 1]; // found attribute
143 while (root->xml.parent) root = (ezxml_root_t)root->xml.parent; // root tag
144 for (i = 0; root->attr[i] && strcmp(xml->name, root->attr[i][0]); i++);
145 if (! root->attr[i]) return NULL; // no matching default attributes
146 while (root->attr[i][j] && strcmp(attr, root->attr[i][j])) j += 3;
147 return (root->attr[i][j]) ? root->attr[i][j + 1] : NULL; // found default
150 // same as ezxml_get but takes an already initialized va_list
151 ezxml_t ezxml_vget(ezxml_t xml, va_list ap)
153 char *name = va_arg(ap, char *);
157 idx = va_arg(ap, int);
158 xml = ezxml_child(xml, name);
160 return (idx < 0) ? xml : ezxml_vget(ezxml_idx(xml, idx), ap);
163 // Traverses the xml tree to retrieve a specific subtag. Takes a variable
164 // length list of tag names and indexes. The argument list must be terminated
165 // by either an index of -1 or an empty string tag name. Example:
166 // title = ezxml_get(library, "shelf", 0, "book", 2, "title", -1);
167 // This retrieves the title of the 3rd book on the 1st shelf of library.
168 // Returns NULL if not found.
169 ezxml_t ezxml_get(ezxml_t xml, ...)
175 r = ezxml_vget(xml, ap);
180 // returns a null terminated array of processing instructions for the given
182 const char **ezxml_pi(ezxml_t xml, const char *target)
184 ezxml_root_t root = (ezxml_root_t)xml;
187 if (! root) return (const char **)EZXML_NIL;
188 while (root->xml.parent) root = (ezxml_root_t)root->xml.parent; // root tag
189 while (root->pi[i] && strcmp(target, root->pi[i][0])) i++; // find target
190 return (const char **)((root->pi[i]) ? root->pi[i] + 1 : EZXML_NIL);
193 // set an error string and return root
194 ezxml_t ezxml_err(ezxml_root_t root, char *s, const char *err, ...)
198 char *t, fmt[EZXML_ERRL];
200 for (t = root->s; t < s; t++) if (*t == '\n') line++;
201 snprintf(fmt, EZXML_ERRL, "[error near line %d]: %s", line, err);
204 vsnprintf(root->err, EZXML_ERRL, fmt, ap);
210 // Recursively decodes entity and character references and normalizes new lines
211 // ent is a null terminated array of alternating entity names and values. set t
212 // to '&' for general entity decoding, '%' for parameter entity decoding, 'c'
213 // for cdata sections, ' ' for attribute normalization, or '*' for non-cdata
214 // attribute normalization. Returns s, or if the decoded string is longer than
215 // s, returns a malloced string that must be freed.
216 char *ezxml_decode(char *s, char **ent, char t)
218 char *e, *r = s, *m = s;
221 for (; *s; s++) { // normalize line endings
224 if (*s == '\n') memmove(s, (s + 1), strlen(s));
229 while (*s && *s != '&' && (*s != '%' || t != '%') && !isspace(*s)) s++;
232 else if (t != 'c' && ! strncmp(s, "&#", 2)) { // character reference
233 if (s[2] == 'x') c = strtol(s + 3, &e, 16); // base 16
234 else c = strtol(s + 2, &e, 10); // base 10
235 if (! c || *e != ';') { s++; continue; } // not a character ref
237 if (c < 0x80) *(s++) = c; // US-ASCII subset
238 else { // multi-byte UTF-8 sequence
239 for (b = 0, d = c; d; d /= 2) b++; // number of bits in c
240 b = (b - 2) / 5; // number of bytes in payload
241 *(s++) = (0xFF << (7 - b)) | (c >> (6 * b)); // head
242 while (b) *(s++) = 0x80 | ((c >> (6 * --b)) & 0x3F); // payload
245 memmove(s, strchr(s, ';') + 1, strlen(strchr(s, ';')));
247 else if ((*s == '&' && (t == '&' || t == ' ' || t == '*')) ||
248 (*s == '%' && t == '%')) { // entity reference
249 for (b = 0; ent[b] && strncmp(s + 1, ent[b], strlen(ent[b]));
250 b += 2); // find entity in entity list
252 if (ent[b++]) { // found a match
253 if ((c = strlen(ent[b])) - 1 > (e = strchr(s, ';')) - s) {
254 l = (d = (s - r)) + c + strlen(e); // new length
255 r = (r == m) ? strcpy(malloc(l), r) : realloc(r, l);
256 e = strchr((s = r + d), ';'); // fix up pointers
259 memmove(s + c, e + 1, strlen(e)); // shift rest of string
260 strncpy(s, ent[b], c); // copy in replacement text
262 else s++; // not a known entity
264 else if ((t == ' ' || t == '*') && isspace(*s)) *(s++) = ' ';
265 else s++; // no decoding needed
268 if (t == '*') { // normalize spaces for non-cdata attributes
269 for (s = r; *s; s++) {
270 if ((l = strspn(s, " "))) memmove(s, s + l, strlen(s + l) + 1);
271 while (*s && *s != ' ') s++;
273 if (--s >= r && *s == ' ') *s = '\0'; // trim any trailing space
278 // called when parser finds start of new tag
279 void ezxml_open_tag(ezxml_root_t root, char *name, char **attr)
281 ezxml_t xml = root->cur;
283 if (xml->name) xml = ezxml_add_child(xml, name, strlen(xml->txt));
284 else xml->name = name; // first open tag
287 root->cur = xml; // update tag insertion point
290 // called when parser finds character content between open and closing tag
291 void ezxml_char_content(ezxml_root_t root, char *s, size_t len, char t)
293 ezxml_t xml = root->cur;
297 if (! xml || ! xml->name || ! len) return; // sanity check
299 s[len] = '\0'; // null terminate text (calling functions anticipate this)
300 len = strlen(s = ezxml_decode(s, root->ent, t)) + 1;
302 if (! *(xml->txt)) xml->txt = s; // initial character content
303 else { // allocate our own memory and make a copy
304 xml->txt = (xml->flags & EZXML_TXTM) // allocate some space
305 ? realloc(xml->txt, (l = strlen(xml->txt)) + len)
306 : strcpy(malloc((l = strlen(xml->txt)) + len), xml->txt);
307 strcpy(xml->txt + l, s); // add new char content
308 if (s != m) free(s); // free s if it was malloced by ezxml_decode()
311 if (xml->txt != m) ezxml_set_flag(xml, EZXML_TXTM);
314 // called when parser finds closing tag
315 ezxml_t ezxml_close_tag(ezxml_root_t root, char *name, char *s)
317 if (! root->cur || ! root->cur->name || strcmp(name, root->cur->name))
318 return ezxml_err(root, s, "unexpected closing tag </%s>", name);
320 root->cur = root->cur->parent;
324 // checks for circular entity references, returns non-zero if no circular
325 // references are found, zero otherwise
326 int ezxml_ent_ok(char *name, char *s, char **ent)
331 while (*s && *s != '&') s++; // find next entity reference
333 if (! strncmp(s + 1, name, strlen(name))) return 0; // circular ref.
334 for (i = 0; ent[i] && strncmp(ent[i], s + 1, strlen(ent[i])); i += 2);
335 if (ent[i] && ! ezxml_ent_ok(name, ent[i + 1], ent)) return 0;
339 // called when the parser finds a processing instruction
340 void ezxml_proc_inst(ezxml_root_t root, char *s, size_t len)
345 s[len] = '\0'; // null terminate instruction
346 if (*(s += strcspn(s, EZXML_WS))) {
347 *s = '\0'; // null terminate target
348 s += strspn(s + 1, EZXML_WS) + 1; // skip whitespace after target
351 if (! strcmp(target, "xml")) { // <?xml ... ?>
352 if ((s = strstr(s, "standalone")) && ! strncmp(s + strspn(s + 10,
353 EZXML_WS "='\"") + 10, "yes", 3)) root->standalone = 1;
357 if (! root->pi[0]) *(root->pi = malloc(sizeof(char **))) = NULL; //first pi
359 while (root->pi[i] && strcmp(target, root->pi[i][0])) i++; // find target
360 if (! root->pi[i]) { // new target
361 root->pi = realloc(root->pi, sizeof(char **) * (i + 2));
362 root->pi[i] = malloc(sizeof(char *) * 3);
363 root->pi[i][0] = target;
364 root->pi[i][1] = (char *)(root->pi[i + 1] = NULL); // terminate pi list
365 root->pi[i][2] = strdup(""); // empty document position list
368 while (root->pi[i][j]) j++; // find end of instruction list for this target
369 root->pi[i] = realloc(root->pi[i], sizeof(char *) * (j + 3));
370 root->pi[i][j + 2] = realloc(root->pi[i][j + 1], j + 1);
371 strcpy(root->pi[i][j + 2] + j - 1, (root->xml.name) ? ">" : "<");
372 root->pi[i][j + 1] = NULL; // null terminate pi list for this target
373 root->pi[i][j] = s; // set instruction
376 // called when the parser finds an internal doctype subset
377 short ezxml_internal_dtd(ezxml_root_t root, char *s, size_t len)
379 char q, *c, *t, *n = NULL, *v, **ent, **pe;
382 pe = memcpy(malloc(sizeof(EZXML_NIL)), EZXML_NIL, sizeof(EZXML_NIL));
384 for (s[len] = '\0'; s; ) {
385 while (*s && *s != '<' && *s != '%') s++; // find next declaration
388 else if (! strncmp(s, "<!ENTITY", 8)) { // parse entity definitions
389 c = s += strspn(s + 8, EZXML_WS) + 8; // skip white space separator
390 n = s + strspn(s, EZXML_WS "%"); // find name
391 *(s = n + strcspn(n, EZXML_WS)) = ';'; // append ; to name
393 v = s + strspn(s + 1, EZXML_WS) + 1; // find value
394 if ((q = *(v++)) != '"' && q != '\'') { // skip externals
399 for (i = 0, ent = (*c == '%') ? pe : root->ent; ent[i]; i++);
400 ent = realloc(ent, (i + 3) * sizeof(char *)); // space for next ent
401 if (*c == '%') pe = ent;
402 else root->ent = ent;
404 *(++s) = '\0'; // null terminate name
405 if ((s = strchr(v, q))) *(s++) = '\0'; // null terminate value
406 ent[i + 1] = ezxml_decode(v, pe, '%'); // set value
407 ent[i + 2] = NULL; // null terminate entity list
408 if (! ezxml_ent_ok(n, ent[i + 1], ent)) { // circular reference
409 if (ent[i + 1] != v) free(ent[i + 1]);
410 ezxml_err(root, v, "circular entity declaration &%s", n);
413 else ent[i] = n; // set entity name
415 else if (! strncmp(s, "<!ATTLIST", 9)) { // parse default attributes
416 t = s + strspn(s + 9, EZXML_WS) + 9; // skip whitespace separator
417 if (! *t) { ezxml_err(root, t, "unclosed <!ATTLIST"); break; }
418 if (*(s = t + strcspn(t, EZXML_WS ">")) == '>') continue;
419 else *s = '\0'; // null terminate tag name
420 for (i = 0; root->attr[i] && strcmp(n, root->attr[i][0]); i++);
422 while (*(n = ++s + strspn(s, EZXML_WS)) && *n != '>') {
423 if (*(s = n + strcspn(n, EZXML_WS))) *s = '\0'; // attr name
424 else { ezxml_err(root, t, "malformed <!ATTLIST"); break; }
426 s += strspn(s + 1, EZXML_WS) + 1; // find next token
427 c = (strncmp(s, "CDATA", 5)) ? "*" : " "; // is it cdata?
428 if (! strncmp(s, "NOTATION", 8))
429 s += strspn(s + 8, EZXML_WS) + 8;
430 s = (*s == '(') ? strchr(s, ')') : s + strcspn(s, EZXML_WS);
431 if (! s) { ezxml_err(root, t, "malformed <!ATTLIST"); break; }
433 s += strspn(s, EZXML_WS ")"); // skip white space separator
434 if (! strncmp(s, "#FIXED", 6))
435 s += strspn(s + 6, EZXML_WS) + 6;
436 if (*s == '#') { // no default value
437 s += strcspn(s, EZXML_WS ">") - 1;
438 if (*c == ' ') continue; // cdata is default, nothing to do
441 else if ((*s == '"' || *s == '\'') && // default value
442 (s = strchr(v = s + 1, *s))) *s = '\0';
443 else { ezxml_err(root, t, "malformed <!ATTLIST"); break; }
445 if (! root->attr[i]) { // new tag name
446 root->attr = (! i) ? malloc(2 * sizeof(char **))
447 : realloc(root->attr,
448 (i + 2) * sizeof(char **));
449 root->attr[i] = malloc(2 * sizeof(char *));
450 root->attr[i][0] = t; // set tag name
451 root->attr[i][1] = (char *)(root->attr[i + 1] = NULL);
454 for (j = 1; root->attr[i][j]; j += 3); // find end of list
455 root->attr[i] = realloc(root->attr[i],
456 (j + 4) * sizeof(char *));
458 root->attr[i][j + 3] = NULL; // null terminate list
459 root->attr[i][j + 2] = c; // is it cdata?
460 root->attr[i][j + 1] = (v) ? ezxml_decode(v, root->ent, *c)
462 root->attr[i][j] = n; // attribute name
465 else if (! strncmp(s, "<!--", 4)) s = strstr(s + 4, "-->"); // comments
466 else if (! strncmp(s, "<?", 2)) { // processing instructions
467 if ((s = strstr(c = s + 2, "?>")))
468 ezxml_proc_inst(root, c, s++ - c);
470 else if (*s == '<') s = strchr(s, '>'); // skip other declarations
471 else if (*(s++) == '%' && ! root->standalone) break;
478 // Converts a UTF-16 string to UTF-8. Returns a new string that must be freed
479 // or NULL if no conversion was needed.
480 char *ezxml_str2utf8(char **s, size_t *len)
483 size_t l = 0, sl, max = *len;
485 int b, be = (**s == '\xFE') ? 1 : (**s == '\xFF') ? 0 : -1;
487 if (be == -1) return NULL; // not UTF-16
490 for (sl = 2; sl < *len - 1; sl += 2) {
491 c = (be) ? (((*s)[sl] & 0xFF) << 8) | ((*s)[sl + 1] & 0xFF) //UTF-16BE
492 : (((*s)[sl + 1] & 0xFF) << 8) | ((*s)[sl] & 0xFF); //UTF-16LE
493 if (c >= 0xD800 && c <= 0xDFFF && (sl += 2) < *len - 1) { // high-half
494 d = (be) ? (((*s)[sl] & 0xFF) << 8) | ((*s)[sl + 1] & 0xFF)
495 : (((*s)[sl + 1] & 0xFF) << 8) | ((*s)[sl] & 0xFF);
496 c = (((c & 0x3FF) << 10) | (d & 0x3FF)) + 0x10000;
499 while (l + 6 > max) u = realloc(u, max += EZXML_BUFSIZE);
500 if (c < 0x80) u[l++] = c; // US-ASCII subset
501 else { // multi-byte UTF-8 sequence
502 for (b = 0, d = c; d; d /= 2) b++; // bits in c
503 b = (b - 2) / 5; // bytes in payload
504 u[l++] = (0xFF << (7 - b)) | (c >> (6 * b)); // head
505 while (b) u[l++] = 0x80 | ((c >> (6 * --b)) & 0x3F); // payload
508 return *s = realloc(u, *len = l);
511 // frees a tag attribute list
512 void ezxml_free_attr(char **attr) {
516 if (! attr || attr == EZXML_NIL) return; // nothing to free
517 while (attr[i]) i += 2; // find end of attribute list
518 m = attr[i + 1]; // list of which names and values are malloced
519 for (i = 0; m[i]; i++) {
520 if (m[i] & EZXML_NAMEM) free(attr[i * 2]);
521 if (m[i] & EZXML_TXTM) free(attr[(i * 2) + 1]);
527 // parse the given xml string and return an ezxml structure
528 ezxml_t ezxml_parse_str(char *s, size_t len)
530 ezxml_root_t root = (ezxml_root_t)ezxml_new(NULL);
531 char q, e, *d, **attr, **a = NULL; // initialize a to avoid compile warning
535 if (! len) return ezxml_err(root, s, "root tag missing");
536 root->u = ezxml_str2utf8(&s, &len); // convert utf-16 to utf-8
537 root->e = (root->s = s) + len; // record start and end of work area
539 e = s[len - 1]; // save end char
540 s[len - 1] = '\0'; // turn end char into null terminator
542 while (*s && *s != '<') s++; // find first tag
543 if (! *s) return ezxml_err(root, s, "root tag missing");
546 attr = (char **)EZXML_NIL;
549 if (isalpha(*s) || *s == '_' || *s == ':') { // new tag
551 return ezxml_err(root, d, "markup outside of root element");
553 s += strcspn(s, EZXML_WS "/>");
554 while (isspace(*s)) *(s++) = '\0'; // null terminate tag name
556 if (*s && *s != '/' && *s != '>') // find tag in default attr list
557 for (i = 0; (a = root->attr[i]) && strcmp(a[0], d); i++);
559 for (l = 0; *s && *s != '/' && *s != '>'; l += 2) { // new attrib
560 attr = (l) ? realloc(attr, (l + 4) * sizeof(char *))
561 : malloc(4 * sizeof(char *)); // allocate space
562 attr[l + 3] = (l) ? realloc(attr[l + 1], (l / 2) + 2)
563 : malloc(2); // mem for list of maloced vals
564 strcpy(attr[l + 3] + (l / 2), " "); // value is not malloced
565 attr[l + 2] = NULL; // null terminate list
566 attr[l + 1] = ""; // temporary attribute value
567 attr[l] = s; // set attribute name
569 s += strcspn(s, EZXML_WS "=/>");
570 if (*s == '=' || isspace(*s)) {
571 *(s++) = '\0'; // null terminate tag attribute name
572 q = *(s += strspn(s, EZXML_WS "="));
573 if (q == '"' || q == '\'') { // attribute value
575 while (*s && *s != q) s++;
576 if (*s) *(s++) = '\0'; // null terminate attribute val
578 ezxml_free_attr(attr);
579 return ezxml_err(root, d, "missing %c", q);
582 for (j = 1; a && a[j] && strcmp(a[j], attr[l]); j +=3);
583 attr[l + 1] = ezxml_decode(attr[l + 1], root->ent, (a
584 && a[j]) ? *a[j + 2] : ' ');
585 if (attr[l + 1] < d || attr[l + 1] > s)
586 attr[l + 3][l / 2] = EZXML_TXTM; // value malloced
589 while (isspace(*s)) s++;
592 if (*s == '/') { // self closing tag
594 if ((*s && *s != '>') || (! *s && e != '>')) {
595 if (l) ezxml_free_attr(attr);
596 return ezxml_err(root, d, "missing >");
598 ezxml_open_tag(root, d, attr);
599 ezxml_close_tag(root, d, s);
601 else if ((q = *s) == '>' || (! *s && e == '>')) { // open tag
602 *s = '\0'; // temporarily null terminate tag name
603 ezxml_open_tag(root, d, attr);
607 if (l) ezxml_free_attr(attr);
608 return ezxml_err(root, d, "missing >");
611 else if (*s == '/') { // close tag
612 s += strcspn(d = s + 1, EZXML_WS ">") + 1;
613 if (! (q = *s) && e != '>') return ezxml_err(root, d, "missing >");
614 *s = '\0'; // temporarily null terminate tag name
615 if (ezxml_close_tag(root, d, s)) return &root->xml;
616 if (isspace(*s = q)) s += strspn(s, EZXML_WS);
618 else if (! strncmp(s, "!--", 3)) { // comment
619 if (! (s = strstr(s + 3, "--")) || (*(s += 2) != '>' && *s) ||
620 (! *s && e != '>')) return ezxml_err(root, d, "unclosed <!--");
622 else if (! strncmp(s, "![CDATA[", 8)) { // cdata
623 if ((s = strstr(s, "]]>")))
624 ezxml_char_content(root, d + 8, (s += 2) - d - 10, 'c');
625 else return ezxml_err(root, d, "unclosed <![CDATA[");
627 else if (! strncmp(s, "!DOCTYPE", 8)) { // dtd
628 for (l = 0; *s && ((! l && *s != '>') || (l && (*s != ']' ||
629 *(s + strspn(s + 1, EZXML_WS) + 1) != '>')));
630 l = (*s == '[') ? 1 : l) s += strcspn(s + 1, "[]>") + 1;
631 if (! *s && e != '>')
632 return ezxml_err(root, d, "unclosed <!DOCTYPE");
633 d = (l) ? strchr(d, '[') + 1 : d;
634 if (l && ! ezxml_internal_dtd(root, d, s++ - d)) return &root->xml;
636 else if (*s == '?') { // <?...?> processing instructions
637 do { s = strchr(s, '?'); } while (s && *(++s) && *s != '>');
638 if (! s || (! *s && e != '>'))
639 return ezxml_err(root, d, "unclosed <?");
640 else ezxml_proc_inst(root, d + 1, s - d - 2);
642 else return ezxml_err(root, d, "unexpected <");
644 if (! s || ! *s) break;
647 if (*s && *s != '<') { // tag character content
648 while (*s && *s != '<') s++;
649 if (*s) ezxml_char_content(root, d, s - d, '&');
652 else if (! *s) break;
655 if (! root->cur) return &root->xml;
656 else if (! root->cur->name) return ezxml_err(root, d, "root tag missing");
657 else return ezxml_err(root, d, "unclosed tag <%s>", root->cur->name);
660 #ifdef CYGPKG_IO_FILEIO
661 // Wrapper for ezxml_parse_str() that accepts a file stream. Reads the entire
662 // stream into memory and then parses it. For xml files, use ezxml_parse_file()
663 // or ezxml_parse_fd()
664 ezxml_t ezxml_parse_fp(FILE *fp)
670 if (! (s = malloc(EZXML_BUFSIZE))) return NULL;
672 len += (l = fread((s + len), 1, EZXML_BUFSIZE, fp));
673 if (l == EZXML_BUFSIZE) s = realloc(s, len + EZXML_BUFSIZE);
674 } while (s && l == EZXML_BUFSIZE);
676 if (! s) return NULL;
677 root = (ezxml_root_t)ezxml_parse_str(s, len);
678 root->len = -1; // so we know to free s in ezxml_free()
682 // A wrapper for ezxml_parse_str() that accepts a file descriptor. First
683 // attempts to mem map the file. Failing that, reads the file into memory.
684 // Returns NULL on failure.
685 ezxml_t ezxml_parse_fd(int fd)
692 if (fd < 0) return NULL;
696 l = (st.st_size + sysconf(_SC_PAGESIZE) - 1) & ~(sysconf(_SC_PAGESIZE) -1);
697 if ((m = mmap(NULL, l, PROT_READ | PROT_WRITE, MAP_PRIVATE, fd, 0)) !=
699 madvise(m, l, MADV_SEQUENTIAL); // optimize for sequential access
700 root = (ezxml_root_t)ezxml_parse_str(m, st.st_size);
701 madvise(m, root->len = l, MADV_NORMAL); // put it back to normal
703 else { // mmap failed, read file into memory
704 #endif // EZXML_NOMMAP
705 l = read(fd, m = malloc(st.st_size), st.st_size);
706 root = (ezxml_root_t)ezxml_parse_str(m, l);
707 root->len = -1; // so we know to free s in ezxml_free()
710 #endif // EZXML_NOMMAP
714 // a wrapper for ezxml_parse_fd that accepts a file name
715 ezxml_t ezxml_parse_file(const char *file)
717 int fd = open(file, O_RDONLY, 0);
718 ezxml_t xml = ezxml_parse_fd(fd);
720 if (fd >= 0) close(fd);
723 #endif // CYGPKG_IO_FILEIO
725 // Encodes ampersand sequences appending the results to *dst, reallocating *dst
726 // if length excedes max. a is non-zero for attribute encoding. Returns *dst
727 char *ezxml_ampencode(const char *s, size_t len, char **dst, size_t *dlen,
728 size_t *max, short a)
732 for (e = s + len; s != e; s++) {
733 while (*dlen + 10 > *max) *dst = realloc(*dst, *max += EZXML_BUFSIZE);
736 case '\0': return *dst;
737 case '&': *dlen += sprintf(*dst + *dlen, "&"); break;
738 case '<': *dlen += sprintf(*dst + *dlen, "<"); break;
739 case '>': *dlen += sprintf(*dst + *dlen, ">"); break;
740 case '"': *dlen += sprintf(*dst + *dlen, (a) ? """ : "\""); break;
741 case '\n': *dlen += sprintf(*dst + *dlen, (a) ? "
" : "\n"); break;
742 case '\t': *dlen += sprintf(*dst + *dlen, (a) ? "	" : "\t"); break;
743 case '\r': *dlen += sprintf(*dst + *dlen, "
"); break;
744 default: (*dst)[(*dlen)++] = *s;
750 // Recursively converts each tag to xml appending it to *s. Reallocates *s if
751 // its length excedes max. start is the location of the previous tag in the
752 // parent tag's character content. Returns *s.
753 char *ezxml_toxml_r(ezxml_t xml, char **s, size_t *len, size_t *max,
754 size_t start, char ***attr)
757 char *txt = (xml->parent) ? xml->parent->txt : "";
760 // parent character content up to this tag
761 *s = ezxml_ampencode(txt + start, xml->off - start, s, len, max, 0);
763 while (*len + strlen(xml->name) + 4 > *max) // reallocate s
764 *s = realloc(*s, *max += EZXML_BUFSIZE);
766 *len += sprintf(*s + *len, "<%s", xml->name); // open tag
767 for (i = 0; xml->attr[i]; i += 2) { // tag attributes
768 if (ezxml_attr(xml, xml->attr[i]) != xml->attr[i + 1]) continue;
769 while (*len + strlen(xml->attr[i]) + 7 > *max) // reallocate s
770 *s = realloc(*s, *max += EZXML_BUFSIZE);
772 *len += sprintf(*s + *len, " %s=\"", xml->attr[i]);
773 ezxml_ampencode(xml->attr[i + 1], -1, s, len, max, 1);
774 *len += sprintf(*s + *len, "\"");
777 for (i = 0; attr[i] && strcmp(attr[i][0], xml->name); i++);
778 for (j = 1; attr[i] && attr[i][j]; j += 3) { // default attributes
779 if (! attr[i][j + 1] || ezxml_attr(xml, attr[i][j]) != attr[i][j + 1])
780 continue; // skip duplicates and non-values
781 while (*len + strlen(attr[i][j]) + 7 > *max) // reallocate s
782 *s = realloc(*s, *max += EZXML_BUFSIZE);
784 *len += sprintf(*s + *len, " %s=\"", attr[i][j]);
785 ezxml_ampencode(attr[i][j + 1], -1, s, len, max, 1);
786 *len += sprintf(*s + *len, "\"");
788 *len += sprintf(*s + *len, ">");
790 *s = (xml->child) ? ezxml_toxml_r(xml->child, s, len, max, 0, attr) //child
791 : ezxml_ampencode(xml->txt, -1, s, len, max, 0); //data
793 while (*len + strlen(xml->name) + 4 > *max) // reallocate s
794 *s = realloc(*s, *max += EZXML_BUFSIZE);
796 *len += sprintf(*s + *len, "</%s>", xml->name); // close tag
798 while (txt[off] && off < xml->off) off++; // make sure off is within bounds
799 return (xml->ordered) ? ezxml_toxml_r(xml->ordered, s, len, max, off, attr)
800 : ezxml_ampencode(txt + off, -1, s, len, max, 0);
803 // converts an ezxml structure back to xml, returning it as a string that must
805 char *ezxml_toxml(ezxml_t xml)
807 ezxml_t p = (xml) ? xml->parent : NULL, o = (xml) ? xml->ordered : NULL;
808 ezxml_root_t root = (ezxml_root_t)xml;
809 size_t len = 0, max = EZXML_BUFSIZE;
810 char *s = strcpy(malloc(max), ""), *t, *n;
813 if (! xml || ! xml->name) return realloc(s, len + 1);
814 while (root->xml.parent) root = (ezxml_root_t)root->xml.parent; // root tag
816 for (i = 0; ! p && root->pi[i]; i++) { // pre-root processing instructions
817 for (k = 2; root->pi[i][k - 1]; k++);
818 for (j = 1; (n = root->pi[i][j]); j++) {
819 if (root->pi[i][k][j - 1] == '>') continue; // not pre-root
820 while (len + strlen(t = root->pi[i][0]) + strlen(n) + 7 > max)
821 s = realloc(s, max += EZXML_BUFSIZE);
822 len += sprintf(s + len, "<?%s%s%s?>\n", t, *n ? " " : "", n);
826 xml->parent = xml->ordered = NULL;
827 s = ezxml_toxml_r(xml, &s, &len, &max, 0, root->attr);
831 for (i = 0; ! p && root->pi[i]; i++) { // post-root processing instructions
832 for (k = 2; root->pi[i][k - 1]; k++);
833 for (j = 1; (n = root->pi[i][j]); j++) {
834 if (root->pi[i][k][j - 1] == '<') continue; // not post-root
835 while (len + strlen(t = root->pi[i][0]) + strlen(n) + 7 > max)
836 s = realloc(s, max += EZXML_BUFSIZE);
837 len += sprintf(s + len, "\n<?%s%s%s?>", t, *n ? " " : "", n);
840 return realloc(s, len + 1);
843 // free the memory allocated for the ezxml structure
844 void ezxml_free(ezxml_t xml)
846 ezxml_root_t root = (ezxml_root_t)xml;
851 ezxml_free(xml->child);
852 ezxml_free(xml->ordered);
854 if (! xml->parent) { // free root tag allocations
855 for (i = 10; root->ent[i]; i += 2) // 0 - 9 are default entites (<>&"')
856 if ((s = root->ent[i + 1]) < root->s || s > root->e) free(s);
857 free(root->ent); // free list of general entities
859 for (i = 0; (a = root->attr[i]); i++) {
860 for (j = 1; a[j++]; j += 2) // free malloced attribute values
861 if (a[j] && (a[j] < root->s || a[j] > root->e)) free(a[j]);
864 if (root->attr[0]) free(root->attr); // free default attribute list
866 for (i = 0; root->pi[i]; i++) {
867 for (j = 1; root->pi[i][j]; j++);
868 free(root->pi[i][j + 1]);
871 if (root->pi[0]) free(root->pi); // free processing instructions
873 if (root->len == -1) free(root->m); // malloced xml data
875 else if (root->len) munmap(root->m, root->len); // mem mapped xml data
876 #endif // EZXML_NOMMAP
877 if (root->u) free(root->u); // utf8 conversion
880 ezxml_free_attr(xml->attr); // tag attributes
881 if ((xml->flags & EZXML_TXTM)) free(xml->txt); // character content
882 if ((xml->flags & EZXML_NAMEM)) free(xml->name); // tag name
886 // return parser error message or empty string if none
887 const char *ezxml_error(ezxml_t xml)
889 while (xml && xml->parent) xml = xml->parent; // find root tag
890 return (xml) ? ((ezxml_root_t)xml)->err : "";
893 // returns a new empty ezxml structure with the given root tag name
894 ezxml_t ezxml_new(const char *name)
896 static char *ent[] = { "lt;", "<", "gt;", ">", "quot;", """,
897 "apos;", "'", "amp;", "&", NULL };
898 ezxml_root_t root = (ezxml_root_t)memset(malloc(sizeof(struct ezxml_root)),
899 '\0', sizeof(struct ezxml_root));
900 root->xml.name = (char *)name;
901 root->cur = &root->xml;
902 strcpy(root->err, root->xml.txt = "");
903 root->ent = memcpy(malloc(sizeof(ent)), ent, sizeof(ent));
904 root->attr = root->pi = (char ***)(root->xml.attr = EZXML_NIL);
908 // Adds a child tag. off is the offset of the child tag relative to the start
909 // of the parent tag's character content. returns the child tag
910 ezxml_t ezxml_add_child(ezxml_t xml, const char *name, size_t off)
912 ezxml_t cur, head, child;
914 if (! xml) return NULL;
915 child = (ezxml_t)memset(malloc(sizeof(struct ezxml)), '\0',
916 sizeof(struct ezxml));
917 child->name = (char *)name;
918 child->attr = EZXML_NIL;
923 if ((head = xml->child)) { // already have sub tags
924 if (head->off <= off) { // not first subtag
925 for (cur = head; cur->ordered && cur->ordered->off <= off;
927 child->ordered = cur->ordered;
928 cur->ordered = child;
930 else { // first subtag
931 child->ordered = head;
935 for (cur = head; cur->sibling && strcmp(cur->name, name);
936 cur = cur->sibling); // find tag type
937 if (! strcmp(cur->name, name) && cur->off <= off) { //not first of type
938 while (cur->next && cur->next->off <= off) cur = cur->next;
939 child->next = cur->next;
942 else { // first tag of this type
943 if (cur->off > off) child->next = cur; // not only tag of this type
944 for (cur = head; cur->sibling && cur->sibling->off <= off;
946 child->sibling = cur->sibling;
947 cur->sibling = child;
950 else xml->child = child; // only sub tag
955 // sets the character content for the given tag and returns the tag
956 ezxml_t ezxml_set_txt(ezxml_t xml, const char *txt)
958 if (! xml) return NULL;
959 if (xml->flags & EZXML_TXTM) free(xml->txt); // existing txt was malloced
960 xml->flags &= ~EZXML_TXTM;
961 xml->txt = (char *)txt;
965 // Sets the given tag attribute or adds a new attribute if not found. A value
966 // of NULL will remove the specified attribute.
967 void ezxml_set_attr(ezxml_t xml, const char *name, const char *value)
972 while (xml->attr[l] && strcmp(xml->attr[l], name)) l += 2;
973 if (! xml->attr[l]) { // not found, add as new attribute
974 if (! value) return; // nothing to do
975 if (xml->attr == EZXML_NIL) { // first attribute
976 xml->attr = malloc(4 * sizeof(char *));
977 xml->attr[1] = strdup(""); // empty list of malloced names/vals
979 else xml->attr = realloc(xml->attr, (l + 4) * sizeof(char *));
981 xml->attr[l] = (char *)name; // set attribute name
982 xml->attr[l + 2] = NULL; // null terminate attribute list
983 xml->attr[l + 3] = realloc(xml->attr[l + 1],
984 (c = strlen(xml->attr[l + 1])) + 2);
985 strcpy(xml->attr[l + 3] + c, " "); // set name/value as not malloced
986 if (xml->flags & EZXML_DUP) xml->attr[l + 3][c] = EZXML_NAMEM;
988 else if (xml->flags & EZXML_DUP) free((char *)name); // name was strduped
990 for (c = l; xml->attr[c]; c += 2); // find end of attribute list
991 if (xml->attr[c + 1][l / 2] & EZXML_TXTM) free(xml->attr[l + 1]); //old val
992 if (xml->flags & EZXML_DUP) xml->attr[c + 1][l / 2] |= EZXML_TXTM;
993 else xml->attr[c + 1][l / 2] &= ~EZXML_TXTM;
995 if (value) xml->attr[l + 1] = (char *)value; // set attribute value
996 else { // remove attribute
997 if (xml->attr[c + 1][l / 2] & EZXML_NAMEM) free(xml->attr[l]);
998 memmove(xml->attr + l, xml->attr + l + 2, (c - l + 2) * sizeof(char*));
999 xml->attr = realloc(xml->attr, (c + 2) * sizeof(char *));
1000 memmove(xml->attr[c + 1] + (l / 2), xml->attr[c + 1] + (l / 2) + 1,
1001 (c / 2) - (l / 2)); // fix list of which name/vals are malloced
1003 xml->flags &= ~EZXML_DUP; // clear strdup() flag
1006 // sets a flag for the given tag and returns the tag
1007 ezxml_t ezxml_set_flag(ezxml_t xml, short flag)
1009 if (xml) xml->flags |= flag;
1013 // removes a tag along with all its subtags
1014 void ezxml_remove(ezxml_t xml)
1018 if (! xml) return; // nothing to do
1019 if (xml->next) xml->next->sibling = xml->sibling; // patch sibling list
1021 if (xml->parent) { // not root tag
1022 cur = xml->parent->child; // find head of subtag list
1023 if (cur == xml) xml->parent->child = xml->ordered; // first subtag
1024 else { // not first subtag
1025 while (cur->ordered != xml) cur = cur->ordered;
1026 cur->ordered = cur->ordered->ordered; // patch ordered list
1028 cur = xml->parent->child; // go back to head of subtag list
1029 if (strcmp(cur->name, xml->name)) { // not in first sibling list
1030 while (strcmp(cur->sibling->name, xml->name))
1032 if (cur->sibling == xml) { // first of a sibling list
1033 cur->sibling = (xml->next) ? xml->next
1034 : cur->sibling->sibling;
1036 else cur = cur->sibling; // not first of a sibling list
1039 while (cur->next && cur->next != xml) cur = cur->next;
1040 if (cur->next) cur->next = cur->next->next; // patch next list
1043 xml->ordered = NULL; // prevent ezxml_free() from clobbering ordered list
1047 #ifdef EZXML_TEST // test harness
1048 int main(int argc, char **argv)
1054 if (argc != 2) return fprintf(stderr, "usage: %s xmlfile\n", argv[0]);
1056 xml = ezxml_parse_file(argv[1]);
1057 printf("%s\n", (s = ezxml_toxml(xml)));
1059 i = fprintf(stderr, "%s", ezxml_error(xml));
1063 #endif // EZXML_TEST