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