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