Coverage Report

Created: 2026-10-19 06:44

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/irssi/subprojects/glib-2.74.7/glib/gmarkup.c
Line
Count
Source
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
0
{
179
0
  GSList *node;
180
0
  if (context->spare_list_nodes != NULL)
181
0
    {
182
0
      node = context->spare_list_nodes;
183
0
      context->spare_list_nodes = g_slist_remove_link (context->spare_list_nodes, node);
184
0
    }
185
0
  else
186
0
    node = g_slist_alloc();
187
0
  node->data = data;
188
0
  return node;
189
0
}
190
191
static void
192
free_list_node (GMarkupParseContext *context, GSList *node)
193
0
{
194
0
  node->data = NULL;
195
0
  context->spare_list_nodes = g_slist_concat (node, context->spare_list_nodes);
196
0
}
197
198
static inline void
199
string_blank (GString *string)
200
0
{
201
0
  string->str[0] = '\0';
202
0
  string->len = 0;
203
0
}
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
0
{
227
0
  GMarkupParseContext *context;
228
229
0
  g_return_val_if_fail (parser != NULL, NULL);
230
231
0
  context = g_new (GMarkupParseContext, 1);
232
233
0
  context->ref_count = 1;
234
0
  context->parser = parser;
235
0
  context->flags = flags;
236
0
  context->user_data = user_data;
237
0
  context->dnotify = user_data_dnotify;
238
239
0
  context->line_number = 1;
240
0
  context->char_number = 1;
241
242
0
  context->partial_chunk = NULL;
243
0
  context->spare_chunks = NULL;
244
0
  context->spare_list_nodes = NULL;
245
246
0
  context->state = STATE_START;
247
0
  context->tag_stack = NULL;
248
0
  context->tag_stack_gstr = NULL;
249
0
  context->attr_names = NULL;
250
0
  context->attr_values = NULL;
251
0
  context->cur_attr = -1;
252
0
  context->alloc_attrs = 0;
253
254
0
  context->current_text = NULL;
255
0
  context->current_text_len = -1;
256
0
  context->current_text_end = NULL;
257
258
0
  context->start = NULL;
259
0
  context->iter = NULL;
260
261
0
  context->document_empty = TRUE;
262
0
  context->parsing = FALSE;
263
264
0
  context->awaiting_pop = FALSE;
265
0
  context->subparser_stack = NULL;
266
0
  context->subparser_element = NULL;
267
268
  /* this is only looked at if awaiting_pop = TRUE.  initialise anyway. */
269
0
  context->held_user_data = NULL;
270
271
0
  context->balance = 0;
272
273
0
  return context;
274
0
}
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
0
{
289
0
  g_return_val_if_fail (context != NULL, NULL);
290
0
  g_return_val_if_fail (context->ref_count > 0, NULL);
291
292
0
  g_atomic_int_inc (&context->ref_count);
293
294
0
  return context;
295
0
}
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
0
{
309
0
  g_return_if_fail (context != NULL);
310
0
  g_return_if_fail (context->ref_count > 0);
311
312
0
  if (g_atomic_int_dec_and_test (&context->ref_count))
313
0
    g_markup_parse_context_free (context);
314
0
}
315
316
static void
317
string_full_free (gpointer ptr)
318
0
{
319
0
  g_string_free (ptr, TRUE);
320
0
}
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
0
{
336
0
  g_return_if_fail (context != NULL);
337
0
  g_return_if_fail (!context->parsing);
338
0
  g_return_if_fail (!context->subparser_stack);
339
0
  g_return_if_fail (!context->awaiting_pop);
340
341
0
  if (context->dnotify)
342
0
    (* context->dnotify) (context->user_data);
343
344
0
  clear_attributes (context);
345
0
  g_free (context->attr_names);
346
0
  g_free (context->attr_values);
347
348
0
  g_slist_free_full (context->tag_stack_gstr, string_full_free);
349
0
  g_slist_free (context->tag_stack);
350
351
0
  g_slist_free_full (context->spare_chunks, string_full_free);
352
0
  g_slist_free (context->spare_list_nodes);
353
354
0
  if (context->partial_chunk)
355
0
    g_string_free (context->partial_chunk, TRUE);
356
357
0
  g_free (context);
358
0
}
359
360
static void pop_subparser_stack (GMarkupParseContext *context);
361
362
static void
363
mark_error (GMarkupParseContext *context,
364
            GError              *error)
365
0
{
366
0
  context->state = STATE_ERROR;
367
368
0
  if (context->parser->error)
369
0
    (*context->parser->error) (context, error, context->user_data);
370
371
  /* report the error all the way up to free all the user-data */
372
0
  while (context->subparser_stack)
373
0
    {
374
0
      pop_subparser_stack (context);
375
0
      context->awaiting_pop = FALSE; /* already been freed */
376
377
0
      if (context->parser->error)
378
0
        (*context->parser->error) (context, error, context->user_data);
379
0
    }
380
0
}
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
0
{
395
0
  GError *tmp_error;
396
397
0
  tmp_error = g_error_new_literal (G_MARKUP_ERROR, code, message);
398
399
0
  g_prefix_error (&tmp_error,
400
0
                  _("Error on line %d char %d: "),
401
0
                  context->line_number,
402
0
                  context->char_number);
403
404
0
  mark_error (context, tmp_error);
405
406
0
  g_propagate_error (error, tmp_error);
407
0
}
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
0
{
417
0
  gchar *s;
418
0
  gchar *s_valid;
419
0
  va_list args;
420
421
0
  va_start (args, format);
422
0
  s = g_strdup_vprintf (format, args);
423
0
  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
0
  s_valid = g_utf8_make_valid (s, -1);
429
0
  set_error_literal (context, error, code, s);
430
431
0
  g_free (s);
432
0
  g_free (s_valid);
433
0
}
434
435
static void
436
propagate_error (GMarkupParseContext  *context,
437
                 GError              **dest,
438
                 GError               *src)
439
0
{
440
0
  if (context->flags & G_MARKUP_PREFIX_ERROR_POSITION)
441
0
    g_prefix_error (&src,
442
0
                    _("Error on line %d char %d: "),
443
0
                    context->line_number,
444
0
                    context->char_number);
445
446
0
  mark_error (context, src);
447
448
0
  g_propagate_error (dest, src);
449
0
}
450
451
#define IS_COMMON_NAME_END_CHAR(c) \
452
0
  ((c) == '=' || (c) == '/' || (c) == '>' || (c) == ' ')
453
454
static gboolean
455
slow_name_validate (GMarkupParseContext  *context,
456
                    const gchar          *name,
457
                    GError              **error)
458
0
{
459
0
  const gchar *p = name;
460
461
0
  if (!g_utf8_validate (name, -1, NULL))
462
0
    {
463
0
      set_error (context, error, G_MARKUP_ERROR_BAD_UTF8,
464
0
                 _("Invalid UTF-8 encoded text in name — not valid “%s”"), name);
465
0
      return FALSE;
466
0
    }
467
468
0
  if (!(g_ascii_isalpha (*p) ||
469
0
        (!IS_COMMON_NAME_END_CHAR (*p) &&
470
0
         (*p == '_' ||
471
0
          *p == ':' ||
472
0
          g_unichar_isalpha (g_utf8_get_char (p))))))
473
0
    {
474
0
      set_error (context, error, G_MARKUP_ERROR_PARSE,
475
0
                 _("“%s” is not a valid name"), name);
476
0
      return FALSE;
477
0
    }
478
479
0
  for (p = g_utf8_next_char (name); *p != '\0'; p = g_utf8_next_char (p))
480
0
    {
481
      /* is_name_char */
482
0
      if (!(g_ascii_isalnum (*p) ||
483
0
            (!IS_COMMON_NAME_END_CHAR (*p) &&
484
0
             (*p == '.' ||
485
0
              *p == '-' ||
486
0
              *p == '_' ||
487
0
              *p == ':' ||
488
0
              g_unichar_isalpha (g_utf8_get_char (p))))))
489
0
        {
490
0
          set_error (context, error, G_MARKUP_ERROR_PARSE,
491
0
                     _("“%s” is not a valid name: “%c”"), name, *p);
492
0
          return FALSE;
493
0
        }
494
0
    }
495
0
  return TRUE;
496
0
}
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
0
{
506
0
  char mask;
507
0
  const char *p;
508
509
  /* name start char */
510
0
  p = name;
511
0
  if (G_UNLIKELY (IS_COMMON_NAME_END_CHAR (*p) ||
512
0
                  !(g_ascii_isalpha (*p) || *p == '_' || *p == ':')))
513
0
    goto slow_validate;
514
515
0
  for (mask = *p++; *p != '\0'; p++)
516
0
    {
517
0
      mask |= *p;
518
519
      /* is_name_char */
520
0
      if (G_UNLIKELY (!(g_ascii_isalnum (*p) ||
521
0
                        (!IS_COMMON_NAME_END_CHAR (*p) &&
522
0
                         (*p == '.' ||
523
0
                          *p == '-' ||
524
0
                          *p == '_' ||
525
0
                          *p == ':')))))
526
0
        goto slow_validate;
527
0
    }
528
529
0
  if (mask & 0x80) /* un-common / non-ascii */
530
0
    goto slow_validate;
531
532
0
  return TRUE;
533
534
0
 slow_validate:
535
0
  return slow_name_validate (context, name, error);
536
0
}
537
538
static gboolean
539
text_validate (GMarkupParseContext  *context,
540
               const gchar          *p,
541
               gint                  len,
542
               GError              **error)
