~ubuntu-branches/ubuntu/wily/pianobar/wily-proposed

« back to all changes in this revision

Viewing changes to libezxml/src/ezxml.c

  • Committer: Bazaar Package Importer
  • Author(s): Luke Faraone
  • Date: 2011-02-08 17:23:25 UTC
  • mfrom: (1.3.3 upstream)
  • Revision ID: james.westby@ubuntu.com-20110208172325-0qf3sxpsu37j5ez9
Tags: 2011.01.24-1
* New upstream version. 
* Switch to DEP5 copyright.
* Augment CFLAGS to use the c99 standard.
* Don't install the now-removed AUTHORS file into docs.
* Drop dep on cmake.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
/* ezxml.c
2
 
 *
3
 
 * Copyright 2004-2006 Aaron Voisine <aaron@voisine.org>
4
 
 *
5
 
 * Permission is hereby granted, free of charge, to any person obtaining
6
 
 * a copy of this software and associated documentation files (the
7
 
 * "Software"), to deal in the Software without restriction, including
8
 
 * without limitation the rights to use, copy, modify, merge, publish,
9
 
 * distribute, sublicense, and/or sell copies of the Software, and to
10
 
 * permit persons to whom the Software is furnished to do so, subject to
11
 
 * the following conditions:
12
 
 *
13
 
 * The above copyright notice and this permission notice shall be included
14
 
 * in all copies or substantial portions of the Software.
15
 
 *
16
 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17
 
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18
 
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
19
 
 * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
20
 
 * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
21
 
 * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
22
 
 * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
23
 
 */
24
 
 
25
 
#define _BSD_SOURCE /* required by strdup() */
26
 
 
27
 
#include <stdlib.h>
28
 
#include <stdio.h>
29
 
#include <stdarg.h>
30
 
#include <string.h>
31
 
#include <ctype.h>
32
 
#include <unistd.h>
33
 
#include <sys/types.h>
34
 
#include <sys/stat.h>
35
 
#include "ezxml.h"
36
 
 
37
 
#define EZXML_WS   "\t\r\n "  // whitespace
38
 
#define EZXML_ERRL 128        // maximum error string length
39
 
 
40
 
typedef struct ezxml_root *ezxml_root_t;
41
 
struct ezxml_root {       // additional data for the root tag
42
 
    struct ezxml xml;     // is a super-struct built on top of ezxml struct
43
 
    ezxml_t cur;          // current xml tree insertion point
44
 
    char *m;              // original xml string
45
 
    size_t len;           // length of allocated memory for mmap, -1 for malloc
46
 
    char *u;              // UTF-8 conversion of string if original was UTF-16
47
 
    char *s;              // start of work area
48
 
    char *e;              // end of work area
49
 
    char **ent;           // general entities (ampersand sequences)
50
 
    char ***attr;         // default attributes
51
 
    char ***pi;           // processing instructions
52
 
    short standalone;     // non-zero if <?xml standalone="yes"?>
53
 
    char err[EZXML_ERRL]; // error string
54
 
};
55
 
 
56
 
char *EZXML_NIL[] = { NULL }; // empty, null terminated array of strings
57
 
 
58
 
// sets a flag for the given tag and returns the tag
59
 
static ezxml_t ezxml_set_flag(ezxml_t xml, short flag) {
60
 
    if (xml) xml->flags |= flag;
61
 
    return xml;
62
 
}
63
 
 
64
 
// inserts an existing tag into an ezxml structure
65
 
static ezxml_t ezxml_insert(ezxml_t xml, ezxml_t dest, size_t off)
66
 
{
67
 
    ezxml_t cur, prev, head;
68
 
 
69
 
    xml->next = xml->sibling = xml->ordered = NULL;
70
 
    xml->off = off;
71
 
    xml->parent = dest;
72
 
 
73
 
    if ((head = dest->child)) { // already have sub tags
74
 
        if (head->off <= off) { // not first subtag
75
 
            for (cur = head; cur->ordered && cur->ordered->off <= off;
76
 
                 cur = cur->ordered);
77
 
            xml->ordered = cur->ordered;
78
 
            cur->ordered = xml;
79
 
        }
80
 
        else { // first subtag
81
 
            xml->ordered = head;
82
 
            dest->child = xml;
83
 
        }
84
 
 
85
 
        for (cur = head, prev = NULL; cur && strcmp(cur->name, xml->name);
86
 
             prev = cur, cur = cur->sibling); // find tag type
87
 
        if (cur && cur->off <= off) { // not first of type
88
 
            while (cur->next && cur->next->off <= off) cur = cur->next;
89
 
            xml->next = cur->next;
90
 
            cur->next = xml;
91
 
        }
92
 
        else { // first tag of this type
93
 
            if (prev && cur) prev->sibling = cur->sibling; // remove old first
94
 
            xml->next = cur; // old first tag is now next
95
 
            for (cur = head, prev = NULL; cur && cur->off <= off;
96
 
                 prev = cur, cur = cur->sibling); // new sibling insert point
97
 
            xml->sibling = cur;
98
 
            if (prev) prev->sibling = xml;
99
 
        }
100
 
    }
101
 
    else dest->child = xml; // only sub tag
102
 
 
103
 
    return xml;
104
 
}
105
 
 
106
 
