ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/radiance/ray/src/gen/ezxml.c
Revision: 2.2
Committed: Wed Dec 12 05:09:58 2007 UTC (17 years, 5 months ago) by greg
Content type: text/plain
Branch: MAIN
Changes since 2.1: +2 -3 lines
Log Message:
Initial implementation of BSDF complete (untested)

File Contents

# User Rev Content
1 greg 2.1 #ifndef lint
2 greg 2.2 static const char RCSid[] = "$Id: ezxml.c,v 2.1 2007/09/21 05:53:21 greg Exp $";
3 greg 2.1 #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 <unistd.h>
34     #include <sys/types.h>
35     #ifndef EZXML_NOMMAP
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 greg 2.2 if ((m = mmap(NULL, l, PROT_READ, MAP_PRIVATE, fd, 0)) != MAP_FAILED) {
642 greg 2.1 madvise(m, l, MADV_SEQUENTIAL); // optimize for sequential access
643     root = (ezxml_root_t)ezxml_parse_str(m, st.st_size);
644     madvise(m, root->len = l, MADV_NORMAL); // put it back to normal
645     }
646     else { // mmap failed, read file into memory
647     #endif // EZXML_NOMMAP
648     l = read(fd, m = malloc(st.st_size), st.st_size);
649     root = (ezxml_root_t)ezxml_parse_str(m, l);
650     root->len = -1; // so we know to free s in ezxml_free()
651     #ifndef EZXML_NOMMAP
652     }
653     #endif // EZXML_NOMMAP
654     return &root->xml;
655     }
656    
657     // a wrapper for ezxml_parse_fd that accepts a file name
658     ezxml_t ezxml_parse_file(const char *file)
659     {
660     int fd = open(file, O_RDONLY, 0);
661     ezxml_t xml = ezxml_parse_fd(fd);
662    
663     if (fd >= 0) close(fd);
664     return xml;
665     }
666    
667     // Encodes ampersand sequences appending the results to *dst, reallocating *dst
668     // if length excedes max. a is non-zero for attribute encoding. Returns *dst
669     char *ezxml_ampencode(const char *s, size_t len, char **dst, size_t *dlen,
670     size_t *max, short a)
671     {
672     const char *e;
673    
674     for (e = s + len; s != e; s++) {
675     while (*dlen + 10 > *max) *dst = realloc(*dst, *max += EZXML_BUFSIZE);
676    
677     switch (*s) {
678     case '\0': return *dst;
679     case '&': *dlen += sprintf(*dst + *dlen, "&amp;"); break;
680     case '<': *dlen += sprintf(*dst + *dlen, "&lt;"); break;
681     case '>': *dlen += sprintf(*dst + *dlen, "&gt;"); break;
682     case '"': *dlen += sprintf(*dst + *dlen, (a) ? "&quot;" : "\""); break;
683     case '\n': *dlen += sprintf(*dst + *dlen, (a) ? "&#xA;" : "\n"); break;
684     case '\t': *dlen += sprintf(*dst + *dlen, (a) ? "&#x9;" : "\t"); break;
685     case '\r': *dlen += sprintf(*dst + *dlen, "&#xD;"); break;
686     default: (*dst)[(*dlen)++] = *s;
687     }
688     }
689     return *dst;
690     }
691    
692     // Recursively converts each tag to xml appending it to *s. Reallocates *s if
693     // its length excedes max. start is the location of the previous tag in the
694     // parent tag's character content. Returns *s.
695     char *ezxml_toxml_r(ezxml_t xml, char **s, size_t *len, size_t *max,
696     size_t start, char ***attr)
697     {
698     int i, j;
699     char *txt = (xml->parent) ? xml->parent->txt : "";
700     size_t off = 0;
701    
702     // parent character content up to this tag
703     *s = ezxml_ampencode(txt + start, xml->off - start, s, len, max, 0);
704    
705     while (*len + strlen(xml->name) + 4 > *max) // reallocate s
706     *s = realloc(*s, *max += EZXML_BUFSIZE);
707    
708     *len += sprintf(*s + *len, "<%s", xml->name); // open tag
709     for (i = 0; xml->attr[i]; i += 2) { // tag attributes
710     if (ezxml_attr(xml, xml->attr[i]) != xml->attr[i + 1]) continue;
711     while (*len + strlen(xml->attr[i]) + 7 > *max) // reallocate s
712     *s = realloc(*s, *max += EZXML_BUFSIZE);
713    
714     *len += sprintf(*s + *len, " %s=\"", xml->attr[i]);
715     ezxml_ampencode(xml->attr[i + 1], -1, s, len, max, 1);
716     *len += sprintf(*s + *len, "\"");
717     }
718    
719     for (i = 0; attr[i] && strcmp(attr[i][0], xml->name); i++);
720     for (j = 1; attr[i] && attr[i][j]; j += 3) { // default attributes
721     if (! attr[i][j + 1] || ezxml_attr(xml, attr[i][j]) != attr[i][j + 1])
722     continue; // skip duplicates and non-values
723     while (*len + strlen(attr[i][j]) + 7 > *max) // reallocate s
724     *s = realloc(*s, *max += EZXML_BUFSIZE);
725    
726     *len += sprintf(*s + *len, " %s=\"", attr[i][j]);
727     ezxml_ampencode(attr[i][j + 1], -1, s, len, max, 1);
728     *len += sprintf(*s + *len, "\"");
729     }
730     *len += sprintf(*s + *len, ">");
731    
732     *s = (xml->child) ? ezxml_toxml_r(xml->child, s, len, max, 0, attr) //child
733     : ezxml_ampencode(xml->txt, -1, s, len, max, 0); //data
734    
735     while (*len + strlen(xml->name) + 4 > *max) // reallocate s
736     *s = realloc(*s, *max += EZXML_BUFSIZE);
737    
738     *len += sprintf(*s + *len, "</%s>", xml->name); // close tag
739    
740     while (txt[off] && off < xml->off) off++; // make sure off is within bounds
741     return (xml->ordered) ? ezxml_toxml_r(xml->ordered, s, len, max, off, attr)
742     : ezxml_ampencode(txt + off, -1, s, len, max, 0);
743     }
744    
745     // Converts an ezxml structure back to xml. Returns a string of xml data that
746     // must be freed.
747     char *ezxml_toxml(ezxml_t xml)
748     {
749     ezxml_t p = (xml) ? xml->parent : NULL, o = (xml) ? xml->ordered : NULL;
750     ezxml_root_t root = (ezxml_root_t)xml;
751     size_t len = 0, max = EZXML_BUFSIZE;
752     char *s = strcpy(malloc(max), ""), *t, *n;
753     int i, j, k;
754    
755     if (! xml || ! xml->name) return realloc(s, len + 1);
756     while (root->xml.parent) root = (ezxml_root_t)root->xml.parent; // root tag
757    
758     for (i = 0; ! p && root->pi[i]; i++) { // pre-root processing instructions
759     for (k = 2; root->pi[i][k - 1]; k++);
760     for (j = 1; (n = root->pi[i][j]); j++) {
761     if (root->pi[i][k][j - 1] == '>') continue; // not pre-root
762     while (len + strlen(t = root->pi[i][0]) + strlen(n) + 7 > max)
763     s = realloc(s, max += EZXML_BUFSIZE);
764     len += sprintf(s + len, "<?%s%s%s?>\n", t, *n ? " " : "", n);
765     }
766     }
767    
768     xml->parent = xml->ordered = NULL;
769     s = ezxml_toxml_r(xml, &s, &len, &max, 0, root->attr);
770     xml->parent = p;
771     xml->ordered = o;
772    
773     for (i = 0; ! p && root->pi[i]; i++) { // post-root processing instructions
774     for (k = 2; root->pi[i][k - 1]; k++);
775     for (j = 1; (n = root->pi[i][j]); j++) {
776     if (root->pi[i][k][j - 1] == '<') continue; // not post-root
777     while (len + strlen(t = root->pi[i][0]) + strlen(n) + 7 > max)
778     s = realloc(s, max += EZXML_BUFSIZE);
779     len += sprintf(s + len, "\n<?%s%s%s?>", t, *n ? " " : "", n);
780     }
781     }
782     return realloc(s, len + 1);
783     }
784    
785     // free the memory allocated for the ezxml structure
786     void ezxml_free(ezxml_t xml)
787     {
788     ezxml_root_t root = (ezxml_root_t)xml;
789     int i, j;
790     char **a, *s;
791    
792     if (! xml) return;
793     ezxml_free(xml->child);
794     ezxml_free(xml->ordered);
795    
796     if (! xml->parent) { // free root tag allocations
797     for (i = 10; root->ent[i]; i += 2) // 0 - 9 are default entites (<>&"')
798     if ((s = root->ent[i + 1]) < root->s || s > root->e) free(s);
799     free(root->ent); // free list of general entities
800    
801     for (i = 0; (a = root->attr[i]); i++) {
802     for (j = 1; a[j++]; j += 2) // free malloced attribute values
803     if (a[j] && (a[j] < root->s || a[j] > root->e)) free(a[j]);
804     free(a);
805     }
806     if (root->attr[0]) free(root->attr); // free default attribute list
807    
808     for (i = 0; root->pi[i]; i++) {
809     for (j = 1; root->pi[i][j]; j++);
810     free(root->pi[i][j + 1]);
811     free(root->pi[i]);
812     }
813     if (root->pi[0]) free(root->pi); // free processing instructions
814    
815     if (root->len == -1) free(root->m); // malloced xml data
816     #ifndef EZXML_NOMMAP
817     else if (root->len) munmap(root->m, root->len); // mem mapped xml data
818     #endif // EZXML_NOMMAP
819     if (root->u) free(root->u); // utf8 conversion
820     }
821    
822     ezxml_free_attr(xml->attr); // tag attributes
823     if ((xml->flags & EZXML_TXTM)) free(xml->txt); // character content
824     if ((xml->flags & EZXML_NAMEM)) free(xml->name); // tag name
825     free(xml);
826     }
827    
828     // return parser error message or empty string if none
829     const char *ezxml_error(ezxml_t xml)
830     {
831     while (xml && xml->parent) xml = xml->parent; // find root tag
832     return (xml) ? ((ezxml_root_t)xml)->err : "";
833     }
834    
835     // returns a new empty ezxml structure with the given root tag name
836     ezxml_t ezxml_new(const char *name)
837     {
838     static char *ent[] = { "lt;", "&#60;", "gt;", "&#62;", "quot;", "&#34;",
839     "apos;", "&#39;", "amp;", "&#38;", NULL };
840     ezxml_root_t root = (ezxml_root_t)memset(malloc(sizeof(struct ezxml_root)),
841     '\0', sizeof(struct ezxml_root));
842     root->xml.name = (char *)name;
843     root->cur = &root->xml;
844     strcpy(root->err, root->xml.txt = "");
845     root->ent = memcpy(malloc(sizeof(ent)), ent, sizeof(ent));
846     root->attr = root->pi = (char ***)(root->xml.attr = EZXML_NIL);
847     return &root->xml;
848     }
849    
850     // inserts an existing tag into an ezxml structure
851     ezxml_t ezxml_insert(ezxml_t xml, ezxml_t dest, size_t off)
852     {
853     ezxml_t cur, prev, head;
854    
855     xml->next = xml->sibling = xml->ordered = NULL;
856     xml->off = off;
857     xml->parent = dest;
858    
859     if ((head = dest->child)) { // already have sub tags
860     if (head->off <= off) { // not first subtag
861     for (cur = head; cur->ordered && cur->ordered->off <= off;
862     cur = cur->ordered);
863     xml->ordered = cur->ordered;
864     cur->ordered = xml;
865     }
866     else { // first subtag
867     xml->ordered = head;
868     dest->child = xml;
869     }
870    
871     for (cur = head, prev = NULL; cur && strcmp(cur->name, xml->name);
872     prev = cur, cur = cur->sibling); // find tag type
873     if (cur && cur->off <= off) { // not first of type
874     while (cur->next && cur->next->off <= off) cur = cur->next;
875     xml->next = cur->next;
876     cur->next = xml;
877     }
878     else { // first tag of this type
879     if (prev && cur) prev->sibling = cur->sibling; // remove old first
880     xml->next = cur; // old first tag is now next
881     for (cur = head, prev = NULL; cur && cur->off <= off;
882     prev = cur, cur = cur->sibling); // new sibling insert point
883     xml->sibling = cur;
884     if (prev) prev->sibling = xml;
885     }
886     }
887     else dest->child = xml; // only sub tag
888    
889     return xml;
890     }
891    
892     // Adds a child tag. off is the offset of the child tag relative to the start
893     // of the parent tag's character content. Returns the child tag.
894     ezxml_t ezxml_add_child(ezxml_t xml, const char *name, size_t off)
895     {
896     ezxml_t child;
897    
898     if (! xml) return NULL;
899     child = (ezxml_t)memset(malloc(sizeof(struct ezxml)), '\0',
900     sizeof(struct ezxml));
901     child->name = (char *)name;
902     child->attr = EZXML_NIL;
903     child->txt = "";
904    
905     return ezxml_insert(child, xml, off);
906     }
907    
908     // sets the character content for the given tag and returns the tag
909     ezxml_t ezxml_set_txt(ezxml_t xml, const char *txt)
910     {
911     if (! xml) return NULL;
912     if (xml->flags & EZXML_TXTM) free(xml->txt); // existing txt was malloced
913     xml->flags &= ~EZXML_TXTM;
914     xml->txt = (char *)txt;
915     return xml;
916     }
917    
918     // Sets the given tag attribute or adds a new attribute if not found. A value
919     // of NULL will remove the specified attribute. Returns the tag given.
920     ezxml_t ezxml_set_attr(ezxml_t xml, const char *name, const char *value)
921     {
922     int l = 0, c;
923    
924     if (! xml) return NULL;
925     while (xml->attr[l] && strcmp(xml->attr[l], name)) l += 2;
926     if (! xml->attr[l]) { // not found, add as new attribute
927     if (! value) return xml; // nothing to do
928     if (xml->attr == EZXML_NIL) { // first attribute
929     xml->attr = malloc(4 * sizeof(char *));
930     xml->attr[1] = strdup(""); // empty list of malloced names/vals
931     }
932     else xml->attr = realloc(xml->attr, (l + 4) * sizeof(char *));
933    
934     xml->attr[l] = (char *)name; // set attribute name
935     xml->attr[l + 2] = NULL; // null terminate attribute list
936     xml->attr[l + 3] = realloc(xml->attr[l + 1],
937     (c = strlen(xml->attr[l + 1])) + 2);
938     strcpy(xml->attr[l + 3] + c, " "); // set name/value as not malloced
939     if (xml->flags & EZXML_DUP) xml->attr[l + 3][c] = EZXML_NAMEM;
940     }
941     else if (xml->flags & EZXML_DUP) free((char *)name); // name was strduped
942    
943     for (c = l; xml->attr[c]; c += 2); // find end of attribute list
944     if (xml->attr[c + 1][l / 2] & EZXML_TXTM) free(xml->attr[l + 1]); //old val
945     if (xml->flags & EZXML_DUP) xml->attr[c + 1][l / 2] |= EZXML_TXTM;
946     else xml->attr[c + 1][l / 2] &= ~EZXML_TXTM;
947    
948     if (value) xml->attr[l + 1] = (char *)value; // set attribute value
949     else { // remove attribute
950     if (xml->attr[c + 1][l / 2] & EZXML_NAMEM) free(xml->attr[l]);
951     memmove(xml->attr + l, xml->attr + l + 2, (c - l + 2) * sizeof(char*));
952     xml->attr = realloc(xml->attr, (c + 2) * sizeof(char *));
953     memmove(xml->attr[c + 1] + (l / 2), xml->attr[c + 1] + (l / 2) + 1,
954     (c / 2) - (l / 2)); // fix list of which name/vals are malloced
955     }
956     xml->flags &= ~EZXML_DUP; // clear strdup() flag
957     return xml;
958     }
959    
960     // sets a flag for the given tag and returns the tag
961     ezxml_t ezxml_set_flag(ezxml_t xml, short flag)
962     {
963     if (xml) xml->flags |= flag;
964     return xml;
965     }
966    
967     // removes a tag along with its subtags without freeing its memory
968     ezxml_t ezxml_cut(ezxml_t xml)
969     {
970     ezxml_t cur;
971    
972     if (! xml) return NULL; // nothing to do
973     if (xml->next) xml->next->sibling = xml->sibling; // patch sibling list
974    
975     if (xml->parent) { // not root tag
976     cur = xml->parent->child; // find head of subtag list
977     if (cur == xml) xml->parent->child = xml->ordered; // first subtag
978     else { // not first subtag
979     while (cur->ordered != xml) cur = cur->ordered;
980     cur->ordered = cur->ordered->ordered; // patch ordered list
981    
982     cur = xml->parent->child; // go back to head of subtag list
983     if (strcmp(cur->name, xml->name)) { // not in first sibling list
984     while (strcmp(cur->sibling->name, xml->name))
985     cur = cur->sibling;
986     if (cur->sibling == xml) { // first of a sibling list
987     cur->sibling = (xml->next) ? xml->next
988     : cur->sibling->sibling;
989     }
990     else cur = cur->sibling; // not first of a sibling list
991     }
992    
993     while (cur->next && cur->next != xml) cur = cur->next;
994     if (cur->next) cur->next = cur->next->next; // patch next list
995     }
996     }
997     xml->ordered = xml->sibling = xml->next = NULL;
998     return xml;
999     }
1000    
1001     #ifdef EZXML_TEST // test harness
1002     int main(int argc, char **argv)
1003     {
1004     ezxml_t xml;
1005     char *s;
1006     int i;
1007    
1008     if (argc != 2) return fprintf(stderr, "usage: %s xmlfile\n", argv[0]);
1009    
1010     xml = ezxml_parse_file(argv[1]);
1011     printf("%s\n", (s = ezxml_toxml(xml)));
1012     free(s);
1013     i = fprintf(stderr, "%s", ezxml_error(xml));
1014     ezxml_free(xml);
1015     return (i) ? 1 : 0;
1016     }
1017     #endif // EZXML_TEST