543
0
{
544
0
  if (!g_utf8_validate_len (p, len, NULL))
545
0
    {
546
0
      set_error (context, error, G_MARKUP_ERROR_BAD_UTF8,
547
0
                 _("Invalid UTF-8 encoded text in name — not valid “%s”"), p);
548
0
      return FALSE;
549
0
    }
550
0
  else
551
0
    return TRUE;
552
0
}
553
554
static gchar*
555
char_str (gunichar c,
556
          gchar   *buf)
557
0
{
558
0
  memset (buf, 0, 8);
559
0
  g_unichar_to_utf8 (c, buf);
560
0
  return buf;
561
0
}
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
0
{
571
0
  gunichar c = g_utf8_get_char_validated (utf8, max_len);
572
0
  if (c == (gunichar) -1 || c == (gunichar) -2)
573
0
    {
574
0
      guchar ch = (max_len > 0) ? (guchar) *utf8 : 0;
575
0
      gchar *temp = g_strdup_printf ("\\x%02x", (guint) ch);
576
0
      memset (buf, 0, 8);
577
0
      memcpy (buf, temp, strlen (temp));
578
0
      g_free (temp);
579
0
    }
580
0
  else
581
0
    char_str (c, buf);
582
0
  return buf;
583
0
}
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
0
{
594
0
  GError *tmp_error;
595
0
  gchar *s;
596
0
  va_list args;
597
0
  gint remaining_newlines;
598
0
  const gchar *p;
599
600
0
  remaining_newlines = 0;
601
0
  p = remaining_text;
602
0
  while (*p != '\0')
603
0
    {
604
0
      if (*p == '\n')
605
0
        ++remaining_newlines;
606
0
      ++p;
607
0
    }
608
609
0
  va_start (args, format);
610
0
  s = g_strdup_vprintf (format, args);
611
0
  va_end (args);
612
613
0
  tmp_error = g_error_new (G_MARKUP_ERROR,
614
0
                           code,
615
0
                           _("Error on line %d: %s"),
616
0
                           context->line_number - remaining_newlines,
617
0
                           s);
618
619
0
  g_free (s);
620
621
0
  mark_error (context, tmp_error);
622
623
0
  g_propagate_error (error, tmp_error);
624
0
}
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
0
{
636
0
  char mask, *to;
637
0
  const char *from;
638
0
  gboolean normalize_attribute;
639
640
0
  *is_ascii = FALSE;
641
642
  /* are we unescaping an attribute or not ? */
643
0
  if (context->state == STATE_INSIDE_ATTRIBUTE_VALUE_SQ ||
644
0
      context->state == STATE_INSIDE_ATTRIBUTE_VALUE_DQ)
645
0
    normalize_attribute = TRUE;
646
0
  else
647
0
    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
0
  mask = 0;
655
0
  for (from = to = string->str; *from != '\0'; from++, to++)
656
0
    {
657
0
      *to = *from;
658
659
0
      mask |= *to;
660
0
      if (normalize_attribute && (*to == '\t' || *to == '\n'))
661
0
        *to = ' ';
662
0
      if (*to == '\r')
663
0
        {
664
0
          *to = normalize_attribute ? ' ' : '\n';
665
0
          if (from[1] == '\n')
666
0
            from++;
667
0
        }
668
0
      if (*from == '&')
669
0
        {
670
0
          from++;
671
0
          if (*from == '#')
672
0
            {
673
0
              gint base = 10;
674
0
              gulong l;
675
0
              gchar *end = NULL;
676
677
0
              from++;
678
679
0
              if (*from == 'x')
680
0
                {
681
0
                  base = 16;
682
0
                  from++;
683
0
                }
684
685
0
              errno = 0;
686
0
              l = strtoul (from, &end, base);
687
688
0
              if (end == from || errno != 0)
689
0
                {
690
0
                  set_unescape_error (context, error,
691
0
                                      from, G_MARKUP_ERROR_PARSE,
692
0
                                      _("Failed to parse “%-.*s”, which "
693
0
                                        "should have been a digit "
694
0
                                        "inside a character reference "
695
0
                                        "(&#234; for example) — perhaps "
696
0
                                        "the digit is too large"),
697
0
                                      (int)(end - from), from);
698
0
                  return FALSE;
699
0
                }
700
0
              else if (*end != ';')
701
0
                {
702
0
                  set_unescape_error (context, error,
703
0
                                      from, G_MARKUP_ERROR_PARSE,
704
0
                                      _("Character reference did not end with a "
705
0
                                        "semicolon; "
706
0
                                        "most likely you used an ampersand "
707
0
                                        "character without intending to start "
708
0
                                        "an entity — escape ampersand as &amp;"));
709
0
                  return FALSE;
710
0
                }
711
0
              else
712
0
                {
713
                  /* characters XML 1.1 permits */
714
0
                  if ((0 < l && l <= 0xD7FF) ||
715
0
                      (0xE000 <= l && l <= 0xFFFD) ||
716
0
                      (0x10000 <= l && l <= 0x10FFFF))
717
0
                    {
718
0
                      gchar buf[8];
719
0
                      char_str (l, buf);
720
0
                      strcpy (to, buf);
721
0
                      to += strlen (buf) - 1;
722
0
                      from = end;
723
0
                      if (l >= 0x80) /* not ascii */
724
0
                        mask |= 0x80;
725
0
                    }
726
0
                  else
727
0
                    {
728
0
                      set_unescape_error (context, error,
729
0
                                          from, G_MARKUP_ERROR_PARSE,
730
0
                                          _("Character reference “%-.*s” does not "
731
0
                                            "encode a permitted character"),
732
0
                                          (int)(end - from), from);
733
0
                      return FALSE;
734
0
                    }
735
0
                }
736
0
            }
737
738
0
          else if (strncmp (from, "lt;", 3) == 0)
739
0
            {
740
0
              *to = '<';
741
0
              from += 2;
742
0
            }
743
0
          else if (strncmp (from, "gt;", 3) == 0)
744
0
            {
745
0
              *to = '>';
746
0
              from += 2;
747
0
            }
748
0
          else if (strncmp (from, "amp;", 4) == 0)
749
0
            {
750
0
              *to = '&';
751
0
              from += 3;
752
0
            }
753
0
          else if (strncmp (from, "quot;", 5) == 0)
754
0
            {
755
0
              *to = '"';
756
0
              from += 4;
757
0
            }
758
0
          else if (strncmp (from, "apos;", 5) == 0)
759
0
            {
760
0
              *to = '\'';
761
0
              from += 4;
762
0
            }
763
0
          else
764
0
            {
765
0
              if (*from == ';')
766
0
                set_unescape_error (context, error,
767
0
                                    from, G_MARKUP_ERROR_PARSE,
768
0
                                    _("Empty entity “&;” seen; valid "
769
0
                                      "entities are: &amp; &quot; &lt; &gt; &apos;"));
770
0
              else
771
0
                {
772
0
                  const char *end = strchr (from, ';');
773
0
                  if (end)
774
0
                    set_unescape_error (context, error,
775
0
                                        from, G_MARKUP_ERROR_PARSE,
776
0
                                        _("Entity name “%-.*s” is not known"),
777
0
                                        (int)(end - from), from);
778
0
                  else
779
0
                    set_unescape_error (context, error,
780
0
                                        from, G_MARKUP_ERROR_PARSE,
781
0
                                        _("Entity did not end with a semicolon; "
782
0
                                          "most likely you used an ampersand "
783
0
                                          "character without intending to start "
784
0
                                          "an entity — escape ampersand as &amp;"));
785
0
                }
786
0
              return FALSE;
787
0
            }
788
0
        }
789
0
    }
790
791
0
  g_assert (to - string->str <= (gssize) string->len);
792
0
  if (to - string->str != (gssize) string->len)
793
0
    g_string_truncate (string, to - string->str);
794
795
0
  *is_ascii = !(mask & 0x80);
796
797
0
  return TRUE;
798
0
}
799
800
static inline gboolean
801
advance_char (GMarkupParseContext *context)
802
0
{
803
0
  context->iter++;
804
0
  context->char_number++;
805
806
0
  if (G_UNLIKELY (context->iter == context->current_text_end))
807
0
      return FALSE;
808
809
0
  else if (G_UNLIKELY (*context->iter == '\n'))
810
0
    {
811
0
      context->line_number++;
812
0
      context->char_number = 1;
813
0
    }
814
815
0
  return TRUE;
816
0
}
817
818
static inline gboolean
819
xml_isspace (char c)
820
0
{
821
0
  return c == ' ' || c == '\t' || c == '\n' || c == '\r';
822
0
}
823
824
static void
825
skip_spaces (GMarkupParseContext *context)
826
0
{
827
0
  do
828
0
    {
829
0
      if (!xml_isspace (*context->iter))
830
0
        return;
831
0
    }
832
0
  while (advance_char (context));
833
0
}
834
835
static void
836
advance_to_name_end (GMarkupParseContext *context)
837
0
{
838
0
  do
839
0
    {
840
0
      if (IS_COMMON_NAME_END_CHAR (*(context->iter)))
841
0
        return;
842
0
      if (xml_isspace (*(context->iter)))
843
0
        return;
844
0
    }
845
0
  while (advance_char (context));
846
0
}
847
848
static void
849
release_chunk (GMarkupParseContext *context, GString *str)
850
0
{
851
0
  GSList *node;
852
0
  if (!str)
853
0
    return;
854
0
  if (str->allocated_len > 256)
855
0
    { /* large strings are unusual and worth freeing */
856
0
      g_string_free (str, TRUE);
857
0
      return;
858
0
    }
859
0
  string_blank (str);
860
0
  node = get_list_node (context, str);
861
0
  context->spare_chunks = g_slist_concat (node, context->spare_chunks);
862
0
}
863
864
static void
865
add_to_partial (GMarkupParseContext *context,
866
                const gchar         *text_start,
867
                const gchar         *text_end)