// Adds a child tag. off is the offset of the child tag relative to the start
107
 
// of the parent tag's character content. Returns the child tag.
108
 
static ezxml_t ezxml_add_child(ezxml_t xml, const char *name, size_t off)
109
 
{
110
 
    ezxml_t child;
111
 
 
112
 
    if (! xml) return NULL;
113
 
    child = (ezxml_t)memset(malloc(sizeof(struct ezxml)), '\0',
114
 
                            sizeof(struct ezxml));
115
 
    child->name = (char *)name;
116
 
    child->attr = EZXML_NIL;
117
 
    child->txt = "";
118
 
 
119
 
    return ezxml_insert(child, xml, off);
120
 
}
121
 
 
122
 
// returns the first child tag with the given name or NULL if not found
123
 
ezxml_t ezxml_child(ezxml_t xml, const char *name)
124
 
{
125
 
    xml = (xml) ? xml->child : NULL;
126
 
    while (xml && strcmp(name, xml->name)) xml = xml->sibling;
127
 
    return xml;
128
 
}
129
 
 
130
 
// returns a new empty ezxml structure with the given root tag name
131
 
static ezxml_t ezxml_new(const char *name)
132
 
{
133
 
    static char *ent[] = { "lt;", "&#60;", "gt;", "&#62;", "quot;", "&#34;",
134
 
                           "apos;", "&#39;", "amp;", "&#38;", NULL };
135
 
    ezxml_root_t root = (ezxml_root_t)memset(malloc(sizeof(struct ezxml_root)), 
136
 
                                             '\0', sizeof(struct ezxml_root));
137
 
    root->xml.name = (char *)name;
138
 
    root->cur = &root->xml;
139
 
    strcpy(root->err, root->xml.txt = "");
140
 
    root->ent = memcpy(malloc(sizeof(ent)), ent, sizeof(ent));
141
 
    root->attr = root->pi = (char ***)(root->xml.attr = EZXML_NIL);
142
 
    return &root->xml;
143
 
}
144
 
 
145
 
// returns the Nth tag with the same name in the same subsection or NULL if not
146
 
// found
147
 
ezxml_t ezxml_idx(ezxml_t xml, int idx)
148
 
{
149
 
    for (; xml && idx; idx--) xml = xml->next;
150
 
    return xml;
151
 
}
152
 
 
153
 
// returns the value of the requested tag attribute or NULL if not found
154
 
const char *ezxml_attr(ezxml_t xml, const char *attr)
155
 
{
156
 
    int i = 0, j = 1;
157
 
    ezxml_root_t root = (ezxml_root_t)xml;
158
 
 
159
 
    if (! xml || ! xml->attr) return NULL;
160
 
    while (xml->attr[i] && strcmp(attr, xml->attr[i])) i += 2;
161
 
    if (xml->attr[i]) return xml->attr[i + 1]; // found attribute
162
 
 
163
 
    while (root->xml.parent) root = (ezxml_root_t)root->xml.parent; // root tag
164
 
    for (i = 0; root->attr[i] && strcmp(xml->name, root->attr[i][0]); i++);
165
 
    if (! root->attr[i]) return NULL; // no matching default attributes
166
 
    while (root->attr[i][j] && strcmp(attr, root->attr[i][j])) j += 3;
167
 
    return (root->attr[i][j]) ? root->attr[i][j + 1] : NULL; // found default
168
 
}
169
 
 
170
 
// same as ezxml_get but takes an already initialized va_list
171
 
static ezxml_t ezxml_vget(ezxml_t xml, va_list ap)
172
 
{
173
 
    char *name = va_arg(ap, char *);
174
 
    int idx = -1;
175
 
 
176
 
    if (name && *name) {
177
 
        idx = va_arg(ap, int);    
178
 
        xml = ezxml_child(xml, name);
179
 
    }
180
 
    return (idx < 0) ? xml : ezxml_vget(ezxml_idx(xml, idx), ap);
181
 
}
182
 
 
183
 
// Traverses the xml tree to retrieve a specific subtag. Takes a variable
184
 
// length list of tag names and indexes. The argument list must be terminated
185
 
// by either an index of -1 or an empty string tag name. Example: 
186
 
// title = ezxml_get(library, "shelf", 0, "book", 2, "title", -1);
187
 
// This retrieves the title of the 3rd book on the 1st shelf of library.
188
 
