ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/radiance/ray/src/common/ezxml.c
Revision: 2.6
Committed: Sun Oct 26 17:35:53 2014 UTC (9 years, 5 months ago) by greg
Content type: text/plain
Branch: MAIN
CVS Tags: rad4R2P2
Changes since 2.5: +4 -3 lines
Log Message:
Fixing minor compiler warnings

File Contents

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