868
0
{
869
0
  if (context->partial_chunk == NULL)
870
0
    { /* allocate a new chunk to parse into */
871
872
0
      if (context->spare_chunks != NULL)
873
0
        {
874
0
          GSList *node = context->spare_chunks;
875
0
          context->spare_chunks = g_slist_remove_link (context->spare_chunks, node);
876
0
          context->partial_chunk = node->data;
877
0
          free_list_node (context, node);
878
0
        }
879
0
      else
880
0
        context->partial_chunk = g_string_sized_new (MAX (28, text_end - text_start));
881
0
    }
882
883
0
  if (text_start != text_end)
884
0
    g_string_insert_len (context->partial_chunk, -1,
885
0
                         text_start, text_end - text_start);
886
0
}
887
888
static inline void
889
truncate_partial (GMarkupParseContext *context)
890
0
{
891
0
  if (context->partial_chunk != NULL)
892
0
    string_blank (context->partial_chunk);
893
0
}
894
895
static inline const gchar*
896
current_element (GMarkupParseContext *context)
897
0
{
898
0
  return context->tag_stack->data;
899
0
}
900
901
static void
902
pop_subparser_stack (GMarkupParseContext *context)
903
0
{
904
0
  GMarkupRecursionTracker *tracker;
905
906
0
  g_assert (context->subparser_stack);
907
908
0
  tracker = context->subparser_stack->data;
909
910
0
  context->awaiting_pop = TRUE;
911
0
  context->held_user_data = context->user_data;
912
913
0
  context->user_data = tracker->prev_user_data;
914
0
  context->parser = tracker->prev_parser;
915
0
  context->subparser_element = tracker->prev_element;
916
0
  g_slice_free (GMarkupRecursionTracker, tracker);
917
918
0
  context->subparser_stack = g_slist_delete_link (context->subparser_stack,
919
0
                                                  context->subparser_stack);
920
0
}
921
922
static void
923
push_partial_as_tag (GMarkupParseContext *context)
924
0
{
925
0
  GString *str = context->partial_chunk;
926
  /* sadly, this is exported by gmarkup_get_element_stack as-is */
927
0
  context->tag_stack = g_slist_concat (get_list_node (context, str->str), context->tag_stack);
928
0
  context->tag_stack_gstr = g_slist_concat (get_list_node (context, str), context->tag_stack_gstr);
929
0
  context->partial_chunk = NULL;
930
0
}
931
932
static void
933
pop_tag (GMarkupParseContext *context)
934
0
{
935
0
  GSList *nodea, *nodeb;
936
937
0
  nodea = context->tag_stack;
938
0
  nodeb = context->tag_stack_gstr;
939
0
  release_chunk (context, nodeb->data);
940
0
  context->tag_stack = g_slist_remove_link (context->tag_stack, nodea);
941
0
  context->tag_stack_gstr = g_slist_remove_link (context->tag_stack_gstr, nodeb);
942
0
  free_list_node (context, nodea);
943
0
  free_list_node (context, nodeb);
944
0
}
945
946
static void
947
possibly_finish_subparser (GMarkupParseContext *context)
948
0
{
949
0
  if (current_element (context) == context->subparser_element)
950
0
    pop_subparser_stack (context);
951
0
}
952
953
static void
954
ensure_no_outstanding_subparser (GMarkupParseContext *context)
955
0
{
956
0
  if (context->awaiting_pop)
957
0
    g_critical ("During the first end_element call after invoking a "
958
0
                "subparser you must pop the subparser stack and handle "
959
0
                "the freeing of the subparser user_data.  This can be "
960
0
                "done by calling the end function of the subparser.  "
961
0
                "Very probably, your program just leaked memory.");
962
963
  /* let valgrind watch the pointer disappear... */
964
0
  context->held_user_data = NULL;
965
0
  context->awaiting_pop = FALSE;
966
0
}
967
968
static const gchar*
969
current_attribute (GMarkupParseContext *context)
970
0
{
971
0
  g_assert (context->cur_attr >= 0);
972
0
  return context->attr_names[context->cur_attr]->str;
973
0
}
974
975
static gboolean
976
add_attribute (GMarkupParseContext *context, GString *str)
977
0
{
978
  /* Sanity check on the number of attributes. */
979
0
  if (context->cur_attr >= 1000)
980
0
    return FALSE;
981
982
0
  if (context->cur_attr + 2 >= context->alloc_attrs)
983
0
    {
984
0
      context->alloc_attrs += 5; /* silly magic number */
985
0
      context->attr_names = g_realloc (context->attr_names, sizeof(GString*)*context->alloc_attrs);
986
0
      context->attr_values = g_realloc (context->attr_values, sizeof(GString*)*context->alloc_attrs);
987
0
    }
988
0
  context->cur_attr++;
989
0
  context->attr_names[context->cur_attr] = str;
990
0
  context->attr_values[context->cur_attr] = NULL;
991
0
  context->attr_names[context->cur_attr+1] = NULL;
992
0
  context->attr_values[context->cur_attr+1] = NULL;
993
994
0
  return TRUE;
995
0
}
996
997
static void
998
clear_attributes (GMarkupParseContext *context)
999
0
{
1000
  /* Go ahead and free the attributes. */
1001
0
  for (; context->cur_attr >= 0; context->cur_attr--)
1002
0
    {
1003
0
      int pos = context->cur_attr;
1004
0
      release_chunk (context, context->attr_names[pos]);
1005
0
      release_chunk (context, context->attr_values[pos]);
1006
0
      context->attr_names[pos] = context->attr_values[pos] = NULL;
1007
0
    }
1008
0
  g_assert (context->cur_attr == -1);
1009
0
  g_assert (context->attr_names == NULL ||
1010
0
            context->attr_names[0] == NULL);
1011
0
  g_assert (context->attr_values == NULL ||
1012
0
            context->attr_values[0] == NULL);
1013
0
}
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
0
{
1023
0
  int i, j = 0;
1024
0
  const gchar *start_name;
1025
0
  const gchar **attr_names;
1026
0
  const gchar **attr_values;
1027
0
  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
0
  if ((context->flags & G_MARKUP_IGNORE_QUALIFIED) && strchr (current_element (context), ':'))
1036
0
    {
1037
0
      static const GMarkupParser ignore_parser = { 0 };
1038
0
      g_markup_parse_context_push (context, &ignore_parser, NULL);
1039
0
      clear_attributes (context);
1040
0
      return;
1041
0
    }
1042
1043
0
  attr_names = g_newa (const gchar *, context->cur_attr + 2);
1044
0
  attr_values = g_newa (const gchar *, context->cur_attr + 2);
1045
0
  for (i = 0; i < context->cur_attr + 1; i++)
1046
0
    {
1047
      /* Possibly omit qualified attribute names from the list */
1048
0
      if ((context->flags & G_MARKUP_IGNORE_QUALIFIED) && strchr (context->attr_names[i]->str, ':'))
1049
0
        continue;
1050
1051
0
      attr_names[j] = context->attr_names[i]->str;
1052
0
      attr_values[j] = context->attr_values[i]->str;
1053
0
      j++;
1054
0
    }
1055
0
  attr_names[j] = NULL;
1056
0
  attr_values[j] = NULL;
1057
1058
  /* Call user callback for element start */
1059
0
  tmp_error = NULL;
1060
0
  start_name = current_element (context);
1061
1062
0
  if (!name_validate (context, start_name, error))
1063
0
    return;
1064
1065
0
  if (context->parser->start_element)
1066
0
    (* context->parser->start_element) (context,
1067
0
                                        start_name,
1068
0
                                        (const gchar **)attr_names,
1069
0
                                        (const gchar **)attr_values,
1070
0
                                        context->user_data,
1071
0
                                        &tmp_error);
1072
0
  clear_attributes (context);
1073
1074
0
  if (tmp_error != NULL)
1075
0
    propagate_error (context, error, tmp_error);
1076
0
}
1077
1078
static void
1079
emit_end_element (GMarkupParseContext  *context,
1080
                  GError              **error)