// Returns NULL if not found.
189
 
ezxml_t ezxml_get(ezxml_t xml, ...)
190
 
{
191
 
    va_list ap;
192
 
    ezxml_t r;
193
 
 
194
 
    va_start(ap, xml);
195
 
    r = ezxml_vget(xml, ap);
196
 
    va_end(ap);
197
 
    return r;
198
 
}
199
 
 
200
 
// set an error string and return root
201
 
static ezxml_t ezxml_err(ezxml_root_t root, char *s, const char *err, ...)
202
 
{
203
 
    va_list ap;
204
 
    int line = 1;
205
 
    char *t, fmt[EZXML_ERRL];
206
 
    
207
 
    for (t = root->s; t < s; t++) if (*t == '\n') line++;
208
 
    snprintf(fmt, EZXML_ERRL, "[error near line %d]: %s", line, err);
209
 
 
210
 
    va_start(ap, err);
211
 
    vsnprintf(root->err, EZXML_ERRL, fmt, ap);
212
 
    va_end(ap);
213
 
 
214
 
    return &root->xml;
215
 
}
216
 
 
217
 
// Recursively decodes entity and character references and normalizes new lines
218
 
// ent is a null terminated array of alternating entity names and values. set t
219
 
// to '&' for general entity decoding, '%' for parameter entity decoding, 'c'
220
 
// for cdata sections, ' ' for attribute normalization, or '*' for non-cdata
221
 
// attribute normalization. Returns s, or if the decoded string is longer than
222
 
// s, returns a malloced string that must be freed.
223
 
static char *ezxml_decode(char *s, char **ent, char t)
224
 
{
225
 
    char *e, *r = s, *m = s;
226
 
    long b, c, d, l;
227
 
 
228
 
    for (; *s; s++) { // normalize line endings
229
 
        while (*s == '\r') {
230
 
            *(s++) = '\n';
231
 
            if (*s == '\n') memmove(s, (s + 1), strlen(s));
232
 
        }
233
 
    }
234
 
    
235
 
    for (s = r; ; ) {
236
 
        while (*s && *s != '&' && (*s != '%' || t != '%') && !isspace(*s)) s++;
237
 
 
238
 
        if (! *s) break;
239
 
        else if (t != 'c' && ! strncmp(s, "&#", 2)) { // character reference
240
 
            if (s[2] == 'x') c = strtol(s + 3, &e, 16); // base 16
241
 
            else c = strtol(s + 2, &e, 10); // base 10
242
 
            if (! c || *e != ';') { s++; continue; } // not a character ref
243
 
 
244
 
            if (c < 0x80) *(s++) = c; // US-ASCII subset
245
 
            else { // multi-byte UTF-8 sequence
246
 
                for (b = 0, d = c; d; d /= 2) b++; // number of bits in c
247
 
                b = (b - 2) / 5; // number of bytes in payload
248
 
                *(s++) = (0xFF << (7 - b)) | (c >> (6 * b)); // head
249
 
                while (b) *(s++) = 0x80 | ((c >> (6 * --b)) & 0x3F); // payload
250
 
            }
251
 
 
252
 
            memmove(s, strchr(s, ';') + 1, strlen(strchr(s, ';')));
253
 
        }
254
 
        else if ((*s == '&' && (t == '&' || t == ' ' || t == '*')) ||
255
 
                 (*s == '%' && t == '%')) { // entity reference
256
 
            for (b = 0; ent[b] && strncmp(s + 1, ent[b], strlen(ent[b]));
257
 
                 b += 2); // find entity in entity list
258
 
 
259
 
            if (ent[b++]) { // found a match
260
 
                if ((c = strlen(ent[b])) - 1 > (e = strchr(s, ';')) - s) {
261
 
                    l = (d = (s - r)) + c + strlen(e); // new length
262
 
                    r = (r == m) ? strcpy(malloc(l), r) : realloc(r, l);
263
 
                    e = strchr((s = r + d), ';'); // fix up pointers
264
 
                }
265
 
 
266
 
                memmove(s + c, e + 1, strlen(e)); // shift rest of string
267
 
                strncpy(s, ent[b], c); // copy in replacement text
268
 
            }
269
 
            else s++; // not a known entity
270
 
        }
271
 
        else if ((t == ' ' || t == '*') && isspace(*s)) *(s++) = ' ';
272
 
        else s++; // no decoding needed
273
 
    }
274
 
 
275
 
    if (t == '*') { // normalize spaces for non-cdata attributes
276
 
        for (s = r; *s; s++) {
277
 
            if ((l = strspn(s, " "))) memmove(s, s + l, strlen(s + l) + 1);
278
 
            while (*s && *s != ' ') s++;
279
 
        }
280
 
        if (--s >= r && *s == ' ') *s = '\0'; // trim any trailing space
281
 
    }
282
 
    return r;
283
 
}
284
 
 
285
 
