ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/radiance/ray/src/common/ezxml.c
Revision: 2.1
Committed: Wed Jun 17 20:41:47 2009 UTC (14 years, 10 months ago) by greg
Content type: text/plain
Branch: MAIN
CVS Tags: rad4R0
Log Message:
Created dctimestep utility for daylight coefficient calculations

File Contents

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