1081
0
{
1082
  /* We need to pop the tag stack and call the end_element
1083
   * function, since this is the close tag
1084
   */
1085
0
  GError *tmp_error = NULL;
1086
1087
0
  g_assert (context->tag_stack != NULL);
1088
1089
0
  possibly_finish_subparser (context);
1090
1091
  /* We might have just returned from our ignore subparser */
1092
0
  if ((context->flags & G_MARKUP_IGNORE_QUALIFIED) && strchr (current_element (context), ':'))
1093
0
    {
1094
0
      g_markup_parse_context_pop (context);
1095
0
      pop_tag (context);
1096
0
      return;
1097
0
    }
1098
1099
0
  tmp_error = NULL;
1100
0
  if (context->parser->end_element)
1101
0
    (* context->parser->end_element) (context,
1102
0
                                      current_element (context),
1103
0
                                      context->user_data,
1104
0
                                      &tmp_error);
1105
1106
0
  ensure_no_outstanding_subparser (context);
1107
1108
0
  if (tmp_error)
1109
0
    {
1110
0
      mark_error (context, tmp_error);
1111
0
      g_propagate_error (error, tmp_error);
1112
0
    }
1113
1114
0
  pop_tag (context);
1115
0
}
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
0
{
1143
0
  g_return_val_if_fail (context != NULL, FALSE);
1144
0
  g_return_val_if_fail (text != NULL, FALSE);
1145
0
  g_return_val_if_fail (context->state != STATE_ERROR, FALSE);
1146
0
  g_return_val_if_fail (!context->parsing, FALSE);
1147
1148
0
  if (text_len < 0)
1149
0
    text_len = strlen (text);
1150
1151
0
  if (text_len == 0)
1152
0
    return TRUE;
1153
1154
0
  context->parsing = TRUE;
1155
1156
1157
0
  context->current_text = text;
1158
0
  context->current_text_len = text_len;
1159
0
  context->current_text_end = context->current_text + text_len;
1160
0
  context->iter = context->current_text;
1161
0
  context->start = context->iter;
1162
1163
0
  while (context->iter != context->current_text_end)
1164
0
    {
1165
0
      switch (context->state)
1166
0
        {
1167
0
        case STATE_START:
1168
          /* Possible next state: AFTER_OPEN_ANGLE */
1169
1170
0
          g_assert (context->tag_stack == NULL);
1171
1172
          /* whitespace is ignored outside of any elements */
1173
0
          skip_spaces (context);
1174
1175
0
          if (context->iter != context->current_text_end)
1176
0
            {
1177
0
              if (*context->iter == '<')
1178
0
                {
1179
                  /* Move after the open angle */
1180
0
                  advance_char (context);
1181
1182
0
                  context->state = STATE_AFTER_OPEN_ANGLE;
1183
1184
                  /* this could start a passthrough */
1185
0
                  context->start = context->iter;
1186
1187
                  /* document is now non-empty */
1188
0
                  context->document_empty = FALSE;
1189
0
                }
1190
0
              else
1191
0
                {
1192
0
                  set_error_literal (context,
1193
0
                                     error,
1194
0
                                     G_MARKUP_ERROR_PARSE,
1195
0
                                     _("Document must begin with an element (e.g. <book>)"));
1196
0
                }
1197
0
            }
1198
0
          break;
1199
1200
0
        case STATE_AFTER_OPEN_ANGLE:
1201
          /* Possible next states: INSIDE_OPEN_TAG_NAME,
1202
           *  AFTER_CLOSE_TAG_SLASH, INSIDE_PASSTHROUGH
1203
           */
1204
0
          if (*context->iter == '?' ||
1205
0
              *context->iter == '!')
1206
0
            {
1207
              /* include < in the passthrough */
1208
0
              const gchar *openangle = "<";
1209
0
              add_to_partial (context, openangle, openangle + 1);
1210
0
              context->start = context->iter;
1211
0
              context->balance = 1;
1212
0
              context->state = STATE_INSIDE_PASSTHROUGH;
1213
0
            }
1214
0
          else if (*context->iter == '/')
1215
0
            {
1216
              /* move after it */
1217
0
              advance_char (context);
1218
1219
0
              context->state = STATE_AFTER_CLOSE_TAG_SLASH;
1220
0
            }
1221
0
          else if (!IS_COMMON_NAME_END_CHAR (*(context->iter)))
1222
0
            {
1223
0
              context->state = STATE_INSIDE_OPEN_TAG_NAME;
1224
1225
              /* start of tag name */
1226
0
              context->start = context->iter;
1227
0
            }
1228
0
          else
1229
0
            {
1230
0
              gchar buf[8];
1231
1232
0
              set_error (context,
1233
0
                         error,
1234
0
                         G_MARKUP_ERROR_PARSE,
1235
0
                         _("“%s” is not a valid character following "
1236
0
                           "a “<” character; it may not begin an "
1237
0
                           "element name"),
1238
0
                         utf8_str (context->iter,
1239
0
                                   context->current_text_end - context->iter, buf));
1240
0
            }
1241
0
          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
0
        case STATE_AFTER_CLOSE_ANGLE:
1249
          /* Possible next states: INSIDE_TEXT, STATE_START */
1250
0
          if (context->tag_stack == NULL)
1251
0
            {
1252
0
              context->start = NULL;
1253
0
              context->state = STATE_START;
1254
0
            }
1255
0
          else
1256
0
            {
1257
0
              context->start = context->iter;
1258
0
              context->state = STATE_INSIDE_TEXT;
1259
0
            }
1260
0
          break;
1261
1262
0
        case STATE_AFTER_ELISION_SLASH:
1263
          /* Possible next state: AFTER_CLOSE_ANGLE */
1264
0
          if (*context->iter == '>')
1265
0
            {
1266
              /* move after the close angle */
1267
0
              advance_char (context);
1268
0
              context->state = STATE_AFTER_CLOSE_ANGLE;
1269
0
              emit_end_element (context, error);
1270
0
            }
1271
0
          else
1272
0
            {
1273
0
              gchar buf[8];
1274
1275
0
              set_error (context,
1276
0
                         error,
1277
0
                         G_MARKUP_ERROR_PARSE,
1278
0
                         _("Odd character “%s”, expected a “>” character "
1279
0
                           "to end the empty-element tag “%s”"),
1280
0
                         utf8_str (context->iter,
1281
0
                                   context->current_text_end - context->iter, buf),
1282
0
                         current_element (context));
1283
0
            }
1284
0
          break;
1285
1286
0
        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
0
          advance_to_name_end (context);
1295
1296
0
          if (context->iter == context->current_text_end)
1297
0
            {
1298
              /* The name hasn't necessarily ended. Merge with
1299
               * partial chunk, leave state unchanged.
1300
               */
1301
0
              add_to_partial (context, context->start, context->iter);
1302
0
            }
1303
0
          else
1304
0
            {
1305
              /* The name has ended. Combine it with the partial chunk
1306
               * if any; push it on the stack; enter next state.
1307
               */
1308
0
              add_to_partial (context, context->start, context->iter);
1309
0
              push_partial_as_tag (context);
1310
1311
0
              context->state = STATE_BETWEEN_ATTRIBUTES;
1312
0
              context->start = NULL;
1313
0
            }
1314
0
          break;
1315
1316
0
        case STATE_INSIDE_ATTRIBUTE_NAME:
1317
          /* Possible next states: AFTER_ATTRIBUTE_NAME */
1318
1319
0
          advance_to_name_end (context);
1320
0
          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
0
          if (context->iter != context->current_text_end)
1327
0
            context->state = STATE_AFTER_ATTRIBUTE_NAME;
1328
0
          break;
1329
1330
0
        case STATE_AFTER_ATTRIBUTE_NAME:
1331
          /* Possible next states: AFTER_ATTRIBUTE_EQUALS_SIGN */
1332
1333
0
          skip_spaces (context);
1334
1335
0
          if (context->iter != context->current_text_end)
1336
0
            {
1337
              /* The name has ended. Combine it with the partial chunk
1338
               * if any; push it on the stack; enter next state.
1339
               */
1340
0
              if (!name_validate (context, context->partial_chunk->str, error))
1341
0
                break;
1342
1343
0
              if (!add_attribute (context, context->partial_chunk))
1344
0
                {
1345
0
                  set_error (context,
1346
0
                             error,
1347
0
                             G_MARKUP_ERROR_PARSE,
1348
0
                             _("Too many attributes in element “%s”"),
1349
0
                             current_element (context));
1350
0
                  break;
1351
0
                }
1352
1353
0
              context->partial_chunk = NULL;
1354
0
              context->start = NULL;
1355
1356
0
              if (*context->iter == '=')
1357
0
                {
1358
0
                  advance_char (context);
1359
0
                  context->state = STATE_AFTER_ATTRIBUTE_EQUALS_SIGN;
1360
0
                }
1361
0
              else
1362
0
                {
1363
0
                  gchar buf[8];
1364
1365
0
                  set_error (context,
1366
0
                             error,
1367
0
                             G_MARKUP_ERROR_PARSE,
1368
0
                             _("Odd character “%s”, expected a “=” after "
1369
0
                               "attribute name “%s” of element “%s”"),
1370
0
                             utf8_str (context->iter,
1371
0
                                       context->current_text_end - context->iter, buf),
1372
0
                             current_attribute (context),
1373
0
                             current_element (context));
1374
1375
0
                }
1376
0
            }
1377
0
          break;
1378
1379
0
        case STATE_BETWEEN_ATTRIBUTES:
1380
          /* Possible next states: AFTER_CLOSE_ANGLE,
1381
           * AFTER_ELISION_SLASH, INSIDE_ATTRIBUTE_NAME
1382
           */
1383
0
          skip_spaces (context);
1384
1385
0
          if (context->iter != context->current_text_end)
1386
0
            {
1387
0
              if (*context->iter == '/')
1388
0
                {
1389
0
                  advance_char (context);
1390
0
                  context->state = STATE_AFTER_ELISION_SLASH;
1391
0
                }
1392
0
              else if (*context->iter == '>')
1393
0
                {
1394
0
                  advance_char (context);
1395
0
                  context->state = STATE_AFTER_CLOSE_ANGLE;
1396
0
                }
1397
0
              else if (!IS_COMMON_NAME_END_CHAR (*(context->iter)))
1398
0
                {
1399
0
                  context->state = STATE_INSIDE_ATTRIBUTE_NAME;
1400
                  /* start of attribute name */
1401
0
                  context->start = context->iter;
1402
0
                }
1403
0
              else
1404
0
                {
1405
0
                  gchar buf[8];
1406
1407
0
                  set_error (context,
1408
0
                             error,
1409
0
                             G_MARKUP_ERROR_PARSE,
1410
0
                             _("Odd character “%s”, expected a “>” or “/” "
1411
0
                               "character to end the start tag of "
1412
0
                               "element “%s”, or optionally an attribute; "
1413
0
                               "perhaps you used an invalid character in "
1414
0
                               "an attribute name"),
1415
0
                             utf8_str (context->iter,
1416
0
                                       context->current_text_end - context->iter, buf),
1417
0
                             current_element (context));
1418
0
                }
1419
1420
              /* If we're done with attributes, invoke
1421
               * the start_element callback
1422
               */
1423
0
              if (context->state == STATE_AFTER_ELISION_SLASH ||
1424
0
                  context->state == STATE_AFTER_CLOSE_ANGLE)
1425
0
                emit_start_element (context, error);
1426
0
            }
1427
0
          break;
1428
1429
0
        case STATE_AFTER_ATTRIBUTE_EQUALS_SIGN:
1430
          /* Possible next state: INSIDE_ATTRIBUTE_VALUE_[SQ/DQ] */
1431
1432
0
          skip_spaces (context);
1433
1434
0
          if (context->iter != context->current_text_end)
1435
0
            {
1436
0
              if (*context->iter == '"')
1437
0
                {
1438
0
                  advance_char (context);
1439
0
                  context->state = STATE_INSIDE_ATTRIBUTE_VALUE_DQ;
1440
0
                  context->start = context->iter;
1441
0
                }
1442
0
              else if (*context->iter == '\'')
1443
0
                {
1444
0
                  advance_char (context);
1445
0
                  context->state = STATE_INSIDE_ATTRIBUTE_VALUE_SQ;
1446
0
                  context->start = context->iter;
1447
0
                }
1448
0
              else
1449
0
                {
1450
0
                  gchar buf[8];
1451
1452
0
                  set_error (context,
1453
0
                             error,
1454
0
                             G_MARKUP_ERROR_PARSE,
1455
0
                             _("Odd character “%s”, expected an open quote mark "
1456
0
                               "after the equals sign when giving value for "
1457
0
                               "attribute “%s” of element “%s”"),
1458
0
                             utf8_str (context->iter,
1459
0
                                       context->current_text_end - context->iter, buf),
1460
0
                             current_attribute (context),
1461
0
                             current_element (context));
1462
0
                }
1463
0
            }
1464
0
          break;
1465
1466
0
        case STATE_INSIDE_ATTRIBUTE_VALUE_SQ:
1467
0
        case STATE_INSIDE_ATTRIBUTE_VALUE_DQ:
1468
          /* Possible next states: BETWEEN_ATTRIBUTES */
1469
0
          {
1470
0
            gchar delim;
1471
1472
0
            if (context->state == STATE_INSIDE_ATTRIBUTE_VALUE_SQ)
1473
0
              {
1474
0
                delim = '\'';
1475
0
              }
1476
0
            else
1477
0
              {
1478
0
                delim = '"';
1479
0
              }
1480
1481
0
            do
1482
0
              {
1483
0
                if (*context->iter == delim)
1484
0
                  break;
1485
0
              }
1486
0
            while (advance_char (context));
1487
0
          }
1488
0
          if (context->iter == context->current_text_end)
1489
0
            {
1490
              /* The value hasn't necessarily ended. Merge with
1491
               * partial chunk, leave state unchanged.
1492
               */
1493
0
              add_to_partial (context, context->start, context->iter);
1494
0
            }
1495
0
          else
1496
0
            {
1497
0
              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
0
              add_to_partial (context, context->start, context->iter);
1503
1504
0
              g_assert (context->cur_attr >= 0);
1505
1506
0
              if (unescape_gstring_inplace (context, context->partial_chunk, &is_ascii, error) &&
1507
0
                  (is_ascii || text_validate (context, context->partial_chunk->str,
1508
0
                                              context->partial_chunk->len, error)))
1509
0
                {
1510
                  /* success, advance past quote and set state. */
1511
0
                  context->attr_values[context->cur_attr] = context->partial_chunk;
1512
0
                  context->partial_chunk = NULL;
1513
0
                  advance_char (context);
1514
0
                  context->state = STATE_BETWEEN_ATTRIBUTES;
1515
0
                  context->start = NULL;
1516
0
                }
1517
1518
0
              truncate_partial (context);
1519
0
            }
1520
0
          break;
1521
1522
0
        case STATE_INSIDE_TEXT:
1523
          /* Possible next states: AFTER_OPEN_ANGLE */
1524
0
          do
1525
0
            {
1526
0
              if (*context->iter == '<')
1527
0
                break;
1528
0
            }
1529
0
          while (advance_char (context));
1530
1531
          /* The text hasn't necessarily ended. Merge with
1532
           * partial chunk, leave state unchanged.
1533
           */
1534
1535
0
          add_to_partial (context, context->start, context->iter);
1536
1537
0
          if (context->iter != context->current_text_end)
1538
0
            {
1539
0
              gboolean is_ascii;
1540
1541
              /* The text has ended at the open angle. Call the text
1542
               * callback.
1543
               */
1544
0
              if (unescape_gstring_inplace (context, context->partial_chunk, &is_ascii, error) &&
1545
0
                  (is_ascii || text_validate (context, context->partial_chunk->str,
1546
0
                                              context->partial_chunk->len, error)))
1547
0
                {
1548
0
                  GError *tmp_error = NULL;
1549
1550
0
                  if (context->parser->text)
1551
0
                    (*context->parser->text) (context,
1552
0
                                              context->partial_chunk->str,
1553
0
                                              context->partial_chunk->len,
1554
0
                                              context->user_data,
1555
0
                                              &tmp_error);
1556
1557
0
                  if (tmp_error == NULL)
1558
0
                    {
1559
                      /* advance past open angle and set state. */
1560
0
                      advance_char (context);
1561
0
                      context->state = STATE_AFTER_OPEN_ANGLE;
1562
                      /* could begin a passthrough */
1563
0
                      context->start = context->iter;
1564
0
                    }
1565
0
                  else
1566
0
                    propagate_error (context, error, tmp_error);
1567
0
                }
1568
1569
0
              truncate_partial (context);
1570
0
            }
1571
0
          break;
1572
1573
0
        case STATE_AFTER_CLOSE_TAG_SLASH:
1574
          /* Possible next state: INSIDE_CLOSE_TAG_NAME */
1575
0
          if (!IS_COMMON_NAME_END_CHAR (*(context->iter)))
1576
0
            {
1577
0
              context->state = STATE_INSIDE_CLOSE_TAG_NAME;
1578
1579
              /* start of tag name */
1580
0
              context->start = context->iter;
1581
0
            }
1582
0
          else
1583
0
            {
1584
0
              gchar buf[8];
1585
1586
0
              set_error (context,
1587
0
                         error,
1588
0
                         G_MARKUP_ERROR_PARSE,
1589
0
                         _("“%s” is not a valid character following "
1590
0
                           "the characters “</”; “%s” may not begin an "
1591
0
                           "element name"),
1592
0
                         utf8_str (context->iter,
1593
0
                                   context->current_text_end - context->iter, buf),
1594
0
                         utf8_str (context->iter,
1595
0
                                   context->current_text_end - context->iter, buf));
1596
0
            }
1597
0
          break;
1598
1599
0
        case STATE_INSIDE_CLOSE_TAG_NAME:
1600
          /* Possible next state: AFTER_CLOSE_TAG_NAME */
1601
0
          advance_to_name_end (context);
1602
0
          add_to_partial (context, context->start, context->iter);
1603
1604
0
          if (context->iter != context->current_text_end)
1605
0
            context->state = STATE_AFTER_CLOSE_TAG_NAME;
1606
0
          break;
1607
1608
0
        case STATE_AFTER_CLOSE_TAG_NAME:
1609
          /* Possible next state: AFTER_CLOSE_TAG_SLASH */
1610
1611
0
          skip_spaces (context);
1612
1613
0
          if (context->iter != context->current_text_end)
1614
0
            {
1615
0
              GString *close_name;
1616
1617
0
              close_name = context->partial_chunk;
1618
0
              context->partial_chunk = NULL;
1619
1620
0
              if (*context->iter != '>')
1621
0
                {
1622
0
                  gchar buf[8];
1623
1624
0
                  set_error (context,
1625
0
                             error,
1626
0
                             G_MARKUP_ERROR_PARSE,
1627
0
                             _("“%s” is not a valid character following "
1628
0
                               "the close element name “%s”; the allowed "
1629
0
                               "character is “>”"),
1630
0
                             utf8_str (context->iter,
1631
0
                                       context->current_text_end - context->iter, buf),
1632
0
                             close_name->str);
1633
0
                }
1634
0
              else if (context->tag_stack == NULL)
1635
0
                {
1636
0
                  set_error (context,
1637
0
                             error,
1638
0
                             G_MARKUP_ERROR_PARSE,
1639
0
                             _("Element “%s” was closed, no element "
1640
0
                               "is currently open"),
1641
0
                             close_name->str);
1642
0
                }
1643
0
              else if (strcmp (close_name->str, current_element (context)) != 0)
1644
0
                {
1645
0
                  set_error (context,
1646
0
                             error,
1647
0
                             G_MARKUP_ERROR_PARSE,
1648
0
                             _("Element “%s” was closed, but the currently "
1649
0
                               "open element is “%s”"),
1650
0
                             close_name->str,
1651
0
                             current_element (context));
1652
0
                }
1653
0
              else
1654
0
                {
1655
0
                  advance_char (context);
1656
0
                  context->state = STATE_AFTER_CLOSE_ANGLE;
1657
0
                  context->start = NULL;
1658
1659
0
                  emit_end_element (context, error);
1660
0
                }
1661
0
              context->partial_chunk = close_name;
1662
0
              truncate_partial (context);
1663
0
            }
1664
0
          break;
1665
1666
0
        case STATE_INSIDE_PASSTHROUGH:
1667
          /* Possible next state: AFTER_CLOSE_ANGLE */
1668
0
          do
1669
0
            {
1670
0
              if (*context->iter == '<')
1671
0
                context->balance++;
1672
0
              if (*context->iter == '>')
1673
0
                {
1674
0
                  gchar *str;
1675
0
                  gsize len;
1676
1677
0
                  context->balance--;
1678
0
                  add_to_partial (context, context->start, context->iter);
1679
0
                  context->start = context->iter;
1680
1681
0
                  str = context->partial_chunk->str;
1682
0
                  len = context->partial_chunk->len;
1683
1684
0
                  if (str[1] == '?' && str[len - 1] == '?')
1685
0
                    break;
1686
0
                  if (strncmp (str, "<!--", 4) == 0 &&
1687
0
                      strcmp (str + len - 2, "--") == 0)
1688
0
                    break;
1689
0
                  if (strncmp (str, "<![CDATA[", 9) == 0 &&
1690
0
                      strcmp (str + len - 2, "]]") == 0)
1691
0
                    break;
1692
0
                  if (strncmp (str, "<!DOCTYPE", 9) == 0 &&
1693
0
                      context->balance == 0)
1694
0
                    break;
1695
0
                }
1696
0
            }
1697
0
          while (advance_char (context));
1698
1699
0
          if (context->iter == context->current_text_end)
1700
0
            {
1701
              /* The passthrough hasn't necessarily ended. Merge with
1702
               * partial chunk, leave state unchanged.
1703
               */
1704
0
               add_to_partial (context, context->start, context->iter);
1705
0
            }
1706
0
          else
1707
0
            {
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
0
              GError *tmp_error = NULL;
1714
1715
0
              advance_char (context); /* advance past close angle */
1716
0
              add_to_partial (context, context->start, context->iter);
1717
1718
0
              if (context->flags & G_MARKUP_TREAT_CDATA_AS_TEXT &&
1719
0
                  strncmp (context->partial_chunk->str, "<![CDATA[", 9) == 0)
1720
0
                {
1721
0
                  if (context->parser->text &&
1722
0
                      text_validate (context,
1723
0
                                     context->partial_chunk->str + 9,
1724
0
                                     context->partial_chunk->len - 12,
1725
0
                                     error))
1726
0
                    (*context->parser->text) (context,
1727
0
                                              context->partial_chunk->str + 9,
1728
0
                                              context->partial_chunk->len - 12,
1729
0
                                              context->user_data,
1730
0
                                              &tmp_error);
1731
0
                }
1732
0
              else if (context->parser->passthrough &&
1733
0
                       text_validate (context,
1734
0
                                      context->partial_chunk->str,
1735
0
                                      context->partial_chunk->len,
1736
0
                                      error))
1737
0
                (*context->parser->passthrough) (context,
1738
0
                                                 context->partial_chunk->str,
1739
0
                                                 context->partial_chunk->len,
1740
0
                                                 context->user_data,
1741
0
                                                 &tmp_error);
1742
1743
0
              truncate_partial (context);
1744
1745
0
              if (tmp_error == NULL)
1746
0
                {
1747
0
                  context->state = STATE_AFTER_CLOSE_ANGLE;
1748
0
                  context->start = context->iter; /* could begin text */
1749
0
                }
1750
0
              else
1751
0
                propagate_error (context, error, tmp_error);
1752
0
            }
1753
0
          break;
1754
1755
0
        case STATE_ERROR:
1756
0
          goto finished;
1757
0
          break;
1758
1759
0
        default:
1760
0
          g_assert_not_reached ();
1761
0
          break;
1762
0
        }
1763
0
    }
1764
1765
0
 finished:
1766
0
  context->parsing = FALSE;
1767
1768
0
  return context->state != STATE_ERROR;
1769
0
}
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
0
{
1788
0
  g_return_val_if_fail (context != NULL, FALSE);
1789
0
  g_return_val_if_fail (!context->parsing, FALSE);
1790
0
  g_return_val_if_fail (context->state != STATE_ERROR, FALSE);
1791
1792
0
  if (context->partial_chunk != NULL)
1793
0
    {
1794
0
      g_string_free (context->partial_chunk, TRUE);
1795
0
      context->partial_chunk = NULL;
1796
0
    }
1797
1798
0
  if (context->document_empty)
1799
0
    {
1800
0
      set_error_literal (context, error, G_MARKUP_ERROR_EMPTY,
1801
0
                         _("Document was empty or contained only whitespace"));
1802
0
      return FALSE;
1803
0
    }
1804
1805
0
  context->parsing = TRUE;
1806
1807
0
  switch (context->state)
1808
0
    {
1809
0
    case STATE_START:
1810
      /* Nothing to do */
1811
0
      break;
1812
1813
0
    case STATE_AFTER_OPEN_ANGLE:
1814
0
      set_error_literal (context, error, G_MARKUP_ERROR_PARSE,
1815
0
                         _("Document ended unexpectedly just after an open angle bracket “<”"));
1816
0
      break;
1817
1818
0
    case STATE_AFTER_CLOSE_ANGLE:
1819
0
      if (context->tag_stack != NULL)
1820
0
        {
1821
          /* Error message the same as for INSIDE_TEXT */
1822
0
          set_error (context, error, G_MARKUP_ERROR_PARSE,
1823
0
                     _("Document ended unexpectedly with elements still open — "
1824
0
                       "“%s” was the last element opened"),
1825
0
                     current_element (context));
1826
0
        }
1827
0
      break;
1828
1829
0
    case STATE_AFTER_ELISION_SLASH:
1830
0
      set_error (context, error, G_MARKUP_ERROR_PARSE,
1831
0
                 _("Document ended unexpectedly, expected to see a close angle "
1832
0
                   "bracket ending the tag <%s/>"), current_element (context));
1833
0
      break;
1834
1835
0
    case STATE_INSIDE_OPEN_TAG_NAME:
1836
0
      set_error_literal (context, error, G_MARKUP_ERROR_PARSE,
1837
0
                         _("Document ended unexpectedly inside an element name"));
1838
0
      break;
1839
1840
0
    case STATE_INSIDE_ATTRIBUTE_NAME:
1841
0
    case STATE_AFTER_ATTRIBUTE_NAME:
1842
0
      set_error_literal (context, error, G_MARKUP_ERROR_PARSE,
1843
0
                         _("Document ended unexpectedly inside an attribute name"));
1844
0
      break;
1845
1846
0
    case STATE_BETWEEN_ATTRIBUTES:
1847
0
      set_error_literal (context, error, G_MARKUP_ERROR_PARSE,
1848
0
                         _("Document ended unexpectedly inside an element-opening "
1849
0
                           "tag."));
1850
0
      break;
1851
1852
0
    case STATE_AFTER_ATTRIBUTE_EQUALS_SIGN:
1853
0
      set_error_literal (context, error, G_MARKUP_ERROR_PARSE,
1854
0
                         _("Document ended unexpectedly after the equals sign "
1855
0
                           "following an attribute name; no attribute value"));
1856
0
      break;
1857
1858
0
    case STATE_INSIDE_ATTRIBUTE_VALUE_SQ:
1859
0
    case STATE_INSIDE_ATTRIBUTE_VALUE_DQ:
1860
0
      set_error_literal (context, error, G_MARKUP_ERROR_PARSE,
1861
0
                         _("Document ended unexpectedly while inside an attribute "
1862
0
                           "value"));
1863
0
      break;
1864
1865
0
    case STATE_INSIDE_TEXT:
1866
0
      g_assert (context->tag_stack != NULL);
1867
0
      set_error (context, error, G_MARKUP_ERROR_PARSE,
1868
0
                 _("Document ended unexpectedly with elements still open — "
1869
0
                   "“%s” was the last element opened"),
1870
0
                 current_element (context));
1871
0
      break;
1872
1873
0
    case STATE_AFTER_CLOSE_TAG_SLASH:
1874
0
    case STATE_INSIDE_CLOSE_TAG_NAME:
1875
0
    case STATE_AFTER_CLOSE_TAG_NAME:
1876
0
      if (context->tag_stack != NULL)
1877
0
        set_error (context, error, G_MARKUP_ERROR_PARSE,
1878
0
                   _("Document ended unexpectedly inside the close tag for "
1879
0
                     "element “%s”"), current_element (context));
1880
0
      else
1881
0
        set_error (context, error, G_MARKUP_ERROR_PARSE,
1882
0
                   _("Document ended unexpectedly inside the close tag for an "
1883
0
                     "unopened element"));
1884
0
      break;
1885
1886
0
    case STATE_INSIDE_PASSTHROUGH:
1887
0
      set_error_literal (context, error, G_MARKUP_ERROR_PARSE,
1888
0
                         _("Document ended unexpectedly inside a comment or "
1889
0
                           "processing instruction"));
1890
0
      break;
1891
1892
0
    case STATE_ERROR:
1893
0
    default:
1894
0
      g_assert_not_reached ();
1895
0
      break;
1896
0
    }
1897
1898
0
  context->parsing = FALSE;
1899
1900
0
  return context->state != STATE_ERROR;
1901
0
}
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
0
{
1920
0
  g_return_val_if_fail (context != NULL, NULL);
1921
1922
0
  if (context->tag_stack == NULL)
1923
0
    return NULL;
1924
0
  else
1925
0
    return current_element (context);
1926
0
}
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
0
{
1951
0
  g_return_val_if_fail (context != NULL, NULL);
1952
0
  return context->tag_stack;
1953
0
}
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
0
{
1971
0
  g_return_if_fail (context != NULL);
1972
1973
0
  if (line_number)
1974
0
    *line_number = context->line_number;
1975
1976
0
  if (char_number)
1977
0
    *char_number = context->char_number;
1978
0
}
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
0
{
1999
0
  return context->user_data;
2000
0
}
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
0
{
2130
0
  GMarkupRecursionTracker *tracker;
2131
2132
0
  tracker = g_slice_new (GMarkupRecursionTracker);
2133
0
  tracker->prev_element = context->subparser_element;
2134
0
  tracker->prev_parser = context->parser;
2135
0
  tracker->prev_user_data = context->user_data;
2136
2137
0
  context->subparser_element = current_element (context);
2138
0
  context->parser = parser;
2139
0
  context->user_data = user_data;
2140
2141
0
  context->subparser_stack = g_slist_prepend (context->subparser_stack,
2142
0
                                              tracker);
2143
0
}
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
0
{
2170
0
  gpointer user_data;
2171
2172
0
  if (!context->awaiting_pop)
2173
0
    possibly_finish_subparser (context);
2174
2175
0
  g_assert (context->awaiting_pop);
2176
2177
0
  context->awaiting_pop = FALSE;
2178
2179
  /* valgrind friendliness */
2180
0
  user_data = context->held_user_data;
2181
0
  context->held_user_data = NULL;
2182
2183
0
  return user_data;
2184
0
}
2185
2186
#define APPEND_TEXT_AND_SEEK(_str, _start, _end)          \
2187
0
  G_STMT_START {                                          \
2188
0
    if (_end > _start)                                    \
2189
0
      g_string_append_len (_str, _start, _end - _start);  \
2190
0
    _start = ++_end;                                      \
2191
0
  } 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