// called when parser finds start of new tag
286
 
static void ezxml_open_tag(ezxml_root_t root, char *name, char **attr)
287
 
{
288
 
    ezxml_t xml = root->cur;
289
 
    
290
 
    if (xml->name) xml = ezxml_add_child(xml, name, strlen(xml->txt));
291
 
    else xml->name = name; // first open tag
292
 
 
293
 
    xml->attr = attr;
294
 
    root->cur = xml; // update tag insertion point
295
 
}
296
 
 
297
 
// called when parser finds character content between open and closing tag
298
 
static void ezxml_char_content(ezxml_root_t root, char *s, size_t len, char t)
299
 
{
300
 
    ezxml_t xml = root->cur;
301
 
    char *m = s;
302
 
    size_t l;
303
 
 
304
 
    if (! xml || ! xml->name || ! len) return; // sanity check
305
 
 
306
 
    s[len] = '\0'; // null terminate text (calling functions anticipate this)
307
 
    len = strlen(s = ezxml_decode(s, root->ent, t)) + 1;
308
 
 
309
 
    if (! *(xml->txt)) xml->txt = s; // initial character content
310
 
    else { // allocate our own memory and make a copy
311
 
        xml->txt = (xml->flags & EZXML_TXTM) // allocate some space
312
 
                   ? realloc(xml->txt, (l = strlen(xml->txt)) + len)
313
 
                   : strcpy(malloc((l = strlen(xml->txt)) + len), xml->txt);
314
 
        strcpy(xml->txt + l, s); // add new char content
315
 
        if (s != m) free(s); // free s if it was malloced by ezxml_decode()
316
 
    }
317
 
 
318
 
    if (xml->txt != m) ezxml_set_flag(xml, EZXML_TXTM);
319
 
}
320
 
 
321
 
// called when parser finds closing tag
322
 
static ezxml_t ezxml_close_tag(ezxml_root_t root, char *name, char *s)
323
 
{
324
 
    if (! root->cur || ! root->cur->name || strcmp(name, root->cur->name))
325
 
        return ezxml_err(root, s, "unexpected closing tag </%s>", name);
326
 
 
327
 
    root->cur = root->cur->parent;
328
 
    return NULL;
329
 
}
330
 
 
331
 
// checks for circular entity references, returns non-zero if no circular
332
 
// references are found, zero otherwise
333
 
static int ezxml_ent_ok(char *name, char *s, char **ent)
334
 
{
335
 
    int i;
336
 
 
337
 
    for (; ; s++) {
338
 
        while (*s && *s != '&') s++; // find next entity reference
339
 
        if (! *s) return 1;
340
 
        if (! strncmp(s + 1, name, strlen(name))) return 0; // circular ref.
341
 
        for (i = 0; ent[i] && strncmp(ent[i], s + 1, strlen(ent[i])); i += 2);
342
 
        if (ent[i] && ! ezxml_ent_ok(name, ent[i + 1], ent)) return 0;
343
 
    }
344
 
}
345
 
 
346
 
// called when the parser finds a processing instruction
347
 
static void ezxml_proc_inst(ezxml_root_t root, char *s, size_t len)
348
 
{
349
 
    int i = 0, j = 1;
350
 
    char *target = s;
351
 
 
352
 
    s[len] = '\0'; // null terminate instruction
353
 
    if (*(s += strcspn(s, EZXML_WS))) {
354
 
        *s = '\0'; // null terminate target
355
 
        s += strspn(s + 1, EZXML_WS) + 1; // skip whitespace after target
356
 
    }
357
 
 
358
 
    if (! strcmp(target, "xml")) { // <?xml ... ?>
359
 
        if ((s = strstr(s, "standalone")) && ! strncmp(s + strspn(s + 10,
360
 
            EZXML_WS "='\"") + 10, "yes", 3)) root->standalone = 1;
361
 
        return;
362
 
    }
363
 
 
364
 
    if (! root->pi[0]) *(root->pi = malloc(sizeof(char **))) = NULL; //first pi
365
 
 
366
 
    while (root->pi[i] && strcmp(target, root->pi[i][0])) i++; // find target
367
 
    if (! root->pi[i]) { // new target
368
 
        root->pi = realloc(root->pi, sizeof(char **) * (i + 2));
369
 
        root->pi[i] = malloc(sizeof(char *) * 3);
370
 
        root->pi[i][0] = target;
371
 
        root->pi[i][1] = (char *)(root->pi[i + 1] = NULL); // terminate pi list
372
 
        root->pi[i][2] = strdup(""); // empty document position list
373
 
    }
374
 
 
375
 
    while (root->pi[i][j]) j++; // find end of instruction list for this target
376
 
    root->pi[i] = realloc(root->pi[i], sizeof(char *) * (j + 3));
377
 
    root->pi[i][j + 2] = realloc(root->pi[i][j + 1], j + 1);
378
 
    strcpy(root->pi[i][j + 2] + j - 1, (root->xml.name) ? ">" : "<");
379
 
    root->pi[i][j + 1] = NULL; // null terminate pi list for this target
380
 
    root->pi[i][j] = s; // set instruction
381
 
}
382
 
 
383
 
