1 /* ezxml.c
2  *
3  * Copyright 2004-2006 Aaron Voisine <aaron@voisine.org>
4  *
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:
12  *
13  * The above copyright notice and this permission notice shall be included
14  * in all copies or substantial portions of the Software.
15  *
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.
23  */
24 
25 #include <stdlib.h>
26 #include <stdio.h>
27 #include <stdarg.h>
28 #include <string.h>
29 #include <ctype.h>
30 
31 #ifndef _WIN32
32 #include <unistd.h>
33 #else
34 #define EZXML_NOMMAP 1
35 #define snprintf _snprintf
36 #define vsnprintf _vsnprintf
37 #endif
38 
39 #include <sys/types.h>
40 #ifndef EZXML_NOMMAP
41 #include <sys/mman.h>
42 #endif // EZXML_NOMMAP
43 #include <sys/stat.h>
44 #include "ezxml.h"
45 
46 #define EZXML_WS   "\t\r\n "  // whitespace
47 #define EZXML_ERRL 128        // maximum error string length
48 
49 typedef struct ezxml_root *ezxml_root_t;
50 struct ezxml_root {       // additional data for the root tag
51   struct ezxml xml;     // is a super-struct built on top of ezxml struct
52   ezxml_t cur;          // current xml tree insertion point
53   char *m;              // original xml string
54   size_t len;           // length of allocated memory for mmap, -1 for malloc
55   char *u;              // UTF-8 conversion of string if original was UTF-16
56   char *s;              // start of work area
57   char *e;              // end of work area
58   char **ent;           // general entities (ampersand sequences)
59   char ***attr;         // default attributes
60   char ***pi;           // processing instructions
61   short standalone;     // non-zero if <?xml standalone="yes"?>
62   char err[EZXML_ERRL]; // error string
63 };
64 
65 char *EZXML_NIL[] = { NULL }; // empty, null terminated array of strings
66 
67 // returns the first child tag with the given name or NULL if not found
ezxml_child(ezxml_t xml,const char * name)68 ezxml_t ezxml_child(ezxml_t xml, const char *name)
69 {
70   xml = (xml) ? xml->child : NULL;
71   while (xml && strcmp(name, xml->name)) xml = xml->sibling;
72   return xml;
73 }
74 
75 // returns the Nth tag with the same name in the same subsection or NULL if not
76 // found
ezxml_idx(ezxml_t xml,int idx)77 ezxml_t ezxml_idx(ezxml_t xml, int idx)
78 {
79   for (; xml && idx; idx--) xml = xml->next;
80   return xml;
81 }
82 
83 // returns the value of the requested tag attribute or NULL if not found
ezxml_attr(ezxml_t xml,const char * attr)84 const char *ezxml_attr(ezxml_t xml, const char *attr)
85 {
86   int i = 0, j = 1;
87   ezxml_root_t root = (ezxml_root_t)xml;
88 
89   if (! xml || ! xml->attr) return NULL;
90   while (xml->attr[i] && strcmp(attr, xml->attr[i])) i += 2;
91   if (xml->attr[i]) return xml->attr[i + 1]; // found attribute
92 
93   while (root->xml.parent) root = (ezxml_root_t)root->xml.parent; // root tag
94   for (i = 0; root->attr[i] && strcmp(xml->name, root->attr[i][0]); i++);
95   if (! root->attr[i]) return NULL; // no matching default attributes
96   while (root->attr[i][j] && strcmp(attr, root->attr[i][j])) j += 3;
97   return (root->attr[i][j]) ? root->attr[i][j + 1] : NULL; // found default
98 }
99 
100 // same as ezxml_get but takes an already initialized va_list
ezxml_vget(ezxml_t xml,va_list ap)101 ezxml_t ezxml_vget(ezxml_t xml, va_list ap)
102 {
103   char *name = va_arg(ap, char *);
104   int idx = -1;
105 
106   if (name && *name) {
107     idx = va_arg(ap, int);
108     xml = ezxml_child(xml, name);
109   }
110   return (idx < 0) ? xml : ezxml_vget(ezxml_idx(xml, idx), ap);
111 }
112 
113 // Traverses the xml tree to retrieve a specific subtag. Takes a variable
114 // length list of tag names and indexes. The argument list must be terminated
115 // by either an index of -1 or an empty string tag name. Example:
116 // title = ezxml_get(library, "shelf", 0, "book", 2, "title", -1);
117 // This retrieves the title of the 3rd book on the 1st shelf of library.
118 // Returns NULL if not found.
ezxml_get(ezxml_t xml,...)119 ezxml_t ezxml_get(ezxml_t xml, ...)
120 {
121   va_list ap;
122   ezxml_t r;
123 
124   va_start(ap, xml);
125   r = ezxml_vget(xml, ap);
126   va_end(ap);
127   return r;
128 }
129 
130 // returns a null terminated array of processing instructions for the given
131 // target
ezxml_pi(ezxml_t xml,const char * target)132 const char **ezxml_pi(ezxml_t xml, const char *target)
133 {
134   ezxml_root_t root = (ezxml_root_t)xml;
135   int i = 0;
136 
137   if (! root) return (const char **)EZXML_NIL;
138   while (root->xml.parent) root = (ezxml_root_t)root->xml.parent; // root tag
139   while (root->pi[i] && strcmp(target, root->pi[i][0])) i++; // find target
140   return (const char **)((root->pi[i]) ? root->pi[i] + 1 : EZXML_NIL);
141 }
142 
143 // set an error string and return root
ezxml_err(ezxml_root_t root,char * s,const char * err,...)144 ezxml_t ezxml_err(ezxml_root_t root, char *s, const char *err, ...)
145 {
146   va_list ap;
147   int line = 1;
148   char *t, fmt[EZXML_ERRL];
149 
150   for (t = root->s; t < s; t++) if (*t == '\n') line++;
151   snprintf(fmt, EZXML_ERRL, "[error near line %d]: %s", line, err);
152 
153   va_start(ap, err);
154   vsnprintf(root->err, EZXML_ERRL, fmt, ap);
155   va_end(ap);
156 
157   return &root->xml;
158 }
159 
160 // Recursively decodes entity and character references and normalizes new lines
161 // ent is a null terminated array of alternating entity names and values. set t
162 // to '&' for general entity decoding, '%' for parameter entity decoding, 'c'
163 // for cdata sections, ' ' for attribute normalization, or '*' for non-cdata
164 // attribute normalization. Returns s, or if the decoded string is longer than
165 // s, returns a malloced string that must be freed.
ezxml_decode(char * s,char ** ent,char t)166 char *ezxml_decode(char *s, char **ent, char t)
167 {
168   char *e, *r = s, *m = s;
169   long b, c, d, l;
170 
171   for (; *s; s++) { // normalize line endings
172     while (*s == '\r') {
173       *(s++) = '\n';
174       if (*s == '\n') memmove(s, (s + 1), strlen(s));
175     }
176   }
177 
178   for (s = r; ; ) {
179     while (*s && *s != '&' && (*s != '%' || t != '%') && !isspace(*s)) s++;
180 
181     if (! *s) break;
182     else if (t != 'c' && ! strncmp(s, "&#", 2)) { // character reference
183       if (s[2] == 'x') c = strtol(s + 3, &e, 16); // base 16
184       else c = strtol(s + 2, &e, 10); // base 10
185       if (! c || *e != ';') {
186         s++;  // not a character ref
187         continue;
188       }
189 
190       if (c < 0x80) *(s++) = c; // US-ASCII subset
191       else { // multi-byte UTF-8 sequence
192         for (b = 0, d = c; d; d /= 2) b++; // number of bits in c
193         b = (b - 2) / 5; // number of bytes in payload
194         *(s++) = (0xFF << (7 - b)) | (c >> (6 * b)); // head
195         while (b) *(s++) = 0x80 | ((c >> (6 * --b)) & 0x3F); // payload
196       }
197 
198       memmove(s, strchr(s, ';') + 1, strlen(strchr(s, ';')));
199     } else if ((*s == '&' && (t == '&' || t == ' ' || t == '*')) ||
200                (*s == '%' && t == '%')) { // entity reference
201       for (b = 0; ent[b] && strncmp(s + 1, ent[b], strlen(ent[b]));
202            b += 2); // find entity in entity list
203 
204       if (ent[b++]) { // found a match
205         if ((c = strlen(ent[b])) - 1 > (e = strchr(s, ';')) - s) {
206           l = (d = (s - r)) + c + strlen(e); // new length
207           r = (r == m) ? strcpy(malloc(l), r) : realloc(r, l);
208           e = strchr((s = r + d), ';'); // fix up pointers
209         }
210 
211         memmove(s + c, e + 1, strlen(e)); // shift rest of string
212         strncpy(s, ent[b], c); // copy in replacement text
213       } else s++; // not a known entity
214     } else if ((t == ' ' || t == '*') && isspace(*s)) *(s++) = ' ';
215     else s++; // no decoding needed
216   }
217 
218   if (t == '*') { // normalize spaces for non-cdata attributes
219     for (s = r; *s; s++) {
220       if ((l = strspn(s, " "))) memmove(s, s + l, strlen(s + l) + 1);
221       while (*s && *s != ' ') s++;
222     }
223     if (--s >= r && *s == ' ') *s = '\0'; // trim any trailing space
224   }
225   return r;
226 }
227 
228 // called when parser finds start of new tag
ezxml_open_tag(ezxml_root_t root,char * name,char ** attr)229 void ezxml_open_tag(ezxml_root_t root, char *name, char **attr)
230 {
231   ezxml_t xml = root->cur;
232 
233   if (xml->name) xml = ezxml_add_child(xml, name, strlen(xml->txt));
234   else xml->name = name; // first open tag
235 
236   xml->attr = attr;
237   root->cur = xml; // update tag insertion point
238 }
239 
240 // called when parser finds character content between open and closing tag
ezxml_char_content(ezxml_root_t root,char * s,size_t len,char t)241 void ezxml_char_content(ezxml_root_t root, char *s, size_t len, char t)
242 {
243   ezxml_t xml = root->cur;
244   char *m = s;
245   size_t l;
246 
247   if (! xml || ! xml->name || ! len) return; // sanity check
248 
249   s[len] = '\0'; // null terminate text (calling functions anticipate this)
250   len = strlen(s = ezxml_decode(s, root->ent, t)) + 1;
251 
252   if (! *(xml->txt)) xml->txt = s; // initial character content
253   else { // allocate our own memory and make a copy
254     xml->txt = (xml->flags & EZXML_TXTM) // allocate some space
255                ? realloc(xml->txt, (l = strlen(xml->txt)) + len)
256                : strcpy(malloc((l = strlen(xml->txt)) + len), xml->txt);
257     strcpy(xml->txt + l, s); // add new char content
258     if (s != m) free(s); // free s if it was malloced by ezxml_decode()
259   }
260 
261   if (xml->txt != m) ezxml_set_flag(xml, EZXML_TXTM);
262 }
263 
264 // called when parser finds closing tag
ezxml_close_tag(ezxml_root_t root,char * name,char * s)265 ezxml_t ezxml_close_tag(ezxml_root_t root, char *name, char *s)
266 {
267   if (! root->cur || ! root->cur->name || strcmp(name, root->cur->name))
268     return ezxml_err(root, s, "unexpected closing tag </%s>", name);
269 
270   root->cur = root->cur->parent;
271   return NULL;
272 }
273 
274 // checks for circular entity references, returns non-zero if no circular
275 // references are found, zero otherwise
ezxml_ent_ok(char * name,char * s,char ** ent)276 int ezxml_ent_ok(char *name, char *s, char **ent)
277 {
278   int i;
279 
280   for (; ; s++) {
281     while (*s && *s != '&') s++; // find next entity reference
282     if (! *s) return 1;
283     if (! strncmp(s + 1, name, strlen(name))) return 0; // circular ref.
284     for (i = 0; ent[i] && strncmp(ent[i], s + 1, strlen(ent[i])); i += 2);
285     if (ent[i] && ! ezxml_ent_ok(name, ent[i + 1], ent)) return 0;
286   }
287 }
288 
289 // called when the parser finds a processing instruction
ezxml_proc_inst(ezxml_root_t root,char * s,size_t len)290 void ezxml_proc_inst(ezxml_root_t root, char *s, size_t len)
291 {
292   int i = 0, j = 1;
293   char *target = s;
294 
295   s[len] = '\0'; // null terminate instruction
296   if (*(s += strcspn(s, EZXML_WS))) {
297     *s = '\0'; // null terminate target
298     s += strspn(s + 1, EZXML_WS) + 1; // skip whitespace after target
299   }
300 
301   if (! strcmp(target, "xml")) { // <?xml ... ?>
302     if ((s = strstr(s, "standalone")) && ! strncmp(s + strspn(s + 10,
303         EZXML_WS "='\"") + 10, "yes", 3)) root->standalone = 1;
304     return;
305   }
306 
307   if (! root->pi[0]) *(root->pi = malloc(sizeof(char **))) = NULL; //first pi
308 
309   while (root->pi[i] && strcmp(target, root->pi[i][0])) i++; // find target
310   if (! root->pi[i]) { // new target
311     root->pi = realloc(root->pi, sizeof(char **) * (i + 2));
312     root->pi[i] = malloc(sizeof(char *) * 3);
313     root->pi[i][0] = target;
314     root->pi[i][1] = (char *)(root->pi[i + 1] = NULL); // terminate pi list
315     root->pi[i][2] = strdup(""); // empty document position list
316   }
317 
318   while (root->pi[i][j]) j++; // find end of instruction list for this target
319   root->pi[i] = realloc(root->pi[i], sizeof(char *) * (j + 3));
320   root->pi[i][j + 2] = realloc(root->pi[i][j + 1], j + 1);
321   strcpy(root->pi[i][j + 2] + j - 1, (root->xml.name) ? ">" : "<");
322   root->pi[i][j + 1] = NULL; // null terminate pi list for this target
323   root->pi[i][j] = s; // set instruction
324 }
325 
326 // called when the parser finds an internal doctype subset
ezxml_internal_dtd(ezxml_root_t root,char * s,size_t len)327 short ezxml_internal_dtd(ezxml_root_t root, char *s, size_t len)
328 {
329   char q, *c, *t, *n = NULL, *v, **ent, **pe;
330   int i, j;
331 
332   pe = memcpy(malloc(sizeof(EZXML_NIL)), EZXML_NIL, sizeof(EZXML_NIL));
333 
334   for (s[len] = '\0'; s; ) {
335     while (*s && *s != '<' && *s != '%') s++; // find next declaration
336 
337     if (! *s) break;
338     else if (! strncmp(s, "<!ENTITY", 8)) { // parse entity definitions
339       c = s += strspn(s + 8, EZXML_WS) + 8; // skip white space separator
340       n = s + strspn(s, EZXML_WS "%"); // find name
341       *(s = n + strcspn(n, EZXML_WS)) = ';'; // append ; to name
342 
343       v = s + strspn(s + 1, EZXML_WS) + 1; // find value
344       if ((q = *(v++)) != '"' && q != '\'') { // skip externals
345         s = strchr(s, '>');
346         continue;
347       }
348 
349       for (i = 0, ent = (*c == '%') ? pe : root->ent; ent[i]; i++);
350       ent = realloc(ent, (i + 3) * sizeof(char *)); // space for next ent
351       if (*c == '%') pe = ent;
352       else root->ent = ent;
353 
354       *(++s) = '\0'; // null terminate name
355       if ((s = strchr(v, q))) *(s++) = '\0'; // null terminate value
356       ent[i + 1] = ezxml_decode(v, pe, '%'); // set value
357       ent[i + 2] = NULL; // null terminate entity list
358       if (! ezxml_ent_ok(n, ent[i + 1], ent)) { // circular reference
359         if (ent[i + 1] != v) free(ent[i + 1]);
360         ezxml_err(root, v, "circular entity declaration &%s", n);
361         break;
362       } else ent[i] = n; // set entity name
363     } else if (! strncmp(s, "<!ATTLIST", 9)) { // parse default attributes
364       t = s + strspn(s + 9, EZXML_WS) + 9; // skip whitespace separator
365       if (! *t) {
366         ezxml_err(root, t, "unclosed <!ATTLIST");
367         break;
368       }
369       if (*(s = t + strcspn(t, EZXML_WS ">")) == '>') continue;
370       else *s = '\0'; // null terminate tag name
371       for (i = 0; root->attr[i] && strcmp(n, root->attr[i][0]); i++);
372 
373       while (*(n = s + 1 + strspn(s + 1, EZXML_WS)) && *n != '>') {
374         if (*(s = n + strcspn(n, EZXML_WS))) *s = '\0'; // attr name
375         else {
376           ezxml_err(root, t, "malformed <!ATTLIST");
377           break;
378         }
379 
380         s += strspn(s + 1, EZXML_WS) + 1; // find next token
381         c = (strncmp(s, "CDATA", 5)) ? "*" : " "; // is it cdata?
382         if (! strncmp(s, "NOTATION", 8))
383           s += strspn(s + 8, EZXML_WS) + 8;
384         s = (*s == '(') ? strchr(s, ')') : s + strcspn(s, EZXML_WS);
385         if (! s) {
386           ezxml_err(root, t, "malformed <!ATTLIST");
387           break;
388         }
389 
390         s += strspn(s, EZXML_WS ")"); // skip white space separator
391         if (! strncmp(s, "#FIXED", 6))
392           s += strspn(s + 6, EZXML_WS) + 6;
393         if (*s == '#') { // no default value
394           s += strcspn(s, EZXML_WS ">") - 1;
395           if (*c == ' ') continue; // cdata is default, nothing to do
396           v = NULL;
397         } else if ((*s == '"' || *s == '\'')  && // default value
398                    (s = strchr(v = s + 1, *s))) *s = '\0';
399         else {
400           ezxml_err(root, t, "malformed <!ATTLIST");
401           break;
402         }
403 
404         if (! root->attr[i]) { // new tag name
405           root->attr = (! i) ? malloc(2 * sizeof(char **))
406                        : realloc(root->attr,
407                                  (i + 2) * sizeof(char **));
408           root->attr[i] = malloc(2 * sizeof(char *));
409           root->attr[i][0] = t; // set tag name
410           root->attr[i][1] = (char *)(root->attr[i + 1] = NULL);
411         }
412 
413         for (j = 1; root->attr[i][j]; j += 3); // find end of list
414         root->attr[i] = realloc(root->attr[i],
415                                 (j + 4) * sizeof(char *));
416 
417         root->attr[i][j + 3] = NULL; // null terminate list
418         root->attr[i][j + 2] = c; // is it cdata?
419         root->attr[i][j + 1] = (v) ? ezxml_decode(v, root->ent, *c)
420                                : NULL;
421         root->attr[i][j] = n; // attribute name
422       }
423     } else if (! strncmp(s, "<!--", 4)) s = strstr(s + 4, "-->"); // comments
424     else if (! strncmp(s, "<?", 2)) { // processing instructions
425       if ((s = strstr(c = s + 2, "?>")))
426         ezxml_proc_inst(root, c, s++ - c);
427     } else if (*s == '<') s = strchr(s, '>'); // skip other declarations
428     else if (*(s++) == '%' && ! root->standalone) break;
429   }
430 
431   free(pe);
432   return ! *root->err;
433 }
434 
435 // Converts a UTF-16 string to UTF-8. Returns a new string that must be freed
436 // or NULL if no conversion was needed.
ezxml_str2utf8(char ** s,size_t * len)437 char *ezxml_str2utf8(char **s, size_t *len)
438 {
439   char *u;
440   size_t l = 0, sl, max = *len;
441   long c, d;
442   int b, be = (**s == '\xFE') ? 1 : (**s == '\xFF') ? 0 : -1;
443 
444   if (be == -1) return NULL; // not UTF-16
445 
446   u = malloc(max);
447   for (sl = 2; sl < *len - 1; sl += 2) {
448     c = (be) ? (((*s)[sl] & 0xFF) << 8) | ((*s)[sl + 1] & 0xFF)  //UTF-16BE
449         : (((*s)[sl + 1] & 0xFF) << 8) | ((*s)[sl] & 0xFF); //UTF-16LE
450     if (c >= 0xD800 && c <= 0xDFFF && (sl += 2) < *len - 1) { // high-half
451       d = (be) ? (((*s)[sl] & 0xFF) << 8) | ((*s)[sl + 1] & 0xFF)
452           : (((*s)[sl + 1] & 0xFF) << 8) | ((*s)[sl] & 0xFF);
453       c = (((c & 0x3FF) << 10) | (d & 0x3FF)) + 0x10000;
454     }
455 
456     while (l + 6 > max) u = realloc(u, max += EZXML_BUFSIZE);
457     if (c < 0x80) u[l++] = c; // US-ASCII subset
458     else { // multi-byte UTF-8 sequence
459       for (b = 0, d = c; d; d /= 2) b++; // bits in c
460       b = (b - 2) / 5; // bytes in payload
461       u[l++] = (0xFF << (7 - b)) | (c >> (6 * b)); // head
462       while (b) u[l++] = 0x80 | ((c >> (6 * --b)) & 0x3F); // payload
463     }
464   }
465   return *s = realloc(u, *len = l);
466 }
467 
468 // frees a tag attribute list
ezxml_free_attr(char ** attr)469 void ezxml_free_attr(char **attr)
470 {
471   int i = 0;
472   char *m;
473 
474   if (! attr || attr == EZXML_NIL) return; // nothing to free
475   while (attr[i]) i += 2; // find end of attribute list
476   m = attr[i + 1]; // list of which names and values are malloced
477   for (i = 0; m[i]; i++) {
478     if (m[i] & EZXML_NAMEM) free(attr[i * 2]);
479     if (m[i] & EZXML_TXTM) free(attr[(i * 2) + 1]);
480   }
481   free(m);
482   free(attr);
483 }
484 
485 // parse the given xml string and return an ezxml structure
ezxml_parse_str(char * s,size_t len)486 ezxml_t ezxml_parse_str(char *s, size_t len)
487 {
488   ezxml_root_t root = (ezxml_root_t)ezxml_new(NULL);
489   char q, e, *d, **attr, **a = NULL; // initialize a to avoid compile warning
490   int l, i, j;
491 
492   root->m = s;
493   if (! len) return ezxml_err(root, NULL, "root tag missing");
494   root->u = ezxml_str2utf8(&s, &len); // convert utf-16 to utf-8
495   root->e = (root->s = s) + len; // record start and end of work area
496 
497   e = s[len - 1]; // save end char
498   s[len - 1] = '\0'; // turn end char into null terminator
499 
500   while (*s && *s != '<') s++; // find first tag
501   if (! *s) return ezxml_err(root, s, "root tag missing");
502 
503   for (; ; ) {
504     attr = (char **)EZXML_NIL;
505     d = ++s;
506 
507     if (isalpha(*s) || *s == '_' || *s == ':' || *s < '\0') { // new tag
508       if (! root->cur)
509         return ezxml_err(root, d, "markup outside of root element");
510 
511       s += strcspn(s, EZXML_WS "/>");
512       while (isspace(*s)) *(s++) = '\0'; // null terminate tag name
513 
514       if (*s && *s != '/' && *s != '>') // find tag in default attr list
515         for (i = 0; (a = root->attr[i]) && strcmp(a[0], d); i++);
516 
517       for (l = 0; *s && *s != '/' && *s != '>'; l += 2) { // new attrib
518         attr = (l) ? realloc(attr, (l + 4) * sizeof(char *))
519                : malloc(4 * sizeof(char *)); // allocate space
520         attr[l + 3] = (l) ? realloc(attr[l + 1], (l / 2) + 2)
521                       : malloc(2); // mem for list of maloced vals
522         strcpy(attr[l + 3] + (l / 2), " "); // value is not malloced
523         attr[l + 2] = NULL; // null terminate list
524         attr[l + 1] = ""; // temporary attribute value
525         attr[l] = s; // set attribute name
526 
527         s += strcspn(s, EZXML_WS "=/>");
528         if (*s == '=' || isspace(*s)) {
529           *(s++) = '\0'; // null terminate tag attribute name
530           q = *(s += strspn(s, EZXML_WS "="));
531           if (q == '"' || q == '\'') { // attribute value
532             attr[l + 1] = ++s;
533             while (*s && *s != q) s++;
534             if (*s) *(s++) = '\0'; // null terminate attribute val
535             else {
536               ezxml_free_attr(attr);
537               return ezxml_err(root, d, "missing %c", q);
538             }
539 
540             for (j = 1; a && a[j] && strcmp(a[j], attr[l]); j +=3);
541             attr[l + 1] = ezxml_decode(attr[l + 1], root->ent, (a
542                                        && a[j]) ? *a[j + 2] : ' ');
543             if (attr[l + 1] < d || attr[l + 1] > s)
544               attr[l + 3][l / 2] = EZXML_TXTM; // value malloced
545           }
546         }
547         while (isspace(*s)) s++;
548       }
549 
550       if (*s == '/') { // self closing tag
551         *(s++) = '\0';
552         if ((*s && *s != '>') || (! *s && e != '>')) {
553           if (l) ezxml_free_attr(attr);
554           return ezxml_err(root, d, "missing >");
555         }
556         ezxml_open_tag(root, d, attr);
557         ezxml_close_tag(root, d, s);
558       } else if ((q = *s) == '>' || (! *s && e == '>')) { // open tag
559         *s = '\0'; // temporarily null terminate tag name
560         ezxml_open_tag(root, d, attr);
561         *s = q;
562       } else {
563         if (l) ezxml_free_attr(attr);
564         return ezxml_err(root, d, "missing >");
565       }
566     } else if (*s == '/') { // close tag
567       s += strcspn(d = s + 1, EZXML_WS ">") + 1;
568       if (! (q = *s) && e != '>') return ezxml_err(root, d, "missing >");
569       *s = '\0'; // temporarily null terminate tag name
570       if (ezxml_close_tag(root, d, s)) return &root->xml;
571       if (isspace(*s = q)) s += strspn(s, EZXML_WS);
572     } else if (! strncmp(s, "!--", 3)) { // xml comment
573       if (! (s = strstr(s + 3, "--")) || (*(s += 2) != '>' && *s) ||
574           (! *s && e != '>')) return ezxml_err(root, d, "unclosed <!--");
575     } else if (! strncmp(s, "![CDATA[", 8)) { // cdata
576       if ((s = strstr(s, "]]>")))
577         ezxml_char_content(root, d + 8, (s += 2) - d - 10, 'c');
578       else return ezxml_err(root, d, "unclosed <![CDATA[");
579     } else if (! strncmp(s, "!DOCTYPE", 8)) { // dtd
580       for (l = 0; *s && ((! l && *s != '>') || (l && (*s != ']' ||
581                          *(s + strspn(s + 1, EZXML_WS) + 1) != '>')));
582            l = (*s == '[') ? 1 : l) s += strcspn(s + 1, "[]>") + 1;
583       if (! *s && e != '>')
584         return ezxml_err(root, d, "unclosed <!DOCTYPE");
585       d = (l) ? strchr(d, '[') + 1 : d;
586       if (l && ! ezxml_internal_dtd(root, d, s++ - d)) return &root->xml;
587     } else if (*s == '?') { // <?...?> processing instructions
588       do {
589         s = strchr(s, '?');
590       } while (s && *(++s) && *s != '>');
591       if (! s || (! *s && e != '>'))
592         return ezxml_err(root, d, "unclosed <?");
593       else ezxml_proc_inst(root, d + 1, s - d - 2);
594     } else return ezxml_err(root, d, "unexpected <");
595 
596     if (! s || ! *s) break;
597     *s = '\0';
598     d = ++s;
599     if (*s && *s != '<') { // tag character content
600       while (*s && *s != '<') s++;
601       if (*s) ezxml_char_content(root, d, s - d, '&');
602       else break;
603     } else if (! *s) break;
604   }
605 
606   if (! root->cur) return &root->xml;
607   else if (! root->cur->name) return ezxml_err(root, d, "root tag missing");
608   else return ezxml_err(root, d, "unclosed tag <%s>", root->cur->name);
609 }
610 
611 // Wrapper for ezxml_parse_str() that accepts a file stream. Reads the entire
612 // stream into memory and then parses it. For xml files, use ezxml_parse_file()
613 // or ezxml_parse_fd()
ezxml_parse_fp(FILE * fp)614 ezxml_t ezxml_parse_fp(FILE *fp)
615 {
616   ezxml_root_t root;
617   size_t l, len = 0;
618   char *s;
619 
620   if (! (s = malloc(EZXML_BUFSIZE))) return NULL;
621   do {
622     len += (l = fread((s + len), 1, EZXML_BUFSIZE, fp));
623     if (l == EZXML_BUFSIZE) s = realloc(s, len + EZXML_BUFSIZE);
624   } while (s && l == EZXML_BUFSIZE);
625 
626   if (! s) return NULL;
627   root = (ezxml_root_t)ezxml_parse_str(s, len);
628   root->len = -1; // so we know to free s in ezxml_free()
629   return &root->xml;
630 }
631 
632 // A wrapper for ezxml_parse_str() that accepts a file descriptor. First
633 // attempts to mem map the file. Failing that, reads the file into memory.
634 // Returns NULL on failure.
ezxml_parse_fd(int fd)635 ezxml_t ezxml_parse_fd(int fd)
636 {
637   ezxml_root_t root;
638   struct stat st;
639   size_t l;
640   void *m;
641 
642   if (fd < 0) return NULL;
643   fstat(fd, &st);
644 
645 #ifndef EZXML_NOMMAP
646   l = (st.st_size + sysconf(_SC_PAGESIZE) - 1) & ~(sysconf(_SC_PAGESIZE) -1);
647   if ((m = mmap(NULL, l, PROT_READ | PROT_WRITE, MAP_PRIVATE, fd, 0)) !=
648       MAP_FAILED) {
649     madvise(m, l, MADV_SEQUENTIAL); // optimize for sequential access
650     root = (ezxml_root_t)ezxml_parse_str(m, st.st_size);
651     madvise(m, root->len = l, MADV_NORMAL); // put it back to normal
652   } else { // mmap failed, read file into memory
653 #endif // EZXML_NOMMAP
654     l = read(fd, m = malloc(st.st_size), st.st_size);
655     root = (ezxml_root_t)ezxml_parse_str(m, l);
656     root->len = -1; // so we know to free s in ezxml_free()
657 #ifndef EZXML_NOMMAP
658   }
659 #endif // EZXML_NOMMAP
660   return &root->xml;
661 }
662 
663 // a wrapper for ezxml_parse_fd that accepts a file name
ezxml_parse_file(const char * file)664 ezxml_t ezxml_parse_file(const char *file)
665 {
666   int fd = open(file, O_RDONLY, 0);
667   ezxml_t xml = ezxml_parse_fd(fd);
668 
669   if (fd >= 0) close(fd);
670   return xml;
671 }
672 
673 // Encodes ampersand sequences appending the results to *dst, reallocating *dst
674 // if length excedes max. a is non-zero for attribute encoding. Returns *dst
ezxml_ampencode(const char * s,size_t len,char ** dst,size_t * dlen,size_t * max,short a)675 char *ezxml_ampencode(const char *s, size_t len, char **dst, size_t *dlen,
676                       size_t *max, short a)
677 {
678   const char *e;
679 
680   for (e = s + len; s != e; s++) {
681     while (*dlen + 10 > *max) *dst = realloc(*dst, *max += EZXML_BUFSIZE);
682 
683     switch (*s) {
684       case '\0':
685         return *dst;
686       case '&':
687         *dlen += sprintf(*dst + *dlen, "&amp;");
688         break;
689       case '<':
690         *dlen += sprintf(*dst + *dlen, "&lt;");
691         break;
692       case '>':
693         *dlen += sprintf(*dst + *dlen, "&gt;");
694         break;
695       case '"':
696         *dlen += sprintf(*dst + *dlen, (a) ? "&quot;" : "\"");
697         break;
698       case '\n':
699         *dlen += sprintf(*dst + *dlen, (a) ? "&#xA;" : "\n");
700         break;
701       case '\t':
702         *dlen += sprintf(*dst + *dlen, (a) ? "&#x9;" : "\t");
703         break;
704       case '\r':
705         *dlen += sprintf(*dst + *dlen, "&#xD;");
706         break;
707       default:
708         (*dst)[(*dlen)++] = *s;
709     }
710   }
711   return *dst;
712 }
713 
714 // Recursively converts each tag to xml appending it to *s. Reallocates *s if
715 // its length excedes max. start is the location of the previous tag in the
716 // parent tag's character content. Returns *s.
ezxml_toxml_r(ezxml_t xml,char ** s,size_t * len,size_t * max,size_t start,char *** attr)717 char *ezxml_toxml_r(ezxml_t xml, char **s, size_t *len, size_t *max,
718                     size_t start, char ***attr)
719 {
720   int i, j;
721   char *txt = (xml->parent) ? xml->parent->txt : "";
722   size_t off = 0;
723 
724   // parent character content up to this tag
725   *s = ezxml_ampencode(txt + start, xml->off - start, s, len, max, 0);
726 
727   while (*len + strlen(xml->name) + 4 > *max) // reallocate s
728     *s = realloc(*s, *max += EZXML_BUFSIZE);
729 
730   *len += sprintf(*s + *len, "<%s", xml->name); // open tag
731   for (i = 0; xml->attr[i]; i += 2) { // tag attributes
732     if (ezxml_attr(xml, xml->attr[i]) != xml->attr[i + 1]) continue;
733     while (*len + strlen(xml->attr[i]) + 7 > *max) // reallocate s
734       *s = realloc(*s, *max += EZXML_BUFSIZE);
735 
736     *len += sprintf(*s + *len, " %s=\"", xml->attr[i]);
737     ezxml_ampencode(xml->attr[i + 1], -1, s, len, max, 1);
738     *len += sprintf(*s + *len, "\"");
739   }
740 
741   for (i = 0; attr[i] && strcmp(attr[i][0], xml->name); i++);
742   for (j = 1; attr[i] && attr[i][j]; j += 3) { // default attributes
743     if (! attr[i][j + 1] || ezxml_attr(xml, attr[i][j]) != attr[i][j + 1])
744       continue; // skip duplicates and non-values
745     while (*len + strlen(attr[i][j]) + 7 > *max) // reallocate s
746       *s = realloc(*s, *max += EZXML_BUFSIZE);
747 
748     *len += sprintf(*s + *len, " %s=\"", attr[i][j]);
749     ezxml_ampencode(attr[i][j + 1], -1, s, len, max, 1);
750     *len += sprintf(*s + *len, "\"");
751   }
752   *len += sprintf(*s + *len, ">");
753 
754   *s = (xml->child) ? ezxml_toxml_r(xml->child, s, len, max, 0, attr) //child
755        : ezxml_ampencode(xml->txt, -1, s, len, max, 0);  //data
756 
757   while (*len + strlen(xml->name) + 4 > *max) // reallocate s
758     *s = realloc(*s, *max += EZXML_BUFSIZE);
759 
760   *len += sprintf(*s + *len, "</%s>", xml->name); // close tag
761 
762   while (txt[off] && off < xml->off) off++; // make sure off is within bounds
763   return (xml->ordered) ? ezxml_toxml_r(xml->ordered, s, len, max, off, attr)
764          : ezxml_ampencode(txt + off, -1, s, len, max, 0);
765 }
766 
767 // Converts an ezxml structure back to xml. Returns a string of xml data that
768 // must be freed.
ezxml_toxml(ezxml_t xml)769 char *ezxml_toxml(ezxml_t xml)
770 {
771   ezxml_t p = (xml) ? xml->parent : NULL, o = (xml) ? xml->ordered : NULL;
772   ezxml_root_t root = (ezxml_root_t)xml;
773   size_t len = 0, max = EZXML_BUFSIZE;
774   char *s = strcpy(malloc(max), ""), *t, *n;
775   int i, j, k;
776 
777   if (! xml || ! xml->name) return realloc(s, len + 1);
778   while (root->xml.parent) root = (ezxml_root_t)root->xml.parent; // root tag
779 
780   for (i = 0; ! p && root->pi[i]; i++) { // pre-root processing instructions
781     for (k = 2; root->pi[i][k - 1]; k++);
782     for (j = 1; (n = root->pi[i][j]); j++) {
783       if (root->pi[i][k][j - 1] == '>') continue; // not pre-root
784       while (len + strlen(t = root->pi[i][0]) + strlen(n) + 7 > max)
785         s = realloc(s, max += EZXML_BUFSIZE);
786       len += sprintf(s + len, "<?%s%s%s?>\n", t, *n ? " " : "", n);
787     }
788   }
789 
790   xml->parent = xml->ordered = NULL;
791   s = ezxml_toxml_r(xml, &s, &len, &max, 0, root->attr);
792   xml->parent = p;
793   xml->ordered = o;
794 
795   for (i = 0; ! p && root->pi[i]; i++) { // post-root processing instructions
796     for (k = 2; root->pi[i][k - 1]; k++);
797     for (j = 1; (n = root->pi[i][j]); j++) {
798       if (root->pi[i][k][j - 1] == '<') continue; // not post-root
799       while (len + strlen(t = root->pi[i][0]) + strlen(n) + 7 > max)
800         s = realloc(s, max += EZXML_BUFSIZE);
801       len += sprintf(s + len, "\n<?%s%s%s?>", t, *n ? " " : "", n);
802     }
803   }
804   return realloc(s, len + 1);
805 }
806 
807 // free the memory allocated for the ezxml structure
ezxml_free(ezxml_t xml)808 void ezxml_free(ezxml_t xml)
809 {
810   ezxml_root_t root = (ezxml_root_t)xml;
811   int i, j;
812   char **a, *s;
813 
814   if (! xml) return;
815   ezxml_free(xml->child);
816   ezxml_free(xml->ordered);
817 
818   if (! xml->parent) { // free root tag allocations
819     for (i = 10; root->ent[i]; i += 2) // 0 - 9 are default entites (<>&"')
820       if ((s = root->ent[i + 1]) < root->s || s > root->e) free(s);
821     free(root->ent); // free list of general entities
822 
823     for (i = 0; (a = root->attr[i]); i++) {
824       for (j = 1; a[j++]; j += 2) // free malloced attribute values
825         if (a[j] && (a[j] < root->s || a[j] > root->e)) free(a[j]);
826       free(a);
827     }
828     if (root->attr[0]) free(root->attr); // free default attribute list
829 
830     for (i = 0; root->pi[i]; i++) {
831       for (j = 1; root->pi[i][j]; j++);
832       free(root->pi[i][j + 1]);
833       free(root->pi[i]);
834     }
835     if (root->pi[0]) free(root->pi); // free processing instructions
836 
837     if (root->len == -1) free(root->m); // malloced xml data
838 #ifndef EZXML_NOMMAP
839     else if (root->len) munmap(root->m, root->len); // mem mapped xml data
840 #endif // EZXML_NOMMAP
841     if (root->u) free(root->u); // utf8 conversion
842   }
843 
844   ezxml_free_attr(xml->attr); // tag attributes
845   if ((xml->flags & EZXML_TXTM)) free(xml->txt); // character content
846   if ((xml->flags & EZXML_NAMEM)) free(xml->name); // tag name
847   free(xml);
848 }
849 
850 // return parser error message or empty string if none
ezxml_error(ezxml_t xml)851 const char *ezxml_error(ezxml_t xml)
852 {
853   while (xml && xml->parent) xml = xml->parent; // find root tag
854   return (xml) ? ((ezxml_root_t)xml)->err : "";
855 }
856 
857 // returns a new empty ezxml structure with the given root tag name
ezxml_new(const char * name)858 ezxml_t ezxml_new(const char *name)
859 {
860   static char *ent[] = { "lt;", "&#60;", "gt;", "&#62;", "quot;", "&#34;",
861                          "apos;", "&#39;", "amp;", "&#38;", NULL
862                        };
863   ezxml_root_t root = (ezxml_root_t)memset(malloc(sizeof(struct ezxml_root)),
864                       '\0', sizeof(struct ezxml_root));
865   root->xml.name = (char *)name;
866   root->cur = &root->xml;
867   strcpy(root->err, root->xml.txt = "");
868   root->ent = memcpy(malloc(sizeof(ent)), ent, sizeof(ent));
869   root->attr = root->pi = (char ***)(root->xml.attr = EZXML_NIL);
870   return &root->xml;
871 }
872 
873 // inserts an existing tag into an ezxml structure
ezxml_insert(ezxml_t xml,ezxml_t dest,size_t off)874 ezxml_t ezxml_insert(ezxml_t xml, ezxml_t dest, size_t off)
875 {
876   ezxml_t cur, prev, head;
877 
878   xml->next = xml->sibling = xml->ordered = NULL;
879   xml->off = off;
880   xml->parent = dest;
881 
882   if ((head = dest->child)) { // already have sub tags
883     if (head->off <= off) { // not first subtag
884       for (cur = head; cur->ordered && cur->ordered->off <= off;
885            cur = cur->ordered);
886       xml->ordered = cur->ordered;
887       cur->ordered = xml;
888     } else { // first subtag
889       xml->ordered = head;
890       dest->child = xml;
891     }
892 
893     for (cur = head, prev = NULL; cur && strcmp(cur->name, xml->name);
894          prev = cur, cur = cur->sibling); // find tag type
895     if (cur && cur->off <= off) { // not first of type
896       while (cur->next && cur->next->off <= off) cur = cur->next;
897       xml->next = cur->next;
898       cur->next = xml;
899     } else { // first tag of this type
900       if (prev && cur) prev->sibling = cur->sibling; // remove old first
901       xml->next = cur; // old first tag is now next
902       for (cur = head, prev = NULL; cur && cur->off <= off;
903            prev = cur, cur = cur->sibling); // new sibling insert point
904       xml->sibling = cur;
905       if (prev) prev->sibling = xml;
906     }
907   } else dest->child = xml; // only sub tag
908 
909   return xml;
910 }
911 
912 // Adds a child tag. off is the offset of the child tag relative to the start
913 // of the parent tag's character content. Returns the child tag.
ezxml_add_child(ezxml_t xml,const char * name,size_t off)914 ezxml_t ezxml_add_child(ezxml_t xml, const char *name, size_t off)
915 {
916   ezxml_t child;
917 
918   if (! xml) return NULL;
919   child = (ezxml_t)memset(malloc(sizeof(struct ezxml)), '\0',
920                           sizeof(struct ezxml));
921   child->name = (char *)name;
922   child->attr = EZXML_NIL;
923   child->txt = "";
924 
925   return ezxml_insert(child, xml, off);
926 }
927 
928 // sets the character content for the given tag and returns the tag
ezxml_set_txt(ezxml_t xml,const char * txt)929 ezxml_t ezxml_set_txt(ezxml_t xml, const char *txt)
930 {
931   if (! xml) return NULL;
932   if (xml->flags & EZXML_TXTM) free(xml->txt); // existing txt was malloced
933   xml->flags &= ~EZXML_TXTM;
934   xml->txt = (char *)txt;
935   return xml;
936 }
937 
938 // Sets the given tag attribute or adds a new attribute if not found. A value
939 // of NULL will remove the specified attribute. Returns the tag given.
ezxml_set_attr(ezxml_t xml,const char * name,const char * value)940 ezxml_t ezxml_set_attr(ezxml_t xml, const char *name, const char *value)
941 {
942   int l = 0, c;
943 
944   if (! xml) return NULL;
945   while (xml->attr[l] && strcmp(xml->attr[l], name)) l += 2;
946   if (! xml->attr[l]) { // not found, add as new attribute
947     if (! value) return xml; // nothing to do
948     if (xml->attr == EZXML_NIL) { // first attribute
949       xml->attr = malloc(4 * sizeof(char *));
950       xml->attr[1] = strdup(""); // empty list of malloced names/vals
951     } else xml->attr = realloc(xml->attr, (l + 4) * sizeof(char *));
952 
953     xml->attr[l] = (char *)name; // set attribute name
954     xml->attr[l + 2] = NULL; // null terminate attribute list
955     xml->attr[l + 3] = realloc(xml->attr[l + 1],
956                                (c = strlen(xml->attr[l + 1])) + 2);
957     strcpy(xml->attr[l + 3] + c, " "); // set name/value as not malloced
958     if (xml->flags & EZXML_DUP) xml->attr[l + 3][c] = EZXML_NAMEM;
959   } else if (xml->flags & EZXML_DUP) free((char *)name); // name was strduped
960 
961   for (c = l; xml->attr[c]; c += 2); // find end of attribute list
962   if (xml->attr[c + 1][l / 2] & EZXML_TXTM) free(xml->attr[l + 1]); //old val
963   if (xml->flags & EZXML_DUP) xml->attr[c + 1][l / 2] |= EZXML_TXTM;
964   else xml->attr[c + 1][l / 2] &= ~EZXML_TXTM;
965 
966   if (value) xml->attr[l + 1] = (char *)value; // set attribute value
967   else { // remove attribute
968     if (xml->attr[c + 1][l / 2] & EZXML_NAMEM) free(xml->attr[l]);
969     memmove(xml->attr + l, xml->attr + l + 2, (c - l + 2) * sizeof(char*));
970     xml->attr = realloc(xml->attr, (c + 2) * sizeof(char *));
971     memmove(xml->attr[c + 1] + (l / 2), xml->attr[c + 1] + (l / 2) + 1,
972             (c / 2) - (l / 2)); // fix list of which name/vals are malloced
973   }
974   xml->flags &= ~EZXML_DUP; // clear strdup() flag
975   return xml;
976 }
977 
978 // sets a flag for the given tag and returns the tag
ezxml_set_flag(ezxml_t xml,short flag)979 ezxml_t ezxml_set_flag(ezxml_t xml, short flag)
980 {
981   if (xml) xml->flags |= flag;
982   return xml;
983 }
984 
985 // removes a tag along with its subtags without freeing its memory
ezxml_cut(ezxml_t xml)986 ezxml_t ezxml_cut(ezxml_t xml)
987 {
988   ezxml_t cur;
989 
990   if (! xml) return NULL; // nothing to do
991   if (xml->next) xml->next->sibling = xml->sibling; // patch sibling list
992 
993   if (xml->parent) { // not root tag
994     cur = xml->parent->child; // find head of subtag list
995     if (cur == xml) xml->parent->child = xml->ordered; // first subtag
996     else { // not first subtag
997       while (cur->ordered != xml) cur = cur->ordered;
998       cur->ordered = cur->ordered->ordered; // patch ordered list
999 
1000       cur = xml->parent->child; // go back to head of subtag list
1001       if (strcmp(cur->name, xml->name)) { // not in first sibling list
1002         while (strcmp(cur->sibling->name, xml->name))
1003           cur = cur->sibling;
1004         if (cur->sibling == xml) { // first of a sibling list
1005           cur->sibling = (xml->next) ? xml->next
1006                          : cur->sibling->sibling;
1007         } else cur = cur->sibling; // not first of a sibling list
1008       }
1009 
1010       while (cur->next && cur->next != xml) cur = cur->next;
1011       if (cur->next) cur->next = cur->next->next; // patch next list
1012     }
1013   }
1014   xml->ordered = xml->sibling = xml->next = NULL;
1015   return xml;
1016 }
1017 
1018 #ifdef EZXML_TEST // test harness
main(int argc,char ** argv)1019 int main(int argc, char **argv)
1020 {
1021   ezxml_t xml;
1022   char *s;
1023   int i;
1024 
1025   if (argc != 2) return fprintf(stderr, "usage: %s xmlfile\n", argv[0]);
1026 
1027   xml = ezxml_parse_file(argv[1]);
1028   printf("%s\n", (s = ezxml_toxml(xml)));
1029   free(s);
1030   i = fprintf(stderr, "%s", ezxml_error(xml));
1031   ezxml_free(xml);
1032   return (i) ? 1 : 0;
1033 }
1034 #endif // EZXML_TEST
1035