]> mj.ucw.cz Git - libucw.git/blob - sherlock/xml/source.c
XML: Several fixes, slightly changed the iface.
[libucw.git] / sherlock / xml / source.c
1 /*
2  *      Sherlock Library -- A simple XML parser
3  *
4  *      (c) 2007--2008 Pavel Charvat <pchar@ucw.cz>
5  *
6  *      This software may be freely distributed and used according to the terms
7  *      of the GNU Lesser General Public License.
8  */
9
10 #undef LOCAL_DEBUG
11
12 #include "sherlock/sherlock.h"
13 #include "sherlock/xml/xml.h"
14 #include "sherlock/xml/dtd.h"
15 #include "sherlock/xml/common.h"
16 #include "lib/unicode.h"
17 #include "lib/ff-unicode.h"
18 #include "charset/charconv.h"
19 #include "charset/fb-charconv.h"
20
21 /*** Charecter categorization ***/
22
23 #include "obj/sherlock/xml/unicat.c"
24
25 static void
26 xml_init_cats(struct xml_context *ctx)
27 {
28   if (!(ctx->flags & XML_VERSION_1_1))
29     {
30       ctx->cat_chars = XML_CHAR_VALID_1_0;
31       ctx->cat_unrestricted = XML_CHAR_VALID_1_0;
32       ctx->cat_new_line = XML_CHAR_NEW_LINE_1_0;
33       ctx->cat_name = XML_CHAR_NAME_1_0;
34       ctx->cat_sname = XML_CHAR_SNAME_1_0;
35     }
36   else
37     {
38       ctx->cat_chars = XML_CHAR_VALID_1_1;
39       ctx->cat_unrestricted = XML_CHAR_UNRESTRICTED_1_1;
40       ctx->cat_new_line = XML_CHAR_NEW_LINE_1_1;
41       ctx->cat_name = XML_CHAR_NAME_1_1;
42       ctx->cat_sname = XML_CHAR_SNAME_1_1;
43     }
44 }
45
46 /*** Reading of document/external entities ***/
47
48 static void NONRET
49 xml_eof(struct xml_context *ctx)
50 {
51   ctx->err_msg = "Unexpected EOF";
52   ctx->err_code = XML_ERR_EOF;
53   xml_throw(ctx);
54 }
55
56 void NONRET
57 xml_fatal_nested(struct xml_context *ctx)
58 {
59   xml_fatal(ctx, "Entity is not nested correctly");
60 }
61
62 static inline void
63 xml_add_char(u32 **bstop, uns c)
64 {
65   *(*bstop)++ = c;
66   *(*bstop)++ = xml_char_cat(c);
67 }
68
69 struct xml_source *
70 xml_push_source(struct xml_context *ctx)
71 {
72   xml_push(ctx);
73   struct xml_source *src = ctx->src;
74   if (src)
75     {
76       src->bptr = ctx->bptr;
77       src->bstop = ctx->bstop;
78     }
79   src = mp_alloc_zero(ctx->stack, sizeof(*src));
80   src->next = ctx->src;
81   src->saved_depth = ctx->depth;
82   ctx->src = src;
83   ctx->flags &= ~(XML_SRC_EOF | XML_SRC_EXPECTED_DECL | XML_SRC_NEW_LINE | XML_SRC_SURROUND | XML_SRC_DOCUMENT);
84   ctx->bstop = ctx->bptr = src->buf;
85   ctx->depth = 0;
86   return src;
87 }
88
89 struct xml_source *
90 xml_push_fastbuf(struct xml_context *ctx, struct fastbuf *fb)
91 {
92   struct xml_source *src = xml_push_source(ctx);
93   src->fb = fb;
94   return src;
95 }
96
97 static void
98 xml_close_source(struct xml_source *src)
99 {
100   bclose(src->fb);
101   if (src->wrapped_fb)
102     bclose(src->wrapped_fb);
103 }
104
105 static void
106 xml_pop_source(struct xml_context *ctx)
107 {
108   TRACE(ctx, "pop_source");
109   if (unlikely(ctx->depth != 0))
110     xml_fatal(ctx, "Unexpected end of entity");
111   struct xml_source *src = ctx->src;
112   if (!src)
113     xml_fatal(ctx, "Undefined source");
114   xml_close_source(src);
115   ctx->depth = src->saved_depth;
116   ctx->src = src = src->next;
117   if (src)
118     {
119       ctx->bptr = src->bptr;
120       ctx->bstop = src->bstop;
121     }
122   xml_pop(ctx);
123   if (unlikely(!src))
124     xml_eof(ctx);
125 }
126
127 void
128 xml_sources_cleanup(struct xml_context *ctx)
129 {
130   struct xml_source *s;
131   while (s = ctx->src)
132     {
133       ctx->src = s->next;
134       xml_close_source(s);
135     }
136 }
137
138 static void xml_refill_utf8(struct xml_context *ctx);
139
140 void
141 xml_def_resolve_entity(struct xml_context *ctx, struct xml_dtd_entity *ent UNUSED)
142 {
143   xml_error(ctx, "References to external entities are not supported");
144 }
145
146 void
147 xml_push_entity(struct xml_context *ctx, struct xml_dtd_entity *ent)
148 {
149   TRACE(ctx, "xml_push_entity");
150   struct xml_source *src;
151   if (ent->flags & XML_DTD_ENTITY_EXTERNAL)
152     {
153       ASSERT(ctx->h_resolve_entity);
154       ctx->h_resolve_entity(ctx, ent);
155       ctx->flags |= XML_SRC_EXPECTED_DECL;
156       src = ctx->src;
157     }
158   else
159     {
160       src = xml_push_source(ctx);
161       fbbuf_init_read(src->fb = &src->wrap_fb, ent->text, strlen(ent->text), 0);
162     }
163   src->refill = xml_refill_utf8;
164   src->refill_cat1 = ctx->cat_unrestricted & ~ctx->cat_new_line;
165   src->refill_cat2 = ctx->cat_new_line;
166 }
167
168 static uns
169 xml_error_restricted(struct xml_context *ctx, uns c)
170 {
171   if (c == ~1U)
172     xml_error(ctx, "Corrupted encoding");
173   else
174     xml_error(ctx, "Restricted char U+%04X", c);
175   return UNI_REPLACEMENT;
176 }
177
178 void xml_parse_decl(struct xml_context *ctx);
179
180 #define REFILL(ctx, func, params...)                                                    \
181   struct xml_source *src = ctx->src;                                                    \
182   struct fastbuf *fb = src->fb;                                                         \
183   if (ctx->bptr == ctx->bstop)                                                          \
184     ctx->bptr = ctx->bstop = src->buf;                                                  \
185   uns f = ctx->flags, c, t1 = src->refill_cat1, t2 = src->refill_cat2, row = src->row;  \
186   u32 *bend = src->buf + ARRAY_SIZE(src->buf), *bstop = ctx->bstop,                     \
187       *last_0xd = (f & XML_SRC_NEW_LINE) ? bstop : bend;                                \
188   do                                                                                    \
189     {                                                                                   \
190       c = func(fb, ##params);                                                           \
191       uns t = xml_char_cat(c);                                                          \
192       if (t & t1)                                                                       \
193         /* Typical branch */                                                            \
194         *bstop++ = c, *bstop++ = t;                                                     \
195       else if (t & t2)                                                                  \
196         {                                                                               \
197           /* New line */                                                                \
198           /* XML 1.0: 0xA | 0xD | 0xD 0xA */                                            \
199           /* XML 1.1: 0xA | 0xD | 0xD 0xA | 0x85 | 0xD 0x85 | 0x2028 */                 \
200           if (c == 0xd)                                                                 \
201             last_0xd = bstop + 2;                                                       \
202           else if (c != 0x2028 && last_0xd == bstop)                                    \
203             {                                                                           \
204               last_0xd = bend;                                                          \
205               continue;                                                                 \
206             }                                                                           \
207           xml_add_char(&bstop, 0xa), row++;                                             \
208         }                                                                               \
209       else if (c == '>')                                                                \
210         {                                                                               \
211           /* Used only in XML/TextDecl to switch the encoding */                        \
212           *bstop++ = c, *bstop++ = t;                                                   \
213           break;                                                                        \
214         }                                                                               \
215       else if (~c)                                                                      \
216         /* Restricted character */                                                      \
217         xml_add_char(&bstop, xml_error_restricted(ctx, c));                             \
218       else                                                                              \
219         {                                                                               \
220           /* EOF */                                                                     \
221           if (f & XML_SRC_SURROUND)                                                     \
222             xml_add_char(&bstop, 0x20);                                                 \
223           f |= XML_SRC_EOF;                                                             \
224           break;                                                                        \
225         }                                                                               \
226     }                                                                                   \
227   while (bstop < bend);                                                                 \
228   ctx->flags = (last_0xd == bstop) ? f | XML_SRC_NEW_LINE : f & ~XML_SRC_NEW_LINE;      \
229   ctx->bstop = bstop;                                                                   \
230   src->row = row;
231
232 static void
233 xml_refill_utf8(struct xml_context *ctx)
234 {
235   REFILL(ctx, bget_utf8_repl, ~1U);
236 }
237
238 static void
239 xml_refill_utf16_le(struct xml_context *ctx)
240 {
241   REFILL(ctx, bget_utf16_le_repl, ~1U);
242 }
243
244 static void
245 xml_refill_utf16_be(struct xml_context *ctx)
246 {
247   REFILL(ctx, bget_utf16_be_repl, ~1U);
248 }
249
250 #undef REFILL
251
252 void
253 xml_refill(struct xml_context *ctx)
254 {
255   do
256     {
257       if (ctx->flags & XML_SRC_EOF)
258         xml_pop_source(ctx);
259       else if (ctx->flags & XML_SRC_EXPECTED_DECL)
260         xml_parse_decl(ctx);
261       else
262         {
263           ctx->src->refill(ctx);
264           TRACE(ctx, "refilled %u characters", (uns)((ctx->bstop - ctx->bptr) / 2));
265         }
266     }
267   while (ctx->bptr == ctx->bstop);
268 }
269
270 static uns
271 xml_source_row(struct xml_context *ctx, struct xml_source *src)
272 {
273   uns row = src->row;
274   for (u32 *p = ctx->bstop; p != ctx->bptr; p -= 2)
275     if (p[-1] & src->refill_cat2)
276       row--;
277   return row + 1;
278 }
279
280 uns
281 xml_row(struct xml_context *ctx)
282 {
283   return ctx->src ? xml_source_row(ctx, ctx->src) : 0;
284 }
285
286 /* Document/external entity header */
287
288 static char *
289 xml_parse_encoding_name(struct xml_context *ctx)
290 {
291   /* EncName ::= '"' [A-Za-z] ([A-Za-z0-9._] | '-')* '"' | "'" [A-Za-z] ([A-Za-z0-9._] | '-')* "'" */
292   char *p = mp_start_noalign(ctx->pool, 1);
293   uns q = xml_parse_quote(ctx);
294   if (unlikely(!(xml_get_cat(ctx) & XML_CHAR_ENC_SNAME)))
295     xml_fatal(ctx, "Invalid character in the encoding name");
296   while (1)
297     {
298       p = mp_spread(ctx->pool, p, 2);
299       *p++ = xml_last_char(ctx);
300       if (xml_get_char(ctx) == q)
301         break;
302       if (unlikely(!(xml_last_cat(ctx) & XML_CHAR_ENC_NAME)))
303         xml_fatal(ctx, "Invalid character in the encoding name");
304     }
305   *p++ = 0;
306   return mp_end(ctx->pool, p);
307 }
308
309 static void
310 xml_init_charconv(struct xml_context *ctx, int cs)
311 {
312   // XXX: with a direct access to libcharset tables could be faster
313   struct xml_source *src = ctx->src;
314   TRACE(ctx, "wrapping charset %s", charset_name(cs));
315   src->wrapped_fb = src->fb;
316   src->fb = fb_wrap_charconv_in(src->fb, cs, CONV_CHARSET_UTF8);
317 }
318
319 void
320 xml_parse_decl(struct xml_context *ctx)
321 {
322   TRACE(ctx, "xml_parse_decl");
323   struct xml_source *src = ctx->src;
324   ctx->flags &= ~XML_SRC_EXPECTED_DECL;
325   uns doc = ctx->flags & XML_SRC_DOCUMENT;
326
327   /* Setup valid Unicode ranges and force the reader to abort refill() after each '>', where we can switch encoding or XML version */
328   if (doc)
329     xml_init_cats(ctx);
330   src->refill_cat1 = ctx->cat_unrestricted & ~ctx->cat_new_line & ~XML_CHAR_GT;
331   src->refill_cat2 = ctx->cat_new_line;
332
333   /* Initialize the supplied charset (if any) or try to guess it */
334   char *expected_encoding = src->expected_encoding ? : src->fb_encoding;
335   src->refill = xml_refill_utf8;
336   int bom = bpeekc(src->fb);
337   if (bom < 0)
338     ctx->flags |= XML_SRC_EOF;
339   if (!src->fb_encoding)
340     {
341       if (bom == 0xfe)
342         src->refill = xml_refill_utf16_be;
343       else if (bom == 0xff)
344         src->refill = xml_refill_utf16_le;
345     }
346   else
347     {
348       int cs = find_charset_by_name(src->fb_encoding);
349       if (cs == CONV_CHARSET_UTF8)
350         {}
351       else if (cs >= 0)
352         {
353           xml_init_charconv(ctx, cs);
354           bom = 0;
355         }
356       else if (strcasecmp(src->fb_encoding, "UTF-16"))
357         {
358           src->refill = xml_refill_utf16_be;
359           if (bom == 0xff)
360             src->refill = xml_refill_utf16_le;
361           if (!src->expected_encoding)
362             expected_encoding = (bom == 0xff) ? "UTF-16LE" : "UTF-16BE";
363         }
364       else if (strcasecmp(src->fb_encoding, "UTF-16BE"))
365         src->refill = xml_refill_utf16_be;
366       else if (strcasecmp(src->fb_encoding, "UTF-16LE"))
367         src->refill = xml_refill_utf16_le;
368       else
369         {
370           xml_error(ctx, "Unknown encoding '%s'", src->fb_encoding);
371           expected_encoding = NULL;
372         }
373     }
374   uns utf16 = src->refill == xml_refill_utf16_le || src->refill == xml_refill_utf16_be;
375   if (bom > 0 && xml_peek_char(ctx) == 0xfeff)
376     xml_skip_char(ctx);
377   else if (utf16)
378     xml_error(ctx, "Missing or corrupted BOM");
379
380   /* Look ahead for presence of XMLDecl or optional TextDecl */
381   if (!(ctx->flags & XML_SRC_EOF) && ctx->bstop != src->buf + ARRAY_SIZE(src->buf))
382     xml_refill(ctx);
383   u32 *bptr = ctx->bptr;
384   uns have_decl = (12 <= ctx->bstop - ctx->bptr && (bptr[11] & XML_CHAR_WHITE) &&
385     bptr[0] == '<' && bptr[2] == '?' && (bptr[4] & 0xdf) == 'X' && (bptr[6] & 0xdf) == 'M' && (bptr[8] & 0xdf) == 'L');
386   if (!have_decl)
387     {
388       if (doc)
389         xml_fatal(ctx, "Missing or corrupted XML header");
390       else if (expected_encoding && strcasecmp(src->expected_encoding, "UTF-8") && !utf16)
391         xml_error(ctx, "Missing or corrupted entity header");
392       goto exit;
393     }
394   ctx->bptr = bptr + 12;
395   xml_parse_white(ctx, 0);
396
397   /* Parse version string (mandatory in XMLDecl, optional in TextDecl) */
398   if (xml_peek_char(ctx) == 'v')
399     {
400       xml_parse_seq(ctx, "version");
401       xml_parse_eq(ctx);
402       char *version = xml_parse_pubid_literal(ctx, ctx->pool);
403       TRACE(ctx, "version=%s", version);
404       uns v = 0;
405       if (!strcmp(version, "1.1"))
406         v = XML_VERSION_1_1;
407       else if (strcmp(version, "1.0"))
408         {
409           xml_error(ctx, "Unknown XML version string '%s'", version);
410           version = "1.0";
411         }
412       if (doc)
413         {
414           ctx->version_str = version;
415           ctx->flags |= v;
416         }
417       else if (v > (ctx->flags & XML_VERSION_1_1))
418         xml_error(ctx, "XML 1.1 external entity included from XML 1.0 document");
419       if (!xml_parse_white(ctx, !doc))
420         goto end;
421     }
422   else if (doc)
423     {
424       xml_error(ctx, "Expected XML version");
425       ctx->version_str = "1.0";
426     }
427
428   /* Parse encoding string (optional in XMLDecl, mandatory in TextDecl) */
429   if (xml_peek_char(ctx) == 'e')
430     {
431       xml_parse_seq(ctx, "encoding");
432       xml_parse_eq(ctx);
433       src->decl_encoding = xml_parse_encoding_name(ctx);
434       TRACE(ctx, "encoding=%s", src->decl_encoding);
435       if (!xml_parse_white(ctx, 0))
436         goto end;
437     }
438   else if (!doc)
439     xml_error(ctx, "Expected XML encoding");
440
441   /* Parse whether the document is standalone (optional in XMLDecl) */
442   if (doc && xml_peek_char(ctx) == 's')
443     {
444       xml_parse_seq(ctx, "standalone");
445       xml_parse_eq(ctx);
446       uns c = xml_parse_quote(ctx);
447       if (ctx->standalone = (xml_peek_char(ctx) == 'y'))
448         xml_parse_seq(ctx, "yes");
449       else
450         xml_parse_seq(ctx, "no");
451       xml_parse_char(ctx, c);
452       TRACE(ctx, "standalone=%d", ctx->standalone);
453       xml_parse_white(ctx, 0);
454     }
455 end:
456   xml_parse_seq(ctx, "?>");
457
458   /* Switch to the final encoding */
459   if (src->decl_encoding)
460     {
461       int cs = find_charset_by_name(src->decl_encoding);
462       if (cs < 0 && !expected_encoding)
463         xml_error(ctx, "Unknown encoding '%s'", src->decl_encoding);
464       else if (!src->fb_encoding && cs >= 0 && cs != CONV_CHARSET_UTF8)
465         xml_init_charconv(ctx, cs);
466       else if (expected_encoding && strcasecmp(src->decl_encoding, expected_encoding) && (!utf16 ||
467         !(!strcasecmp(src->decl_encoding, "UTF-16") ||
468          (!strcasecmp(src->decl_encoding, "UTF-16BE") && strcasecmp(expected_encoding, "UTF-16LE")) ||
469          (!strcasecmp(src->decl_encoding, "UTF-16LE") && strcasecmp(expected_encoding, "UTF-16BE")))))
470         xml_error(ctx, "The header contains encoding '%s' instead of expected '%s'", src->decl_encoding, expected_encoding);
471     }
472
473 exit:
474   /* Update valid Unicode ranges */
475   if (doc)
476     xml_init_cats(ctx);
477   src->refill_cat1 = ctx->cat_unrestricted & ~ctx->cat_new_line;
478   src->refill_cat2 = ctx->cat_new_line;
479 }