// called when the parser finds an internal doctype subset
384
 
static short ezxml_internal_dtd(ezxml_root_t root, char *s, size_t len)
385
 
{
386
 
    char q, *c, *t, *n = NULL, *v, **ent, **pe;
387
 
    int i, j;
388
 
    
389
 
    pe = memcpy(malloc(sizeof(EZXML_NIL)), EZXML_NIL, sizeof(EZXML_NIL));
390
 
 
391
 
    for (s[len] = '\0'; s; ) {
392
 
        while (*s && *s != '<' && *s != '%') s++; // find next declaration
393
 
 
394
 
        if (! *s) break;
395
 
        else if (! strncmp(s, "<!ENTITY", 8)) { // parse entity definitions
396
 
            c = s += strspn(s + 8, EZXML_WS) + 8; // skip white space separator
397
 
            n = s + strspn(s, EZXML_WS "%"); // find name
398
 
            *(s = n + strcspn(n, EZXML_WS)) = ';'; // append ; to name
399
 
 
400
 
            v = s + strspn(s + 1, EZXML_WS) + 1; // find value
401
 
            if ((q = *(v++)) != '"' && q != '\'') { // skip externals
402
 
                s = strchr(s, '>');
403
 
                continue;
404
 
            }
405
 
 
406
 
            for (i = 0, ent = (*c == '%') ? pe : root->ent; ent[i]; i++);
407
 
            ent = realloc(ent, (i + 3) * sizeof(char *)); // space for next ent
408
 
            if (*c == '%') pe = ent;
409
 
            else root->ent = ent;
410
 
 
411
 
            *(++s) = '\0'; // null terminate name
412
 
            if ((s = strchr(v, q))) *(s++) = '\0'; // null terminate value
413
 
            ent[i + 1] = ezxml_decode(v, pe, '%'); // set value
414
 
            ent[i + 2] = NULL; // null terminate entity list
415
 
            if (! ezxml_ent_ok(n, ent[i + 1], ent)) { // circular reference
416
 
                if (ent[i + 1] != v) free(ent[i + 1]);
417
 
                ezxml_err(root, v, "circular entity declaration &%s", n);
418
 
                break;
419
 
            }
420
 
            else ent[i] = n; // set entity name
421
 
        }
422
 
        else if (! strncmp(s, "<!ATTLIST", 9)) { // parse default attributes
423
 
            t = s + strspn(s + 9, EZXML_WS) + 9; // skip whitespace separator
424
 
            if (! *t) { ezxml_err(root, t, "unclosed <!ATTLIST"); break; }
425
 
            if (*(s = t + strcspn(t, EZXML_WS ">")) == '>') continue;
426
 
            else *s = '\0'; // null terminate tag name
427
 
            for (i = 0; root->attr[i] && strcmp(n, root->attr[i][0]); i++);
428
 
 
429
 
            ++s; // ansi cpr
430
 
            while (*(n = s + strspn(s, EZXML_WS)) && *n != '>') {
431
 
                if (*(s = n + strcspn(n, EZXML_WS))) *s = '\0'; // attr name
432
 
                else { ezxml_err(root, t, "malformed <!ATTLIST"); break; }
433
 
 
434
 
                s += strspn(s + 1, EZXML_WS) + 1; // find next token
435
 
                c = (strncmp(s, "CDATA", 5)) ? "*" : " "; // is it cdata?
436
 
                if (! strncmp(s, "NOTATION", 8))
437
 
                    s += strspn(s + 8, EZXML_WS) + 8;
438
 
                s = (*s == '(') ? strchr(s, ')') : s + strcspn(s, EZXML_WS);
439
 
                if (! s) { ezxml_err(root, t, "malformed <!ATTLIST"); break; }
440
 
 
441
 
                s += strspn(s, EZXML_WS ")"); // skip white space separator
442
 
                if (! strncmp(s, "#FIXED", 6))
443
 
                    s += strspn(s + 6, EZXML_WS) + 6;
444
 
                if (*s == '#') { // no default value
445
 
                    s += strcspn(s, EZXML_WS ">") - 1;
446
 
                    if (*c == ' ') continue; // cdata is default, nothing to do
447
 
                    v = NULL;
448
 
                }
449
 
                else if ((*s == '"' || *s == '\'')  &&  // default value
450
 
                         (s = strchr(v = s + 1, *s))) *s = '\0';
451
 
                else { ezxml_err(root, t, "malformed <!ATTLIST"); break; }
452
 
 
453
 
                if (! root->attr[i]) { // new tag name
454
 
                    root->attr = (! i) ? malloc(2 * sizeof(char **))
455
 
                                       : realloc(root->attr,
456
 
                                                 (i + 2) * sizeof(char **));
457
 
                    root->attr[i] = malloc(2 * sizeof(char *));
458
 
                    root->attr[i][0] = t; // set tag name
459
 
                    root->attr[i][1] = (char *)(root->attr[i + 1] = NULL);
460
 
                }
461
 
 
462
 
                for (j = 1; root->attr[i][j]; j += 3); // find end of list
463
 
                root->attr[i] = realloc(root->attr[i],
464
 
                                        (j + 4) * sizeof(char *));
465
 
 
466
 
                root->attr[i][j + 3] = NULL; // null terminate list
467
 
                root->attr[i][j + 2] = c; // is it cdata?
468
 
                root->attr[i][j + 1] = (v) ? ezxml_decode(v, root->ent, *c)
469
 
                                           : NULL;
470
 
                root->attr[i][j] = n; // attribute name 
471
 
                ++s;
472
 
            }
473
 
        }
474
 
        else if (! strncmp(s, "<!--", 4)) s = strstr(s + 4, "-->"); // comments
475
 
        else if (! strncmp(s, "<?", 2)) { // processing instructions
476
 
            if ((s = strstr(c = s + 2, "?>")))
477
 
                ezxml_proc_inst(root, c, s++ - c);
478
 
        }
479
 
        else if (*s == '<') s = strchr(s, '>'); // skip other declarations
480
 
        else if (*(s++) == '%' && ! root->standalone) break;
481
 
    }
482
 
 
483
 
    free(pe);
484
 
    return ! *root->err;
485
 
}
486
 
 
487
 