0
{
2210
0
  const gchar *p, *pending;
2211
0
  const gchar *end;
2212
2213
0
  p = pending = text;
2214
0
  end = text + length;
2215
2216
0
  while (p < end && pending < end)
2217
0
    {
2218
0
      guchar c = (guchar) *pending;
2219
2220
0
      switch (c)
2221
0
        {
2222
0
        case '&':
2223
0
          APPEND_TEXT_AND_SEEK (str, p, pending);
2224
0
          g_string_append (str, "&amp;");
2225
0
          break;
2226
2227
0
        case '<':
2228
0
          APPEND_TEXT_AND_SEEK (str, p, pending);
2229
0
          g_string_append (str, "&lt;");
2230
0
          break;
2231
2232
0
        case '>':
2233
0
          APPEND_TEXT_AND_SEEK (str, p, pending);
2234
0
          g_string_append (str, "&gt;");
2235
0
          break;
2236
2237
0
        case '\'':
2238
0
          APPEND_TEXT_AND_SEEK (str, p, pending);
2239
0
          g_string_append (str, "&apos;");
2240
0
          break;
2241
2242
0
        case '"':
2243
0
          APPEND_TEXT_AND_SEEK (str, p, pending);
2244
0
          g_string_append (str, "&quot;");
2245
0
          break;
2246
2247
0
        default:
2248
0
          if ((0x1 <= c && c <= 0x8) ||
2249
0
              (0xb <= c && c  <= 0xc) ||
2250
0
              (0xe <= c && c <= 0x1f) ||
2251
0
              (c == 0x7f))
2252
0
            {
2253
0
              APPEND_TEXT_AND_SEEK (str, p, pending);
2254
0
              g_string_append_printf (str, "&#x%x;", c);
2255
0
            }
2256
          /* The utf-8 control characters to escape begins with 0xc2 byte */
2257
0
          else if (c == 0xc2)
2258
0
            {
2259
0
              gunichar u = g_utf8_get_char (pending);
2260
2261
0
              if ((0x7f < u && u <= 0x84) ||
2262
0
                  (0x86 <= u && u <= 0x9f))
2263
0
                {
2264
0
                  APPEND_TEXT_AND_SEEK (str, p, pending);
2265
0
                  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
0
                  p++;
2273
0
                }
2274
0
              else
2275
0
                pending++;
2276
0
            }
2277
0
          else
2278
0
            pending++;
2279
0
          break;
2280
0
        }
2281
0
    }
2282
2283
0
  if (pending > p)
2284
0
    g_string_append_len (str, p, pending - p);
2285
0
}
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
0
{
2315
0
  GString *str;
2316
2317
0
  g_return_val_if_fail (text != NULL, NULL);
2318
2319
0
  if (length < 0)
2320
0
    length = strlen (text);
2321
2322
  /* prealloc at least as long as original text */
2323
0
  str = g_string_sized_new (length);
2324
0
  append_escaped_text (str, text, length);
2325
2326
0
  return g_string_free (str, FALSE);
2327
0
}
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
0
{
2347
0
  const char *start = format;
2348
0
  const char *cp;
2349
2350
0
  while (*start != '\0' && *start != '%')
2351
0
    start++;
2352
2353
0
  if (*start == '\0')
2354
0
    {
2355
0
      *after = start;
2356
0
      return NULL;
2357
0
    }
2358
2359
0
  cp = start + 1;
2360
2361
0
  if (*cp == '\0')
2362
0
    {
2363
0
      *after = cp;
2364
0
      return NULL;
2365
0
    }
2366
2367
  /* Test for positional argument.  */
2368
0
  if (*cp >= '0' && *cp <= '9')
2369
0
    {
2370
0
      const char *np;
2371
2372
0
      for (np = cp; *np >= '0' && *np <= '9'; np++)
2373
0
        ;
2374
0
      if (*np == '$')
2375
0
        cp = np + 1;
2376
0
    }
2377
2378
  /* Skip the flags.  */
2379
0
  for (;;)
2380
0
    {
2381
0
      if (*cp == '\'' ||
2382
0
          *cp == '-' ||
2383
0
          *cp == '+' ||
2384
0
          *cp == ' ' ||
2385
0
          *cp == '#' ||
2386
0
          *cp == '0')
2387
0
        cp++;
2388
0
      else
2389
0
        break;
2390
0
    }
2391
2392
  /* Skip the field width.  */
2393
0
  if (*cp == '*')
2394
0
    {
2395
0
      cp++;
2396
2397
      /* Test for positional argument.  */
2398
0
      if (*cp >= '0' && *cp <= '9')
2399
0
        {
2400
0
          const char *np;
2401
2402
0
          for (np = cp; *np >= '0' && *np <= '9'; np++)
2403
0
            ;
2404
0
          if (*np == '$')
2405
0
            cp = np + 1;
2406
0
        }
2407
0
    }
2408
0
  else
2409
0
    {
2410
0
      for (; *cp >= '0' && *cp <= '9'; cp++)
2411
0
        ;
2412
0
    }
2413
2414
  /* Skip the precision.  */
2415
0
  if (*cp == '.')
2416
0
    {
2417
0
      cp++;
2418
0
      if (*cp == '*')
2419
0
        {
2420
          /* Test for positional argument.  */
2421
0
          if (*cp >= '0' && *cp <= '9')
2422
0
            {
2423
0
              const char *np;
2424
2425
0
              for (np = cp; *np >= '0' && *np <= '9'; np++)
2426
0
                ;
2427
0
              if (*np == '$')
2428
0
                cp = np + 1;
2429
0
            }
2430
0
        }
2431
0
      else
2432
0
        {
2433
0
          for (; *cp >= '0' && *cp <= '9'; cp++)
2434
0
            ;
2435
0
        }
2436
0
    }
2437
2438
  /* Skip argument type/size specifiers.  */
2439
0
  while (*cp == 'h' ||
2440
0
         *cp == 'L' ||
2441
0
         *cp == 'l' ||
2442
0
         *cp == 'j' ||
2443
0
         *cp == 'z' ||
2444
0
         *cp == 'Z' ||
2445
0
         *cp == 't')
2446
0
    cp++;
2447
2448
  /* Skip the conversion character.  */
2449
0
  cp++;
2450
2451
0
  *after = cp;
2452
0
  return start;
2453
0
}
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
0
{
2476
0
  GString *format1;
2477
0
  GString *format2;
2478
0
  GString *result = NULL;
2479
0
  gchar *output1 = NULL;
2480
0
  gchar *output2 = NULL;
2481
0
  const char *p, *op1, *op2;
2482
0
  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
0
  format1 = g_string_new (NULL);
2514
0
  format2 = g_string_new (NULL);
2515
0
  p = format;
2516
0
  while (TRUE)
2517
0
    {
2518
0
      const char *after;
2519
0
      const char *conv = find_conversion (p, &after);
2520
0
      if (!conv)
2521
0
        break;
2522
2523
0
      g_string_append_len (format1, conv, after - conv);
2524
0
      g_string_append_c (format1, 'X');
2525
0
      g_string_append_len (format2, conv, after - conv);
2526
0
      g_string_append_c (format2, 'Y');
2527
2528
0
      p = after;
2529
0
    }
2530
2531
  /* Use them to format the arguments
2532
   */
2533
0
  G_VA_COPY (args2, args);
2534
2535
0
  output1 = g_strdup_vprintf (format1->str, args);
2536
2537
0
  if (!output1)
2538
0
    {
2539
0
      va_end (args2);
2540
0
      goto cleanup;
2541
0
    }
2542
2543
0
  output2 = g_strdup_vprintf (format2->str, args2);
2544
0
  va_end (args2);
2545
0
  if (!output2)
2546
0
    goto cleanup;
2547
0
  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
0
  op1 = output1;
2554
0
  op2 = output2;
2555
0
  p = format;
2556
0
  while (TRUE)
2557
0
    {
2558
0
      const char *after;
2559
0
      const char *output_start;
2560
0
      const char *conv = find_conversion (p, &after);
2561
0
      char *escaped;
2562
2563
0
      if (!conv)        /* The end, after points to the trailing \0 */
2564
0
        {
2565
0
          g_string_append_len (result, p, after - p);
2566
0
          break;
2567
0
        }
2568
2569
0
      g_string_append_len (result, p, conv - p);
2570
0
      output_start = op1;
2571
0
      while (*op1 == *op2)
2572
0
        {
2573
0
          op1++;
2574
0
          op2++;
2575
0
        }
2576
2577
0
      escaped = g_markup_escape_text (output_start, op1 - output_start);
2578
0
      g_string_append (result, escaped);
2579
0
      g_free (escaped);
2580
2581
0
      p = after;
2582
0
      op1++;
2583
0
      op2++;
2584
0
    }
2585
2586
0
 cleanup:
2587
0
  g_string_free (format1, TRUE);
2588
0
  g_string_free (format2, TRUE);
2589
0
  g_free (output1);
2590
0
  g_free (output2);
2591
2592
0
  if (result)
2593
0
    return g_string_free (result, FALSE);
2594
0
  else
2595
0
    return NULL;
2596
0
}
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
0
{
2632
0
  char *result;
2633
0
  va_list args;
2634
2635
0
  va_start (args, format);
2636
0
  result = g_markup_vprintf_escaped (format, args);
2637
0
  va_end (args);
2638
2639
0
  return result;
2640
0
}
2641
2642
static gboolean
2643
g_markup_parse_boolean (const char  *string,
2644
                        gboolean    *value)
