3 * Copyright 2004-2006 Aaron Voisine <aaron@voisine.org>
5 * Permission is hereby granted, free of charge, to any person obtaining
6 * a copy of this software and associated documentation files (the
7 * "Software"), to deal in the Software without restriction, including
8 * without limitation the rights to use, copy, modify, merge, publish,
9 * distribute, sublicense, and/or sell copies of the Software, and to
10 * permit persons to whom the Software is furnished to do so, subject to
11 * the following conditions:
13 * The above copyright notice and this permission notice shall be included
14 * in all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
19 * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
20 * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
21 * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
22 * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
35 #include <sys/types.h>
42 #endif // EZXML_NOMMAP
46 #include "sci_malloc.h"
48 #include "os_string.h"
51 #define snprintf _snprintf
57 #define EZXML_WS "\t\n " // whitespace
58 #define EZXML_ERRL 128 // maximum error string length
60 typedef struct ezxml_root *ezxml_root_t;
61 struct ezxml_root // additional data for the root tag
63 struct ezxml xml; // is a super-struct built on top of ezxml struct
64 ezxml_t cur; // current xml tree insertion point
65 char *m; // original xml string
66 size_t len; // length of allocated memory for mmap, -1 for malloc
67 char *u; // UTF-8 conversion of string if original was UTF-16
68 char *s; // start of work area
69 char *e; // end of work area
70 char **ent; // general entities (ampersand sequences)
71 char ***attr; // default attributes
72 char ***pi; // processing instructions
73 short standalone; // non-zero if <?xml standalone="yes"?>
74 char err[EZXML_ERRL]; // error string
77 char *EZXML_NIL[] = { NULL }; // empty, null terminated array of strings
79 // returns the first child tag with the given name or NULL if not found
80 ezxml_t ezxml_child(ezxml_t xml, const char *name)
82 xml = (xml) ? xml->child : NULL;
83 while (xml && strcmp(name, xml->name))
90 // returns the Nth tag with the same name in the same subsection or NULL if not
92 ezxml_t ezxml_idx(ezxml_t xml, int idx)
94 for (; xml && idx; idx--)
101 // returns the value of the requested tag attribute or NULL if not found
102 const char *ezxml_attr(ezxml_t xml, const char *attr)
105 ezxml_root_t root = (ezxml_root_t)xml;
107 if (! xml || ! xml->attr)
111 while (xml->attr[i] && strcmp(attr, xml->attr[i]))
117 return xml->attr[i + 1]; // found attribute
120 while (root->xml.parent)
122 root = (ezxml_root_t)root->xml.parent; // root tag
124 for (i = 0; root->attr[i] && strcmp(xml->name, root->attr[i][0]); i++)
130 return NULL; // no matching default attributes
132 while (root->attr[i][j] && strcmp(attr, root->attr[i][j]))
136 return (root->attr[i][j]) ? root->attr[i][j + 1] : NULL; // found default
139 // same as ezxml_get but takes an already initialized va_list
140 ezxml_t ezxml_vget(ezxml_t xml, va_list ap)
142 char *name = va_arg(ap, char *);
147 idx = va_arg(ap, int);
148 xml = ezxml_child(xml, name);
150 return (idx < 0) ? xml : ezxml_vget(ezxml_idx(xml, idx), ap);
153 // Traverses the xml tree to retrieve a specific subtag. Takes a variable
154 // length list of tag names and indexes. The argument list must be terminated
155 // by either an index of -1 or an empty string tag name. Example:
156 // title = ezxml_get(library, "shelf", 0, "book", 2, "title", -1);
157 // This retrieves the title of the 3rd book on the 1st shelf of library.
158 // Returns NULL if not found.
159 ezxml_t ezxml_get(ezxml_t xml, ...)
165 r = ezxml_vget(xml, ap);
170 // returns a null terminated array of processing instructions for the given
172 const char **ezxml_pi(ezxml_t xml, const char *target)
174 ezxml_root_t root = (ezxml_root_t)xml;
179 return (const char **)EZXML_NIL;
181 while (root->xml.parent)
183 root = (ezxml_root_t)root->xml.parent; // root tag
185 while (root->pi[i] && strcmp(target, root->pi[i][0]))
189 return (const char **)((root->pi[i]) ? root->pi[i] + 1 : EZXML_NIL);
192 // set an error string and return root
193 ezxml_t ezxml_err(ezxml_root_t root, char *s, const char *err, ...)
197 char *t, fmt[EZXML_ERRL];
199 for (t = root->s; t < s; t++) if (*t == '\n')
203 snprintf(fmt, EZXML_ERRL, "[error near line %d]: %s", line, err);
206 vsnprintf(root->err, EZXML_ERRL, fmt, ap);
212 // Recursively decodes entity and character references and normalizes new lines
213 // ent is a null terminated array of alternating entity names and values. set t
214 // to '&' for general entity decoding, '%' for parameter entity decoding, 'c'
215 // for cdata sections, ' ' for attribute normalization, or '*' for non-cdata
216 // attribute normalization. Returns s, or if the decoded string is longer than
217 // s, returns a malloced string that must be freed.
218 char *ezxml_decode(char *s, char **ent, char t)
220 char *e, *r = s, *m = s;
223 for (; *s; s++) // normalize line endings
230 memmove(s, (s + 1), strlen(s));
237 while (*s && *s != '&' && (*s != '%' || t != '%') && !isspace(*s))
246 else if (t != 'c' && ! strncmp(s, "&#", 2)) // character reference
250 c = strtol(s + 3, &e, 16); // base 16
254 c = strtol(s + 2, &e, 10); // base 10
256 if (! c || *e != ';')
258 s++; // not a character ref
264 *(s++) = (char)c; // US-ASCII subset
266 else // multi-byte UTF-8 sequence
268 for (b = 0, d = c; d; d /= 2)
270 b++; // number of bits in c
272 b = (b - 2) / 5; // number of bytes in payload
273 *(s++) = (char)(0xFF << (7 - b)) | (char)(c >> (6 * b)); // head
276 *(s++) = 0x80 | ((c >> (6 * --b)) & 0x3F); // payload
280 memmove(s, strchr(s, ';') + 1, strlen(strchr(s, ';')));
282 else if ((*s == '&' && (t == '&' || t == ' ' || t == '*')) ||
283 (*s == '%' && t == '%')) // entity reference
285 for (b = 0; ent[b] && strncmp(s + 1, ent[b], strlen(ent[b]));
288 ; // find entity in entity list
291 if (ent[b++]) // found a match
293 if ((c = (long)strlen(ent[b])) - 1 > (e = strchr(s, ';')) - s)
295 l = (long)(d = (long)(s - r)) + c + (long)strlen(e); // new length
296 r = (r == m) ? strcpy(MALLOC(l), r) : REALLOC(r, l);
297 e = strchr((s = r + d), ';'); // fix up pointers
302 memmove(s + c, e + 1, strlen(e)); // shift rest of string
303 strncpy(s, ent[b], c); // copy in replacement text
308 s++; // not a known entity
311 else if ((t == ' ' || t == '*') && isspace(*s))
317 s++; // no decoding needed
321 if (t == '*') // normalize spaces for non-cdata attributes
325 if ((l = (long)strspn(s, " ")))
327 memmove(s, s + l, (long)strlen(s + l) + 1);
329 while (*s && *s != ' ')
334 if (--s >= r && *s == ' ')
336 *s = '\0'; // trim any trailing space
342 // called when parser finds start of new tag
343 void ezxml_open_tag(ezxml_root_t root, char *name, char **attr)
345 ezxml_t xml = root->cur;
349 xml = ezxml_add_child(xml, name, strlen(xml->txt));
353 xml->name = name; // first open tag
357 root->cur = xml; // update tag insertion point
360 // called when parser finds character content between open and closing tag
361 void ezxml_char_content(ezxml_root_t root, char *s, size_t len, char t)
363 ezxml_t xml = root->cur;
367 if (! xml || ! xml->name || ! len)
369 return; // sanity check
372 s[len] = '\0'; // null terminate text (calling functions anticipate this)
373 len = strlen(s = ezxml_decode(s, root->ent, t)) + 1;
377 xml->txt = s; // initial character content
379 else // allocate our own memory and make a copy
381 xml->txt = (xml->flags & EZXML_TXTM) // allocate some space
382 ? REALLOC(xml->txt, (l = strlen(xml->txt)) + len)
383 : strcpy(MALLOC((l = strlen(xml->txt)) + len), xml->txt);
384 strcpy(xml->txt + l, s); // add new char content
387 FREE(s); // free s if it was malloced by ezxml_decode()
393 ezxml_set_flag(xml, EZXML_TXTM);
397 // called when parser finds closing tag
398 ezxml_t ezxml_close_tag(ezxml_root_t root, char *name, char *s)
400 if (! root->cur || ! root->cur->name || strcmp(name, root->cur->name))
402 return ezxml_err(root, s, "unexpected closing tag </%s>", name);
405 root->cur = root->cur->parent;
409 // checks for circular entity references, returns non-zero if no circular
410 // references are found, zero otherwise
411 int ezxml_ent_ok(char *name, char *s, char **ent)
417 while (*s && *s != '&')
419 s++; // find next entity reference
425 if (! strncmp(s + 1, name, strlen(name)))
427 return 0; // circular ref.
429 for (i = 0; ent[i] && strncmp(ent[i], s + 1, strlen(ent[i])); i += 2)
433 if (ent[i] && ! ezxml_ent_ok(name, ent[i + 1], ent))
440 // called when the parser finds a processing instruction
441 void ezxml_proc_inst(ezxml_root_t root, char *s, size_t len)
446 s[len] = '\0'; // null terminate instruction
447 if (*(s += strcspn(s, EZXML_WS)))
449 *s = '\0'; // null terminate target
450 s += strspn(s + 1, EZXML_WS) + 1; // skip whitespace after target
453 if (! strcmp(target, "xml")) // <?xml ... ?>
455 if ((s = strstr(s, "standalone")) && ! strncmp(s + strspn(s + 10,
456 EZXML_WS "='\"") + 10, "yes", 3))
458 root->standalone = 1;
465 *(root->pi = MALLOC(sizeof(char **))) = NULL; //first pi
468 while (root->pi[i] && strcmp(target, root->pi[i][0]))
472 if (! root->pi[i]) // new target
474 root->pi = REALLOC(root->pi, sizeof(char **) * (i + 2));
475 root->pi[i] = MALLOC(sizeof(char *) * 3);
476 root->pi[i][0] = target;
477 root->pi[i][1] = (char *)(root->pi[i + 1] = NULL); // terminate pi list
478 root->pi[i][2] = os_strdup(""); // empty document position list
481 while (root->pi[i][j])
483 j++; // find end of instruction list for this target
485 root->pi[i] = REALLOC(root->pi[i], sizeof(char *) * (j + 3));
486 root->pi[i][j + 2] = REALLOC(root->pi[i][j + 1], j + 1);
487 strcpy(root->pi[i][j + 2] + j - 1, (root->xml.name) ? ">" : "<");
488 root->pi[i][j + 1] = NULL; // null terminate pi list for this target
489 root->pi[i][j] = s; // set instruction
492 // called when the parser finds an internal doctype subset
493 short ezxml_internal_dtd(ezxml_root_t root, char *s, size_t len)
495 char q, *c, *t, *n = NULL, *v, **ent, **pe;
498 pe = memcpy(MALLOC(sizeof(EZXML_NIL)), EZXML_NIL, sizeof(EZXML_NIL));
500 for (s[len] = '\0'; s; )
502 while (*s && *s != '<' && *s != '%')
504 s++; // find next declaration
511 else if (! strncmp(s, "<!ENTITY", 8)) // parse entity definitions
513 c = s += strspn(s + 8, EZXML_WS) + 8; // skip white space separator
514 n = s + strspn(s, EZXML_WS "%"); // find name
515 *(s = n + strcspn(n, EZXML_WS)) = ';'; // append ; to name
517 v = s + strspn(s + 1, EZXML_WS) + 1; // find value
518 if ((q = *(v++)) != '"' && q != '\'') // skip externals
524 for (i = 0, ent = (*c == '%') ? pe : root->ent; ent[i]; i++)
528 ent = REALLOC(ent, (i + 3) * sizeof(char *)); // space for next ent
538 *(++s) = '\0'; // null terminate name
539 if ((s = strchr(v, q)))
541 *(s++) = '\0'; // null terminate value
543 ent[i + 1] = ezxml_decode(v, pe, '%'); // set value
544 ent[i + 2] = NULL; // null terminate entity list
545 if (! ezxml_ent_ok(n, ent[i + 1], ent)) // circular reference
551 ezxml_err(root, v, "circular entity declaration &%s", n);
556 ent[i] = n; // set entity name
559 else if (! strncmp(s, "<!ATTLIST", 9)) // parse default attributes
561 t = s + strspn(s + 9, EZXML_WS) + 9; // skip whitespace separator
564 ezxml_err(root, t, "unclosed <!ATTLIST");
567 if (*(s = t + strcspn(t, EZXML_WS ">")) == '>')
573 *s = '\0'; // null terminate tag name
578 for (i = 0; root->attr[i] && strcmp(n, root->attr[i][0]); i++)
584 while (*(n = ++s + strspn(s, EZXML_WS)) && *n != '>')
586 if (*(s = n + strcspn(n, EZXML_WS)))
588 *s = '\0'; // attr name
592 ezxml_err(root, t, "malformed <!ATTLIST");
596 s += strspn(s + 1, EZXML_WS) + 1; // find next token
597 c = (strncmp(s, "CDATA", 5)) ? "*" : " "; // is it cdata?
598 if (! strncmp(s, "NOTATION", 8))
600 s += strspn(s + 8, EZXML_WS) + 8;
602 s = (*s == '(') ? strchr(s, ')') : s + strcspn(s, EZXML_WS);
605 ezxml_err(root, t, "malformed <!ATTLIST");
609 s += strspn(s, EZXML_WS ")"); // skip white space separator
610 if (! strncmp(s, "#FIXED", 6))
612 s += strspn(s + 6, EZXML_WS) + 6;
614 if (*s == '#') // no default value
616 s += strcspn(s, EZXML_WS ">") - 1;
619 continue; // cdata is default, nothing to do
623 else if ((*s == '"' || *s == '\'') && // default value
624 (s = strchr(v = s + 1, *s)))
630 ezxml_err(root, t, "malformed <!ATTLIST");
634 if (! root->attr[i]) // new tag name
636 root->attr = (! i) ? MALLOC(2 * sizeof(char **))
637 : REALLOC(root->attr,
638 (i + 2) * sizeof(char **));
639 root->attr[i] = MALLOC(2 * sizeof(char *));
640 root->attr[i][0] = t; // set tag name
641 root->attr[i][1] = (char *)(root->attr[i + 1] = NULL);
644 for (j = 1; root->attr[i][j]; j += 3)
646 ; // find end of list
648 root->attr[i] = REALLOC(root->attr[i],
649 (j + 4) * sizeof(char *));
651 root->attr[i][j + 3] = NULL; // null terminate list
652 root->attr[i][j + 2] = c; // is it cdata?
653 root->attr[i][j + 1] = (v) ? ezxml_decode(v, root->ent, *c)
655 root->attr[i][j] = n; // attribute name
658 else if (! strncmp(s, "<!--", 4))
660 s = strstr(s + 4, "-->"); // comments
662 else if (! strncmp(s, "<?", 2)) // processing instructions
664 if ((s = strstr(c = s + 2, "?>")))
666 ezxml_proc_inst(root, c, s++ - c);
671 s = strchr(s, '>'); // skip other declarations
673 else if (*(s++) == '%' && ! root->standalone)
683 // Converts a UTF-16 string to UTF-8. Returns a new string that must be freed
684 // or NULL if no conversion was needed.
685 char *ezxml_str2utf8(char **s, size_t *len)
688 size_t l = 0, sl, max = *len;
690 int b, be = (**s == '\xFE') ? 1 : (**s == '\xFF') ? 0 : -1;
694 return NULL; // not UTF-16
698 for (sl = 2; sl < *len - 1; sl += 2)
700 c = (be) ? (((*s)[sl] & 0xFF) << 8) | ((*s)[sl + 1] & 0xFF) //UTF-16BE
701 : (((*s)[sl + 1] & 0xFF) << 8) | ((*s)[sl] & 0xFF); //UTF-16LE
702 if (c >= 0xD800 && c <= 0xDFFF && (sl += 2) < *len - 1) // high-half
704 d = (be) ? (((*s)[sl] & 0xFF) << 8) | ((*s)[sl + 1] & 0xFF)
705 : (((*s)[sl + 1] & 0xFF) << 8) | ((*s)[sl] & 0xFF);
706 c = (((c & 0x3FF) << 10) | (d & 0x3FF)) + 0x10000;
711 u = REALLOC(u, max += EZXML_BUFSIZE);
715 u[l++] = (char)c; // US-ASCII subset
717 else // multi-byte UTF-8 sequence
719 for (b = 0, d = c; d; d /= 2)
723 b = (b - 2) / 5; // bytes in payload
724 u[l++] = (char)(0xFF << (7 - b)) | (char)(c >> (6 * b)); // head
727 u[l++] = 0x80 | ((c >> (6 * --b)) & 0x3F); // payload
731 return *s = REALLOC(u, *len = l);
734 // frees a tag attribute list
735 void ezxml_free_attr(char **attr)
740 if (! attr || attr == EZXML_NIL)
742 return; // nothing to free
746 i += 2; // find end of attribute list
748 m = attr[i + 1]; // list of which names and values are malloced
749 for (i = 0; m[i]; i++)
751 if (m[i] & EZXML_NAMEM)
755 if (m[i] & EZXML_TXTM)
757 FREE(attr[(i * 2) + 1]);
764 // parse the given xml string and return an ezxml structure
765 ezxml_t ezxml_parse_str(char *s, size_t len)
767 ezxml_root_t root = (ezxml_root_t)ezxml_new(NULL);
768 char q, e, *d, **attr, **a = NULL; // initialize a to avoid compile warning
774 return ezxml_err(root, NULL, "root tag missing");
776 root->u = ezxml_str2utf8(&s, &len); // convert utf-16 to utf-8
777 root->e = (root->s = s) + len; // record start and end of work area
779 e = s[len - 1]; // save end char
780 s[len - 1] = '\0'; // turn end char into null terminator
782 while (*s && *s != '<')
784 s++; // find first tag
788 return ezxml_err(root, s, "root tag missing");
793 attr = (char **)EZXML_NIL;
796 if (isalpha(*s) || *s == '_' || *s == ':' || *s < '\0') // new tag
800 return ezxml_err(root, d, "markup outside of root element");
803 s += strcspn(s, EZXML_WS "/>");
806 *(s++) = '\0'; // null terminate tag name
809 if (*s && *s != '/' && *s != '>') // find tag in default attr list
810 for (i = 0; (a = root->attr[i]) && strcmp(a[0], d); i++)
815 for (l = 0; *s && *s != '/' && *s != '>'; l += 2) // new attrib
817 attr = (l) ? REALLOC(attr, (l + 4) * sizeof(char *))
818 : MALLOC(4 * sizeof(char *)); // allocate space
819 attr[l + 3] = (l) ? REALLOC(attr[l + 1], (l / 2) + 2)
820 : MALLOC(2); // mem for list of maloced vals
821 strcpy(attr[l + 3] + (l / 2), " "); // value is not malloced
822 attr[l + 2] = NULL; // null terminate list
823 attr[l + 1] = ""; // temporary attribute value
824 attr[l] = s; // set attribute name
826 s += strcspn(s, EZXML_WS "=/>");
827 if (*s == '=' || isspace(*s))
829 *(s++) = '\0'; // null terminate tag attribute name
830 q = *(s += strspn(s, EZXML_WS "="));
831 if (q == '"' || q == '\'') // attribute value
834 while (*s && *s != q)
840 *(s++) = '\0'; // null terminate attribute val
844 ezxml_free_attr(attr);
845 return ezxml_err(root, d, "missing %c", q);
848 for (j = 1; a && a[j] && strcmp(a[j], attr[l]); j += 3)
852 attr[l + 1] = ezxml_decode(attr[l + 1], root->ent, (a
853 && a[j]) ? *a[j + 2] : ' ');
854 if (attr[l + 1] < d || attr[l + 1] > s)
856 attr[l + 3][l / 2] = EZXML_TXTM; // value malloced
866 if (*s == '/') // self closing tag
869 if ((*s && *s != '>') || (! *s && e != '>'))
873 ezxml_free_attr(attr);
875 return ezxml_err(root, d, "missing >");
877 ezxml_open_tag(root, d, attr);
878 ezxml_close_tag(root, d, s);
880 else if ((q = *s) == '>' || (! *s && e == '>')) // open tag
882 *s = '\0'; // temporarily null terminate tag name
883 ezxml_open_tag(root, d, attr);
890 ezxml_free_attr(attr);
892 return ezxml_err(root, d, "missing >");
895 else if (*s == '/') // close tag
897 s += strcspn(d = s + 1, EZXML_WS ">") + 1;
898 if (! (q = *s) && e != '>')
900 return ezxml_err(root, d, "missing >");
902 *s = '\0'; // temporarily null terminate tag name
903 if (ezxml_close_tag(root, d, s))
909 s += strspn(s, EZXML_WS);
912 else if (! strncmp(s, "!--", 3)) // xml comment
914 if (! (s = strstr(s + 3, "--")) || (*(s += 2) != '>' && *s) ||
917 return ezxml_err(root, d, "unclosed <!--");
920 else if (! strncmp(s, "![CDATA[", 8)) // cdata
922 if ((s = strstr(s, "]]>")))
924 ezxml_char_content(root, d + 8, (s += 2) - d - 10, 'c');
928 return ezxml_err(root, d, "unclosed <![CDATA[");
931 else if (! strncmp(s, "!DOCTYPE", 8)) // dtd
933 for (l = 0; *s && ((! l && *s != '>') || (l && (*s != ']' ||
934 *(s + strspn(s + 1, EZXML_WS) + 1) != '>')));
935 l = (*s == '[') ? 1 : l)
937 s += strcspn(s + 1, "[]>") + 1;
939 if (! *s && e != '>')
941 return ezxml_err(root, d, "unclosed <!DOCTYPE");
943 d = (l) ? strchr(d, '[') + 1 : d;
944 if (l && ! ezxml_internal_dtd(root, d, s++ - d))
949 else if (*s == '?') // <?...?> processing instructions
955 while (s && *(++s) && *s != '>');
956 if (! s || (! *s && e != '>'))
958 return ezxml_err(root, d, "unclosed <?");
962 ezxml_proc_inst(root, d + 1, s - d - 2);
967 return ezxml_err(root, d, "unexpected <");
976 if (*s && *s != '<') // tag character content
978 while (*s && *s != '<')
984 ezxml_char_content(root, d, s - d, '&');
1001 else if (! root->cur->name)
1003 return ezxml_err(root, d, "root tag missing");
1007 return ezxml_err(root, d, "unclosed tag <%s>", root->cur->name);
1011 // Wrapper for ezxml_parse_str() that accepts a file stream. Reads the entire
1012 // stream into memory and then parses it. For xml files, use ezxml_parse_file()
1013 // or ezxml_parse_fd()
1014 ezxml_t ezxml_parse_fp(FILE *fp)
1020 if (! (s = MALLOC(EZXML_BUFSIZE)))
1026 len += (l = fread((s + len), 1, EZXML_BUFSIZE, fp));
1027 if (l == EZXML_BUFSIZE)
1029 s = REALLOC(s, len + EZXML_BUFSIZE);
1032 while (s && l == EZXML_BUFSIZE);
1038 root = (ezxml_root_t)ezxml_parse_str(s, len);
1039 root->len = (size_t) - 1; // so we know to free s in ezxml_free()
1043 // A wrapper for ezxml_parse_str() that accepts a file descriptor. First
1044 // attempts to mem map the file. Failing that, reads the file into memory.
1045 // Returns NULL on failure.
1046 ezxml_t ezxml_parse_fd(int fd)
1057 if (fstat(fd, &st) < 0)
1062 #ifndef EZXML_NOMMAP
1063 l = (st.st_size + sysconf(_SC_PAGESIZE) - 1) & ~(sysconf(_SC_PAGESIZE) - 1);
1064 if ((m = mmap(NULL, l, PROT_READ | PROT_WRITE, MAP_PRIVATE, fd, 0)) != MAP_FAILED)
1066 madvise(m, l, MADV_SEQUENTIAL); // optimize for sequential access
1067 root = (ezxml_root_t)ezxml_parse_str(m, st.st_size);
1068 madvise(m, root->len = l, MADV_NORMAL); // put it back to normal
1070 else // mmap failed, read file into memory
1072 #endif // EZXML_NOMMAP
1073 l = (size_t) read(fd, m = MALLOC(st.st_size), st.st_size);
1074 if ((ssize_t) l <= 0)
1080 root = (ezxml_root_t)ezxml_parse_str(m, l);
1081 root->len = (size_t) - 1; // so we know to free s in ezxml_free()
1082 #ifndef EZXML_NOMMAP
1084 #endif // EZXML_NOMMAP
1089 // a wrapper for ezxml_parse_fd that accepts a file name
1090 ezxml_t ezxml_parse_file(const char *file)
1092 int fd = open(file, O_RDONLY, 0);
1093 ezxml_t xml = ezxml_parse_fd(fd);
1101 // Encodes ampersand sequences appending the results to *dst, reallocating *dst
1102 // if length exceeds max. a is non-zero for attribute encoding. Returns *dst
1103 char *ezxml_ampencode(const char *s, size_t len, char **dst, size_t *dlen,
1104 size_t *max, short a)
1108 for (e = s + len; s != e; s++)
1110 while (*dlen + 10 > *max)
1112 *dst = REALLOC(*dst, *max += EZXML_BUFSIZE);
1120 *dlen += sprintf(*dst + *dlen, "&");
1123 *dlen += sprintf(*dst + *dlen, "<");
1126 *dlen += sprintf(*dst + *dlen, ">");
1129 *dlen += sprintf(*dst + *dlen, (a) ? """ : "\"");
1132 *dlen += sprintf(*dst + *dlen, (a) ? "
" : "\n");
1135 *dlen += sprintf(*dst + *dlen, (a) ? "	" : "\t");
1138 *dlen += sprintf(*dst + *dlen, "
");
1141 (*dst)[(*dlen)++] = *s;
1147 // Recursively converts each tag to xml appending it to *s. Reallocates *s if
1148 // its length excedes max. start is the location of the previous tag in the
1149 // parent tag's character content. Returns *s.
1150 char *ezxml_toxml_r(ezxml_t xml, char **s, size_t *len, size_t *max,
1151 size_t start, char ***attr)
1154 char *txt = (xml->parent) ? xml->parent->txt : "";
1157 // parent character content up to this tag
1158 *s = ezxml_ampencode(txt + start, xml->off - start, s, len, max, 0);
1160 while (*len + strlen(xml->name) + 4 > *max) // reallocate s
1162 *s = REALLOC(*s, *max += EZXML_BUFSIZE);
1165 *len += sprintf(*s + *len, "<%s", xml->name); // open tag
1166 for (i = 0; xml->attr[i]; i += 2) // tag attributes
1168 if (ezxml_attr(xml, xml->attr[i]) != xml->attr[i + 1])
1172 while (*len + strlen(xml->attr[i]) + 7 > *max) // reallocate s
1174 *s = REALLOC(*s, *max += EZXML_BUFSIZE);
1177 *len += sprintf(*s + *len, " %s=\"", xml->attr[i]);
1178 ezxml_ampencode(xml->attr[i + 1], (size_t)(-1), s, len, max, 1);
1179 *len += sprintf(*s + *len, "\"");
1182 for (i = 0; attr[i] && strcmp(attr[i][0], xml->name); i++)
1186 for (j = 1; attr[i] && attr[i][j]; j += 3) // default attributes
1188 if (! attr[i][j + 1] || ezxml_attr(xml, attr[i][j]) != attr[i][j + 1])
1190 continue; // skip duplicates and non-values
1192 while (*len + strlen(attr[i][j]) + 7 > *max) // reallocate s
1194 *s = REALLOC(*s, *max += EZXML_BUFSIZE);
1197 *len += sprintf(*s + *len, " %s=\"", attr[i][j]);
1198 ezxml_ampencode(attr[i][j + 1], (size_t)(-1), s, len, max, 1);
1199 *len += sprintf(*s + *len, "\"");
1201 *len += sprintf(*s + *len, ">");
1203 *s = (xml->child) ? ezxml_toxml_r(xml->child, s, len, max, 0, attr) //child
1204 : ezxml_ampencode(xml->txt, (size_t)(-1), s, len, max, 0); //data
1206 while (*len + strlen(xml->name) + 4 > *max) // reallocate s
1208 *s = REALLOC(*s, *max += EZXML_BUFSIZE);
1211 *len += sprintf(*s + *len, "</%s>", xml->name); // close tag
1213 while (txt[off] && off < xml->off)
1215 off++; // make sure off is within bounds
1217 return (xml->ordered) ? ezxml_toxml_r(xml->ordered, s, len, max, off, attr)
1218 : ezxml_ampencode(txt + off, (size_t)(-1), s, len, max, 0);
1221 // Converts an ezxml structure back to xml. Returns a string of xml data that
1223 char *ezxml_toxml(ezxml_t xml)
1225 ezxml_t p = (xml) ? xml->parent : NULL, o = (xml) ? xml->ordered : NULL;
1226 ezxml_root_t root = (ezxml_root_t)xml;
1227 size_t len = 0, max = EZXML_BUFSIZE;
1228 char *s = strcpy(MALLOC(max), ""), *t, *n;
1231 if (! xml || ! xml->name)
1233 return REALLOC(s, len + 1);
1235 while (root->xml.parent)
1237 root = (ezxml_root_t)root->xml.parent; // root tag
1240 for (i = 0; ! p && root->pi[i]; i++) // pre-root processing instructions
1242 for (k = 2; root->pi[i][k - 1]; k++)
1246 for (j = 1; (n = root->pi[i][j]); j++)
1248 if (root->pi[i][k][j - 1] == '>')
1250 continue; // not pre-root
1252 while (len + strlen(t = root->pi[i][0]) + strlen(n) + 7 > max)
1254 s = REALLOC(s, max += EZXML_BUFSIZE);
1256 len += sprintf(s + len, "<?%s%s%s?>\n", t, *n ? " " : "", n);
1260 xml->parent = xml->ordered = NULL;
1261 s = ezxml_toxml_r(xml, &s, &len, &max, 0, root->attr);
1265 for (i = 0; ! p && root->pi[i]; i++) // post-root processing instructions
1267 for (k = 2; root->pi[i][k - 1]; k++)
1271 for (j = 1; (n = root->pi[i][j]); j++)
1273 if (root->pi[i][k][j - 1] == '<')
1275 continue; // not post-root
1277 while (len + strlen(t = root->pi[i][0]) + strlen(n) + 7 > max)
1279 s = REALLOC(s, max += EZXML_BUFSIZE);
1281 len += sprintf(s + len, "\n<?%s%s%s?>", t, *n ? " " : "", n);
1284 return REALLOC(s, len + 1);
1287 // free the memory allocated for the ezxml structure
1288 void ezxml_free(ezxml_t xml)
1290 ezxml_root_t root = (ezxml_root_t)xml;
1298 ezxml_free(xml->child);
1299 ezxml_free(xml->ordered);
1301 if (! xml->parent) // free root tag allocations
1303 for (i = 10; root->ent[i]; i += 2) // 0 - 9 are default entites (<>&"')
1304 if ((s = root->ent[i + 1]) < root->s || s > root->e)
1308 FREE(root->ent); // free list of general entities
1310 for (i = 0; (a = root->attr[i]); i++)
1312 for (j = 1; a[j++]; j += 2) // free malloced attribute values
1313 if (a[j] && (a[j] < root->s || a[j] > root->e))
1321 FREE(root->attr); // free default attribute list
1324 for (i = 0; root->pi[i]; i++)
1326 for (j = 1; root->pi[i][j]; j++)
1330 FREE(root->pi[i][j + 1]);
1335 FREE(root->pi); // free processing instructions
1338 if (root->len == -1)
1340 FREE(root->m); // malloced xml data
1342 #ifndef EZXML_NOMMAP
1345 munmap(root->m, root->len); // mem mapped xml data
1347 #endif // EZXML_NOMMAP
1350 FREE(root->u); // utf8 conversion
1354 ezxml_free_attr(xml->attr); // tag attributes
1355 if ((xml->flags & EZXML_TXTM))
1357 FREE(xml->txt); // character content
1359 if ((xml->flags & EZXML_NAMEM))
1361 FREE(xml->name); // tag name
1366 // return parser error message or empty string if none
1367 const char *ezxml_error(ezxml_t xml)
1369 while (xml && xml->parent)
1371 xml = xml->parent; // find root tag
1373 return (xml) ? ((ezxml_root_t)xml)->err : "";
1376 // returns a new empty ezxml structure with the given root tag name
1377 ezxml_t ezxml_new(const char *name)
1379 static char *ent[] = { "lt;", "<", "gt;", ">", "quot;", """,
1380 "apos;", "'", "amp;", "&", NULL
1382 ezxml_root_t root = (ezxml_root_t)memset(MALLOC(sizeof(struct ezxml_root)),
1383 '\0', sizeof(struct ezxml_root));
1384 root->xml.name = (char *)name;
1385 root->cur = &root->xml;
1386 strcpy(root->err, root->xml.txt = "");
1387 root->ent = memcpy(MALLOC(sizeof(ent)), ent, sizeof(ent));
1388 root->attr = root->pi = (char ***)(root->xml.attr = EZXML_NIL);
1392 // inserts an existing tag into an ezxml structure
1393 ezxml_t ezxml_insert(ezxml_t xml, ezxml_t dest, size_t off)
1395 ezxml_t cur, prev, head;
1397 xml->next = xml->sibling = xml->ordered = NULL;
1401 if ((head = dest->child)) // already have sub tags
1403 if (head->off <= off) // not first subtag
1405 for (cur = head; cur->ordered && cur->ordered->off <= off;
1410 xml->ordered = cur->ordered;
1413 else // first subtag
1415 xml->ordered = head;
1419 for (cur = head, prev = NULL; cur && strcmp(cur->name, xml->name);
1420 prev = cur, cur = cur->sibling)
1424 if (cur && cur->off <= off) // not first of type
1426 while (cur->next && cur->next->off <= off)
1430 xml->next = cur->next;
1433 else // first tag of this type
1437 prev->sibling = cur->sibling; // remove old first
1439 xml->next = cur; // old first tag is now next
1440 for (cur = head, prev = NULL; cur && cur->off <= off;
1441 prev = cur, cur = cur->sibling)
1443 ; // new sibling insert point
1448 prev->sibling = xml;
1454 dest->child = xml; // only sub tag
1460 // Adds a child tag. off is the offset of the child tag relative to the start
1461 // of the parent tag's character content. Returns the child tag.
1462 ezxml_t ezxml_add_child(ezxml_t xml, const char *name, size_t off)
1470 child = (ezxml_t)memset(MALLOC(sizeof(struct ezxml)), '\0',
1471 sizeof(struct ezxml));
1472 child->name = (char *)name;
1473 child->attr = EZXML_NIL;
1476 return ezxml_insert(child, xml, off);
1479 // sets the character content for the given tag and returns the tag
1480 ezxml_t ezxml_set_txt(ezxml_t xml, const char *txt)
1486 if (xml->flags & EZXML_TXTM)
1488 FREE(xml->txt); // existing txt was malloced
1490 xml->flags &= ~EZXML_TXTM;
1491 xml->txt = (char *)txt;
1495 // Sets the given tag attribute or adds a new attribute if not found. A value
1496 // of NULL will remove the specified attribute. Returns the tag given.
1497 ezxml_t ezxml_set_attr(ezxml_t xml, const char *name, char *value)
1504 while (xml->attr[l] && strcmp(xml->attr[l], name))
1509 if (! xml->attr[l]) // not found, add as new attribute
1513 return xml; // nothing to do
1515 if (xml->attr == EZXML_NIL) // first attribute
1517 xml->attr = MALLOC(4 * sizeof(char *));
1518 xml->attr[1] = os_strdup(""); // empty list of malloced names/vals
1522 xml->attr = REALLOC(xml->attr, (l + 4) * sizeof(char *));
1525 xml->attr[l] = (char *)name; // set attribute name
1526 xml->attr[l + 2] = NULL; // null terminate attribute list
1527 xml->attr[l + 3] = REALLOC(xml->attr[l + 1], (c = (int)strlen(xml->attr[l + 1])) + 2);
1528 strcpy(xml->attr[l + 3] + c, " "); // set name/value as not malloced
1529 if (xml->flags & EZXML_DUP)
1531 xml->attr[l + 3][c] = EZXML_NAMEM;
1534 else if (xml->flags & EZXML_DUP)
1536 FREE((char *)name); // name was os_strduped
1539 for (c = l; xml->attr[c]; c += 2)
1541 ; // find end of attribute list
1543 if (xml->attr[c + 1][l / 2] & EZXML_TXTM)
1545 FREE(xml->attr[l + 1]); //old val
1547 if (xml->flags & EZXML_DUP)
1549 xml->attr[c + 1][l / 2] |= EZXML_TXTM;
1553 xml->attr[c + 1][l / 2] &= ~EZXML_TXTM;
1558 xml->attr[l + 1] = (char *)value; // set attribute value
1560 else // remove attribute
1562 if (xml->attr[c + 1][l / 2] & EZXML_NAMEM)
1566 memmove(xml->attr + l, xml->attr + l + 2, (c - l + 2) * sizeof(char*));
1567 xml->attr = REALLOC(xml->attr, (c + 2) * sizeof(char *));
1568 memmove(xml->attr[c + 1] + (l / 2), xml->attr[c + 1] + (l / 2) + 1,
1569 (c / 2) - (l / 2)); // fix list of which name/vals are malloced
1571 xml->flags &= ~EZXML_DUP; // clear os_strdup() flag
1575 // sets a flag for the given tag and returns the tag
1576 ezxml_t ezxml_set_flag(ezxml_t xml, short flag)
1585 // removes a tag along with its subtags without freeing its memory
1586 ezxml_t ezxml_cut(ezxml_t xml)
1592 return NULL; // nothing to do
1596 xml->next->sibling = xml->sibling; // patch sibling list
1599 if (xml->parent) // not root tag
1601 cur = xml->parent->child; // find head of subtag list
1604 xml->parent->child = xml->ordered; // first subtag
1606 else // not first subtag
1608 while (cur->ordered != xml)
1612 cur->ordered = cur->ordered->ordered; // patch ordered list
1614 cur = xml->parent->child; // go back to head of subtag list
1615 if (strcmp(cur->name, xml->name)) // not in first sibling list
1617 while (strcmp(cur->sibling->name, xml->name))
1621 if (cur->sibling == xml) // first of a sibling list
1623 cur->sibling = (xml->next) ? xml->next
1624 : cur->sibling->sibling;
1628 cur = cur->sibling; // not first of a sibling list
1632 while (cur->next && cur->next != xml)
1638 cur->next = cur->next->next; // patch next list
1642 xml->ordered = xml->sibling = xml->next = NULL;
1645 /*----------------------------------------------------------*/
1646 int write_in_child(ezxml_t *parent, char *idx, char *w)
1648 ezxml_t terminal, structx, subnode, i_value;
1653 for (terminal = ezxml_child(*parent, "terminal"); terminal; terminal = terminal->next)
1655 if (strcmp(ezxml_child(terminal, "id")->txt, idx) == 0)
1657 i_value = ezxml_child(terminal, "initial_value");
1658 ezxml_set_attr(i_value, "value", w);
1659 return 1; /* found */
1663 for (structx = ezxml_child(*parent, "struct"); structx; structx = structx->next)
1665 for (subnode = ezxml_child(structx, "subnodes"); subnode; subnode = subnode->next)
1667 result = write_in_child(&subnode, idx, w);
1675 return 0; /* not found*/
1677 /*----------------------------------------------------------*/
1678 int search_in_child(ezxml_t *parent, char *idx, char *value)
1680 ezxml_t terminal, structx, subnode, i_value;
1681 const char *teamname;
1684 for (terminal = ezxml_child(*parent, "terminal"); terminal; terminal = terminal->next)
1686 if (strcmp(ezxml_child(terminal, "id")->txt, idx) == 0)
1688 i_value = ezxml_child(terminal, "initial_value");
1689 teamname = ezxml_attr(i_value, "value");
1690 strcpy (value, teamname);
1691 return 1; /* found */
1695 for (structx = ezxml_child(*parent, "struct"); structx; structx = structx->next)
1697 for (subnode = ezxml_child(structx, "subnodes"); subnode; subnode = subnode->next)
1699 result = search_in_child(&subnode, idx, value);
1707 return 0; /* not found*/
1710 /*----------------------------------------------------------*/