// Converts a UTF-16 string to UTF-8. Returns a new string that must be freed
488
 
// or NULL if no conversion was needed.
489
 
static char *ezxml_str2utf8(char **s, size_t *len)
490
 
{
491
 
    char *u;
492
 
    size_t l = 0, sl, max = *len;
493
 
    long c, d;
494
 
    int b, be = (**s == '\xFE') ? 1 : (**s == '\xFF') ? 0 : -1;
495
 
 
496
 
    if (be == -1) return NULL; // not UTF-16
497
 
 
498
 
    u = malloc(max);
499
 
    for (sl = 2; sl < *len - 1; sl += 2) {
500
 
        c = (be) ? (((*s)[sl] & 0xFF) << 8) | ((*s)[sl + 1] & 0xFF)  //UTF-16BE
501
 
                 : (((*s)[sl + 1] & 0xFF) << 8) | ((*s)[sl] & 0xFF); //UTF-16LE
502
 
        if (c >= 0xD800 && c <= 0xDFFF && (sl += 2) < *len - 1) { // high-half
503
 
            d = (be) ? (((*s)[sl] & 0xFF) << 8) | ((*s)[sl + 1] & 0xFF)
504
 
                     : (((*s)[sl + 1] & 0xFF) << 8) | ((*s)[sl] & 0xFF);
505
 
            c = (((c & 0x3FF) << 10) | (d & 0x3FF)) + 0x10000;
506
 
        }
507
 
 
508
 
        while (l + 6 > max) u = realloc(u, max += EZXML_BUFSIZE);
509
 
        if (c < 0x80) u[l++] = c; // US-ASCII subset
510
 
        else { // multi-byte UTF-8 sequence
511
 
            for (b = 0, d = c; d; d /= 2) b++; // bits in c
512
 
            b = (b - 2) / 5; // bytes in payload
513
 
            u[l++] = (0xFF << (7 - b)) | (c >> (6 * b)); // head
514
 
            while (b) u[l++] = 0x80 | ((c >> (6 * --b)) & 0x3F); // payload
515
 
        }
516
 
    }
517
 
    return *s = realloc(u, *len = l);
518
 
}
519
 
 
520
 
// frees a tag attribute list
521
 
static void ezxml_free_attr(char **attr) {
522
 
    int i = 0;
523
 
    char *m;
524
 
    
525
 
    if (! attr || attr == EZXML_NIL) return; // nothing to free
526
 
    while (attr[i]) i += 2; // find end of attribute list
527
 
    m = attr[i + 1]; // list of which names and values are malloced
528
 
    for (i = 0; m[i]; i++) {
529
 
        if (m[i] & EZXML_NAMEM) free(attr[i * 2]);
530
 
        if (m[i] & EZXML_TXTM) free(attr[(i * 2) + 1]);
531
 
    }
532
 
    free(m);
533
 
    free(attr);
534
 
}
535
 
 
536
 
// parse the given xml string and return an ezxml structure
537
 
ezxml_t ezxml_parse_str(char *s, size_t len)
538
 
