docs: let go of *
[platform/upstream/glib.git] / glib / gmarkup.c
1 /* gmarkup.c - Simple XML-like parser
2  *
3  *  Copyright 2000, 2003 Red Hat, Inc.
4  *  Copyright 2007, 2008 Ryan Lortie <desrt@desrt.ca>
5  *
6  * GLib is free software; you can redistribute it and/or modify it
7  * under the terms of the GNU Lesser General Public License as
8  * published by the Free Software Foundation; either version 2 of the
9  * License, or (at your option) any later version.
10  *
11  * GLib is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with GLib; see the file COPYING.LIB.  If not,
18  * see <http://www.gnu.org/licenses/>.
19  */
20
21 #include "config.h"
22
23 #include <stdarg.h>
24 #include <string.h>
25 #include <stdio.h>
26 #include <stdlib.h>
27 #include <errno.h>
28
29 #include "gmarkup.h"
30
31 #include "gatomic.h"
32 #include "gslice.h"
33 #include "galloca.h"
34 #include "gstrfuncs.h"
35 #include "gstring.h"
36 #include "gtestutils.h"
37 #include "glibintl.h"
38 #include "gthread.h"
39
40 /**
41  * SECTION:markup
42  * @Title: Simple XML Subset Parser * @Short_description: parses a subset of XML
43  * @See_also: [XML Specification](http://www.w3.org/TR/REC-xml/)
44  *
45  * The "GMarkup" parser is intended to parse a simple markup format
46  * that's a subset of XML. This is a small, efficient, easy-to-use
47  * parser. It should not be used if you expect to interoperate with
48  * other applications generating full-scale XML. However, it's very
49  * useful for application data files, config files, etc. where you
50  * know your application will be the only one writing the file.
51  * Full-scale XML parsers should be able to parse the subset used by
52  * GMarkup, so you can easily migrate to full-scale XML at a later
53  * time if the need arises.
54  *
55  * GMarkup is not guaranteed to signal an error on all invalid XML;
56  * the parser may accept documents that an XML parser would not.
57  * However, XML documents which are not well-formed (which is a
58  * weaker condition than being valid. See the
59  * [XML specification](http://www.w3.org/TR/REC-xml/)
60  * for definitions of these terms.) are not considered valid GMarkup
61  * documents.
62  *
63  * Simplifications to XML include:
64  *
65  * - Only UTF-8 encoding is allowed
66  *
67  * - No user-defined entities
68  *
69  * - Processing instructions, comments and the doctype declaration
70  *   are "passed through" but are not interpreted in any way
71  *
72  * - No DTD or validation
73  *
74  * The markup format does support:
75  *
76  * - Elements
77  *
78  * - Attributes
79  *
80  * - 5 standard entities: &amp; &lt; &gt; &quot; &apos;
81  *
82  * - Character references
83  *
84  * - Sections marked as CDATA
85  */
86
87 G_DEFINE_QUARK (g-markup-error-quark, g_markup_error)
88
89 typedef enum
90 {
91   STATE_START,
92   STATE_AFTER_OPEN_ANGLE,
93   STATE_AFTER_CLOSE_ANGLE,
94   STATE_AFTER_ELISION_SLASH, /* the slash that obviates need for end element */
95   STATE_INSIDE_OPEN_TAG_NAME,
96   STATE_INSIDE_ATTRIBUTE_NAME,
97   STATE_AFTER_ATTRIBUTE_NAME,
98   STATE_BETWEEN_ATTRIBUTES,
99   STATE_AFTER_ATTRIBUTE_EQUALS_SIGN,
100   STATE_INSIDE_ATTRIBUTE_VALUE_SQ,
101   STATE_INSIDE_ATTRIBUTE_VALUE_DQ,
102   STATE_INSIDE_TEXT,
103   STATE_AFTER_CLOSE_TAG_SLASH,
104   STATE_INSIDE_CLOSE_TAG_NAME,
105   STATE_AFTER_CLOSE_TAG_NAME,
106   STATE_INSIDE_PASSTHROUGH,
107   STATE_ERROR
108 } GMarkupParseState;
109
110 typedef struct
111 {
112   const char *prev_element;
113   const GMarkupParser *prev_parser;
114   gpointer prev_user_data;
115 } GMarkupRecursionTracker;
116
117 struct _GMarkupParseContext
118 {
119   const GMarkupParser *parser;
120
121   volatile gint ref_count;
122
123   GMarkupParseFlags flags;
124
125   gint line_number;
126   gint char_number;
127
128   GMarkupParseState state;
129
130   gpointer user_data;
131   GDestroyNotify dnotify;
132
133   /* A piece of character data or an element that
134    * hasn't "ended" yet so we haven't yet called
135    * the callback for it.
136    */
137   GString *partial_chunk;
138   GSList *spare_chunks;
139
140   GSList *tag_stack;
141   GSList *tag_stack_gstr;
142   GSList *spare_list_nodes;
143
144   GString **attr_names;
145   GString **attr_values;
146   gint cur_attr;
147   gint alloc_attrs;
148
149   const gchar *current_text;
150   gssize       current_text_len;
151   const gchar *current_text_end;
152
153   /* used to save the start of the last interesting thingy */
154   const gchar *start;
155
156   const gchar *iter;
157
158   guint document_empty : 1;
159   guint parsing : 1;
160   guint awaiting_pop : 1;
161   gint balance;
162
163   /* subparser support */
164   GSList *subparser_stack; /* (GMarkupRecursionTracker *) */
165   const char *subparser_element;
166   gpointer held_user_data;
167 };
168
169 /*
170  * Helpers to reduce our allocation overhead, we have
171  * a well defined allocation lifecycle.
172  */
173 static GSList *
174 get_list_node (GMarkupParseContext *context, gpointer data)
175 {
176   GSList *node;
177   if (context->spare_list_nodes != NULL)
178     {
179       node = context->spare_list_nodes;
180       context->spare_list_nodes = g_slist_remove_link (context->spare_list_nodes, node);
181     }
182   else
183     node = g_slist_alloc();
184   node->data = data;
185   return node;
186 }
187
188 static void
189 free_list_node (GMarkupParseContext *context, GSList *node)
190 {
191   node->data = NULL;
192   context->spare_list_nodes = g_slist_concat (node, context->spare_list_nodes);
193 }
194
195 static inline void
196 string_blank (GString *string)
197 {
198   string->str[0] = '\0';
199   string->len = 0;
200 }
201
202 /**
203  * g_markup_parse_context_new:
204  * @parser: a #GMarkupParser
205  * @flags: one or more #GMarkupParseFlags
206  * @user_data: user data to pass to #GMarkupParser functions
207  * @user_data_dnotify: user data destroy notifier called when
208  *     the parse context is freed
209  *
210  * Creates a new parse context. A parse context is used to parse
211  * marked-up documents. You can feed any number of documents into
212  * a context, as long as no errors occur; once an error occurs,
213  * the parse context can't continue to parse text (you have to
214  * free it and create a new parse context).
215  *
216  * Return value: a new #GMarkupParseContext
217  **/
218 GMarkupParseContext *
219 g_markup_parse_context_new (const GMarkupParser *parser,
220                             GMarkupParseFlags    flags,
221                             gpointer             user_data,
222                             GDestroyNotify       user_data_dnotify)
223 {
224   GMarkupParseContext *context;
225
226   g_return_val_if_fail (parser != NULL, NULL);
227
228   context = g_new (GMarkupParseContext, 1);
229
230   context->ref_count = 1;
231   context->parser = parser;
232   context->flags = flags;
233   context->user_data = user_data;
234   context->dnotify = user_data_dnotify;
235
236   context->line_number = 1;
237   context->char_number = 1;
238
239   context->partial_chunk = NULL;
240   context->spare_chunks = NULL;
241   context->spare_list_nodes = NULL;
242
243   context->state = STATE_START;
244   context->tag_stack = NULL;
245   context->tag_stack_gstr = NULL;
246   context->attr_names = NULL;
247   context->attr_values = NULL;
248   context->cur_attr = -1;
249   context->alloc_attrs = 0;
250
251   context->current_text = NULL;
252   context->current_text_len = -1;
253   context->current_text_end = NULL;
254
255   context->start = NULL;
256   context->iter = NULL;
257
258   context->document_empty = TRUE;
259   context->parsing = FALSE;
260
261   context->awaiting_pop = FALSE;
262   context->subparser_stack = NULL;
263   context->subparser_element = NULL;
264
265   /* this is only looked at if awaiting_pop = TRUE.  initialise anyway. */
266   context->held_user_data = NULL;
267
268   context->balance = 0;
269
270   return context;
271 }
272
273 /**
274  * g_markup_parse_context_ref:
275  * @context: a #GMarkupParseContext
276  *
277  * Increases the reference count of @context.
278  *
279  * Returns: the same @context
280  *
281  * Since: 2.36
282  **/
283 GMarkupParseContext *
284 g_markup_parse_context_ref (GMarkupParseContext *context)
285 {
286   g_return_val_if_fail (context != NULL, NULL);
287   g_return_val_if_fail (context->ref_count > 0, NULL);
288
289   g_atomic_int_inc (&context->ref_count);
290
291   return context;
292 }
293
294 /**
295  * g_markup_parse_context_unref:
296  * @context: a #GMarkupParseContext
297  *
298  * Decreases the reference count of @context.  When its reference count
299  * drops to 0, it is freed.
300  *
301  * Since: 2.36
302  **/
303 void
304 g_markup_parse_context_unref (GMarkupParseContext *context)
305 {
306   g_return_if_fail (context != NULL);
307   g_return_if_fail (context->ref_count > 0);
308
309   if (g_atomic_int_dec_and_test (&context->ref_count))
310     g_markup_parse_context_free (context);
311 }
312
313 static void
314 string_full_free (gpointer ptr)
315 {
316   g_string_free (ptr, TRUE);
317 }
318
319 static void clear_attributes (GMarkupParseContext *context);
320
321 /**
322  * g_markup_parse_context_free:
323  * @context: a #GMarkupParseContext
324  *
325  * Frees a #GMarkupParseContext.
326  *
327  * This function can't be called from inside one of the
328  * #GMarkupParser functions or while a subparser is pushed.
329  */
330 void
331 g_markup_parse_context_free (GMarkupParseContext *context)
332 {
333   g_return_if_fail (context != NULL);
334   g_return_if_fail (!context->parsing);
335   g_return_if_fail (!context->subparser_stack);
336   g_return_if_fail (!context->awaiting_pop);
337
338   if (context->dnotify)
339     (* context->dnotify) (context->user_data);
340
341   clear_attributes (context);
342   g_free (context->attr_names);
343   g_free (context->attr_values);
344
345   g_slist_free_full (context->tag_stack_gstr, string_full_free);
346   g_slist_free (context->tag_stack);
347
348   g_slist_free_full (context->spare_chunks, string_full_free);
349   g_slist_free (context->spare_list_nodes);
350
351   if (context->partial_chunk)
352     g_string_free (context->partial_chunk, TRUE);
353
354   g_free (context);
355 }
356
357 static void pop_subparser_stack (GMarkupParseContext *context);
358
359 static void
360 mark_error (GMarkupParseContext *context,
361             GError              *error)
362 {
363   context->state = STATE_ERROR;
364
365   if (context->parser->error)
366     (*context->parser->error) (context, error, context->user_data);
367
368   /* report the error all the way up to free all the user-data */
369   while (context->subparser_stack)
370     {
371       pop_subparser_stack (context);
372       context->awaiting_pop = FALSE; /* already been freed */
373
374       if (context->parser->error)
375         (*context->parser->error) (context, error, context->user_data);
376     }
377 }
378
379 static void
380 set_error (GMarkupParseContext  *context,
381            GError              **error,
382            GMarkupError          code,
383            const gchar          *format,
384            ...) G_GNUC_PRINTF (4, 5);
385
386 static void
387 set_error_literal (GMarkupParseContext  *context,
388                    GError              **error,
389                    GMarkupError          code,
390                    const gchar          *message)
391 {
392   GError *tmp_error;
393
394   tmp_error = g_error_new_literal (G_MARKUP_ERROR, code, message);
395
396   g_prefix_error (&tmp_error,
397                   _("Error on line %d char %d: "),
398                   context->line_number,
399                   context->char_number);
400
401   mark_error (context, tmp_error);
402
403   g_propagate_error (error, tmp_error);
404 }
405
406 G_GNUC_PRINTF(4, 5)
407 static void
408 set_error (GMarkupParseContext  *context,
409            GError              **error,
410            GMarkupError          code,
411            const gchar          *format,
412            ...)
413 {
414   gchar *s;
415   gchar *s_valid;
416   va_list args;
417
418   va_start (args, format);
419   s = g_strdup_vprintf (format, args);
420   va_end (args);
421
422   /* Make sure that the GError message is valid UTF-8
423    * even if it is complaining about invalid UTF-8 in the markup
424    */
425   s_valid = _g_utf8_make_valid (s);
426   set_error_literal (context, error, code, s);
427
428   g_free (s);
429   g_free (s_valid);
430 }
431
432 static void
433 propagate_error (GMarkupParseContext  *context,
434                  GError              **dest,
435                  GError               *src)
436 {
437   if (context->flags & G_MARKUP_PREFIX_ERROR_POSITION)
438     g_prefix_error (&src,
439                     _("Error on line %d char %d: "),
440                     context->line_number,
441                     context->char_number);
442
443   mark_error (context, src);
444
445   g_propagate_error (dest, src);
446 }
447
448 #define IS_COMMON_NAME_END_CHAR(c) \
449   ((c) == '=' || (c) == '/' || (c) == '>' || (c) == ' ')
450
451 static gboolean
452 slow_name_validate (GMarkupParseContext  *context,
453                     const gchar          *name,
454                     GError              **error)
455 {
456   const gchar *p = name;
457
458   if (!g_utf8_validate (name, strlen (name), NULL))
459     {
460       set_error (context, error, G_MARKUP_ERROR_BAD_UTF8,
461                  _("Invalid UTF-8 encoded text in name - not valid '%s'"), name);
462       return FALSE;
463     }
464
465   if (!(g_ascii_isalpha (*p) ||
466         (!IS_COMMON_NAME_END_CHAR (*p) &&
467          (*p == '_' ||
468           *p == ':' ||
469           g_unichar_isalpha (g_utf8_get_char (p))))))
470     {
471       set_error (context, error, G_MARKUP_ERROR_PARSE,
472                  _("'%s' is not a valid name"), name);
473       return FALSE;
474     }
475
476   for (p = g_utf8_next_char (name); *p != '\0'; p = g_utf8_next_char (p))
477     {
478       /* is_name_char */
479       if (!(g_ascii_isalnum (*p) ||
480             (!IS_COMMON_NAME_END_CHAR (*p) &&
481              (*p == '.' ||
482               *p == '-' ||
483               *p == '_' ||
484               *p == ':' ||
485               g_unichar_isalpha (g_utf8_get_char (p))))))
486         {
487           set_error (context, error, G_MARKUP_ERROR_PARSE,
488                      _("'%s' is not a valid name: '%c'"), name, *p);
489           return FALSE;
490         }
491     }
492   return TRUE;
493 }
494
495 /*
496  * Use me for elements, attributes etc.
497  */
498 static gboolean
499 name_validate (GMarkupParseContext  *context,
500                const gchar          *name,
501                GError              **error)
502 {
503   char mask;
504   const char *p;
505
506   /* name start char */
507   p = name;
508   if (G_UNLIKELY (IS_COMMON_NAME_END_CHAR (*p) ||
509                   !(g_ascii_isalpha (*p) || *p == '_' || *p == ':')))
510     goto slow_validate;
511
512   for (mask = *p++; *p != '\0'; p++)
513     {
514       mask |= *p;
515
516       /* is_name_char */
517       if (G_UNLIKELY (!(g_ascii_isalnum (*p) ||
518                         (!IS_COMMON_NAME_END_CHAR (*p) &&
519                          (*p == '.' ||
520                           *p == '-' ||
521                           *p == '_' ||
522                           *p == ':')))))
523         goto slow_validate;
524     }
525
526   if (mask & 0x80) /* un-common / non-ascii */
527     goto slow_validate;
528
529   return TRUE;
530
531  slow_validate:
532   return slow_name_validate (context, name, error);
533 }
534
535 static gboolean
536 text_validate (GMarkupParseContext  *context,
537                const gchar          *p,
538                gint                  len,
539                GError              **error)
540 {
541   if (!g_utf8_validate (p, len, NULL))
542     {
543       set_error (context, error, G_MARKUP_ERROR_BAD_UTF8,
544                  _("Invalid UTF-8 encoded text in name - not valid '%s'"), p);
545       return FALSE;
546     }
547   else
548     return TRUE;
549 }
550
551 static gchar*
552 char_str (gunichar c,
553           gchar   *buf)
554 {
555   memset (buf, 0, 8);
556   g_unichar_to_utf8 (c, buf);
557   return buf;
558 }
559
560 static gchar*
561 utf8_str (const gchar *utf8,
562           gchar       *buf)
563 {
564   char_str (g_utf8_get_char (utf8), buf);
565   return buf;
566 }
567
568 G_GNUC_PRINTF(5, 6)
569 static void
570 set_unescape_error (GMarkupParseContext  *context,
571                     GError              **error,
572                     const gchar          *remaining_text,
573                     GMarkupError          code,
574                     const gchar          *format,
575                     ...)
576 {
577   GError *tmp_error;
578   gchar *s;
579   va_list args;
580   gint remaining_newlines;
581   const gchar *p;
582
583   remaining_newlines = 0;
584   p = remaining_text;
585   while (*p != '\0')
586     {
587       if (*p == '\n')
588         ++remaining_newlines;
589       ++p;
590     }
591
592   va_start (args, format);
593   s = g_strdup_vprintf (format, args);
594   va_end (args);
595
596   tmp_error = g_error_new (G_MARKUP_ERROR,
597                            code,
598                            _("Error on line %d: %s"),
599                            context->line_number - remaining_newlines,
600                            s);
601
602   g_free (s);
603
604   mark_error (context, tmp_error);
605
606   g_propagate_error (error, tmp_error);
607 }
608
609 /*
610  * re-write the GString in-place, unescaping anything that escaped.
611  * most XML does not contain entities, or escaping.
612  */
613 static gboolean
614 unescape_gstring_inplace (GMarkupParseContext  *context,
615                           GString              *string,
616                           gboolean             *is_ascii,
617                           GError              **error)
618 {
619   char mask, *to;
620   int line_num = 1;
621   const char *from;
622   gboolean normalize_attribute;
623
624   *is_ascii = FALSE;
625
626   /* are we unescaping an attribute or not ? */
627   if (context->state == STATE_INSIDE_ATTRIBUTE_VALUE_SQ ||
628       context->state == STATE_INSIDE_ATTRIBUTE_VALUE_DQ)
629     normalize_attribute = TRUE;
630   else
631     normalize_attribute = FALSE;
632
633   /*
634    * Meeks' theorem: unescaping can only shrink text.
635    * for &lt; etc. this is obvious, for &#xffff; more
636    * thought is required, but this is patently so.
637    */
638   mask = 0;
639   for (from = to = string->str; *from != '\0'; from++, to++)
640     {
641       *to = *from;
642
643       mask |= *to;
644       if (*to == '\n')
645         line_num++;
646       if (normalize_attribute && (*to == '\t' || *to == '\n'))
647         *to = ' ';
648       if (*to == '\r')
649         {
650           *to = normalize_attribute ? ' ' : '\n';
651           if (from[1] == '\n')
652             from++;
653         }
654       if (*from == '&')
655         {
656           from++;
657           if (*from == '#')
658             {
659               gboolean is_hex = FALSE;
660               gulong l;
661               gchar *end = NULL;
662
663               from++;
664
665               if (*from == 'x')
666                 {
667                   is_hex = TRUE;
668                   from++;
669                 }
670
671               /* digit is between start and p */
672               errno = 0;
673               if (is_hex)
674                 l = strtoul (from, &end, 16);
675               else
676                 l = strtoul (from, &end, 10);
677
678               if (end == from || errno != 0)
679                 {
680                   set_unescape_error (context, error,
681                                       from, G_MARKUP_ERROR_PARSE,
682                                       _("Failed to parse '%-.*s', which "
683                                         "should have been a digit "
684                                         "inside a character reference "
685                                         "(&#234; for example) - perhaps "
686                                         "the digit is too large"),
687                                       (int)(end - from), from);
688                   return FALSE;
689                 }
690               else if (*end != ';')
691                 {
692                   set_unescape_error (context, error,
693                                       from, G_MARKUP_ERROR_PARSE,
694                                       _("Character reference did not end with a "
695                                         "semicolon; "
696                                         "most likely you used an ampersand "
697                                         "character without intending to start "
698                                         "an entity - escape ampersand as &amp;"));
699                   return FALSE;
700                 }
701               else
702                 {
703                   /* characters XML 1.1 permits */
704                   if ((0 < l && l <= 0xD7FF) ||
705                       (0xE000 <= l && l <= 0xFFFD) ||
706                       (0x10000 <= l && l <= 0x10FFFF))
707                     {
708                       gchar buf[8];
709                       char_str (l, buf);
710                       strcpy (to, buf);
711                       to += strlen (buf) - 1;
712                       from = end;
713                       if (l >= 0x80) /* not ascii */
714                         mask |= 0x80;
715                     }
716                   else
717                     {
718                       set_unescape_error (context, error,
719                                           from, G_MARKUP_ERROR_PARSE,
720                                           _("Character reference '%-.*s' does not "
721                                             "encode a permitted character"),
722                                           (int)(end - from), from);
723                       return FALSE;
724                     }
725                 }
726             }
727
728           else if (strncmp (from, "lt;", 3) == 0)
729             {
730               *to = '<';
731               from += 2;
732             }
733           else if (strncmp (from, "gt;", 3) == 0)
734             {
735               *to = '>';
736               from += 2;
737             }
738           else if (strncmp (from, "amp;", 4) == 0)
739             {
740               *to = '&';
741               from += 3;
742             }
743           else if (strncmp (from, "quot;", 5) == 0)
744             {
745               *to = '"';
746               from += 4;
747             }
748           else if (strncmp (from, "apos;", 5) == 0)
749             {
750               *to = '\'';
751               from += 4;
752             }
753           else
754             {
755               if (*from == ';')
756                 set_unescape_error (context, error,
757                                     from, G_MARKUP_ERROR_PARSE,
758                                     _("Empty entity '&;' seen; valid "
759                                       "entities are: &amp; &quot; &lt; &gt; &apos;"));
760               else
761                 {
762                   const char *end = strchr (from, ';');
763                   if (end)
764                     set_unescape_error (context, error,
765                                         from, G_MARKUP_ERROR_PARSE,
766                                         _("Entity name '%-.*s' is not known"),
767                                         (int)(end - from), from);
768                   else
769                     set_unescape_error (context, error,
770                                         from, G_MARKUP_ERROR_PARSE,
771                                         _("Entity did not end with a semicolon; "
772                                           "most likely you used an ampersand "
773                                           "character without intending to start "
774                                           "an entity - escape ampersand as &amp;"));
775                 }
776               return FALSE;
777             }
778         }
779     }
780
781   g_assert (to - string->str <= string->len);
782   if (to - string->str != string->len)
783     g_string_truncate (string, to - string->str);
784
785   *is_ascii = !(mask & 0x80);
786
787   return TRUE;
788 }
789
790 static inline gboolean
791 advance_char (GMarkupParseContext *context)
792 {
793   context->iter++;
794   context->char_number++;
795
796   if (G_UNLIKELY (context->iter == context->current_text_end))
797       return FALSE;
798
799   else if (G_UNLIKELY (*context->iter == '\n'))
800     {
801       context->line_number++;
802       context->char_number = 1;
803     }
804
805   return TRUE;
806 }
807
808 static inline gboolean
809 xml_isspace (char c)
810 {
811   return c == ' ' || c == '\t' || c == '\n' || c == '\r';
812 }
813
814 static void
815 skip_spaces (GMarkupParseContext *context)
816 {
817   do
818     {
819       if (!xml_isspace (*context->iter))
820         return;
821     }
822   while (advance_char (context));
823 }
824
825 static void
826 advance_to_name_end (GMarkupParseContext *context)
827 {
828   do
829     {
830       if (IS_COMMON_NAME_END_CHAR (*(context->iter)))
831         return;
832       if (xml_isspace (*(context->iter)))
833         return;
834     }
835   while (advance_char (context));
836 }
837
838 static void
839 release_chunk (GMarkupParseContext *context, GString *str)
840 {
841   GSList *node;
842   if (!str)
843     return;
844   if (str->allocated_len > 256)
845     { /* large strings are unusual and worth freeing */
846       g_string_free (str, TRUE);
847       return;
848     }
849   string_blank (str);
850   node = get_list_node (context, str);
851   context->spare_chunks = g_slist_concat (node, context->spare_chunks);
852 }
853
854 static void
855 add_to_partial (GMarkupParseContext *context,
856                 const gchar         *text_start,
857                 const gchar         *text_end)
858 {
859   if (context->partial_chunk == NULL)
860     { /* allocate a new chunk to parse into */
861
862       if (context->spare_chunks != NULL)
863         {
864           GSList *node = context->spare_chunks;
865           context->spare_chunks = g_slist_remove_link (context->spare_chunks, node);
866           context->partial_chunk = node->data;
867           free_list_node (context, node);
868         }
869       else
870         context->partial_chunk = g_string_sized_new (MAX (28, text_end - text_start));
871     }
872
873   if (text_start != text_end)
874     g_string_insert_len (context->partial_chunk, -1,
875                          text_start, text_end - text_start);
876 }
877
878 static inline void
879 truncate_partial (GMarkupParseContext *context)
880 {
881   if (context->partial_chunk != NULL)
882     string_blank (context->partial_chunk);
883 }
884
885 static inline const gchar*
886 current_element (GMarkupParseContext *context)
887 {
888   return context->tag_stack->data;
889 }
890
891 static void
892 pop_subparser_stack (GMarkupParseContext *context)
893 {
894   GMarkupRecursionTracker *tracker;
895
896   g_assert (context->subparser_stack);
897
898   tracker = context->subparser_stack->data;
899
900   context->awaiting_pop = TRUE;
901   context->held_user_data = context->user_data;
902
903   context->user_data = tracker->prev_user_data;
904   context->parser = tracker->prev_parser;
905   context->subparser_element = tracker->prev_element;
906   g_slice_free (GMarkupRecursionTracker, tracker);
907
908   context->subparser_stack = g_slist_delete_link (context->subparser_stack,
909                                                   context->subparser_stack);
910 }
911
912 static void
913 push_partial_as_tag (GMarkupParseContext *context)
914 {
915   GString *str = context->partial_chunk;
916   /* sadly, this is exported by gmarkup_get_element_stack as-is */
917   context->tag_stack = g_slist_concat (get_list_node (context, str->str), context->tag_stack);
918   context->tag_stack_gstr = g_slist_concat (get_list_node (context, str), context->tag_stack_gstr);
919   context->partial_chunk = NULL;
920 }
921
922 static void
923 pop_tag (GMarkupParseContext *context)
924 {
925   GSList *nodea, *nodeb;
926
927   nodea = context->tag_stack;
928   nodeb = context->tag_stack_gstr;
929   release_chunk (context, nodeb->data);
930   context->tag_stack = g_slist_remove_link (context->tag_stack, nodea);
931   context->tag_stack_gstr = g_slist_remove_link (context->tag_stack_gstr, nodeb);
932   free_list_node (context, nodea);
933   free_list_node (context, nodeb);
934 }
935
936 static void
937 possibly_finish_subparser (GMarkupParseContext *context)
938 {
939   if (current_element (context) == context->subparser_element)
940     pop_subparser_stack (context);
941 }
942
943 static void
944 ensure_no_outstanding_subparser (GMarkupParseContext *context)
945 {
946   if (context->awaiting_pop)
947     g_critical ("During the first end_element call after invoking a "
948                 "subparser you must pop the subparser stack and handle "
949                 "the freeing of the subparser user_data.  This can be "
950                 "done by calling the end function of the subparser.  "
951                 "Very probably, your program just leaked memory.");
952
953   /* let valgrind watch the pointer disappear... */
954   context->held_user_data = NULL;
955   context->awaiting_pop = FALSE;
956 }
957
958 static const gchar*
959 current_attribute (GMarkupParseContext *context)
960 {
961   g_assert (context->cur_attr >= 0);
962   return context->attr_names[context->cur_attr]->str;
963 }
964
965 static void
966 add_attribute (GMarkupParseContext *context, GString *str)
967 {
968   if (context->cur_attr + 2 >= context->alloc_attrs)
969     {
970       context->alloc_attrs += 5; /* silly magic number */
971       context->attr_names = g_realloc (context->attr_names, sizeof(GString*)*context->alloc_attrs);
972       context->attr_values = g_realloc (context->attr_values, sizeof(GString*)*context->alloc_attrs);
973     }
974   context->cur_attr++;
975   context->attr_names[context->cur_attr] = str;
976   context->attr_values[context->cur_attr] = NULL;
977   context->attr_names[context->cur_attr+1] = NULL;
978   context->attr_values[context->cur_attr+1] = NULL;
979 }
980
981 static void
982 clear_attributes (GMarkupParseContext *context)
983 {
984   /* Go ahead and free the attributes. */
985   for (; context->cur_attr >= 0; context->cur_attr--)
986     {
987       int pos = context->cur_attr;
988       release_chunk (context, context->attr_names[pos]);
989       release_chunk (context, context->attr_values[pos]);
990       context->attr_names[pos] = context->attr_values[pos] = NULL;
991     }
992   g_assert (context->cur_attr == -1);
993   g_assert (context->attr_names == NULL ||
994             context->attr_names[0] == NULL);
995   g_assert (context->attr_values == NULL ||
996             context->attr_values[0] == NULL);
997 }
998
999 /* This has to be a separate function to ensure the alloca's
1000  * are unwound on exit - otherwise we grow & blow the stack
1001  * with large documents
1002  */
1003 static inline void
1004 emit_start_element (GMarkupParseContext  *context,
1005                     GError              **error)
1006 {
1007   int i, j = 0;
1008   const gchar *start_name;
1009   const gchar **attr_names;
1010   const gchar **attr_values;
1011   GError *tmp_error;
1012
1013   /* In case we want to ignore qualified tags and we see that we have
1014    * one here, we push a subparser.  This will ignore all tags inside of
1015    * the qualified tag.
1016    *
1017    * We deal with the end of the subparser from emit_end_element.
1018    */
1019   if ((context->flags & G_MARKUP_IGNORE_QUALIFIED) && strchr (current_element (context), ':'))
1020     {
1021       static const GMarkupParser ignore_parser;
1022       g_markup_parse_context_push (context, &ignore_parser, NULL);
1023       clear_attributes (context);
1024       return;
1025     }
1026
1027   attr_names = g_newa (const gchar *, context->cur_attr + 2);
1028   attr_values = g_newa (const gchar *, context->cur_attr + 2);
1029   for (i = 0; i < context->cur_attr + 1; i++)
1030     {
1031       /* Possibly omit qualified attribute names from the list */
1032       if ((context->flags & G_MARKUP_IGNORE_QUALIFIED) && strchr (context->attr_names[i]->str, ':'))
1033         continue;
1034
1035       attr_names[j] = context->attr_names[i]->str;
1036       attr_values[j] = context->attr_values[i]->str;
1037       j++;
1038     }
1039   attr_names[j] = NULL;
1040   attr_values[j] = NULL;
1041
1042   /* Call user callback for element start */
1043   tmp_error = NULL;
1044   start_name = current_element (context);
1045
1046   if (context->parser->start_element &&
1047       name_validate (context, start_name, error))
1048     (* context->parser->start_element) (context,
1049                                         start_name,
1050                                         (const gchar **)attr_names,
1051                                         (const gchar **)attr_values,
1052                                         context->user_data,
1053                                         &tmp_error);
1054   clear_attributes (context);
1055
1056   if (tmp_error != NULL)
1057     propagate_error (context, error, tmp_error);
1058 }
1059
1060 static void
1061 emit_end_element (GMarkupParseContext  *context,
1062                   GError              **error)
1063 {
1064   /* We need to pop the tag stack and call the end_element
1065    * function, since this is the close tag
1066    */
1067   GError *tmp_error = NULL;
1068
1069   g_assert (context->tag_stack != NULL);
1070
1071   possibly_finish_subparser (context);
1072
1073   /* We might have just returned from our ignore subparser */
1074   if ((context->flags & G_MARKUP_IGNORE_QUALIFIED) && strchr (current_element (context), ':'))
1075     {
1076       g_markup_parse_context_pop (context);
1077       pop_tag (context);
1078       return;
1079     }
1080
1081   tmp_error = NULL;
1082   if (context->parser->end_element)
1083     (* context->parser->end_element) (context,
1084                                       current_element (context),
1085                                       context->user_data,
1086                                       &tmp_error);
1087
1088   ensure_no_outstanding_subparser (context);
1089
1090   if (tmp_error)
1091     {
1092       mark_error (context, tmp_error);
1093       g_propagate_error (error, tmp_error);
1094     }
1095
1096   pop_tag (context);
1097 }
1098
1099 /**
1100  * g_markup_parse_context_parse:
1101  * @context: a #GMarkupParseContext
1102  * @text: chunk of text to parse
1103  * @text_len: length of @text in bytes
1104  * @error: return location for a #GError
1105  *
1106  * Feed some data to the #GMarkupParseContext.
1107  *
1108  * The data need not be valid UTF-8; an error will be signaled if
1109  * it's invalid. The data need not be an entire document; you can
1110  * feed a document into the parser incrementally, via multiple calls
1111  * to this function. Typically, as you receive data from a network
1112  * connection or file, you feed each received chunk of data into this
1113  * function, aborting the process if an error occurs. Once an error
1114  * is reported, no further data may be fed to the #GMarkupParseContext;
1115  * all errors are fatal.
1116  *
1117  * Return value: %FALSE if an error occurred, %TRUE on success
1118  */
1119 gboolean
1120 g_markup_parse_context_parse (GMarkupParseContext  *context,
1121                               const gchar          *text,
1122                               gssize                text_len,
1123                               GError              **error)
1124 {
1125   g_return_val_if_fail (context != NULL, FALSE);
1126   g_return_val_if_fail (text != NULL, FALSE);
1127   g_return_val_if_fail (context->state != STATE_ERROR, FALSE);
1128   g_return_val_if_fail (!context->parsing, FALSE);
1129
1130   if (text_len < 0)
1131     text_len = strlen (text);
1132
1133   if (text_len == 0)
1134     return TRUE;
1135
1136   context->parsing = TRUE;
1137
1138
1139   context->current_text = text;
1140   context->current_text_len = text_len;
1141   context->current_text_end = context->current_text + text_len;
1142   context->iter = context->current_text;
1143   context->start = context->iter;
1144
1145   while (context->iter != context->current_text_end)
1146     {
1147       switch (context->state)
1148         {
1149         case STATE_START:
1150           /* Possible next state: AFTER_OPEN_ANGLE */
1151
1152           g_assert (context->tag_stack == NULL);
1153
1154           /* whitespace is ignored outside of any elements */
1155           skip_spaces (context);
1156
1157           if (context->iter != context->current_text_end)
1158             {
1159               if (*context->iter == '<')
1160                 {
1161                   /* Move after the open angle */
1162                   advance_char (context);
1163
1164                   context->state = STATE_AFTER_OPEN_ANGLE;
1165
1166                   /* this could start a passthrough */
1167                   context->start = context->iter;
1168
1169                   /* document is now non-empty */
1170                   context->document_empty = FALSE;
1171                 }
1172               else
1173                 {
1174                   set_error_literal (context,
1175                                      error,
1176                                      G_MARKUP_ERROR_PARSE,
1177                                      _("Document must begin with an element (e.g. <book>)"));
1178                 }
1179             }
1180           break;
1181
1182         case STATE_AFTER_OPEN_ANGLE:
1183           /* Possible next states: INSIDE_OPEN_TAG_NAME,
1184            *  AFTER_CLOSE_TAG_SLASH, INSIDE_PASSTHROUGH
1185            */
1186           if (*context->iter == '?' ||
1187               *context->iter == '!')
1188             {
1189               /* include < in the passthrough */
1190               const gchar *openangle = "<";
1191               add_to_partial (context, openangle, openangle + 1);
1192               context->start = context->iter;
1193               context->balance = 1;
1194               context->state = STATE_INSIDE_PASSTHROUGH;
1195             }
1196           else if (*context->iter == '/')
1197             {
1198               /* move after it */
1199               advance_char (context);
1200
1201               context->state = STATE_AFTER_CLOSE_TAG_SLASH;
1202             }
1203           else if (!IS_COMMON_NAME_END_CHAR (*(context->iter)))
1204             {
1205               context->state = STATE_INSIDE_OPEN_TAG_NAME;
1206
1207               /* start of tag name */
1208               context->start = context->iter;
1209             }
1210           else
1211             {
1212               gchar buf[8];
1213
1214               set_error (context,
1215                          error,
1216                          G_MARKUP_ERROR_PARSE,
1217                          _("'%s' is not a valid character following "
1218                            "a '<' character; it may not begin an "
1219                            "element name"),
1220                          utf8_str (context->iter, buf));
1221             }
1222           break;
1223
1224           /* The AFTER_CLOSE_ANGLE state is actually sort of
1225            * broken, because it doesn't correspond to a range
1226            * of characters in the input stream as the others do,
1227            * and thus makes things harder to conceptualize
1228            */
1229         case STATE_AFTER_CLOSE_ANGLE:
1230           /* Possible next states: INSIDE_TEXT, STATE_START */
1231           if (context->tag_stack == NULL)
1232             {
1233               context->start = NULL;
1234               context->state = STATE_START;
1235             }
1236           else
1237             {
1238               context->start = context->iter;
1239               context->state = STATE_INSIDE_TEXT;
1240             }
1241           break;
1242
1243         case STATE_AFTER_ELISION_SLASH:
1244           /* Possible next state: AFTER_CLOSE_ANGLE */
1245           if (*context->iter == '>')
1246             {
1247               /* move after the close angle */
1248               advance_char (context);
1249               context->state = STATE_AFTER_CLOSE_ANGLE;
1250               emit_end_element (context, error);
1251             }
1252           else
1253             {
1254               gchar buf[8];
1255
1256               set_error (context,
1257                          error,
1258                          G_MARKUP_ERROR_PARSE,
1259                          _("Odd character '%s', expected a '>' character "
1260                            "to end the empty-element tag '%s'"),
1261                          utf8_str (context->iter, buf),
1262                          current_element (context));
1263             }
1264           break;
1265
1266         case STATE_INSIDE_OPEN_TAG_NAME:
1267           /* Possible next states: BETWEEN_ATTRIBUTES */
1268
1269           /* if there's a partial chunk then it's the first part of the
1270            * tag name. If there's a context->start then it's the start
1271            * of the tag name in current_text, the partial chunk goes
1272            * before that start though.
1273            */
1274           advance_to_name_end (context);
1275
1276           if (context->iter == context->current_text_end)
1277             {
1278               /* The name hasn't necessarily ended. Merge with
1279                * partial chunk, leave state unchanged.
1280                */
1281               add_to_partial (context, context->start, context->iter);
1282             }
1283           else
1284             {
1285               /* The name has ended. Combine it with the partial chunk
1286                * if any; push it on the stack; enter next state.
1287                */
1288               add_to_partial (context, context->start, context->iter);
1289               push_partial_as_tag (context);
1290
1291               context->state = STATE_BETWEEN_ATTRIBUTES;
1292               context->start = NULL;
1293             }
1294           break;
1295
1296         case STATE_INSIDE_ATTRIBUTE_NAME:
1297           /* Possible next states: AFTER_ATTRIBUTE_NAME */
1298
1299           advance_to_name_end (context);
1300           add_to_partial (context, context->start, context->iter);
1301
1302           /* read the full name, if we enter the equals sign state
1303            * then add the attribute to the list (without the value),
1304            * otherwise store a partial chunk to be prepended later.
1305            */
1306           if (context->iter != context->current_text_end)
1307             context->state = STATE_AFTER_ATTRIBUTE_NAME;
1308           break;
1309
1310         case STATE_AFTER_ATTRIBUTE_NAME:
1311           /* Possible next states: AFTER_ATTRIBUTE_EQUALS_SIGN */
1312
1313           skip_spaces (context);
1314
1315           if (context->iter != context->current_text_end)
1316             {
1317               /* The name has ended. Combine it with the partial chunk
1318                * if any; push it on the stack; enter next state.
1319                */
1320               if (!name_validate (context, context->partial_chunk->str, error))
1321                 break;
1322
1323               add_attribute (context, context->partial_chunk);
1324
1325               context->partial_chunk = NULL;
1326               context->start = NULL;
1327
1328               if (*context->iter == '=')
1329                 {
1330                   advance_char (context);
1331                   context->state = STATE_AFTER_ATTRIBUTE_EQUALS_SIGN;
1332                 }
1333               else
1334                 {
1335                   gchar buf[8];
1336
1337                   set_error (context,
1338                              error,
1339                              G_MARKUP_ERROR_PARSE,
1340                              _("Odd character '%s', expected a '=' after "
1341                                "attribute name '%s' of element '%s'"),
1342                              utf8_str (context->iter, buf),
1343                              current_attribute (context),
1344                              current_element (context));
1345
1346                 }
1347             }
1348           break;
1349
1350         case STATE_BETWEEN_ATTRIBUTES:
1351           /* Possible next states: AFTER_CLOSE_ANGLE,
1352            * AFTER_ELISION_SLASH, INSIDE_ATTRIBUTE_NAME
1353            */
1354           skip_spaces (context);
1355
1356           if (context->iter != context->current_text_end)
1357             {
1358               if (*context->iter == '/')
1359                 {
1360                   advance_char (context);
1361                   context->state = STATE_AFTER_ELISION_SLASH;
1362                 }
1363               else if (*context->iter == '>')
1364                 {
1365                   advance_char (context);
1366                   context->state = STATE_AFTER_CLOSE_ANGLE;
1367                 }
1368               else if (!IS_COMMON_NAME_END_CHAR (*(context->iter)))
1369                 {
1370                   context->state = STATE_INSIDE_ATTRIBUTE_NAME;
1371                   /* start of attribute name */
1372                   context->start = context->iter;
1373                 }
1374               else
1375                 {
1376                   gchar buf[8];
1377
1378                   set_error (context,
1379                              error,
1380                              G_MARKUP_ERROR_PARSE,
1381                              _("Odd character '%s', expected a '>' or '/' "
1382                                "character to end the start tag of "
1383                                "element '%s', or optionally an attribute; "
1384                                "perhaps you used an invalid character in "
1385                                "an attribute name"),
1386                              utf8_str (context->iter, buf),
1387                              current_element (context));
1388                 }
1389
1390               /* If we're done with attributes, invoke
1391                * the start_element callback
1392                */
1393               if (context->state == STATE_AFTER_ELISION_SLASH ||
1394                   context->state == STATE_AFTER_CLOSE_ANGLE)
1395                 emit_start_element (context, error);
1396             }
1397           break;
1398
1399         case STATE_AFTER_ATTRIBUTE_EQUALS_SIGN:
1400           /* Possible next state: INSIDE_ATTRIBUTE_VALUE_[SQ/DQ] */
1401
1402           skip_spaces (context);
1403
1404           if (context->iter != context->current_text_end)
1405             {
1406               if (*context->iter == '"')
1407                 {
1408                   advance_char (context);
1409                   context->state = STATE_INSIDE_ATTRIBUTE_VALUE_DQ;
1410                   context->start = context->iter;
1411                 }
1412               else if (*context->iter == '\'')
1413                 {
1414                   advance_char (context);
1415                   context->state = STATE_INSIDE_ATTRIBUTE_VALUE_SQ;
1416                   context->start = context->iter;
1417                 }
1418               else
1419                 {
1420                   gchar buf[8];
1421
1422                   set_error (context,
1423                              error,
1424                              G_MARKUP_ERROR_PARSE,
1425                              _("Odd character '%s', expected an open quote mark "
1426                                "after the equals sign when giving value for "
1427                                "attribute '%s' of element '%s'"),
1428                              utf8_str (context->iter, buf),
1429                              current_attribute (context),
1430                              current_element (context));
1431                 }
1432             }
1433           break;
1434
1435         case STATE_INSIDE_ATTRIBUTE_VALUE_SQ:
1436         case STATE_INSIDE_ATTRIBUTE_VALUE_DQ:
1437           /* Possible next states: BETWEEN_ATTRIBUTES */
1438           {
1439             gchar delim;
1440
1441             if (context->state == STATE_INSIDE_ATTRIBUTE_VALUE_SQ)
1442               {
1443                 delim = '\'';
1444               }
1445             else
1446               {
1447                 delim = '"';
1448               }
1449
1450             do
1451               {
1452                 if (*context->iter == delim)
1453                   break;
1454               }
1455             while (advance_char (context));
1456           }
1457           if (context->iter == context->current_text_end)
1458             {
1459               /* The value hasn't necessarily ended. Merge with
1460                * partial chunk, leave state unchanged.
1461                */
1462               add_to_partial (context, context->start, context->iter);
1463             }
1464           else
1465             {
1466               gboolean is_ascii;
1467               /* The value has ended at the quote mark. Combine it
1468                * with the partial chunk if any; set it for the current
1469                * attribute.
1470                */
1471               add_to_partial (context, context->start, context->iter);
1472
1473               g_assert (context->cur_attr >= 0);
1474
1475               if (unescape_gstring_inplace (context, context->partial_chunk, &is_ascii, error) &&
1476                   (is_ascii || text_validate (context, context->partial_chunk->str,
1477                                               context->partial_chunk->len, error)))
1478                 {
1479                   /* success, advance past quote and set state. */
1480                   context->attr_values[context->cur_attr] = context->partial_chunk;
1481                   context->partial_chunk = NULL;
1482                   advance_char (context);
1483                   context->state = STATE_BETWEEN_ATTRIBUTES;
1484                   context->start = NULL;
1485                 }
1486
1487               truncate_partial (context);
1488             }
1489           break;
1490
1491         case STATE_INSIDE_TEXT:
1492           /* Possible next states: AFTER_OPEN_ANGLE */
1493           do
1494             {
1495               if (*context->iter == '<')
1496                 break;
1497             }
1498           while (advance_char (context));
1499
1500           /* The text hasn't necessarily ended. Merge with
1501            * partial chunk, leave state unchanged.
1502            */
1503
1504           add_to_partial (context, context->start, context->iter);
1505
1506           if (context->iter != context->current_text_end)
1507             {
1508               gboolean is_ascii;
1509
1510               /* The text has ended at the open angle. Call the text
1511                * callback.
1512                */
1513               if (unescape_gstring_inplace (context, context->partial_chunk, &is_ascii, error) &&
1514                   (is_ascii || text_validate (context, context->partial_chunk->str,
1515                                               context->partial_chunk->len, error)))
1516                 {
1517                   GError *tmp_error = NULL;
1518
1519                   if (context->parser->text)
1520                     (*context->parser->text) (context,
1521                                               context->partial_chunk->str,
1522                                               context->partial_chunk->len,
1523                                               context->user_data,
1524                                               &tmp_error);
1525
1526                   if (tmp_error == NULL)
1527                     {
1528                       /* advance past open angle and set state. */
1529                       advance_char (context);
1530                       context->state = STATE_AFTER_OPEN_ANGLE;
1531                       /* could begin a passthrough */
1532                       context->start = context->iter;
1533                     }
1534                   else
1535                     propagate_error (context, error, tmp_error);
1536                 }
1537
1538               truncate_partial (context);
1539             }
1540           break;
1541
1542         case STATE_AFTER_CLOSE_TAG_SLASH:
1543           /* Possible next state: INSIDE_CLOSE_TAG_NAME */
1544           if (!IS_COMMON_NAME_END_CHAR (*(context->iter)))
1545             {
1546               context->state = STATE_INSIDE_CLOSE_TAG_NAME;
1547
1548               /* start of tag name */
1549               context->start = context->iter;
1550             }
1551           else
1552             {
1553               gchar buf[8];
1554
1555               set_error (context,
1556                          error,
1557                          G_MARKUP_ERROR_PARSE,
1558                          _("'%s' is not a valid character following "
1559                            "the characters '</'; '%s' may not begin an "
1560                            "element name"),
1561                          utf8_str (context->iter, buf),
1562                          utf8_str (context->iter, buf));
1563             }
1564           break;
1565
1566         case STATE_INSIDE_CLOSE_TAG_NAME:
1567           /* Possible next state: AFTER_CLOSE_TAG_NAME */
1568           advance_to_name_end (context);
1569           add_to_partial (context, context->start, context->iter);
1570
1571           if (context->iter != context->current_text_end)
1572             context->state = STATE_AFTER_CLOSE_TAG_NAME;
1573           break;
1574
1575         case STATE_AFTER_CLOSE_TAG_NAME:
1576           /* Possible next state: AFTER_CLOSE_TAG_SLASH */
1577
1578           skip_spaces (context);
1579
1580           if (context->iter != context->current_text_end)
1581             {
1582               GString *close_name;
1583
1584               close_name = context->partial_chunk;
1585               context->partial_chunk = NULL;
1586
1587               if (*context->iter != '>')
1588                 {
1589                   gchar buf[8];
1590
1591                   set_error (context,
1592                              error,
1593                              G_MARKUP_ERROR_PARSE,
1594                              _("'%s' is not a valid character following "
1595                                "the close element name '%s'; the allowed "
1596                                "character is '>'"),
1597                              utf8_str (context->iter, buf),
1598                              close_name->str);
1599                 }
1600               else if (context->tag_stack == NULL)
1601                 {
1602                   set_error (context,
1603                              error,
1604                              G_MARKUP_ERROR_PARSE,
1605                              _("Element '%s' was closed, no element "
1606                                "is currently open"),
1607                              close_name->str);
1608                 }
1609               else if (strcmp (close_name->str, current_element (context)) != 0)
1610                 {
1611                   set_error (context,
1612                              error,
1613                              G_MARKUP_ERROR_PARSE,
1614                              _("Element '%s' was closed, but the currently "
1615                                "open element is '%s'"),
1616                              close_name->str,
1617                              current_element (context));
1618                 }
1619               else
1620                 {
1621                   advance_char (context);
1622                   context->state = STATE_AFTER_CLOSE_ANGLE;
1623                   context->start = NULL;
1624
1625                   emit_end_element (context, error);
1626                 }
1627               context->partial_chunk = close_name;
1628               truncate_partial (context);
1629             }
1630           break;
1631
1632         case STATE_INSIDE_PASSTHROUGH:
1633           /* Possible next state: AFTER_CLOSE_ANGLE */
1634           do
1635             {
1636               if (*context->iter == '<')
1637                 context->balance++;
1638               if (*context->iter == '>')
1639                 {
1640                   gchar *str;
1641                   gsize len;
1642
1643                   context->balance--;
1644                   add_to_partial (context, context->start, context->iter);
1645                   context->start = context->iter;
1646
1647                   str = context->partial_chunk->str;
1648                   len = context->partial_chunk->len;
1649
1650                   if (str[1] == '?' && str[len - 1] == '?')
1651                     break;
1652                   if (strncmp (str, "<!--", 4) == 0 &&
1653                       strcmp (str + len - 2, "--") == 0)
1654                     break;
1655                   if (strncmp (str, "<![CDATA[", 9) == 0 &&
1656                       strcmp (str + len - 2, "]]") == 0)
1657                     break;
1658                   if (strncmp (str, "<!DOCTYPE", 9) == 0 &&
1659                       context->balance == 0)
1660                     break;
1661                 }
1662             }
1663           while (advance_char (context));
1664
1665           if (context->iter == context->current_text_end)
1666             {
1667               /* The passthrough hasn't necessarily ended. Merge with
1668                * partial chunk, leave state unchanged.
1669                */
1670                add_to_partial (context, context->start, context->iter);
1671             }
1672           else
1673             {
1674               /* The passthrough has ended at the close angle. Combine
1675                * it with the partial chunk if any. Call the passthrough
1676                * callback. Note that the open/close angles are
1677                * included in the text of the passthrough.
1678                */
1679               GError *tmp_error = NULL;
1680
1681               advance_char (context); /* advance past close angle */
1682               add_to_partial (context, context->start, context->iter);
1683
1684               if (context->flags & G_MARKUP_TREAT_CDATA_AS_TEXT &&
1685                   strncmp (context->partial_chunk->str, "<![CDATA[", 9) == 0)
1686                 {
1687                   if (context->parser->text &&
1688                       text_validate (context,
1689                                      context->partial_chunk->str + 9,
1690                                      context->partial_chunk->len - 12,
1691                                      error))
1692                     (*context->parser->text) (context,
1693                                               context->partial_chunk->str + 9,
1694                                               context->partial_chunk->len - 12,
1695                                               context->user_data,
1696                                               &tmp_error);
1697                 }
1698               else if (context->parser->passthrough &&
1699                        text_validate (context,
1700                                       context->partial_chunk->str,
1701                                       context->partial_chunk->len,
1702                                       error))
1703                 (*context->parser->passthrough) (context,
1704                                                  context->partial_chunk->str,
1705                                                  context->partial_chunk->len,
1706                                                  context->user_data,
1707                                                  &tmp_error);
1708
1709               truncate_partial (context);
1710
1711               if (tmp_error == NULL)
1712                 {
1713                   context->state = STATE_AFTER_CLOSE_ANGLE;
1714                   context->start = context->iter; /* could begin text */
1715                 }
1716               else
1717                 propagate_error (context, error, tmp_error);
1718             }
1719           break;
1720
1721         case STATE_ERROR:
1722           goto finished;
1723           break;
1724
1725         default:
1726           g_assert_not_reached ();
1727           break;
1728         }
1729     }
1730
1731  finished:
1732   context->parsing = FALSE;
1733
1734   return context->state != STATE_ERROR;
1735 }
1736
1737 /**
1738  * g_markup_parse_context_end_parse:
1739  * @context: a #GMarkupParseContext
1740  * @error: return location for a #GError
1741  *
1742  * Signals to the #GMarkupParseContext that all data has been
1743  * fed into the parse context with g_markup_parse_context_parse().
1744  *
1745  * This function reports an error if the document isn't complete,
1746  * for example if elements are still open.
1747  *
1748  * Return value: %TRUE on success, %FALSE if an error was set
1749  */
1750 gboolean
1751 g_markup_parse_context_end_parse (GMarkupParseContext  *context,
1752                                   GError              **error)
1753 {
1754   g_return_val_if_fail (context != NULL, FALSE);
1755   g_return_val_if_fail (!context->parsing, FALSE);
1756   g_return_val_if_fail (context->state != STATE_ERROR, FALSE);
1757
1758   if (context->partial_chunk != NULL)
1759     {
1760       g_string_free (context->partial_chunk, TRUE);
1761       context->partial_chunk = NULL;
1762     }
1763
1764   if (context->document_empty)
1765     {
1766       set_error_literal (context, error, G_MARKUP_ERROR_EMPTY,
1767                          _("Document was empty or contained only whitespace"));
1768       return FALSE;
1769     }
1770
1771   context->parsing = TRUE;
1772
1773   switch (context->state)
1774     {
1775     case STATE_START:
1776       /* Nothing to do */
1777       break;
1778
1779     case STATE_AFTER_OPEN_ANGLE:
1780       set_error_literal (context, error, G_MARKUP_ERROR_PARSE,
1781                          _("Document ended unexpectedly just after an open angle bracket '<'"));
1782       break;
1783
1784     case STATE_AFTER_CLOSE_ANGLE:
1785       if (context->tag_stack != NULL)
1786         {
1787           /* Error message the same as for INSIDE_TEXT */
1788           set_error (context, error, G_MARKUP_ERROR_PARSE,
1789                      _("Document ended unexpectedly with elements still open - "
1790                        "'%s' was the last element opened"),
1791                      current_element (context));
1792         }
1793       break;
1794
1795     case STATE_AFTER_ELISION_SLASH:
1796       set_error (context, error, G_MARKUP_ERROR_PARSE,
1797                  _("Document ended unexpectedly, expected to see a close angle "
1798                    "bracket ending the tag <%s/>"), current_element (context));
1799       break;
1800
1801     case STATE_INSIDE_OPEN_TAG_NAME:
1802       set_error_literal (context, error, G_MARKUP_ERROR_PARSE,
1803                          _("Document ended unexpectedly inside an element name"));
1804       break;
1805
1806     case STATE_INSIDE_ATTRIBUTE_NAME:
1807     case STATE_AFTER_ATTRIBUTE_NAME:
1808       set_error_literal (context, error, G_MARKUP_ERROR_PARSE,
1809                          _("Document ended unexpectedly inside an attribute name"));
1810       break;
1811
1812     case STATE_BETWEEN_ATTRIBUTES:
1813       set_error_literal (context, error, G_MARKUP_ERROR_PARSE,
1814                          _("Document ended unexpectedly inside an element-opening "
1815                            "tag."));
1816       break;
1817
1818     case STATE_AFTER_ATTRIBUTE_EQUALS_SIGN:
1819       set_error_literal (context, error, G_MARKUP_ERROR_PARSE,
1820                          _("Document ended unexpectedly after the equals sign "
1821                            "following an attribute name; no attribute value"));
1822       break;
1823
1824     case STATE_INSIDE_ATTRIBUTE_VALUE_SQ:
1825     case STATE_INSIDE_ATTRIBUTE_VALUE_DQ:
1826       set_error_literal (context, error, G_MARKUP_ERROR_PARSE,
1827                          _("Document ended unexpectedly while inside an attribute "
1828                            "value"));
1829       break;
1830
1831     case STATE_INSIDE_TEXT:
1832       g_assert (context->tag_stack != NULL);
1833       set_error (context, error, G_MARKUP_ERROR_PARSE,
1834                  _("Document ended unexpectedly with elements still open - "
1835                    "'%s' was the last element opened"),
1836                  current_element (context));
1837       break;
1838
1839     case STATE_AFTER_CLOSE_TAG_SLASH:
1840     case STATE_INSIDE_CLOSE_TAG_NAME:
1841     case STATE_AFTER_CLOSE_TAG_NAME:
1842       set_error (context, error, G_MARKUP_ERROR_PARSE,
1843                  _("Document ended unexpectedly inside the close tag for "
1844                    "element '%s'"), current_element (context));
1845       break;
1846
1847     case STATE_INSIDE_PASSTHROUGH:
1848       set_error_literal (context, error, G_MARKUP_ERROR_PARSE,
1849                          _("Document ended unexpectedly inside a comment or "
1850                            "processing instruction"));
1851       break;
1852
1853     case STATE_ERROR:
1854     default:
1855       g_assert_not_reached ();
1856       break;
1857     }
1858
1859   context->parsing = FALSE;
1860
1861   return context->state != STATE_ERROR;
1862 }
1863
1864 /**
1865  * g_markup_parse_context_get_element:
1866  * @context: a #GMarkupParseContext
1867  *
1868  * Retrieves the name of the currently open element.
1869  *
1870  * If called from the start_element or end_element handlers this will
1871  * give the element_name as passed to those functions. For the parent
1872  * elements, see g_markup_parse_context_get_element_stack().
1873  *
1874  * Returns: the name of the currently open element, or %NULL
1875  *
1876  * Since: 2.2
1877  */
1878 const gchar *
1879 g_markup_parse_context_get_element (GMarkupParseContext *context)
1880 {
1881   g_return_val_if_fail (context != NULL, NULL);
1882
1883   if (context->tag_stack == NULL)
1884     return NULL;
1885   else
1886     return current_element (context);
1887 }
1888
1889 /**
1890  * g_markup_parse_context_get_element_stack:
1891  * @context: a #GMarkupParseContext
1892  *
1893  * Retrieves the element stack from the internal state of the parser.
1894  *
1895  * The returned #GSList is a list of strings where the first item is
1896  * the currently open tag (as would be returned by
1897  * g_markup_parse_context_get_element()) and the next item is its
1898  * immediate parent.
1899  *
1900  * This function is intended to be used in the start_element and
1901  * end_element handlers where g_markup_parse_context_get_element()
1902  * would merely return the name of the element that is being
1903  * processed.
1904  *
1905  * Returns: the element stack, which must not be modified
1906  *
1907  * Since: 2.16
1908  */
1909 const GSList *
1910 g_markup_parse_context_get_element_stack (GMarkupParseContext *context)
1911 {
1912   g_return_val_if_fail (context != NULL, NULL);
1913   return context->tag_stack;
1914 }
1915
1916 /**
1917  * g_markup_parse_context_get_position:
1918  * @context: a #GMarkupParseContext
1919  * @line_number: (allow-none): return location for a line number, or %NULL
1920  * @char_number: (allow-none): return location for a char-on-line number, or %NULL
1921  *
1922  * Retrieves the current line number and the number of the character on
1923  * that line. Intended for use in error messages; there are no strict
1924  * semantics for what constitutes the "current" line number other than
1925  * "the best number we could come up with for error messages."
1926  */
1927 void
1928 g_markup_parse_context_get_position (GMarkupParseContext *context,
1929                                      gint                *line_number,
1930                                      gint                *char_number)
1931 {
1932   g_return_if_fail (context != NULL);
1933
1934   if (line_number)
1935     *line_number = context->line_number;
1936
1937   if (char_number)
1938     *char_number = context->char_number;
1939 }
1940
1941 /**
1942  * g_markup_parse_context_get_user_data:
1943  * @context: a #GMarkupParseContext
1944  *
1945  * Returns the user_data associated with @context.
1946  *
1947  * This will either be the user_data that was provided to
1948  * g_markup_parse_context_new() or to the most recent call
1949  * of g_markup_parse_context_push().
1950  *
1951  * Returns: the provided user_data. The returned data belongs to
1952  *     the markup context and will be freed when
1953  *     g_markup_parse_context_free() is called.
1954  *
1955  * Since: 2.18
1956  */
1957 gpointer
1958 g_markup_parse_context_get_user_data (GMarkupParseContext *context)
1959 {
1960   return context->user_data;
1961 }
1962
1963 /**
1964  * g_markup_parse_context_push:
1965  * @context: a #GMarkupParseContext
1966  * @parser: a #GMarkupParser
1967  * @user_data: user data to pass to #GMarkupParser functions
1968  *
1969  * Temporarily redirects markup data to a sub-parser.
1970  *
1971  * This function may only be called from the start_element handler of
1972  * a #GMarkupParser. It must be matched with a corresponding call to
1973  * g_markup_parse_context_pop() in the matching end_element handler
1974  * (except in the case that the parser aborts due to an error).
1975  *
1976  * All tags, text and other data between the matching tags is
1977  * redirected to the subparser given by @parser. @user_data is used
1978  * as the user_data for that parser. @user_data is also passed to the
1979  * error callback in the event that an error occurs. This includes
1980  * errors that occur in subparsers of the subparser.
1981  *
1982  * The end tag matching the start tag for which this call was made is
1983  * handled by the previous parser (which is given its own user_data)
1984  * which is why g_markup_parse_context_pop() is provided to allow "one
1985  * last access" to the @user_data provided to this function. In the
1986  * case of error, the @user_data provided here is passed directly to
1987  * the error callback of the subparser and g_markup_parse_context_pop()
1988  * should not be called. In either case, if @user_data was allocated
1989  * then it ought to be freed from both of these locations.
1990  *
1991  * This function is not intended to be directly called by users
1992  * interested in invoking subparsers. Instead, it is intended to be
1993  * used by the subparsers themselves to implement a higher-level
1994  * interface.
1995  *
1996  * As an example, see the following implementation of a simple
1997  * parser that counts the number of tags encountered.
1998  *
1999  * |[<!-- language="C" --> 
2000  * typedef struct
2001  * {
2002  *   gint tag_count;
2003  * } CounterData;
2004  *
2005  * static void
2006  * counter_start_element (GMarkupParseContext  *context,
2007  *                        const gchar          *element_name,
2008  *                        const gchar         **attribute_names,
2009  *                        const gchar         **attribute_values,
2010  *                        gpointer              user_data,
2011  *                        GError              **error)
2012  * {
2013  *   CounterData *data = user_data;
2014  *
2015  *   data->tag_count++;
2016  * }
2017  *
2018  * static void
2019  * counter_error (GMarkupParseContext *context,
2020  *                GError              *error,
2021  *                gpointer             user_data)
2022  * {
2023  *   CounterData *data = user_data;
2024  *
2025  *   g_slice_free (CounterData, data);
2026  * }
2027  *
2028  * static GMarkupParser counter_subparser =
2029  * {
2030  *   counter_start_element,
2031  *   NULL,
2032  *   NULL,
2033  *   NULL,
2034  *   counter_error
2035  * };
2036  * ]|
2037  *
2038  * In order to allow this parser to be easily used as a subparser, the
2039  * following interface is provided:
2040  *
2041  * |[<!-- language="C" --> 
2042  * void
2043  * start_counting (GMarkupParseContext *context)
2044  * {
2045  *   CounterData *data = g_slice_new (CounterData);
2046  *
2047  *   data->tag_count = 0;
2048  *   g_markup_parse_context_push (context, &counter_subparser, data);
2049  * }
2050  *
2051  * gint
2052  * end_counting (GMarkupParseContext *context)
2053  * {
2054  *   CounterData *data = g_markup_parse_context_pop (context);
2055  *   int result;
2056  *
2057  *   result = data->tag_count;
2058  *   g_slice_free (CounterData, data);
2059  *
2060  *   return result;
2061  * }
2062  * ]|
2063  *
2064  * The subparser would then be used as follows:
2065  *
2066  * |[<!-- language="C" --> 
2067  * static void start_element (context, element_name, ...)
2068  * {
2069  *   if (strcmp (element_name, "count-these") == 0)
2070  *     start_counting (context);
2071  *
2072  *   // else, handle other tags...
2073  * }
2074  *
2075  * static void end_element (context, element_name, ...)
2076  * {
2077  *   if (strcmp (element_name, "count-these") == 0)
2078  *     g_print ("Counted %d tags\n", end_counting (context));
2079  *
2080  *   // else, handle other tags...
2081  * }
2082  * ]|
2083  *
2084  * Since: 2.18
2085  **/
2086 void
2087 g_markup_parse_context_push (GMarkupParseContext *context,
2088                              const GMarkupParser *parser,
2089                              gpointer             user_data)
2090 {
2091   GMarkupRecursionTracker *tracker;
2092
2093   tracker = g_slice_new (GMarkupRecursionTracker);
2094   tracker->prev_element = context->subparser_element;
2095   tracker->prev_parser = context->parser;
2096   tracker->prev_user_data = context->user_data;
2097
2098   context->subparser_element = current_element (context);
2099   context->parser = parser;
2100   context->user_data = user_data;
2101
2102   context->subparser_stack = g_slist_prepend (context->subparser_stack,
2103                                               tracker);
2104 }
2105
2106 /**
2107  * g_markup_parse_context_pop:
2108  * @context: a #GMarkupParseContext
2109  *
2110  * Completes the process of a temporary sub-parser redirection.
2111  *
2112  * This function exists to collect the user_data allocated by a
2113  * matching call to g_markup_parse_context_push(). It must be called
2114  * in the end_element handler corresponding to the start_element
2115  * handler during which g_markup_parse_context_push() was called.
2116  * You must not call this function from the error callback -- the
2117  * @user_data is provided directly to the callback in that case.
2118  *
2119  * This function is not intended to be directly called by users
2120  * interested in invoking subparsers. Instead, it is intended to
2121  * be used by the subparsers themselves to implement a higher-level
2122  * interface.
2123  *
2124  * Returns: the user data passed to g_markup_parse_context_push()
2125  *
2126  * Since: 2.18
2127  */
2128 gpointer
2129 g_markup_parse_context_pop (GMarkupParseContext *context)
2130 {
2131   gpointer user_data;
2132
2133   if (!context->awaiting_pop)
2134     possibly_finish_subparser (context);
2135
2136   g_assert (context->awaiting_pop);
2137
2138   context->awaiting_pop = FALSE;
2139
2140   /* valgrind friendliness */
2141   user_data = context->held_user_data;
2142   context->held_user_data = NULL;
2143
2144   return user_data;
2145 }
2146
2147 static void
2148 append_escaped_text (GString     *str,
2149                      const gchar *text,
2150                      gssize       length)
2151 {
2152   const gchar *p;
2153   const gchar *end;
2154   gunichar c;
2155
2156   p = text;
2157   end = text + length;
2158
2159   while (p != end)
2160     {
2161       const gchar *next;
2162       next = g_utf8_next_char (p);
2163
2164       switch (*p)
2165         {
2166         case '&':
2167           g_string_append (str, "&amp;");
2168           break;
2169
2170         case '<':
2171           g_string_append (str, "&lt;");
2172           break;
2173
2174         case '>':
2175           g_string_append (str, "&gt;");
2176           break;
2177
2178         case '\'':
2179           g_string_append (str, "&apos;");
2180           break;
2181
2182         case '"':
2183           g_string_append (str, "&quot;");
2184           break;
2185
2186         default:
2187           c = g_utf8_get_char (p);
2188           if ((0x1 <= c && c <= 0x8) ||
2189               (0xb <= c && c  <= 0xc) ||
2190               (0xe <= c && c <= 0x1f) ||
2191               (0x7f <= c && c <= 0x84) ||
2192               (0x86 <= c && c <= 0x9f))
2193             g_string_append_printf (str, "&#x%x;", c);
2194           else
2195             g_string_append_len (str, p, next - p);
2196           break;
2197         }
2198
2199       p = next;
2200     }
2201 }
2202
2203 /**
2204  * g_markup_escape_text:
2205  * @text: some valid UTF-8 text
2206  * @length: length of @text in bytes, or -1 if the text is nul-terminated
2207  *
2208  * Escapes text so that the markup parser will parse it verbatim.
2209  * Less than, greater than, ampersand, etc. are replaced with the
2210  * corresponding entities. This function would typically be used
2211  * when writing out a file to be parsed with the markup parser.
2212  *
2213  * Note that this function doesn't protect whitespace and line endings
2214  * from being processed according to the XML rules for normalization
2215  * of line endings and attribute values.
2216  *
2217  * Note also that this function will produce character references in
2218  * the range of &#x1; ... &#x1f; for all control sequences
2219  * except for tabstop, newline and carriage return.  The character
2220  * references in this range are not valid XML 1.0, but they are
2221  * valid XML 1.1 and will be accepted by the GMarkup parser.
2222  *
2223  * Return value: a newly allocated string with the escaped text
2224  */
2225 gchar*
2226 g_markup_escape_text (const gchar *text,
2227                       gssize       length)
2228 {
2229   GString *str;
2230
2231   g_return_val_if_fail (text != NULL, NULL);
2232
2233   if (length < 0)
2234     length = strlen (text);
2235
2236   /* prealloc at least as long as original text */
2237   str = g_string_sized_new (length);
2238   append_escaped_text (str, text, length);
2239
2240   return g_string_free (str, FALSE);
2241 }
2242
2243 /*
2244  * find_conversion:
2245  * @format: a printf-style format string
2246  * @after: location to store a pointer to the character after
2247  *     the returned conversion. On a %NULL return, returns the
2248  *     pointer to the trailing NUL in the string
2249  *
2250  * Find the next conversion in a printf-style format string.
2251  * Partially based on code from printf-parser.c,
2252  * Copyright (C) 1999-2000, 2002-2003 Free Software Foundation, Inc.
2253  *
2254  * Return value: pointer to the next conversion in @format,
2255  *  or %NULL, if none.
2256  */
2257 static const char *
2258 find_conversion (const char  *format,
2259                  const char **after)
2260 {
2261   const char *start = format;
2262   const char *cp;
2263
2264   while (*start != '\0' && *start != '%')
2265     start++;
2266
2267   if (*start == '\0')
2268     {
2269       *after = start;
2270       return NULL;
2271     }
2272
2273   cp = start + 1;
2274
2275   if (*cp == '\0')
2276     {
2277       *after = cp;
2278       return NULL;
2279     }
2280
2281   /* Test for positional argument.  */
2282   if (*cp >= '0' && *cp <= '9')
2283     {
2284       const char *np;
2285
2286       for (np = cp; *np >= '0' && *np <= '9'; np++)
2287         ;
2288       if (*np == '$')
2289         cp = np + 1;
2290     }
2291
2292   /* Skip the flags.  */
2293   for (;;)
2294     {
2295       if (*cp == '\'' ||
2296           *cp == '-' ||
2297           *cp == '+' ||
2298           *cp == ' ' ||
2299           *cp == '#' ||
2300           *cp == '0')
2301         cp++;
2302       else
2303         break;
2304     }
2305
2306   /* Skip the field width.  */
2307   if (*cp == '*')
2308     {
2309       cp++;
2310
2311       /* Test for positional argument.  */
2312       if (*cp >= '0' && *cp <= '9')
2313         {
2314           const char *np;
2315
2316           for (np = cp; *np >= '0' && *np <= '9'; np++)
2317             ;
2318           if (*np == '$')
2319             cp = np + 1;
2320         }
2321     }
2322   else
2323     {
2324       for (; *cp >= '0' && *cp <= '9'; cp++)
2325         ;
2326     }
2327
2328   /* Skip the precision.  */
2329   if (*cp == '.')
2330     {
2331       cp++;
2332       if (*cp == '*')
2333         {
2334           /* Test for positional argument.  */
2335           if (*cp >= '0' && *cp <= '9')
2336             {
2337               const char *np;
2338
2339               for (np = cp; *np >= '0' && *np <= '9'; np++)
2340                 ;
2341               if (*np == '$')
2342                 cp = np + 1;
2343             }
2344         }
2345       else
2346         {
2347           for (; *cp >= '0' && *cp <= '9'; cp++)
2348             ;
2349         }
2350     }
2351
2352   /* Skip argument type/size specifiers.  */
2353   while (*cp == 'h' ||
2354          *cp == 'L' ||
2355          *cp == 'l' ||
2356          *cp == 'j' ||
2357          *cp == 'z' ||
2358          *cp == 'Z' ||
2359          *cp == 't')
2360     cp++;
2361
2362   /* Skip the conversion character.  */
2363   cp++;
2364
2365   *after = cp;
2366   return start;
2367 }
2368
2369 /**
2370  * g_markup_vprintf_escaped:
2371  * @format: printf() style format string
2372  * @args: variable argument list, similar to vprintf()
2373  *
2374  * Formats the data in @args according to @format, escaping
2375  * all string and character arguments in the fashion
2376  * of g_markup_escape_text(). See g_markup_printf_escaped().
2377  *
2378  * Return value: newly allocated result from formatting
2379  *  operation. Free with g_free().
2380  *
2381  * Since: 2.4
2382  */
2383 #pragma GCC diagnostic push
2384 #pragma GCC diagnostic ignored "-Wformat-nonliteral"
2385
2386 gchar *
2387 g_markup_vprintf_escaped (const gchar *format,
2388                           va_list      args)
2389 {
2390   GString *format1;
2391   GString *format2;
2392   GString *result = NULL;
2393   gchar *output1 = NULL;
2394   gchar *output2 = NULL;
2395   const char *p, *op1, *op2;
2396   va_list args2;
2397
2398   /* The technique here, is that we make two format strings that
2399    * have the identical conversions in the identical order to the
2400    * original strings, but differ in the text in-between. We
2401    * then use the normal g_strdup_vprintf() to format the arguments
2402    * with the two new format strings. By comparing the results,
2403    * we can figure out what segments of the output come from
2404    * the original format string, and what from the arguments,
2405    * and thus know what portions of the string to escape.
2406    *
2407    * For instance, for:
2408    *
2409    *  g_markup_printf_escaped ("%s ate %d apples", "Susan & Fred", 5);
2410    *
2411    * We form the two format strings "%sX%dX" and %sY%sY". The results
2412    * of formatting with those two strings are
2413    *
2414    * "%sX%dX" => "Susan & FredX5X"
2415    * "%sY%dY" => "Susan & FredY5Y"
2416    *
2417    * To find the span of the first argument, we find the first position
2418    * where the two arguments differ, which tells us that the first
2419    * argument formatted to "Susan & Fred". We then escape that
2420    * to "Susan & Fred" and join up with the intermediate portions
2421    * of the format string and the second argument to get
2422    * "Susan & Fred ate 5 apples".
2423    */
2424
2425   /* Create the two modified format strings
2426    */
2427   format1 = g_string_new (NULL);
2428   format2 = g_string_new (NULL);
2429   p = format;
2430   while (TRUE)
2431     {
2432       const char *after;
2433       const char *conv = find_conversion (p, &after);
2434       if (!conv)
2435         break;
2436
2437       g_string_append_len (format1, conv, after - conv);
2438       g_string_append_c (format1, 'X');
2439       g_string_append_len (format2, conv, after - conv);
2440       g_string_append_c (format2, 'Y');
2441
2442       p = after;
2443     }
2444
2445   /* Use them to format the arguments
2446    */
2447   G_VA_COPY (args2, args);
2448
2449   output1 = g_strdup_vprintf (format1->str, args);
2450
2451   if (!output1)
2452     {
2453       va_end (args2);
2454       goto cleanup;
2455     }
2456
2457   output2 = g_strdup_vprintf (format2->str, args2);
2458   va_end (args2);
2459   if (!output2)
2460     goto cleanup;
2461   result = g_string_new (NULL);
2462
2463   /* Iterate through the original format string again,
2464    * copying the non-conversion portions and the escaped
2465    * converted arguments to the output string.
2466    */
2467   op1 = output1;
2468   op2 = output2;
2469   p = format;
2470   while (TRUE)
2471     {
2472       const char *after;
2473       const char *output_start;
2474       const char *conv = find_conversion (p, &after);
2475       char *escaped;
2476
2477       if (!conv)        /* The end, after points to the trailing \0 */
2478         {
2479           g_string_append_len (result, p, after - p);
2480           break;
2481         }
2482
2483       g_string_append_len (result, p, conv - p);
2484       output_start = op1;
2485       while (*op1 == *op2)
2486         {
2487           op1++;
2488           op2++;
2489         }
2490
2491       escaped = g_markup_escape_text (output_start, op1 - output_start);
2492       g_string_append (result, escaped);
2493       g_free (escaped);
2494
2495       p = after;
2496       op1++;
2497       op2++;
2498     }
2499
2500  cleanup:
2501   g_string_free (format1, TRUE);
2502   g_string_free (format2, TRUE);
2503   g_free (output1);
2504   g_free (output2);
2505
2506   if (result)
2507     return g_string_free (result, FALSE);
2508   else
2509     return NULL;
2510 }
2511
2512 #pragma GCC diagnostic pop
2513
2514 /**
2515  * g_markup_printf_escaped:
2516  * @format: printf() style format string
2517  * @...: the arguments to insert in the format string
2518  *
2519  * Formats arguments according to @format, escaping
2520  * all string and character arguments in the fashion
2521  * of g_markup_escape_text(). This is useful when you
2522  * want to insert literal strings into XML-style markup
2523  * output, without having to worry that the strings
2524  * might themselves contain markup.
2525  *
2526  * |[<!-- language="C" --> 
2527  * const char *store = "Fortnum & Mason";
2528  * const char *item = "Tea";
2529  * char *output;
2530  * 
2531  * output = g_markup_printf_escaped ("<purchase>"
2532  *                                   "<store>%s</store>"
2533  *                                   "<item>%s</item>"
2534  *                                   "</purchase>",
2535  *                                   store, item);
2536  * ]|
2537  *
2538  * Return value: newly allocated result from formatting
2539  *    operation. Free with g_free().
2540  *
2541  * Since: 2.4
2542  */
2543 gchar *
2544 g_markup_printf_escaped (const gchar *format, ...)
2545 {
2546   char *result;
2547   va_list args;
2548
2549   va_start (args, format);
2550   result = g_markup_vprintf_escaped (format, args);
2551   va_end (args);
2552
2553   return result;
2554 }
2555
2556 static gboolean
2557 g_markup_parse_boolean (const char  *string,
2558                         gboolean    *value)
2559 {
2560   char const * const falses[] = { "false", "f", "no", "n", "0" };
2561   char const * const trues[] = { "true", "t", "yes", "y", "1" };
2562   int i;
2563
2564   for (i = 0; i < G_N_ELEMENTS (falses); i++)
2565     {
2566       if (g_ascii_strcasecmp (string, falses[i]) == 0)
2567         {
2568           if (value != NULL)
2569             *value = FALSE;
2570
2571           return TRUE;
2572         }
2573     }
2574
2575   for (i = 0; i < G_N_ELEMENTS (trues); i++)
2576     {
2577       if (g_ascii_strcasecmp (string, trues[i]) == 0)
2578         {
2579           if (value != NULL)
2580             *value = TRUE;
2581
2582           return TRUE;
2583         }
2584     }
2585
2586   return FALSE;
2587 }
2588
2589 /**
2590  * GMarkupCollectType:
2591  * @G_MARKUP_COLLECT_INVALID: used to terminate the list of attributes
2592  *     to collect
2593  * @G_MARKUP_COLLECT_STRING: collect the string pointer directly from
2594  *     the attribute_values[] array. Expects a parameter of type (const
2595  *     char **). If %G_MARKUP_COLLECT_OPTIONAL is specified and the
2596  *     attribute isn't present then the pointer will be set to %NULL
2597  * @G_MARKUP_COLLECT_STRDUP: as with %G_MARKUP_COLLECT_STRING, but
2598  *     expects a parameter of type (char **) and g_strdup()s the
2599  *     returned pointer. The pointer must be freed with g_free()
2600  * @G_MARKUP_COLLECT_BOOLEAN: expects a parameter of type (gboolean *)
2601  *     and parses the attribute value as a boolean. Sets %FALSE if the
2602  *     attribute isn't present. Valid boolean values consist of
2603  *     (case-insensitive) "false", "f", "no", "n", "0" and "true", "t",
2604  *     "yes", "y", "1"
2605  * @G_MARKUP_COLLECT_TRISTATE: as with %G_MARKUP_COLLECT_BOOLEAN, but
2606  *     in the case of a missing attribute a value is set that compares
2607  *     equal to neither %FALSE nor %TRUE G_MARKUP_COLLECT_OPTIONAL is
2608  *     implied
2609  * @G_MARKUP_COLLECT_OPTIONAL: can be bitwise ORed with the other fields.
2610  *     If present, allows the attribute not to appear. A default value
2611  *     is set depending on what value type is used
2612  *
2613  * A mixed enumerated type and flags field. You must specify one type
2614  * (string, strdup, boolean, tristate).  Additionally, you may  optionally
2615  * bitwise OR the type with the flag %G_MARKUP_COLLECT_OPTIONAL.
2616  *
2617  * It is likely that this enum will be extended in the future to
2618  * support other types.
2619  */
2620
2621 /**
2622  * g_markup_collect_attributes:
2623  * @element_name: the current tag name
2624  * @attribute_names: the attribute names
2625  * @attribute_values: the attribute values
2626  * @error: a pointer to a #GError or %NULL
2627  * @first_type: the #GMarkupCollectType of the first attribute
2628  * @first_attr: the name of the first attribute
2629  * @...: a pointer to the storage location of the first attribute
2630  *     (or %NULL), followed by more types names and pointers, ending
2631  *     with %G_MARKUP_COLLECT_INVALID
2632  *
2633  * Collects the attributes of the element from the data passed to the
2634  * #GMarkupParser start_element function, dealing with common error
2635  * conditions and supporting boolean values.
2636  *
2637  * This utility function is not required to write a parser but can save
2638  * a lot of typing.
2639  *
2640  * The @element_name, @attribute_names, @attribute_values and @error
2641  * parameters passed to the start_element callback should be passed
2642  * unmodified to this function.
2643  *
2644  * Following these arguments is a list of "supported" attributes to collect.
2645  * It is an error to specify multiple attributes with the same name. If any
2646  * attribute not in the list appears in the @attribute_names array then an
2647  * unknown attribute error will result.
2648  *
2649  * The #GMarkupCollectType field allows specifying the type of collection
2650  * to perform and if a given attribute must appear or is optional.
2651  *
2652  * The attribute name is simply the name of the attribute to collect.
2653  *
2654  * The pointer should be of the appropriate type (see the descriptions
2655  * under #GMarkupCollectType) and may be %NULL in case a particular
2656  * attribute is to be allowed but ignored.
2657  *
2658  * This function deals with issuing errors for missing attributes
2659  * (of type %G_MARKUP_ERROR_MISSING_ATTRIBUTE), unknown attributes
2660  * (of type %G_MARKUP_ERROR_UNKNOWN_ATTRIBUTE) and duplicate
2661  * attributes (of type %G_MARKUP_ERROR_INVALID_CONTENT) as well
2662  * as parse errors for boolean-valued attributes (again of type
2663  * %G_MARKUP_ERROR_INVALID_CONTENT). In all of these cases %FALSE
2664  * will be returned and @error will be set as appropriate.
2665  *
2666  * Return value: %TRUE if successful
2667  *
2668  * Since: 2.16
2669  **/
2670 gboolean
2671 g_markup_collect_attributes (const gchar         *element_name,
2672                              const gchar        **attribute_names,
2673                              const gchar        **attribute_values,
2674                              GError             **error,
2675                              GMarkupCollectType   first_type,
2676                              const gchar         *first_attr,
2677                              ...)
2678 {
2679   GMarkupCollectType type;
2680   const gchar *attr;
2681   guint64 collected;
2682   int written;
2683   va_list ap;
2684   int i;
2685
2686   type = first_type;
2687   attr = first_attr;
2688   collected = 0;
2689   written = 0;
2690
2691   va_start (ap, first_attr);
2692   while (type != G_MARKUP_COLLECT_INVALID)
2693     {
2694       gboolean mandatory;
2695       const gchar *value;
2696
2697       mandatory = !(type & G_MARKUP_COLLECT_OPTIONAL);
2698       type &= (G_MARKUP_COLLECT_OPTIONAL - 1);
2699
2700       /* tristate records a value != TRUE and != FALSE
2701        * for the case where the attribute is missing
2702        */
2703       if (type == G_MARKUP_COLLECT_TRISTATE)
2704         mandatory = FALSE;
2705
2706       for (i = 0; attribute_names[i]; i++)
2707         if (i >= 40 || !(collected & (G_GUINT64_CONSTANT(1) << i)))
2708           if (!strcmp (attribute_names[i], attr))
2709             break;
2710
2711       /* ISO C99 only promises that the user can pass up to 127 arguments.
2712        * Subtracting the first 4 arguments plus the final NULL and dividing
2713        * by 3 arguments per collected attribute, we are left with a maximum
2714        * number of supported attributes of (127 - 5) / 3 = 40.
2715        *
2716        * In reality, nobody is ever going to call us with anywhere close to
2717        * 40 attributes to collect, so it is safe to assume that if i > 40
2718        * then the user has given some invalid or repeated arguments.  These
2719        * problems will be caught and reported at the end of the function.
2720        *
2721        * We know at this point that we have an error, but we don't know
2722        * what error it is, so just continue...
2723        */
2724       if (i < 40)
2725         collected |= (G_GUINT64_CONSTANT(1) << i);
2726
2727       value = attribute_values[i];
2728
2729       if (value == NULL && mandatory)
2730         {
2731           g_set_error (error, G_MARKUP_ERROR,
2732                        G_MARKUP_ERROR_MISSING_ATTRIBUTE,
2733                        "element '%s' requires attribute '%s'",
2734                        element_name, attr);
2735
2736           va_end (ap);
2737           goto failure;
2738         }
2739
2740       switch (type)
2741         {
2742         case G_MARKUP_COLLECT_STRING:
2743           {
2744             const char **str_ptr;
2745
2746             str_ptr = va_arg (ap, const char **);
2747
2748             if (str_ptr != NULL)
2749               *str_ptr = value;
2750           }
2751           break;
2752
2753         case G_MARKUP_COLLECT_STRDUP:
2754           {
2755             char **str_ptr;
2756
2757             str_ptr = va_arg (ap, char **);
2758
2759             if (str_ptr != NULL)
2760               *str_ptr = g_strdup (value);
2761           }
2762           break;
2763
2764         case G_MARKUP_COLLECT_BOOLEAN:
2765         case G_MARKUP_COLLECT_TRISTATE:
2766           if (value == NULL)
2767             {
2768               gboolean *bool_ptr;
2769
2770               bool_ptr = va_arg (ap, gboolean *);
2771
2772               if (bool_ptr != NULL)
2773                 {
2774                   if (type == G_MARKUP_COLLECT_TRISTATE)
2775                     /* constructivists rejoice!
2776                      * neither false nor true...
2777                      */
2778                     *bool_ptr = -1;
2779
2780                   else /* G_MARKUP_COLLECT_BOOLEAN */
2781                     *bool_ptr = FALSE;
2782                 }
2783             }
2784           else
2785             {
2786               if (!g_markup_parse_boolean (value, va_arg (ap, gboolean *)))
2787                 {
2788                   g_set_error (error, G_MARKUP_ERROR,
2789                                G_MARKUP_ERROR_INVALID_CONTENT,
2790                                "element '%s', attribute '%s', value '%s' "
2791                                "cannot be parsed as a boolean value",
2792                                element_name, attr, value);
2793
2794                   va_end (ap);
2795                   goto failure;
2796                 }
2797             }
2798
2799           break;
2800
2801         default:
2802           g_assert_not_reached ();
2803         }
2804
2805       type = va_arg (ap, GMarkupCollectType);
2806       attr = va_arg (ap, const char *);
2807       written++;
2808     }
2809   va_end (ap);
2810
2811   /* ensure we collected all the arguments */
2812   for (i = 0; attribute_names[i]; i++)
2813     if ((collected & (G_GUINT64_CONSTANT(1) << i)) == 0)
2814       {
2815         /* attribute not collected:  could be caused by two things.
2816          *
2817          * 1) it doesn't exist in our list of attributes
2818          * 2) it existed but was matched by a duplicate attribute earlier
2819          *
2820          * find out.
2821          */
2822         int j;
2823
2824         for (j = 0; j < i; j++)
2825           if (strcmp (attribute_names[i], attribute_names[j]) == 0)
2826             /* duplicate! */
2827             break;
2828
2829         /* j is now the first occurrence of attribute_names[i] */
2830         if (i == j)
2831           g_set_error (error, G_MARKUP_ERROR,
2832                        G_MARKUP_ERROR_UNKNOWN_ATTRIBUTE,
2833                        "attribute '%s' invalid for element '%s'",
2834                        attribute_names[i], element_name);
2835         else
2836           g_set_error (error, G_MARKUP_ERROR,
2837                        G_MARKUP_ERROR_INVALID_CONTENT,
2838                        "attribute '%s' given multiple times for element '%s'",
2839                        attribute_names[i], element_name);
2840
2841         goto failure;
2842       }
2843
2844   return TRUE;
2845
2846 failure:
2847   /* replay the above to free allocations */
2848   type = first_type;
2849   attr = first_attr;
2850
2851   va_start (ap, first_attr);
2852   while (type != G_MARKUP_COLLECT_INVALID)
2853     {
2854       gpointer ptr;
2855
2856       ptr = va_arg (ap, gpointer);
2857
2858       if (ptr != NULL)
2859         {
2860           switch (type & (G_MARKUP_COLLECT_OPTIONAL - 1))
2861             {
2862             case G_MARKUP_COLLECT_STRDUP:
2863               if (written)
2864                 g_free (*(char **) ptr);
2865
2866             case G_MARKUP_COLLECT_STRING:
2867               *(char **) ptr = NULL;
2868               break;
2869
2870             case G_MARKUP_COLLECT_BOOLEAN:
2871               *(gboolean *) ptr = FALSE;
2872               break;
2873
2874             case G_MARKUP_COLLECT_TRISTATE:
2875               *(gboolean *) ptr = -1;
2876               break;
2877             }
2878         }
2879
2880       type = va_arg (ap, GMarkupCollectType);
2881       attr = va_arg (ap, const char *);
2882     }
2883   va_end (ap);
2884
2885   return FALSE;
2886 }