ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/radiance/ray/src/common/ezxml.c
Revision: 2.9
Committed: Sun Mar 6 01:13:17 2016 UTC (8 years, 1 month ago) by schorsch
Content type: text/plain
Branch: MAIN
CVS Tags: rad5R4, rad5R2, rad5R1, rad5R3, HEAD
Changes since 2.8: +6 -7 lines
Log Message:
Prepare for SCons build on Win32 and Win64

File Contents

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