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