ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/radiance/ray/src/common/ezxml.c
Revision: 2.4
Committed: Sat Jun 11 01:04:08 2011 UTC (12 years, 10 months ago) by greg
Content type: text/plain
Branch: MAIN
CVS Tags: rad4R1
Changes since 2.3: +2 -3 lines
Log Message:
Removed problematic reference to snprintf()

File Contents

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