{
539
 
    ezxml_root_t root = (ezxml_root_t)ezxml_new(NULL);
540
 
    char q, e, *d, **attr, **a = NULL; // initialize a to avoid compile warning
541
 
    int l, i, j;
542
 
 
543
 
    root->m = s;
544
 
    if (! len) return ezxml_err(root, NULL, "root tag missing");
545
 
    root->u = ezxml_str2utf8(&s, &len); // convert utf-16 to utf-8
546
 
    root->e = (root->s = s) + len; // record start and end of work area
547
 
    
548
 
    e = s[len - 1]; // save end char
549
 
    s[len - 1] = '\0'; // turn end char into null terminator
550
 
 
551
 
    while (*s && *s != '<') s++; // find first tag
552
 
    if (! *s) return ezxml_err(root, s, "root tag missing");
553
 
 
554
 
    for (; ; ) {
555
 
        attr = (char **)EZXML_NIL;
556
 
        d = ++s;
557
 
        
558
 
        if (isalpha(*s) || *s == '_' || *s == ':' || *s < '\0') { // new tag
559
 
            if (! root->cur)
560
 
                return ezxml_err(root, d, "markup outside of root element");
561
 
 
562
 
            s += strcspn(s, EZXML_WS "/>");
563
 
            while (isspace(*s)) *(s++) = '\0'; // null terminate tag name
564
 
  
565
 
            if (*s && *s != '/' && *s != '>') // find tag in default attr list
566
 
                for (i = 0; (a = root->attr[i]) && strcmp(a[0], d); i++);
567
 
 
568
 
            for (l = 0; *s && *s != '/' && *s != '>'; l += 2) { // new attrib
569
 
                attr = (l) ? realloc(attr, (l + 4) * sizeof(char *))
570
 
                           : malloc(4 * sizeof(char *)); // allocate space
571
 
                attr[l + 3] = (l) ? realloc(attr[l + 1], (l / 2) + 2)
572
 
                                  : malloc(2); // mem for list of maloced vals
573
 
                strcpy(attr[l + 3] + (l / 2), " "); // value is not malloced
574
 
                attr[l + 2] = NULL; // null terminate list
575
 
                attr[l + 1] = ""; // temporary attribute value
576
 
                attr[l] = s; // set attribute name
577
 
 
578
 
                s += strcspn(s, EZXML_WS "=/>");
579
 
                if (*s == '=' || isspace(*s)) { 
580
 
                    *(s++) = '\0'; // null terminate tag attribute name
581
 
                    q = *(s += strspn(s, EZXML_WS "="));
582
 
                    if (q == '"' || q == '\'') { // attribute value
583
 
                        attr[l + 1] = ++s;
584
 
                        while (*s && *s != q) s++;
585
 
                        if (*s) *(s++) = '\0'; // null terminate attribute val
586
 
                        else {
587
 
                            ezxml_free_attr(attr);
588
 
                            return ezxml_err(root, d, "missing %c", q);
589
 
                        }
590
 
 
591
 
                        for (j = 1; a && a[j] && strcmp(a[j], attr[l]); j +=3);
592
 
                        attr[l + 1] = ezxml_decode(attr[l + 1], root->ent, (a
593
 
                                                   && a[j]) ? *a[j + 2] : ' ');
594
 
                        if (attr[l + 1] < d || attr[l + 1] > s)
595
 
                            attr[l + 3][l / 2] = EZXML_TXTM; // value malloced
596
 
                    }
597
 
                }
598
 
                while (isspace(*s)) s++;
599
 
            }
600
 
 
601
 
            if (*s == '/') { // self closing tag
602
 
                *(s++) = '\0';
603
 
                if ((*s && *s != '>') || (! *s && e != '>')) {
604
 
                    if (l) ezxml_free_attr(attr);
605
 
                    return ezxml_err(root, d, "missing >");
606
 
                }
607
 
                ezxml_open_tag(root, d, attr);
608
 
                ezxml_close_tag(root, d, s);
609
 
            }
610
 
            else if ((q = *s) == '>' || (! *s && e == '>')) { // open tag
611
 
                *s = '\0'; // temporarily null terminate tag name
612
 
                ezxml_open_tag(root, d, attr);
613
 
                *s = q;
614
 
            }
615
 
            else {
616
 
                if (l) ezxml_free_attr(attr);
617
 
                return ezxml_err(root, d, "missing >"); 
618
 
            }
619
 
        }
620
 
        else if (*s == '/') { // close tag
621
 
            s += strcspn(d = s + 1, EZXML_WS ">") + 1;
622
 
            if (! (q = *s) && e != '>') return ezxml_err(root, d, "missing >");
623
 
            *s = '\0'; // temporarily null terminate tag name
624
 
            if (ezxml_close_tag(root, d, s)) return &root->xml;
625
 
            if (isspace(*s = q)) s += strspn(s, EZXML_WS);
626
 
        }
627
 
        else if (! strncmp(s, "!--", 3)) { // xml comment
628
 
            if (! (s = strstr(s + 3, "--")) || (*(s += 2) != '>' && *s) ||
629
 
                (! *s && e != '>')) return ezxml_err(root, d, "unclosed <!--");
630
 
        }
631
 
        else if (! strncmp(s, "![CDATA[", 8)) { // cdata
632
 
            if ((s = strstr(s, "]]>")))
633
 
                ezxml_char_content(root, d + 8, (s += 2) - d - 10, 'c');
634
 
            else return ezxml_err(root, d, "unclosed <![CDATA[");
635
 
        }
636
 
        else if (! strncmp(s, "!DOCTYPE", 8)) { // dtd
637
 
            for (l = 0; *s && ((! l && *s != '>') || (l && (*s != ']' || 
638
 
                 *(s + strspn(s + 1, EZXML_WS) + 1) != '>')));
639
 
                 l = (*s == '[') ? 1 : l) s += strcspn(s + 1, "[]>") + 1;
640
 
            if (! *s && e != '>')
641
 
                return ezxml_err(root, d, "unclosed <!DOCTYPE");
642
 
            d = (l) ? strchr(d, '[') + 1 : d;
643
 
            if (l && ! ezxml_internal_dtd(root, d, s++ - d)) return &root->xml;
644
 
        }
645
 
        else if (*s == '?') { // <?...?> processing instructions
646
 
            do { s = strchr(s, '?'); } while (s && *(++s) && *s != '>');
647
 
            if (! s || (! *s && e != '>')) 
648
 
                return ezxml_err(root, d, "unclosed <?");
649
 
            else ezxml_proc_inst(root, d + 1, s - d - 2);
650
 
        }
651
 
        else return ezxml_err(root, d, "unexpected <");
652
 
        
653
 
        if (! s || ! *s) break;
654
 
        *s = '\0';
655
 
        d = ++s;
656
 
        if (*s && *s != '<') { // tag character content
657
 
            while (*s && *s != '<') s++;
658
 
            if (*s) ezxml_char_content(root, d, s - d, '&');
659
 
            else break;
660
 
        }
661
 
        else if (! *s) break;
662
 
    }
663
 
 
664
 
    if (! root->cur) return &root->xml;
665
 
    else if (! root->cur->name) return ezxml_err(root, d, "root tag missing");
666
 
    else return ezxml_err(root, d, "unclosed tag <%s>", root->cur->name);
667
 
}
668
 
 
669
 
