ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/radiance/ray/src/common/ezxml.c
Revision: 2.8
Committed: Thu Apr 2 16:40:32 2015 UTC (9 years, 2 months ago) by greg
Content type: text/plain
Branch: MAIN
CVS Tags: rad5R0
Changes since 2.7: +9 -1 lines
Log Message:
Support for color BSDF rendering using Klems representation

File Contents

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