Coverage Report

Created: 2026-10-14 08:19

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