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