// free the memory allocated for the ezxml structure
670
 
void ezxml_free(ezxml_t xml)
671
 
{
672
 
    ezxml_root_t root = (ezxml_root_t)xml;
673
 
    int i, j;
674
 
    char **a, *s;
675
 
 
676
 
    if (! xml) return;
677
 
    ezxml_free(xml->child);
678
 
    ezxml_free(xml->ordered);
679
 
 
680
 
    if (! xml->parent) { // free root tag allocations
681
 
        for (i = 10; root->ent[i]; i += 2) // 0 - 9 are default entites (<>&"')
682
 
            if ((s = root->ent[i + 1]) < root->s || s > root->e) free(s);
683
 
        free(root->ent); // free list of general entities
684
 
 
685
 
        for (i = 0; (a = root->attr[i]); i++) {
686
 
            for (j = 1; a[j++]; j += 2) // free malloced attribute values
687
 
                if (a[j] && (a[j] < root->s || a[j] > root->e)) free(a[j]);
688
 
            free(a);
689
 
        }
690
 
        if (root->attr[0]) free(root->attr); // free default attribute list
691
 
 
692
 
        for (i = 0; root->pi[i]; i++) {
693
 
            for (j = 1; root->pi[i][j]; j++);
694
 
            free(root->pi[i][j + 1]);
695
 
            free(root->pi[i]);
696
 
        }            
697
 
        if (root->pi[0]) free(root->pi); // free processing instructions
698
 
 
699
 
        if (root->len == -1) free(root->m); // malloced xml data
700
 
        if (root->u) free(root->u); // utf8 conversion
701
 
    }
702
 
 
703
 
    ezxml_free_attr(xml->attr); // tag attributes
704
 
    if ((xml->flags & EZXML_TXTM)) free(xml->txt); // character content
705
 
    if ((xml->flags & EZXML_NAMEM)) free(xml->name); // tag name
706
 
    free(xml);
707
 
}
708
 
 
709
 
// return parser error message or empty string if none
710
 
const char *ezxml_error(ezxml_t xml)
711
 
{
712
 
    while (xml && xml->parent) xml = xml->parent; // find root tag
713
 
    return (xml) ? ((ezxml_root_t)xml)->err : "";
714
 
}
715