2645
0
{
2646
0
  char const * const falses[] = { "false", "f", "no", "n", "0" };
2647
0
  char const * const trues[] = { "true", "t", "yes", "y", "1" };
2648
0
  gsize i;
2649
2650
0
  for (i = 0; i < G_N_ELEMENTS (falses); i++)
2651
0
    {
2652
0
      if (g_ascii_strcasecmp (string, falses[i]) == 0)
2653
0
        {
2654
0
          if (value != NULL)
2655
0
            *value = FALSE;
2656
2657
0
          return TRUE;
2658
0
        }
2659
0
    }
2660
2661
0
  for (i = 0; i < G_N_ELEMENTS (trues); i++)
2662
0
    {
2663
0
      if (g_ascii_strcasecmp (string, trues[i]) == 0)
2664
0
        {
2665
0
          if (value != NULL)
2666
0
            *value = TRUE;
2667
2668
0
          return TRUE;
2669
0
        }
2670
0
    }
2671
2672
0
  return FALSE;
2673
0
}
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
0
{
2765
0
  GMarkupCollectType type;
2766
0
  const gchar *attr;
2767
0
  guint64 collected;
2768
0
  int written;
2769
0
  va_list ap;
2770
0
  int i;
2771
2772
0
  type = first_type;
2773
0
  attr = first_attr;
2774
0
  collected = 0;
2775
0
  written = 0;
2776
2777
0
  va_start (ap, first_attr);
2778
0
  while (type != G_MARKUP_COLLECT_INVALID)
2779
0
    {
2780
0
      gboolean mandatory;
2781
0
      const gchar *value;
2782
2783
0
      mandatory = !(type & G_MARKUP_COLLECT_OPTIONAL);
2784
0
      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
0
      if (type == G_MARKUP_COLLECT_TRISTATE)
2790
0
        mandatory = FALSE;
2791
2792
0
      for (i = 0; attribute_names[i]; i++)
2793
0
        if (i >= 40 || !(collected & (G_GUINT64_CONSTANT(1) << i)))
2794
0
          if (!strcmp (attribute_names[i], attr))
2795
0
            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
0
      if (i < 40)
2811
0
        collected |= (G_GUINT64_CONSTANT(1) << i);
2812
2813
0
      value = attribute_values[i];
2814
2815
0
      if (value == NULL && mandatory)
2816
0
        {
2817
0
          g_set_error (error, G_MARKUP_ERROR,
2818
0
                       G_MARKUP_ERROR_MISSING_ATTRIBUTE,
2819
0
                       "element '%s' requires attribute '%s'",
2820
0
                       element_name, attr);
2821
2822
0
          va_end (ap);
2823
0
          goto failure;
2824
0
        }
2825
2826
0
      switch (type)
2827
0
        {
2828
0
        case G_MARKUP_COLLECT_STRING:
2829
0
          {
2830
0
            const char **str_ptr;
2831
2832
0
            str_ptr = va_arg (ap, const char **);
2833
2834
0
            if (str_ptr != NULL)
2835
0
              *str_ptr = value;
2836
0
          }
2837
0
          break;
2838
2839
0
        case G_MARKUP_COLLECT_STRDUP:
2840
0
          {
2841
0
            char **str_ptr;
2842
2843
0
            str_ptr = va_arg (ap, char **);
2844
2845
0
            if (str_ptr != NULL)
2846
0
              *str_ptr = g_strdup (value);
2847
0
          }
2848
0
          break;
2849
2850
0
        case G_MARKUP_COLLECT_BOOLEAN:
2851
0
        case G_MARKUP_COLLECT_TRISTATE:
2852
0
          if (value == NULL)
2853
0
            {
2854
0
              gboolean *bool_ptr;
2855
2856
0
              bool_ptr = va_arg (ap, gboolean *);
2857
2858
0
              if (bool_ptr != NULL)
2859
0
                {
2860
0
                  if (type == G_MARKUP_COLLECT_TRISTATE)
2861
                    /* constructivists rejoice!
2862
                     * neither false nor true...
2863
                     */
2864
0
                    *bool_ptr = -1;
2865
2866
0
                  else /* G_MARKUP_COLLECT_BOOLEAN */
2867
0
                    *bool_ptr = FALSE;
2868
0
                }
2869
0
            }
2870
0
          else
2871
0
            {
2872
0
              if (!g_markup_parse_boolean (value, va_arg (ap, gboolean *)))
2873
0
                {
2874
0
                  g_set_error (error, G_MARKUP_ERROR,
2875
0
                               G_MARKUP_ERROR_INVALID_CONTENT,
2876
0
                               "element '%s', attribute '%s', value '%s' "
2877
0
                               "cannot be parsed as a boolean value",
2878
0
                               element_name, attr, value);
2879
2880
0
                  va_end (ap);
2881
0
                  goto failure;
2882
0
                }
2883
0
            }
2884
2885
0
          break;
2886
2887
0
        default:
2888
0
          g_assert_not_reached ();
2889
0
        }
2890
2891
0
      written++;
2892
0
      type = va_arg (ap, GMarkupCollectType);
2893
0
      if (type != G_MARKUP_COLLECT_INVALID)
2894
0
        attr = va_arg (ap, const char *);
2895
0
    }
2896
0
  va_end (ap);
2897
2898
  /* ensure we collected all the arguments */
2899
0
  for (i = 0; attribute_names[i]; i++)
2900
0
    if ((collected & (G_GUINT64_CONSTANT(1) << i)) == 0)
2901
0
      {
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
0
        int j;
2910
2911
0
        for (j = 0; j < i; j++)
2912
0
          if (strcmp (attribute_names[i], attribute_names[j]) == 0)
2913
            /* duplicate! */
2914
0
            break;
2915
2916
        /* j is now the first occurrence of attribute_names[i] */
2917
0
        if (i == j)
2918
0
          g_set_error (error, G_MARKUP_ERROR,
2919
0
                       G_MARKUP_ERROR_UNKNOWN_ATTRIBUTE,
2920
0
                       "attribute '%s' invalid for element '%s'",
2921
0
                       attribute_names[i], element_name);
2922
0
        else
2923
0
          g_set_error (error, G_MARKUP_ERROR,
2924
0
                       G_MARKUP_ERROR_INVALID_CONTENT,
2925
0
                       "attribute '%s' given multiple times for element '%s'",
2926
0
                       attribute_names[i], element_name);
2927
2928
0
        goto failure;
2929
0
      }
2930
2931
0
  return TRUE;
2932
2933
0
failure:
2934
  /* replay the above to free allocations */
2935
0
  type = first_type;
2936
2937
0
  va_start (ap, first_attr);
2938
0
  while (type != G_MARKUP_COLLECT_INVALID)
2939
0
    {
2940
0
      gpointer ptr;
2941
2942
0
      ptr = va_arg (ap, gpointer);
2943
2944
0
      if (ptr != NULL)
2945
0
        {
2946
0
          switch (type & (G_MARKUP_COLLECT_OPTIONAL - 1))
2947
0
            {
2948
0
            case G_MARKUP_COLLECT_STRDUP:
2949
0
              if (written)
2950
0
                g_free (*(char **) ptr);
2951
0
              *(char **) ptr = NULL;
2952
0
              break;
2953
2954
0
            case G_MARKUP_COLLECT_STRING:
2955
0
              *(char **) ptr = NULL;
2956
0
              break;
2957
2958
0
            case G_MARKUP_COLLECT_BOOLEAN:
2959
0
              *(gboolean *) ptr = FALSE;
2960
0
              break;
2961
2962
0
            case G_MARKUP_COLLECT_TRISTATE:
2963
0
              *(gboolean *) ptr = -1;
2964
0
              break;
2965
0
            }
2966
0
        }
2967
2968
0
      type = va_arg (ap, GMarkupCollectType);
2969
0
      if (type != G_MARKUP_COLLECT_INVALID)
2970
0
        {
2971
0
          attr = va_arg (ap, const char *);
2972
0
          (void) attr;
2973
0
        }
2974
0
    }
2975
0
  va_end (ap);
2976
2977
0
  return FALSE;
2978
0
}