Coverage Report

Created: 2025-11-24 06:51

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/libxml2/parser.c
Line
Count
Source
1
/*
2
 * parser.c : an XML 1.0 parser, namespaces and validity support are mostly
3
 *            implemented on top of the SAX interfaces
4
 *
5
 * References:
6
 *   The XML specification:
7
 *     http://www.w3.org/TR/REC-xml
8
 *   Original 1.0 version:
9
 *     http://www.w3.org/TR/1998/REC-xml-19980210
10
 *   XML second edition working draft
11
 *     http://www.w3.org/TR/2000/WD-xml-2e-20000814
12
 *
13
 * Okay this is a big file, the parser core is around 7000 lines, then it
14
 * is followed by the progressive parser top routines, then the various
15
 * high level APIs to call the parser and a few miscellaneous functions.
16
 * A number of helper functions and deprecated ones have been moved to
17
 * parserInternals.c to reduce this file size.
18
 * As much as possible the functions are associated with their relative
19
 * production in the XML specification. A few productions defining the
20
 * different ranges of character are actually implanted either in
21
 * parserInternals.h or parserInternals.c
22
 * The DOM tree build is realized from the default SAX callbacks in
23
 * the module SAX2.c.
24
 * The routines doing the validation checks are in valid.c and called either
25
 * from the SAX callbacks or as standalone functions using a preparsed
26
 * document.
27
 *
28
 * See Copyright for the status of this software.
29
 *
30
 * daniel@veillard.com
31
 */
32
33
/* To avoid EBCDIC trouble when parsing on zOS */
34
#if defined(__MVS__)
35
#pragma convert("ISO8859-1")
36
#endif
37
38
#define IN_LIBXML
39
#include "libxml.h"
40
41
#if defined(_WIN32)
42
#define XML_DIR_SEP '\\'
43
#else
44
#define XML_DIR_SEP '/'
45
#endif
46
47
#include <stdlib.h>
48
#include <limits.h>
49
#include <string.h>
50
#include <stdarg.h>
51
#include <stddef.h>
52
#include <ctype.h>
53
#include <stdlib.h>
54
#include <libxml/parser.h>
55
#include <libxml/xmlmemory.h>
56
#include <libxml/tree.h>
57
#include <libxml/parserInternals.h>
58
#include <libxml/valid.h>
59
#include <libxml/entities.h>
60
#include <libxml/xmlerror.h>
61
#include <libxml/encoding.h>
62
#include <libxml/xmlIO.h>
63
#include <libxml/uri.h>
64
#include <libxml/SAX2.h>
65
#include <libxml/HTMLparser.h>
66
#ifdef LIBXML_CATALOG_ENABLED
67
#include <libxml/catalog.h>
68
#endif
69
70
#include "private/buf.h"
71
#include "private/dict.h"
72
#include "private/entities.h"
73
#include "private/error.h"
74
#include "private/html.h"
75
#include "private/io.h"
76
#include "private/memory.h"
77
#include "private/parser.h"
78
79
4.64M
#define NS_INDEX_EMPTY  INT_MAX
80
126k
#define NS_INDEX_XML    (INT_MAX - 1)
81
1.74M
#define URI_HASH_EMPTY  0xD943A04E
82
61.2k
#define URI_HASH_XML    0xF0451F02
83
84
#ifndef STDIN_FILENO
85
0
  #define STDIN_FILENO 0
86
#endif
87
88
#ifndef SIZE_MAX
89
  #define SIZE_MAX ((size_t) -1)
90
#endif
91
92
1.89M
#define XML_MAX_ATTRS 100000000 /* 100 million */
93
94
struct _xmlStartTag {
95
    const xmlChar *prefix;
96
    const xmlChar *URI;
97
    int line;
98
    int nsNr;
99
};
100
101
typedef struct {
102
    void *saxData;
103
    unsigned prefixHashValue;
104
    unsigned uriHashValue;
105
    unsigned elementId;
106
    int oldIndex;
107
} xmlParserNsExtra;
108
109
typedef struct {
110
    unsigned hashValue;
111
    int index;
112
} xmlParserNsBucket;
113
114
struct _xmlParserNsData {
115
    xmlParserNsExtra *extra;
116
117
    unsigned hashSize;
118
    unsigned hashElems;
119
    xmlParserNsBucket *hash;
120
121
    unsigned elementId;
122
    int defaultNsIndex;
123
    int minNsIndex;
124
};
125
126
static int
127
xmlParseElementStart(xmlParserCtxtPtr ctxt);
128
129
static void
130
xmlParseElementEnd(xmlParserCtxtPtr ctxt);
131
132
static xmlEntityPtr
133
xmlLookupGeneralEntity(xmlParserCtxtPtr ctxt, const xmlChar *name, int inAttr);
134
135
static const xmlChar *
136
xmlParseEntityRefInternal(xmlParserCtxtPtr ctxt);
137
138
/************************************************************************
139
 *                  *
140
 *  Arbitrary limits set in the parser. See XML_PARSE_HUGE    *
141
 *                  *
142
 ************************************************************************/
143
144
#define XML_PARSER_BIG_ENTITY 1000
145
#define XML_PARSER_LOT_ENTITY 5000
146
147
/*
148
 * Constants for protection against abusive entity expansion
149
 * ("billion laughs").
150
 */
151
152
/*
153
 * A certain amount of entity expansion which is always allowed.
154
 */
155
3.41M
#define XML_PARSER_ALLOWED_EXPANSION 1000000
156
157
/*
158
 * Fixed cost for each entity reference. This crudely models processing time
159
 * as well to protect, for example, against exponential expansion of empty
160
 * or very short entities.
161
 */
162
3.41M
#define XML_ENT_FIXED_COST 20
163
164
256M
#define XML_PARSER_BIG_BUFFER_SIZE 300
165
626k
#define XML_PARSER_BUFFER_SIZE 100
166
784k
#define SAX_COMPAT_MODE BAD_CAST "SAX compatibility mode document"
167
168
/**
169
 * XML_PARSER_CHUNK_SIZE
170
 *
171
 * When calling GROW that's the minimal amount of data
172
 * the parser expected to have received. It is not a hard
173
 * limit but an optimization when reading strings like Names
174
 * It is not strictly needed as long as inputs available characters
175
 * are followed by 0, which should be provided by the I/O level
176
 */
177
#define XML_PARSER_CHUNK_SIZE 100
178
179
/**
180
 * xmlParserVersion:
181
 *
182
 * Constant string describing the internal version of the library
183
 */
184
const char *const
185
xmlParserVersion = LIBXML_VERSION_STRING LIBXML_VERSION_EXTRA;
186
187
/*
188
 * List of XML prefixed PI allowed by W3C specs
189
 */
190
191
static const char* const xmlW3CPIs[] = {
192
    "xml-stylesheet",
193
    "xml-model",
194
    NULL
195
};
196
197
198
/* DEPR void xmlParserHandleReference(xmlParserCtxtPtr ctxt); */
199
static xmlEntityPtr xmlParseStringPEReference(xmlParserCtxtPtr ctxt,
200
                                              const xmlChar **str);
201
202
static void
203
xmlCtxtParseEntity(xmlParserCtxtPtr ctxt, xmlEntityPtr ent);
204
205
static int
206
xmlLoadEntityContent(xmlParserCtxtPtr ctxt, xmlEntityPtr entity);
207
208
/************************************************************************
209
 *                  *
210
 *    Some factorized error routines        *
211
 *                  *
212
 ************************************************************************/
213
214
static void
215
2.13k
xmlErrMemory(xmlParserCtxtPtr ctxt) {
216
2.13k
    xmlCtxtErrMemory(ctxt);
217
2.13k
}
218
219
/**
220
 * xmlErrAttributeDup:
221
 * @ctxt:  an XML parser context
222
 * @prefix:  the attribute prefix
223
 * @localname:  the attribute localname
224
 *
225
 * Handle a redefinition of attribute error
226
 */
227
static void
228
xmlErrAttributeDup(xmlParserCtxtPtr ctxt, const xmlChar * prefix,
229
                   const xmlChar * localname)
230
6.14k
{
231
6.14k
    if (prefix == NULL)
232
2.87k
        xmlCtxtErr(ctxt, NULL, XML_FROM_PARSER, XML_ERR_ATTRIBUTE_REDEFINED,
233
2.87k
                   XML_ERR_FATAL, localname, NULL, NULL, 0,
234
2.87k
                   "Attribute %s redefined\n", localname);
235
3.27k
    else
236
3.27k
        xmlCtxtErr(ctxt, NULL, XML_FROM_PARSER, XML_ERR_ATTRIBUTE_REDEFINED,
237
3.27k
                   XML_ERR_FATAL, prefix, localname, NULL, 0,
238
3.27k
                   "Attribute %s:%s redefined\n", prefix, localname);
239
6.14k
}
240
241
/**
242
 * xmlFatalErrMsg:
243
 * @ctxt:  an XML parser context
244
 * @error:  the error number
245
 * @msg:  the error message
246
 *
247
 * Handle a fatal parser error, i.e. violating Well-Formedness constraints
248
 */
249
static void LIBXML_ATTR_FORMAT(3,0)
250
xmlFatalErrMsg(xmlParserCtxtPtr ctxt, xmlParserErrors error,
251
               const char *msg)
252
41.4M
{
253
41.4M
    xmlCtxtErr(ctxt, NULL, XML_FROM_PARSER, error, XML_ERR_FATAL,
254
41.4M
               NULL, NULL, NULL, 0, "%s", msg);
255
41.4M
}
256
257
/**
258
 * xmlWarningMsg:
259
 * @ctxt:  an XML parser context
260
 * @error:  the error number
261
 * @msg:  the error message
262
 * @str1:  extra data
263
 * @str2:  extra data
264
 *
265
 * Handle a warning.
266
 */
267
void LIBXML_ATTR_FORMAT(3,0)
268
xmlWarningMsg(xmlParserCtxtPtr ctxt, xmlParserErrors error,
269
              const char *msg, const xmlChar *str1, const xmlChar *str2)
270
38.1k
{
271
38.1k
    xmlCtxtErr(ctxt, NULL, XML_FROM_PARSER, error, XML_ERR_WARNING,
272
38.1k
               str1, str2, NULL, 0, msg, str1, str2);
273
38.1k
}
274
275
/**
276
 * xmlValidityError:
277
 * @ctxt:  an XML parser context
278
 * @error:  the error number
279
 * @msg:  the error message
280
 * @str1:  extra data
281
 *
282
 * Handle a validity error.
283
 */
284
static void LIBXML_ATTR_FORMAT(3,0)
285
xmlValidityError(xmlParserCtxtPtr ctxt, xmlParserErrors error,
286
              const char *msg, const xmlChar *str1, const xmlChar *str2)
287
0
{
288
0
    ctxt->valid = 0;
289
290
0
    xmlCtxtErr(ctxt, NULL, XML_FROM_DTD, error, XML_ERR_ERROR,
291
0
               str1, str2, NULL, 0, msg, str1, str2);
292
0
}
293
294
/**
295
 * xmlFatalErrMsgInt:
296
 * @ctxt:  an XML parser context
297
 * @error:  the error number
298
 * @msg:  the error message
299
 * @val:  an integer value
300
 *
301
 * Handle a fatal parser error, i.e. violating Well-Formedness constraints
302
 */
303
static void LIBXML_ATTR_FORMAT(3,0)
304
xmlFatalErrMsgInt(xmlParserCtxtPtr ctxt, xmlParserErrors error,
305
                  const char *msg, int val)
306
9.26M
{
307
9.26M
    xmlCtxtErr(ctxt, NULL, XML_FROM_PARSER, error, XML_ERR_FATAL,
308
9.26M
               NULL, NULL, NULL, val, msg, val);
309
9.26M
}
310
311
/**
312
 * xmlFatalErrMsgStrIntStr:
313
 * @ctxt:  an XML parser context
314
 * @error:  the error number
315
 * @msg:  the error message
316
 * @str1:  an string info
317
 * @val:  an integer value
318
 * @str2:  an string info
319
 *
320
 * Handle a fatal parser error, i.e. violating Well-Formedness constraints
321
 */
322
static void LIBXML_ATTR_FORMAT(3,0)
323
xmlFatalErrMsgStrIntStr(xmlParserCtxtPtr ctxt, xmlParserErrors error,
324
                  const char *msg, const xmlChar *str1, int val,
325
      const xmlChar *str2)
326
1.47M
{
327
1.47M
    xmlCtxtErr(ctxt, NULL, XML_FROM_PARSER, error, XML_ERR_FATAL,
328
1.47M
               str1, str2, NULL, val, msg, str1, val, str2);
329
1.47M
}
330
331
/**
332
 * xmlFatalErrMsgStr:
333
 * @ctxt:  an XML parser context
334
 * @error:  the error number
335
 * @msg:  the error message
336
 * @val:  a string value
337
 *
338
 * Handle a fatal parser error, i.e. violating Well-Formedness constraints
339
 */
340
static void LIBXML_ATTR_FORMAT(3,0)
341
xmlFatalErrMsgStr(xmlParserCtxtPtr ctxt, xmlParserErrors error,
342
                  const char *msg, const xmlChar * val)
343
417k
{
344
417k
    xmlCtxtErr(ctxt, NULL, XML_FROM_PARSER, error, XML_ERR_FATAL,
345
417k
               val, NULL, NULL, 0, msg, val);
346
417k
}
347
348
/**
349
 * xmlErrMsgStr:
350
 * @ctxt:  an XML parser context
351
 * @error:  the error number
352
 * @msg:  the error message
353
 * @val:  a string value
354
 *
355
 * Handle a non fatal parser error
356
 */
357
static void LIBXML_ATTR_FORMAT(3,0)
358
xmlErrMsgStr(xmlParserCtxtPtr ctxt, xmlParserErrors error,
359
                  const char *msg, const xmlChar * val)
360
16.3k
{
361
16.3k
    xmlCtxtErr(ctxt, NULL, XML_FROM_PARSER, error, XML_ERR_ERROR,
362
16.3k
               val, NULL, NULL, 0, msg, val);
363
16.3k
}
364
365
/**
366
 * xmlNsErr:
367
 * @ctxt:  an XML parser context
368
 * @error:  the error number
369
 * @msg:  the message
370
 * @info1:  extra information string
371
 * @info2:  extra information string
372
 *
373
 * Handle a fatal parser error, i.e. violating Well-Formedness constraints
374
 */
375
static void LIBXML_ATTR_FORMAT(3,0)
376
xmlNsErr(xmlParserCtxtPtr ctxt, xmlParserErrors error,
377
         const char *msg,
378
         const xmlChar * info1, const xmlChar * info2,
379
         const xmlChar * info3)
380
864k
{
381
864k
    ctxt->nsWellFormed = 0;
382
383
864k
    xmlCtxtErr(ctxt, NULL, XML_FROM_NAMESPACE, error, XML_ERR_ERROR,
384
864k
               info1, info2, info3, 0, msg, info1, info2, info3);
385
864k
}
386
387
/**
388
 * xmlNsWarn
389
 * @ctxt:  an XML parser context
390
 * @error:  the error number
391
 * @msg:  the message
392
 * @info1:  extra information string
393
 * @info2:  extra information string
394
 *
395
 * Handle a namespace warning error
396
 */
397
static void LIBXML_ATTR_FORMAT(3,0)
398
xmlNsWarn(xmlParserCtxtPtr ctxt, xmlParserErrors error,
399
         const char *msg,
400
         const xmlChar * info1, const xmlChar * info2,
401
         const xmlChar * info3)
402
19.0k
{
403
19.0k
    xmlCtxtErr(ctxt, NULL, XML_FROM_NAMESPACE, error, XML_ERR_WARNING,
404
19.0k
               info1, info2, info3, 0, msg, info1, info2, info3);
405
19.0k
}
406
407
static void
408
10.3M
xmlSaturatedAdd(unsigned long *dst, unsigned long val) {
409
10.3M
    if (val > ULONG_MAX - *dst)
410
0
        *dst = ULONG_MAX;
411
10.3M
    else
412
10.3M
        *dst += val;
413
10.3M
}
414
415
static void
416
3.45M
xmlSaturatedAddSizeT(unsigned long *dst, unsigned long val) {
417
3.45M
    if (val > ULONG_MAX - *dst)
418
0
        *dst = ULONG_MAX;
419
3.45M
    else
420
3.45M
        *dst += val;
421
3.45M
}
422
423
/**
424
 * xmlParserEntityCheck:
425
 * @ctxt:  parser context
426
 * @extra:  sum of unexpanded entity sizes
427
 *
428
 * Check for non-linear entity expansion behaviour.
429
 *
430
 * In some cases like xmlExpandEntityInAttValue, this function is called
431
 * for each, possibly nested entity and its unexpanded content length.
432
 *
433
 * In other cases like xmlParseReference, it's only called for each
434
 * top-level entity with its unexpanded content length plus the sum of
435
 * the unexpanded content lengths (plus fixed cost) of all nested
436
 * entities.
437
 *
438
 * Summing the unexpanded lengths also adds the length of the reference.
439
 * This is by design. Taking the length of the entity name into account
440
 * discourages attacks that try to waste CPU time with abusively long
441
 * entity names. See test/recurse/lol6.xml for example. Each call also
442
 * adds some fixed cost XML_ENT_FIXED_COST to discourage attacks with
443
 * short entities.
444
 *
445
 * Returns 1 on error, 0 on success.
446
 */
447
static int
448
xmlParserEntityCheck(xmlParserCtxtPtr ctxt, unsigned long extra)
449
3.41M
{
450
3.41M
    unsigned long consumed;
451
3.41M
    unsigned long *expandedSize;
452
3.41M
    xmlParserInputPtr input = ctxt->input;
453
3.41M
    xmlEntityPtr entity = input->entity;
454
455
3.41M
    if ((entity) && (entity->flags & XML_ENT_CHECKED))
456
1.69k
        return(0);
457
458
    /*
459
     * Compute total consumed bytes so far, including input streams of
460
     * external entities.
461
     */
462
3.41M
    consumed = input->consumed;
463
3.41M
    xmlSaturatedAddSizeT(&consumed, input->cur - input->base);
464
3.41M
    xmlSaturatedAdd(&consumed, ctxt->sizeentities);
465
466
3.41M
    if (entity)
467
965k
        expandedSize = &entity->expandedSize;
468
2.44M
    else
469
2.44M
        expandedSize = &ctxt->sizeentcopy;
470
471
    /*
472
     * Add extra cost and some fixed cost.
473
     */
474
3.41M
    xmlSaturatedAdd(expandedSize, extra);
475
3.41M
    xmlSaturatedAdd(expandedSize, XML_ENT_FIXED_COST);
476
477
    /*
478
     * It's important to always use saturation arithmetic when tracking
479
     * entity sizes to make the size checks reliable. If "sizeentcopy"
480
     * overflows, we have to abort.
481
     */
482
3.41M
    if ((*expandedSize > XML_PARSER_ALLOWED_EXPANSION) &&
483
160k
        ((*expandedSize >= ULONG_MAX) ||
484
160k
         (*expandedSize / ctxt->maxAmpl > consumed))) {
485
1.99k
        xmlFatalErrMsg(ctxt, XML_ERR_RESOURCE_LIMIT,
486
1.99k
                       "Maximum entity amplification factor exceeded, see "
487
1.99k
                       "xmlCtxtSetMaxAmplification.\n");
488
1.99k
        xmlHaltParser(ctxt);
489
1.99k
        return(1);
490
1.99k
    }
491
492
3.41M
    return(0);
493
3.41M
}
494
495
/************************************************************************
496
 *                  *
497
 *    Library wide options          *
498
 *                  *
499
 ************************************************************************/
500
501
/**
502
  * xmlHasFeature:
503
  * @feature: the feature to be examined
504
  *
505
  * Examines if the library has been compiled with a given feature.
506
  *
507
  * Returns a non-zero value if the feature exist, otherwise zero.
508
  * Returns zero (0) if the feature does not exist or an unknown
509
  * unknown feature is requested, non-zero otherwise.
510
  */
511
int
512
xmlHasFeature(xmlFeature feature)
513
0
{
514
0
    switch (feature) {
515
0
  case XML_WITH_THREAD:
516
0
#ifdef LIBXML_THREAD_ENABLED
517
0
      return(1);
518
#else
519
      return(0);
520
#endif
521
0
        case XML_WITH_TREE:
522
0
            return(1);
523
0
        case XML_WITH_OUTPUT:
524
0
#ifdef LIBXML_OUTPUT_ENABLED
525
0
            return(1);
526
#else
527
            return(0);
528
#endif
529
0
        case XML_WITH_PUSH:
530
#ifdef LIBXML_PUSH_ENABLED
531
            return(1);
532
#else
533
0
            return(0);
534
0
#endif
535
0
        case XML_WITH_READER:
536
#ifdef LIBXML_READER_ENABLED
537
            return(1);
538
#else
539
0
            return(0);
540
0
#endif
541
0
        case XML_WITH_PATTERN:
542
0
#ifdef LIBXML_PATTERN_ENABLED
543
0
            return(1);
544
#else
545
            return(0);
546
#endif
547
0
        case XML_WITH_WRITER:
548
#ifdef LIBXML_WRITER_ENABLED
549
            return(1);
550
#else
551
0
            return(0);
552
0
#endif
553
0
        case XML_WITH_SAX1:
554
#ifdef LIBXML_SAX1_ENABLED
555
            return(1);
556
#else
557
0
            return(0);
558
0
#endif
559
0
        case XML_WITH_HTTP:
560
#ifdef LIBXML_HTTP_ENABLED
561
            return(1);
562
#else
563
0
            return(0);
564
0
#endif
565
0
        case XML_WITH_VALID:
566
#ifdef LIBXML_VALID_ENABLED
567
            return(1);
568
#else
569
0
            return(0);
570
0
#endif
571
0
        case XML_WITH_HTML:
572
0
#ifdef LIBXML_HTML_ENABLED
573
0
            return(1);
574
#else
575
            return(0);
576
#endif
577
0
        case XML_WITH_LEGACY:
578
0
            return(0);
579
0
        case XML_WITH_C14N:
580
#ifdef LIBXML_C14N_ENABLED
581
            return(1);
582
#else
583
0
            return(0);
584
0
#endif
585
0
        case XML_WITH_CATALOG:
586
0
#ifdef LIBXML_CATALOG_ENABLED
587
0
            return(1);
588
#else
589
            return(0);
590
#endif
591
0
        case XML_WITH_XPATH:
592
0
#ifdef LIBXML_XPATH_ENABLED
593
0
            return(1);
594
#else
595
            return(0);
596
#endif
597
0
        case XML_WITH_XPTR:
598
0
#ifdef LIBXML_XPTR_ENABLED
599
0
            return(1);
600
#else
601
            return(0);
602
#endif
603
0
        case XML_WITH_XINCLUDE:
604
0
#ifdef LIBXML_XINCLUDE_ENABLED
605
0
            return(1);
606
#else
607
            return(0);
608
#endif
609
0
        case XML_WITH_ICONV:
610
0
#ifdef LIBXML_ICONV_ENABLED
611
0
            return(1);
612
#else
613
            return(0);
614
#endif
615
0
        case XML_WITH_ISO8859X:
616
0
#ifdef LIBXML_ISO8859X_ENABLED
617
0
            return(1);
618
#else
619
            return(0);
620
#endif
621
0
        case XML_WITH_UNICODE:
622
0
            return(0);
623
0
        case XML_WITH_REGEXP:
624
#ifdef LIBXML_REGEXP_ENABLED
625
            return(1);
626
#else
627
0
            return(0);
628
0
#endif
629
0
        case XML_WITH_AUTOMATA:
630
#ifdef LIBXML_REGEXP_ENABLED
631
            return(1);
632
#else
633
0
            return(0);
634
0
#endif
635
0
        case XML_WITH_EXPR:
636
#ifdef LIBXML_EXPR_ENABLED
637
            return(1);
638
#else
639
0
            return(0);
640
0
#endif
641
0
        case XML_WITH_RELAXNG:
642
#ifdef LIBXML_RELAXNG_ENABLED
643
            return(1);
644
#else
645
0
            return(0);
646
0
#endif
647
0
        case XML_WITH_SCHEMAS:
648
#ifdef LIBXML_SCHEMAS_ENABLED
649
            return(1);
650
#else
651
0
            return(0);
652
0
#endif
653
0
        case XML_WITH_SCHEMATRON:
654
#ifdef LIBXML_SCHEMATRON_ENABLED
655
            return(1);
656
#else
657
0
            return(0);
658
0
#endif
659
0
        case XML_WITH_MODULES:
660
0
#ifdef LIBXML_MODULES_ENABLED
661
0
            return(1);
662
#else
663
            return(0);
664
#endif
665
0
        case XML_WITH_DEBUG:
666
0
#ifdef LIBXML_DEBUG_ENABLED
667
0
            return(1);
668
#else
669
            return(0);
670
#endif
671
0
        case XML_WITH_DEBUG_MEM:
672
0
            return(0);
673
0
        case XML_WITH_ZLIB:
674
#ifdef LIBXML_ZLIB_ENABLED
675
            return(1);
676
#else
677
0
            return(0);
678
0
#endif
679
0
        case XML_WITH_LZMA:
680
#ifdef LIBXML_LZMA_ENABLED
681
            return(1);
682
#else
683
0
            return(0);
684
0
#endif
685
0
        case XML_WITH_ICU:
686
#ifdef LIBXML_ICU_ENABLED
687
            return(1);
688
#else
689
0
            return(0);
690
0
#endif
691
0
        default:
692
0
      break;
693
0
     }
694
0
     return(0);
695
0
}
696
697
/************************************************************************
698
 *                  *
699
 *      Simple string buffer        *
700
 *                  *
701
 ************************************************************************/
702
703
typedef struct {
704
    xmlChar *mem;
705
    unsigned size;
706
    unsigned cap; /* size < cap */
707
    unsigned max; /* size <= max */
708
    xmlParserErrors code;
709
} xmlSBuf;
710
711
static void
712
3.71M
xmlSBufInit(xmlSBuf *buf, unsigned max) {
713
3.71M
    buf->mem = NULL;
714
3.71M
    buf->size = 0;
715
3.71M
    buf->cap = 0;
716
3.71M
    buf->max = max;
717
3.71M
    buf->code = XML_ERR_OK;
718
3.71M
}
719
720
static int
721
452k
xmlSBufGrow(xmlSBuf *buf, unsigned len) {
722
452k
    xmlChar *mem;
723
452k
    unsigned cap;
724
725
452k
    if (len >= UINT_MAX / 2 - buf->size) {
726
0
        if (buf->code == XML_ERR_OK)
727
0
            buf->code = XML_ERR_RESOURCE_LIMIT;
728
0
        return(-1);
729
0
    }
730
731
452k
    cap = (buf->size + len) * 2;
732
452k
    if (cap < 240)
733
288k
        cap = 240;
734
735
452k
    mem = xmlRealloc(buf->mem, cap);
736
452k
    if (mem == NULL) {
737
86.1k
        buf->code = XML_ERR_NO_MEMORY;
738
86.1k
        return(-1);
739
86.1k
    }
740
741
365k
    buf->mem = mem;
742
365k
    buf->cap = cap;
743
744
365k
    return(0);
745
452k
}
746
747
static void
748
148M
xmlSBufAddString(xmlSBuf *buf, const xmlChar *str, unsigned len) {
749
148M
    if (buf->max - buf->size < len) {
750
51.3k
        if (buf->code == XML_ERR_OK)
751
35
            buf->code = XML_ERR_RESOURCE_LIMIT;
752
51.3k
        return;
753
51.3k
    }
754
755
148M
    if (buf->cap - buf->size <= len) {
756
440k
        if (xmlSBufGrow(buf, len) < 0)
757
85.5k
            return;
758
440k
    }
759
760
147M
    if (len > 0)
761
147M
        memcpy(buf->mem + buf->size, str, len);
762
147M
    buf->size += len;
763
147M
}
764
765
static void
766
138M
xmlSBufAddCString(xmlSBuf *buf, const char *str, unsigned len) {
767
138M
    xmlSBufAddString(buf, (const xmlChar *) str, len);
768
138M
}
769
770
static void
771
197k
xmlSBufAddChar(xmlSBuf *buf, int c) {
772
197k
    xmlChar *end;
773
774
197k
    if (buf->max - buf->size < 4) {
775
73
        if (buf->code == XML_ERR_OK)
776
0
            buf->code = XML_ERR_RESOURCE_LIMIT;
777
73
        return;
778
73
    }
779
780
197k
    if (buf->cap - buf->size <= 4) {
781
11.7k
        if (xmlSBufGrow(buf, 4) < 0)
782
585
            return;
783
11.7k
    }
784
785
196k
    end = buf->mem + buf->size;
786
787
196k
    if (c < 0x80) {
788
105k
        *end = (xmlChar) c;
789
105k
        buf->size += 1;
790
105k
    } else {
791
90.7k
        buf->size += xmlCopyCharMultiByte(end, c);
792
90.7k
    }
793
196k
}
794
795
static void
796
83.7M
xmlSBufAddReplChar(xmlSBuf *buf) {
797
83.7M
    xmlSBufAddCString(buf, "\xEF\xBF\xBD", 3);
798
83.7M
}
799
800
static void
801
209
xmlSBufReportError(xmlSBuf *buf, xmlParserCtxtPtr ctxt, const char *errMsg) {
802
209
    if (buf->code == XML_ERR_NO_MEMORY)
803
174
        xmlCtxtErrMemory(ctxt);
804
35
    else
805
35
        xmlFatalErr(ctxt, buf->code, errMsg);
806
209
}
807
808
static xmlChar *
809
xmlSBufFinish(xmlSBuf *buf, int *sizeOut, xmlParserCtxtPtr ctxt,
810
324k
              const char *errMsg) {
811
324k
    if (buf->mem == NULL) {
812
40.0k
        buf->mem = xmlMalloc(1);
813
40.0k
        if (buf->mem == NULL) {
814
39
            buf->code = XML_ERR_NO_MEMORY;
815
40.0k
        } else {
816
40.0k
            buf->mem[0] = 0;
817
40.0k
        }
818
284k
    } else {
819
284k
        buf->mem[buf->size] = 0;
820
284k
    }
821
822
324k
    if (buf->code == XML_ERR_OK) {
823
324k
        if (sizeOut != NULL)
824
149k
            *sizeOut = buf->size;
825
324k
        return(buf->mem);
826
324k
    }
827
828
83
    xmlSBufReportError(buf, ctxt, errMsg);
829
830
83
    xmlFree(buf->mem);
831
832
83
    if (sizeOut != NULL)
833
23
        *sizeOut = 0;
834
83
    return(NULL);
835
324k
}
836
837
static void
838
3.38M
xmlSBufCleanup(xmlSBuf *buf, xmlParserCtxtPtr ctxt, const char *errMsg) {
839
3.38M
    if (buf->code != XML_ERR_OK)
840
126
        xmlSBufReportError(buf, ctxt, errMsg);
841
842
3.38M
    xmlFree(buf->mem);
843
3.38M
}
844
845
static int
846
xmlUTF8MultibyteLen(xmlParserCtxtPtr ctxt, const xmlChar *str,
847
187M
                    const char *errMsg) {
848
187M
    int c = str[0];
849
187M
    int c1 = str[1];
850
851
187M
    if ((c1 & 0xC0) != 0x80)
852
11.2M
        goto encoding_error;
853
854
176M
    if (c < 0xE0) {
855
        /* 2-byte sequence */
856
46.8M
        if (c < 0xC2)
857
33.1M
            goto encoding_error;
858
859
13.7M
        return(2);
860
129M
    } else {
861
129M
        int c2 = str[2];
862
863
129M
        if ((c2 & 0xC0) != 0x80)
864
19.7k
            goto encoding_error;
865
866
129M
        if (c < 0xF0) {
867
            /* 3-byte sequence */
868
129M
            if (c == 0xE0) {
869
                /* overlong */
870
17.0M
                if (c1 < 0xA0)
871
543
                    goto encoding_error;
872
112M
            } else if (c == 0xED) {
873
                /* surrogate */
874
4.17k
                if (c1 >= 0xA0)
875
896
                    goto encoding_error;
876
112M
            } else if (c == 0xEF) {
877
                /* U+FFFE and U+FFFF are invalid Chars */
878
140k
                if ((c1 == 0xBF) && (c2 >= 0xBE))
879
614
                    xmlFatalErrMsg(ctxt, XML_ERR_INVALID_CHAR, errMsg);
880
140k
            }
881
882
129M
            return(3);
883
129M
        } else {
884
            /* 4-byte sequence */
885
65.9k
            if ((str[3] & 0xC0) != 0x80)
886
3.15k
                goto encoding_error;
887
62.7k
            if (c == 0xF0) {
888
                /* overlong */
889
39.1k
                if (c1 < 0x90)
890
2.31k
                    goto encoding_error;
891
39.1k
            } else if (c >= 0xF4) {
892
                /* greater than 0x10FFFF */
893
17.8k
                if ((c > 0xF4) || (c1 >= 0x90))
894
17.2k
                    goto encoding_error;
895
17.8k
            }
896
897
43.1k
            return(4);
898
62.7k
        }
899
129M
    }
900
901
44.4M
encoding_error:
902
    /* Only report the first error */
903
44.4M
    if ((ctxt->input->flags & XML_INPUT_ENCODING_ERROR) == 0) {
904
23.5k
        xmlCtxtErrIO(ctxt, XML_ERR_INVALID_ENCODING, NULL);
905
23.5k
        ctxt->input->flags |= XML_INPUT_ENCODING_ERROR;
906
23.5k
    }
907
908
44.4M
    return(0);
909
176M
}
910
911
/************************************************************************
912
 *                  *
913
 *    SAX2 defaulted attributes handling      *
914
 *                  *
915
 ************************************************************************/
916
917
/**
918
 * xmlCtxtInitializeLate:
919
 * @ctxt:  an XML parser context
920
 *
921
 * Final initialization of the parser context before starting to parse.
922
 *
923
 * This accounts for users modifying struct members of parser context
924
 * directly.
925
 */
926
static void
927
728k
xmlCtxtInitializeLate(xmlParserCtxtPtr ctxt) {
928
728k
    xmlSAXHandlerPtr sax;
929
930
    /* Avoid unused variable warning if features are disabled. */
931
728k
    (void) sax;
932
933
    /*
934
     * Changing the SAX struct directly is still widespread practice
935
     * in internal and external code.
936
     */
937
728k
    if (ctxt == NULL) return;
938
728k
    sax = ctxt->sax;
939
#ifdef LIBXML_SAX1_ENABLED
940
    /*
941
     * Only enable SAX2 if there SAX2 element handlers, except when there
942
     * are no element handlers at all.
943
     */
944
    if (((ctxt->options & XML_PARSE_SAX1) == 0) &&
945
        (sax) &&
946
        (sax->initialized == XML_SAX2_MAGIC) &&
947
        ((sax->startElementNs != NULL) ||
948
         (sax->endElementNs != NULL) ||
949
         ((sax->startElement == NULL) && (sax->endElement == NULL))))
950
        ctxt->sax2 = 1;
951
#else
952
728k
    ctxt->sax2 = 1;
953
728k
#endif /* LIBXML_SAX1_ENABLED */
954
955
    /*
956
     * Some users replace the dictionary directly in the context struct.
957
     * We really need an API function to do that cleanly.
958
     */
959
728k
    ctxt->str_xml = xmlDictLookup(ctxt->dict, BAD_CAST "xml", 3);
960
728k
    ctxt->str_xmlns = xmlDictLookup(ctxt->dict, BAD_CAST "xmlns", 5);
961
728k
    ctxt->str_xml_ns = xmlDictLookup(ctxt->dict, XML_XML_NAMESPACE, 36);
962
728k
    if ((ctxt->str_xml==NULL) || (ctxt->str_xmlns==NULL) ||
963
728k
    (ctxt->str_xml_ns == NULL)) {
964
0
        xmlErrMemory(ctxt);
965
0
    }
966
967
728k
    xmlDictSetLimit(ctxt->dict,
968
728k
                    (ctxt->options & XML_PARSE_HUGE) ?
969
0
                        0 :
970
728k
                        XML_MAX_DICTIONARY_LIMIT);
971
728k
}
972
973
typedef struct {
974
    xmlHashedString prefix;
975
    xmlHashedString name;
976
    xmlHashedString value;
977
    const xmlChar *valueEnd;
978
    int external;
979
    int expandedSize;
980
} xmlDefAttr;
981
982
typedef struct _xmlDefAttrs xmlDefAttrs;
983
typedef xmlDefAttrs *xmlDefAttrsPtr;
984
struct _xmlDefAttrs {
985
    int nbAttrs;  /* number of defaulted attributes on that element */
986
    int maxAttrs;       /* the size of the array */
987
#if __STDC_VERSION__ >= 199901L
988
    /* Using a C99 flexible array member avoids UBSan errors. */
989
    xmlDefAttr attrs[] ATTRIBUTE_COUNTED_BY(maxAttrs);
990
#else
991
    xmlDefAttr attrs[1];
992
#endif
993
};
994
995
/**
996
 * xmlAttrNormalizeSpace:
997
 * @src: the source string
998
 * @dst: the target string
999
 *
1000
 * Normalize the space in non CDATA attribute values:
1001
 * If the attribute type is not CDATA, then the XML processor MUST further
1002
 * process the normalized attribute value by discarding any leading and
1003
 * trailing space (#x20) characters, and by replacing sequences of space
1004
 * (#x20) characters by a single space (#x20) character.
1005
 * Note that the size of dst need to be at least src, and if one doesn't need
1006
 * to preserve dst (and it doesn't come from a dictionary or read-only) then
1007
 * passing src as dst is just fine.
1008
 *
1009
 * Returns a pointer to the normalized value (dst) or NULL if no conversion
1010
 *         is needed.
1011
 */
1012
static xmlChar *
1013
xmlAttrNormalizeSpace(const xmlChar *src, xmlChar *dst)
1014
57.8k
{
1015
57.8k
    if ((src == NULL) || (dst == NULL))
1016
0
        return(NULL);
1017
1018
58.1k
    while (*src == 0x20) src++;
1019
29.2M
    while (*src != 0) {
1020
29.2M
  if (*src == 0x20) {
1021
29.7M
      while (*src == 0x20) src++;
1022
73.8k
      if (*src != 0)
1023
73.5k
    *dst++ = 0x20;
1024
29.1M
  } else {
1025
29.1M
      *dst++ = *src++;
1026
29.1M
  }
1027
29.2M
    }
1028
57.8k
    *dst = 0;
1029
57.8k
    if (dst == src)
1030
56.9k
       return(NULL);
1031
861
    return(dst);
1032
57.8k
}
1033
1034
/**
1035
 * xmlAddDefAttrs:
1036
 * @ctxt:  an XML parser context
1037
 * @fullname:  the element fullname
1038
 * @fullattr:  the attribute fullname
1039
 * @value:  the attribute value
1040
 *
1041
 * Add a defaulted attribute for an element
1042
 */
1043
static void
1044
xmlAddDefAttrs(xmlParserCtxtPtr ctxt,
1045
               const xmlChar *fullname,
1046
               const xmlChar *fullattr,
1047
62.6k
               const xmlChar *value) {
1048
62.6k
    xmlDefAttrsPtr defaults;
1049
62.6k
    xmlDefAttr *attr;
1050
62.6k
    int len, expandedSize;
1051
62.6k
    xmlHashedString name;
1052
62.6k
    xmlHashedString prefix;
1053
62.6k
    xmlHashedString hvalue;
1054
62.6k
    const xmlChar *localname;
1055
1056
    /*
1057
     * Allows to detect attribute redefinitions
1058
     */
1059
62.6k
    if (ctxt->attsSpecial != NULL) {
1060
47.5k
        if (xmlHashLookup2(ctxt->attsSpecial, fullname, fullattr) != NULL)
1061
3.07k
      return;
1062
47.5k
    }
1063
1064
59.5k
    if (ctxt->attsDefault == NULL) {
1065
15.7k
        ctxt->attsDefault = xmlHashCreateDict(10, ctxt->dict);
1066
15.7k
  if (ctxt->attsDefault == NULL)
1067
16
      goto mem_error;
1068
15.7k
    }
1069
1070
    /*
1071
     * split the element name into prefix:localname , the string found
1072
     * are within the DTD and then not associated to namespace names.
1073
     */
1074
59.5k
    localname = xmlSplitQName3(fullname, &len);
1075
59.5k
    if (localname == NULL) {
1076
58.2k
        name = xmlDictLookupHashed(ctxt->dict, fullname, -1);
1077
58.2k
  prefix.name = NULL;
1078
58.2k
    } else {
1079
1.32k
        name = xmlDictLookupHashed(ctxt->dict, localname, -1);
1080
1.32k
  prefix = xmlDictLookupHashed(ctxt->dict, fullname, len);
1081
1.32k
        if (prefix.name == NULL)
1082
0
            goto mem_error;
1083
1.32k
    }
1084
59.5k
    if (name.name == NULL)
1085
0
        goto mem_error;
1086
1087
    /*
1088
     * make sure there is some storage
1089
     */
1090
59.5k
    defaults = xmlHashLookup2(ctxt->attsDefault, name.name, prefix.name);
1091
59.5k
    if ((defaults == NULL) ||
1092
43.3k
        (defaults->nbAttrs >= defaults->maxAttrs)) {
1093
21.7k
        xmlDefAttrsPtr temp;
1094
21.7k
        int newSize;
1095
1096
21.7k
        if (defaults == NULL) {
1097
16.1k
            newSize = 4;
1098
16.1k
        } else {
1099
5.61k
            if ((defaults->maxAttrs >= XML_MAX_ATTRS) ||
1100
5.61k
                ((size_t) defaults->maxAttrs >
1101
5.61k
                     SIZE_MAX / 2 / sizeof(temp[0]) - sizeof(*defaults)))
1102
0
                goto mem_error;
1103
1104
5.61k
            if (defaults->maxAttrs > XML_MAX_ATTRS / 2)
1105
0
                newSize = XML_MAX_ATTRS;
1106
5.61k
            else
1107
5.61k
                newSize = defaults->maxAttrs * 2;
1108
5.61k
        }
1109
21.7k
        temp = xmlRealloc(defaults,
1110
21.7k
                          sizeof(*defaults) + newSize * sizeof(xmlDefAttr));
1111
21.7k
  if (temp == NULL)
1112
2
      goto mem_error;
1113
21.7k
        if (defaults == NULL)
1114
16.1k
            temp->nbAttrs = 0;
1115
21.7k
  temp->maxAttrs = newSize;
1116
21.7k
        defaults = temp;
1117
21.7k
  if (xmlHashUpdateEntry2(ctxt->attsDefault, name.name, prefix.name,
1118
21.7k
                          defaults, NULL) < 0) {
1119
0
      xmlFree(defaults);
1120
0
      goto mem_error;
1121
0
  }
1122
21.7k
    }
1123
1124
    /*
1125
     * Split the attribute name into prefix:localname , the string found
1126
     * are within the DTD and hen not associated to namespace names.
1127
     */
1128
59.5k
    localname = xmlSplitQName3(fullattr, &len);
1129
59.5k
    if (localname == NULL) {
1130
15.6k
        name = xmlDictLookupHashed(ctxt->dict, fullattr, -1);
1131
15.6k
  prefix.name = NULL;
1132
43.8k
    } else {
1133
43.8k
        name = xmlDictLookupHashed(ctxt->dict, localname, -1);
1134
43.8k
  prefix = xmlDictLookupHashed(ctxt->dict, fullattr, len);
1135
43.8k
        if (prefix.name == NULL)
1136
3
            goto mem_error;
1137
43.8k
    }
1138
59.5k
    if (name.name == NULL)
1139
1
        goto mem_error;
1140
1141
    /* intern the string and precompute the end */
1142
59.5k
    len = strlen((const char *) value);
1143
59.5k
    hvalue = xmlDictLookupHashed(ctxt->dict, value, len);
1144
59.5k
    if (hvalue.name == NULL)
1145
1
        goto mem_error;
1146
1147
59.5k
    expandedSize = strlen((const char *) name.name);
1148
59.5k
    if (prefix.name != NULL)
1149
43.8k
        expandedSize += strlen((const char *) prefix.name);
1150
59.5k
    expandedSize += len;
1151
1152
59.5k
    attr = &defaults->attrs[defaults->nbAttrs++];
1153
59.5k
    attr->name = name;
1154
59.5k
    attr->prefix = prefix;
1155
59.5k
    attr->value = hvalue;
1156
59.5k
    attr->valueEnd = hvalue.name + len;
1157
59.5k
    attr->external = PARSER_EXTERNAL(ctxt);
1158
59.5k
    attr->expandedSize = expandedSize;
1159
1160
59.5k
    return;
1161
1162
23
mem_error:
1163
23
    xmlErrMemory(ctxt);
1164
23
}
1165
1166
/**
1167
 * xmlAddSpecialAttr:
1168
 * @ctxt:  an XML parser context
1169
 * @fullname:  the element fullname
1170
 * @fullattr:  the attribute fullname
1171
 * @type:  the attribute type
1172
 *
1173
 * Register this attribute type
1174
 */
1175
static void
1176
xmlAddSpecialAttr(xmlParserCtxtPtr ctxt,
1177
      const xmlChar *fullname,
1178
      const xmlChar *fullattr,
1179
      int type)
1180
90.3k
{
1181
90.3k
    if (ctxt->attsSpecial == NULL) {
1182
24.9k
        ctxt->attsSpecial = xmlHashCreateDict(10, ctxt->dict);
1183
24.9k
  if (ctxt->attsSpecial == NULL)
1184
37
      goto mem_error;
1185
24.9k
    }
1186
1187
90.3k
    if (xmlHashAdd2(ctxt->attsSpecial, fullname, fullattr,
1188
90.3k
                    XML_INT_TO_PTR(type)) < 0)
1189
1
        goto mem_error;
1190
90.3k
    return;
1191
1192
90.3k
mem_error:
1193
38
    xmlErrMemory(ctxt);
1194
38
}
1195
1196
/**
1197
 * xmlCleanSpecialAttrCallback:
1198
 *
1199
 * Removes CDATA attributes from the special attribute table
1200
 */
1201
static void
1202
xmlCleanSpecialAttrCallback(void *payload, void *data,
1203
                            const xmlChar *fullname, const xmlChar *fullattr,
1204
83.2k
                            const xmlChar *unused ATTRIBUTE_UNUSED) {
1205
83.2k
    xmlParserCtxtPtr ctxt = (xmlParserCtxtPtr) data;
1206
1207
83.2k
    if (XML_PTR_TO_INT(payload) == XML_ATTRIBUTE_CDATA) {
1208
16.0k
        xmlHashRemoveEntry2(ctxt->attsSpecial, fullname, fullattr, NULL);
1209
16.0k
    }
1210
83.2k
}
1211
1212
/**
1213
 * xmlCleanSpecialAttr:
1214
 * @ctxt:  an XML parser context
1215
 *
1216
 * Trim the list of attributes defined to remove all those of type
1217
 * CDATA as they are not special. This call should be done when finishing
1218
 * to parse the DTD and before starting to parse the document root.
1219
 */
1220
static void
1221
xmlCleanSpecialAttr(xmlParserCtxtPtr ctxt)
1222
165k
{
1223
165k
    if (ctxt->attsSpecial == NULL)
1224
140k
        return;
1225
1226
24.9k
    xmlHashScanFull(ctxt->attsSpecial, xmlCleanSpecialAttrCallback, ctxt);
1227
1228
24.9k
    if (xmlHashSize(ctxt->attsSpecial) == 0) {
1229
4.22k
        xmlHashFree(ctxt->attsSpecial, NULL);
1230
4.22k
        ctxt->attsSpecial = NULL;
1231
4.22k
    }
1232
24.9k
}
1233
1234
/**
1235
 * xmlCheckLanguageID:
1236
 * @lang:  pointer to the string value
1237
 *
1238
 * DEPRECATED: Internal function, do not use.
1239
 *
1240
 * Checks that the value conforms to the LanguageID production:
1241
 *
1242
 * NOTE: this is somewhat deprecated, those productions were removed from
1243
 *       the XML Second edition.
1244
 *
1245
 * [33] LanguageID ::= Langcode ('-' Subcode)*
1246
 * [34] Langcode ::= ISO639Code |  IanaCode |  UserCode
1247
 * [35] ISO639Code ::= ([a-z] | [A-Z]) ([a-z] | [A-Z])
1248
 * [36] IanaCode ::= ('i' | 'I') '-' ([a-z] | [A-Z])+
1249
 * [37] UserCode ::= ('x' | 'X') '-' ([a-z] | [A-Z])+
1250
 * [38] Subcode ::= ([a-z] | [A-Z])+
1251
 *
1252
 * The current REC reference the successors of RFC 1766, currently 5646
1253
 *
1254
 * http://www.rfc-editor.org/rfc/rfc5646.txt
1255
 * langtag       = language
1256
 *                 ["-" script]
1257
 *                 ["-" region]
1258
 *                 *("-" variant)
1259
 *                 *("-" extension)
1260
 *                 ["-" privateuse]
1261
 * language      = 2*3ALPHA            ; shortest ISO 639 code
1262
 *                 ["-" extlang]       ; sometimes followed by
1263
 *                                     ; extended language subtags
1264
 *               / 4ALPHA              ; or reserved for future use
1265
 *               / 5*8ALPHA            ; or registered language subtag
1266
 *
1267
 * extlang       = 3ALPHA              ; selected ISO 639 codes
1268
 *                 *2("-" 3ALPHA)      ; permanently reserved
1269
 *
1270
 * script        = 4ALPHA              ; ISO 15924 code
1271
 *
1272
 * region        = 2ALPHA              ; ISO 3166-1 code
1273
 *               / 3DIGIT              ; UN M.49 code
1274
 *
1275
 * variant       = 5*8alphanum         ; registered variants
1276
 *               / (DIGIT 3alphanum)
1277
 *
1278
 * extension     = singleton 1*("-" (2*8alphanum))
1279
 *
1280
 *                                     ; Single alphanumerics
1281
 *                                     ; "x" reserved for private use
1282
 * singleton     = DIGIT               ; 0 - 9
1283
 *               / %x41-57             ; A - W
1284
 *               / %x59-5A             ; Y - Z
1285
 *               / %x61-77             ; a - w
1286
 *               / %x79-7A             ; y - z
1287
 *
1288
 * it sounds right to still allow Irregular i-xxx IANA and user codes too
1289
 * The parser below doesn't try to cope with extension or privateuse
1290
 * that could be added but that's not interoperable anyway
1291
 *
1292
 * Returns 1 if correct 0 otherwise
1293
 **/
1294
int
1295
xmlCheckLanguageID(const xmlChar * lang)
1296
0
{
1297
0
    const xmlChar *cur = lang, *nxt;
1298
1299
0
    if (cur == NULL)
1300
0
        return (0);
1301
0
    if (((cur[0] == 'i') && (cur[1] == '-')) ||
1302
0
        ((cur[0] == 'I') && (cur[1] == '-')) ||
1303
0
        ((cur[0] == 'x') && (cur[1] == '-')) ||
1304
0
        ((cur[0] == 'X') && (cur[1] == '-'))) {
1305
        /*
1306
         * Still allow IANA code and user code which were coming
1307
         * from the previous version of the XML-1.0 specification
1308
         * it's deprecated but we should not fail
1309
         */
1310
0
        cur += 2;
1311
0
        while (((cur[0] >= 'A') && (cur[0] <= 'Z')) ||
1312
0
               ((cur[0] >= 'a') && (cur[0] <= 'z')))
1313
0
            cur++;
1314
0
        return(cur[0] == 0);
1315
0
    }
1316
0
    nxt = cur;
1317
0
    while (((nxt[0] >= 'A') && (nxt[0] <= 'Z')) ||
1318
0
           ((nxt[0] >= 'a') && (nxt[0] <= 'z')))
1319
0
           nxt++;
1320
0
    if (nxt - cur >= 4) {
1321
        /*
1322
         * Reserved
1323
         */
1324
0
        if ((nxt - cur > 8) || (nxt[0] != 0))
1325
0
            return(0);
1326
0
        return(1);
1327
0
    }
1328
0
    if (nxt - cur < 2)
1329
0
        return(0);
1330
    /* we got an ISO 639 code */
1331
0
    if (nxt[0] == 0)
1332
0
        return(1);
1333
0
    if (nxt[0] != '-')
1334
0
        return(0);
1335
1336
0
    nxt++;
1337
0
    cur = nxt;
1338
    /* now we can have extlang or script or region or variant */
1339
0
    if ((nxt[0] >= '0') && (nxt[0] <= '9'))
1340
0
        goto region_m49;
1341
1342
0
    while (((nxt[0] >= 'A') && (nxt[0] <= 'Z')) ||
1343
0
           ((nxt[0] >= 'a') && (nxt[0] <= 'z')))
1344
0
           nxt++;
1345
0
    if (nxt - cur == 4)
1346
0
        goto script;
1347
0
    if (nxt - cur == 2)
1348
0
        goto region;
1349
0
    if ((nxt - cur >= 5) && (nxt - cur <= 8))
1350
0
        goto variant;
1351
0
    if (nxt - cur != 3)
1352
0
        return(0);
1353
    /* we parsed an extlang */
1354
0
    if (nxt[0] == 0)
1355
0
        return(1);
1356
0
    if (nxt[0] != '-')
1357
0
        return(0);
1358
1359
0
    nxt++;
1360
0
    cur = nxt;
1361
    /* now we can have script or region or variant */
1362
0
    if ((nxt[0] >= '0') && (nxt[0] <= '9'))
1363
0
        goto region_m49;
1364
1365
0
    while (((nxt[0] >= 'A') && (nxt[0] <= 'Z')) ||
1366
0
           ((nxt[0] >= 'a') && (nxt[0] <= 'z')))
1367
0
           nxt++;
1368
0
    if (nxt - cur == 2)
1369
0
        goto region;
1370
0
    if ((nxt - cur >= 5) && (nxt - cur <= 8))
1371
0
        goto variant;
1372
0
    if (nxt - cur != 4)
1373
0
        return(0);
1374
    /* we parsed a script */
1375
0
script:
1376
0
    if (nxt[0] == 0)
1377
0
        return(1);
1378
0
    if (nxt[0] != '-')
1379
0
        return(0);
1380
1381
0
    nxt++;
1382
0
    cur = nxt;
1383
    /* now we can have region or variant */
1384
0
    if ((nxt[0] >= '0') && (nxt[0] <= '9'))
1385
0
        goto region_m49;
1386
1387
0
    while (((nxt[0] >= 'A') && (nxt[0] <= 'Z')) ||
1388
0
           ((nxt[0] >= 'a') && (nxt[0] <= 'z')))
1389
0
           nxt++;
1390
1391
0
    if ((nxt - cur >= 5) && (nxt - cur <= 8))
1392
0
        goto variant;
1393
0
    if (nxt - cur != 2)
1394
0
        return(0);
1395
    /* we parsed a region */
1396
0
region:
1397
0
    if (nxt[0] == 0)
1398
0
        return(1);
1399
0
    if (nxt[0] != '-')
1400
0
        return(0);
1401
1402
0
    nxt++;
1403
0
    cur = nxt;
1404
    /* now we can just have a variant */
1405
0
    while (((nxt[0] >= 'A') && (nxt[0] <= 'Z')) ||
1406
0
           ((nxt[0] >= 'a') && (nxt[0] <= 'z')))
1407
0
           nxt++;
1408
1409
0
    if ((nxt - cur < 5) || (nxt - cur > 8))
1410
0
        return(0);
1411
1412
    /* we parsed a variant */
1413
0
variant:
1414
0
    if (nxt[0] == 0)
1415
0
        return(1);
1416
0
    if (nxt[0] != '-')
1417
0
        return(0);
1418
    /* extensions and private use subtags not checked */
1419
0
    return (1);
1420
1421
0
region_m49:
1422
0
    if (((nxt[1] >= '0') && (nxt[1] <= '9')) &&
1423
0
        ((nxt[2] >= '0') && (nxt[2] <= '9'))) {
1424
0
        nxt += 3;
1425
0
        goto region;
1426
0
    }
1427
0
    return(0);
1428
0
}
1429
1430
/************************************************************************
1431
 *                  *
1432
 *    Parser stacks related functions and macros    *
1433
 *                  *
1434
 ************************************************************************/
1435
1436
static xmlChar *
1437
xmlParseStringEntityRef(xmlParserCtxtPtr ctxt, const xmlChar **str);
1438
1439
/**
1440
 * xmlParserNsCreate:
1441
 *
1442
 * Create a new namespace database.
1443
 *
1444
 * Returns the new obejct.
1445
 */
1446
xmlParserNsData *
1447
876k
xmlParserNsCreate(void) {
1448
876k
    xmlParserNsData *nsdb = xmlMalloc(sizeof(*nsdb));
1449
1450
876k
    if (nsdb == NULL)
1451
47
        return(NULL);
1452
875k
    memset(nsdb, 0, sizeof(*nsdb));
1453
875k
    nsdb->defaultNsIndex = INT_MAX;
1454
1455
875k
    return(nsdb);
1456
876k
}
1457
1458
/**
1459
 * xmlParserNsFree:
1460
 * @nsdb: namespace database
1461
 *
1462
 * Free a namespace database.
1463
 */
1464
void
1465
875k
xmlParserNsFree(xmlParserNsData *nsdb) {
1466
875k
    if (nsdb == NULL)
1467
0
        return;
1468
1469
875k
    xmlFree(nsdb->extra);
1470
875k
    xmlFree(nsdb->hash);
1471
875k
    xmlFree(nsdb);
1472
875k
}
1473
1474
/**
1475
 * xmlParserNsReset:
1476
 * @nsdb: namespace database
1477
 *
1478
 * Reset a namespace database.
1479
 */
1480
static void
1481
0
xmlParserNsReset(xmlParserNsData *nsdb) {
1482
0
    if (nsdb == NULL)
1483
0
        return;
1484
1485
0
    nsdb->hashElems = 0;
1486
0
    nsdb->elementId = 0;
1487
0
    nsdb->defaultNsIndex = INT_MAX;
1488
1489
0
    if (nsdb->hash)
1490
0
        memset(nsdb->hash, 0, nsdb->hashSize * sizeof(nsdb->hash[0]));
1491
0
}
1492
1493
/**
1494
 * xmlParserStartElement:
1495
 * @nsdb: namespace database
1496
 *
1497
 * Signal that a new element has started.
1498
 *
1499
 * Returns 0 on success, -1 if the element counter overflowed.
1500
 */
1501
static int
1502
5.13M
xmlParserNsStartElement(xmlParserNsData *nsdb) {
1503
5.13M
    if (nsdb->elementId == UINT_MAX)
1504
0
        return(-1);
1505
5.13M
    nsdb->elementId++;
1506
1507
5.13M
    return(0);
1508
5.13M
}
1509
1510
/**
1511
 * xmlParserNsLookup:
1512
 * @ctxt: parser context
1513
 * @prefix: namespace prefix
1514
 * @bucketPtr: optional bucket (return value)
1515
 *
1516
 * Lookup namespace with given prefix. If @bucketPtr is non-NULL, it will
1517
 * be set to the matching bucket, or the first empty bucket if no match
1518
 * was found.
1519
 *
1520
 * Returns the namespace index on success, INT_MAX if no namespace was
1521
 * found.
1522
 */
1523
static int
1524
xmlParserNsLookup(xmlParserCtxtPtr ctxt, const xmlHashedString *prefix,
1525
10.3M
                  xmlParserNsBucket **bucketPtr) {
1526
10.3M
    xmlParserNsBucket *bucket, *tombstone;
1527
10.3M
    unsigned index, hashValue;
1528
1529
10.3M
    if (prefix->name == NULL)
1530
2.39M
        return(ctxt->nsdb->defaultNsIndex);
1531
1532
7.93M
    if (ctxt->nsdb->hashSize == 0)
1533
665k
        return(INT_MAX);
1534
1535
7.27M
    hashValue = prefix->hashValue;
1536
7.27M
    index = hashValue & (ctxt->nsdb->hashSize - 1);
1537
7.27M
    bucket = &ctxt->nsdb->hash[index];
1538
7.27M
    tombstone = NULL;
1539
1540
7.90M
    while (bucket->hashValue) {
1541
7.21M
        if (bucket->index == INT_MAX) {
1542
140k
            if (tombstone == NULL)
1543
117k
                tombstone = bucket;
1544
7.07M
        } else if (bucket->hashValue == hashValue) {
1545
6.58M
            if (ctxt->nsTab[bucket->index * 2] == prefix->name) {
1546
6.58M
                if (bucketPtr != NULL)
1547
1.75M
                    *bucketPtr = bucket;
1548
6.58M
                return(bucket->index);
1549
6.58M
            }
1550
6.58M
        }
1551
1552
635k
        index++;
1553
635k
        bucket++;
1554
635k
        if (index == ctxt->nsdb->hashSize) {
1555
49.7k
            index = 0;
1556
49.7k
            bucket = ctxt->nsdb->hash;
1557
49.7k
        }
1558
635k
    }
1559
1560
689k
    if (bucketPtr != NULL)
1561
188k
        *bucketPtr = tombstone ? tombstone : bucket;
1562
689k
    return(INT_MAX);
1563
7.27M
}
1564
1565
/**
1566
 * xmlParserNsLookupUri:
1567
 * @ctxt: parser context
1568
 * @prefix: namespace prefix
1569
 *
1570
 * Lookup namespace URI with given prefix.
1571
 *
1572
 * Returns the namespace URI on success, NULL if no namespace was found.
1573
 */
1574
static const xmlChar *
1575
4.83M
xmlParserNsLookupUri(xmlParserCtxtPtr ctxt, const xmlHashedString *prefix) {
1576
4.83M
    const xmlChar *ret;
1577
4.83M
    int nsIndex;
1578
1579
4.83M
    if (prefix->name == ctxt->str_xml)
1580
583
        return(ctxt->str_xml_ns);
1581
1582
    /*
1583
     * minNsIndex is used when building an entity tree. We must
1584
     * ignore namespaces declared outside the entity.
1585
     */
1586
4.83M
    nsIndex = xmlParserNsLookup(ctxt, prefix, NULL);
1587
4.83M
    if ((nsIndex == INT_MAX) || (nsIndex < ctxt->nsdb->minNsIndex))
1588
1.88M
        return(NULL);
1589
1590
2.95M
    ret = ctxt->nsTab[nsIndex * 2 + 1];
1591
2.95M
    if (ret[0] == 0)
1592
29.3k
        ret = NULL;
1593
2.95M
    return(ret);
1594
4.83M
}
1595
1596
/**
1597
 * xmlParserNsLookupSax:
1598
 * @ctxt: parser context
1599
 * @prefix: namespace prefix
1600
 *
1601
 * Lookup extra data for the given prefix. This returns data stored
1602
 * with xmlParserNsUdpateSax.
1603
 *
1604
 * Returns the data on success, NULL if no namespace was found.
1605
 */
1606
void *
1607
2.05M
xmlParserNsLookupSax(xmlParserCtxtPtr ctxt, const xmlChar *prefix) {
1608
2.05M
    xmlHashedString hprefix;
1609
2.05M
    int nsIndex;
1610
1611
2.05M
    if (prefix == ctxt->str_xml)
1612
55.4k
        return(NULL);
1613
1614
1.99M
    hprefix.name = prefix;
1615
1.99M
    if (prefix != NULL)
1616
1.85M
        hprefix.hashValue = xmlDictComputeHash(ctxt->dict, prefix);
1617
138k
    else
1618
138k
        hprefix.hashValue = 0;
1619
1.99M
    nsIndex = xmlParserNsLookup(ctxt, &hprefix, NULL);
1620
1.99M
    if ((nsIndex == INT_MAX) || (nsIndex < ctxt->nsdb->minNsIndex))
1621
0
        return(NULL);
1622
1623
1.99M
    return(ctxt->nsdb->extra[nsIndex].saxData);
1624
1.99M
}
1625
1626
/**
1627
 * xmlParserNsUpdateSax:
1628
 * @ctxt: parser context
1629
 * @prefix: namespace prefix
1630
 * @saxData: extra data for SAX handler
1631
 *
1632
 * Sets or updates extra data for the given prefix. This value will be
1633
 * returned by xmlParserNsLookupSax as long as the namespace with the
1634
 * given prefix is in scope.
1635
 *
1636
 * Returns the data on success, NULL if no namespace was found.
1637
 */
1638
int
1639
xmlParserNsUpdateSax(xmlParserCtxtPtr ctxt, const xmlChar *prefix,
1640
588k
                     void *saxData) {
1641
588k
    xmlHashedString hprefix;
1642
588k
    int nsIndex;
1643
1644
588k
    if (prefix == ctxt->str_xml)
1645
0
        return(-1);
1646
1647
588k
    hprefix.name = prefix;
1648
588k
    if (prefix != NULL)
1649
566k
        hprefix.hashValue = xmlDictComputeHash(ctxt->dict, prefix);
1650
22.0k
    else
1651
22.0k
        hprefix.hashValue = 0;
1652
588k
    nsIndex = xmlParserNsLookup(ctxt, &hprefix, NULL);
1653
588k
    if ((nsIndex == INT_MAX) || (nsIndex < ctxt->nsdb->minNsIndex))
1654
0
        return(-1);
1655
1656
588k
    ctxt->nsdb->extra[nsIndex].saxData = saxData;
1657
588k
    return(0);
1658
588k
}
1659
1660
/**
1661
 * xmlParserNsGrow:
1662
 * @ctxt: parser context
1663
 *
1664
 * Grows the namespace tables.
1665
 *
1666
 * Returns 0 on success, -1 if a memory allocation failed.
1667
 */
1668
static int
1669
616k
xmlParserNsGrow(xmlParserCtxtPtr ctxt) {
1670
616k
    const xmlChar **table;
1671
616k
    xmlParserNsExtra *extra;
1672
616k
    int newSize;
1673
1674
616k
    newSize = xmlGrowCapacity(ctxt->nsMax,
1675
616k
                              sizeof(table[0]) + sizeof(extra[0]),
1676
616k
                              16, XML_MAX_ITEMS);
1677
616k
    if (newSize < 0)
1678
0
        goto error;
1679
1680
616k
    table = xmlRealloc(ctxt->nsTab, 2 * newSize * sizeof(table[0]));
1681
616k
    if (table == NULL)
1682
68
        goto error;
1683
616k
    ctxt->nsTab = table;
1684
1685
616k
    extra = xmlRealloc(ctxt->nsdb->extra, newSize * sizeof(extra[0]));
1686
616k
    if (extra == NULL)
1687
44
        goto error;
1688
616k
    ctxt->nsdb->extra = extra;
1689
1690
616k
    ctxt->nsMax = newSize;
1691
616k
    return(0);
1692
1693
112
error:
1694
112
    xmlErrMemory(ctxt);
1695
112
    return(-1);
1696
616k
}
1697
1698
/**
1699
 * xmlParserNsPush:
1700
 * @ctxt: parser context
1701
 * @prefix: prefix with hash value
1702
 * @uri: uri with hash value
1703
 * @saxData: extra data for SAX handler
1704
 * @defAttr: whether the namespace comes from a default attribute
1705
 *
1706
 * Push a new namespace on the table.
1707
 *
1708
 * Returns 1 if the namespace was pushed, 0 if the namespace was ignored,
1709
 * -1 if a memory allocation failed.
1710
 */
1711
static int
1712
xmlParserNsPush(xmlParserCtxtPtr ctxt, const xmlHashedString *prefix,
1713
1.53M
                const xmlHashedString *uri, void *saxData, int defAttr) {
1714
1.53M
    xmlParserNsBucket *bucket = NULL;
1715
1.53M
    xmlParserNsExtra *extra;
1716
1.53M
    const xmlChar **ns;
1717
1.53M
    unsigned hashValue, nsIndex, oldIndex;
1718
1719
1.53M
    if ((prefix != NULL) && (prefix->name == ctxt->str_xml))
1720
740
        return(0);
1721
1722
1.53M
    if ((ctxt->nsNr >= ctxt->nsMax) && (xmlParserNsGrow(ctxt) < 0)) {
1723
112
        xmlErrMemory(ctxt);
1724
112
        return(-1);
1725
112
    }
1726
1727
    /*
1728
     * Default namespace and 'xml' namespace
1729
     */
1730
1.53M
    if ((prefix == NULL) || (prefix->name == NULL)) {
1731
302k
        oldIndex = ctxt->nsdb->defaultNsIndex;
1732
1733
302k
        if (oldIndex != INT_MAX) {
1734
257k
            extra = &ctxt->nsdb->extra[oldIndex];
1735
1736
257k
            if (extra->elementId == ctxt->nsdb->elementId) {
1737
1.68k
                if (defAttr == 0)
1738
694
                    xmlErrAttributeDup(ctxt, NULL, BAD_CAST "xmlns");
1739
1.68k
                return(0);
1740
1.68k
            }
1741
1742
255k
            if ((ctxt->options & XML_PARSE_NSCLEAN) &&
1743
0
                (uri->name == ctxt->nsTab[oldIndex * 2 + 1]))
1744
0
                return(0);
1745
255k
        }
1746
1747
300k
        ctxt->nsdb->defaultNsIndex = ctxt->nsNr;
1748
300k
        goto populate_entry;
1749
302k
    }
1750
1751
    /*
1752
     * Hash table lookup
1753
     */
1754
1.22M
    oldIndex = xmlParserNsLookup(ctxt, prefix, &bucket);
1755
1.22M
    if (oldIndex != INT_MAX) {
1756
560k
        extra = &ctxt->nsdb->extra[oldIndex];
1757
1758
        /*
1759
         * Check for duplicate definitions on the same element.
1760
         */
1761
560k
        if (extra->elementId == ctxt->nsdb->elementId) {
1762
912
            if (defAttr == 0)
1763
693
                xmlErrAttributeDup(ctxt, BAD_CAST "xmlns", prefix->name);
1764
912
            return(0);
1765
912
        }
1766
1767
559k
        if ((ctxt->options & XML_PARSE_NSCLEAN) &&
1768
0
            (uri->name == ctxt->nsTab[bucket->index * 2 + 1]))
1769
0
            return(0);
1770
1771
559k
        bucket->index = ctxt->nsNr;
1772
559k
        goto populate_entry;
1773
559k
    }
1774
1775
    /*
1776
     * Insert new bucket
1777
     */
1778
1779
668k
    hashValue = prefix->hashValue;
1780
1781
    /*
1782
     * Grow hash table, 50% fill factor
1783
     */
1784
668k
    if (ctxt->nsdb->hashElems + 1 > ctxt->nsdb->hashSize / 2) {
1785
483k
        xmlParserNsBucket *newHash;
1786
483k
        unsigned newSize, i, index;
1787
1788
483k
        if (ctxt->nsdb->hashSize > UINT_MAX / 2) {
1789
0
            xmlErrMemory(ctxt);
1790
0
            return(-1);
1791
0
        }
1792
483k
        newSize = ctxt->nsdb->hashSize ? ctxt->nsdb->hashSize * 2 : 16;
1793
483k
        newHash = xmlMalloc(newSize * sizeof(newHash[0]));
1794
483k
        if (newHash == NULL) {
1795
44
            xmlErrMemory(ctxt);
1796
44
            return(-1);
1797
44
        }
1798
483k
        memset(newHash, 0, newSize * sizeof(newHash[0]));
1799
1800
748k
        for (i = 0; i < ctxt->nsdb->hashSize; i++) {
1801
265k
            unsigned hv = ctxt->nsdb->hash[i].hashValue;
1802
265k
            unsigned newIndex;
1803
1804
265k
            if ((hv == 0) || (ctxt->nsdb->hash[i].index == INT_MAX))
1805
238k
                continue;
1806
26.5k
            newIndex = hv & (newSize - 1);
1807
1808
41.4k
            while (newHash[newIndex].hashValue != 0) {
1809
14.9k
                newIndex++;
1810
14.9k
                if (newIndex == newSize)
1811
3.07k
                    newIndex = 0;
1812
14.9k
            }
1813
1814
26.5k
            newHash[newIndex] = ctxt->nsdb->hash[i];
1815
26.5k
        }
1816
1817
483k
        xmlFree(ctxt->nsdb->hash);
1818
483k
        ctxt->nsdb->hash = newHash;
1819
483k
        ctxt->nsdb->hashSize = newSize;
1820
1821
        /*
1822
         * Relookup
1823
         */
1824
483k
        index = hashValue & (newSize - 1);
1825
1826
487k
        while (newHash[index].hashValue != 0) {
1827
4.02k
            index++;
1828
4.02k
            if (index == newSize)
1829
1.25k
                index = 0;
1830
4.02k
        }
1831
1832
483k
        bucket = &newHash[index];
1833
483k
    }
1834
1835
668k
    bucket->hashValue = hashValue;
1836
668k
    bucket->index = ctxt->nsNr;
1837
668k
    ctxt->nsdb->hashElems++;
1838
668k
    oldIndex = INT_MAX;
1839
1840
1.52M
populate_entry:
1841
1.52M
    nsIndex = ctxt->nsNr;
1842
1843
1.52M
    ns = &ctxt->nsTab[nsIndex * 2];
1844
1.52M
    ns[0] = prefix ? prefix->name : NULL;
1845
1.52M
    ns[1] = uri->name;
1846
1847
1.52M
    extra = &ctxt->nsdb->extra[nsIndex];
1848
1.52M
    extra->saxData = saxData;
1849
1.52M
    extra->prefixHashValue = prefix ? prefix->hashValue : 0;
1850
1.52M
    extra->uriHashValue = uri->hashValue;
1851
1.52M
    extra->elementId = ctxt->nsdb->elementId;
1852
1.52M
    extra->oldIndex = oldIndex;
1853
1854
1.52M
    ctxt->nsNr++;
1855
1856
1.52M
    return(1);
1857
668k
}
1858
1859
/**
1860
 * xmlParserNsPop:
1861
 * @ctxt: an XML parser context
1862
 * @nr:  the number to pop
1863
 *
1864
 * Pops the top @nr namespaces and restores the hash table.
1865
 *
1866
 * Returns the number of namespaces popped.
1867
 */
1868
static int
1869
xmlParserNsPop(xmlParserCtxtPtr ctxt, int nr)
1870
789k
{
1871
789k
    int i;
1872
1873
    /* assert(nr <= ctxt->nsNr); */
1874
1875
2.28M
    for (i = ctxt->nsNr - 1; i >= ctxt->nsNr - nr; i--) {
1876
1.49M
        const xmlChar *prefix = ctxt->nsTab[i * 2];
1877
1.49M
        xmlParserNsExtra *extra = &ctxt->nsdb->extra[i];
1878
1879
1.49M
        if (prefix == NULL) {
1880
295k
            ctxt->nsdb->defaultNsIndex = extra->oldIndex;
1881
1.19M
        } else {
1882
1.19M
            xmlHashedString hprefix;
1883
1.19M
            xmlParserNsBucket *bucket = NULL;
1884
1885
1.19M
            hprefix.name = prefix;
1886
1.19M
            hprefix.hashValue = extra->prefixHashValue;
1887
1.19M
            xmlParserNsLookup(ctxt, &hprefix, &bucket);
1888
            /* assert(bucket && bucket->hashValue); */
1889
1.19M
            bucket->index = extra->oldIndex;
1890
1.19M
        }
1891
1.49M
    }
1892
1893
789k
    ctxt->nsNr -= nr;
1894
789k
    return(nr);
1895
789k
}
1896
1897
static int
1898
688k
xmlCtxtGrowAttrs(xmlParserCtxtPtr ctxt) {
1899
688k
    const xmlChar **atts;
1900
688k
    unsigned *attallocs;
1901
688k
    int newSize;
1902
1903
688k
    newSize = xmlGrowCapacity(ctxt->maxatts / 5,
1904
688k
                              sizeof(atts[0]) * 5 + sizeof(attallocs[0]),
1905
688k
                              10, XML_MAX_ATTRS);
1906
688k
    if (newSize < 0) {
1907
0
        xmlFatalErr(ctxt, XML_ERR_RESOURCE_LIMIT,
1908
0
                    "Maximum number of attributes exceeded");
1909
0
        return(-1);
1910
0
    }
1911
1912
688k
    atts = xmlRealloc(ctxt->atts, newSize * sizeof(atts[0]) * 5);
1913
688k
    if (atts == NULL)
1914
54
        goto mem_error;
1915
688k
    ctxt->atts = atts;
1916
1917
688k
    attallocs = xmlRealloc(ctxt->attallocs,
1918
688k
                           newSize * sizeof(attallocs[0]));
1919
688k
    if (attallocs == NULL)
1920
44
        goto mem_error;
1921
688k
    ctxt->attallocs = attallocs;
1922
1923
688k
    ctxt->maxatts = newSize * 5;
1924
1925
688k
    return(0);
1926
1927
98
mem_error:
1928
98
    xmlErrMemory(ctxt);
1929
98
    return(-1);
1930
688k
}
1931
1932
/**
1933
 * xmlCtxtPushInput:
1934
 * @ctxt:  an XML parser context
1935
 * @value:  the parser input
1936
 *
1937
 * Pushes a new parser input on top of the input stack
1938
 *
1939
 * Returns -1 in case of error, the index in the stack otherwise
1940
 */
1941
int
1942
xmlCtxtPushInput(xmlParserCtxtPtr ctxt, xmlParserInputPtr value)
1943
797k
{
1944
797k
    char *directory = NULL;
1945
797k
    int maxDepth;
1946
1947
797k
    if ((ctxt == NULL) || (value == NULL))
1948
4.48k
        return(-1);
1949
1950
792k
    maxDepth = (ctxt->options & XML_PARSE_HUGE) ? 40 : 20;
1951
1952
792k
    if (ctxt->inputNr >= ctxt->inputMax) {
1953
43.7k
        xmlParserInputPtr *tmp;
1954
43.7k
        int newSize;
1955
1956
43.7k
        newSize = xmlGrowCapacity(ctxt->inputMax, sizeof(tmp[0]),
1957
43.7k
                                  5, maxDepth);
1958
43.7k
        if (newSize < 0) {
1959
0
            xmlFatalErrMsg(ctxt, XML_ERR_RESOURCE_LIMIT,
1960
0
                           "Maximum entity nesting depth exceeded");
1961
0
            xmlHaltParser(ctxt);
1962
0
            return(-1);
1963
0
        }
1964
43.7k
        tmp = xmlRealloc(ctxt->inputTab, newSize * sizeof(tmp[0]));
1965
43.7k
        if (tmp == NULL) {
1966
2
            xmlErrMemory(ctxt);
1967
2
            return(-1);
1968
2
        }
1969
43.7k
        ctxt->inputTab = tmp;
1970
43.7k
        ctxt->inputMax = newSize;
1971
43.7k
    }
1972
1973
792k
    if ((ctxt->inputNr == 0) && (value->filename != NULL)) {
1974
62.7k
        directory = xmlParserGetDirectory(value->filename);
1975
62.7k
        if (directory == NULL) {
1976
0
            xmlErrMemory(ctxt);
1977
0
            return(-1);
1978
0
        }
1979
62.7k
    }
1980
1981
792k
    if (ctxt->input_id >= INT_MAX) {
1982
0
        xmlFatalErrMsg(ctxt, XML_ERR_RESOURCE_LIMIT, "Input ID overflow\n");
1983
0
        return(-1);
1984
0
    }
1985
1986
792k
    ctxt->inputTab[ctxt->inputNr] = value;
1987
792k
    ctxt->input = value;
1988
1989
792k
    if (ctxt->inputNr == 0) {
1990
744k
        xmlFree(ctxt->directory);
1991
744k
        ctxt->directory = directory;
1992
744k
    }
1993
1994
    /*
1995
     * Internally, the input ID is only used to detect parameter entity
1996
     * boundaries. But there are entity loaders in downstream code that
1997
     * detect the main document by checking for "input_id == 1".
1998
     */
1999
792k
    value->id = ctxt->input_id++;
2000
2001
792k
    return(ctxt->inputNr++);
2002
792k
}
2003
2004
/**
2005
 * xmlCtxtPopInput:
2006
 * @ctxt: an XML parser context
2007
 *
2008
 * Pops the top parser input from the input stack
2009
 *
2010
 * Returns the input just removed
2011
 */
2012
xmlParserInputPtr
2013
xmlCtxtPopInput(xmlParserCtxtPtr ctxt)
2014
2.53M
{
2015
2.53M
    xmlParserInputPtr ret;
2016
2017
2.53M
    if (ctxt == NULL)
2018
0
        return(NULL);
2019
2.53M
    if (ctxt->inputNr <= 0)
2020
1.75M
        return (NULL);
2021
779k
    ctxt->inputNr--;
2022
779k
    if (ctxt->inputNr > 0)
2023
48.5k
        ctxt->input = ctxt->inputTab[ctxt->inputNr - 1];
2024
730k
    else
2025
730k
        ctxt->input = NULL;
2026
779k
    ret = ctxt->inputTab[ctxt->inputNr];
2027
779k
    ctxt->inputTab[ctxt->inputNr] = NULL;
2028
779k
    return (ret);
2029
2.53M
}
2030
2031
/**
2032
 * nodePush:
2033
 * @ctxt:  an XML parser context
2034
 * @value:  the element node
2035
 *
2036
 * DEPRECATED: Internal function, do not use.
2037
 *
2038
 * Pushes a new element node on top of the node stack
2039
 *
2040
 * Returns -1 in case of error, the index in the stack otherwise
2041
 */
2042
int
2043
nodePush(xmlParserCtxtPtr ctxt, xmlNodePtr value)
2044
3.94M
{
2045
3.94M
    if (ctxt == NULL)
2046
0
        return(0);
2047
2048
3.94M
    if (ctxt->nodeNr >= ctxt->nodeMax) {
2049
656k
        int maxDepth = (ctxt->options & XML_PARSE_HUGE) ? 2048 : 256;
2050
656k
        xmlNodePtr *tmp;
2051
656k
        int newSize;
2052
2053
656k
        newSize = xmlGrowCapacity(ctxt->nodeMax, sizeof(tmp[0]),
2054
656k
                                  10, maxDepth);
2055
656k
        if (newSize < 0) {
2056
245
            xmlFatalErrMsgInt(ctxt, XML_ERR_RESOURCE_LIMIT,
2057
245
                    "Excessive depth in document: %d,"
2058
245
                    " use XML_PARSE_HUGE option\n",
2059
245
                    ctxt->nodeNr);
2060
245
            xmlHaltParser(ctxt);
2061
245
            return(-1);
2062
245
        }
2063
2064
656k
  tmp = xmlRealloc(ctxt->nodeTab, newSize * sizeof(tmp[0]));
2065
656k
        if (tmp == NULL) {
2066
36
            xmlErrMemory(ctxt);
2067
36
            return (-1);
2068
36
        }
2069
656k
        ctxt->nodeTab = tmp;
2070
656k
  ctxt->nodeMax = newSize;
2071
656k
    }
2072
2073
3.94M
    ctxt->nodeTab[ctxt->nodeNr] = value;
2074
3.94M
    ctxt->node = value;
2075
3.94M
    return (ctxt->nodeNr++);
2076
3.94M
}
2077
2078
/**
2079
 * nodePop:
2080
 * @ctxt: an XML parser context
2081
 *
2082
 * DEPRECATED: Internal function, do not use.
2083
 *
2084
 * Pops the top element node from the node stack
2085
 *
2086
 * Returns the node just removed
2087
 */
2088
xmlNodePtr
2089
nodePop(xmlParserCtxtPtr ctxt)
2090
4.34M
{
2091
4.34M
    xmlNodePtr ret;
2092
2093
4.34M
    if (ctxt == NULL) return(NULL);
2094
4.34M
    if (ctxt->nodeNr <= 0)
2095
425k
        return (NULL);
2096
3.92M
    ctxt->nodeNr--;
2097
3.92M
    if (ctxt->nodeNr > 0)
2098
3.42M
        ctxt->node = ctxt->nodeTab[ctxt->nodeNr - 1];
2099
497k
    else
2100
497k
        ctxt->node = NULL;
2101
3.92M
    ret = ctxt->nodeTab[ctxt->nodeNr];
2102
3.92M
    ctxt->nodeTab[ctxt->nodeNr] = NULL;
2103
3.92M
    return (ret);
2104
4.34M
}
2105
2106
/**
2107
 * nameNsPush:
2108
 * @ctxt:  an XML parser context
2109
 * @value:  the element name
2110
 * @prefix:  the element prefix
2111
 * @URI:  the element namespace name
2112
 * @line:  the current line number for error messages
2113
 * @nsNr:  the number of namespaces pushed on the namespace table
2114
 *
2115
 * Pushes a new element name/prefix/URL on top of the name stack
2116
 *
2117
 * Returns -1 in case of error, the index in the stack otherwise
2118
 */
2119
static int
2120
nameNsPush(xmlParserCtxtPtr ctxt, const xmlChar * value,
2121
           const xmlChar *prefix, const xmlChar *URI, int line, int nsNr)
2122
4.84M
{
2123
4.84M
    xmlStartTag *tag;
2124
2125
4.84M
    if (ctxt->nameNr >= ctxt->nameMax) {
2126
732k
        const xmlChar **tmp;
2127
732k
        xmlStartTag *tmp2;
2128
732k
        int newSize;
2129
2130
732k
        newSize = xmlGrowCapacity(ctxt->nameMax,
2131
732k
                                  sizeof(tmp[0]) + sizeof(tmp2[0]),
2132
732k
                                  10, XML_MAX_ITEMS);
2133
732k
        if (newSize < 0)
2134
0
            goto mem_error;
2135
2136
732k
        tmp = xmlRealloc(ctxt->nameTab, newSize * sizeof(tmp[0]));
2137
732k
        if (tmp == NULL)
2138
278
      goto mem_error;
2139
732k
  ctxt->nameTab = tmp;
2140
2141
732k
        tmp2 = xmlRealloc(ctxt->pushTab, newSize * sizeof(tmp2[0]));
2142
732k
        if (tmp2 == NULL)
2143
38
      goto mem_error;
2144
732k
  ctxt->pushTab = tmp2;
2145
2146
732k
        ctxt->nameMax = newSize;
2147
4.11M
    } else if (ctxt->pushTab == NULL) {
2148
560k
        ctxt->pushTab = xmlMalloc(ctxt->nameMax * sizeof(ctxt->pushTab[0]));
2149
560k
        if (ctxt->pushTab == NULL)
2150
712
            goto mem_error;
2151
560k
    }
2152
4.84M
    ctxt->nameTab[ctxt->nameNr] = value;
2153
4.84M
    ctxt->name = value;
2154
4.84M
    tag = &ctxt->pushTab[ctxt->nameNr];
2155
4.84M
    tag->prefix = prefix;
2156
4.84M
    tag->URI = URI;
2157
4.84M
    tag->line = line;
2158
4.84M
    tag->nsNr = nsNr;
2159
4.84M
    return (ctxt->nameNr++);
2160
1.02k
mem_error:
2161
1.02k
    xmlErrMemory(ctxt);
2162
1.02k
    return (-1);
2163
4.84M
}
2164
#ifdef LIBXML_PUSH_ENABLED
2165
/**
2166
 * nameNsPop:
2167
 * @ctxt: an XML parser context
2168
 *
2169
 * Pops the top element/prefix/URI name from the name stack
2170
 *
2171
 * Returns the name just removed
2172
 */
2173
static const xmlChar *
2174
nameNsPop(xmlParserCtxtPtr ctxt)
2175
{
2176
    const xmlChar *ret;
2177
2178
    if (ctxt->nameNr <= 0)
2179
        return (NULL);
2180
    ctxt->nameNr--;
2181
    if (ctxt->nameNr > 0)
2182
        ctxt->name = ctxt->nameTab[ctxt->nameNr - 1];
2183
    else
2184
        ctxt->name = NULL;
2185
    ret = ctxt->nameTab[ctxt->nameNr];
2186
    ctxt->nameTab[ctxt->nameNr] = NULL;
2187
    return (ret);
2188
}
2189
#endif /* LIBXML_PUSH_ENABLED */
2190
2191
/**
2192
 * namePop:
2193
 * @ctxt: an XML parser context
2194
 *
2195
 * DEPRECATED: Internal function, do not use.
2196
 *
2197
 * Pops the top element name from the name stack
2198
 *
2199
 * Returns the name just removed
2200
 */
2201
static const xmlChar *
2202
namePop(xmlParserCtxtPtr ctxt)
2203
4.79M
{
2204
4.79M
    const xmlChar *ret;
2205
2206
4.79M
    if ((ctxt == NULL) || (ctxt->nameNr <= 0))
2207
270
        return (NULL);
2208
4.79M
    ctxt->nameNr--;
2209
4.79M
    if (ctxt->nameNr > 0)
2210
4.28M
        ctxt->name = ctxt->nameTab[ctxt->nameNr - 1];
2211
508k
    else
2212
508k
        ctxt->name = NULL;
2213
4.79M
    ret = ctxt->nameTab[ctxt->nameNr];
2214
4.79M
    ctxt->nameTab[ctxt->nameNr] = NULL;
2215
4.79M
    return (ret);
2216
4.79M
}
2217
2218
5.14M
static int spacePush(xmlParserCtxtPtr ctxt, int val) {
2219
5.14M
    if (ctxt->spaceNr >= ctxt->spaceMax) {
2220
1.25M
        int *tmp;
2221
1.25M
        int newSize;
2222
2223
1.25M
        newSize = xmlGrowCapacity(ctxt->spaceMax, sizeof(tmp[0]),
2224
1.25M
                                  10, XML_MAX_ITEMS);
2225
1.25M
        if (newSize < 0) {
2226
0
      xmlErrMemory(ctxt);
2227
0
      return(-1);
2228
0
        }
2229
2230
1.25M
        tmp = xmlRealloc(ctxt->spaceTab, newSize * sizeof(tmp[0]));
2231
1.25M
        if (tmp == NULL) {
2232
172
      xmlErrMemory(ctxt);
2233
172
      return(-1);
2234
172
  }
2235
1.25M
  ctxt->spaceTab = tmp;
2236
2237
1.25M
        ctxt->spaceMax = newSize;
2238
1.25M
    }
2239
5.14M
    ctxt->spaceTab[ctxt->spaceNr] = val;
2240
5.14M
    ctxt->space = &ctxt->spaceTab[ctxt->spaceNr];
2241
5.14M
    return(ctxt->spaceNr++);
2242
5.14M
}
2243
2244
5.09M
static int spacePop(xmlParserCtxtPtr ctxt) {
2245
5.09M
    int ret;
2246
5.09M
    if (ctxt->spaceNr <= 0) return(0);
2247
5.09M
    ctxt->spaceNr--;
2248
5.09M
    if (ctxt->spaceNr > 0)
2249
5.09M
  ctxt->space = &ctxt->spaceTab[ctxt->spaceNr - 1];
2250
115
    else
2251
115
        ctxt->space = &ctxt->spaceTab[0];
2252
5.09M
    ret = ctxt->spaceTab[ctxt->spaceNr];
2253
5.09M
    ctxt->spaceTab[ctxt->spaceNr] = -1;
2254
5.09M
    return(ret);
2255
5.09M
}
2256
2257
/*
2258
 * Macros for accessing the content. Those should be used only by the parser,
2259
 * and not exported.
2260
 *
2261
 * Dirty macros, i.e. one often need to make assumption on the context to
2262
 * use them
2263
 *
2264
 *   CUR_PTR return the current pointer to the xmlChar to be parsed.
2265
 *           To be used with extreme caution since operations consuming
2266
 *           characters may move the input buffer to a different location !
2267
 *   CUR     returns the current xmlChar value, i.e. a 8 bit value if compiled
2268
 *           This should be used internally by the parser
2269
 *           only to compare to ASCII values otherwise it would break when
2270
 *           running with UTF-8 encoding.
2271
 *   RAW     same as CUR but in the input buffer, bypass any token
2272
 *           extraction that may have been done
2273
 *   NXT(n)  returns the n'th next xmlChar. Same as CUR is should be used only
2274
 *           to compare on ASCII based substring.
2275
 *   SKIP(n) Skip n xmlChar, and must also be used only to skip ASCII defined
2276
 *           strings without newlines within the parser.
2277
 *   NEXT1(l) Skip 1 xmlChar, and must also be used only to skip 1 non-newline ASCII
2278
 *           defined char within the parser.
2279
 * Clean macros, not dependent of an ASCII context, expect UTF-8 encoding
2280
 *
2281
 *   NEXT    Skip to the next character, this does the proper decoding
2282
 *           in UTF-8 mode. It also pop-up unfinished entities on the fly.
2283
 *   NEXTL(l) Skip the current unicode character of l xmlChars long.
2284
 *   CUR_SCHAR  same but operate on a string instead of the context
2285
 *   COPY_BUF  copy the current unicode char to the target buffer, increment
2286
 *            the index
2287
 *   GROW, SHRINK  handling of input buffers
2288
 */
2289
2290
57.4M
#define RAW (*ctxt->input->cur)
2291
587M
#define CUR (*ctxt->input->cur)
2292
23.6M
#define NXT(val) ctxt->input->cur[(val)]
2293
929M
#define CUR_PTR ctxt->input->cur
2294
23.1M
#define BASE_PTR ctxt->input->base
2295
2296
#define CMP4( s, c1, c2, c3, c4 ) \
2297
47.5M
  ( ((unsigned char *) s)[ 0 ] == c1 && ((unsigned char *) s)[ 1 ] == c2 && \
2298
24.4M
    ((unsigned char *) s)[ 2 ] == c3 && ((unsigned char *) s)[ 3 ] == c4 )
2299
#define CMP5( s, c1, c2, c3, c4, c5 ) \
2300
45.0M
  ( CMP4( s, c1, c2, c3, c4 ) && ((unsigned char *) s)[ 4 ] == c5 )
2301
#define CMP6( s, c1, c2, c3, c4, c5, c6 ) \
2302
42.9M
  ( CMP5( s, c1, c2, c3, c4, c5 ) && ((unsigned char *) s)[ 5 ] == c6 )
2303
#define CMP7( s, c1, c2, c3, c4, c5, c6, c7 ) \
2304
41.5M
  ( CMP6( s, c1, c2, c3, c4, c5, c6 ) && ((unsigned char *) s)[ 6 ] == c7 )
2305
#define CMP8( s, c1, c2, c3, c4, c5, c6, c7, c8 ) \
2306
40.8M
  ( CMP7( s, c1, c2, c3, c4, c5, c6, c7 ) && ((unsigned char *) s)[ 7 ] == c8 )
2307
#define CMP9( s, c1, c2, c3, c4, c5, c6, c7, c8, c9 ) \
2308
20.3M
  ( CMP8( s, c1, c2, c3, c4, c5, c6, c7, c8 ) && \
2309
20.3M
    ((unsigned char *) s)[ 8 ] == c9 )
2310
#define CMP10( s, c1, c2, c3, c4, c5, c6, c7, c8, c9, c10 ) \
2311
63.6k
  ( CMP9( s, c1, c2, c3, c4, c5, c6, c7, c8, c9 ) && \
2312
63.6k
    ((unsigned char *) s)[ 9 ] == c10 )
2313
2314
5.75M
#define SKIP(val) do {             \
2315
5.75M
    ctxt->input->cur += (val),ctxt->input->col+=(val);      \
2316
5.75M
    if (*ctxt->input->cur == 0)           \
2317
5.75M
        xmlParserGrow(ctxt);           \
2318
5.75M
  } while (0)
2319
2320
#define SKIPL(val) do {             \
2321
    int skipl;                \
2322
    for(skipl=0; skipl<val; skipl++) {          \
2323
  if (*(ctxt->input->cur) == '\n') {        \
2324
  ctxt->input->line++; ctxt->input->col = 1;      \
2325
  } else ctxt->input->col++;          \
2326
  ctxt->input->cur++;           \
2327
    }                 \
2328
    if (*ctxt->input->cur == 0)           \
2329
        xmlParserGrow(ctxt);            \
2330
  } while (0)
2331
2332
#define SHRINK \
2333
30.8M
    if (!PARSER_PROGRESSIVE(ctxt)) \
2334
30.8M
  xmlParserShrink(ctxt);
2335
2336
#define GROW \
2337
86.6M
    if ((!PARSER_PROGRESSIVE(ctxt)) && \
2338
86.6M
        (ctxt->input->end - ctxt->input->cur < INPUT_CHUNK)) \
2339
30.4M
  xmlParserGrow(ctxt);
2340
2341
18.1M
#define SKIP_BLANKS xmlSkipBlankChars(ctxt)
2342
2343
2.44M
#define SKIP_BLANKS_PE xmlSkipBlankCharsPE(ctxt)
2344
2345
157M
#define NEXT xmlNextChar(ctxt)
2346
2347
7.80M
#define NEXT1 {               \
2348
7.80M
  ctxt->input->col++;           \
2349
7.80M
  ctxt->input->cur++;           \
2350
7.80M
  if (*ctxt->input->cur == 0)         \
2351
7.80M
      xmlParserGrow(ctxt);           \
2352
7.80M
    }
2353
2354
854M
#define NEXTL(l) do {             \
2355
854M
    if (*(ctxt->input->cur) == '\n') {         \
2356
155M
  ctxt->input->line++; ctxt->input->col = 1;      \
2357
699M
    } else ctxt->input->col++;           \
2358
854M
    ctxt->input->cur += l;        \
2359
854M
  } while (0)
2360
2361
5.40M
#define CUR_SCHAR(s, l) xmlStringCurrentChar(ctxt, s, &l)
2362
2363
#define COPY_BUF(b, i, v)           \
2364
354M
    if (v < 0x80) b[i++] = v;           \
2365
354M
    else i += xmlCopyCharMultiByte(&b[i],v)
2366
2367
static int
2368
334M
xmlCurrentCharRecover(xmlParserCtxtPtr ctxt, int *len) {
2369
334M
    int c = xmlCurrentChar(ctxt, len);
2370
2371
334M
    if (c == XML_INVALID_CHAR)
2372
58.4M
        c = 0xFFFD; /* replacement character */
2373
2374
334M
    return(c);
2375
334M
}
2376
2377
/**
2378
 * xmlSkipBlankChars:
2379
 * @ctxt:  the XML parser context
2380
 *
2381
 * DEPRECATED: Internal function, do not use.
2382
 *
2383
 * Skip whitespace in the input stream.
2384
 *
2385
 * Returns the number of space chars skipped
2386
 */
2387
int
2388
20.0M
xmlSkipBlankChars(xmlParserCtxtPtr ctxt) {
2389
20.0M
    const xmlChar *cur;
2390
20.0M
    int res = 0;
2391
2392
20.0M
    cur = ctxt->input->cur;
2393
20.0M
    while (IS_BLANK_CH(*cur)) {
2394
10.6M
        if (*cur == '\n') {
2395
2.31M
            ctxt->input->line++; ctxt->input->col = 1;
2396
8.37M
        } else {
2397
8.37M
            ctxt->input->col++;
2398
8.37M
        }
2399
10.6M
        cur++;
2400
10.6M
        if (res < INT_MAX)
2401
10.6M
            res++;
2402
10.6M
        if (*cur == 0) {
2403
434k
            ctxt->input->cur = cur;
2404
434k
            xmlParserGrow(ctxt);
2405
434k
            cur = ctxt->input->cur;
2406
434k
        }
2407
10.6M
    }
2408
20.0M
    ctxt->input->cur = cur;
2409
2410
20.0M
    if (res > 4)
2411
231k
        GROW;
2412
2413
20.0M
    return(res);
2414
20.0M
}
2415
2416
static void
2417
35.6k
xmlPopPE(xmlParserCtxtPtr ctxt) {
2418
35.6k
    unsigned long consumed;
2419
35.6k
    xmlEntityPtr ent;
2420
2421
35.6k
    ent = ctxt->input->entity;
2422
2423
35.6k
    ent->flags &= ~XML_ENT_EXPANDING;
2424
2425
35.6k
    if ((ent->flags & XML_ENT_CHECKED) == 0) {
2426
31.5k
        int result;
2427
2428
        /*
2429
         * Read the rest of the stream in case of errors. We want
2430
         * to account for the whole entity size.
2431
         */
2432
32.7k
        do {
2433
32.7k
            ctxt->input->cur = ctxt->input->end;
2434
32.7k
            xmlParserShrink(ctxt);
2435
32.7k
            result = xmlParserGrow(ctxt);
2436
32.7k
        } while (result > 0);
2437
2438
31.5k
        consumed = ctxt->input->consumed;
2439
31.5k
        xmlSaturatedAddSizeT(&consumed,
2440
31.5k
                             ctxt->input->end - ctxt->input->base);
2441
2442
31.5k
        xmlSaturatedAdd(&ent->expandedSize, consumed);
2443
2444
        /*
2445
         * Add to sizeentities when parsing an external entity
2446
         * for the first time.
2447
         */
2448
31.5k
        if (ent->etype == XML_EXTERNAL_PARAMETER_ENTITY) {
2449
29.9k
            xmlSaturatedAdd(&ctxt->sizeentities, consumed);
2450
29.9k
        }
2451
2452
31.5k
        ent->flags |= XML_ENT_CHECKED;
2453
31.5k
    }
2454
2455
35.6k
    xmlFreeInputStream(xmlCtxtPopInput(ctxt));
2456
2457
35.6k
    xmlParserEntityCheck(ctxt, ent->expandedSize);
2458
2459
35.6k
    GROW;
2460
35.6k
}
2461
2462
/**
2463
 * xmlSkipBlankCharsPE:
2464
 * @ctxt:  the XML parser context
2465
 *
2466
 * Skip whitespace in the input stream, also handling parameter
2467
 * entities.
2468
 *
2469
 * Returns the number of space chars skipped
2470
 */
2471
static int
2472
2.44M
xmlSkipBlankCharsPE(xmlParserCtxtPtr ctxt) {
2473
2.44M
    int res = 0;
2474
2.44M
    int inParam;
2475
2.44M
    int expandParam;
2476
2477
2.44M
    inParam = PARSER_IN_PE(ctxt);
2478
2.44M
    expandParam = PARSER_EXTERNAL(ctxt);
2479
2480
2.44M
    if (!inParam && !expandParam)
2481
1.91M
        return(xmlSkipBlankChars(ctxt));
2482
2483
    /*
2484
     * It's Okay to use CUR/NEXT here since all the blanks are on
2485
     * the ASCII range.
2486
     */
2487
2.40M
    while (PARSER_STOPPED(ctxt) == 0) {
2488
2.35M
        if (IS_BLANK_CH(CUR)) { /* CHECKED tstblanks.xml */
2489
1.83M
            NEXT;
2490
1.83M
        } else if (CUR == '%') {
2491
55.1k
            if ((expandParam == 0) ||
2492
51.6k
                (IS_BLANK_CH(NXT(1))) || (NXT(1) == 0))
2493
36.3k
                break;
2494
2495
            /*
2496
             * Expand parameter entity. We continue to consume
2497
             * whitespace at the start of the entity and possible
2498
             * even consume the whole entity and pop it. We might
2499
             * even pop multiple PEs in this loop.
2500
             */
2501
18.7k
            xmlParsePEReference(ctxt);
2502
2503
18.7k
            inParam = PARSER_IN_PE(ctxt);
2504
18.7k
            expandParam = PARSER_EXTERNAL(ctxt);
2505
469k
        } else if (CUR == 0) {
2506
19.8k
            if (inParam == 0)
2507
3.87k
                break;
2508
2509
15.9k
            xmlPopPE(ctxt);
2510
2511
15.9k
            inParam = PARSER_IN_PE(ctxt);
2512
15.9k
            expandParam = PARSER_EXTERNAL(ctxt);
2513
450k
        } else {
2514
450k
            break;
2515
450k
        }
2516
2517
        /*
2518
         * Also increase the counter when entering or exiting a PERef.
2519
         * The spec says: "When a parameter-entity reference is recognized
2520
         * in the DTD and included, its replacement text MUST be enlarged
2521
         * by the attachment of one leading and one following space (#x20)
2522
         * character."
2523
         */
2524
1.86M
        if (res < INT_MAX)
2525
1.86M
            res++;
2526
1.86M
    }
2527
2528
534k
    return(res);
2529
2.44M
}
2530
2531
/************************************************************************
2532
 *                  *
2533
 *    Commodity functions to handle entities      *
2534
 *                  *
2535
 ************************************************************************/
2536
2537
/**
2538
 * xmlPopInput:
2539
 * @ctxt:  an XML parser context
2540
 *
2541
 * DEPRECATED: Internal function, don't use.
2542
 *
2543
 * Returns the current xmlChar in the parser context
2544
 */
2545
xmlChar
2546
0
xmlPopInput(xmlParserCtxtPtr ctxt) {
2547
0
    xmlParserInputPtr input;
2548
2549
0
    if ((ctxt == NULL) || (ctxt->inputNr <= 1)) return(0);
2550
0
    input = xmlCtxtPopInput(ctxt);
2551
0
    xmlFreeInputStream(input);
2552
0
    if (*ctxt->input->cur == 0)
2553
0
        xmlParserGrow(ctxt);
2554
0
    return(CUR);
2555
0
}
2556
2557
/**
2558
 * xmlPushInput:
2559
 * @ctxt:  an XML parser context
2560
 * @input:  an XML parser input fragment (entity, XML fragment ...).
2561
 *
2562
 * DEPRECATED: Internal function, don't use.
2563
 *
2564
 * Push an input stream onto the stack.
2565
 *
2566
 * Returns -1 in case of error or the index in the input stack
2567
 */
2568
int
2569
0
xmlPushInput(xmlParserCtxtPtr ctxt, xmlParserInputPtr input) {
2570
0
    int ret;
2571
2572
0
    if ((ctxt == NULL) || (input == NULL))
2573
0
        return(-1);
2574
2575
0
    ret = xmlCtxtPushInput(ctxt, input);
2576
0
    if (ret >= 0)
2577
0
        GROW;
2578
0
    return(ret);
2579
0
}
2580
2581
/**
2582
 * xmlParseCharRef:
2583
 * @ctxt:  an XML parser context
2584
 *
2585
 * DEPRECATED: Internal function, don't use.
2586
 *
2587
 * Parse a numeric character reference. Always consumes '&'.
2588
 *
2589
 * [66] CharRef ::= '&#' [0-9]+ ';' |
2590
 *                  '&#x' [0-9a-fA-F]+ ';'
2591
 *
2592
 * [ WFC: Legal Character ]
2593
 * Characters referred to using character references must match the
2594
 * production for Char.
2595
 *
2596
 * Returns the value parsed (as an int), 0 in case of error
2597
 */
2598
int
2599
162k
xmlParseCharRef(xmlParserCtxtPtr ctxt) {
2600
162k
    int val = 0;
2601
162k
    int count = 0;
2602
2603
    /*
2604
     * Using RAW/CUR/NEXT is okay since we are working on ASCII range here
2605
     */
2606
162k
    if ((RAW == '&') && (NXT(1) == '#') &&
2607
162k
        (NXT(2) == 'x')) {
2608
46.9k
  SKIP(3);
2609
46.9k
  GROW;
2610
153k
  while ((RAW != ';') && (PARSER_STOPPED(ctxt) == 0)) {
2611
111k
      if (count++ > 20) {
2612
824
    count = 0;
2613
824
    GROW;
2614
824
      }
2615
111k
      if ((RAW >= '0') && (RAW <= '9'))
2616
90.7k
          val = val * 16 + (CUR - '0');
2617
20.9k
      else if ((RAW >= 'a') && (RAW <= 'f') && (count < 20))
2618
3.15k
          val = val * 16 + (CUR - 'a') + 10;
2619
17.7k
      else if ((RAW >= 'A') && (RAW <= 'F') && (count < 20))
2620
12.2k
          val = val * 16 + (CUR - 'A') + 10;
2621
5.49k
      else {
2622
5.49k
    xmlFatalErr(ctxt, XML_ERR_INVALID_HEX_CHARREF, NULL);
2623
5.49k
    val = 0;
2624
5.49k
    break;
2625
5.49k
      }
2626
106k
      if (val > 0x110000)
2627
11.5k
          val = 0x110000;
2628
2629
106k
      NEXT;
2630
106k
      count++;
2631
106k
  }
2632
46.9k
  if (RAW == ';') {
2633
      /* on purpose to avoid reentrancy problems with NEXT and SKIP */
2634
41.4k
      ctxt->input->col++;
2635
41.4k
      ctxt->input->cur++;
2636
41.4k
  }
2637
115k
    } else if  ((RAW == '&') && (NXT(1) == '#')) {
2638
115k
  SKIP(2);
2639
115k
  GROW;
2640
367k
  while (RAW != ';') { /* loop blocked by count */
2641
258k
      if (count++ > 20) {
2642
3.35k
    count = 0;
2643
3.35k
    GROW;
2644
3.35k
      }
2645
258k
      if ((RAW >= '0') && (RAW <= '9'))
2646
252k
          val = val * 10 + (CUR - '0');
2647
5.92k
      else {
2648
5.92k
    xmlFatalErr(ctxt, XML_ERR_INVALID_DEC_CHARREF, NULL);
2649
5.92k
    val = 0;
2650
5.92k
    break;
2651
5.92k
      }
2652
252k
      if (val > 0x110000)
2653
34.3k
          val = 0x110000;
2654
2655
252k
      NEXT;
2656
252k
      count++;
2657
252k
  }
2658
115k
  if (RAW == ';') {
2659
      /* on purpose to avoid reentrancy problems with NEXT and SKIP */
2660
109k
      ctxt->input->col++;
2661
109k
      ctxt->input->cur++;
2662
109k
  }
2663
115k
    } else {
2664
0
        if (RAW == '&')
2665
0
            SKIP(1);
2666
0
        xmlFatalErr(ctxt, XML_ERR_INVALID_CHARREF, NULL);
2667
0
    }
2668
2669
    /*
2670
     * [ WFC: Legal Character ]
2671
     * Characters referred to using character references must match the
2672
     * production for Char.
2673
     */
2674
162k
    if (val >= 0x110000) {
2675
879
        xmlFatalErrMsgInt(ctxt, XML_ERR_INVALID_CHAR,
2676
879
                "xmlParseCharRef: character reference out of bounds\n",
2677
879
          val);
2678
161k
    } else if (IS_CHAR(val)) {
2679
148k
        return(val);
2680
148k
    } else {
2681
12.6k
        xmlFatalErrMsgInt(ctxt, XML_ERR_INVALID_CHAR,
2682
12.6k
                          "xmlParseCharRef: invalid xmlChar value %d\n",
2683
12.6k
                    val);
2684
12.6k
    }
2685
13.5k
    return(0);
2686
162k
}
2687
2688
/**
2689
 * xmlParseStringCharRef:
2690
 * @ctxt:  an XML parser context
2691
 * @str:  a pointer to an index in the string
2692
 *
2693
 * parse Reference declarations, variant parsing from a string rather
2694
 * than an an input flow.
2695
 *
2696
 * [66] CharRef ::= '&#' [0-9]+ ';' |
2697
 *                  '&#x' [0-9a-fA-F]+ ';'
2698
 *
2699
 * [ WFC: Legal Character ]
2700
 * Characters referred to using character references must match the
2701
 * production for Char.
2702
 *
2703
 * Returns the value parsed (as an int), 0 in case of error, str will be
2704
 *         updated to the current value of the index
2705
 */
2706
static int
2707
132k
xmlParseStringCharRef(xmlParserCtxtPtr ctxt, const xmlChar **str) {
2708
132k
    const xmlChar *ptr;
2709
132k
    xmlChar cur;
2710
132k
    int val = 0;
2711
2712
132k
    if ((str == NULL) || (*str == NULL)) return(0);
2713
132k
    ptr = *str;
2714
132k
    cur = *ptr;
2715
132k
    if ((cur == '&') && (ptr[1] == '#') && (ptr[2] == 'x')) {
2716
101k
  ptr += 3;
2717
101k
  cur = *ptr;
2718
463k
  while (cur != ';') { /* Non input consuming loop */
2719
363k
      if ((cur >= '0') && (cur <= '9'))
2720
271k
          val = val * 16 + (cur - '0');
2721
91.4k
      else if ((cur >= 'a') && (cur <= 'f'))
2722
3.17k
          val = val * 16 + (cur - 'a') + 10;
2723
88.2k
      else if ((cur >= 'A') && (cur <= 'F'))
2724
87.0k
          val = val * 16 + (cur - 'A') + 10;
2725
1.25k
      else {
2726
1.25k
    xmlFatalErr(ctxt, XML_ERR_INVALID_HEX_CHARREF, NULL);
2727
1.25k
    val = 0;
2728
1.25k
    break;
2729
1.25k
      }
2730
362k
      if (val > 0x110000)
2731
468
          val = 0x110000;
2732
2733
362k
      ptr++;
2734
362k
      cur = *ptr;
2735
362k
  }
2736
101k
  if (cur == ';')
2737
99.8k
      ptr++;
2738
101k
    } else if  ((cur == '&') && (ptr[1] == '#')){
2739
31.6k
  ptr += 2;
2740
31.6k
  cur = *ptr;
2741
101k
  while (cur != ';') { /* Non input consuming loops */
2742
71.6k
      if ((cur >= '0') && (cur <= '9'))
2743
69.8k
          val = val * 10 + (cur - '0');
2744
1.78k
      else {
2745
1.78k
    xmlFatalErr(ctxt, XML_ERR_INVALID_DEC_CHARREF, NULL);
2746
1.78k
    val = 0;
2747
1.78k
    break;
2748
1.78k
      }
2749
69.8k
      if (val > 0x110000)
2750
8.49k
          val = 0x110000;
2751
2752
69.8k
      ptr++;
2753
69.8k
      cur = *ptr;
2754
69.8k
  }
2755
31.6k
  if (cur == ';')
2756
29.8k
      ptr++;
2757
31.6k
    } else {
2758
0
  xmlFatalErr(ctxt, XML_ERR_INVALID_CHARREF, NULL);
2759
0
  return(0);
2760
0
    }
2761
132k
    *str = ptr;
2762
2763
    /*
2764
     * [ WFC: Legal Character ]
2765
     * Characters referred to using character references must match the
2766
     * production for Char.
2767
     */
2768
132k
    if (val >= 0x110000) {
2769
315
        xmlFatalErrMsgInt(ctxt, XML_ERR_INVALID_CHAR,
2770
315
                "xmlParseStringCharRef: character reference out of bounds\n",
2771
315
                val);
2772
132k
    } else if (IS_CHAR(val)) {
2773
128k
        return(val);
2774
128k
    } else {
2775
3.91k
        xmlFatalErrMsgInt(ctxt, XML_ERR_INVALID_CHAR,
2776
3.91k
        "xmlParseStringCharRef: invalid xmlChar value %d\n",
2777
3.91k
        val);
2778
3.91k
    }
2779
4.23k
    return(0);
2780
132k
}
2781
2782
/**
2783
 * xmlParserHandlePEReference:
2784
 * @ctxt:  the parser context
2785
 *
2786
 * DEPRECATED: Internal function, do not use.
2787
 *
2788
 * [69] PEReference ::= '%' Name ';'
2789
 *
2790
 * [ WFC: No Recursion ]
2791
 * A parsed entity must not contain a recursive
2792
 * reference to itself, either directly or indirectly.
2793
 *
2794
 * [ WFC: Entity Declared ]
2795
 * In a document without any DTD, a document with only an internal DTD
2796
 * subset which contains no parameter entity references, or a document
2797
 * with "standalone='yes'", ...  ... The declaration of a parameter
2798
 * entity must precede any reference to it...
2799
 *
2800
 * [ VC: Entity Declared ]
2801
 * In a document with an external subset or external parameter entities
2802
 * with "standalone='no'", ...  ... The declaration of a parameter entity
2803
 * must precede any reference to it...
2804
 *
2805
 * [ WFC: In DTD ]
2806
 * Parameter-entity references may only appear in the DTD.
2807
 * NOTE: misleading but this is handled.
2808
 *
2809
 * A PEReference may have been detected in the current input stream
2810
 * the handling is done accordingly to
2811
 *      http://www.w3.org/TR/REC-xml#entproc
2812
 * i.e.
2813
 *   - Included in literal in entity values
2814
 *   - Included as Parameter Entity reference within DTDs
2815
 */
2816
void
2817
0
xmlParserHandlePEReference(xmlParserCtxtPtr ctxt) {
2818
0
    xmlParsePEReference(ctxt);
2819
0
}
2820
2821
/**
2822
 * xmlStringLenDecodeEntities:
2823
 * @ctxt:  the parser context
2824
 * @str:  the input string
2825
 * @len: the string length
2826
 * @what:  combination of XML_SUBSTITUTE_REF and XML_SUBSTITUTE_PEREF
2827
 * @end:  an end marker xmlChar, 0 if none
2828
 * @end2:  an end marker xmlChar, 0 if none
2829
 * @end3:  an end marker xmlChar, 0 if none
2830
 *
2831
 * DEPRECATED: Internal function, don't use.
2832
 *
2833
 * Returns A newly allocated string with the substitution done. The caller
2834
 *      must deallocate it !
2835
 */
2836
xmlChar *
2837
xmlStringLenDecodeEntities(xmlParserCtxtPtr ctxt, const xmlChar *str, int len,
2838
                           int what ATTRIBUTE_UNUSED,
2839
0
                           xmlChar end, xmlChar end2, xmlChar end3) {
2840
0
    if ((ctxt == NULL) || (str == NULL) || (len < 0))
2841
0
        return(NULL);
2842
2843
0
    if ((str[len] != 0) ||
2844
0
        (end != 0) || (end2 != 0) || (end3 != 0))
2845
0
        return(NULL);
2846
2847
0
    return(xmlExpandEntitiesInAttValue(ctxt, str, 0));
2848
0
}
2849
2850
/**
2851
 * xmlStringDecodeEntities:
2852
 * @ctxt:  the parser context
2853
 * @str:  the input string
2854
 * @what:  combination of XML_SUBSTITUTE_REF and XML_SUBSTITUTE_PEREF
2855
 * @end:  an end marker xmlChar, 0 if none
2856
 * @end2:  an end marker xmlChar, 0 if none
2857
 * @end3:  an end marker xmlChar, 0 if none
2858
 *
2859
 * DEPRECATED: Internal function, don't use.
2860
 *
2861
 * Returns A newly allocated string with the substitution done. The caller
2862
 *      must deallocate it !
2863
 */
2864
xmlChar *
2865
xmlStringDecodeEntities(xmlParserCtxtPtr ctxt, const xmlChar *str,
2866
                        int what ATTRIBUTE_UNUSED,
2867
0
            xmlChar end, xmlChar  end2, xmlChar end3) {
2868
0
    if ((ctxt == NULL) || (str == NULL))
2869
0
        return(NULL);
2870
2871
0
    if ((end != 0) || (end2 != 0) || (end3 != 0))
2872
0
        return(NULL);
2873
2874
0
    return(xmlExpandEntitiesInAttValue(ctxt, str, 0));
2875
0
}
2876
2877
/************************************************************************
2878
 *                  *
2879
 *    Commodity functions, cleanup needed ?     *
2880
 *                  *
2881
 ************************************************************************/
2882
2883
/**
2884
 * areBlanks:
2885
 * @ctxt:  an XML parser context
2886
 * @str:  a xmlChar *
2887
 * @len:  the size of @str
2888
 * @blank_chars: we know the chars are blanks
2889
 *
2890
 * Is this a sequence of blank chars that one can ignore ?
2891
 *
2892
 * Returns 1 if ignorable 0 otherwise.
2893
 */
2894
2895
static int areBlanks(xmlParserCtxtPtr ctxt, const xmlChar *str, int len,
2896
0
                     int blank_chars) {
2897
0
    int i;
2898
0
    xmlNodePtr lastChild;
2899
2900
    /*
2901
     * Check for xml:space value.
2902
     */
2903
0
    if ((ctxt->space == NULL) || (*(ctxt->space) == 1) ||
2904
0
        (*(ctxt->space) == -2))
2905
0
  return(0);
2906
2907
    /*
2908
     * Check that the string is made of blanks
2909
     */
2910
0
    if (blank_chars == 0) {
2911
0
  for (i = 0;i < len;i++)
2912
0
      if (!(IS_BLANK_CH(str[i]))) return(0);
2913
0
    }
2914
2915
    /*
2916
     * Look if the element is mixed content in the DTD if available
2917
     */
2918
0
    if (ctxt->node == NULL) return(0);
2919
0
    if (ctxt->myDoc != NULL) {
2920
0
        xmlElementPtr elemDecl = NULL;
2921
0
        xmlDocPtr doc = ctxt->myDoc;
2922
0
        const xmlChar *prefix = NULL;
2923
2924
0
        if (ctxt->node->ns)
2925
0
            prefix = ctxt->node->ns->prefix;
2926
0
        if (doc->intSubset != NULL)
2927
0
            elemDecl = xmlHashLookup2(doc->intSubset->elements, ctxt->node->name,
2928
0
                                      prefix);
2929
0
        if ((elemDecl == NULL) && (doc->extSubset != NULL))
2930
0
            elemDecl = xmlHashLookup2(doc->extSubset->elements, ctxt->node->name,
2931
0
                                      prefix);
2932
0
        if (elemDecl != NULL) {
2933
0
            if (elemDecl->etype == XML_ELEMENT_TYPE_ELEMENT)
2934
0
                return(1);
2935
0
            if ((elemDecl->etype == XML_ELEMENT_TYPE_ANY) ||
2936
0
                (elemDecl->etype == XML_ELEMENT_TYPE_MIXED))
2937
0
                return(0);
2938
0
        }
2939
0
    }
2940
2941
    /*
2942
     * Otherwise, heuristic :-\
2943
     *
2944
     * When push parsing, we could be at the end of a chunk.
2945
     * This makes the look-ahead and consequently the NOBLANKS
2946
     * option unreliable.
2947
     */
2948
0
    if ((RAW != '<') && (RAW != 0xD)) return(0);
2949
0
    if ((ctxt->node->children == NULL) &&
2950
0
  (RAW == '<') && (NXT(1) == '/')) return(0);
2951
2952
0
    lastChild = xmlGetLastChild(ctxt->node);
2953
0
    if (lastChild == NULL) {
2954
0
        if ((ctxt->node->type != XML_ELEMENT_NODE) &&
2955
0
            (ctxt->node->content != NULL)) return(0);
2956
0
    } else if (xmlNodeIsText(lastChild))
2957
0
        return(0);
2958
0
    else if ((ctxt->node->children != NULL) &&
2959
0
             (xmlNodeIsText(ctxt->node->children)))
2960
0
        return(0);
2961
0
    return(1);
2962
0
}
2963
2964
/************************************************************************
2965
 *                  *
2966
 *    Extra stuff for namespace support     *
2967
 *  Relates to http://www.w3.org/TR/WD-xml-names      *
2968
 *                  *
2969
 ************************************************************************/
2970
2971
/**
2972
 * xmlSplitQName:
2973
 * @ctxt:  an XML parser context
2974
 * @name:  an XML parser context
2975
 * @prefixOut:  a xmlChar **
2976
 *
2977
 * DEPRECATED: Don't use.
2978
 *
2979
 * parse an UTF8 encoded XML qualified name string
2980
 *
2981
 * [NS 5] QName ::= (Prefix ':')? LocalPart
2982
 *
2983
 * [NS 6] Prefix ::= NCName
2984
 *
2985
 * [NS 7] LocalPart ::= NCName
2986
 *
2987
 * Returns the local part, and prefix is updated
2988
 *   to get the Prefix if any.
2989
 */
2990
2991
xmlChar *
2992
0
xmlSplitQName(xmlParserCtxtPtr ctxt, const xmlChar *name, xmlChar **prefixOut) {
2993
0
    xmlChar buf[XML_MAX_NAMELEN + 5];
2994
0
    xmlChar *buffer = NULL;
2995
0
    int len = 0;
2996
0
    int max = XML_MAX_NAMELEN;
2997
0
    xmlChar *ret = NULL;
2998
0
    xmlChar *prefix;
2999
0
    const xmlChar *cur = name;
3000
0
    int c;
3001
3002
0
    if (prefixOut == NULL) return(NULL);
3003
0
    *prefixOut = NULL;
3004
3005
0
    if (cur == NULL) return(NULL);
3006
3007
    /* nasty but well=formed */
3008
0
    if (cur[0] == ':')
3009
0
  return(xmlStrdup(name));
3010
3011
0
    c = *cur++;
3012
0
    while ((c != 0) && (c != ':') && (len < max)) { /* tested bigname.xml */
3013
0
  buf[len++] = c;
3014
0
  c = *cur++;
3015
0
    }
3016
0
    if (len >= max) {
3017
  /*
3018
   * Okay someone managed to make a huge name, so he's ready to pay
3019
   * for the processing speed.
3020
   */
3021
0
  max = len * 2;
3022
3023
0
  buffer = xmlMalloc(max);
3024
0
  if (buffer == NULL) {
3025
0
      xmlErrMemory(ctxt);
3026
0
      return(NULL);
3027
0
  }
3028
0
  memcpy(buffer, buf, len);
3029
0
  while ((c != 0) && (c != ':')) { /* tested bigname.xml */
3030
0
      if (len + 10 > max) {
3031
0
          xmlChar *tmp;
3032
0
                int newSize;
3033
3034
0
                newSize = xmlGrowCapacity(max, 1, 1, XML_MAX_ITEMS);
3035
0
                if (newSize < 0) {
3036
0
        xmlErrMemory(ctxt);
3037
0
        xmlFree(buffer);
3038
0
        return(NULL);
3039
0
                }
3040
0
    tmp = xmlRealloc(buffer, newSize);
3041
0
    if (tmp == NULL) {
3042
0
        xmlErrMemory(ctxt);
3043
0
        xmlFree(buffer);
3044
0
        return(NULL);
3045
0
    }
3046
0
    buffer = tmp;
3047
0
    max = newSize;
3048
0
      }
3049
0
      buffer[len++] = c;
3050
0
      c = *cur++;
3051
0
  }
3052
0
  buffer[len] = 0;
3053
0
    }
3054
3055
0
    if ((c == ':') && (*cur == 0)) {
3056
0
        if (buffer != NULL)
3057
0
      xmlFree(buffer);
3058
0
  return(xmlStrdup(name));
3059
0
    }
3060
3061
0
    if (buffer == NULL) {
3062
0
  ret = xmlStrndup(buf, len);
3063
0
        if (ret == NULL) {
3064
0
      xmlErrMemory(ctxt);
3065
0
      return(NULL);
3066
0
        }
3067
0
    } else {
3068
0
  ret = buffer;
3069
0
  buffer = NULL;
3070
0
  max = XML_MAX_NAMELEN;
3071
0
    }
3072
3073
3074
0
    if (c == ':') {
3075
0
  c = *cur;
3076
0
        prefix = ret;
3077
0
  if (c == 0) {
3078
0
      ret = xmlStrndup(BAD_CAST "", 0);
3079
0
            if (ret == NULL) {
3080
0
                xmlFree(prefix);
3081
0
                return(NULL);
3082
0
            }
3083
0
            *prefixOut = prefix;
3084
0
            return(ret);
3085
0
  }
3086
0
  len = 0;
3087
3088
  /*
3089
   * Check that the first character is proper to start
3090
   * a new name
3091
   */
3092
0
  if (!(((c >= 0x61) && (c <= 0x7A)) ||
3093
0
        ((c >= 0x41) && (c <= 0x5A)) ||
3094
0
        (c == '_') || (c == ':'))) {
3095
0
      int l;
3096
0
      int first = CUR_SCHAR(cur, l);
3097
3098
0
      if (!IS_LETTER(first) && (first != '_')) {
3099
0
    xmlFatalErrMsgStr(ctxt, XML_NS_ERR_QNAME,
3100
0
          "Name %s is not XML Namespace compliant\n",
3101
0
          name);
3102
0
      }
3103
0
  }
3104
0
  cur++;
3105
3106
0
  while ((c != 0) && (len < max)) { /* tested bigname2.xml */
3107
0
      buf[len++] = c;
3108
0
      c = *cur++;
3109
0
  }
3110
0
  if (len >= max) {
3111
      /*
3112
       * Okay someone managed to make a huge name, so he's ready to pay
3113
       * for the processing speed.
3114
       */
3115
0
      max = len * 2;
3116
3117
0
      buffer = xmlMalloc(max);
3118
0
      if (buffer == NULL) {
3119
0
          xmlErrMemory(ctxt);
3120
0
                xmlFree(prefix);
3121
0
    return(NULL);
3122
0
      }
3123
0
      memcpy(buffer, buf, len);
3124
0
      while (c != 0) { /* tested bigname2.xml */
3125
0
    if (len + 10 > max) {
3126
0
        xmlChar *tmp;
3127
0
                    int newSize;
3128
3129
0
                    newSize = xmlGrowCapacity(max, 1, 1, XML_MAX_ITEMS);
3130
0
                    if (newSize < 0) {
3131
0
                        xmlErrMemory(ctxt);
3132
0
                        xmlFree(buffer);
3133
0
                        return(NULL);
3134
0
                    }
3135
0
        tmp = xmlRealloc(buffer, newSize);
3136
0
        if (tmp == NULL) {
3137
0
      xmlErrMemory(ctxt);
3138
0
                        xmlFree(prefix);
3139
0
      xmlFree(buffer);
3140
0
      return(NULL);
3141
0
        }
3142
0
        buffer = tmp;
3143
0
                    max = newSize;
3144
0
    }
3145
0
    buffer[len++] = c;
3146
0
    c = *cur++;
3147
0
      }
3148
0
      buffer[len] = 0;
3149
0
  }
3150
3151
0
  if (buffer == NULL) {
3152
0
      ret = xmlStrndup(buf, len);
3153
0
            if (ret == NULL) {
3154
0
                xmlFree(prefix);
3155
0
                return(NULL);
3156
0
            }
3157
0
  } else {
3158
0
      ret = buffer;
3159
0
  }
3160
3161
0
        *prefixOut = prefix;
3162
0
    }
3163
3164
0
    return(ret);
3165
0
}
3166
3167
/************************************************************************
3168
 *                  *
3169
 *      The parser itself       *
3170
 *  Relates to http://www.w3.org/TR/REC-xml       *
3171
 *                  *
3172
 ************************************************************************/
3173
3174
/************************************************************************
3175
 *                  *
3176
 *  Routines to parse Name, NCName and NmToken      *
3177
 *                  *
3178
 ************************************************************************/
3179
3180
/*
3181
 * The two following functions are related to the change of accepted
3182
 * characters for Name and NmToken in the Revision 5 of XML-1.0
3183
 * They correspond to the modified production [4] and the new production [4a]
3184
 * changes in that revision. Also note that the macros used for the
3185
 * productions Letter, Digit, CombiningChar and Extender are not needed
3186
 * anymore.
3187
 * We still keep compatibility to pre-revision5 parsing semantic if the
3188
 * new XML_PARSE_OLD10 option is given to the parser.
3189
 */
3190
static int
3191
2.17M
xmlIsNameStartChar(xmlParserCtxtPtr ctxt, int c) {
3192
2.17M
    if ((ctxt->options & XML_PARSE_OLD10) == 0) {
3193
        /*
3194
   * Use the new checks of production [4] [4a] amd [5] of the
3195
   * Update 5 of XML-1.0
3196
   */
3197
2.17M
  if ((c != ' ') && (c != '>') && (c != '/') && /* accelerators */
3198
2.17M
      (((c >= 'a') && (c <= 'z')) ||
3199
1.65M
       ((c >= 'A') && (c <= 'Z')) ||
3200
1.63M
       (c == '_') || (c == ':') ||
3201
1.61M
       ((c >= 0xC0) && (c <= 0xD6)) ||
3202
1.61M
       ((c >= 0xD8) && (c <= 0xF6)) ||
3203
1.60M
       ((c >= 0xF8) && (c <= 0x2FF)) ||
3204
1.60M
       ((c >= 0x370) && (c <= 0x37D)) ||
3205
1.60M
       ((c >= 0x37F) && (c <= 0x1FFF)) ||
3206
1.56M
       ((c >= 0x200C) && (c <= 0x200D)) ||
3207
1.56M
       ((c >= 0x2070) && (c <= 0x218F)) ||
3208
1.56M
       ((c >= 0x2C00) && (c <= 0x2FEF)) ||
3209
1.55M
       ((c >= 0x3001) && (c <= 0xD7FF)) ||
3210
1.55M
       ((c >= 0xF900) && (c <= 0xFDCF)) ||
3211
1.55M
       ((c >= 0xFDF0) && (c <= 0xFFFD)) ||
3212
1.55M
       ((c >= 0x10000) && (c <= 0xEFFFF))))
3213
619k
      return(1);
3214
2.17M
    } else {
3215
0
        if (IS_LETTER(c) || (c == '_') || (c == ':'))
3216
0
      return(1);
3217
0
    }
3218
1.55M
    return(0);
3219
2.17M
}
3220
3221
static int
3222
59.4M
xmlIsNameChar(xmlParserCtxtPtr ctxt, int c) {
3223
59.4M
    if ((ctxt->options & XML_PARSE_OLD10) == 0) {
3224
        /*
3225
   * Use the new checks of production [4] [4a] amd [5] of the
3226
   * Update 5 of XML-1.0
3227
   */
3228
59.4M
  if ((c != ' ') && (c != '>') && (c != '/') && /* accelerators */
3229
59.3M
      (((c >= 'a') && (c <= 'z')) ||
3230
17.3M
       ((c >= 'A') && (c <= 'Z')) ||
3231
17.1M
       ((c >= '0') && (c <= '9')) || /* !start */
3232
16.9M
       (c == '_') || (c == ':') ||
3233
16.6M
       (c == '-') || (c == '.') || (c == 0xB7) || /* !start */
3234
16.5M
       ((c >= 0xC0) && (c <= 0xD6)) ||
3235
15.2M
       ((c >= 0xD8) && (c <= 0xF6)) ||
3236
15.1M
       ((c >= 0xF8) && (c <= 0x2FF)) ||
3237
15.1M
       ((c >= 0x300) && (c <= 0x36F)) || /* !start */
3238
15.1M
       ((c >= 0x370) && (c <= 0x37D)) ||
3239
15.1M
       ((c >= 0x37F) && (c <= 0x1FFF)) ||
3240
8.95M
       ((c >= 0x200C) && (c <= 0x200D)) ||
3241
8.95M
       ((c >= 0x203F) && (c <= 0x2040)) || /* !start */
3242
8.95M
       ((c >= 0x2070) && (c <= 0x218F)) ||
3243
6.26M
       ((c >= 0x2C00) && (c <= 0x2FEF)) ||
3244
6.25M
       ((c >= 0x3001) && (c <= 0xD7FF)) ||
3245
6.09M
       ((c >= 0xF900) && (c <= 0xFDCF)) ||
3246
6.09M
       ((c >= 0xFDF0) && (c <= 0xFFFD)) ||
3247
643k
       ((c >= 0x10000) && (c <= 0xEFFFF))))
3248
58.7M
       return(1);
3249
59.4M
    } else {
3250
0
        if ((IS_LETTER(c)) || (IS_DIGIT(c)) ||
3251
0
            (c == '.') || (c == '-') ||
3252
0
      (c == '_') || (c == ':') ||
3253
0
      (IS_COMBINING(c)) ||
3254
0
      (IS_EXTENDER(c)))
3255
0
      return(1);
3256
0
    }
3257
654k
    return(0);
3258
59.4M
}
3259
3260
static const xmlChar *
3261
518k
xmlParseNameComplex(xmlParserCtxtPtr ctxt) {
3262
518k
    const xmlChar *ret;
3263
518k
    int len = 0, l;
3264
518k
    int c;
3265
518k
    int maxLength = (ctxt->options & XML_PARSE_HUGE) ?
3266
0
                    XML_MAX_TEXT_LENGTH :
3267
518k
                    XML_MAX_NAME_LENGTH;
3268
3269
    /*
3270
     * Handler for more complex cases
3271
     */
3272
518k
    c = xmlCurrentChar(ctxt, &l);
3273
518k
    if ((ctxt->options & XML_PARSE_OLD10) == 0) {
3274
        /*
3275
   * Use the new checks of production [4] [4a] amd [5] of the
3276
   * Update 5 of XML-1.0
3277
   */
3278
518k
  if ((c == ' ') || (c == '>') || (c == '/') || /* accelerators */
3279
481k
      (!(((c >= 'a') && (c <= 'z')) ||
3280
404k
         ((c >= 'A') && (c <= 'Z')) ||
3281
389k
         (c == '_') || (c == ':') ||
3282
387k
         ((c >= 0xC0) && (c <= 0xD6)) ||
3283
386k
         ((c >= 0xD8) && (c <= 0xF6)) ||
3284
385k
         ((c >= 0xF8) && (c <= 0x2FF)) ||
3285
384k
         ((c >= 0x370) && (c <= 0x37D)) ||
3286
383k
         ((c >= 0x37F) && (c <= 0x1FFF)) ||
3287
343k
         ((c >= 0x200C) && (c <= 0x200D)) ||
3288
343k
         ((c >= 0x2070) && (c <= 0x218F)) ||
3289
341k
         ((c >= 0x2C00) && (c <= 0x2FEF)) ||
3290
339k
         ((c >= 0x3001) && (c <= 0xD7FF)) ||
3291
338k
         ((c >= 0xF900) && (c <= 0xFDCF)) ||
3292
338k
         ((c >= 0xFDF0) && (c <= 0xFFFD)) ||
3293
369k
         ((c >= 0x10000) && (c <= 0xEFFFF))))) {
3294
369k
      return(NULL);
3295
369k
  }
3296
148k
  len += l;
3297
148k
  NEXTL(l);
3298
148k
  c = xmlCurrentChar(ctxt, &l);
3299
46.5M
  while ((c != ' ') && (c != '>') && (c != '/') && /* accelerators */
3300
46.5M
         (((c >= 'a') && (c <= 'z')) ||
3301
12.0M
          ((c >= 'A') && (c <= 'Z')) ||
3302
12.0M
          ((c >= '0') && (c <= '9')) || /* !start */
3303
11.8M
          (c == '_') || (c == ':') ||
3304
11.8M
          (c == '-') || (c == '.') || (c == 0xB7) || /* !start */
3305
11.7M
          ((c >= 0xC0) && (c <= 0xD6)) ||
3306
11.7M
          ((c >= 0xD8) && (c <= 0xF6)) ||
3307
11.7M
          ((c >= 0xF8) && (c <= 0x2FF)) ||
3308
11.7M
          ((c >= 0x300) && (c <= 0x36F)) || /* !start */
3309
11.7M
          ((c >= 0x370) && (c <= 0x37D)) ||
3310
11.7M
          ((c >= 0x37F) && (c <= 0x1FFF)) ||
3311
713k
          ((c >= 0x200C) && (c <= 0x200D)) ||
3312
713k
          ((c >= 0x203F) && (c <= 0x2040)) || /* !start */
3313
713k
          ((c >= 0x2070) && (c <= 0x218F)) ||
3314
611k
          ((c >= 0x2C00) && (c <= 0x2FEF)) ||
3315
606k
          ((c >= 0x3001) && (c <= 0xD7FF)) ||
3316
566k
          ((c >= 0xF900) && (c <= 0xFDCF)) ||
3317
566k
          ((c >= 0xFDF0) && (c <= 0xFFFD)) ||
3318
165k
          ((c >= 0x10000) && (c <= 0xEFFFF))
3319
46.5M
    )) {
3320
46.4M
            if (len <= INT_MAX - l)
3321
46.4M
          len += l;
3322
46.4M
      NEXTL(l);
3323
46.4M
      c = xmlCurrentChar(ctxt, &l);
3324
46.4M
  }
3325
148k
    } else {
3326
0
  if ((c == ' ') || (c == '>') || (c == '/') || /* accelerators */
3327
0
      (!IS_LETTER(c) && (c != '_') &&
3328
0
       (c != ':'))) {
3329
0
      return(NULL);
3330
0
  }
3331
0
  len += l;
3332
0
  NEXTL(l);
3333
0
  c = xmlCurrentChar(ctxt, &l);
3334
3335
0
  while ((c != ' ') && (c != '>') && (c != '/') && /* test bigname.xml */
3336
0
         ((IS_LETTER(c)) || (IS_DIGIT(c)) ||
3337
0
    (c == '.') || (c == '-') ||
3338
0
    (c == '_') || (c == ':') ||
3339
0
    (IS_COMBINING(c)) ||
3340
0
    (IS_EXTENDER(c)))) {
3341
0
            if (len <= INT_MAX - l)
3342
0
          len += l;
3343
0
      NEXTL(l);
3344
0
      c = xmlCurrentChar(ctxt, &l);
3345
0
  }
3346
0
    }
3347
148k
    if (len > maxLength) {
3348
629
        xmlFatalErr(ctxt, XML_ERR_NAME_TOO_LONG, "Name");
3349
629
        return(NULL);
3350
629
    }
3351
148k
    if (ctxt->input->cur - ctxt->input->base < len) {
3352
        /*
3353
         * There were a couple of bugs where PERefs lead to to a change
3354
         * of the buffer. Check the buffer size to avoid passing an invalid
3355
         * pointer to xmlDictLookup.
3356
         */
3357
0
        xmlFatalErr(ctxt, XML_ERR_INTERNAL_ERROR,
3358
0
                    "unexpected change of input buffer");
3359
0
        return (NULL);
3360
0
    }
3361
148k
    if ((*ctxt->input->cur == '\n') && (ctxt->input->cur[-1] == '\r'))
3362
2.01k
        ret = xmlDictLookup(ctxt->dict, ctxt->input->cur - (len + 1), len);
3363
146k
    else
3364
146k
        ret = xmlDictLookup(ctxt->dict, ctxt->input->cur - len, len);
3365
148k
    if (ret == NULL)
3366
3
        xmlErrMemory(ctxt);
3367
148k
    return(ret);
3368
148k
}
3369
3370
/**
3371
 * xmlParseName:
3372
 * @ctxt:  an XML parser context
3373
 *
3374
 * DEPRECATED: Internal function, don't use.
3375
 *
3376
 * parse an XML name.
3377
 *
3378
 * [4] NameChar ::= Letter | Digit | '.' | '-' | '_' | ':' |
3379
 *                  CombiningChar | Extender
3380
 *
3381
 * [5] Name ::= (Letter | '_' | ':') (NameChar)*
3382
 *
3383
 * [6] Names ::= Name (#x20 Name)*
3384
 *
3385
 * Returns the Name parsed or NULL
3386
 */
3387
3388
const xmlChar *
3389
2.96M
xmlParseName(xmlParserCtxtPtr ctxt) {
3390
2.96M
    const xmlChar *in;
3391
2.96M
    const xmlChar *ret;
3392
2.96M
    size_t count = 0;
3393
2.96M
    size_t maxLength = (ctxt->options & XML_PARSE_HUGE) ?
3394
0
                       XML_MAX_TEXT_LENGTH :
3395
2.96M
                       XML_MAX_NAME_LENGTH;
3396
3397
2.96M
    GROW;
3398
3399
    /*
3400
     * Accelerator for simple ASCII names
3401
     */
3402
2.96M
    in = ctxt->input->cur;
3403
2.96M
    if (((*in >= 0x61) && (*in <= 0x7A)) ||
3404
622k
  ((*in >= 0x41) && (*in <= 0x5A)) ||
3405
2.53M
  (*in == '_') || (*in == ':')) {
3406
2.53M
  in++;
3407
72.7M
  while (((*in >= 0x61) && (*in <= 0x7A)) ||
3408
3.50M
         ((*in >= 0x41) && (*in <= 0x5A)) ||
3409
3.08M
         ((*in >= 0x30) && (*in <= 0x39)) ||
3410
2.80M
         (*in == '_') || (*in == '-') ||
3411
2.76M
         (*in == ':') || (*in == '.'))
3412
70.2M
      in++;
3413
2.53M
  if ((*in > 0) && (*in < 0x80)) {
3414
2.44M
      count = in - ctxt->input->cur;
3415
2.44M
            if (count > maxLength) {
3416
420
                xmlFatalErr(ctxt, XML_ERR_NAME_TOO_LONG, "Name");
3417
420
                return(NULL);
3418
420
            }
3419
2.44M
      ret = xmlDictLookup(ctxt->dict, ctxt->input->cur, count);
3420
2.44M
      ctxt->input->cur = in;
3421
2.44M
      ctxt->input->col += count;
3422
2.44M
      if (ret == NULL)
3423
3
          xmlErrMemory(ctxt);
3424
2.44M
      return(ret);
3425
2.44M
  }
3426
2.53M
    }
3427
    /* accelerator for special cases */
3428
518k
    return(xmlParseNameComplex(ctxt));
3429
2.96M
}
3430
3431
static xmlHashedString
3432
1.77M
xmlParseNCNameComplex(xmlParserCtxtPtr ctxt) {
3433
1.77M
    xmlHashedString ret;
3434
1.77M
    int len = 0, l;
3435
1.77M
    int c;
3436
1.77M
    int maxLength = (ctxt->options & XML_PARSE_HUGE) ?
3437
0
                    XML_MAX_TEXT_LENGTH :
3438
1.77M
                    XML_MAX_NAME_LENGTH;
3439
1.77M
    size_t startPosition = 0;
3440
3441
1.77M
    ret.name = NULL;
3442
1.77M
    ret.hashValue = 0;
3443
3444
    /*
3445
     * Handler for more complex cases
3446
     */
3447
1.77M
    startPosition = CUR_PTR - BASE_PTR;
3448
1.77M
    c = xmlCurrentChar(ctxt, &l);
3449
1.77M
    if ((c == ' ') || (c == '>') || (c == '/') || /* accelerators */
3450
1.74M
  (!xmlIsNameStartChar(ctxt, c) || (c == ':'))) {
3451
1.59M
  return(ret);
3452
1.59M
    }
3453
3454
28.8M
    while ((c != ' ') && (c != '>') && (c != '/') && /* test bigname.xml */
3455
28.8M
     (xmlIsNameChar(ctxt, c) && (c != ':'))) {
3456
28.6M
        if (len <= INT_MAX - l)
3457
28.6M
      len += l;
3458
28.6M
  NEXTL(l);
3459
28.6M
  c = xmlCurrentChar(ctxt, &l);
3460
28.6M
    }
3461
174k
    if (len > maxLength) {
3462
393
        xmlFatalErr(ctxt, XML_ERR_NAME_TOO_LONG, "NCName");
3463
393
        return(ret);
3464
393
    }
3465
174k
    ret = xmlDictLookupHashed(ctxt->dict, (BASE_PTR + startPosition), len);
3466
174k
    if (ret.name == NULL)
3467
2
        xmlErrMemory(ctxt);
3468
174k
    return(ret);
3469
174k
}
3470
3471
/**
3472
 * xmlParseNCName:
3473
 * @ctxt:  an XML parser context
3474
 * @len:  length of the string parsed
3475
 *
3476
 * parse an XML name.
3477
 *
3478
 * [4NS] NCNameChar ::= Letter | Digit | '.' | '-' | '_' |
3479
 *                      CombiningChar | Extender
3480
 *
3481
 * [5NS] NCName ::= (Letter | '_') (NCNameChar)*
3482
 *
3483
 * Returns the Name parsed or NULL
3484
 */
3485
3486
static xmlHashedString
3487
13.3M
xmlParseNCName(xmlParserCtxtPtr ctxt) {
3488
13.3M
    const xmlChar *in, *e;
3489
13.3M
    xmlHashedString ret;
3490
13.3M
    size_t count = 0;
3491
13.3M
    size_t maxLength = (ctxt->options & XML_PARSE_HUGE) ?
3492
0
                       XML_MAX_TEXT_LENGTH :
3493
13.3M
                       XML_MAX_NAME_LENGTH;
3494
3495
13.3M
    ret.name = NULL;
3496
3497
    /*
3498
     * Accelerator for simple ASCII names
3499
     */
3500
13.3M
    in = ctxt->input->cur;
3501
13.3M
    e = ctxt->input->end;
3502
13.3M
    if ((((*in >= 0x61) && (*in <= 0x7A)) ||
3503
2.10M
   ((*in >= 0x41) && (*in <= 0x5A)) ||
3504
11.6M
   (*in == '_')) && (in < e)) {
3505
11.6M
  in++;
3506
115M
  while ((((*in >= 0x61) && (*in <= 0x7A)) ||
3507
13.4M
          ((*in >= 0x41) && (*in <= 0x5A)) ||
3508
12.5M
          ((*in >= 0x30) && (*in <= 0x39)) ||
3509
12.1M
          (*in == '_') || (*in == '-') ||
3510
104M
          (*in == '.')) && (in < e))
3511
104M
      in++;
3512
11.6M
  if (in >= e)
3513
4.06k
      goto complex;
3514
11.6M
  if ((*in > 0) && (*in < 0x80)) {
3515
11.5M
      count = in - ctxt->input->cur;
3516
11.5M
            if (count > maxLength) {
3517
843
                xmlFatalErr(ctxt, XML_ERR_NAME_TOO_LONG, "NCName");
3518
843
                return(ret);
3519
843
            }
3520
11.5M
      ret = xmlDictLookupHashed(ctxt->dict, ctxt->input->cur, count);
3521
11.5M
      ctxt->input->cur = in;
3522
11.5M
      ctxt->input->col += count;
3523
11.5M
      if (ret.name == NULL) {
3524
4
          xmlErrMemory(ctxt);
3525
4
      }
3526
11.5M
      return(ret);
3527
11.5M
  }
3528
11.6M
    }
3529
1.77M
complex:
3530
1.77M
    return(xmlParseNCNameComplex(ctxt));
3531
13.3M
}
3532
3533
/**
3534
 * xmlParseNameAndCompare:
3535
 * @ctxt:  an XML parser context
3536
 *
3537
 * parse an XML name and compares for match
3538
 * (specialized for endtag parsing)
3539
 *
3540
 * Returns NULL for an illegal name, (xmlChar*) 1 for success
3541
 * and the name for mismatch
3542
 */
3543
3544
static const xmlChar *
3545
332k
xmlParseNameAndCompare(xmlParserCtxtPtr ctxt, xmlChar const *other) {
3546
332k
    register const xmlChar *cmp = other;
3547
332k
    register const xmlChar *in;
3548
332k
    const xmlChar *ret;
3549
3550
332k
    GROW;
3551
3552
332k
    in = ctxt->input->cur;
3553
1.23M
    while (*in != 0 && *in == *cmp) {
3554
903k
  ++in;
3555
903k
  ++cmp;
3556
903k
    }
3557
332k
    if (*cmp == 0 && (*in == '>' || IS_BLANK_CH (*in))) {
3558
  /* success */
3559
264k
  ctxt->input->col += in - ctxt->input->cur;
3560
264k
  ctxt->input->cur = in;
3561
264k
  return (const xmlChar*) 1;
3562
264k
    }
3563
    /* failure (or end of input buffer), check with full function */
3564
67.6k
    ret = xmlParseName (ctxt);
3565
    /* strings coming from the dictionary direct compare possible */
3566
67.6k
    if (ret == other) {
3567
1.08k
  return (const xmlChar*) 1;
3568
1.08k
    }
3569
66.6k
    return ret;
3570
67.6k
}
3571
3572
/**
3573
 * xmlParseStringName:
3574
 * @ctxt:  an XML parser context
3575
 * @str:  a pointer to the string pointer (IN/OUT)
3576
 *
3577
 * parse an XML name.
3578
 *
3579
 * [4] NameChar ::= Letter | Digit | '.' | '-' | '_' | ':' |
3580
 *                  CombiningChar | Extender
3581
 *
3582
 * [5] Name ::= (Letter | '_' | ':') (NameChar)*
3583
 *
3584
 * [6] Names ::= Name (#x20 Name)*
3585
 *
3586
 * Returns the Name parsed or NULL. The @str pointer
3587
 * is updated to the current location in the string.
3588
 */
3589
3590
static xmlChar *
3591
431k
xmlParseStringName(xmlParserCtxtPtr ctxt, const xmlChar** str) {
3592
431k
    xmlChar buf[XML_MAX_NAMELEN + 5];
3593
431k
    xmlChar *ret;
3594
431k
    const xmlChar *cur = *str;
3595
431k
    int len = 0, l;
3596
431k
    int c;
3597
431k
    int maxLength = (ctxt->options & XML_PARSE_HUGE) ?
3598
0
                    XML_MAX_TEXT_LENGTH :
3599
431k
                    XML_MAX_NAME_LENGTH;
3600
3601
431k
    c = CUR_SCHAR(cur, l);
3602
431k
    if (!xmlIsNameStartChar(ctxt, c)) {
3603
5.46k
  return(NULL);
3604
5.46k
    }
3605
3606
426k
    COPY_BUF(buf, len, c);
3607
426k
    cur += l;
3608
426k
    c = CUR_SCHAR(cur, l);
3609
820k
    while (xmlIsNameChar(ctxt, c)) {
3610
395k
  COPY_BUF(buf, len, c);
3611
395k
  cur += l;
3612
395k
  c = CUR_SCHAR(cur, l);
3613
395k
  if (len >= XML_MAX_NAMELEN) { /* test bigentname.xml */
3614
      /*
3615
       * Okay someone managed to make a huge name, so he's ready to pay
3616
       * for the processing speed.
3617
       */
3618
1.50k
      xmlChar *buffer;
3619
1.50k
      int max = len * 2;
3620
3621
1.50k
      buffer = xmlMalloc(max);
3622
1.50k
      if (buffer == NULL) {
3623
1
          xmlErrMemory(ctxt);
3624
1
    return(NULL);
3625
1
      }
3626
1.50k
      memcpy(buffer, buf, len);
3627
4.15M
      while (xmlIsNameChar(ctxt, c)) {
3628
4.15M
    if (len + 10 > max) {
3629
5.77k
        xmlChar *tmp;
3630
5.77k
                    int newSize;
3631
3632
5.77k
                    newSize = xmlGrowCapacity(max, 1, 1, maxLength);
3633
5.77k
                    if (newSize < 0) {
3634
114
                        xmlFatalErr(ctxt, XML_ERR_NAME_TOO_LONG, "NCName");
3635
114
                        xmlFree(buffer);
3636
114
                        return(NULL);
3637
114
                    }
3638
5.65k
        tmp = xmlRealloc(buffer, newSize);
3639
5.65k
        if (tmp == NULL) {
3640
1
      xmlErrMemory(ctxt);
3641
1
      xmlFree(buffer);
3642
1
      return(NULL);
3643
1
        }
3644
5.65k
        buffer = tmp;
3645
5.65k
                    max = newSize;
3646
5.65k
    }
3647
4.15M
    COPY_BUF(buffer, len, c);
3648
4.15M
    cur += l;
3649
4.15M
    c = CUR_SCHAR(cur, l);
3650
4.15M
      }
3651
1.39k
      buffer[len] = 0;
3652
1.39k
      *str = cur;
3653
1.39k
      return(buffer);
3654
1.50k
  }
3655
395k
    }
3656
424k
    if (len > maxLength) {
3657
0
        xmlFatalErr(ctxt, XML_ERR_NAME_TOO_LONG, "NCName");
3658
0
        return(NULL);
3659
0
    }
3660
424k
    *str = cur;
3661
424k
    ret = xmlStrndup(buf, len);
3662
424k
    if (ret == NULL)
3663
13
        xmlErrMemory(ctxt);
3664
424k
    return(ret);
3665
424k
}
3666
3667
/**
3668
 * xmlParseNmtoken:
3669
 * @ctxt:  an XML parser context
3670
 *
3671
 * DEPRECATED: Internal function, don't use.
3672
 *
3673
 * parse an XML Nmtoken.
3674
 *
3675
 * [7] Nmtoken ::= (NameChar)+
3676
 *
3677
 * [8] Nmtokens ::= Nmtoken (#x20 Nmtoken)*
3678
 *
3679
 * Returns the Nmtoken parsed or NULL
3680
 */
3681
3682
xmlChar *
3683
73.9k
xmlParseNmtoken(xmlParserCtxtPtr ctxt) {
3684
73.9k
    xmlChar buf[XML_MAX_NAMELEN + 5];
3685
73.9k
    xmlChar *ret;
3686
73.9k
    int len = 0, l;
3687
73.9k
    int c;
3688
73.9k
    int maxLength = (ctxt->options & XML_PARSE_HUGE) ?
3689
0
                    XML_MAX_TEXT_LENGTH :
3690
73.9k
                    XML_MAX_NAME_LENGTH;
3691
3692
73.9k
    c = xmlCurrentChar(ctxt, &l);
3693
3694
648k
    while (xmlIsNameChar(ctxt, c)) {
3695
578k
  COPY_BUF(buf, len, c);
3696
578k
  NEXTL(l);
3697
578k
  c = xmlCurrentChar(ctxt, &l);
3698
578k
  if (len >= XML_MAX_NAMELEN) {
3699
      /*
3700
       * Okay someone managed to make a huge token, so he's ready to pay
3701
       * for the processing speed.
3702
       */
3703
4.24k
      xmlChar *buffer;
3704
4.24k
      int max = len * 2;
3705
3706
4.24k
      buffer = xmlMalloc(max);
3707
4.24k
      if (buffer == NULL) {
3708
1
          xmlErrMemory(ctxt);
3709
1
    return(NULL);
3710
1
      }
3711
4.24k
      memcpy(buffer, buf, len);
3712
24.9M
      while (xmlIsNameChar(ctxt, c)) {
3713
24.9M
    if (len + 10 > max) {
3714
9.73k
        xmlChar *tmp;
3715
9.73k
                    int newSize;
3716
3717
9.73k
                    newSize = xmlGrowCapacity(max, 1, 1, maxLength);
3718
9.73k
                    if (newSize < 0) {
3719
527
                        xmlFatalErr(ctxt, XML_ERR_NAME_TOO_LONG, "NmToken");
3720
527
                        xmlFree(buffer);
3721
527
                        return(NULL);
3722
527
                    }
3723
9.20k
        tmp = xmlRealloc(buffer, newSize);
3724
9.20k
        if (tmp == NULL) {
3725
2
      xmlErrMemory(ctxt);
3726
2
      xmlFree(buffer);
3727
2
      return(NULL);
3728
2
        }
3729
9.20k
        buffer = tmp;
3730
9.20k
                    max = newSize;
3731
9.20k
    }
3732
24.9M
    COPY_BUF(buffer, len, c);
3733
24.9M
    NEXTL(l);
3734
24.9M
    c = xmlCurrentChar(ctxt, &l);
3735
24.9M
      }
3736
3.71k
      buffer[len] = 0;
3737
3.71k
      return(buffer);
3738
4.24k
  }
3739
578k
    }
3740
69.7k
    if (len == 0)
3741
31.9k
        return(NULL);
3742
37.7k
    if (len > maxLength) {
3743
0
        xmlFatalErr(ctxt, XML_ERR_NAME_TOO_LONG, "NmToken");
3744
0
        return(NULL);
3745
0
    }
3746
37.7k
    ret = xmlStrndup(buf, len);
3747
37.7k
    if (ret == NULL)
3748
9
        xmlErrMemory(ctxt);
3749
37.7k
    return(ret);
3750
37.7k
}
3751
3752
/**
3753
 * xmlExpandPEsInEntityValue:
3754
 * @ctxt:  parser context
3755
 * @buf:  string buffer
3756
 * @str:  entity value
3757
 * @length:  size of entity value
3758
 * @depth:  nesting depth
3759
 *
3760
 * Validate an entity value and expand parameter entities.
3761
 */
3762
static void
3763
xmlExpandPEsInEntityValue(xmlParserCtxtPtr ctxt, xmlSBuf *buf,
3764
128k
                          const xmlChar *str, int length, int depth) {
3765
128k
    int maxDepth = (ctxt->options & XML_PARSE_HUGE) ? 40 : 20;
3766
128k
    const xmlChar *end, *chunk;
3767
128k
    int c, l;
3768
3769
128k
    if (str == NULL)
3770
4.57k
        return;
3771
3772
123k
    depth += 1;
3773
123k
    if (depth > maxDepth) {
3774
0
  xmlFatalErrMsg(ctxt, XML_ERR_RESOURCE_LIMIT,
3775
0
                       "Maximum entity nesting depth exceeded");
3776
0
  return;
3777
0
    }
3778
3779
123k
    end = str + length;
3780
123k
    chunk = str;
3781
3782
124M
    while ((str < end) && (!PARSER_STOPPED(ctxt))) {
3783
124M
        c = *str;
3784
3785
124M
        if (c >= 0x80) {
3786
112M
            l = xmlUTF8MultibyteLen(ctxt, str,
3787
112M
                    "invalid character in entity value\n");
3788
112M
            if (l == 0) {
3789
14.4M
                if (chunk < str)
3790
167k
                    xmlSBufAddString(buf, chunk, str - chunk);
3791
14.4M
                xmlSBufAddReplChar(buf);
3792
14.4M
                str += 1;
3793
14.4M
                chunk = str;
3794
97.5M
            } else {
3795
97.5M
                str += l;
3796
97.5M
            }
3797
112M
        } else if (c == '&') {
3798
73.3k
            if (str[1] == '#') {
3799
34.4k
                if (chunk < str)
3800
21.5k
                    xmlSBufAddString(buf, chunk, str - chunk);
3801
3802
34.4k
                c = xmlParseStringCharRef(ctxt, &str);
3803
34.4k
                if (c == 0)
3804
3.66k
                    return;
3805
3806
30.8k
                xmlSBufAddChar(buf, c);
3807
3808
30.8k
                chunk = str;
3809
38.8k
            } else {
3810
38.8k
                xmlChar *name;
3811
3812
                /*
3813
                 * General entity references are checked for
3814
                 * syntactic validity.
3815
                 */
3816
38.8k
                str++;
3817
38.8k
                name = xmlParseStringName(ctxt, &str);
3818
3819
38.8k
                if ((name == NULL) || (*str++ != ';')) {
3820
2.84k
                    xmlFatalErrMsg(ctxt, XML_ERR_ENTITY_CHAR_ERROR,
3821
2.84k
                            "EntityValue: '&' forbidden except for entities "
3822
2.84k
                            "references\n");
3823
2.84k
                    xmlFree(name);
3824
2.84k
                    return;
3825
2.84k
                }
3826
3827
36.0k
                xmlFree(name);
3828
36.0k
            }
3829
12.2M
        } else if (c == '%') {
3830
33.0k
            xmlEntityPtr ent;
3831
3832
33.0k
            if (chunk < str)
3833
12.9k
                xmlSBufAddString(buf, chunk, str - chunk);
3834
3835
33.0k
            ent = xmlParseStringPEReference(ctxt, &str);
3836
33.0k
            if (ent == NULL)
3837
5.63k
                return;
3838
3839
27.3k
            if (!PARSER_EXTERNAL(ctxt)) {
3840
393
                xmlFatalErr(ctxt, XML_ERR_ENTITY_PE_INTERNAL, NULL);
3841
393
                return;
3842
393
            }
3843
3844
26.9k
            if (ent->content == NULL) {
3845
                /*
3846
                 * Note: external parsed entities will not be loaded,
3847
                 * it is not required for a non-validating parser to
3848
                 * complete external PEReferences coming from the
3849
                 * internal subset
3850
                 */
3851
16.8k
                if (((ctxt->options & XML_PARSE_NO_XXE) == 0) &&
3852
16.8k
                    ((ctxt->replaceEntities) ||
3853
16.8k
                     (ctxt->validate))) {
3854
16.8k
                    xmlLoadEntityContent(ctxt, ent);
3855
16.8k
                } else {
3856
0
                    xmlWarningMsg(ctxt, XML_ERR_ENTITY_PROCESSING,
3857
0
                                  "not validating will not read content for "
3858
0
                                  "PE entity %s\n", ent->name, NULL);
3859
0
                }
3860
16.8k
            }
3861
3862
            /*
3863
             * TODO: Skip if ent->content is still NULL.
3864
             */
3865
3866
26.9k
            if (xmlParserEntityCheck(ctxt, ent->length))
3867
105
                return;
3868
3869
26.8k
            if (ent->flags & XML_ENT_EXPANDING) {
3870
10.2k
                xmlFatalErr(ctxt, XML_ERR_ENTITY_LOOP, NULL);
3871
10.2k
                xmlHaltParser(ctxt);
3872
10.2k
                return;
3873
10.2k
            }
3874
3875
16.6k
            ent->flags |= XML_ENT_EXPANDING;
3876
16.6k
            xmlExpandPEsInEntityValue(ctxt, buf, ent->content, ent->length,
3877
16.6k
                                      depth);
3878
16.6k
            ent->flags &= ~XML_ENT_EXPANDING;
3879
3880
16.6k
            chunk = str;
3881
12.1M
        } else {
3882
            /* Normal ASCII char */
3883
12.1M
            if (!IS_BYTE_CHAR(c)) {
3884
2.65M
                xmlFatalErrMsg(ctxt, XML_ERR_INVALID_CHAR,
3885
2.65M
                        "invalid character in entity value\n");
3886
2.65M
                if (chunk < str)
3887
43.8k
                    xmlSBufAddString(buf, chunk, str - chunk);
3888
2.65M
                xmlSBufAddReplChar(buf);
3889
2.65M
                str += 1;
3890
2.65M
                chunk = str;
3891
9.51M
            } else {
3892
9.51M
                str += 1;
3893
9.51M
            }
3894
12.1M
        }
3895
124M
    }
3896
3897
100k
    if (chunk < str)
3898
88.9k
        xmlSBufAddString(buf, chunk, str - chunk);
3899
100k
}
3900
3901
/**
3902
 * xmlParseEntityValue:
3903
 * @ctxt:  an XML parser context
3904
 * @orig:  if non-NULL store a copy of the original entity value
3905
 *
3906
 * DEPRECATED: Internal function, don't use.
3907
 *
3908
 * parse a value for ENTITY declarations
3909
 *
3910
 * [9] EntityValue ::= '"' ([^%&"] | PEReference | Reference)* '"' |
3911
 *                 "'" ([^%&'] | PEReference | Reference)* "'"
3912
 *
3913
 * Returns the EntityValue parsed with reference substituted or NULL
3914
 */
3915
xmlChar *
3916
115k
xmlParseEntityValue(xmlParserCtxtPtr ctxt, xmlChar **orig) {
3917
115k
    unsigned maxLength = (ctxt->options & XML_PARSE_HUGE) ?
3918
0
                         XML_MAX_HUGE_LENGTH :
3919
115k
                         XML_MAX_TEXT_LENGTH;
3920
115k
    xmlSBuf buf;
3921
115k
    const xmlChar *start;
3922
115k
    int quote, length;
3923
3924
115k
    xmlSBufInit(&buf, maxLength);
3925
3926
115k
    GROW;
3927
3928
115k
    quote = CUR;
3929
115k
    if ((quote != '"') && (quote != '\'')) {
3930
0
  xmlFatalErr(ctxt, XML_ERR_ATTRIBUTE_NOT_STARTED, NULL);
3931
0
  return(NULL);
3932
0
    }
3933
115k
    CUR_PTR++;
3934
3935
115k
    length = 0;
3936
3937
    /*
3938
     * Copy raw content of the entity into a buffer
3939
     */
3940
180M
    while (1) {
3941
180M
        int c;
3942
3943
180M
        if (PARSER_STOPPED(ctxt))
3944
70
            goto error;
3945
3946
180M
        if (CUR_PTR >= ctxt->input->end) {
3947
957
            xmlFatalErrMsg(ctxt, XML_ERR_ENTITY_NOT_FINISHED, NULL);
3948
957
            goto error;
3949
957
        }
3950
3951
180M
        c = CUR;
3952
3953
180M
        if (c == 0) {
3954
2.68k
            xmlFatalErrMsg(ctxt, XML_ERR_INVALID_CHAR,
3955
2.68k
                    "invalid character in entity value\n");
3956
2.68k
            goto error;
3957
2.68k
        }
3958
180M
        if (c == quote)
3959
111k
            break;
3960
180M
        NEXTL(1);
3961
180M
        length += 1;
3962
3963
        /*
3964
         * TODO: Check growth threshold
3965
         */
3966
180M
        if (ctxt->input->end - CUR_PTR < 10)
3967
33.3k
            GROW;
3968
180M
    }
3969
3970
111k
    start = CUR_PTR - length;
3971
3972
111k
    if (orig != NULL) {
3973
111k
        *orig = xmlStrndup(start, length);
3974
111k
        if (*orig == NULL)
3975
4
            xmlErrMemory(ctxt);
3976
111k
    }
3977
3978
111k
    xmlExpandPEsInEntityValue(ctxt, &buf, start, length, ctxt->inputNr);
3979
3980
111k
    NEXTL(1);
3981
3982
111k
    return(xmlSBufFinish(&buf, NULL, ctxt, "entity length too long"));
3983
3984
3.70k
error:
3985
3.70k
    xmlSBufCleanup(&buf, ctxt, "entity length too long");
3986
3.70k
    return(NULL);
3987
115k
}
3988
3989
/**
3990
 * xmlCheckEntityInAttValue:
3991
 * @ctxt:  parser context
3992
 * @pent:  entity
3993
 * @depth:  nesting depth
3994
 *
3995
 * Check an entity reference in an attribute value for validity
3996
 * without expanding it.
3997
 */
3998
static void
3999
26
xmlCheckEntityInAttValue(xmlParserCtxtPtr ctxt, xmlEntityPtr pent, int depth) {
4000
26
    int maxDepth = (ctxt->options & XML_PARSE_HUGE) ? 40 : 20;
4001
26
    const xmlChar *str;
4002
26
    unsigned long expandedSize = pent->length;
4003
26
    int c, flags;
4004
4005
26
    depth += 1;
4006
26
    if (depth > maxDepth) {
4007
0
  xmlFatalErrMsg(ctxt, XML_ERR_RESOURCE_LIMIT,
4008
0
                       "Maximum entity nesting depth exceeded");
4009
0
  return;
4010
0
    }
4011
4012
26
    if (pent->flags & XML_ENT_EXPANDING) {
4013
0
        xmlFatalErr(ctxt, XML_ERR_ENTITY_LOOP, NULL);
4014
0
        xmlHaltParser(ctxt);
4015
0
        return;
4016
0
    }
4017
4018
    /*
4019
     * If we're parsing a default attribute value in DTD content,
4020
     * the entity might reference other entities which weren't
4021
     * defined yet, so the check isn't reliable.
4022
     */
4023
26
    if (ctxt->inSubset == 0)
4024
26
        flags = XML_ENT_CHECKED | XML_ENT_VALIDATED;
4025
0
    else
4026
0
        flags = XML_ENT_VALIDATED;
4027
4028
26
    str = pent->content;
4029
26
    if (str == NULL)
4030
0
        goto done;
4031
4032
    /*
4033
     * Note that entity values are already validated. We only check
4034
     * for illegal less-than signs and compute the expanded size
4035
     * of the entity. No special handling for multi-byte characters
4036
     * is needed.
4037
     */
4038
1.75M
    while (!PARSER_STOPPED(ctxt)) {
4039
1.75M
        c = *str;
4040
4041
1.75M
  if (c != '&') {
4042
1.75M
            if (c == 0)
4043
26
                break;
4044
4045
1.75M
            if (c == '<')
4046
5.85k
                xmlFatalErrMsgStr(ctxt, XML_ERR_LT_IN_ATTRIBUTE,
4047
5.85k
                        "'<' in entity '%s' is not allowed in attributes "
4048
5.85k
                        "values\n", pent->name);
4049
4050
1.75M
            str += 1;
4051
1.75M
        } else if (str[1] == '#') {
4052
0
            int val;
4053
4054
0
      val = xmlParseStringCharRef(ctxt, &str);
4055
0
      if (val == 0) {
4056
0
                pent->content[0] = 0;
4057
0
                break;
4058
0
            }
4059
3.23k
  } else {
4060
3.23k
            xmlChar *name;
4061
3.23k
            xmlEntityPtr ent;
4062
4063
3.23k
      name = xmlParseStringEntityRef(ctxt, &str);
4064
3.23k
      if (name == NULL) {
4065
0
                pent->content[0] = 0;
4066
0
                break;
4067
0
            }
4068
4069
3.23k
            ent = xmlLookupGeneralEntity(ctxt, name, /* inAttr */ 1);
4070
3.23k
            xmlFree(name);
4071
4072
3.23k
            if ((ent != NULL) &&
4073
3.21k
                (ent->etype != XML_INTERNAL_PREDEFINED_ENTITY)) {
4074
2.09k
                if ((ent->flags & flags) != flags) {
4075
14
                    pent->flags |= XML_ENT_EXPANDING;
4076
14
                    xmlCheckEntityInAttValue(ctxt, ent, depth);
4077
14
                    pent->flags &= ~XML_ENT_EXPANDING;
4078
14
                }
4079
4080
2.09k
                xmlSaturatedAdd(&expandedSize, ent->expandedSize);
4081
2.09k
                xmlSaturatedAdd(&expandedSize, XML_ENT_FIXED_COST);
4082
2.09k
            }
4083
3.23k
        }
4084
1.75M
    }
4085
4086
26
done:
4087
26
    if (ctxt->inSubset == 0)
4088
26
        pent->expandedSize = expandedSize;
4089
4090
26
    pent->flags |= flags;
4091
26
}
4092
4093
/**
4094
 * xmlExpandEntityInAttValue:
4095
 * @ctxt:  parser context
4096
 * @buf:  string buffer
4097
 * @str:  entity or attribute value
4098
 * @pent:  entity for entity value, NULL for attribute values
4099
 * @normalize:  whether to collapse whitespace
4100
 * @inSpace:  whitespace state
4101
 * @depth:  nesting depth
4102
 * @check:  whether to check for amplification
4103
 *
4104
 * Expand general entity references in an entity or attribute value.
4105
 * Perform attribute value normalization.
4106
 */
4107
static void
4108
xmlExpandEntityInAttValue(xmlParserCtxtPtr ctxt, xmlSBuf *buf,
4109
                          const xmlChar *str, xmlEntityPtr pent, int normalize,
4110
1.25M
                          int *inSpace, int depth, int check) {
4111
1.25M
    int maxDepth = (ctxt->options & XML_PARSE_HUGE) ? 40 : 20;
4112
1.25M
    int c, chunkSize;
4113
4114
1.25M
    if (str == NULL)
4115
0
        return;
4116
4117
1.25M
    depth += 1;
4118
1.25M
    if (depth > maxDepth) {
4119
0
  xmlFatalErrMsg(ctxt, XML_ERR_RESOURCE_LIMIT,
4120
0
                       "Maximum entity nesting depth exceeded");
4121
0
  return;
4122
0
    }
4123
4124
1.25M
    if (pent != NULL) {
4125
1.25M
        if (pent->flags & XML_ENT_EXPANDING) {
4126
316
            xmlFatalErr(ctxt, XML_ERR_ENTITY_LOOP, NULL);
4127
316
            xmlHaltParser(ctxt);
4128
316
            return;
4129
316
        }
4130
4131
1.25M
        if (check) {
4132
1.25M
            if (xmlParserEntityCheck(ctxt, pent->length))
4133
393
                return;
4134
1.25M
        }
4135
1.25M
    }
4136
4137
1.25M
    chunkSize = 0;
4138
4139
    /*
4140
     * Note that entity values are already validated. No special
4141
     * handling for multi-byte characters is needed.
4142
     */
4143
1.09G
    while (!PARSER_STOPPED(ctxt)) {
4144
1.09G
        c = *str;
4145
4146
1.09G
  if (c != '&') {
4147
1.09G
            if (c == 0)
4148
1.18M
                break;
4149
4150
            /*
4151
             * If this function is called without an entity, it is used to
4152
             * expand entities in an attribute content where less-than was
4153
             * already unscaped and is allowed.
4154
             */
4155
1.09G
            if ((pent != NULL) && (c == '<')) {
4156
66.7k
                xmlFatalErrMsgStr(ctxt, XML_ERR_LT_IN_ATTRIBUTE,
4157
66.7k
                        "'<' in entity '%s' is not allowed in attributes "
4158
66.7k
                        "values\n", pent->name);
4159
66.7k
                break;
4160
66.7k
            }
4161
4162
1.09G
            if (c <= 0x20) {
4163
35.0M
                if ((normalize) && (*inSpace)) {
4164
                    /* Skip char */
4165
23.2M
                    if (chunkSize > 0) {
4166
5.02M
                        xmlSBufAddString(buf, str - chunkSize, chunkSize);
4167
5.02M
                        chunkSize = 0;
4168
5.02M
                    }
4169
23.2M
                } else if (c < 0x20) {
4170
5.77M
                    if (chunkSize > 0) {
4171
942k
                        xmlSBufAddString(buf, str - chunkSize, chunkSize);
4172
942k
                        chunkSize = 0;
4173
942k
                    }
4174
4175
5.77M
                    xmlSBufAddCString(buf, " ", 1);
4176
5.97M
                } else {
4177
5.97M
                    chunkSize += 1;
4178
5.97M
                }
4179
4180
35.0M
                *inSpace = 1;
4181
1.05G
            } else {
4182
1.05G
                chunkSize += 1;
4183
1.05G
                *inSpace = 0;
4184
1.05G
            }
4185
4186
1.09G
            str += 1;
4187
1.09G
        } else if (str[1] == '#') {
4188
98.2k
            int val;
4189
4190
98.2k
            if (chunkSize > 0) {
4191
92.1k
                xmlSBufAddString(buf, str - chunkSize, chunkSize);
4192
92.1k
                chunkSize = 0;
4193
92.1k
            }
4194
4195
98.2k
      val = xmlParseStringCharRef(ctxt, &str);
4196
98.2k
      if (val == 0) {
4197
570
                if (pent != NULL)
4198
570
                    pent->content[0] = 0;
4199
570
                break;
4200
570
            }
4201
4202
97.7k
            if (val == ' ') {
4203
8.93k
                if ((!normalize) || (!*inSpace))
4204
8.36k
                    xmlSBufAddCString(buf, " ", 1);
4205
8.93k
                *inSpace = 1;
4206
88.7k
            } else {
4207
88.7k
                xmlSBufAddChar(buf, val);
4208
88.7k
                *inSpace = 0;
4209
88.7k
            }
4210
356k
  } else {
4211
356k
            xmlChar *name;
4212
356k
            xmlEntityPtr ent;
4213
4214
356k
            if (chunkSize > 0) {
4215
225k
                xmlSBufAddString(buf, str - chunkSize, chunkSize);
4216
225k
                chunkSize = 0;
4217
225k
            }
4218
4219
356k
      name = xmlParseStringEntityRef(ctxt, &str);
4220
356k
            if (name == NULL) {
4221
1.15k
                if (pent != NULL)
4222
1.15k
                    pent->content[0] = 0;
4223
1.15k
                break;
4224
1.15k
            }
4225
4226
355k
            ent = xmlLookupGeneralEntity(ctxt, name, /* inAttr */ 1);
4227
355k
            xmlFree(name);
4228
4229
355k
      if ((ent != NULL) &&
4230
301k
    (ent->etype == XML_INTERNAL_PREDEFINED_ENTITY)) {
4231
96.5k
    if (ent->content == NULL) {
4232
0
        xmlFatalErrMsg(ctxt, XML_ERR_INTERNAL_ERROR,
4233
0
          "predefined entity has no content\n");
4234
0
                    break;
4235
0
                }
4236
4237
96.5k
                xmlSBufAddString(buf, ent->content, ent->length);
4238
4239
96.5k
                *inSpace = 0;
4240
259k
      } else if ((ent != NULL) && (ent->content != NULL)) {
4241
205k
                if (pent != NULL)
4242
205k
                    pent->flags |= XML_ENT_EXPANDING;
4243
205k
    xmlExpandEntityInAttValue(ctxt, buf, ent->content, ent,
4244
205k
                                          normalize, inSpace, depth, check);
4245
205k
                if (pent != NULL)
4246
205k
                    pent->flags &= ~XML_ENT_EXPANDING;
4247
205k
      }
4248
355k
        }
4249
1.09G
    }
4250
4251
1.25M
    if (chunkSize > 0)
4252
300k
        xmlSBufAddString(buf, str - chunkSize, chunkSize);
4253
1.25M
}
4254
4255
/**
4256
 * xmlExpandEntitiesInAttValue:
4257
 * @ctxt:  parser context
4258
 * @str:  entity or attribute value
4259
 * @normalize:  whether to collapse whitespace
4260
 *
4261
 * Expand general entity references in an entity or attribute value.
4262
 * Perform attribute value normalization.
4263
 *
4264
 * Returns the expanded attribtue value.
4265
 */
4266
xmlChar *
4267
xmlExpandEntitiesInAttValue(xmlParserCtxtPtr ctxt, const xmlChar *str,
4268
0
                            int normalize) {
4269
0
    unsigned maxLength = (ctxt->options & XML_PARSE_HUGE) ?
4270
0
                         XML_MAX_HUGE_LENGTH :
4271
0
                         XML_MAX_TEXT_LENGTH;
4272
0
    xmlSBuf buf;
4273
0
    int inSpace = 1;
4274
4275
0
    xmlSBufInit(&buf, maxLength);
4276
4277
0
    xmlExpandEntityInAttValue(ctxt, &buf, str, NULL, normalize, &inSpace,
4278
0
                              ctxt->inputNr, /* check */ 0);
4279
4280
0
    if ((normalize) && (inSpace) && (buf.size > 0))
4281
0
        buf.size--;
4282
4283
0
    return(xmlSBufFinish(&buf, NULL, ctxt, "AttValue length too long"));
4284
0
}
4285
4286
/**
4287
 * xmlParseAttValueInternal:
4288
 * @ctxt:  an XML parser context
4289
 * @len:  attribute len result
4290
 * @alloc:  whether the attribute was reallocated as a new string
4291
 * @normalize:  if 1 then further non-CDATA normalization must be done
4292
 *
4293
 * parse a value for an attribute.
4294
 * NOTE: if no normalization is needed, the routine will return pointers
4295
 *       directly from the data buffer.
4296
 *
4297
 * 3.3.3 Attribute-Value Normalization:
4298
 * Before the value of an attribute is passed to the application or
4299
 * checked for validity, the XML processor must normalize it as follows:
4300
 * - a character reference is processed by appending the referenced
4301
 *   character to the attribute value
4302
 * - an entity reference is processed by recursively processing the
4303
 *   replacement text of the entity
4304
 * - a whitespace character (#x20, #xD, #xA, #x9) is processed by
4305
 *   appending #x20 to the normalized value, except that only a single
4306
 *   #x20 is appended for a "#xD#xA" sequence that is part of an external
4307
 *   parsed entity or the literal entity value of an internal parsed entity
4308
 * - other characters are processed by appending them to the normalized value
4309
 * If the declared value is not CDATA, then the XML processor must further
4310
 * process the normalized attribute value by discarding any leading and
4311
 * trailing space (#x20) characters, and by replacing sequences of space
4312
 * (#x20) characters by a single space (#x20) character.
4313
 * All attributes for which no declaration has been read should be treated
4314
 * by a non-validating parser as if declared CDATA.
4315
 *
4316
 * Returns the AttValue parsed or NULL. The value has to be freed by the
4317
 *     caller if it was copied, this can be detected by val[*len] == 0.
4318
 */
4319
static xmlChar *
4320
xmlParseAttValueInternal(xmlParserCtxtPtr ctxt, int *attlen, int *alloc,
4321
3.60M
                         int normalize, int isNamespace) {
4322
3.60M
    unsigned maxLength = (ctxt->options & XML_PARSE_HUGE) ?
4323
0
                         XML_MAX_HUGE_LENGTH :
4324
3.60M
                         XML_MAX_TEXT_LENGTH;
4325
3.60M
    xmlSBuf buf;
4326
3.60M
    xmlChar *ret;
4327
3.60M
    int c, l, quote, flags, chunkSize;
4328
3.60M
    int inSpace = 1;
4329
3.60M
    int replaceEntities;
4330
4331
    /* Always expand namespace URIs */
4332
3.60M
    replaceEntities = (ctxt->replaceEntities) || (isNamespace);
4333
4334
3.60M
    xmlSBufInit(&buf, maxLength);
4335
4336
3.60M
    GROW;
4337
4338
3.60M
    quote = CUR;
4339
3.60M
    if ((quote != '"') && (quote != '\'')) {
4340
14.1k
  xmlFatalErr(ctxt, XML_ERR_ATTRIBUTE_NOT_STARTED, NULL);
4341
14.1k
  return(NULL);
4342
14.1k
    }
4343
3.58M
    NEXTL(1);
4344
4345
3.58M
    if (ctxt->inSubset == 0)
4346
3.52M
        flags = XML_ENT_CHECKED | XML_ENT_VALIDATED;
4347
63.8k
    else
4348
63.8k
        flags = XML_ENT_VALIDATED;
4349
4350
3.58M
    inSpace = 1;
4351
3.58M
    chunkSize = 0;
4352
4353
237M
    while (1) {
4354
237M
        if (PARSER_STOPPED(ctxt))
4355
775
            goto error;
4356
4357
237M
        if (CUR_PTR >= ctxt->input->end) {
4358
9.04k
            xmlFatalErrMsg(ctxt, XML_ERR_ATTRIBUTE_NOT_FINISHED,
4359
9.04k
                           "AttValue: ' expected\n");
4360
9.04k
            goto error;
4361
9.04k
        }
4362
4363
        /*
4364
         * TODO: Check growth threshold
4365
         */
4366
237M
        if (ctxt->input->end - CUR_PTR < 10)
4367
137k
            GROW;
4368
4369
237M
        c = CUR;
4370
4371
237M
        if (c >= 0x80) {
4372
75.2M
            l = xmlUTF8MultibyteLen(ctxt, CUR_PTR,
4373
75.2M
                    "invalid character in attribute value\n");
4374
75.2M
            if (l == 0) {
4375
29.9M
                if (chunkSize > 0) {
4376
519k
                    xmlSBufAddString(&buf, CUR_PTR - chunkSize, chunkSize);
4377
519k
                    chunkSize = 0;
4378
519k
                }
4379
29.9M
                xmlSBufAddReplChar(&buf);
4380
29.9M
                NEXTL(1);
4381
45.2M
            } else {
4382
45.2M
                chunkSize += l;
4383
45.2M
                NEXTL(l);
4384
45.2M
            }
4385
4386
75.2M
            inSpace = 0;
4387
162M
        } else if (c != '&') {
4388
160M
            if (c > 0x20) {
4389
73.8M
                if (c == quote)
4390
3.57M
                    break;
4391
4392
70.2M
                if (c == '<')
4393
671k
                    xmlFatalErr(ctxt, XML_ERR_LT_IN_ATTRIBUTE, NULL);
4394
4395
70.2M
                chunkSize += 1;
4396
70.2M
                inSpace = 0;
4397
87.0M
            } else if (!IS_BYTE_CHAR(c)) {
4398
36.6M
                xmlFatalErrMsg(ctxt, XML_ERR_INVALID_CHAR,
4399
36.6M
                        "invalid character in attribute value\n");
4400
36.6M
                if (chunkSize > 0) {
4401
207k
                    xmlSBufAddString(&buf, CUR_PTR - chunkSize, chunkSize);
4402
207k
                    chunkSize = 0;
4403
207k
                }
4404
36.6M
                xmlSBufAddReplChar(&buf);
4405
36.6M
                inSpace = 0;
4406
50.4M
            } else {
4407
                /* Whitespace */
4408
50.4M
                if ((normalize) && (inSpace)) {
4409
                    /* Skip char */
4410
514k
                    if (chunkSize > 0) {
4411
113k
                        xmlSBufAddString(&buf, CUR_PTR - chunkSize, chunkSize);
4412
113k
                        chunkSize = 0;
4413
113k
                    }
4414
49.9M
                } else if (c < 0x20) {
4415
                    /* Convert to space */
4416
48.7M
                    if (chunkSize > 0) {
4417
283k
                        xmlSBufAddString(&buf, CUR_PTR - chunkSize, chunkSize);
4418
283k
                        chunkSize = 0;
4419
283k
                    }
4420
4421
48.7M
                    xmlSBufAddCString(&buf, " ", 1);
4422
48.7M
                } else {
4423
1.16M
                    chunkSize += 1;
4424
1.16M
                }
4425
4426
50.4M
                inSpace = 1;
4427
4428
50.4M
                if ((c == 0xD) && (NXT(1) == 0xA))
4429
19.6k
                    CUR_PTR++;
4430
50.4M
            }
4431
4432
157M
            NEXTL(1);
4433
157M
        } else if (NXT(1) == '#') {
4434
129k
            int val;
4435
4436
129k
            if (chunkSize > 0) {
4437
61.3k
                xmlSBufAddString(&buf, CUR_PTR - chunkSize, chunkSize);
4438
61.3k
                chunkSize = 0;
4439
61.3k
            }
4440
4441
129k
            val = xmlParseCharRef(ctxt);
4442
129k
            if (val == 0)
4443
2.91k
                goto error;
4444
4445
126k
            if ((val == '&') && (!replaceEntities)) {
4446
                /*
4447
                 * The reparsing will be done in xmlNodeParseContent()
4448
                 * called from SAX2.c
4449
                 */
4450
479
                xmlSBufAddCString(&buf, "&#38;", 5);
4451
479
                inSpace = 0;
4452
126k
            } else if (val == ' ') {
4453
48.7k
                if ((!normalize) || (!inSpace))
4454
48.4k
                    xmlSBufAddCString(&buf, " ", 1);
4455
48.7k
                inSpace = 1;
4456
77.6k
            } else {
4457
77.6k
                xmlSBufAddChar(&buf, val);
4458
77.6k
                inSpace = 0;
4459
77.6k
            }
4460
1.62M
        } else {
4461
1.62M
            const xmlChar *name;
4462
1.62M
            xmlEntityPtr ent;
4463
4464
1.62M
            if (chunkSize > 0) {
4465
1.36M
                xmlSBufAddString(&buf, CUR_PTR - chunkSize, chunkSize);
4466
1.36M
                chunkSize = 0;
4467
1.36M
            }
4468
4469
1.62M
            name = xmlParseEntityRefInternal(ctxt);
4470
1.62M
            if (name == NULL) {
4471
                /*
4472
                 * Probably a literal '&' which wasn't escaped.
4473
                 * TODO: Handle gracefully in recovery mode.
4474
                 */
4475
437k
                continue;
4476
437k
            }
4477
4478
1.18M
            ent = xmlLookupGeneralEntity(ctxt, name, /* isAttr */ 1);
4479
1.18M
            if (ent == NULL)
4480
112k
                continue;
4481
4482
1.07M
            if (ent->etype == XML_INTERNAL_PREDEFINED_ENTITY) {
4483
9.14k
                if ((ent->content[0] == '&') && (!replaceEntities))
4484
183
                    xmlSBufAddCString(&buf, "&#38;", 5);
4485
8.96k
                else
4486
8.96k
                    xmlSBufAddString(&buf, ent->content, ent->length);
4487
9.14k
                inSpace = 0;
4488
1.06M
            } else if (replaceEntities) {
4489
1.05M
                xmlExpandEntityInAttValue(ctxt, &buf, ent->content, ent,
4490
1.05M
                                          normalize, &inSpace, ctxt->inputNr,
4491
1.05M
                                          /* check */ 1);
4492
1.05M
            } else {
4493
11.4k
                if ((ent->flags & flags) != flags)
4494
12
                    xmlCheckEntityInAttValue(ctxt, ent, ctxt->inputNr);
4495
4496
11.4k
                if (xmlParserEntityCheck(ctxt, ent->expandedSize)) {
4497
6
                    ent->content[0] = 0;
4498
6
                    goto error;
4499
6
                }
4500
4501
                /*
4502
                 * Just output the reference
4503
                 */
4504
11.4k
                xmlSBufAddCString(&buf, "&", 1);
4505
11.4k
                xmlSBufAddString(&buf, ent->name, xmlStrlen(ent->name));
4506
11.4k
                xmlSBufAddCString(&buf, ";", 1);
4507
4508
11.4k
                inSpace = 0;
4509
11.4k
            }
4510
1.07M
  }
4511
237M
    }
4512
4513
3.57M
    if ((buf.mem == NULL) && (alloc != NULL)) {
4514
3.36M
        ret = (xmlChar *) CUR_PTR - chunkSize;
4515
4516
3.36M
        if (attlen != NULL)
4517
3.36M
            *attlen = chunkSize;
4518
3.36M
        if ((normalize) && (inSpace) && (chunkSize > 0))
4519
385
            *attlen -= 1;
4520
3.36M
        *alloc = 0;
4521
4522
        /* Report potential error */
4523
3.36M
        xmlSBufCleanup(&buf, ctxt, "AttValue length too long");
4524
3.36M
    } else {
4525
212k
        if (chunkSize > 0)
4526
127k
            xmlSBufAddString(&buf, CUR_PTR - chunkSize, chunkSize);
4527
4528
212k
        if ((normalize) && (inSpace) && (buf.size > 0))
4529
2.08k
            buf.size--;
4530
4531
212k
        ret = xmlSBufFinish(&buf, attlen, ctxt, "AttValue length too long");
4532
4533
212k
        if (ret != NULL) {
4534
212k
            if (attlen != NULL)
4535
149k
                *attlen = buf.size;
4536
212k
            if (alloc != NULL)
4537
149k
                *alloc = 1;
4538
212k
        }
4539
212k
    }
4540
4541
3.57M
    NEXTL(1);
4542
4543
3.57M
    return(ret);
4544
4545
12.7k
error:
4546
12.7k
    xmlSBufCleanup(&buf, ctxt, "AttValue length too long");
4547
12.7k
    return(NULL);
4548
3.58M
}
4549
4550
/**
4551
 * xmlParseAttValue:
4552
 * @ctxt:  an XML parser context
4553
 *
4554
 * DEPRECATED: Internal function, don't use.
4555
 *
4556
 * parse a value for an attribute
4557
 * Note: the parser won't do substitution of entities here, this
4558
 * will be handled later in xmlStringGetNodeList
4559
 *
4560
 * [10] AttValue ::= '"' ([^<&"] | Reference)* '"' |
4561
 *                   "'" ([^<&'] | Reference)* "'"
4562
 *
4563
 * 3.3.3 Attribute-Value Normalization:
4564
 * Before the value of an attribute is passed to the application or
4565
 * checked for validity, the XML processor must normalize it as follows:
4566
 * - a character reference is processed by appending the referenced
4567
 *   character to the attribute value
4568
 * - an entity reference is processed by recursively processing the
4569
 *   replacement text of the entity
4570
 * - a whitespace character (#x20, #xD, #xA, #x9) is processed by
4571
 *   appending #x20 to the normalized value, except that only a single
4572
 *   #x20 is appended for a "#xD#xA" sequence that is part of an external
4573
 *   parsed entity or the literal entity value of an internal parsed entity
4574
 * - other characters are processed by appending them to the normalized value
4575
 * If the declared value is not CDATA, then the XML processor must further
4576
 * process the normalized attribute value by discarding any leading and
4577
 * trailing space (#x20) characters, and by replacing sequences of space
4578
 * (#x20) characters by a single space (#x20) character.
4579
 * All attributes for which no declaration has been read should be treated
4580
 * by a non-validating parser as if declared CDATA.
4581
 *
4582
 * Returns the AttValue parsed or NULL. The value has to be freed by the caller.
4583
 */
4584
4585
4586
xmlChar *
4587
73.4k
xmlParseAttValue(xmlParserCtxtPtr ctxt) {
4588
73.4k
    if ((ctxt == NULL) || (ctxt->input == NULL)) return(NULL);
4589
73.4k
    return(xmlParseAttValueInternal(ctxt, NULL, NULL, 0, 0));
4590
73.4k
}
4591
4592
/**
4593
 * xmlParseSystemLiteral:
4594
 * @ctxt:  an XML parser context
4595
 *
4596
 * DEPRECATED: Internal function, don't use.
4597
 *
4598
 * parse an XML Literal
4599
 *
4600
 * [11] SystemLiteral ::= ('"' [^"]* '"') | ("'" [^']* "'")
4601
 *
4602
 * Returns the SystemLiteral parsed or NULL
4603
 */
4604
4605
xmlChar *
4606
133k
xmlParseSystemLiteral(xmlParserCtxtPtr ctxt) {
4607
133k
    xmlChar *buf = NULL;
4608
133k
    int len = 0;
4609
133k
    int size = XML_PARSER_BUFFER_SIZE;
4610
133k
    int cur, l;
4611
133k
    int maxLength = (ctxt->options & XML_PARSE_HUGE) ?
4612
0
                    XML_MAX_TEXT_LENGTH :
4613
133k
                    XML_MAX_NAME_LENGTH;
4614
133k
    xmlChar stop;
4615
4616
133k
    if (RAW == '"') {
4617
115k
        NEXT;
4618
115k
  stop = '"';
4619
115k
    } else if (RAW == '\'') {
4620
14.7k
        NEXT;
4621
14.7k
  stop = '\'';
4622
14.7k
    } else {
4623
3.54k
  xmlFatalErr(ctxt, XML_ERR_LITERAL_NOT_STARTED, NULL);
4624
3.54k
  return(NULL);
4625
3.54k
    }
4626
4627
130k
    buf = xmlMalloc(size);
4628
130k
    if (buf == NULL) {
4629
13
        xmlErrMemory(ctxt);
4630
13
  return(NULL);
4631
13
    }
4632
130k
    cur = xmlCurrentCharRecover(ctxt, &l);
4633
11.9M
    while ((IS_CHAR(cur)) && (cur != stop)) { /* checked */
4634
11.7M
  if (len + 5 >= size) {
4635
25.2k
      xmlChar *tmp;
4636
25.2k
            int newSize;
4637
4638
25.2k
            newSize = xmlGrowCapacity(size, 1, 1, maxLength);
4639
25.2k
            if (newSize < 0) {
4640
261
                xmlFatalErr(ctxt, XML_ERR_NAME_TOO_LONG, "SystemLiteral");
4641
261
                xmlFree(buf);
4642
261
                return(NULL);
4643
261
            }
4644
24.9k
      tmp = xmlRealloc(buf, newSize);
4645
24.9k
      if (tmp == NULL) {
4646
5
          xmlFree(buf);
4647
5
    xmlErrMemory(ctxt);
4648
5
    return(NULL);
4649
5
      }
4650
24.9k
      buf = tmp;
4651
24.9k
            size = newSize;
4652
24.9k
  }
4653
11.7M
  COPY_BUF(buf, len, cur);
4654
11.7M
  NEXTL(l);
4655
11.7M
  cur = xmlCurrentCharRecover(ctxt, &l);
4656
11.7M
    }
4657
129k
    buf[len] = 0;
4658
129k
    if (!IS_CHAR(cur)) {
4659
1.75k
  xmlFatalErr(ctxt, XML_ERR_LITERAL_NOT_FINISHED, NULL);
4660
128k
    } else {
4661
128k
  NEXT;
4662
128k
    }
4663
129k
    return(buf);
4664
130k
}
4665
4666
/**
4667
 * xmlParsePubidLiteral:
4668
 * @ctxt:  an XML parser context
4669
 *
4670
 * DEPRECATED: Internal function, don't use.
4671
 *
4672
 * parse an XML public literal
4673
 *
4674
 * [12] PubidLiteral ::= '"' PubidChar* '"' | "'" (PubidChar - "'")* "'"
4675
 *
4676
 * Returns the PubidLiteral parsed or NULL.
4677
 */
4678
4679
xmlChar *
4680
23.7k
xmlParsePubidLiteral(xmlParserCtxtPtr ctxt) {
4681
23.7k
    xmlChar *buf = NULL;
4682
23.7k
    int len = 0;
4683
23.7k
    int size = XML_PARSER_BUFFER_SIZE;
4684
23.7k
    int maxLength = (ctxt->options & XML_PARSE_HUGE) ?
4685
0
                    XML_MAX_TEXT_LENGTH :
4686
23.7k
                    XML_MAX_NAME_LENGTH;
4687
23.7k
    xmlChar cur;
4688
23.7k
    xmlChar stop;
4689
4690
23.7k
    if (RAW == '"') {
4691
5.72k
        NEXT;
4692
5.72k
  stop = '"';
4693
18.0k
    } else if (RAW == '\'') {
4694
17.1k
        NEXT;
4695
17.1k
  stop = '\'';
4696
17.1k
    } else {
4697
865
  xmlFatalErr(ctxt, XML_ERR_LITERAL_NOT_STARTED, NULL);
4698
865
  return(NULL);
4699
865
    }
4700
22.8k
    buf = xmlMalloc(size);
4701
22.8k
    if (buf == NULL) {
4702
5
  xmlErrMemory(ctxt);
4703
5
  return(NULL);
4704
5
    }
4705
22.8k
    cur = CUR;
4706
84.0M
    while ((IS_PUBIDCHAR_CH(cur)) && (cur != stop) &&
4707
84.0M
           (PARSER_STOPPED(ctxt) == 0)) { /* checked */
4708
84.0M
  if (len + 1 >= size) {
4709
29.2k
      xmlChar *tmp;
4710
29.2k
            int newSize;
4711
4712
29.2k
      newSize = xmlGrowCapacity(size, 1, 1, maxLength);
4713
29.2k
            if (newSize < 0) {
4714
1.24k
                xmlFatalErr(ctxt, XML_ERR_NAME_TOO_LONG, "Public ID");
4715
1.24k
                xmlFree(buf);
4716
1.24k
                return(NULL);
4717
1.24k
            }
4718
27.9k
      tmp = xmlRealloc(buf, newSize);
4719
27.9k
      if (tmp == NULL) {
4720
1
    xmlErrMemory(ctxt);
4721
1
    xmlFree(buf);
4722
1
    return(NULL);
4723
1
      }
4724
27.9k
      buf = tmp;
4725
27.9k
            size = newSize;
4726
27.9k
  }
4727
84.0M
  buf[len++] = cur;
4728
84.0M
  NEXT;
4729
84.0M
  cur = CUR;
4730
84.0M
    }
4731
21.6k
    buf[len] = 0;
4732
21.6k
    if (cur != stop) {
4733
1.19k
  xmlFatalErr(ctxt, XML_ERR_LITERAL_NOT_FINISHED, NULL);
4734
20.4k
    } else {
4735
20.4k
  NEXTL(1);
4736
20.4k
    }
4737
21.6k
    return(buf);
4738
22.8k
}
4739
4740
static void xmlParseCharDataComplex(xmlParserCtxtPtr ctxt, int partial);
4741
4742
/*
4743
 * used for the test in the inner loop of the char data testing
4744
 */
4745
static const unsigned char test_char_data[256] = {
4746
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
4747
    0x00, 0x09, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x9, CR/LF separated */
4748
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
4749
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
4750
    0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x00, 0x27, /* & */
4751
    0x28, 0x29, 0x2A, 0x2B, 0x2C, 0x2D, 0x2E, 0x2F,
4752
    0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37,
4753
    0x38, 0x39, 0x3A, 0x3B, 0x00, 0x3D, 0x3E, 0x3F, /* < */
4754
    0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47,
4755
    0x48, 0x49, 0x4A, 0x4B, 0x4C, 0x4D, 0x4E, 0x4F,
4756
    0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57,
4757
    0x58, 0x59, 0x5A, 0x5B, 0x5C, 0x00, 0x5E, 0x5F, /* ] */
4758
    0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67,
4759
    0x68, 0x69, 0x6A, 0x6B, 0x6C, 0x6D, 0x6E, 0x6F,
4760
    0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77,
4761
    0x78, 0x79, 0x7A, 0x7B, 0x7C, 0x7D, 0x7E, 0x7F,
4762
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* non-ascii */
4763
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
4764
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
4765
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
4766
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
4767
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
4768
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
4769
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
4770
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
4771
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
4772
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
4773
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
4774
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
4775
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
4776
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
4777
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
4778
};
4779
4780
static void
4781
xmlCharacters(xmlParserCtxtPtr ctxt, const xmlChar *buf, int size,
4782
11.1M
              int isBlank) {
4783
11.1M
    int checkBlanks;
4784
4785
11.1M
    if ((ctxt->sax == NULL) || (ctxt->disableSAX))
4786
7.16M
        return;
4787
4788
3.95M
    checkBlanks = (!ctxt->keepBlanks) ||
4789
3.95M
                  (ctxt->sax->ignorableWhitespace != ctxt->sax->characters);
4790
4791
    /*
4792
     * Calling areBlanks with only parts of a text node
4793
     * is fundamentally broken, making the NOBLANKS option
4794
     * essentially unusable.
4795
     */
4796
3.95M
    if ((checkBlanks) &&
4797
0
        (areBlanks(ctxt, buf, size, isBlank))) {
4798
0
        if ((ctxt->sax->ignorableWhitespace != NULL) &&
4799
0
            (ctxt->keepBlanks))
4800
0
            ctxt->sax->ignorableWhitespace(ctxt->userData, buf, size);
4801
3.95M
    } else {
4802
3.95M
        if (ctxt->sax->characters != NULL)
4803
3.95M
            ctxt->sax->characters(ctxt->userData, buf, size);
4804
4805
        /*
4806
         * The old code used to update this value for "complex" data
4807
         * even if checkBlanks was false. This was probably a bug.
4808
         */
4809
3.95M
        if ((checkBlanks) && (*ctxt->space == -1))
4810
0
            *ctxt->space = -2;
4811
3.95M
    }
4812
3.95M
}
4813
4814
/**
4815
 * xmlParseCharDataInternal:
4816
 * @ctxt:  an XML parser context
4817
 * @partial:  buffer may contain partial UTF-8 sequences
4818
 *
4819
 * Parse character data. Always makes progress if the first char isn't
4820
 * '<' or '&'.
4821
 *
4822
 * The right angle bracket (>) may be represented using the string "&gt;",
4823
 * and must, for compatibility, be escaped using "&gt;" or a character
4824
 * reference when it appears in the string "]]>" in content, when that
4825
 * string is not marking the end of a CDATA section.
4826
 *
4827
 * [14] CharData ::= [^<&]* - ([^<&]* ']]>' [^<&]*)
4828
 */
4829
static void
4830
13.1M
xmlParseCharDataInternal(xmlParserCtxtPtr ctxt, int partial) {
4831
13.1M
    const xmlChar *in;
4832
13.1M
    int nbchar = 0;
4833
13.1M
    int line = ctxt->input->line;
4834
13.1M
    int col = ctxt->input->col;
4835
13.1M
    int ccol;
4836
4837
13.1M
    GROW;
4838
    /*
4839
     * Accelerated common case where input don't need to be
4840
     * modified before passing it to the handler.
4841
     */
4842
13.1M
    in = ctxt->input->cur;
4843
13.1M
    do {
4844
14.7M
get_more_space:
4845
18.4M
        while (*in == 0x20) { in++; ctxt->input->col++; }
4846
14.7M
        if (*in == 0xA) {
4847
37.1M
            do {
4848
37.1M
                ctxt->input->line++; ctxt->input->col = 1;
4849
37.1M
                in++;
4850
37.1M
            } while (*in == 0xA);
4851
1.54M
            goto get_more_space;
4852
1.54M
        }
4853
13.1M
        if (*in == '<') {
4854
2.10M
            nbchar = in - ctxt->input->cur;
4855
2.10M
            if (nbchar > 0) {
4856
2.10M
                const xmlChar *tmp = ctxt->input->cur;
4857
2.10M
                ctxt->input->cur = in;
4858
4859
2.10M
                xmlCharacters(ctxt, tmp, nbchar, 1);
4860
2.10M
            }
4861
2.10M
            return;
4862
2.10M
        }
4863
4864
11.5M
get_more:
4865
11.5M
        ccol = ctxt->input->col;
4866
96.0M
        while (test_char_data[*in]) {
4867
84.5M
            in++;
4868
84.5M
            ccol++;
4869
84.5M
        }
4870
11.5M
        ctxt->input->col = ccol;
4871
11.5M
        if (*in == 0xA) {
4872
21.0M
            do {
4873
21.0M
                ctxt->input->line++; ctxt->input->col = 1;
4874
21.0M
                in++;
4875
21.0M
            } while (*in == 0xA);
4876
380k
            goto get_more;
4877
380k
        }
4878
11.1M
        if (*in == ']') {
4879
103k
            if ((in[1] == ']') && (in[2] == '>')) {
4880
3.19k
                xmlFatalErr(ctxt, XML_ERR_MISPLACED_CDATA_END, NULL);
4881
3.19k
                ctxt->input->cur = in + 1;
4882
3.19k
                return;
4883
3.19k
            }
4884
100k
            if ((!partial) || (ctxt->input->end - in >= 2)) {
4885
100k
                in++;
4886
100k
                ctxt->input->col++;
4887
100k
                goto get_more;
4888
100k
            }
4889
100k
        }
4890
11.0M
        nbchar = in - ctxt->input->cur;
4891
11.0M
        if (nbchar > 0) {
4892
3.25M
            const xmlChar *tmp = ctxt->input->cur;
4893
3.25M
            ctxt->input->cur = in;
4894
4895
3.25M
            xmlCharacters(ctxt, tmp, nbchar, 0);
4896
4897
3.25M
            line = ctxt->input->line;
4898
3.25M
            col = ctxt->input->col;
4899
3.25M
        }
4900
11.0M
        ctxt->input->cur = in;
4901
11.0M
        if (*in == 0xD) {
4902
106k
            in++;
4903
106k
            if (*in == 0xA) {
4904
61.0k
                ctxt->input->cur = in;
4905
61.0k
                in++;
4906
61.0k
                ctxt->input->line++; ctxt->input->col = 1;
4907
61.0k
                continue; /* while */
4908
61.0k
            }
4909
45.7k
            in--;
4910
45.7k
        }
4911
11.0M
        if (*in == '<') {
4912
912k
            return;
4913
912k
        }
4914
10.0M
        if (*in == '&') {
4915
99.7k
            return;
4916
99.7k
        }
4917
9.99M
        if ((partial) && (*in == ']') && (ctxt->input->end - in < 2)) {
4918
0
            return;
4919
0
        }
4920
9.99M
        SHRINK;
4921
9.99M
        GROW;
4922
9.99M
        in = ctxt->input->cur;
4923
10.0M
    } while (((*in >= 0x20) && (*in <= 0x7F)) ||
4924
10.0M
             (*in == 0x09) || (*in == 0x0a));
4925
9.99M
    ctxt->input->line = line;
4926
9.99M
    ctxt->input->col = col;
4927
9.99M
    xmlParseCharDataComplex(ctxt, partial);
4928
9.99M
}
4929
4930
/**
4931
 * xmlParseCharDataComplex:
4932
 * @ctxt:  an XML parser context
4933
 * @cdata:  int indicating whether we are within a CDATA section
4934
 *
4935
 * Always makes progress if the first char isn't '<' or '&'.
4936
 *
4937
 * parse a CharData section.this is the fallback function
4938
 * of xmlParseCharData() when the parsing requires handling
4939
 * of non-ASCII characters.
4940
 */
4941
static void
4942
9.99M
xmlParseCharDataComplex(xmlParserCtxtPtr ctxt, int partial) {
4943
9.99M
    xmlChar buf[XML_PARSER_BIG_BUFFER_SIZE + 5];
4944
9.99M
    int nbchar = 0;
4945
9.99M
    int cur, l;
4946
4947
9.99M
    cur = xmlCurrentCharRecover(ctxt, &l);
4948
266M
    while ((cur != '<') && /* checked */
4949
266M
           (cur != '&') &&
4950
265M
           ((!partial) || (cur != ']') ||
4951
0
            (ctxt->input->end - ctxt->input->cur >= 2)) &&
4952
265M
     (IS_CHAR(cur))) {
4953
256M
  if ((cur == ']') && (NXT(1) == ']') && (NXT(2) == '>')) {
4954
4.99k
      xmlFatalErr(ctxt, XML_ERR_MISPLACED_CDATA_END, NULL);
4955
4.99k
  }
4956
256M
  COPY_BUF(buf, nbchar, cur);
4957
  /* move current position before possible calling of ctxt->sax->characters */
4958
256M
  NEXTL(l);
4959
256M
  if (nbchar >= XML_PARSER_BIG_BUFFER_SIZE) {
4960
1.12M
      buf[nbchar] = 0;
4961
4962
1.12M
            xmlCharacters(ctxt, buf, nbchar, 0);
4963
1.12M
      nbchar = 0;
4964
1.12M
            SHRINK;
4965
1.12M
  }
4966
256M
  cur = xmlCurrentCharRecover(ctxt, &l);
4967
256M
    }
4968
9.99M
    if (nbchar != 0) {
4969
4.63M
        buf[nbchar] = 0;
4970
4971
4.63M
        xmlCharacters(ctxt, buf, nbchar, 0);
4972
4.63M
    }
4973
    /*
4974
     * cur == 0 can mean
4975
     *
4976
     * - End of buffer.
4977
     * - An actual 0 character.
4978
     * - An incomplete UTF-8 sequence. This is allowed if partial is set.
4979
     */
4980
9.99M
    if (ctxt->input->cur < ctxt->input->end) {
4981
9.96M
        if ((cur == 0) && (CUR != 0)) {
4982
4.06k
            if (partial == 0) {
4983
4.06k
                xmlFatalErrMsgInt(ctxt, XML_ERR_INVALID_CHAR,
4984
4.06k
                        "Incomplete UTF-8 sequence starting with %02X\n", CUR);
4985
4.06k
                NEXTL(1);
4986
4.06k
            }
4987
9.95M
        } else if ((cur != '<') && (cur != '&') && (cur != ']')) {
4988
            /* Generate the error and skip the offending character */
4989
9.21M
            xmlFatalErrMsgInt(ctxt, XML_ERR_INVALID_CHAR,
4990
9.21M
                              "PCDATA invalid Char value %d\n", cur);
4991
9.21M
            NEXTL(l);
4992
9.21M
        }
4993
9.96M
    }
4994
9.99M
}
4995
4996
/**
4997
 * xmlParseCharData:
4998
 * @ctxt:  an XML parser context
4999
 * @cdata:  unused
5000
 *
5001
 * DEPRECATED: Internal function, don't use.
5002
 */
5003
void
5004
0
xmlParseCharData(xmlParserCtxtPtr ctxt, ATTRIBUTE_UNUSED int cdata) {
5005
0
    xmlParseCharDataInternal(ctxt, 0);
5006
0
}
5007
5008
/**
5009
 * xmlParseExternalID:
5010
 * @ctxt:  an XML parser context
5011
 * @publicID:  a xmlChar** receiving PubidLiteral
5012
 * @strict: indicate whether we should restrict parsing to only
5013
 *          production [75], see NOTE below
5014
 *
5015
 * DEPRECATED: Internal function, don't use.
5016
 *
5017
 * Parse an External ID or a Public ID
5018
 *
5019
 * NOTE: Productions [75] and [83] interact badly since [75] can generate
5020
 *       'PUBLIC' S PubidLiteral S SystemLiteral
5021
 *
5022
 * [75] ExternalID ::= 'SYSTEM' S SystemLiteral
5023
 *                   | 'PUBLIC' S PubidLiteral S SystemLiteral
5024
 *
5025
 * [83] PublicID ::= 'PUBLIC' S PubidLiteral
5026
 *
5027
 * Returns the function returns SystemLiteral and in the second
5028
 *                case publicID receives PubidLiteral, is strict is off
5029
 *                it is possible to return NULL and have publicID set.
5030
 */
5031
5032
xmlChar *
5033
270k
xmlParseExternalID(xmlParserCtxtPtr ctxt, xmlChar **publicID, int strict) {
5034
270k
    xmlChar *URI = NULL;
5035
5036
270k
    *publicID = NULL;
5037
270k
    if (CMP6(CUR_PTR, 'S', 'Y', 'S', 'T', 'E', 'M')) {
5038
111k
        SKIP(6);
5039
111k
  if (SKIP_BLANKS == 0) {
5040
621
      xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED,
5041
621
                     "Space required after 'SYSTEM'\n");
5042
621
  }
5043
111k
  URI = xmlParseSystemLiteral(ctxt);
5044
111k
  if (URI == NULL) {
5045
551
      xmlFatalErr(ctxt, XML_ERR_URI_REQUIRED, NULL);
5046
551
        }
5047
158k
    } else if (CMP6(CUR_PTR, 'P', 'U', 'B', 'L', 'I', 'C')) {
5048
23.7k
        SKIP(6);
5049
23.7k
  if (SKIP_BLANKS == 0) {
5050
495
      xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED,
5051
495
        "Space required after 'PUBLIC'\n");
5052
495
  }
5053
23.7k
  *publicID = xmlParsePubidLiteral(ctxt);
5054
23.7k
  if (*publicID == NULL) {
5055
2.11k
      xmlFatalErr(ctxt, XML_ERR_PUBID_REQUIRED, NULL);
5056
2.11k
  }
5057
23.7k
  if (strict) {
5058
      /*
5059
       * We don't handle [83] so "S SystemLiteral" is required.
5060
       */
5061
20.5k
      if (SKIP_BLANKS == 0) {
5062
3.39k
    xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED,
5063
3.39k
      "Space required after the Public Identifier\n");
5064
3.39k
      }
5065
20.5k
  } else {
5066
      /*
5067
       * We handle [83] so we return immediately, if
5068
       * "S SystemLiteral" is not detected. We skip blanks if no
5069
             * system literal was found, but this is harmless since we must
5070
             * be at the end of a NotationDecl.
5071
       */
5072
3.24k
      if (SKIP_BLANKS == 0) return(NULL);
5073
1.99k
      if ((CUR != '\'') && (CUR != '"')) return(NULL);
5074
1.99k
  }
5075
22.2k
  URI = xmlParseSystemLiteral(ctxt);
5076
22.2k
  if (URI == NULL) {
5077
3.26k
      xmlFatalErr(ctxt, XML_ERR_URI_REQUIRED, NULL);
5078
3.26k
        }
5079
22.2k
    }
5080
268k
    return(URI);
5081
270k
}
5082
5083
/**
5084
 * xmlParseCommentComplex:
5085
 * @ctxt:  an XML parser context
5086
 * @buf:  the already parsed part of the buffer
5087
 * @len:  number of bytes in the buffer
5088
 * @size:  allocated size of the buffer
5089
 *
5090
 * Skip an XML (SGML) comment <!-- .... -->
5091
 *  The spec says that "For compatibility, the string "--" (double-hyphen)
5092
 *  must not occur within comments. "
5093
 * This is the slow routine in case the accelerator for ascii didn't work
5094
 *
5095
 * [15] Comment ::= '<!--' ((Char - '-') | ('-' (Char - '-')))* '-->'
5096
 */
5097
static void
5098
xmlParseCommentComplex(xmlParserCtxtPtr ctxt, xmlChar *buf,
5099
52.0k
                       size_t len, size_t size) {
5100
52.0k
    int q, ql;
5101
52.0k
    int r, rl;
5102
52.0k
    int cur, l;
5103
52.0k
    int maxLength = (ctxt->options & XML_PARSE_HUGE) ?
5104
0
                    XML_MAX_HUGE_LENGTH :
5105
52.0k
                    XML_MAX_TEXT_LENGTH;
5106
5107
52.0k
    if (buf == NULL) {
5108
4.43k
        len = 0;
5109
4.43k
  size = XML_PARSER_BUFFER_SIZE;
5110
4.43k
  buf = xmlMalloc(size);
5111
4.43k
  if (buf == NULL) {
5112
2
      xmlErrMemory(ctxt);
5113
2
      return;
5114
2
  }
5115
4.43k
    }
5116
52.0k
    q = xmlCurrentCharRecover(ctxt, &ql);
5117
52.0k
    if (q == 0)
5118
2.26k
        goto not_terminated;
5119
49.7k
    if (!IS_CHAR(q)) {
5120
6.55k
        xmlFatalErrMsgInt(ctxt, XML_ERR_INVALID_CHAR,
5121
6.55k
                          "xmlParseComment: invalid xmlChar value %d\n",
5122
6.55k
                    q);
5123
6.55k
  xmlFree (buf);
5124
6.55k
  return;
5125
6.55k
    }
5126
43.2k
    NEXTL(ql);
5127
43.2k
    r = xmlCurrentCharRecover(ctxt, &rl);
5128
43.2k
    if (r == 0)
5129
751
        goto not_terminated;
5130
42.4k
    if (!IS_CHAR(r)) {
5131
859
        xmlFatalErrMsgInt(ctxt, XML_ERR_INVALID_CHAR,
5132
859
                          "xmlParseComment: invalid xmlChar value %d\n",
5133
859
                    r);
5134
859
  xmlFree (buf);
5135
859
  return;
5136
859
    }
5137
41.6k
    NEXTL(rl);
5138
41.6k
    cur = xmlCurrentCharRecover(ctxt, &l);
5139
41.6k
    if (cur == 0)
5140
1.13k
        goto not_terminated;
5141
29.4M
    while (IS_CHAR(cur) && /* checked */
5142
29.4M
           ((cur != '>') ||
5143
29.4M
      (r != '-') || (q != '-'))) {
5144
29.4M
  if ((r == '-') && (q == '-')) {
5145
6.74k
      xmlFatalErr(ctxt, XML_ERR_HYPHEN_IN_COMMENT, NULL);
5146
6.74k
  }
5147
29.4M
  if (len + 5 >= size) {
5148
14.3k
      xmlChar *tmp;
5149
14.3k
            int newSize;
5150
5151
14.3k
      newSize = xmlGrowCapacity(size, 1, 1, maxLength);
5152
14.3k
            if (newSize < 0) {
5153
0
                xmlFatalErrMsgStr(ctxt, XML_ERR_COMMENT_NOT_FINISHED,
5154
0
                             "Comment too big found", NULL);
5155
0
                xmlFree (buf);
5156
0
                return;
5157
0
            }
5158
14.3k
      tmp = xmlRealloc(buf, newSize);
5159
14.3k
      if (tmp == NULL) {
5160
3
    xmlErrMemory(ctxt);
5161
3
    xmlFree(buf);
5162
3
    return;
5163
3
      }
5164
14.3k
      buf = tmp;
5165
14.3k
            size = newSize;
5166
14.3k
  }
5167
29.4M
  COPY_BUF(buf, len, q);
5168
5169
29.4M
  q = r;
5170
29.4M
  ql = rl;
5171
29.4M
  r = cur;
5172
29.4M
  rl = l;
5173
5174
29.4M
  NEXTL(l);
5175
29.4M
  cur = xmlCurrentCharRecover(ctxt, &l);
5176
5177
29.4M
    }
5178
40.4k
    buf[len] = 0;
5179
40.4k
    if (cur == 0) {
5180
6.39k
  xmlFatalErrMsgStr(ctxt, XML_ERR_COMMENT_NOT_FINISHED,
5181
6.39k
                       "Comment not terminated \n<!--%.50s\n", buf);
5182
34.0k
    } else if (!IS_CHAR(cur)) {
5183
3.19k
        xmlFatalErrMsgInt(ctxt, XML_ERR_INVALID_CHAR,
5184
3.19k
                          "xmlParseComment: invalid xmlChar value %d\n",
5185
3.19k
                    cur);
5186
30.8k
    } else {
5187
30.8k
        NEXT;
5188
30.8k
  if ((ctxt->sax != NULL) && (ctxt->sax->comment != NULL) &&
5189
30.8k
      (!ctxt->disableSAX))
5190
22.8k
      ctxt->sax->comment(ctxt->userData, buf);
5191
30.8k
    }
5192
40.4k
    xmlFree(buf);
5193
40.4k
    return;
5194
4.15k
not_terminated:
5195
4.15k
    xmlFatalErrMsgStr(ctxt, XML_ERR_COMMENT_NOT_FINISHED,
5196
4.15k
       "Comment not terminated\n", NULL);
5197
4.15k
    xmlFree(buf);
5198
4.15k
}
5199
5200
/**
5201
 * xmlParseComment:
5202
 * @ctxt:  an XML parser context
5203
 *
5204
 * DEPRECATED: Internal function, don't use.
5205
 *
5206
 * Parse an XML (SGML) comment. Always consumes '<!'.
5207
 *
5208
 *  The spec says that "For compatibility, the string "--" (double-hyphen)
5209
 *  must not occur within comments. "
5210
 *
5211
 * [15] Comment ::= '<!--' ((Char - '-') | ('-' (Char - '-')))* '-->'
5212
 */
5213
void
5214
131k
xmlParseComment(xmlParserCtxtPtr ctxt) {
5215
131k
    xmlChar *buf = NULL;
5216
131k
    size_t size = XML_PARSER_BUFFER_SIZE;
5217
131k
    size_t len = 0;
5218
131k
    size_t maxLength = (ctxt->options & XML_PARSE_HUGE) ?
5219
0
                       XML_MAX_HUGE_LENGTH :
5220
131k
                       XML_MAX_TEXT_LENGTH;
5221
131k
    const xmlChar *in;
5222
131k
    size_t nbchar = 0;
5223
131k
    int ccol;
5224
5225
    /*
5226
     * Check that there is a comment right here.
5227
     */
5228
131k
    if ((RAW != '<') || (NXT(1) != '!'))
5229
0
        return;
5230
131k
    SKIP(2);
5231
131k
    if ((RAW != '-') || (NXT(1) != '-'))
5232
421
        return;
5233
131k
    SKIP(2);
5234
131k
    GROW;
5235
5236
    /*
5237
     * Accelerated common case where input don't need to be
5238
     * modified before passing it to the handler.
5239
     */
5240
131k
    in = ctxt->input->cur;
5241
131k
    do {
5242
131k
  if (*in == 0xA) {
5243
147k
      do {
5244
147k
    ctxt->input->line++; ctxt->input->col = 1;
5245
147k
    in++;
5246
147k
      } while (*in == 0xA);
5247
12.8k
  }
5248
292k
get_more:
5249
292k
        ccol = ctxt->input->col;
5250
5.97M
  while (((*in > '-') && (*in <= 0x7F)) ||
5251
1.43M
         ((*in >= 0x20) && (*in < '-')) ||
5252
5.67M
         (*in == 0x09)) {
5253
5.67M
        in++;
5254
5.67M
        ccol++;
5255
5.67M
  }
5256
292k
  ctxt->input->col = ccol;
5257
292k
  if (*in == 0xA) {
5258
499k
      do {
5259
499k
    ctxt->input->line++; ctxt->input->col = 1;
5260
499k
    in++;
5261
499k
      } while (*in == 0xA);
5262
40.9k
      goto get_more;
5263
40.9k
  }
5264
251k
  nbchar = in - ctxt->input->cur;
5265
  /*
5266
   * save current set of data
5267
   */
5268
251k
  if (nbchar > 0) {
5269
234k
            if (nbchar > maxLength - len) {
5270
0
                xmlFatalErrMsgStr(ctxt, XML_ERR_COMMENT_NOT_FINISHED,
5271
0
                                  "Comment too big found", NULL);
5272
0
                xmlFree(buf);
5273
0
                return;
5274
0
            }
5275
234k
            if (buf == NULL) {
5276
126k
                if ((*in == '-') && (in[1] == '-'))
5277
54.9k
                    size = nbchar + 1;
5278
71.3k
                else
5279
71.3k
                    size = XML_PARSER_BUFFER_SIZE + nbchar;
5280
126k
                buf = xmlMalloc(size);
5281
126k
                if (buf == NULL) {
5282
5
                    xmlErrMemory(ctxt);
5283
5
                    return;
5284
5
                }
5285
126k
                len = 0;
5286
126k
            } else if (len + nbchar + 1 >= size) {
5287
14.6k
                xmlChar *new_buf;
5288
14.6k
                size += len + nbchar + XML_PARSER_BUFFER_SIZE;
5289
14.6k
                new_buf = xmlRealloc(buf, size);
5290
14.6k
                if (new_buf == NULL) {
5291
2
                    xmlErrMemory(ctxt);
5292
2
                    xmlFree(buf);
5293
2
                    return;
5294
2
                }
5295
14.6k
                buf = new_buf;
5296
14.6k
            }
5297
234k
            memcpy(&buf[len], ctxt->input->cur, nbchar);
5298
234k
            len += nbchar;
5299
234k
            buf[len] = 0;
5300
234k
  }
5301
251k
  ctxt->input->cur = in;
5302
251k
  if (*in == 0xA) {
5303
0
      in++;
5304
0
      ctxt->input->line++; ctxt->input->col = 1;
5305
0
  }
5306
251k
  if (*in == 0xD) {
5307
49.3k
      in++;
5308
49.3k
      if (*in == 0xA) {
5309
42.3k
    ctxt->input->cur = in;
5310
42.3k
    in++;
5311
42.3k
    ctxt->input->line++; ctxt->input->col = 1;
5312
42.3k
    goto get_more;
5313
42.3k
      }
5314
7.00k
      in--;
5315
7.00k
  }
5316
209k
  SHRINK;
5317
209k
  GROW;
5318
209k
  in = ctxt->input->cur;
5319
209k
  if (*in == '-') {
5320
156k
      if (in[1] == '-') {
5321
95.5k
          if (in[2] == '>') {
5322
79.3k
        SKIP(3);
5323
79.3k
        if ((ctxt->sax != NULL) && (ctxt->sax->comment != NULL) &&
5324
79.3k
            (!ctxt->disableSAX)) {
5325
59.3k
      if (buf != NULL)
5326
59.0k
          ctxt->sax->comment(ctxt->userData, buf);
5327
374
      else
5328
374
          ctxt->sax->comment(ctxt->userData, BAD_CAST "");
5329
59.3k
        }
5330
79.3k
        if (buf != NULL)
5331
78.6k
            xmlFree(buf);
5332
79.3k
        return;
5333
79.3k
    }
5334
16.2k
    if (buf != NULL) {
5335
13.5k
        xmlFatalErrMsgStr(ctxt, XML_ERR_HYPHEN_IN_COMMENT,
5336
13.5k
                          "Double hyphen within comment: "
5337
13.5k
                                      "<!--%.50s\n",
5338
13.5k
              buf);
5339
13.5k
    } else
5340
2.64k
        xmlFatalErrMsgStr(ctxt, XML_ERR_HYPHEN_IN_COMMENT,
5341
2.64k
                          "Double hyphen within comment\n", NULL);
5342
16.2k
    in++;
5343
16.2k
    ctxt->input->col++;
5344
16.2k
      }
5345
77.4k
      in++;
5346
77.4k
      ctxt->input->col++;
5347
77.4k
      goto get_more;
5348
156k
  }
5349
209k
    } while (((*in >= 0x20) && (*in <= 0x7F)) || (*in == 0x09) || (*in == 0x0a));
5350
52.0k
    xmlParseCommentComplex(ctxt, buf, len, size);
5351
52.0k
}
5352
5353
5354
/**
5355
 * xmlParsePITarget:
5356
 * @ctxt:  an XML parser context
5357
 *
5358
 * DEPRECATED: Internal function, don't use.
5359
 *
5360
 * parse the name of a PI
5361
 *
5362
 * [17] PITarget ::= Name - (('X' | 'x') ('M' | 'm') ('L' | 'l'))
5363
 *
5364
 * Returns the PITarget name or NULL
5365
 */
5366
5367
const xmlChar *
5368
132k
xmlParsePITarget(xmlParserCtxtPtr ctxt) {
5369
132k
    const xmlChar *name;
5370
5371
132k
    name = xmlParseName(ctxt);
5372
132k
    if ((name != NULL) &&
5373
121k
        ((name[0] == 'x') || (name[0] == 'X')) &&
5374
62.3k
        ((name[1] == 'm') || (name[1] == 'M')) &&
5375
28.8k
        ((name[2] == 'l') || (name[2] == 'L'))) {
5376
6.10k
  int i;
5377
6.10k
  if ((name[0] == 'x') && (name[1] == 'm') &&
5378
4.55k
      (name[2] == 'l') && (name[3] == 0)) {
5379
2.77k
      xmlFatalErrMsg(ctxt, XML_ERR_RESERVED_XML_NAME,
5380
2.77k
     "XML declaration allowed only at the start of the document\n");
5381
2.77k
      return(name);
5382
3.33k
  } else if (name[3] == 0) {
5383
563
      xmlFatalErr(ctxt, XML_ERR_RESERVED_XML_NAME, NULL);
5384
563
      return(name);
5385
563
  }
5386
7.77k
  for (i = 0;;i++) {
5387
7.77k
      if (xmlW3CPIs[i] == NULL) break;
5388
5.28k
      if (xmlStrEqual(name, (const xmlChar *)xmlW3CPIs[i]))
5389
274
          return(name);
5390
5.28k
  }
5391
2.49k
  xmlWarningMsg(ctxt, XML_ERR_RESERVED_XML_NAME,
5392
2.49k
          "xmlParsePITarget: invalid name prefix 'xml'\n",
5393
2.49k
          NULL, NULL);
5394
2.49k
    }
5395
129k
    if ((name != NULL) && (xmlStrchr(name, ':') != NULL)) {
5396
982
  xmlNsErr(ctxt, XML_NS_ERR_COLON,
5397
982
     "colons are forbidden from PI names '%s'\n", name, NULL, NULL);
5398
982
    }
5399
129k
    return(name);
5400
132k
}
5401
5402
#ifdef LIBXML_CATALOG_ENABLED
5403
/**
5404
 * xmlParseCatalogPI:
5405
 * @ctxt:  an XML parser context
5406
 * @catalog:  the PI value string
5407
 *
5408
 * parse an XML Catalog Processing Instruction.
5409
 *
5410
 * <?oasis-xml-catalog catalog="http://example.com/catalog.xml"?>
5411
 *
5412
 * Occurs only if allowed by the user and if happening in the Misc
5413
 * part of the document before any doctype information
5414
 * This will add the given catalog to the parsing context in order
5415
 * to be used if there is a resolution need further down in the document
5416
 */
5417
5418
static void
5419
0
xmlParseCatalogPI(xmlParserCtxtPtr ctxt, const xmlChar *catalog) {
5420
0
    xmlChar *URL = NULL;
5421
0
    const xmlChar *tmp, *base;
5422
0
    xmlChar marker;
5423
5424
0
    tmp = catalog;
5425
0
    while (IS_BLANK_CH(*tmp)) tmp++;
5426
0
    if (xmlStrncmp(tmp, BAD_CAST"catalog", 7))
5427
0
  goto error;
5428
0
    tmp += 7;
5429
0
    while (IS_BLANK_CH(*tmp)) tmp++;
5430
0
    if (*tmp != '=') {
5431
0
  return;
5432
0
    }
5433
0
    tmp++;
5434
0
    while (IS_BLANK_CH(*tmp)) tmp++;
5435
0
    marker = *tmp;
5436
0
    if ((marker != '\'') && (marker != '"'))
5437
0
  goto error;
5438
0
    tmp++;
5439
0
    base = tmp;
5440
0
    while ((*tmp != 0) && (*tmp != marker)) tmp++;
5441
0
    if (*tmp == 0)
5442
0
  goto error;
5443
0
    URL = xmlStrndup(base, tmp - base);
5444
0
    tmp++;
5445
0
    while (IS_BLANK_CH(*tmp)) tmp++;
5446
0
    if (*tmp != 0)
5447
0
  goto error;
5448
5449
0
    if (URL != NULL) {
5450
        /*
5451
         * Unfortunately, the catalog API doesn't report OOM errors.
5452
         * xmlGetLastError isn't very helpful since we don't know
5453
         * where the last error came from. We'd have to reset it
5454
         * before this call and restore it afterwards.
5455
         */
5456
0
  ctxt->catalogs = xmlCatalogAddLocal(ctxt->catalogs, URL);
5457
0
  xmlFree(URL);
5458
0
    }
5459
0
    return;
5460
5461
0
error:
5462
0
    xmlWarningMsg(ctxt, XML_WAR_CATALOG_PI,
5463
0
            "Catalog PI syntax error: %s\n",
5464
0
      catalog, NULL);
5465
0
    if (URL != NULL)
5466
0
  xmlFree(URL);
5467
0
}
5468
#endif
5469
5470
/**
5471
 * xmlParsePI:
5472
 * @ctxt:  an XML parser context
5473
 *
5474
 * DEPRECATED: Internal function, don't use.
5475
 *
5476
 * parse an XML Processing Instruction.
5477
 *
5478
 * [16] PI ::= '<?' PITarget (S (Char* - (Char* '?>' Char*)))? '?>'
5479
 *
5480
 * The processing is transferred to SAX once parsed.
5481
 */
5482
5483
void
5484
132k
xmlParsePI(xmlParserCtxtPtr ctxt) {
5485
132k
    xmlChar *buf = NULL;
5486
132k
    size_t len = 0;
5487
132k
    size_t size = XML_PARSER_BUFFER_SIZE;
5488
132k
    size_t maxLength = (ctxt->options & XML_PARSE_HUGE) ?
5489
0
                       XML_MAX_HUGE_LENGTH :
5490
132k
                       XML_MAX_TEXT_LENGTH;
5491
132k
    int cur, l;
5492
132k
    const xmlChar *target;
5493
5494
132k
    if ((RAW == '<') && (NXT(1) == '?')) {
5495
  /*
5496
   * this is a Processing Instruction.
5497
   */
5498
132k
  SKIP(2);
5499
5500
  /*
5501
   * Parse the target name and check for special support like
5502
   * namespace.
5503
   */
5504
132k
        target = xmlParsePITarget(ctxt);
5505
132k
  if (target != NULL) {
5506
121k
      if ((RAW == '?') && (NXT(1) == '>')) {
5507
46.3k
    SKIP(2);
5508
5509
    /*
5510
     * SAX: PI detected.
5511
     */
5512
46.3k
    if ((ctxt->sax) && (!ctxt->disableSAX) &&
5513
38.1k
        (ctxt->sax->processingInstruction != NULL))
5514
38.1k
        ctxt->sax->processingInstruction(ctxt->userData,
5515
38.1k
                                         target, NULL);
5516
46.3k
    return;
5517
46.3k
      }
5518
75.4k
      buf = xmlMalloc(size);
5519
75.4k
      if (buf == NULL) {
5520
8
    xmlErrMemory(ctxt);
5521
8
    return;
5522
8
      }
5523
75.4k
      if (SKIP_BLANKS == 0) {
5524
16.3k
    xmlFatalErrMsgStr(ctxt, XML_ERR_SPACE_REQUIRED,
5525
16.3k
        "ParsePI: PI %s space expected\n", target);
5526
16.3k
      }
5527
75.4k
      cur = xmlCurrentCharRecover(ctxt, &l);
5528
22.1M
      while (IS_CHAR(cur) && /* checked */
5529
22.1M
       ((cur != '?') || (NXT(1) != '>'))) {
5530
22.0M
    if (len + 5 >= size) {
5531
15.4k
        xmlChar *tmp;
5532
15.4k
                    int newSize;
5533
5534
15.4k
                    newSize = xmlGrowCapacity(size, 1, 1, maxLength);
5535
15.4k
                    if (newSize < 0) {
5536
0
                        xmlFatalErrMsgStr(ctxt, XML_ERR_PI_NOT_FINISHED,
5537
0
                                          "PI %s too big found", target);
5538
0
                        xmlFree(buf);
5539
0
                        return;
5540
0
                    }
5541
15.4k
        tmp = xmlRealloc(buf, newSize);
5542
15.4k
        if (tmp == NULL) {
5543
4
      xmlErrMemory(ctxt);
5544
4
      xmlFree(buf);
5545
4
      return;
5546
4
        }
5547
15.4k
        buf = tmp;
5548
15.4k
                    size = newSize;
5549
15.4k
    }
5550
22.0M
    COPY_BUF(buf, len, cur);
5551
22.0M
    NEXTL(l);
5552
22.0M
    cur = xmlCurrentCharRecover(ctxt, &l);
5553
22.0M
      }
5554
75.4k
      buf[len] = 0;
5555
75.4k
      if (cur != '?') {
5556
14.4k
    xmlFatalErrMsgStr(ctxt, XML_ERR_PI_NOT_FINISHED,
5557
14.4k
          "ParsePI: PI %s never end ...\n", target);
5558
61.0k
      } else {
5559
61.0k
    SKIP(2);
5560
5561
61.0k
#ifdef LIBXML_CATALOG_ENABLED
5562
61.0k
    if ((ctxt->inSubset == 0) &&
5563
56.2k
        (xmlStrEqual(target, XML_CATALOG_PI))) {
5564
348
        xmlCatalogAllow allow = xmlCatalogGetDefaults();
5565
5566
348
        if ((ctxt->options & XML_PARSE_CATALOG_PI) &&
5567
0
                        ((allow == XML_CATA_ALLOW_DOCUMENT) ||
5568
0
       (allow == XML_CATA_ALLOW_ALL)))
5569
0
      xmlParseCatalogPI(ctxt, buf);
5570
348
    }
5571
61.0k
#endif
5572
5573
    /*
5574
     * SAX: PI detected.
5575
     */
5576
61.0k
    if ((ctxt->sax) && (!ctxt->disableSAX) &&
5577
52.9k
        (ctxt->sax->processingInstruction != NULL))
5578
52.9k
        ctxt->sax->processingInstruction(ctxt->userData,
5579
52.9k
                                         target, buf);
5580
61.0k
      }
5581
75.4k
      xmlFree(buf);
5582
75.4k
  } else {
5583
10.8k
      xmlFatalErr(ctxt, XML_ERR_PI_NOT_STARTED, NULL);
5584
10.8k
  }
5585
132k
    }
5586
132k
}
5587
5588
/**
5589
 * xmlParseNotationDecl:
5590
 * @ctxt:  an XML parser context
5591
 *
5592
 * DEPRECATED: Internal function, don't use.
5593
 *
5594
 * Parse a notation declaration. Always consumes '<!'.
5595
 *
5596
 * [82] NotationDecl ::= '<!NOTATION' S Name S (ExternalID |  PublicID) S? '>'
5597
 *
5598
 * Hence there is actually 3 choices:
5599
 *     'PUBLIC' S PubidLiteral
5600
 *     'PUBLIC' S PubidLiteral S SystemLiteral
5601
 * and 'SYSTEM' S SystemLiteral
5602
 *
5603
 * See the NOTE on xmlParseExternalID().
5604
 */
5605
5606
void
5607
11.3k
xmlParseNotationDecl(xmlParserCtxtPtr ctxt) {
5608
11.3k
    const xmlChar *name;
5609
11.3k
    xmlChar *Pubid;
5610
11.3k
    xmlChar *Systemid;
5611
5612
11.3k
    if ((CUR != '<') || (NXT(1) != '!'))
5613
0
        return;
5614
11.3k
    SKIP(2);
5615
5616
11.3k
    if (CMP8(CUR_PTR, 'N', 'O', 'T', 'A', 'T', 'I', 'O', 'N')) {
5617
7.24k
  int inputid = ctxt->input->id;
5618
7.24k
  SKIP(8);
5619
7.24k
  if (SKIP_BLANKS_PE == 0) {
5620
462
      xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED,
5621
462
         "Space required after '<!NOTATION'\n");
5622
462
      return;
5623
462
  }
5624
5625
6.77k
        name = xmlParseName(ctxt);
5626
6.77k
  if (name == NULL) {
5627
270
      xmlFatalErr(ctxt, XML_ERR_NOTATION_NOT_STARTED, NULL);
5628
270
      return;
5629
270
  }
5630
6.50k
  if (xmlStrchr(name, ':') != NULL) {
5631
627
      xmlNsErr(ctxt, XML_NS_ERR_COLON,
5632
627
         "colons are forbidden from notation names '%s'\n",
5633
627
         name, NULL, NULL);
5634
627
  }
5635
6.50k
  if (SKIP_BLANKS_PE == 0) {
5636
1.92k
      xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED,
5637
1.92k
         "Space required after the NOTATION name'\n");
5638
1.92k
      return;
5639
1.92k
  }
5640
5641
  /*
5642
   * Parse the IDs.
5643
   */
5644
4.58k
  Systemid = xmlParseExternalID(ctxt, &Pubid, 0);
5645
4.58k
  SKIP_BLANKS_PE;
5646
5647
4.58k
  if (RAW == '>') {
5648
3.54k
      if (inputid != ctxt->input->id) {
5649
0
    xmlFatalErrMsg(ctxt, XML_ERR_ENTITY_BOUNDARY,
5650
0
                         "Notation declaration doesn't start and stop"
5651
0
                               " in the same entity\n");
5652
0
      }
5653
3.54k
      NEXT;
5654
3.54k
      if ((ctxt->sax != NULL) && (!ctxt->disableSAX) &&
5655
3.27k
    (ctxt->sax->notationDecl != NULL))
5656
3.27k
    ctxt->sax->notationDecl(ctxt->userData, name, Pubid, Systemid);
5657
3.54k
  } else {
5658
1.03k
      xmlFatalErr(ctxt, XML_ERR_NOTATION_NOT_FINISHED, NULL);
5659
1.03k
  }
5660
4.58k
  if (Systemid != NULL) xmlFree(Systemid);
5661
4.58k
  if (Pubid != NULL) xmlFree(Pubid);
5662
4.58k
    }
5663
11.3k
}
5664
5665
/**
5666
 * xmlParseEntityDecl:
5667
 * @ctxt:  an XML parser context
5668
 *
5669
 * DEPRECATED: Internal function, don't use.
5670
 *
5671
 * Parse an entity declaration. Always consumes '<!'.
5672
 *
5673
 * [70] EntityDecl ::= GEDecl | PEDecl
5674
 *
5675
 * [71] GEDecl ::= '<!ENTITY' S Name S EntityDef S? '>'
5676
 *
5677
 * [72] PEDecl ::= '<!ENTITY' S '%' S Name S PEDef S? '>'
5678
 *
5679
 * [73] EntityDef ::= EntityValue | (ExternalID NDataDecl?)
5680
 *
5681
 * [74] PEDef ::= EntityValue | ExternalID
5682
 *
5683
 * [76] NDataDecl ::= S 'NDATA' S Name
5684
 *
5685
 * [ VC: Notation Declared ]
5686
 * The Name must match the declared name of a notation.
5687
 */
5688
5689
void
5690
230k
xmlParseEntityDecl(xmlParserCtxtPtr ctxt) {
5691
230k
    const xmlChar *name = NULL;
5692
230k
    xmlChar *value = NULL;
5693
230k
    xmlChar *URI = NULL, *literal = NULL;
5694
230k
    const xmlChar *ndata = NULL;
5695
230k
    int isParameter = 0;
5696
230k
    xmlChar *orig = NULL;
5697
5698
230k
    if ((CUR != '<') || (NXT(1) != '!'))
5699
0
        return;
5700
230k
    SKIP(2);
5701
5702
    /* GROW; done in the caller */
5703
230k
    if (CMP6(CUR_PTR, 'E', 'N', 'T', 'I', 'T', 'Y')) {
5704
228k
  int inputid = ctxt->input->id;
5705
228k
  SKIP(6);
5706
228k
  if (SKIP_BLANKS_PE == 0) {
5707
3.92k
      xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED,
5708
3.92k
         "Space required after '<!ENTITY'\n");
5709
3.92k
  }
5710
5711
228k
  if (RAW == '%') {
5712
121k
      NEXT;
5713
121k
      if (SKIP_BLANKS_PE == 0) {
5714
18.3k
    xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED,
5715
18.3k
             "Space required after '%%'\n");
5716
18.3k
      }
5717
121k
      isParameter = 1;
5718
121k
  }
5719
5720
228k
        name = xmlParseName(ctxt);
5721
228k
  if (name == NULL) {
5722
13.4k
      xmlFatalErrMsg(ctxt, XML_ERR_NAME_REQUIRED,
5723
13.4k
                     "xmlParseEntityDecl: no name\n");
5724
13.4k
            return;
5725
13.4k
  }
5726
215k
  if (xmlStrchr(name, ':') != NULL) {
5727
7.06k
      xmlNsErr(ctxt, XML_NS_ERR_COLON,
5728
7.06k
         "colons are forbidden from entities names '%s'\n",
5729
7.06k
         name, NULL, NULL);
5730
7.06k
  }
5731
215k
  if (SKIP_BLANKS_PE == 0) {
5732
7.02k
      xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED,
5733
7.02k
         "Space required after the entity name\n");
5734
7.02k
  }
5735
5736
  /*
5737
   * handle the various case of definitions...
5738
   */
5739
215k
  if (isParameter) {
5740
110k
      if ((RAW == '"') || (RAW == '\'')) {
5741
32.5k
          value = xmlParseEntityValue(ctxt, &orig);
5742
32.5k
    if (value) {
5743
31.9k
        if ((ctxt->sax != NULL) &&
5744
31.9k
      (!ctxt->disableSAX) && (ctxt->sax->entityDecl != NULL))
5745
19.1k
      ctxt->sax->entityDecl(ctxt->userData, name,
5746
19.1k
                        XML_INTERNAL_PARAMETER_ENTITY,
5747
19.1k
            NULL, NULL, value);
5748
31.9k
    }
5749
77.8k
      } else {
5750
77.8k
          URI = xmlParseExternalID(ctxt, &literal, 1);
5751
77.8k
    if ((URI == NULL) && (literal == NULL)) {
5752
1.64k
        xmlFatalErr(ctxt, XML_ERR_VALUE_REQUIRED, NULL);
5753
1.64k
    }
5754
77.8k
    if (URI) {
5755
76.0k
                    if (xmlStrchr(URI, '#')) {
5756
306
                        xmlFatalErr(ctxt, XML_ERR_URI_FRAGMENT, NULL);
5757
75.7k
                    } else {
5758
75.7k
                        if ((ctxt->sax != NULL) &&
5759
75.7k
                            (!ctxt->disableSAX) &&
5760
58.8k
                            (ctxt->sax->entityDecl != NULL))
5761
58.8k
                            ctxt->sax->entityDecl(ctxt->userData, name,
5762
58.8k
                                        XML_EXTERNAL_PARAMETER_ENTITY,
5763
58.8k
                                        literal, URI, NULL);
5764
75.7k
                    }
5765
76.0k
    }
5766
77.8k
      }
5767
110k
  } else {
5768
105k
      if ((RAW == '"') || (RAW == '\'')) {
5769
82.5k
          value = xmlParseEntityValue(ctxt, &orig);
5770
82.5k
    if ((ctxt->sax != NULL) &&
5771
82.5k
        (!ctxt->disableSAX) && (ctxt->sax->entityDecl != NULL))
5772
48.2k
        ctxt->sax->entityDecl(ctxt->userData, name,
5773
48.2k
        XML_INTERNAL_GENERAL_ENTITY,
5774
48.2k
        NULL, NULL, value);
5775
    /*
5776
     * For expat compatibility in SAX mode.
5777
     */
5778
82.5k
    if ((ctxt->myDoc == NULL) ||
5779
68.2k
        (xmlStrEqual(ctxt->myDoc->version, SAX_COMPAT_MODE))) {
5780
17.2k
        if (ctxt->myDoc == NULL) {
5781
14.3k
      ctxt->myDoc = xmlNewDoc(SAX_COMPAT_MODE);
5782
14.3k
      if (ctxt->myDoc == NULL) {
5783
34
          xmlErrMemory(ctxt);
5784
34
          goto done;
5785
34
      }
5786
14.2k
      ctxt->myDoc->properties = XML_DOC_INTERNAL;
5787
14.2k
        }
5788
17.1k
        if (ctxt->myDoc->intSubset == NULL) {
5789
14.2k
      ctxt->myDoc->intSubset = xmlNewDtd(ctxt->myDoc,
5790
14.2k
              BAD_CAST "fake", NULL, NULL);
5791
14.2k
                        if (ctxt->myDoc->intSubset == NULL) {
5792
4
                            xmlErrMemory(ctxt);
5793
4
                            goto done;
5794
4
                        }
5795
14.2k
                    }
5796
5797
17.1k
        xmlSAX2EntityDecl(ctxt, name, XML_INTERNAL_GENERAL_ENTITY,
5798
17.1k
                    NULL, NULL, value);
5799
17.1k
    }
5800
82.5k
      } else {
5801
22.4k
          URI = xmlParseExternalID(ctxt, &literal, 1);
5802
22.4k
    if ((URI == NULL) && (literal == NULL)) {
5803
5.48k
        xmlFatalErr(ctxt, XML_ERR_VALUE_REQUIRED, NULL);
5804
5.48k
    }
5805
22.4k
    if (URI) {
5806
15.9k
                    if (xmlStrchr(URI, '#')) {
5807
417
                        xmlFatalErr(ctxt, XML_ERR_URI_FRAGMENT, NULL);
5808
417
                    }
5809
15.9k
    }
5810
22.4k
    if ((RAW != '>') && (SKIP_BLANKS_PE == 0)) {
5811
6.74k
        xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED,
5812
6.74k
           "Space required before 'NDATA'\n");
5813
6.74k
    }
5814
22.4k
    if (CMP5(CUR_PTR, 'N', 'D', 'A', 'T', 'A')) {
5815
1.11k
        SKIP(5);
5816
1.11k
        if (SKIP_BLANKS_PE == 0) {
5817
886
      xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED,
5818
886
               "Space required after 'NDATA'\n");
5819
886
        }
5820
1.11k
        ndata = xmlParseName(ctxt);
5821
1.11k
        if ((ctxt->sax != NULL) && (!ctxt->disableSAX) &&
5822
229
            (ctxt->sax->unparsedEntityDecl != NULL))
5823
229
      ctxt->sax->unparsedEntityDecl(ctxt->userData, name,
5824
229
            literal, URI, ndata);
5825
21.3k
    } else {
5826
21.3k
        if ((ctxt->sax != NULL) &&
5827
21.3k
            (!ctxt->disableSAX) && (ctxt->sax->entityDecl != NULL))
5828
14.1k
      ctxt->sax->entityDecl(ctxt->userData, name,
5829
14.1k
            XML_EXTERNAL_GENERAL_PARSED_ENTITY,
5830
14.1k
            literal, URI, NULL);
5831
        /*
5832
         * For expat compatibility in SAX mode.
5833
         * assuming the entity replacement was asked for
5834
         */
5835
21.3k
        if ((ctxt->replaceEntities != 0) &&
5836
21.2k
      ((ctxt->myDoc == NULL) ||
5837
20.7k
      (xmlStrEqual(ctxt->myDoc->version, SAX_COMPAT_MODE)))) {
5838
919
      if (ctxt->myDoc == NULL) {
5839
435
          ctxt->myDoc = xmlNewDoc(SAX_COMPAT_MODE);
5840
435
          if (ctxt->myDoc == NULL) {
5841
1
              xmlErrMemory(ctxt);
5842
1
        goto done;
5843
1
          }
5844
434
          ctxt->myDoc->properties = XML_DOC_INTERNAL;
5845
434
      }
5846
5847
918
      if (ctxt->myDoc->intSubset == NULL) {
5848
434
          ctxt->myDoc->intSubset = xmlNewDtd(ctxt->myDoc,
5849
434
            BAD_CAST "fake", NULL, NULL);
5850
434
                            if (ctxt->myDoc->intSubset == NULL) {
5851
1
                                xmlErrMemory(ctxt);
5852
1
                                goto done;
5853
1
                            }
5854
434
                        }
5855
917
      xmlSAX2EntityDecl(ctxt, name,
5856
917
                  XML_EXTERNAL_GENERAL_PARSED_ENTITY,
5857
917
                  literal, URI, NULL);
5858
917
        }
5859
21.3k
    }
5860
22.4k
      }
5861
105k
  }
5862
215k
  SKIP_BLANKS_PE;
5863
215k
  if (RAW != '>') {
5864
34.2k
      xmlFatalErrMsgStr(ctxt, XML_ERR_ENTITY_NOT_FINISHED,
5865
34.2k
              "xmlParseEntityDecl: entity %s not terminated\n", name);
5866
34.2k
      xmlHaltParser(ctxt);
5867
181k
  } else {
5868
181k
      if (inputid != ctxt->input->id) {
5869
344
    xmlFatalErrMsg(ctxt, XML_ERR_ENTITY_BOUNDARY,
5870
344
                         "Entity declaration doesn't start and stop in"
5871
344
                               " the same entity\n");
5872
344
      }
5873
181k
      NEXT;
5874
181k
  }
5875
215k
  if (orig != NULL) {
5876
      /*
5877
       * Ugly mechanism to save the raw entity value.
5878
       */
5879
111k
      xmlEntityPtr cur = NULL;
5880
5881
111k
      if (isParameter) {
5882
31.9k
          if ((ctxt->sax != NULL) &&
5883
31.9k
        (ctxt->sax->getParameterEntity != NULL))
5884
31.9k
        cur = ctxt->sax->getParameterEntity(ctxt->userData, name);
5885
79.3k
      } else {
5886
79.3k
          if ((ctxt->sax != NULL) &&
5887
79.3k
        (ctxt->sax->getEntity != NULL))
5888
79.3k
        cur = ctxt->sax->getEntity(ctxt->userData, name);
5889
79.3k
    if ((cur == NULL) && (ctxt->userData==ctxt)) {
5890
14.3k
        cur = xmlSAX2GetEntity(ctxt, name);
5891
14.3k
    }
5892
79.3k
      }
5893
111k
            if ((cur != NULL) && (cur->orig == NULL)) {
5894
75.3k
    cur->orig = orig;
5895
75.3k
                orig = NULL;
5896
75.3k
      }
5897
111k
  }
5898
5899
215k
done:
5900
215k
  if (value != NULL) xmlFree(value);
5901
215k
  if (URI != NULL) xmlFree(URI);
5902
215k
  if (literal != NULL) xmlFree(literal);
5903
215k
        if (orig != NULL) xmlFree(orig);
5904
215k
    }
5905
230k
}
5906
5907
/**
5908
 * xmlParseDefaultDecl:
5909
 * @ctxt:  an XML parser context
5910
 * @value:  Receive a possible fixed default value for the attribute
5911
 *
5912
 * DEPRECATED: Internal function, don't use.
5913
 *
5914
 * Parse an attribute default declaration
5915
 *
5916
 * [60] DefaultDecl ::= '#REQUIRED' | '#IMPLIED' | (('#FIXED' S)? AttValue)
5917
 *
5918
 * [ VC: Required Attribute ]
5919
 * if the default declaration is the keyword #REQUIRED, then the
5920
 * attribute must be specified for all elements of the type in the
5921
 * attribute-list declaration.
5922
 *
5923
 * [ VC: Attribute Default Legal ]
5924
 * The declared default value must meet the lexical constraints of
5925
 * the declared attribute type c.f. xmlValidateAttributeDecl()
5926
 *
5927
 * [ VC: Fixed Attribute Default ]
5928
 * if an attribute has a default value declared with the #FIXED
5929
 * keyword, instances of that attribute must match the default value.
5930
 *
5931
 * [ WFC: No < in Attribute Values ]
5932
 * handled in xmlParseAttValue()
5933
 *
5934
 * returns: XML_ATTRIBUTE_NONE, XML_ATTRIBUTE_REQUIRED, XML_ATTRIBUTE_IMPLIED
5935
 *          or XML_ATTRIBUTE_FIXED.
5936
 */
5937
5938
int
5939
101k
xmlParseDefaultDecl(xmlParserCtxtPtr ctxt, xmlChar **value) {
5940
101k
    int val;
5941
101k
    xmlChar *ret;
5942
5943
101k
    *value = NULL;
5944
101k
    if (CMP9(CUR_PTR, '#', 'R', 'E', 'Q', 'U', 'I', 'R', 'E', 'D')) {
5945
1.02k
  SKIP(9);
5946
1.02k
  return(XML_ATTRIBUTE_REQUIRED);
5947
1.02k
    }
5948
100k
    if (CMP8(CUR_PTR, '#', 'I', 'M', 'P', 'L', 'I', 'E', 'D')) {
5949
26.7k
  SKIP(8);
5950
26.7k
  return(XML_ATTRIBUTE_IMPLIED);
5951
26.7k
    }
5952
73.4k
    val = XML_ATTRIBUTE_NONE;
5953
73.4k
    if (CMP6(CUR_PTR, '#', 'F', 'I', 'X', 'E', 'D')) {
5954
2.73k
  SKIP(6);
5955
2.73k
  val = XML_ATTRIBUTE_FIXED;
5956
2.73k
  if (SKIP_BLANKS_PE == 0) {
5957
476
      xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED,
5958
476
         "Space required after '#FIXED'\n");
5959
476
  }
5960
2.73k
    }
5961
73.4k
    ret = xmlParseAttValue(ctxt);
5962
73.4k
    if (ret == NULL) {
5963
9.78k
  xmlFatalErrMsg(ctxt, (xmlParserErrors)ctxt->errNo,
5964
9.78k
           "Attribute default value declaration error\n");
5965
9.78k
    } else
5966
63.6k
        *value = ret;
5967
73.4k
    return(val);
5968
100k
}
5969
5970
/**
5971
 * xmlParseNotationType:
5972
 * @ctxt:  an XML parser context
5973
 *
5974
 * DEPRECATED: Internal function, don't use.
5975
 *
5976
 * parse an Notation attribute type.
5977
 *
5978
 * Note: the leading 'NOTATION' S part has already being parsed...
5979
 *
5980
 * [58] NotationType ::= 'NOTATION' S '(' S? Name (S? '|' S? Name)* S? ')'
5981
 *
5982
 * [ VC: Notation Attributes ]
5983
 * Values of this type must match one of the notation names included
5984
 * in the declaration; all notation names in the declaration must be declared.
5985
 *
5986
 * Returns: the notation attribute tree built while parsing
5987
 */
5988
5989
xmlEnumerationPtr
5990
1.13k
xmlParseNotationType(xmlParserCtxtPtr ctxt) {
5991
1.13k
    const xmlChar *name;
5992
1.13k
    xmlEnumerationPtr ret = NULL, last = NULL, cur, tmp;
5993
5994
1.13k
    if (RAW != '(') {
5995
235
  xmlFatalErr(ctxt, XML_ERR_NOTATION_NOT_STARTED, NULL);
5996
235
  return(NULL);
5997
235
    }
5998
1.18k
    do {
5999
1.18k
        NEXT;
6000
1.18k
  SKIP_BLANKS_PE;
6001
1.18k
        name = xmlParseName(ctxt);
6002
1.18k
  if (name == NULL) {
6003
324
      xmlFatalErrMsg(ctxt, XML_ERR_NAME_REQUIRED,
6004
324
         "Name expected in NOTATION declaration\n");
6005
324
            xmlFreeEnumeration(ret);
6006
324
      return(NULL);
6007
324
  }
6008
865
        tmp = NULL;
6009
#ifdef LIBXML_VALID_ENABLED
6010
        if (ctxt->validate) {
6011
            tmp = ret;
6012
            while (tmp != NULL) {
6013
                if (xmlStrEqual(name, tmp->name)) {
6014
                    xmlValidityError(ctxt, XML_DTD_DUP_TOKEN,
6015
              "standalone: attribute notation value token %s duplicated\n",
6016
                                     name, NULL);
6017
                    if (!xmlDictOwns(ctxt->dict, name))
6018
                        xmlFree((xmlChar *) name);
6019
                    break;
6020
                }
6021
                tmp = tmp->next;
6022
            }
6023
        }
6024
#endif /* LIBXML_VALID_ENABLED */
6025
865
  if (tmp == NULL) {
6026
865
      cur = xmlCreateEnumeration(name);
6027
865
      if (cur == NULL) {
6028
1
                xmlErrMemory(ctxt);
6029
1
                xmlFreeEnumeration(ret);
6030
1
                return(NULL);
6031
1
            }
6032
864
      if (last == NULL) ret = last = cur;
6033
263
      else {
6034
263
    last->next = cur;
6035
263
    last = cur;
6036
263
      }
6037
864
  }
6038
864
  SKIP_BLANKS_PE;
6039
864
    } while (RAW == '|');
6040
579
    if (RAW != ')') {
6041
229
  xmlFatalErr(ctxt, XML_ERR_NOTATION_NOT_FINISHED, NULL);
6042
229
        xmlFreeEnumeration(ret);
6043
229
  return(NULL);
6044
229
    }
6045
350
    NEXT;
6046
350
    return(ret);
6047
579
}
6048
6049
/**
6050
 * xmlParseEnumerationType:
6051
 * @ctxt:  an XML parser context
6052
 *
6053
 * DEPRECATED: Internal function, don't use.
6054
 *
6055
 * parse an Enumeration attribute type.
6056
 *
6057
 * [59] Enumeration ::= '(' S? Nmtoken (S? '|' S? Nmtoken)* S? ')'
6058
 *
6059
 * [ VC: Enumeration ]
6060
 * Values of this type must match one of the Nmtoken tokens in
6061
 * the declaration
6062
 *
6063
 * Returns: the enumeration attribute tree built while parsing
6064
 */
6065
6066
xmlEnumerationPtr
6067
16.2k
xmlParseEnumerationType(xmlParserCtxtPtr ctxt) {
6068
16.2k
    xmlChar *name;
6069
16.2k
    xmlEnumerationPtr ret = NULL, last = NULL, cur, tmp;
6070
6071
16.2k
    if (RAW != '(') {
6072
6.94k
  xmlFatalErr(ctxt, XML_ERR_ATTLIST_NOT_STARTED, NULL);
6073
6.94k
  return(NULL);
6074
6.94k
    }
6075
13.2k
    do {
6076
13.2k
        NEXT;
6077
13.2k
  SKIP_BLANKS_PE;
6078
13.2k
        name = xmlParseNmtoken(ctxt);
6079
13.2k
  if (name == NULL) {
6080
561
      xmlFatalErr(ctxt, XML_ERR_NMTOKEN_REQUIRED, NULL);
6081
561
      return(ret);
6082
561
  }
6083
12.6k
        tmp = NULL;
6084
#ifdef LIBXML_VALID_ENABLED
6085
        if (ctxt->validate) {
6086
            tmp = ret;
6087
            while (tmp != NULL) {
6088
                if (xmlStrEqual(name, tmp->name)) {
6089
                    xmlValidityError(ctxt, XML_DTD_DUP_TOKEN,
6090
              "standalone: attribute enumeration value token %s duplicated\n",
6091
                                     name, NULL);
6092
                    if (!xmlDictOwns(ctxt->dict, name))
6093
                        xmlFree(name);
6094
                    break;
6095
                }
6096
                tmp = tmp->next;
6097
            }
6098
        }
6099
#endif /* LIBXML_VALID_ENABLED */
6100
12.6k
  if (tmp == NULL) {
6101
12.6k
      cur = xmlCreateEnumeration(name);
6102
12.6k
      if (!xmlDictOwns(ctxt->dict, name))
6103
12.6k
    xmlFree(name);
6104
12.6k
      if (cur == NULL) {
6105
2
                xmlErrMemory(ctxt);
6106
2
                xmlFreeEnumeration(ret);
6107
2
                return(NULL);
6108
2
            }
6109
12.6k
      if (last == NULL) ret = last = cur;
6110
3.74k
      else {
6111
3.74k
    last->next = cur;
6112
3.74k
    last = cur;
6113
3.74k
      }
6114
12.6k
  }
6115
12.6k
  SKIP_BLANKS_PE;
6116
12.6k
    } while (RAW == '|');
6117
8.77k
    if (RAW != ')') {
6118
1.03k
  xmlFatalErr(ctxt, XML_ERR_ATTLIST_NOT_FINISHED, NULL);
6119
1.03k
  return(ret);
6120
1.03k
    }
6121
7.73k
    NEXT;
6122
7.73k
    return(ret);
6123
8.77k
}
6124
6125
/**
6126
 * xmlParseEnumeratedType:
6127
 * @ctxt:  an XML parser context
6128
 * @tree:  the enumeration tree built while parsing
6129
 *
6130
 * DEPRECATED: Internal function, don't use.
6131
 *
6132
 * parse an Enumerated attribute type.
6133
 *
6134
 * [57] EnumeratedType ::= NotationType | Enumeration
6135
 *
6136
 * [58] NotationType ::= 'NOTATION' S '(' S? Name (S? '|' S? Name)* S? ')'
6137
 *
6138
 *
6139
 * Returns: XML_ATTRIBUTE_ENUMERATION or XML_ATTRIBUTE_NOTATION
6140
 */
6141
6142
int
6143
17.6k
xmlParseEnumeratedType(xmlParserCtxtPtr ctxt, xmlEnumerationPtr *tree) {
6144
17.6k
    if (CMP8(CUR_PTR, 'N', 'O', 'T', 'A', 'T', 'I', 'O', 'N')) {
6145
1.37k
  SKIP(8);
6146
1.37k
  if (SKIP_BLANKS_PE == 0) {
6147
240
      xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED,
6148
240
         "Space required after 'NOTATION'\n");
6149
240
      return(0);
6150
240
  }
6151
1.13k
  *tree = xmlParseNotationType(ctxt);
6152
1.13k
  if (*tree == NULL) return(0);
6153
350
  return(XML_ATTRIBUTE_NOTATION);
6154
1.13k
    }
6155
16.2k
    *tree = xmlParseEnumerationType(ctxt);
6156
16.2k
    if (*tree == NULL) return(0);
6157
8.93k
    return(XML_ATTRIBUTE_ENUMERATION);
6158
16.2k
}
6159
6160
/**
6161
 * xmlParseAttributeType:
6162
 * @ctxt:  an XML parser context
6163
 * @tree:  the enumeration tree built while parsing
6164
 *
6165
 * DEPRECATED: Internal function, don't use.
6166
 *
6167
 * parse the Attribute list def for an element
6168
 *
6169
 * [54] AttType ::= StringType | TokenizedType | EnumeratedType
6170
 *
6171
 * [55] StringType ::= 'CDATA'
6172
 *
6173
 * [56] TokenizedType ::= 'ID' | 'IDREF' | 'IDREFS' | 'ENTITY' |
6174
 *                        'ENTITIES' | 'NMTOKEN' | 'NMTOKENS'
6175
 *
6176
 * Validity constraints for attribute values syntax are checked in
6177
 * xmlValidateAttributeValue()
6178
 *
6179
 * [ VC: ID ]
6180
 * Values of type ID must match the Name production. A name must not
6181
 * appear more than once in an XML document as a value of this type;
6182
 * i.e., ID values must uniquely identify the elements which bear them.
6183
 *
6184
 * [ VC: One ID per Element Type ]
6185
 * No element type may have more than one ID attribute specified.
6186
 *
6187
 * [ VC: ID Attribute Default ]
6188
 * An ID attribute must have a declared default of #IMPLIED or #REQUIRED.
6189
 *
6190
 * [ VC: IDREF ]
6191
 * Values of type IDREF must match the Name production, and values
6192
 * of type IDREFS must match Names; each IDREF Name must match the value
6193
 * of an ID attribute on some element in the XML document; i.e. IDREF
6194
 * values must match the value of some ID attribute.
6195
 *
6196
 * [ VC: Entity Name ]
6197
 * Values of type ENTITY must match the Name production, values
6198
 * of type ENTITIES must match Names; each Entity Name must match the
6199
 * name of an unparsed entity declared in the DTD.
6200
 *
6201
 * [ VC: Name Token ]
6202
 * Values of type NMTOKEN must match the Nmtoken production; values
6203
 * of type NMTOKENS must match Nmtokens.
6204
 *
6205
 * Returns the attribute type
6206
 */
6207
int
6208
114k
xmlParseAttributeType(xmlParserCtxtPtr ctxt, xmlEnumerationPtr *tree) {
6209
114k
    if (CMP5(CUR_PTR, 'C', 'D', 'A', 'T', 'A')) {
6210
22.8k
  SKIP(5);
6211
22.8k
  return(XML_ATTRIBUTE_CDATA);
6212
91.3k
     } else if (CMP6(CUR_PTR, 'I', 'D', 'R', 'E', 'F', 'S')) {
6213
834
  SKIP(6);
6214
834
  return(XML_ATTRIBUTE_IDREFS);
6215
90.4k
     } else if (CMP5(CUR_PTR, 'I', 'D', 'R', 'E', 'F')) {
6216
2.76k
  SKIP(5);
6217
2.76k
  return(XML_ATTRIBUTE_IDREF);
6218
87.7k
     } else if ((RAW == 'I') && (NXT(1) == 'D')) {
6219
55.9k
        SKIP(2);
6220
55.9k
  return(XML_ATTRIBUTE_ID);
6221
55.9k
     } else if (CMP6(CUR_PTR, 'E', 'N', 'T', 'I', 'T', 'Y')) {
6222
476
  SKIP(6);
6223
476
  return(XML_ATTRIBUTE_ENTITY);
6224
31.3k
     } else if (CMP8(CUR_PTR, 'E', 'N', 'T', 'I', 'T', 'I', 'E', 'S')) {
6225
1.14k
  SKIP(8);
6226
1.14k
  return(XML_ATTRIBUTE_ENTITIES);
6227
30.1k
     } else if (CMP8(CUR_PTR, 'N', 'M', 'T', 'O', 'K', 'E', 'N', 'S')) {
6228
9.66k
  SKIP(8);
6229
9.66k
  return(XML_ATTRIBUTE_NMTOKENS);
6230
20.5k
     } else if (CMP7(CUR_PTR, 'N', 'M', 'T', 'O', 'K', 'E', 'N')) {
6231
2.84k
  SKIP(7);
6232
2.84k
  return(XML_ATTRIBUTE_NMTOKEN);
6233
2.84k
     }
6234
17.6k
     return(xmlParseEnumeratedType(ctxt, tree));
6235
114k
}
6236
6237
/**
6238
 * xmlParseAttributeListDecl:
6239
 * @ctxt:  an XML parser context
6240
 *
6241
 * DEPRECATED: Internal function, don't use.
6242
 *
6243
 * Parse an attribute list declaration for an element. Always consumes '<!'.
6244
 *
6245
 * [52] AttlistDecl ::= '<!ATTLIST' S Name AttDef* S? '>'
6246
 *
6247
 * [53] AttDef ::= S Name S AttType S DefaultDecl
6248
 *
6249
 */
6250
void
6251
67.2k
xmlParseAttributeListDecl(xmlParserCtxtPtr ctxt) {
6252
67.2k
    const xmlChar *elemName;
6253
67.2k
    const xmlChar *attrName;
6254
67.2k
    xmlEnumerationPtr tree;
6255
6256
67.2k
    if ((CUR != '<') || (NXT(1) != '!'))
6257
0
        return;
6258
67.2k
    SKIP(2);
6259
6260
67.2k
    if (CMP7(CUR_PTR, 'A', 'T', 'T', 'L', 'I', 'S', 'T')) {
6261
64.6k
  int inputid = ctxt->input->id;
6262
6263
64.6k
  SKIP(7);
6264
64.6k
  if (SKIP_BLANKS_PE == 0) {
6265
1.31k
      xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED,
6266
1.31k
                     "Space required after '<!ATTLIST'\n");
6267
1.31k
  }
6268
64.6k
        elemName = xmlParseName(ctxt);
6269
64.6k
  if (elemName == NULL) {
6270
511
      xmlFatalErrMsg(ctxt, XML_ERR_NAME_REQUIRED,
6271
511
         "ATTLIST: no name for Element\n");
6272
511
      return;
6273
511
  }
6274
64.1k
  SKIP_BLANKS_PE;
6275
64.1k
  GROW;
6276
154k
  while ((RAW != '>') && (PARSER_STOPPED(ctxt) == 0)) {
6277
117k
      int type;
6278
117k
      int def;
6279
117k
      xmlChar *defaultValue = NULL;
6280
6281
117k
      GROW;
6282
117k
            tree = NULL;
6283
117k
      attrName = xmlParseName(ctxt);
6284
117k
      if (attrName == NULL) {
6285
2.92k
    xmlFatalErrMsg(ctxt, XML_ERR_NAME_REQUIRED,
6286
2.92k
             "ATTLIST: no name for Attribute\n");
6287
2.92k
    break;
6288
2.92k
      }
6289
114k
      GROW;
6290
114k
      if (SKIP_BLANKS_PE == 0) {
6291
839
    xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED,
6292
839
            "Space required after the attribute name\n");
6293
839
    break;
6294
839
      }
6295
6296
114k
      type = xmlParseAttributeType(ctxt, &tree);
6297
114k
      if (type <= 0) {
6298
8.38k
          break;
6299
8.38k
      }
6300
6301
105k
      GROW;
6302
105k
      if (SKIP_BLANKS_PE == 0) {
6303
4.50k
    xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED,
6304
4.50k
             "Space required after the attribute type\n");
6305
4.50k
          if (tree != NULL)
6306
1.49k
        xmlFreeEnumeration(tree);
6307
4.50k
    break;
6308
4.50k
      }
6309
6310
101k
      def = xmlParseDefaultDecl(ctxt, &defaultValue);
6311
101k
      if (def <= 0) {
6312
0
                if (defaultValue != NULL)
6313
0
        xmlFree(defaultValue);
6314
0
          if (tree != NULL)
6315
0
        xmlFreeEnumeration(tree);
6316
0
          break;
6317
0
      }
6318
101k
      if ((type != XML_ATTRIBUTE_CDATA) && (defaultValue != NULL))
6319
57.8k
          xmlAttrNormalizeSpace(defaultValue, defaultValue);
6320
6321
101k
      GROW;
6322
101k
            if (RAW != '>') {
6323
75.6k
    if (SKIP_BLANKS_PE == 0) {
6324
10.8k
        xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED,
6325
10.8k
      "Space required after the attribute default value\n");
6326
10.8k
        if (defaultValue != NULL)
6327
1.07k
      xmlFree(defaultValue);
6328
10.8k
        if (tree != NULL)
6329
420
      xmlFreeEnumeration(tree);
6330
10.8k
        break;
6331
10.8k
    }
6332
75.6k
      }
6333
90.3k
      if ((ctxt->sax != NULL) && (!ctxt->disableSAX) &&
6334
41.3k
    (ctxt->sax->attributeDecl != NULL))
6335
41.3k
    ctxt->sax->attributeDecl(ctxt->userData, elemName, attrName,
6336
41.3k
                          type, def, defaultValue, tree);
6337
49.0k
      else if (tree != NULL)
6338
898
    xmlFreeEnumeration(tree);
6339
6340
90.3k
      if ((ctxt->sax2) && (defaultValue != NULL) &&
6341
62.6k
          (def != XML_ATTRIBUTE_IMPLIED) &&
6342
62.6k
    (def != XML_ATTRIBUTE_REQUIRED)) {
6343
62.6k
    xmlAddDefAttrs(ctxt, elemName, attrName, defaultValue);
6344
62.6k
      }
6345
90.3k
      if (ctxt->sax2) {
6346
90.3k
    xmlAddSpecialAttr(ctxt, elemName, attrName, type);
6347
90.3k
      }
6348
90.3k
      if (defaultValue != NULL)
6349
62.6k
          xmlFree(defaultValue);
6350
90.3k
      GROW;
6351
90.3k
  }
6352
64.1k
  if (RAW == '>') {
6353
37.2k
      if (inputid != ctxt->input->id) {
6354
419
    xmlFatalErrMsg(ctxt, XML_ERR_ENTITY_BOUNDARY,
6355
419
                               "Attribute list declaration doesn't start and"
6356
419
                               " stop in the same entity\n");
6357
419
      }
6358
37.2k
      NEXT;
6359
37.2k
  }
6360
64.1k
    }
6361
67.2k
}
6362
6363
/**
6364
 * xmlParseElementMixedContentDecl:
6365
 * @ctxt:  an XML parser context
6366
 * @inputchk:  the input used for the current entity, needed for boundary checks
6367
 *
6368
 * DEPRECATED: Internal function, don't use.
6369
 *
6370
 * parse the declaration for a Mixed Element content
6371
 * The leading '(' and spaces have been skipped in xmlParseElementContentDecl
6372
 *
6373
 * [51] Mixed ::= '(' S? '#PCDATA' (S? '|' S? Name)* S? ')*' |
6374
 *                '(' S? '#PCDATA' S? ')'
6375
 *
6376
 * [ VC: Proper Group/PE Nesting ] applies to [51] too (see [49])
6377
 *
6378
 * [ VC: No Duplicate Types ]
6379
 * The same name must not appear more than once in a single
6380
 * mixed-content declaration.
6381
 *
6382
 * returns: the list of the xmlElementContentPtr describing the element choices
6383
 */
6384
xmlElementContentPtr
6385
15.5k
xmlParseElementMixedContentDecl(xmlParserCtxtPtr ctxt, int inputchk) {
6386
15.5k
    xmlElementContentPtr ret = NULL, cur = NULL, n;
6387
15.5k
    const xmlChar *elem = NULL;
6388
6389
15.5k
    GROW;
6390
15.5k
    if (CMP7(CUR_PTR, '#', 'P', 'C', 'D', 'A', 'T', 'A')) {
6391
15.5k
  SKIP(7);
6392
15.5k
  SKIP_BLANKS_PE;
6393
15.5k
  if (RAW == ')') {
6394
13.2k
      if (ctxt->input->id != inputchk) {
6395
0
    xmlFatalErrMsg(ctxt, XML_ERR_ENTITY_BOUNDARY,
6396
0
                               "Element content declaration doesn't start and"
6397
0
                               " stop in the same entity\n");
6398
0
      }
6399
13.2k
      NEXT;
6400
13.2k
      ret = xmlNewDocElementContent(ctxt->myDoc, NULL, XML_ELEMENT_CONTENT_PCDATA);
6401
13.2k
      if (ret == NULL)
6402
3
                goto mem_error;
6403
13.2k
      if (RAW == '*') {
6404
217
    ret->ocur = XML_ELEMENT_CONTENT_MULT;
6405
217
    NEXT;
6406
217
      }
6407
13.2k
      return(ret);
6408
13.2k
  }
6409
2.28k
  if ((RAW == '(') || (RAW == '|')) {
6410
1.40k
      ret = cur = xmlNewDocElementContent(ctxt->myDoc, NULL, XML_ELEMENT_CONTENT_PCDATA);
6411
1.40k
      if (ret == NULL)
6412
1
                goto mem_error;
6413
1.40k
  }
6414
3.34k
  while ((RAW == '|') && (PARSER_STOPPED(ctxt) == 0)) {
6415
1.55k
      NEXT;
6416
1.55k
            n = xmlNewDocElementContent(ctxt->myDoc, NULL, XML_ELEMENT_CONTENT_OR);
6417
1.55k
            if (n == NULL)
6418
1
                goto mem_error;
6419
1.55k
      if (elem == NULL) {
6420
1.20k
    n->c1 = cur;
6421
1.20k
    if (cur != NULL)
6422
1.20k
        cur->parent = n;
6423
1.20k
    ret = cur = n;
6424
1.20k
      } else {
6425
356
          cur->c2 = n;
6426
356
    n->parent = cur;
6427
356
    n->c1 = xmlNewDocElementContent(ctxt->myDoc, elem, XML_ELEMENT_CONTENT_ELEMENT);
6428
356
                if (n->c1 == NULL)
6429
1
                    goto mem_error;
6430
355
    n->c1->parent = n;
6431
355
    cur = n;
6432
355
      }
6433
1.55k
      SKIP_BLANKS_PE;
6434
1.55k
      elem = xmlParseName(ctxt);
6435
1.55k
      if (elem == NULL) {
6436
496
    xmlFatalErrMsg(ctxt, XML_ERR_NAME_REQUIRED,
6437
496
      "xmlParseElementMixedContentDecl : Name expected\n");
6438
496
    xmlFreeDocElementContent(ctxt->myDoc, ret);
6439
496
    return(NULL);
6440
496
      }
6441
1.06k
      SKIP_BLANKS_PE;
6442
1.06k
      GROW;
6443
1.06k
  }
6444
1.78k
  if ((RAW == ')') && (NXT(1) == '*')) {
6445
456
      if (elem != NULL) {
6446
456
    cur->c2 = xmlNewDocElementContent(ctxt->myDoc, elem,
6447
456
                                   XML_ELEMENT_CONTENT_ELEMENT);
6448
456
    if (cur->c2 == NULL)
6449
1
                    goto mem_error;
6450
455
    cur->c2->parent = cur;
6451
455
            }
6452
455
            if (ret != NULL)
6453
455
                ret->ocur = XML_ELEMENT_CONTENT_MULT;
6454
455
      if (ctxt->input->id != inputchk) {
6455
0
    xmlFatalErrMsg(ctxt, XML_ERR_ENTITY_BOUNDARY,
6456
0
                               "Element content declaration doesn't start and"
6457
0
                               " stop in the same entity\n");
6458
0
      }
6459
455
      SKIP(2);
6460
1.32k
  } else {
6461
1.32k
      xmlFreeDocElementContent(ctxt->myDoc, ret);
6462
1.32k
      xmlFatalErr(ctxt, XML_ERR_MIXED_NOT_STARTED, NULL);
6463
1.32k
      return(NULL);
6464
1.32k
  }
6465
6466
1.78k
    } else {
6467
0
  xmlFatalErr(ctxt, XML_ERR_PCDATA_REQUIRED, NULL);
6468
0
    }
6469
455
    return(ret);
6470
6471
7
mem_error:
6472
7
    xmlErrMemory(ctxt);
6473
7
    xmlFreeDocElementContent(ctxt->myDoc, ret);
6474
7
    return(NULL);
6475
15.5k
}
6476
6477
/**
6478
 * xmlParseElementChildrenContentDeclPriv:
6479
 * @ctxt:  an XML parser context
6480
 * @inputchk:  the input used for the current entity, needed for boundary checks
6481
 * @depth: the level of recursion
6482
 *
6483
 * parse the declaration for a Mixed Element content
6484
 * The leading '(' and spaces have been skipped in xmlParseElementContentDecl
6485
 *
6486
 *
6487
 * [47] children ::= (choice | seq) ('?' | '*' | '+')?
6488
 *
6489
 * [48] cp ::= (Name | choice | seq) ('?' | '*' | '+')?
6490
 *
6491
 * [49] choice ::= '(' S? cp ( S? '|' S? cp )* S? ')'
6492
 *
6493
 * [50] seq ::= '(' S? cp ( S? ',' S? cp )* S? ')'
6494
 *
6495
 * [ VC: Proper Group/PE Nesting ] applies to [49] and [50]
6496
 * TODO Parameter-entity replacement text must be properly nested
6497
 *  with parenthesized groups. That is to say, if either of the
6498
 *  opening or closing parentheses in a choice, seq, or Mixed
6499
 *  construct is contained in the replacement text for a parameter
6500
 *  entity, both must be contained in the same replacement text. For
6501
 *  interoperability, if a parameter-entity reference appears in a
6502
 *  choice, seq, or Mixed construct, its replacement text should not
6503
 *  be empty, and neither the first nor last non-blank character of
6504
 *  the replacement text should be a connector (| or ,).
6505
 *
6506
 * Returns the tree of xmlElementContentPtr describing the element
6507
 *          hierarchy.
6508
 */
6509
static xmlElementContentPtr
6510
xmlParseElementChildrenContentDeclPriv(xmlParserCtxtPtr ctxt, int inputchk,
6511
89.1k
                                       int depth) {
6512
89.1k
    int maxDepth = (ctxt->options & XML_PARSE_HUGE) ? 2048 : 256;
6513
89.1k
    xmlElementContentPtr ret = NULL, cur = NULL, last = NULL, op = NULL;
6514
89.1k
    const xmlChar *elem;
6515
89.1k
    xmlChar type = 0;
6516
6517
89.1k
    if (depth > maxDepth) {
6518
73
        xmlFatalErrMsgInt(ctxt, XML_ERR_RESOURCE_LIMIT,
6519
73
                "xmlParseElementChildrenContentDecl : depth %d too deep, "
6520
73
                "use XML_PARSE_HUGE\n", depth);
6521
73
  return(NULL);
6522
73
    }
6523
89.1k
    SKIP_BLANKS_PE;
6524
89.1k
    GROW;
6525
89.1k
    if (RAW == '(') {
6526
43.0k
  int inputid = ctxt->input->id;
6527
6528
        /* Recurse on first child */
6529
43.0k
  NEXT;
6530
43.0k
  SKIP_BLANKS_PE;
6531
43.0k
        cur = ret = xmlParseElementChildrenContentDeclPriv(ctxt, inputid,
6532
43.0k
                                                           depth + 1);
6533
43.0k
        if (cur == NULL)
6534
25.0k
            return(NULL);
6535
17.9k
  SKIP_BLANKS_PE;
6536
17.9k
  GROW;
6537
46.0k
    } else {
6538
46.0k
  elem = xmlParseName(ctxt);
6539
46.0k
  if (elem == NULL) {
6540
2.28k
      xmlFatalErr(ctxt, XML_ERR_ELEMCONTENT_NOT_STARTED, NULL);
6541
2.28k
      return(NULL);
6542
2.28k
  }
6543
43.7k
        cur = ret = xmlNewDocElementContent(ctxt->myDoc, elem, XML_ELEMENT_CONTENT_ELEMENT);
6544
43.7k
  if (cur == NULL) {
6545
5
      xmlErrMemory(ctxt);
6546
5
      return(NULL);
6547
5
  }
6548
43.7k
  GROW;
6549
43.7k
  if (RAW == '?') {
6550
2.73k
      cur->ocur = XML_ELEMENT_CONTENT_OPT;
6551
2.73k
      NEXT;
6552
41.0k
  } else if (RAW == '*') {
6553
7.02k
      cur->ocur = XML_ELEMENT_CONTENT_MULT;
6554
7.02k
      NEXT;
6555
34.0k
  } else if (RAW == '+') {
6556
1.73k
      cur->ocur = XML_ELEMENT_CONTENT_PLUS;
6557
1.73k
      NEXT;
6558
32.2k
  } else {
6559
32.2k
      cur->ocur = XML_ELEMENT_CONTENT_ONCE;
6560
32.2k
  }
6561
43.7k
  GROW;
6562
43.7k
    }
6563
61.7k
    SKIP_BLANKS_PE;
6564
100k
    while ((RAW != ')') && (PARSER_STOPPED(ctxt) == 0)) {
6565
        /*
6566
   * Each loop we parse one separator and one element.
6567
   */
6568
47.1k
        if (RAW == ',') {
6569
23.6k
      if (type == 0) type = CUR;
6570
6571
      /*
6572
       * Detect "Name | Name , Name" error
6573
       */
6574
16.1k
      else if (type != CUR) {
6575
264
    xmlFatalErrMsgInt(ctxt, XML_ERR_SEPARATOR_REQUIRED,
6576
264
        "xmlParseElementChildrenContentDecl : '%c' expected\n",
6577
264
                      type);
6578
264
    if ((last != NULL) && (last != ret))
6579
264
        xmlFreeDocElementContent(ctxt->myDoc, last);
6580
264
    if (ret != NULL)
6581
264
        xmlFreeDocElementContent(ctxt->myDoc, ret);
6582
264
    return(NULL);
6583
264
      }
6584
23.3k
      NEXT;
6585
6586
23.3k
      op = xmlNewDocElementContent(ctxt->myDoc, NULL, XML_ELEMENT_CONTENT_SEQ);
6587
23.3k
      if (op == NULL) {
6588
4
                xmlErrMemory(ctxt);
6589
4
    if ((last != NULL) && (last != ret))
6590
2
        xmlFreeDocElementContent(ctxt->myDoc, last);
6591
4
          xmlFreeDocElementContent(ctxt->myDoc, ret);
6592
4
    return(NULL);
6593
4
      }
6594
23.3k
      if (last == NULL) {
6595
7.47k
    op->c1 = ret;
6596
7.47k
    if (ret != NULL)
6597
7.47k
        ret->parent = op;
6598
7.47k
    ret = cur = op;
6599
15.8k
      } else {
6600
15.8k
          cur->c2 = op;
6601
15.8k
    if (op != NULL)
6602
15.8k
        op->parent = cur;
6603
15.8k
    op->c1 = last;
6604
15.8k
    if (last != NULL)
6605
15.8k
        last->parent = op;
6606
15.8k
    cur =op;
6607
15.8k
    last = NULL;
6608
15.8k
      }
6609
23.5k
  } else if (RAW == '|') {
6610
20.9k
      if (type == 0) type = CUR;
6611
6612
      /*
6613
       * Detect "Name , Name | Name" error
6614
       */
6615
7.47k
      else if (type != CUR) {
6616
262
    xmlFatalErrMsgInt(ctxt, XML_ERR_SEPARATOR_REQUIRED,
6617
262
        "xmlParseElementChildrenContentDecl : '%c' expected\n",
6618
262
          type);
6619
262
    if ((last != NULL) && (last != ret))
6620
262
        xmlFreeDocElementContent(ctxt->myDoc, last);
6621
262
    if (ret != NULL)
6622
262
        xmlFreeDocElementContent(ctxt->myDoc, ret);
6623
262
    return(NULL);
6624
262
      }
6625
20.7k
      NEXT;
6626
6627
20.7k
      op = xmlNewDocElementContent(ctxt->myDoc, NULL, XML_ELEMENT_CONTENT_OR);
6628
20.7k
      if (op == NULL) {
6629
6
                xmlErrMemory(ctxt);
6630
6
    if ((last != NULL) && (last != ret))
6631
1
        xmlFreeDocElementContent(ctxt->myDoc, last);
6632
6
    if (ret != NULL)
6633
6
        xmlFreeDocElementContent(ctxt->myDoc, ret);
6634
6
    return(NULL);
6635
6
      }
6636
20.7k
      if (last == NULL) {
6637
13.4k
    op->c1 = ret;
6638
13.4k
    if (ret != NULL)
6639
13.4k
        ret->parent = op;
6640
13.4k
    ret = cur = op;
6641
13.4k
      } else {
6642
7.21k
          cur->c2 = op;
6643
7.21k
    if (op != NULL)
6644
7.21k
        op->parent = cur;
6645
7.21k
    op->c1 = last;
6646
7.21k
    if (last != NULL)
6647
7.21k
        last->parent = op;
6648
7.21k
    cur =op;
6649
7.21k
    last = NULL;
6650
7.21k
      }
6651
20.7k
  } else {
6652
2.55k
      xmlFatalErr(ctxt, XML_ERR_ELEMCONTENT_NOT_FINISHED, NULL);
6653
2.55k
      if ((last != NULL) && (last != ret))
6654
1.72k
          xmlFreeDocElementContent(ctxt->myDoc, last);
6655
2.55k
      if (ret != NULL)
6656
2.55k
    xmlFreeDocElementContent(ctxt->myDoc, ret);
6657
2.55k
      return(NULL);
6658
2.55k
  }
6659
44.0k
  GROW;
6660
44.0k
  SKIP_BLANKS_PE;
6661
44.0k
  GROW;
6662
44.0k
  if (RAW == '(') {
6663
11.9k
      int inputid = ctxt->input->id;
6664
      /* Recurse on second child */
6665
11.9k
      NEXT;
6666
11.9k
      SKIP_BLANKS_PE;
6667
11.9k
      last = xmlParseElementChildrenContentDeclPriv(ctxt, inputid,
6668
11.9k
                                                          depth + 1);
6669
11.9k
            if (last == NULL) {
6670
4.87k
    if (ret != NULL)
6671
4.87k
        xmlFreeDocElementContent(ctxt->myDoc, ret);
6672
4.87k
    return(NULL);
6673
4.87k
            }
6674
7.07k
      SKIP_BLANKS_PE;
6675
32.1k
  } else {
6676
32.1k
      elem = xmlParseName(ctxt);
6677
32.1k
      if (elem == NULL) {
6678
392
    xmlFatalErr(ctxt, XML_ERR_ELEMCONTENT_NOT_STARTED, NULL);
6679
392
    if (ret != NULL)
6680
392
        xmlFreeDocElementContent(ctxt->myDoc, ret);
6681
392
    return(NULL);
6682
392
      }
6683
31.7k
      last = xmlNewDocElementContent(ctxt->myDoc, elem, XML_ELEMENT_CONTENT_ELEMENT);
6684
31.7k
      if (last == NULL) {
6685
2
                xmlErrMemory(ctxt);
6686
2
    if (ret != NULL)
6687
2
        xmlFreeDocElementContent(ctxt->myDoc, ret);
6688
2
    return(NULL);
6689
2
      }
6690
31.7k
      if (RAW == '?') {
6691
12.2k
    last->ocur = XML_ELEMENT_CONTENT_OPT;
6692
12.2k
    NEXT;
6693
19.4k
      } else if (RAW == '*') {
6694
1.60k
    last->ocur = XML_ELEMENT_CONTENT_MULT;
6695
1.60k
    NEXT;
6696
17.8k
      } else if (RAW == '+') {
6697
731
    last->ocur = XML_ELEMENT_CONTENT_PLUS;
6698
731
    NEXT;
6699
17.1k
      } else {
6700
17.1k
    last->ocur = XML_ELEMENT_CONTENT_ONCE;
6701
17.1k
      }
6702
31.7k
  }
6703
38.7k
  SKIP_BLANKS_PE;
6704
38.7k
  GROW;
6705
38.7k
    }
6706
53.3k
    if ((cur != NULL) && (last != NULL)) {
6707
13.4k
        cur->c2 = last;
6708
13.4k
  if (last != NULL)
6709
13.4k
      last->parent = cur;
6710
13.4k
    }
6711
53.3k
    if (ctxt->input->id != inputchk) {
6712
524
  xmlFatalErrMsg(ctxt, XML_ERR_ENTITY_BOUNDARY,
6713
524
                       "Element content declaration doesn't start and stop in"
6714
524
                       " the same entity\n");
6715
524
    }
6716
53.3k
    NEXT;
6717
53.3k
    if (RAW == '?') {
6718
2.36k
  if (ret != NULL) {
6719
2.36k
      if ((ret->ocur == XML_ELEMENT_CONTENT_PLUS) ||
6720
1.82k
          (ret->ocur == XML_ELEMENT_CONTENT_MULT))
6721
1.16k
          ret->ocur = XML_ELEMENT_CONTENT_MULT;
6722
1.20k
      else
6723
1.20k
          ret->ocur = XML_ELEMENT_CONTENT_OPT;
6724
2.36k
  }
6725
2.36k
  NEXT;
6726
51.0k
    } else if (RAW == '*') {
6727
6.16k
  if (ret != NULL) {
6728
6.16k
      ret->ocur = XML_ELEMENT_CONTENT_MULT;
6729
6.16k
      cur = ret;
6730
      /*
6731
       * Some normalization:
6732
       * (a | b* | c?)* == (a | b | c)*
6733
       */
6734
13.2k
      while ((cur != NULL) && (cur->type == XML_ELEMENT_CONTENT_OR)) {
6735
7.06k
    if ((cur->c1 != NULL) &&
6736
7.06k
              ((cur->c1->ocur == XML_ELEMENT_CONTENT_OPT) ||
6737
6.67k
         (cur->c1->ocur == XML_ELEMENT_CONTENT_MULT)))
6738
1.88k
        cur->c1->ocur = XML_ELEMENT_CONTENT_ONCE;
6739
7.06k
    if ((cur->c2 != NULL) &&
6740
7.06k
              ((cur->c2->ocur == XML_ELEMENT_CONTENT_OPT) ||
6741
6.35k
         (cur->c2->ocur == XML_ELEMENT_CONTENT_MULT)))
6742
943
        cur->c2->ocur = XML_ELEMENT_CONTENT_ONCE;
6743
7.06k
    cur = cur->c2;
6744
7.06k
      }
6745
6.16k
  }
6746
6.16k
  NEXT;
6747
44.8k
    } else if (RAW == '+') {
6748
3.21k
  if (ret != NULL) {
6749
3.21k
      int found = 0;
6750
6751
3.21k
      if ((ret->ocur == XML_ELEMENT_CONTENT_OPT) ||
6752
2.93k
          (ret->ocur == XML_ELEMENT_CONTENT_MULT))
6753
887
          ret->ocur = XML_ELEMENT_CONTENT_MULT;
6754
2.32k
      else
6755
2.32k
          ret->ocur = XML_ELEMENT_CONTENT_PLUS;
6756
      /*
6757
       * Some normalization:
6758
       * (a | b*)+ == (a | b)*
6759
       * (a | b?)+ == (a | b)*
6760
       */
6761
7.59k
      while ((cur != NULL) && (cur->type == XML_ELEMENT_CONTENT_OR)) {
6762
4.38k
    if ((cur->c1 != NULL) &&
6763
4.38k
              ((cur->c1->ocur == XML_ELEMENT_CONTENT_OPT) ||
6764
3.97k
         (cur->c1->ocur == XML_ELEMENT_CONTENT_MULT))) {
6765
864
        cur->c1->ocur = XML_ELEMENT_CONTENT_ONCE;
6766
864
        found = 1;
6767
864
    }
6768
4.38k
    if ((cur->c2 != NULL) &&
6769
4.38k
              ((cur->c2->ocur == XML_ELEMENT_CONTENT_OPT) ||
6770
3.70k
         (cur->c2->ocur == XML_ELEMENT_CONTENT_MULT))) {
6771
1.26k
        cur->c2->ocur = XML_ELEMENT_CONTENT_ONCE;
6772
1.26k
        found = 1;
6773
1.26k
    }
6774
4.38k
    cur = cur->c2;
6775
4.38k
      }
6776
3.21k
      if (found)
6777
1.13k
    ret->ocur = XML_ELEMENT_CONTENT_MULT;
6778
3.21k
  }
6779
3.21k
  NEXT;
6780
3.21k
    }
6781
53.3k
    return(ret);
6782
61.7k
}
6783
6784
/**
6785
 * xmlParseElementChildrenContentDecl:
6786
 * @ctxt:  an XML parser context
6787
 * @inputchk:  the input used for the current entity, needed for boundary checks
6788
 *
6789
 * DEPRECATED: Internal function, don't use.
6790
 *
6791
 * parse the declaration for a Mixed Element content
6792
 * The leading '(' and spaces have been skipped in xmlParseElementContentDecl
6793
 *
6794
 * [47] children ::= (choice | seq) ('?' | '*' | '+')?
6795
 *
6796
 * [48] cp ::= (Name | choice | seq) ('?' | '*' | '+')?
6797
 *
6798
 * [49] choice ::= '(' S? cp ( S? '|' S? cp )* S? ')'
6799
 *
6800
 * [50] seq ::= '(' S? cp ( S? ',' S? cp )* S? ')'
6801
 *
6802
 * [ VC: Proper Group/PE Nesting ] applies to [49] and [50]
6803
 * TODO Parameter-entity replacement text must be properly nested
6804
 *  with parenthesized groups. That is to say, if either of the
6805
 *  opening or closing parentheses in a choice, seq, or Mixed
6806
 *  construct is contained in the replacement text for a parameter
6807
 *  entity, both must be contained in the same replacement text. For
6808
 *  interoperability, if a parameter-entity reference appears in a
6809
 *  choice, seq, or Mixed construct, its replacement text should not
6810
 *  be empty, and neither the first nor last non-blank character of
6811
 *  the replacement text should be a connector (| or ,).
6812
 *
6813
 * Returns the tree of xmlElementContentPtr describing the element
6814
 *          hierarchy.
6815
 */
6816
xmlElementContentPtr
6817
0
xmlParseElementChildrenContentDecl(xmlParserCtxtPtr ctxt, int inputchk) {
6818
    /* stub left for API/ABI compat */
6819
0
    return(xmlParseElementChildrenContentDeclPriv(ctxt, inputchk, 1));
6820
0
}
6821
6822
/**
6823
 * xmlParseElementContentDecl:
6824
 * @ctxt:  an XML parser context
6825
 * @name:  the name of the element being defined.
6826
 * @result:  the Element Content pointer will be stored here if any
6827
 *
6828
 * DEPRECATED: Internal function, don't use.
6829
 *
6830
 * parse the declaration for an Element content either Mixed or Children,
6831
 * the cases EMPTY and ANY are handled directly in xmlParseElementDecl
6832
 *
6833
 * [46] contentspec ::= 'EMPTY' | 'ANY' | Mixed | children
6834
 *
6835
 * returns: the type of element content XML_ELEMENT_TYPE_xxx
6836
 */
6837
6838
int
6839
xmlParseElementContentDecl(xmlParserCtxtPtr ctxt, const xmlChar *name,
6840
49.7k
                           xmlElementContentPtr *result) {
6841
6842
49.7k
    xmlElementContentPtr tree = NULL;
6843
49.7k
    int inputid = ctxt->input->id;
6844
49.7k
    int res;
6845
6846
49.7k
    *result = NULL;
6847
6848
49.7k
    if (RAW != '(') {
6849
0
  xmlFatalErrMsgStr(ctxt, XML_ERR_ELEMCONTENT_NOT_STARTED,
6850
0
    "xmlParseElementContentDecl : %s '(' expected\n", name);
6851
0
  return(-1);
6852
0
    }
6853
49.7k
    NEXT;
6854
49.7k
    GROW;
6855
49.7k
    SKIP_BLANKS_PE;
6856
49.7k
    if (CMP7(CUR_PTR, '#', 'P', 'C', 'D', 'A', 'T', 'A')) {
6857
15.5k
        tree = xmlParseElementMixedContentDecl(ctxt, inputid);
6858
15.5k
  res = XML_ELEMENT_TYPE_MIXED;
6859
34.1k
    } else {
6860
34.1k
        tree = xmlParseElementChildrenContentDeclPriv(ctxt, inputid, 1);
6861
34.1k
  res = XML_ELEMENT_TYPE_ELEMENT;
6862
34.1k
    }
6863
49.7k
    SKIP_BLANKS_PE;
6864
49.7k
    *result = tree;
6865
49.7k
    return(res);
6866
49.7k
}
6867
6868
/**
6869
 * xmlParseElementDecl:
6870
 * @ctxt:  an XML parser context
6871
 *
6872
 * DEPRECATED: Internal function, don't use.
6873
 *
6874
 * Parse an element declaration. Always consumes '<!'.
6875
 *
6876
 * [45] elementdecl ::= '<!ELEMENT' S Name S contentspec S? '>'
6877
 *
6878
 * [ VC: Unique Element Type Declaration ]
6879
 * No element type may be declared more than once
6880
 *
6881
 * Returns the type of the element, or -1 in case of error
6882
 */
6883
int
6884
66.8k
xmlParseElementDecl(xmlParserCtxtPtr ctxt) {
6885
66.8k
    const xmlChar *name;
6886
66.8k
    int ret = -1;
6887
66.8k
    xmlElementContentPtr content  = NULL;
6888
6889
66.8k
    if ((CUR != '<') || (NXT(1) != '!'))
6890
0
        return(ret);
6891
66.8k
    SKIP(2);
6892
6893
    /* GROW; done in the caller */
6894
66.8k
    if (CMP7(CUR_PTR, 'E', 'L', 'E', 'M', 'E', 'N', 'T')) {
6895
65.0k
  int inputid = ctxt->input->id;
6896
6897
65.0k
  SKIP(7);
6898
65.0k
  if (SKIP_BLANKS_PE == 0) {
6899
635
      xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED,
6900
635
               "Space required after 'ELEMENT'\n");
6901
635
      return(-1);
6902
635
  }
6903
64.4k
        name = xmlParseName(ctxt);
6904
64.4k
  if (name == NULL) {
6905
420
      xmlFatalErrMsg(ctxt, XML_ERR_NAME_REQUIRED,
6906
420
         "xmlParseElementDecl: no name for Element\n");
6907
420
      return(-1);
6908
420
  }
6909
64.0k
  if (SKIP_BLANKS_PE == 0) {
6910
3.41k
      xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED,
6911
3.41k
         "Space required after the element name\n");
6912
3.41k
  }
6913
64.0k
  if (CMP5(CUR_PTR, 'E', 'M', 'P', 'T', 'Y')) {
6914
10.4k
      SKIP(5);
6915
      /*
6916
       * Element must always be empty.
6917
       */
6918
10.4k
      ret = XML_ELEMENT_TYPE_EMPTY;
6919
53.5k
  } else if ((RAW == 'A') && (NXT(1) == 'N') &&
6920
823
             (NXT(2) == 'Y')) {
6921
595
      SKIP(3);
6922
      /*
6923
       * Element is a generic container.
6924
       */
6925
595
      ret = XML_ELEMENT_TYPE_ANY;
6926
52.9k
  } else if (RAW == '(') {
6927
49.7k
      ret = xmlParseElementContentDecl(ctxt, name, &content);
6928
49.7k
  } else {
6929
      /*
6930
       * [ WFC: PEs in Internal Subset ] error handling.
6931
       */
6932
3.17k
            xmlFatalErrMsg(ctxt, XML_ERR_ELEMCONTENT_NOT_STARTED,
6933
3.17k
                  "xmlParseElementDecl: 'EMPTY', 'ANY' or '(' expected\n");
6934
3.17k
      return(-1);
6935
3.17k
  }
6936
6937
60.8k
  SKIP_BLANKS_PE;
6938
6939
60.8k
  if (RAW != '>') {
6940
8.72k
      xmlFatalErr(ctxt, XML_ERR_GT_REQUIRED, NULL);
6941
8.72k
      if (content != NULL) {
6942
1.32k
    xmlFreeDocElementContent(ctxt->myDoc, content);
6943
1.32k
      }
6944
52.1k
  } else {
6945
52.1k
      if (inputid != ctxt->input->id) {
6946
282
    xmlFatalErrMsg(ctxt, XML_ERR_ENTITY_BOUNDARY,
6947
282
                               "Element declaration doesn't start and stop in"
6948
282
                               " the same entity\n");
6949
282
      }
6950
6951
52.1k
      NEXT;
6952
52.1k
      if ((ctxt->sax != NULL) && (!ctxt->disableSAX) &&
6953
43.6k
    (ctxt->sax->elementDecl != NULL)) {
6954
43.6k
    if (content != NULL)
6955
37.3k
        content->parent = NULL;
6956
43.6k
          ctxt->sax->elementDecl(ctxt->userData, name, ret,
6957
43.6k
                           content);
6958
43.6k
    if ((content != NULL) && (content->parent == NULL)) {
6959
        /*
6960
         * this is a trick: if xmlAddElementDecl is called,
6961
         * instead of copying the full tree it is plugged directly
6962
         * if called from the parser. Avoid duplicating the
6963
         * interfaces or change the API/ABI
6964
         */
6965
453
        xmlFreeDocElementContent(ctxt->myDoc, content);
6966
453
    }
6967
43.6k
      } else if (content != NULL) {
6968
3.36k
    xmlFreeDocElementContent(ctxt->myDoc, content);
6969
3.36k
      }
6970
52.1k
  }
6971
60.8k
    }
6972
62.5k
    return(ret);
6973
66.8k
}
6974
6975
/**
6976
 * xmlParseConditionalSections
6977
 * @ctxt:  an XML parser context
6978
 *
6979
 * Parse a conditional section. Always consumes '<!['.
6980
 *
6981
 * [61] conditionalSect ::= includeSect | ignoreSect
6982
 * [62] includeSect ::= '<![' S? 'INCLUDE' S? '[' extSubsetDecl ']]>'
6983
 * [63] ignoreSect ::= '<![' S? 'IGNORE' S? '[' ignoreSectContents* ']]>'
6984
 * [64] ignoreSectContents ::= Ignore ('<![' ignoreSectContents ']]>' Ignore)*
6985
 * [65] Ignore ::= Char* - (Char* ('<![' | ']]>') Char*)
6986
 */
6987
6988
static void
6989
11.1k
xmlParseConditionalSections(xmlParserCtxtPtr ctxt) {
6990
11.1k
    int *inputIds = NULL;
6991
11.1k
    size_t inputIdsSize = 0;
6992
11.1k
    size_t depth = 0;
6993
6994
23.7k
    while (PARSER_STOPPED(ctxt) == 0) {
6995
23.7k
        if ((RAW == '<') && (NXT(1) == '!') && (NXT(2) == '[')) {
6996
11.7k
            int id = ctxt->input->id;
6997
6998
11.7k
            SKIP(3);
6999
11.7k
            SKIP_BLANKS_PE;
7000
7001
11.7k
            if (CMP7(CUR_PTR, 'I', 'N', 'C', 'L', 'U', 'D', 'E')) {
7002
7.52k
                SKIP(7);
7003
7.52k
                SKIP_BLANKS_PE;
7004
7.52k
                if (RAW != '[') {
7005
416
                    xmlFatalErr(ctxt, XML_ERR_CONDSEC_INVALID, NULL);
7006
416
                    xmlHaltParser(ctxt);
7007
416
                    goto error;
7008
416
                }
7009
7.11k
                if (ctxt->input->id != id) {
7010
5.35k
                    xmlFatalErrMsg(ctxt, XML_ERR_ENTITY_BOUNDARY,
7011
5.35k
                                   "All markup of the conditional section is"
7012
5.35k
                                   " not in the same entity\n");
7013
5.35k
                }
7014
7.11k
                NEXT;
7015
7016
7.11k
                if (inputIdsSize <= depth) {
7017
6.87k
                    int *tmp;
7018
6.87k
                    int newSize;
7019
7020
6.87k
                    newSize = xmlGrowCapacity(inputIdsSize, sizeof(tmp[0]),
7021
6.87k
                                              4, 1000);
7022
6.87k
                    if (newSize < 0) {
7023
0
                        xmlFatalErrMsg(ctxt, XML_ERR_RESOURCE_LIMIT,
7024
0
                                       "Maximum conditional section nesting"
7025
0
                                       " depth exceeded\n");
7026
0
                        goto error;
7027
0
                    }
7028
6.87k
                    tmp = xmlRealloc(inputIds, newSize * sizeof(tmp[0]));
7029
6.87k
                    if (tmp == NULL) {
7030
2
                        xmlErrMemory(ctxt);
7031
2
                        goto error;
7032
2
                    }
7033
6.87k
                    inputIds = tmp;
7034
6.87k
                    inputIdsSize = newSize;
7035
6.87k
                }
7036
7.11k
                inputIds[depth] = id;
7037
7.11k
                depth++;
7038
7.11k
            } else if (CMP6(CUR_PTR, 'I', 'G', 'N', 'O', 'R', 'E')) {
7039
1.42k
                size_t ignoreDepth = 0;
7040
7041
1.42k
                SKIP(6);
7042
1.42k
                SKIP_BLANKS_PE;
7043
1.42k
                if (RAW != '[') {
7044
271
                    xmlFatalErr(ctxt, XML_ERR_CONDSEC_INVALID, NULL);
7045
271
                    xmlHaltParser(ctxt);
7046
271
                    goto error;
7047
271
                }
7048
1.15k
                if (ctxt->input->id != id) {
7049
236
                    xmlFatalErrMsg(ctxt, XML_ERR_ENTITY_BOUNDARY,
7050
236
                                   "All markup of the conditional section is"
7051
236
                                   " not in the same entity\n");
7052
236
                }
7053
1.15k
                NEXT;
7054
7055
2.13M
                while (PARSER_STOPPED(ctxt) == 0) {
7056
2.13M
                    if (RAW == 0) {
7057
869
                        xmlFatalErr(ctxt, XML_ERR_CONDSEC_NOT_FINISHED, NULL);
7058
869
                        goto error;
7059
869
                    }
7060
2.13M
                    if ((RAW == '<') && (NXT(1) == '!') && (NXT(2) == '[')) {
7061
4.80k
                        SKIP(3);
7062
4.80k
                        ignoreDepth++;
7063
                        /* Check for integer overflow */
7064
4.80k
                        if (ignoreDepth == 0) {
7065
0
                            xmlErrMemory(ctxt);
7066
0
                            goto error;
7067
0
                        }
7068
2.13M
                    } else if ((RAW == ']') && (NXT(1) == ']') &&
7069
3.50k
                               (NXT(2) == '>')) {
7070
3.21k
                        SKIP(3);
7071
3.21k
                        if (ignoreDepth == 0)
7072
282
                            break;
7073
2.93k
                        ignoreDepth--;
7074
2.13M
                    } else {
7075
2.13M
                        NEXT;
7076
2.13M
                    }
7077
2.13M
                }
7078
7079
284
                if (ctxt->input->id != id) {
7080
236
                    xmlFatalErrMsg(ctxt, XML_ERR_ENTITY_BOUNDARY,
7081
236
                                   "All markup of the conditional section is"
7082
236
                                   " not in the same entity\n");
7083
236
                }
7084
2.79k
            } else {
7085
2.79k
                xmlFatalErr(ctxt, XML_ERR_CONDSEC_INVALID_KEYWORD, NULL);
7086
2.79k
                xmlHaltParser(ctxt);
7087
2.79k
                goto error;
7088
2.79k
            }
7089
12.0k
        } else if ((depth > 0) &&
7090
12.0k
                   (RAW == ']') && (NXT(1) == ']') && (NXT(2) == '>')) {
7091
506
            depth--;
7092
506
            if (ctxt->input->id != inputIds[depth]) {
7093
246
                xmlFatalErrMsg(ctxt, XML_ERR_ENTITY_BOUNDARY,
7094
246
                               "All markup of the conditional section is not"
7095
246
                               " in the same entity\n");
7096
246
            }
7097
506
            SKIP(3);
7098
11.4k
        } else if ((RAW == '<') && ((NXT(1) == '!') || (NXT(1) == '?'))) {
7099
5.30k
            xmlParseMarkupDecl(ctxt);
7100
6.19k
        } else {
7101
6.19k
            xmlFatalErr(ctxt, XML_ERR_EXT_SUBSET_NOT_FINISHED, NULL);
7102
6.19k
            xmlHaltParser(ctxt);
7103
6.19k
            goto error;
7104
6.19k
        }
7105
7106
13.2k
        if (depth == 0)
7107
532
            break;
7108
7109
12.6k
        SKIP_BLANKS_PE;
7110
12.6k
        SHRINK;
7111
12.6k
        GROW;
7112
12.6k
    }
7113
7114
11.1k
error:
7115
11.1k
    xmlFree(inputIds);
7116
11.1k
}
7117
7118
/**
7119
 * xmlParseMarkupDecl:
7120
 * @ctxt:  an XML parser context
7121
 *
7122
 * DEPRECATED: Internal function, don't use.
7123
 *
7124
 * Parse markup declarations. Always consumes '<!' or '<?'.
7125
 *
7126
 * [29] markupdecl ::= elementdecl | AttlistDecl | EntityDecl |
7127
 *                     NotationDecl | PI | Comment
7128
 *
7129
 * [ VC: Proper Declaration/PE Nesting ]
7130
 * Parameter-entity replacement text must be properly nested with
7131
 * markup declarations. That is to say, if either the first character
7132
 * or the last character of a markup declaration (markupdecl above) is
7133
 * contained in the replacement text for a parameter-entity reference,
7134
 * both must be contained in the same replacement text.
7135
 *
7136
 * [ WFC: PEs in Internal Subset ]
7137
 * In the internal DTD subset, parameter-entity references can occur
7138
 * only where markup declarations can occur, not within markup declarations.
7139
 * (This does not apply to references that occur in external parameter
7140
 * entities or to the external subset.)
7141
 */
7142
void
7143
454k
xmlParseMarkupDecl(xmlParserCtxtPtr ctxt) {
7144
454k
    GROW;
7145
454k
    if (CUR == '<') {
7146
454k
        if (NXT(1) == '!') {
7147
441k
      switch (NXT(2)) {
7148
297k
          case 'E':
7149
297k
        if (NXT(3) == 'L')
7150
66.8k
      xmlParseElementDecl(ctxt);
7151
230k
        else if (NXT(3) == 'N')
7152
230k
      xmlParseEntityDecl(ctxt);
7153
412
                    else
7154
412
                        SKIP(2);
7155
297k
        break;
7156
67.2k
          case 'A':
7157
67.2k
        xmlParseAttributeListDecl(ctxt);
7158
67.2k
        break;
7159
11.3k
          case 'N':
7160
11.3k
        xmlParseNotationDecl(ctxt);
7161
11.3k
        break;
7162
63.5k
          case '-':
7163
63.5k
        xmlParseComment(ctxt);
7164
63.5k
        break;
7165
1.38k
    default:
7166
1.38k
                    xmlFatalErr(ctxt,
7167
1.38k
                                ctxt->inSubset == 2 ?
7168
382
                                    XML_ERR_EXT_SUBSET_NOT_FINISHED :
7169
1.38k
                                    XML_ERR_INT_SUBSET_NOT_FINISHED,
7170
1.38k
                                NULL);
7171
1.38k
                    SKIP(2);
7172
1.38k
        break;
7173
441k
      }
7174
441k
  } else if (NXT(1) == '?') {
7175
13.0k
      xmlParsePI(ctxt);
7176
13.0k
  }
7177
454k
    }
7178
454k
}
7179
7180
/**
7181
 * xmlParseTextDecl:
7182
 * @ctxt:  an XML parser context
7183
 *
7184
 * DEPRECATED: Internal function, don't use.
7185
 *
7186
 * parse an XML declaration header for external entities
7187
 *
7188
 * [77] TextDecl ::= '<?xml' VersionInfo? EncodingDecl S? '?>'
7189
 */
7190
7191
void
7192
26.3k
xmlParseTextDecl(xmlParserCtxtPtr ctxt) {
7193
26.3k
    xmlChar *version;
7194
7195
    /*
7196
     * We know that '<?xml' is here.
7197
     */
7198
26.3k
    if ((CMP5(CUR_PTR, '<', '?', 'x', 'm', 'l')) && (IS_BLANK_CH(NXT(5)))) {
7199
26.0k
  SKIP(5);
7200
26.0k
    } else {
7201
259
  xmlFatalErr(ctxt, XML_ERR_XMLDECL_NOT_STARTED, NULL);
7202
259
  return;
7203
259
    }
7204
7205
26.0k
    if (SKIP_BLANKS == 0) {
7206
0
  xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED,
7207
0
           "Space needed after '<?xml'\n");
7208
0
    }
7209
7210
    /*
7211
     * We may have the VersionInfo here.
7212
     */
7213
26.0k
    version = xmlParseVersionInfo(ctxt);
7214
26.0k
    if (version == NULL) {
7215
17.6k
  version = xmlCharStrdup(XML_DEFAULT_VERSION);
7216
17.6k
        if (version == NULL) {
7217
5
            xmlErrMemory(ctxt);
7218
5
            return;
7219
5
        }
7220
17.6k
    } else {
7221
8.44k
  if (SKIP_BLANKS == 0) {
7222
4.20k
      xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED,
7223
4.20k
               "Space needed here\n");
7224
4.20k
  }
7225
8.44k
    }
7226
26.0k
    ctxt->input->version = version;
7227
7228
    /*
7229
     * We must have the encoding declaration
7230
     */
7231
26.0k
    xmlParseEncodingDecl(ctxt);
7232
7233
26.0k
    SKIP_BLANKS;
7234
26.0k
    if ((RAW == '?') && (NXT(1) == '>')) {
7235
3.62k
        SKIP(2);
7236
22.4k
    } else if (RAW == '>') {
7237
        /* Deprecated old WD ... */
7238
315
  xmlFatalErr(ctxt, XML_ERR_XMLDECL_NOT_FINISHED, NULL);
7239
315
  NEXT;
7240
22.1k
    } else {
7241
22.1k
        int c;
7242
7243
22.1k
  xmlFatalErr(ctxt, XML_ERR_XMLDECL_NOT_FINISHED, NULL);
7244
514k
        while ((PARSER_STOPPED(ctxt) == 0) && ((c = CUR) != 0)) {
7245
511k
            NEXT;
7246
511k
            if (c == '>')
7247
19.1k
                break;
7248
511k
        }
7249
22.1k
    }
7250
26.0k
}
7251
7252
/**
7253
 * xmlParseExternalSubset:
7254
 * @ctxt:  an XML parser context
7255
 * @ExternalID: the external identifier
7256
 * @SystemID: the system identifier (or URL)
7257
 *
7258
 * DEPRECATED: Internal function, don't use.
7259
 *
7260
 * parse Markup declarations from an external subset
7261
 *
7262
 * [30] extSubset ::= textDecl? extSubsetDecl
7263
 *
7264
 * [31] extSubsetDecl ::= (markupdecl | conditionalSect | PEReference | S) *
7265
 */
7266
void
7267
xmlParseExternalSubset(xmlParserCtxtPtr ctxt, const xmlChar *ExternalID,
7268
13.6k
                       const xmlChar *SystemID) {
7269
13.6k
    int oldInputNr;
7270
7271
13.6k
    xmlCtxtInitializeLate(ctxt);
7272
7273
13.6k
    xmlDetectEncoding(ctxt);
7274
7275
13.6k
    if (CMP5(CUR_PTR, '<', '?', 'x', 'm', 'l')) {
7276
7.01k
  xmlParseTextDecl(ctxt);
7277
7.01k
    }
7278
13.6k
    if (ctxt->myDoc == NULL) {
7279
0
        ctxt->myDoc = xmlNewDoc(BAD_CAST "1.0");
7280
0
  if (ctxt->myDoc == NULL) {
7281
0
      xmlErrMemory(ctxt);
7282
0
      return;
7283
0
  }
7284
0
  ctxt->myDoc->properties = XML_DOC_INTERNAL;
7285
0
    }
7286
13.6k
    if ((ctxt->myDoc != NULL) && (ctxt->myDoc->intSubset == NULL) &&
7287
0
        (xmlCreateIntSubset(ctxt->myDoc, NULL, ExternalID, SystemID) == NULL)) {
7288
0
        xmlErrMemory(ctxt);
7289
0
    }
7290
7291
13.6k
    ctxt->inSubset = 2;
7292
13.6k
    oldInputNr = ctxt->inputNr;
7293
7294
13.6k
    SKIP_BLANKS_PE;
7295
56.3k
    while (((RAW != 0) || (ctxt->inputNr > oldInputNr)) &&
7296
52.9k
           (!PARSER_STOPPED(ctxt))) {
7297
48.8k
  GROW;
7298
48.8k
        if ((RAW == '<') && (NXT(1) == '!') && (NXT(2) == '[')) {
7299
3.32k
            xmlParseConditionalSections(ctxt);
7300
45.5k
        } else if ((RAW == '<') && ((NXT(1) == '!') || (NXT(1) == '?'))) {
7301
39.3k
            xmlParseMarkupDecl(ctxt);
7302
39.3k
        } else {
7303
6.19k
            xmlFatalErr(ctxt, XML_ERR_EXT_SUBSET_NOT_FINISHED, NULL);
7304
6.19k
            xmlHaltParser(ctxt);
7305
6.19k
            return;
7306
6.19k
        }
7307
42.6k
        SKIP_BLANKS_PE;
7308
42.6k
        SHRINK;
7309
42.6k
    }
7310
7311
8.17k
    while (ctxt->inputNr > oldInputNr)
7312
724
        xmlPopPE(ctxt);
7313
7314
7.45k
    xmlParserCheckEOF(ctxt, XML_ERR_EXT_SUBSET_NOT_FINISHED);
7315
7.45k
}
7316
7317
/**
7318
 * xmlParseReference:
7319
 * @ctxt:  an XML parser context
7320
 *
7321
 * DEPRECATED: Internal function, don't use.
7322
 *
7323
 * parse and handle entity references in content, depending on the SAX
7324
 * interface, this may end-up in a call to character() if this is a
7325
 * CharRef, a predefined entity, if there is no reference() callback.
7326
 * or if the parser was asked to switch to that mode.
7327
 *
7328
 * Always consumes '&'.
7329
 *
7330
 * [67] Reference ::= EntityRef | CharRef
7331
 */
7332
void
7333
373k
xmlParseReference(xmlParserCtxtPtr ctxt) {
7334
373k
    xmlEntityPtr ent = NULL;
7335
373k
    const xmlChar *name;
7336
373k
    xmlChar *val;
7337
7338
373k
    if (RAW != '&')
7339
0
        return;
7340
7341
    /*
7342
     * Simple case of a CharRef
7343
     */
7344
373k
    if (NXT(1) == '#') {
7345
32.7k
  int i = 0;
7346
32.7k
  xmlChar out[16];
7347
32.7k
  int value = xmlParseCharRef(ctxt);
7348
7349
32.7k
  if (value == 0)
7350
10.5k
      return;
7351
7352
        /*
7353
         * Just encode the value in UTF-8
7354
         */
7355
22.1k
        COPY_BUF(out, i, value);
7356
22.1k
        out[i] = 0;
7357
22.1k
        if ((ctxt->sax != NULL) && (ctxt->sax->characters != NULL) &&
7358
22.1k
            (!ctxt->disableSAX))
7359
12.0k
            ctxt->sax->characters(ctxt->userData, out, i);
7360
22.1k
  return;
7361
32.7k
    }
7362
7363
    /*
7364
     * We are seeing an entity reference
7365
     */
7366
340k
    name = xmlParseEntityRefInternal(ctxt);
7367
340k
    if (name == NULL)
7368
242k
        return;
7369
98.2k
    ent = xmlLookupGeneralEntity(ctxt, name, /* isAttr */ 0);
7370
98.2k
    if (ent == NULL) {
7371
        /*
7372
         * Create a reference for undeclared entities.
7373
         */
7374
28.3k
        if ((ctxt->replaceEntities == 0) &&
7375
2.49k
            (ctxt->sax != NULL) &&
7376
2.49k
            (ctxt->disableSAX == 0) &&
7377
2.49k
            (ctxt->sax->reference != NULL)) {
7378
2.49k
            ctxt->sax->reference(ctxt->userData, name);
7379
2.49k
        }
7380
28.3k
        return;
7381
28.3k
    }
7382
69.9k
    if (!ctxt->wellFormed)
7383
46.4k
  return;
7384
7385
    /* special case of predefined entities */
7386
23.4k
    if ((ent->name == NULL) ||
7387
23.4k
        (ent->etype == XML_INTERNAL_PREDEFINED_ENTITY)) {
7388
10.8k
  val = ent->content;
7389
10.8k
  if (val == NULL) return;
7390
  /*
7391
   * inline the entity.
7392
   */
7393
10.8k
  if ((ctxt->sax != NULL) && (ctxt->sax->characters != NULL) &&
7394
10.8k
      (!ctxt->disableSAX))
7395
10.8k
      ctxt->sax->characters(ctxt->userData, val, xmlStrlen(val));
7396
10.8k
  return;
7397
10.8k
    }
7398
7399
    /*
7400
     * Some users try to parse entities on their own and used to set
7401
     * the renamed "checked" member. Fix the flags to cover this
7402
     * case.
7403
     */
7404
12.6k
    if (((ent->flags & XML_ENT_PARSED) == 0) && (ent->children != NULL))
7405
0
        ent->flags |= XML_ENT_PARSED;
7406
7407
    /*
7408
     * The first reference to the entity trigger a parsing phase
7409
     * where the ent->children is filled with the result from
7410
     * the parsing.
7411
     * Note: external parsed entities will not be loaded, it is not
7412
     * required for a non-validating parser, unless the parsing option
7413
     * of validating, or substituting entities were given. Doing so is
7414
     * far more secure as the parser will only process data coming from
7415
     * the document entity by default.
7416
     *
7417
     * FIXME: This doesn't work correctly since entities can be
7418
     * expanded with different namespace declarations in scope.
7419
     * For example:
7420
     *
7421
     * <!DOCTYPE doc [
7422
     *   <!ENTITY ent "<ns:elem/>">
7423
     * ]>
7424
     * <doc>
7425
     *   <decl1 xmlns:ns="urn:ns1">
7426
     *     &ent;
7427
     *   </decl1>
7428
     *   <decl2 xmlns:ns="urn:ns2">
7429
     *     &ent;
7430
     *   </decl2>
7431
     * </doc>
7432
     *
7433
     * Proposed fix:
7434
     *
7435
     * - Ignore current namespace declarations when parsing the
7436
     *   entity. If a prefix can't be resolved, don't report an error
7437
     *   but mark it as unresolved.
7438
     * - Try to resolve these prefixes when expanding the entity.
7439
     *   This will require a specialized version of xmlStaticCopyNode
7440
     *   which can also make use of the namespace hash table to avoid
7441
     *   quadratic behavior.
7442
     *
7443
     * Alternatively, we could simply reparse the entity on each
7444
     * expansion like we already do with custom SAX callbacks.
7445
     * External entity content should be cached in this case.
7446
     */
7447
12.6k
    if ((ent->etype == XML_INTERNAL_GENERAL_ENTITY) ||
7448
10.0k
        (((ctxt->options & XML_PARSE_NO_XXE) == 0) &&
7449
10.0k
         ((ctxt->replaceEntities) ||
7450
12.6k
          (ctxt->validate)))) {
7451
12.6k
        if ((ent->flags & XML_ENT_PARSED) == 0) {
7452
11.2k
            xmlCtxtParseEntity(ctxt, ent);
7453
11.2k
        } else if (ent->children == NULL) {
7454
            /*
7455
             * Probably running in SAX mode and the callbacks don't
7456
             * build the entity content. Parse the entity again.
7457
             *
7458
             * This will also be triggered in normal tree builder mode
7459
             * if an entity happens to be empty, causing unnecessary
7460
             * reloads. It's hard to come up with a reliable check in
7461
             * which mode we're running.
7462
             */
7463
384
            xmlCtxtParseEntity(ctxt, ent);
7464
384
        }
7465
12.6k
    }
7466
7467
    /*
7468
     * We also check for amplification if entities aren't substituted.
7469
     * They might be expanded later.
7470
     */
7471
12.6k
    if (xmlParserEntityCheck(ctxt, ent->expandedSize))
7472
9
        return;
7473
7474
12.6k
    if ((ctxt->sax == NULL) || (ctxt->disableSAX))
7475
8.25k
        return;
7476
7477
4.35k
    if (ctxt->replaceEntities == 0) {
7478
  /*
7479
   * Create a reference
7480
   */
7481
25
        if (ctxt->sax->reference != NULL)
7482
25
      ctxt->sax->reference(ctxt->userData, ent->name);
7483
4.33k
    } else if ((ent->children != NULL) && (ctxt->node != NULL)) {
7484
3.13k
        xmlNodePtr copy, cur;
7485
7486
        /*
7487
         * Seems we are generating the DOM content, copy the tree
7488
   */
7489
3.13k
        cur = ent->children;
7490
7491
        /*
7492
         * Handle first text node with SAX to coalesce text efficiently
7493
         */
7494
3.13k
        if ((cur->type == XML_TEXT_NODE) ||
7495
2.08k
            (cur->type == XML_CDATA_SECTION_NODE)) {
7496
2.08k
            int len = xmlStrlen(cur->content);
7497
7498
2.08k
            if ((cur->type == XML_TEXT_NODE) ||
7499
2.08k
                (ctxt->options & XML_PARSE_NOCDATA)) {
7500
2.08k
                if (ctxt->sax->characters != NULL)
7501
2.08k
                    ctxt->sax->characters(ctxt, cur->content, len);
7502
2.08k
            } else {
7503
0
                if (ctxt->sax->cdataBlock != NULL)
7504
0
                    ctxt->sax->cdataBlock(ctxt, cur->content, len);
7505
0
            }
7506
7507
2.08k
            cur = cur->next;
7508
2.08k
        }
7509
7510
7.37k
        while (cur != NULL) {
7511
5.35k
            xmlNodePtr last;
7512
7513
            /*
7514
             * Handle last text node with SAX to coalesce text efficiently
7515
             */
7516
5.35k
            if ((cur->next == NULL) &&
7517
1.48k
                ((cur->type == XML_TEXT_NODE) ||
7518
1.08k
                 (cur->type == XML_CDATA_SECTION_NODE))) {
7519
1.08k
                int len = xmlStrlen(cur->content);
7520
7521
1.08k
                if ((cur->type == XML_TEXT_NODE) ||
7522
1.08k
                    (ctxt->options & XML_PARSE_NOCDATA)) {
7523
1.08k
                    if (ctxt->sax->characters != NULL)
7524
1.08k
                        ctxt->sax->characters(ctxt, cur->content, len);
7525
1.08k
                } else {
7526
0
                    if (ctxt->sax->cdataBlock != NULL)
7527
0
                        ctxt->sax->cdataBlock(ctxt, cur->content, len);
7528
0
                }
7529
7530
1.08k
                break;
7531
1.08k
            }
7532
7533
            /*
7534
             * Reset coalesce buffer stats only for non-text nodes.
7535
             */
7536
4.27k
            ctxt->nodemem = 0;
7537
4.27k
            ctxt->nodelen = 0;
7538
7539
4.27k
            copy = xmlDocCopyNode(cur, ctxt->myDoc, 1);
7540
7541
4.27k
            if (copy == NULL) {
7542
27
                xmlErrMemory(ctxt);
7543
27
                break;
7544
27
            }
7545
7546
4.24k
            if (ctxt->parseMode == XML_PARSE_READER) {
7547
                /* Needed for reader */
7548
0
                copy->extra = cur->extra;
7549
                /* Maybe needed for reader */
7550
0
                copy->_private = cur->_private;
7551
0
            }
7552
7553
4.24k
            copy->parent = ctxt->node;
7554
4.24k
            last = ctxt->node->last;
7555
4.24k
            if (last == NULL) {
7556
238
                ctxt->node->children = copy;
7557
4.00k
            } else {
7558
4.00k
                last->next = copy;
7559
4.00k
                copy->prev = last;
7560
4.00k
            }
7561
4.24k
            ctxt->node->last = copy;
7562
7563
4.24k
            cur = cur->next;
7564
4.24k
        }
7565
3.13k
    }
7566
4.35k
}
7567
7568
static void
7569
208k
xmlHandleUndeclaredEntity(xmlParserCtxtPtr ctxt, const xmlChar *name) {
7570
    /*
7571
     * [ WFC: Entity Declared ]
7572
     * In a document without any DTD, a document with only an
7573
     * internal DTD subset which contains no parameter entity
7574
     * references, or a document with "standalone='yes'", the
7575
     * Name given in the entity reference must match that in an
7576
     * entity declaration, except that well-formed documents
7577
     * need not declare any of the following entities: amp, lt,
7578
     * gt, apos, quot.
7579
     * The declaration of a parameter entity must precede any
7580
     * reference to it.
7581
     * Similarly, the declaration of a general entity must
7582
     * precede any reference to it which appears in a default
7583
     * value in an attribute-list declaration. Note that if
7584
     * entities are declared in the external subset or in
7585
     * external parameter entities, a non-validating processor
7586
     * is not obligated to read and process their declarations;
7587
     * for such documents, the rule that an entity must be
7588
     * declared is a well-formedness constraint only if
7589
     * standalone='yes'.
7590
     */
7591
208k
    if ((ctxt->standalone == 1) ||
7592
208k
        ((ctxt->hasExternalSubset == 0) &&
7593
194k
         (ctxt->hasPErefs == 0))) {
7594
191k
        xmlFatalErrMsgStr(ctxt, XML_ERR_UNDECLARED_ENTITY,
7595
191k
                          "Entity '%s' not defined\n", name);
7596
191k
    } else if (ctxt->validate) {
7597
        /*
7598
         * [ VC: Entity Declared ]
7599
         * In a document with an external subset or external
7600
         * parameter entities with "standalone='no'", ...
7601
         * ... The declaration of a parameter entity must
7602
         * precede any reference to it...
7603
         */
7604
0
        xmlValidityError(ctxt, XML_ERR_UNDECLARED_ENTITY,
7605
0
                         "Entity '%s' not defined\n", name, NULL);
7606
16.5k
    } else if ((ctxt->loadsubset & ~XML_SKIP_IDS) ||
7607
216
               ((ctxt->replaceEntities) &&
7608
16.3k
                ((ctxt->options & XML_PARSE_NO_XXE) == 0))) {
7609
        /*
7610
         * Also raise a non-fatal error
7611
         *
7612
         * - if the external subset is loaded and all entity declarations
7613
         *   should be available, or
7614
         * - entity substition was requested without restricting
7615
         *   external entity access.
7616
         */
7617
16.3k
        xmlErrMsgStr(ctxt, XML_WAR_UNDECLARED_ENTITY,
7618
16.3k
                     "Entity '%s' not defined\n", name);
7619
16.3k
    } else {
7620
216
        xmlWarningMsg(ctxt, XML_WAR_UNDECLARED_ENTITY,
7621
216
                      "Entity '%s' not defined\n", name, NULL);
7622
216
    }
7623
7624
208k
    ctxt->valid = 0;
7625
208k
}
7626
7627
static xmlEntityPtr
7628
1.64M
xmlLookupGeneralEntity(xmlParserCtxtPtr ctxt, const xmlChar *name, int inAttr) {
7629
1.64M
    xmlEntityPtr ent = NULL;
7630
7631
    /*
7632
     * Predefined entities override any extra definition
7633
     */
7634
1.64M
    if ((ctxt->options & XML_PARSE_OLDSAX) == 0) {
7635
1.64M
        ent = xmlGetPredefinedEntity(name);
7636
1.64M
        if (ent != NULL)
7637
122k
            return(ent);
7638
1.64M
    }
7639
7640
    /*
7641
     * Ask first SAX for entity resolution, otherwise try the
7642
     * entities which may have stored in the parser context.
7643
     */
7644
1.51M
    if (ctxt->sax != NULL) {
7645
1.51M
  if (ctxt->sax->getEntity != NULL)
7646
1.51M
      ent = ctxt->sax->getEntity(ctxt->userData, name);
7647
1.51M
  if ((ctxt->wellFormed == 1 ) && (ent == NULL) &&
7648
1.32k
      (ctxt->options & XML_PARSE_OLDSAX))
7649
0
      ent = xmlGetPredefinedEntity(name);
7650
1.51M
  if ((ctxt->wellFormed == 1 ) && (ent == NULL) &&
7651
1.32k
      (ctxt->userData==ctxt)) {
7652
1.32k
      ent = xmlSAX2GetEntity(ctxt, name);
7653
1.32k
  }
7654
1.51M
    }
7655
7656
1.51M
    if (ent == NULL) {
7657
192k
        xmlHandleUndeclaredEntity(ctxt, name);
7658
192k
    }
7659
7660
    /*
7661
     * [ WFC: Parsed Entity ]
7662
     * An entity reference must not contain the name of an
7663
     * unparsed entity
7664
     */
7665
1.32M
    else if (ent->etype == XML_EXTERNAL_GENERAL_UNPARSED_ENTITY) {
7666
0
  xmlFatalErrMsgStr(ctxt, XML_ERR_UNPARSED_ENTITY,
7667
0
     "Entity reference to unparsed entity %s\n", name);
7668
0
        ent = NULL;
7669
0
    }
7670
7671
    /*
7672
     * [ WFC: No External Entity References ]
7673
     * Attribute values cannot contain direct or indirect
7674
     * entity references to external entities.
7675
     */
7676
1.32M
    else if (ent->etype == XML_EXTERNAL_GENERAL_PARSED_ENTITY) {
7677
15.1k
        if (inAttr) {
7678
2.19k
            xmlFatalErrMsgStr(ctxt, XML_ERR_ENTITY_IS_EXTERNAL,
7679
2.19k
                 "Attribute references external entity '%s'\n", name);
7680
2.19k
            ent = NULL;
7681
2.19k
        }
7682
15.1k
    }
7683
7684
1.51M
    return(ent);
7685
1.64M
}
7686
7687
/**
7688
 * xmlParseEntityRefInternal:
7689
 * @ctxt:  an XML parser context
7690
 * @inAttr:  whether we are in an attribute value
7691
 *
7692
 * Parse an entity reference. Always consumes '&'.
7693
 *
7694
 * [68] EntityRef ::= '&' Name ';'
7695
 *
7696
 * Returns the name, or NULL in case of error.
7697
 */
7698
static const xmlChar *
7699
1.96M
xmlParseEntityRefInternal(xmlParserCtxtPtr ctxt) {
7700
1.96M
    const xmlChar *name;
7701
7702
1.96M
    GROW;
7703
7704
1.96M
    if (RAW != '&')
7705
0
        return(NULL);
7706
1.96M
    NEXT;
7707
1.96M
    name = xmlParseName(ctxt);
7708
1.96M
    if (name == NULL) {
7709
318k
  xmlFatalErrMsg(ctxt, XML_ERR_NAME_REQUIRED,
7710
318k
           "xmlParseEntityRef: no name\n");
7711
318k
        return(NULL);
7712
318k
    }
7713
1.64M
    if (RAW != ';') {
7714
361k
  xmlFatalErr(ctxt, XML_ERR_ENTITYREF_SEMICOL_MISSING, NULL);
7715
361k
  return(NULL);
7716
361k
    }
7717
1.28M
    NEXT;
7718
7719
1.28M
    return(name);
7720
1.64M
}
7721
7722
/**
7723
 * xmlParseEntityRef:
7724
 * @ctxt:  an XML parser context
7725
 *
7726
 * DEPRECATED: Internal function, don't use.
7727
 *
7728
 * Returns the xmlEntityPtr if found, or NULL otherwise.
7729
 */
7730
xmlEntityPtr
7731
0
xmlParseEntityRef(xmlParserCtxtPtr ctxt) {
7732
0
    const xmlChar *name;
7733
7734
0
    if (ctxt == NULL)
7735
0
        return(NULL);
7736
7737
0
    name = xmlParseEntityRefInternal(ctxt);
7738
0
    if (name == NULL)
7739
0
        return(NULL);
7740
7741
0
    return(xmlLookupGeneralEntity(ctxt, name, /* inAttr */ 0));
7742
0
}
7743
7744
/**
7745
 * xmlParseStringEntityRef:
7746
 * @ctxt:  an XML parser context
7747
 * @str:  a pointer to an index in the string
7748
 *
7749
 * parse ENTITY references declarations, but this version parses it from
7750
 * a string value.
7751
 *
7752
 * [68] EntityRef ::= '&' Name ';'
7753
 *
7754
 * [ WFC: Entity Declared ]
7755
 * In a document without any DTD, a document with only an internal DTD
7756
 * subset which contains no parameter entity references, or a document
7757
 * with "standalone='yes'", the Name given in the entity reference
7758
 * must match that in an entity declaration, except that well-formed
7759
 * documents need not declare any of the following entities: amp, lt,
7760
 * gt, apos, quot.  The declaration of a parameter entity must precede
7761
 * any reference to it.  Similarly, the declaration of a general entity
7762
 * must precede any reference to it which appears in a default value in an
7763
 * attribute-list declaration. Note that if entities are declared in the
7764
 * external subset or in external parameter entities, a non-validating
7765
 * processor is not obligated to read and process their declarations;
7766
 * for such documents, the rule that an entity must be declared is a
7767
 * well-formedness constraint only if standalone='yes'.
7768
 *
7769
 * [ WFC: Parsed Entity ]
7770
 * An entity reference must not contain the name of an unparsed entity
7771
 *
7772
 * Returns the xmlEntityPtr if found, or NULL otherwise. The str pointer
7773
 * is updated to the current location in the string.
7774
 */
7775
static xmlChar *
7776
359k
xmlParseStringEntityRef(xmlParserCtxtPtr ctxt, const xmlChar ** str) {
7777
359k
    xmlChar *name;
7778
359k
    const xmlChar *ptr;
7779
359k
    xmlChar cur;
7780
7781
359k
    if ((str == NULL) || (*str == NULL))
7782
0
        return(NULL);
7783
359k
    ptr = *str;
7784
359k
    cur = *ptr;
7785
359k
    if (cur != '&')
7786
0
  return(NULL);
7787
7788
359k
    ptr++;
7789
359k
    name = xmlParseStringName(ctxt, &ptr);
7790
359k
    if (name == NULL) {
7791
378
  xmlFatalErrMsg(ctxt, XML_ERR_NAME_REQUIRED,
7792
378
           "xmlParseStringEntityRef: no name\n");
7793
378
  *str = ptr;
7794
378
  return(NULL);
7795
378
    }
7796
359k
    if (*ptr != ';') {
7797
776
  xmlFatalErr(ctxt, XML_ERR_ENTITYREF_SEMICOL_MISSING, NULL);
7798
776
        xmlFree(name);
7799
776
  *str = ptr;
7800
776
  return(NULL);
7801
776
    }
7802
358k
    ptr++;
7803
7804
358k
    *str = ptr;
7805
358k
    return(name);
7806
359k
}
7807
7808
/**
7809
 * xmlParsePEReference:
7810
 * @ctxt:  an XML parser context
7811
 *
7812
 * DEPRECATED: Internal function, don't use.
7813
 *
7814
 * Parse a parameter entity reference. Always consumes '%'.
7815
 *
7816
 * The entity content is handled directly by pushing it's content as
7817
 * a new input stream.
7818
 *
7819
 * [69] PEReference ::= '%' Name ';'
7820
 *
7821
 * [ WFC: No Recursion ]
7822
 * A parsed entity must not contain a recursive
7823
 * reference to itself, either directly or indirectly.
7824
 *
7825
 * [ WFC: Entity Declared ]
7826
 * In a document without any DTD, a document with only an internal DTD
7827
 * subset which contains no parameter entity references, or a document
7828
 * with "standalone='yes'", ...  ... The declaration of a parameter
7829
 * entity must precede any reference to it...
7830
 *
7831
 * [ VC: Entity Declared ]
7832
 * In a document with an external subset or external parameter entities
7833
 * with "standalone='no'", ...  ... The declaration of a parameter entity
7834
 * must precede any reference to it...
7835
 *
7836
 * [ WFC: In DTD ]
7837
 * Parameter-entity references may only appear in the DTD.
7838
 * NOTE: misleading but this is handled.
7839
 */
7840
void
7841
xmlParsePEReference(xmlParserCtxtPtr ctxt)
7842
70.6k
{
7843
70.6k
    const xmlChar *name;
7844
70.6k
    xmlEntityPtr entity = NULL;
7845
70.6k
    xmlParserInputPtr input;
7846
7847
70.6k
    if (RAW != '%')
7848
0
        return;
7849
70.6k
    NEXT;
7850
70.6k
    name = xmlParseName(ctxt);
7851
70.6k
    if (name == NULL) {
7852
6.63k
  xmlFatalErrMsg(ctxt, XML_ERR_PEREF_NO_NAME, "PEReference: no name\n");
7853
6.63k
  return;
7854
6.63k
    }
7855
64.0k
    if (RAW != ';') {
7856
5.32k
  xmlFatalErr(ctxt, XML_ERR_PEREF_SEMICOL_MISSING, NULL);
7857
5.32k
        return;
7858
5.32k
    }
7859
7860
58.6k
    NEXT;
7861
7862
    /* Must be set before xmlHandleUndeclaredEntity */
7863
58.6k
    ctxt->hasPErefs = 1;
7864
7865
    /*
7866
     * Request the entity from SAX
7867
     */
7868
58.6k
    if ((ctxt->sax != NULL) &&
7869
58.6k
  (ctxt->sax->getParameterEntity != NULL))
7870
58.6k
  entity = ctxt->sax->getParameterEntity(ctxt->userData, name);
7871
7872
58.6k
    if (entity == NULL) {
7873
15.4k
        xmlHandleUndeclaredEntity(ctxt, name);
7874
43.1k
    } else {
7875
  /*
7876
   * Internal checking in case the entity quest barfed
7877
   */
7878
43.1k
  if ((entity->etype != XML_INTERNAL_PARAMETER_ENTITY) &&
7879
39.9k
      (entity->etype != XML_EXTERNAL_PARAMETER_ENTITY)) {
7880
0
      xmlWarningMsg(ctxt, XML_WAR_UNDECLARED_ENTITY,
7881
0
      "Internal: %%%s; is not a parameter entity\n",
7882
0
        name, NULL);
7883
43.1k
  } else {
7884
43.1k
      if ((entity->etype == XML_EXTERNAL_PARAMETER_ENTITY) &&
7885
39.9k
                ((ctxt->options & XML_PARSE_NO_XXE) ||
7886
39.9k
     ((ctxt->loadsubset == 0) &&
7887
0
      (ctxt->replaceEntities == 0) &&
7888
0
      (ctxt->validate == 0))))
7889
0
    return;
7890
7891
43.1k
            if (entity->flags & XML_ENT_EXPANDING) {
7892
725
                xmlFatalErr(ctxt, XML_ERR_ENTITY_LOOP, NULL);
7893
725
                xmlHaltParser(ctxt);
7894
725
                return;
7895
725
            }
7896
7897
42.4k
      input = xmlNewEntityInputStream(ctxt, entity);
7898
42.4k
      if (xmlCtxtPushInput(ctxt, input) < 0) {
7899
4.49k
                xmlFreeInputStream(input);
7900
4.49k
    return;
7901
4.49k
            }
7902
7903
37.9k
            entity->flags |= XML_ENT_EXPANDING;
7904
7905
37.9k
            GROW;
7906
7907
37.9k
      if (entity->etype == XML_EXTERNAL_PARAMETER_ENTITY) {
7908
34.7k
                xmlDetectEncoding(ctxt);
7909
7910
34.7k
                if ((CMP5(CUR_PTR, '<', '?', 'x', 'm', 'l')) &&
7911
10.7k
                    (IS_BLANK_CH(NXT(5)))) {
7912
10.0k
                    xmlParseTextDecl(ctxt);
7913
10.0k
                }
7914
34.7k
            }
7915
37.9k
  }
7916
43.1k
    }
7917
58.6k
}
7918
7919
/**
7920
 * xmlLoadEntityContent:
7921
 * @ctxt:  an XML parser context
7922
 * @entity: an unloaded system entity
7923
 *
7924
 * Load the content of an entity.
7925
 *
7926
 * Returns 0 in case of success and -1 in case of failure
7927
 */
7928
static int
7929
16.8k
xmlLoadEntityContent(xmlParserCtxtPtr ctxt, xmlEntityPtr entity) {
7930
16.8k
    xmlParserInputPtr oldinput, input = NULL;
7931
16.8k
    xmlParserInputPtr *oldinputTab;
7932
16.8k
    const xmlChar *oldencoding;
7933
16.8k
    xmlChar *content = NULL;
7934
16.8k
    xmlResourceType rtype;
7935
16.8k
    size_t length, i;
7936
16.8k
    int oldinputNr, oldinputMax;
7937
16.8k
    int ret = -1;
7938
16.8k
    int res;
7939
7940
16.8k
    if ((ctxt == NULL) || (entity == NULL) ||
7941
16.8k
        ((entity->etype != XML_EXTERNAL_PARAMETER_ENTITY) &&
7942
0
   (entity->etype != XML_EXTERNAL_GENERAL_PARSED_ENTITY)) ||
7943
16.8k
  (entity->content != NULL)) {
7944
0
  xmlFatalErr(ctxt, XML_ERR_ARGUMENT,
7945
0
              "xmlLoadEntityContent parameter error");
7946
0
        return(-1);
7947
0
    }
7948
7949
16.8k
    if (entity->etype == XML_EXTERNAL_PARAMETER_ENTITY)
7950
16.8k
        rtype = XML_RESOURCE_PARAMETER_ENTITY;
7951
0
    else
7952
0
        rtype = XML_RESOURCE_GENERAL_ENTITY;
7953
7954
16.8k
    input = xmlLoadResource(ctxt, (char *) entity->URI,
7955
16.8k
                            (char *) entity->ExternalID, rtype);
7956
16.8k
    if (input == NULL)
7957
443
        return(-1);
7958
7959
16.4k
    oldinput = ctxt->input;
7960
16.4k
    oldinputNr = ctxt->inputNr;
7961
16.4k
    oldinputMax = ctxt->inputMax;
7962
16.4k
    oldinputTab = ctxt->inputTab;
7963
16.4k
    oldencoding = ctxt->encoding;
7964
7965
16.4k
    ctxt->input = NULL;
7966
16.4k
    ctxt->inputNr = 0;
7967
16.4k
    ctxt->inputMax = 1;
7968
16.4k
    ctxt->encoding = NULL;
7969
16.4k
    ctxt->inputTab = xmlMalloc(sizeof(xmlParserInputPtr));
7970
16.4k
    if (ctxt->inputTab == NULL) {
7971
1
        xmlErrMemory(ctxt);
7972
1
        xmlFreeInputStream(input);
7973
1
        goto error;
7974
1
    }
7975
7976
16.4k
    xmlBufResetInput(input->buf->buffer, input);
7977
7978
16.4k
    if (xmlCtxtPushInput(ctxt, input) < 0) {
7979
0
        xmlFreeInputStream(input);
7980
0
        goto error;
7981
0
    }
7982
7983
16.4k
    xmlDetectEncoding(ctxt);
7984
7985
    /*
7986
     * Parse a possible text declaration first
7987
     */
7988
16.4k
    if ((CMP5(CUR_PTR, '<', '?', 'x', 'm', 'l')) && (IS_BLANK_CH(NXT(5)))) {
7989
5.86k
  xmlParseTextDecl(ctxt);
7990
        /*
7991
         * An XML-1.0 document can't reference an entity not XML-1.0
7992
         */
7993
5.86k
        if ((xmlStrEqual(ctxt->version, BAD_CAST "1.0")) &&
7994
5.72k
            (!xmlStrEqual(ctxt->input->version, BAD_CAST "1.0"))) {
7995
1.95k
            xmlFatalErrMsg(ctxt, XML_ERR_VERSION_MISMATCH,
7996
1.95k
                           "Version mismatch between document and entity\n");
7997
1.95k
        }
7998
5.86k
    }
7999
8000
16.4k
    length = input->cur - input->base;
8001
16.4k
    xmlBufShrink(input->buf->buffer, length);
8002
16.4k
    xmlSaturatedAdd(&ctxt->sizeentities, length);
8003
8004
24.5k
    while ((res = xmlParserInputBufferGrow(input->buf, 4096)) > 0)
8005
8.09k
        ;
8006
8007
16.4k
    xmlBufResetInput(input->buf->buffer, input);
8008
8009
16.4k
    if (res < 0) {
8010
278
        xmlCtxtErrIO(ctxt, input->buf->error, NULL);
8011
278
        goto error;
8012
278
    }
8013
8014
16.1k
    length = xmlBufUse(input->buf->buffer);
8015
16.1k
    if (length > INT_MAX) {
8016
0
        xmlErrMemory(ctxt);
8017
0
        goto error;
8018
0
    }
8019
8020
16.1k
    content = xmlStrndup(xmlBufContent(input->buf->buffer), length);
8021
16.1k
    if (content == NULL) {
8022
3
        xmlErrMemory(ctxt);
8023
3
        goto error;
8024
3
    }
8025
8026
7.43M
    for (i = 0; i < length; ) {
8027
7.43M
        int clen = length - i;
8028
7.43M
        int c = xmlGetUTF8Char(content + i, &clen);
8029
8030
7.43M
        if ((c < 0) || (!IS_CHAR(c))) {
8031
13.4k
            xmlFatalErrMsgInt(ctxt, XML_ERR_INVALID_CHAR,
8032
13.4k
                              "xmlLoadEntityContent: invalid char value %d\n",
8033
13.4k
                              content[i]);
8034
13.4k
            goto error;
8035
13.4k
        }
8036
7.42M
        i += clen;
8037
7.42M
    }
8038
8039
2.69k
    xmlSaturatedAdd(&ctxt->sizeentities, length);
8040
2.69k
    entity->content = content;
8041
2.69k
    entity->length = length;
8042
2.69k
    content = NULL;
8043
2.69k
    ret = 0;
8044
8045
16.4k
error:
8046
32.8k
    while (ctxt->inputNr > 0)
8047
16.4k
        xmlFreeInputStream(xmlCtxtPopInput(ctxt));
8048
16.4k
    xmlFree(ctxt->inputTab);
8049
16.4k
    xmlFree((xmlChar *) ctxt->encoding);
8050
8051
16.4k
    ctxt->input = oldinput;
8052
16.4k
    ctxt->inputNr = oldinputNr;
8053
16.4k
    ctxt->inputMax = oldinputMax;
8054
16.4k
    ctxt->inputTab = oldinputTab;
8055
16.4k
    ctxt->encoding = oldencoding;
8056
8057
16.4k
    xmlFree(content);
8058
8059
16.4k
    return(ret);
8060
2.69k
}
8061
8062
/**
8063
 * xmlParseStringPEReference:
8064
 * @ctxt:  an XML parser context
8065
 * @str:  a pointer to an index in the string
8066
 *
8067
 * parse PEReference declarations
8068
 *
8069
 * [69] PEReference ::= '%' Name ';'
8070
 *
8071
 * [ WFC: No Recursion ]
8072
 * A parsed entity must not contain a recursive
8073
 * reference to itself, either directly or indirectly.
8074
 *
8075
 * [ WFC: Entity Declared ]
8076
 * In a document without any DTD, a document with only an internal DTD
8077
 * subset which contains no parameter entity references, or a document
8078
 * with "standalone='yes'", ...  ... The declaration of a parameter
8079
 * entity must precede any reference to it...
8080
 *
8081
 * [ VC: Entity Declared ]
8082
 * In a document with an external subset or external parameter entities
8083
 * with "standalone='no'", ...  ... The declaration of a parameter entity
8084
 * must precede any reference to it...
8085
 *
8086
 * [ WFC: In DTD ]
8087
 * Parameter-entity references may only appear in the DTD.
8088
 * NOTE: misleading but this is handled.
8089
 *
8090
 * Returns the string of the entity content.
8091
 *         str is updated to the current value of the index
8092
 */
8093
static xmlEntityPtr
8094
33.0k
xmlParseStringPEReference(xmlParserCtxtPtr ctxt, const xmlChar **str) {
8095
33.0k
    const xmlChar *ptr;
8096
33.0k
    xmlChar cur;
8097
33.0k
    xmlChar *name;
8098
33.0k
    xmlEntityPtr entity = NULL;
8099
8100
33.0k
    if ((str == NULL) || (*str == NULL)) return(NULL);
8101
33.0k
    ptr = *str;
8102
33.0k
    cur = *ptr;
8103
33.0k
    if (cur != '%')
8104
0
        return(NULL);
8105
33.0k
    ptr++;
8106
33.0k
    name = xmlParseStringName(ctxt, &ptr);
8107
33.0k
    if (name == NULL) {
8108
3.43k
  xmlFatalErrMsg(ctxt, XML_ERR_NAME_REQUIRED,
8109
3.43k
           "xmlParseStringPEReference: no name\n");
8110
3.43k
  *str = ptr;
8111
3.43k
  return(NULL);
8112
3.43k
    }
8113
29.5k
    cur = *ptr;
8114
29.5k
    if (cur != ';') {
8115
1.34k
  xmlFatalErr(ctxt, XML_ERR_ENTITYREF_SEMICOL_MISSING, NULL);
8116
1.34k
  xmlFree(name);
8117
1.34k
  *str = ptr;
8118
1.34k
  return(NULL);
8119
1.34k
    }
8120
28.2k
    ptr++;
8121
8122
    /* Must be set before xmlHandleUndeclaredEntity */
8123
28.2k
    ctxt->hasPErefs = 1;
8124
8125
    /*
8126
     * Request the entity from SAX
8127
     */
8128
28.2k
    if ((ctxt->sax != NULL) &&
8129
28.2k
  (ctxt->sax->getParameterEntity != NULL))
8130
28.2k
  entity = ctxt->sax->getParameterEntity(ctxt->userData, name);
8131
8132
28.2k
    if (entity == NULL) {
8133
850
        xmlHandleUndeclaredEntity(ctxt, name);
8134
27.3k
    } else {
8135
  /*
8136
   * Internal checking in case the entity quest barfed
8137
   */
8138
27.3k
  if ((entity->etype != XML_INTERNAL_PARAMETER_ENTITY) &&
8139
26.4k
      (entity->etype != XML_EXTERNAL_PARAMETER_ENTITY)) {
8140
0
      xmlWarningMsg(ctxt, XML_WAR_UNDECLARED_ENTITY,
8141
0
        "%%%s; is not a parameter entity\n",
8142
0
        name, NULL);
8143
0
  }
8144
27.3k
    }
8145
8146
28.2k
    xmlFree(name);
8147
28.2k
    *str = ptr;
8148
28.2k
    return(entity);
8149
29.5k
}
8150
8151
/**
8152
 * xmlParseDocTypeDecl:
8153
 * @ctxt:  an XML parser context
8154
 *
8155
 * DEPRECATED: Internal function, don't use.
8156
 *
8157
 * parse a DOCTYPE declaration
8158
 *
8159
 * [28] doctypedecl ::= '<!DOCTYPE' S Name (S ExternalID)? S?
8160
 *                      ('[' (markupdecl | PEReference | S)* ']' S?)? '>'
8161
 *
8162
 * [ VC: Root Element Type ]
8163
 * The Name in the document type declaration must match the element
8164
 * type of the root element.
8165
 */
8166
8167
void
8168
165k
xmlParseDocTypeDecl(xmlParserCtxtPtr ctxt) {
8169
165k
    const xmlChar *name = NULL;
8170
165k
    xmlChar *ExternalID = NULL;
8171
165k
    xmlChar *URI = NULL;
8172
8173
    /*
8174
     * We know that '<!DOCTYPE' has been detected.
8175
     */
8176
165k
    SKIP(9);
8177
8178
165k
    if (SKIP_BLANKS == 0) {
8179
20.1k
        xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED,
8180
20.1k
                       "Space required after 'DOCTYPE'\n");
8181
20.1k
    }
8182
8183
    /*
8184
     * Parse the DOCTYPE name.
8185
     */
8186
165k
    name = xmlParseName(ctxt);
8187
165k
    if (name == NULL) {
8188
3.25k
  xmlFatalErrMsg(ctxt, XML_ERR_NAME_REQUIRED,
8189
3.25k
           "xmlParseDocTypeDecl : no DOCTYPE name !\n");
8190
3.25k
    }
8191
165k
    ctxt->intSubName = name;
8192
8193
165k
    SKIP_BLANKS;
8194
8195
    /*
8196
     * Check for SystemID and ExternalID
8197
     */
8198
165k
    URI = xmlParseExternalID(ctxt, &ExternalID, 1);
8199
8200
165k
    if ((URI != NULL) || (ExternalID != NULL)) {
8201
35.6k
        ctxt->hasExternalSubset = 1;
8202
35.6k
    }
8203
165k
    ctxt->extSubURI = URI;
8204
165k
    ctxt->extSubSystem = ExternalID;
8205
8206
165k
    SKIP_BLANKS;
8207
8208
    /*
8209
     * Create and update the internal subset.
8210
     */
8211
165k
    if ((ctxt->sax != NULL) && (ctxt->sax->internalSubset != NULL) &&
8212
165k
  (!ctxt->disableSAX))
8213
130k
  ctxt->sax->internalSubset(ctxt->userData, name, ExternalID, URI);
8214
8215
165k
    if ((RAW != '[') && (RAW != '>')) {
8216
4.14k
  xmlFatalErr(ctxt, XML_ERR_DOCTYPE_NOT_FINISHED, NULL);
8217
4.14k
    }
8218
165k
}
8219
8220
/**
8221
 * xmlParseInternalSubset:
8222
 * @ctxt:  an XML parser context
8223
 *
8224
 * parse the internal subset declaration
8225
 *
8226
 * [28 end] ('[' (markupdecl | PEReference | S)* ']' S?)? '>'
8227
 */
8228
8229
static void
8230
156k
xmlParseInternalSubset(xmlParserCtxtPtr ctxt) {
8231
    /*
8232
     * Is there any DTD definition ?
8233
     */
8234
156k
    if (RAW == '[') {
8235
156k
        int oldInputNr = ctxt->inputNr;
8236
8237
156k
        NEXT;
8238
  /*
8239
   * Parse the succession of Markup declarations and
8240
   * PEReferences.
8241
   * Subsequence (markupdecl | PEReference | S)*
8242
   */
8243
156k
  SKIP_BLANKS;
8244
625k
  while (((RAW != ']') || (ctxt->inputNr > oldInputNr)) &&
8245
577k
               (PARSER_STOPPED(ctxt) == 0)) {
8246
8247
            /*
8248
             * Conditional sections are allowed from external entities included
8249
             * by PE References in the internal subset.
8250
             */
8251
536k
            if ((PARSER_EXTERNAL(ctxt)) &&
8252
59.8k
                (RAW == '<') && (NXT(1) == '!') && (NXT(2) == '[')) {
8253
7.79k
                xmlParseConditionalSections(ctxt);
8254
529k
            } else if ((RAW == '<') && ((NXT(1) == '!') || (NXT(1) == '?'))) {
8255
409k
          xmlParseMarkupDecl(ctxt);
8256
409k
            } else if (RAW == '%') {
8257
51.8k
          xmlParsePEReference(ctxt);
8258
67.6k
            } else {
8259
67.6k
    xmlFatalErr(ctxt, XML_ERR_INT_SUBSET_NOT_FINISHED, NULL);
8260
67.6k
                break;
8261
67.6k
            }
8262
469k
      SKIP_BLANKS_PE;
8263
469k
            SHRINK;
8264
469k
            GROW;
8265
469k
  }
8266
8267
175k
        while (ctxt->inputNr > oldInputNr)
8268
19.0k
            xmlPopPE(ctxt);
8269
8270
156k
  if (RAW == ']') {
8271
49.3k
      NEXT;
8272
49.3k
      SKIP_BLANKS;
8273
49.3k
  }
8274
156k
    }
8275
8276
    /*
8277
     * We should be at the end of the DOCTYPE declaration.
8278
     */
8279
156k
    if ((ctxt->wellFormed) && (RAW != '>')) {
8280
763
  xmlFatalErr(ctxt, XML_ERR_DOCTYPE_NOT_FINISHED, NULL);
8281
763
  return;
8282
763
    }
8283
155k
    NEXT;
8284
155k
}
8285
8286
#ifdef LIBXML_SAX1_ENABLED
8287
/**
8288
 * xmlParseAttribute:
8289
 * @ctxt:  an XML parser context
8290
 * @value:  a xmlChar ** used to store the value of the attribute
8291
 *
8292
 * DEPRECATED: Internal function, don't use.
8293
 *
8294
 * parse an attribute
8295
 *
8296
 * [41] Attribute ::= Name Eq AttValue
8297
 *
8298
 * [ WFC: No External Entity References ]
8299
 * Attribute values cannot contain direct or indirect entity references
8300
 * to external entities.
8301
 *
8302
 * [ WFC: No < in Attribute Values ]
8303
 * The replacement text of any entity referred to directly or indirectly in
8304
 * an attribute value (other than "&lt;") must not contain a <.
8305
 *
8306
 * [ VC: Attribute Value Type ]
8307
 * The attribute must have been declared; the value must be of the type
8308
 * declared for it.
8309
 *
8310
 * [25] Eq ::= S? '=' S?
8311
 *
8312
 * With namespace:
8313
 *
8314
 * [NS 11] Attribute ::= QName Eq AttValue
8315
 *
8316
 * Also the case QName == xmlns:??? is handled independently as a namespace
8317
 * definition.
8318
 *
8319
 * Returns the attribute name, and the value in *value.
8320
 */
8321
8322
const xmlChar *
8323
xmlParseAttribute(xmlParserCtxtPtr ctxt, xmlChar **value) {
8324
    const xmlChar *name;
8325
    xmlChar *val;
8326
8327
    *value = NULL;
8328
    GROW;
8329
    name = xmlParseName(ctxt);
8330
    if (name == NULL) {
8331
  xmlFatalErrMsg(ctxt, XML_ERR_NAME_REQUIRED,
8332
                 "error parsing attribute name\n");
8333
        return(NULL);
8334
    }
8335
8336
    /*
8337
     * read the value
8338
     */
8339
    SKIP_BLANKS;
8340
    if (RAW == '=') {
8341
        NEXT;
8342
  SKIP_BLANKS;
8343
  val = xmlParseAttValue(ctxt);
8344
    } else {
8345
  xmlFatalErrMsgStr(ctxt, XML_ERR_ATTRIBUTE_WITHOUT_VALUE,
8346
         "Specification mandates value for attribute %s\n", name);
8347
  return(name);
8348
    }
8349
8350
    /*
8351
     * Check that xml:lang conforms to the specification
8352
     * No more registered as an error, just generate a warning now
8353
     * since this was deprecated in XML second edition
8354
     */
8355
    if ((ctxt->pedantic) && (xmlStrEqual(name, BAD_CAST "xml:lang"))) {
8356
  if (!xmlCheckLanguageID(val)) {
8357
      xmlWarningMsg(ctxt, XML_WAR_LANG_VALUE,
8358
              "Malformed value for xml:lang : %s\n",
8359
        val, NULL);
8360
  }
8361
    }
8362
8363
    /*
8364
     * Check that xml:space conforms to the specification
8365
     */
8366
    if (xmlStrEqual(name, BAD_CAST "xml:space")) {
8367
  if (xmlStrEqual(val, BAD_CAST "default"))
8368
      *(ctxt->space) = 0;
8369
  else if (xmlStrEqual(val, BAD_CAST "preserve"))
8370
      *(ctxt->space) = 1;
8371
  else {
8372
    xmlWarningMsg(ctxt, XML_WAR_SPACE_VALUE,
8373
"Invalid value \"%s\" for xml:space : \"default\" or \"preserve\" expected\n",
8374
                                 val, NULL);
8375
  }
8376
    }
8377
8378
    *value = val;
8379
    return(name);
8380
}
8381
8382
/**
8383
 * xmlParseStartTag:
8384
 * @ctxt:  an XML parser context
8385
 *
8386
 * DEPRECATED: Internal function, don't use.
8387
 *
8388
 * Parse a start tag. Always consumes '<'.
8389
 *
8390
 * [40] STag ::= '<' Name (S Attribute)* S? '>'
8391
 *
8392
 * [ WFC: Unique Att Spec ]
8393
 * No attribute name may appear more than once in the same start-tag or
8394
 * empty-element tag.
8395
 *
8396
 * [44] EmptyElemTag ::= '<' Name (S Attribute)* S? '/>'
8397
 *
8398
 * [ WFC: Unique Att Spec ]
8399
 * No attribute name may appear more than once in the same start-tag or
8400
 * empty-element tag.
8401
 *
8402
 * With namespace:
8403
 *
8404
 * [NS 8] STag ::= '<' QName (S Attribute)* S? '>'
8405
 *
8406
 * [NS 10] EmptyElement ::= '<' QName (S Attribute)* S? '/>'
8407
 *
8408
 * Returns the element name parsed
8409
 */
8410
8411
const xmlChar *
8412
xmlParseStartTag(xmlParserCtxtPtr ctxt) {
8413
    const xmlChar *name;
8414
    const xmlChar *attname;
8415
    xmlChar *attvalue;
8416
    const xmlChar **atts = ctxt->atts;
8417
    int nbatts = 0;
8418
    int maxatts = ctxt->maxatts;
8419
    int i;
8420
8421
    if (RAW != '<') return(NULL);
8422
    NEXT1;
8423
8424
    name = xmlParseName(ctxt);
8425
    if (name == NULL) {
8426
  xmlFatalErrMsg(ctxt, XML_ERR_NAME_REQUIRED,
8427
       "xmlParseStartTag: invalid element name\n");
8428
        return(NULL);
8429
    }
8430
8431
    /*
8432
     * Now parse the attributes, it ends up with the ending
8433
     *
8434
     * (S Attribute)* S?
8435
     */
8436
    SKIP_BLANKS;
8437
    GROW;
8438
8439
    while (((RAW != '>') &&
8440
     ((RAW != '/') || (NXT(1) != '>')) &&
8441
     (IS_BYTE_CHAR(RAW))) && (PARSER_STOPPED(ctxt) == 0)) {
8442
  attname = xmlParseAttribute(ctxt, &attvalue);
8443
        if (attname == NULL)
8444
      break;
8445
        if (attvalue != NULL) {
8446
      /*
8447
       * [ WFC: Unique Att Spec ]
8448
       * No attribute name may appear more than once in the same
8449
       * start-tag or empty-element tag.
8450
       */
8451
      for (i = 0; i < nbatts;i += 2) {
8452
          if (xmlStrEqual(atts[i], attname)) {
8453
        xmlErrAttributeDup(ctxt, NULL, attname);
8454
        goto failed;
8455
    }
8456
      }
8457
      /*
8458
       * Add the pair to atts
8459
       */
8460
      if (nbatts + 4 > maxatts) {
8461
          const xmlChar **n;
8462
                int newSize;
8463
8464
                newSize = xmlGrowCapacity(maxatts, sizeof(n[0]) * 2,
8465
                                          11, XML_MAX_ATTRS);
8466
                if (newSize < 0) {
8467
        xmlErrMemory(ctxt);
8468
        goto failed;
8469
    }
8470
#ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
8471
                if (newSize < 2)
8472
                    newSize = 2;
8473
#endif
8474
          n = xmlRealloc(atts, newSize * sizeof(n[0]) * 2);
8475
    if (n == NULL) {
8476
        xmlErrMemory(ctxt);
8477
        goto failed;
8478
    }
8479
    atts = n;
8480
                maxatts = newSize * 2;
8481
    ctxt->atts = atts;
8482
    ctxt->maxatts = maxatts;
8483
      }
8484
8485
      atts[nbatts++] = attname;
8486
      atts[nbatts++] = attvalue;
8487
      atts[nbatts] = NULL;
8488
      atts[nbatts + 1] = NULL;
8489
8490
            attvalue = NULL;
8491
  }
8492
8493
failed:
8494
8495
        if (attvalue != NULL)
8496
            xmlFree(attvalue);
8497
8498
  GROW
8499
  if ((RAW == '>') || (((RAW == '/') && (NXT(1) == '>'))))
8500
      break;
8501
  if (SKIP_BLANKS == 0) {
8502
      xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED,
8503
         "attributes construct error\n");
8504
  }
8505
  SHRINK;
8506
        GROW;
8507
    }
8508
8509
    /*
8510
     * SAX: Start of Element !
8511
     */
8512
    if ((ctxt->sax != NULL) && (ctxt->sax->startElement != NULL) &&
8513
  (!ctxt->disableSAX)) {
8514
  if (nbatts > 0)
8515
      ctxt->sax->startElement(ctxt->userData, name, atts);
8516
  else
8517
      ctxt->sax->startElement(ctxt->userData, name, NULL);
8518
    }
8519
8520
    if (atts != NULL) {
8521
        /* Free only the content strings */
8522
        for (i = 1;i < nbatts;i+=2)
8523
      if (atts[i] != NULL)
8524
         xmlFree((xmlChar *) atts[i]);
8525
    }
8526
    return(name);
8527
}
8528
8529
/**
8530
 * xmlParseEndTag1:
8531
 * @ctxt:  an XML parser context
8532
 * @line:  line of the start tag
8533
 * @nsNr:  number of namespaces on the start tag
8534
 *
8535
 * Parse an end tag. Always consumes '</'.
8536
 *
8537
 * [42] ETag ::= '</' Name S? '>'
8538
 *
8539
 * With namespace
8540
 *
8541
 * [NS 9] ETag ::= '</' QName S? '>'
8542
 */
8543
8544
static void
8545
xmlParseEndTag1(xmlParserCtxtPtr ctxt, int line) {
8546
    const xmlChar *name;
8547
8548
    GROW;
8549
    if ((RAW != '<') || (NXT(1) != '/')) {
8550
  xmlFatalErrMsg(ctxt, XML_ERR_LTSLASH_REQUIRED,
8551
           "xmlParseEndTag: '</' not found\n");
8552
  return;
8553
    }
8554
    SKIP(2);
8555
8556
    name = xmlParseNameAndCompare(ctxt,ctxt->name);
8557
8558
    /*
8559
     * We should definitely be at the ending "S? '>'" part
8560
     */
8561
    GROW;
8562
    SKIP_BLANKS;
8563
    if ((!IS_BYTE_CHAR(RAW)) || (RAW != '>')) {
8564
  xmlFatalErr(ctxt, XML_ERR_GT_REQUIRED, NULL);
8565
    } else
8566
  NEXT1;
8567
8568
    /*
8569
     * [ WFC: Element Type Match ]
8570
     * The Name in an element's end-tag must match the element type in the
8571
     * start-tag.
8572
     *
8573
     */
8574
    if (name != (xmlChar*)1) {
8575
        if (name == NULL) name = BAD_CAST "unparsable";
8576
        xmlFatalErrMsgStrIntStr(ctxt, XML_ERR_TAG_NAME_MISMATCH,
8577
         "Opening and ending tag mismatch: %s line %d and %s\n",
8578
                    ctxt->name, line, name);
8579
    }
8580
8581
    /*
8582
     * SAX: End of Tag
8583
     */
8584
    if ((ctxt->sax != NULL) && (ctxt->sax->endElement != NULL) &&
8585
  (!ctxt->disableSAX))
8586
        ctxt->sax->endElement(ctxt->userData, ctxt->name);
8587
8588
    namePop(ctxt);
8589
    spacePop(ctxt);
8590
}
8591
8592
/**
8593
 * xmlParseEndTag:
8594
 * @ctxt:  an XML parser context
8595
 *
8596
 * DEPRECATED: Internal function, don't use.
8597
 *
8598
 * parse an end of tag
8599
 *
8600
 * [42] ETag ::= '</' Name S? '>'
8601
 *
8602
 * With namespace
8603
 *
8604
 * [NS 9] ETag ::= '</' QName S? '>'
8605
 */
8606
8607
void
8608
xmlParseEndTag(xmlParserCtxtPtr ctxt) {
8609
    xmlParseEndTag1(ctxt, 0);
8610
}
8611
#endif /* LIBXML_SAX1_ENABLED */
8612
8613
/************************************************************************
8614
 *                  *
8615
 *          SAX 2 specific operations       *
8616
 *                  *
8617
 ************************************************************************/
8618
8619
/**
8620
 * xmlParseQNameHashed:
8621
 * @ctxt:  an XML parser context
8622
 * @prefix:  pointer to store the prefix part
8623
 *
8624
 * parse an XML Namespace QName
8625
 *
8626
 * [6]  QName  ::= (Prefix ':')? LocalPart
8627
 * [7]  Prefix  ::= NCName
8628
 * [8]  LocalPart  ::= NCName
8629
 *
8630
 * Returns the Name parsed or NULL
8631
 */
8632
8633
static xmlHashedString
8634
9.99M
xmlParseQNameHashed(xmlParserCtxtPtr ctxt, xmlHashedString *prefix) {
8635
9.99M
    xmlHashedString l, p;
8636
9.99M
    int start, isNCName = 0;
8637
8638
9.99M
    l.name = NULL;
8639
9.99M
    p.name = NULL;
8640
8641
9.99M
    GROW;
8642
9.99M
    start = CUR_PTR - BASE_PTR;
8643
8644
9.99M
    l = xmlParseNCName(ctxt);
8645
9.99M
    if (l.name != NULL) {
8646
8.43M
        isNCName = 1;
8647
8.43M
        if (CUR == ':') {
8648
3.36M
            NEXT;
8649
3.36M
            p = l;
8650
3.36M
            l = xmlParseNCName(ctxt);
8651
3.36M
        }
8652
8.43M
    }
8653
9.99M
    if ((l.name == NULL) || (CUR == ':')) {
8654
1.60M
        xmlChar *tmp;
8655
8656
1.60M
        l.name = NULL;
8657
1.60M
        p.name = NULL;
8658
1.60M
        if ((isNCName == 0) && (CUR != ':'))
8659
1.54M
            return(l);
8660
60.7k
        tmp = xmlParseNmtoken(ctxt);
8661
60.7k
        if (tmp != NULL)
8662
28.8k
            xmlFree(tmp);
8663
60.7k
        l = xmlDictLookupHashed(ctxt->dict, BASE_PTR + start,
8664
60.7k
                                CUR_PTR - (BASE_PTR + start));
8665
60.7k
        if (l.name == NULL) {
8666
4
            xmlErrMemory(ctxt);
8667
4
            return(l);
8668
4
        }
8669
60.7k
        xmlNsErr(ctxt, XML_NS_ERR_QNAME,
8670
60.7k
                 "Failed to parse QName '%s'\n", l.name, NULL, NULL);
8671
60.7k
    }
8672
8673
8.44M
    *prefix = p;
8674
8.44M
    return(l);
8675
9.99M
}
8676
8677
/**
8678
 * xmlParseQName:
8679
 * @ctxt:  an XML parser context
8680
 * @prefix:  pointer to store the prefix part
8681
 *
8682
 * parse an XML Namespace QName
8683
 *
8684
 * [6]  QName  ::= (Prefix ':')? LocalPart
8685
 * [7]  Prefix  ::= NCName
8686
 * [8]  LocalPart  ::= NCName
8687
 *
8688
 * Returns the Name parsed or NULL
8689
 */
8690
8691
static const xmlChar *
8692
34.4k
xmlParseQName(xmlParserCtxtPtr ctxt, const xmlChar **prefix) {
8693
34.4k
    xmlHashedString n, p;
8694
8695
34.4k
    n = xmlParseQNameHashed(ctxt, &p);
8696
34.4k
    if (n.name == NULL)
8697
2.44k
        return(NULL);
8698
31.9k
    *prefix = p.name;
8699
31.9k
    return(n.name);
8700
34.4k
}
8701
8702
/**
8703
 * xmlParseQNameAndCompare:
8704
 * @ctxt:  an XML parser context
8705
 * @name:  the localname
8706
 * @prefix:  the prefix, if any.
8707
 *
8708
 * parse an XML name and compares for match
8709
 * (specialized for endtag parsing)
8710
 *
8711
 * Returns NULL for an illegal name, (xmlChar*) 1 for success
8712
 * and the name for mismatch
8713
 */
8714
8715
static const xmlChar *
8716
xmlParseQNameAndCompare(xmlParserCtxtPtr ctxt, xmlChar const *name,
8717
805k
                        xmlChar const *prefix) {
8718
805k
    const xmlChar *cmp;
8719
805k
    const xmlChar *in;
8720
805k
    const xmlChar *ret;
8721
805k
    const xmlChar *prefix2;
8722
8723
805k
    if (prefix == NULL) return(xmlParseNameAndCompare(ctxt, name));
8724
8725
805k
    GROW;
8726
805k
    in = ctxt->input->cur;
8727
8728
805k
    cmp = prefix;
8729
2.87M
    while (*in != 0 && *in == *cmp) {
8730
2.06M
  ++in;
8731
2.06M
  ++cmp;
8732
2.06M
    }
8733
805k
    if ((*cmp == 0) && (*in == ':')) {
8734
790k
        in++;
8735
790k
  cmp = name;
8736
7.68M
  while (*in != 0 && *in == *cmp) {
8737
6.89M
      ++in;
8738
6.89M
      ++cmp;
8739
6.89M
  }
8740
790k
  if (*cmp == 0 && (*in == '>' || IS_BLANK_CH (*in))) {
8741
      /* success */
8742
771k
            ctxt->input->col += in - ctxt->input->cur;
8743
771k
      ctxt->input->cur = in;
8744
771k
      return((const xmlChar*) 1);
8745
771k
  }
8746
790k
    }
8747
    /*
8748
     * all strings coms from the dictionary, equality can be done directly
8749
     */
8750
34.4k
    ret = xmlParseQName (ctxt, &prefix2);
8751
34.4k
    if (ret == NULL)
8752
2.44k
        return(NULL);
8753
31.9k
    if ((ret == name) && (prefix == prefix2))
8754
10.2k
  return((const xmlChar*) 1);
8755
21.7k
    return ret;
8756
31.9k
}
8757
8758
/**
8759
 * xmlParseAttribute2:
8760
 * @ctxt:  an XML parser context
8761
 * @pref:  the element prefix
8762
 * @elem:  the element name
8763
 * @prefix:  a xmlChar ** used to store the value of the attribute prefix
8764
 * @value:  a xmlChar ** used to store the value of the attribute
8765
 * @len:  an int * to save the length of the attribute
8766
 * @alloc:  an int * to indicate if the attribute was allocated
8767
 *
8768
 * parse an attribute in the new SAX2 framework.
8769
 *
8770
 * Returns the attribute name, and the value in *value, .
8771
 */
8772
8773
static xmlHashedString
8774
xmlParseAttribute2(xmlParserCtxtPtr ctxt,
8775
                   const xmlChar * pref, const xmlChar * elem,
8776
                   xmlHashedString * hprefix, xmlChar ** value,
8777
                   int *len, int *alloc)
8778
4.82M
{
8779
4.82M
    xmlHashedString hname;
8780
4.82M
    const xmlChar *prefix, *name;
8781
4.82M
    xmlChar *val = NULL, *internal_val = NULL;
8782
4.82M
    int normalize = 0;
8783
4.82M
    int isNamespace;
8784
8785
4.82M
    *value = NULL;
8786
4.82M
    GROW;
8787
4.82M
    hname = xmlParseQNameHashed(ctxt, hprefix);
8788
4.82M
    if (hname.name == NULL) {
8789
1.24M
        xmlFatalErrMsg(ctxt, XML_ERR_NAME_REQUIRED,
8790
1.24M
                       "error parsing attribute name\n");
8791
1.24M
        return(hname);
8792
1.24M
    }
8793
3.57M
    name = hname.name;
8794
3.57M
    prefix = hprefix->name;
8795
8796
    /*
8797
     * get the type if needed
8798
     */
8799
3.57M
    if (ctxt->attsSpecial != NULL) {
8800
51.7k
        int type;
8801
8802
51.7k
        type = XML_PTR_TO_INT(xmlHashQLookup2(ctxt->attsSpecial, pref, elem,
8803
51.7k
                                              prefix, name));
8804
51.7k
        if (type != 0)
8805
10.8k
            normalize = 1;
8806
51.7k
    }
8807
8808
    /*
8809
     * read the value
8810
     */
8811
3.57M
    SKIP_BLANKS;
8812
3.57M
    if (RAW == '=') {
8813
3.53M
        NEXT;
8814
3.53M
        SKIP_BLANKS;
8815
3.53M
        isNamespace = (((prefix == NULL) && (name == ctxt->str_xmlns)) ||
8816
3.46M
                       (prefix == ctxt->str_xmlns));
8817
3.53M
        val = xmlParseAttValueInternal(ctxt, len, alloc, normalize,
8818
3.53M
                                       isNamespace);
8819
3.53M
        if (val == NULL)
8820
17.1k
            goto error;
8821
3.53M
    } else {
8822
45.4k
        xmlFatalErrMsgStr(ctxt, XML_ERR_ATTRIBUTE_WITHOUT_VALUE,
8823
45.4k
                          "Specification mandates value for attribute %s\n",
8824
45.4k
                          name);
8825
45.4k
        goto error;
8826
45.4k
    }
8827
8828
3.51M
    if (prefix == ctxt->str_xml) {
8829
        /*
8830
         * Check that xml:lang conforms to the specification
8831
         * No more registered as an error, just generate a warning now
8832
         * since this was deprecated in XML second edition
8833
         */
8834
42.5k
        if ((ctxt->pedantic) && (xmlStrEqual(name, BAD_CAST "lang"))) {
8835
0
            internal_val = xmlStrndup(val, *len);
8836
0
            if (internal_val == NULL)
8837
0
                goto mem_error;
8838
0
            if (!xmlCheckLanguageID(internal_val)) {
8839
0
                xmlWarningMsg(ctxt, XML_WAR_LANG_VALUE,
8840
0
                              "Malformed value for xml:lang : %s\n",
8841
0
                              internal_val, NULL);
8842
0
            }
8843
0
        }
8844
8845
        /*
8846
         * Check that xml:space conforms to the specification
8847
         */
8848
42.5k
        if (xmlStrEqual(name, BAD_CAST "space")) {
8849
1.00k
            internal_val = xmlStrndup(val, *len);
8850
1.00k
            if (internal_val == NULL)
8851
2
                goto mem_error;
8852
998
            if (xmlStrEqual(internal_val, BAD_CAST "default"))
8853
368
                *(ctxt->space) = 0;
8854
630
            else if (xmlStrEqual(internal_val, BAD_CAST "preserve"))
8855
323
                *(ctxt->space) = 1;
8856
307
            else {
8857
307
                xmlWarningMsg(ctxt, XML_WAR_SPACE_VALUE,
8858
307
                              "Invalid value \"%s\" for xml:space : \"default\" or \"preserve\" expected\n",
8859
307
                              internal_val, NULL);
8860
307
            }
8861
998
        }
8862
42.4k
        if (internal_val) {
8863
998
            xmlFree(internal_val);
8864
998
        }
8865
42.4k
    }
8866
8867
3.51M
    *value = val;
8868
3.51M
    return (hname);
8869
8870
2
mem_error:
8871
2
    xmlErrMemory(ctxt);
8872
62.5k
error:
8873
62.5k
    if ((val != NULL) && (*alloc != 0))
8874
1
        xmlFree(val);
8875
62.5k
    return(hname);
8876
2
}
8877
8878
/**
8879
 * xmlAttrHashInsert:
8880
 * @ctxt: parser context
8881
 * @size: size of the hash table
8882
 * @name: attribute name
8883
 * @uri: namespace uri
8884
 * @hashValue: combined hash value of name and uri
8885
 * @aindex: attribute index (this is a multiple of 5)
8886
 *
8887
 * Inserts a new attribute into the hash table.
8888
 *
8889
 * Returns INT_MAX if no existing attribute was found, the attribute
8890
 * index if an attribute was found, -1 if a memory allocation failed.
8891
 */
8892
static int
8893
xmlAttrHashInsert(xmlParserCtxtPtr ctxt, unsigned size, const xmlChar *name,
8894
1.80M
                  const xmlChar *uri, unsigned hashValue, int aindex) {
8895
1.80M
    xmlAttrHashBucket *table = ctxt->attrHash;
8896
1.80M
    xmlAttrHashBucket *bucket;
8897
1.80M
    unsigned hindex;
8898
8899
1.80M
    hindex = hashValue & (size - 1);
8900
1.80M
    bucket = &table[hindex];
8901
8902
2.30M
    while (bucket->index >= 0) {
8903
525k
        const xmlChar **atts = &ctxt->atts[bucket->index];
8904
8905
525k
        if (name == atts[0]) {
8906
27.3k
            int nsIndex = XML_PTR_TO_INT(atts[2]);
8907
8908
27.3k
            if ((nsIndex == NS_INDEX_EMPTY) ? (uri == NULL) :
8909
27.3k
                (nsIndex == NS_INDEX_XML) ? (uri == ctxt->str_xml_ns) :
8910
6.84k
                (uri == ctxt->nsTab[nsIndex * 2 + 1]))
8911
25.2k
                return(bucket->index);
8912
27.3k
        }
8913
8914
500k
        hindex++;
8915
500k
        bucket++;
8916
500k
        if (hindex >= size) {
8917
212k
            hindex = 0;
8918
212k
            bucket = table;
8919
212k
        }
8920
500k
    }
8921
8922
1.78M
    bucket->index = aindex;
8923
8924
1.78M
    return(INT_MAX);
8925
1.80M
}
8926
8927
static int
8928
xmlAttrHashInsertQName(xmlParserCtxtPtr ctxt, unsigned size,
8929
                       const xmlChar *name, const xmlChar *prefix,
8930
4.90k
                       unsigned hashValue, int aindex) {
8931
4.90k
    xmlAttrHashBucket *table = ctxt->attrHash;
8932
4.90k
    xmlAttrHashBucket *bucket;
8933
4.90k
    unsigned hindex;
8934
8935
4.90k
    hindex = hashValue & (size - 1);
8936
4.90k
    bucket = &table[hindex];
8937
8938
8.33k
    while (bucket->index >= 0) {
8939
4.76k
        const xmlChar **atts = &ctxt->atts[bucket->index];
8940
8941
4.76k
        if ((name == atts[0]) && (prefix == atts[1]))
8942
1.33k
            return(bucket->index);
8943
8944
3.43k
        hindex++;
8945
3.43k
        bucket++;
8946
3.43k
        if (hindex >= size) {
8947
377
            hindex = 0;
8948
377
            bucket = table;
8949
377
        }
8950
3.43k
    }
8951
8952
3.57k
    bucket->index = aindex;
8953
8954
3.57k
    return(INT_MAX);
8955
4.90k
}
8956
/**
8957
 * xmlParseStartTag2:
8958
 * @ctxt:  an XML parser context
8959
 *
8960
 * Parse a start tag. Always consumes '<'.
8961
 *
8962
 * This routine is called when running SAX2 parsing
8963
 *
8964
 * [40] STag ::= '<' Name (S Attribute)* S? '>'
8965
 *
8966
 * [ WFC: Unique Att Spec ]
8967
 * No attribute name may appear more than once in the same start-tag or
8968
 * empty-element tag.
8969
 *
8970
 * [44] EmptyElemTag ::= '<' Name (S Attribute)* S? '/>'
8971
 *
8972
 * [ WFC: Unique Att Spec ]
8973
 * No attribute name may appear more than once in the same start-tag or
8974
 * empty-element tag.
8975
 *
8976
 * With namespace:
8977
 *
8978
 * [NS 8] STag ::= '<' QName (S Attribute)* S? '>'
8979
 *
8980
 * [NS 10] EmptyElement ::= '<' QName (S Attribute)* S? '/>'
8981
 *
8982
 * Returns the element name parsed
8983
 */
8984
8985
static const xmlChar *
8986
xmlParseStartTag2(xmlParserCtxtPtr ctxt, const xmlChar **pref,
8987
5.13M
                  const xmlChar **URI, int *nbNsPtr) {
8988
5.13M
    xmlHashedString hlocalname;
8989
5.13M
    xmlHashedString hprefix;
8990
5.13M
    xmlHashedString hattname;
8991
5.13M
    xmlHashedString haprefix;
8992
5.13M
    const xmlChar *localname;
8993
5.13M
    const xmlChar *prefix;
8994
5.13M
    const xmlChar *attname;
8995
5.13M
    const xmlChar *aprefix;
8996
5.13M
    const xmlChar *uri;
8997
5.13M
    xmlChar *attvalue = NULL;
8998
5.13M
    const xmlChar **atts = ctxt->atts;
8999
5.13M
    unsigned attrHashSize = 0;
9000
5.13M
    int maxatts = ctxt->maxatts;
9001
5.13M
    int nratts, nbatts, nbdef;
9002
5.13M
    int i, j, nbNs, nbTotalDef, attval, nsIndex, maxAtts;
9003
5.13M
    int alloc = 0;
9004
5.13M
    int numNsErr = 0;
9005
5.13M
    int numDupErr = 0;
9006
9007
5.13M
    if (RAW != '<') return(NULL);
9008
5.13M
    NEXT1;
9009
9010
5.13M
    nbatts = 0;
9011
5.13M
    nratts = 0;
9012
5.13M
    nbdef = 0;
9013
5.13M
    nbNs = 0;
9014
5.13M
    nbTotalDef = 0;
9015
5.13M
    attval = 0;
9016
9017
5.13M
    if (xmlParserNsStartElement(ctxt->nsdb) < 0) {
9018
0
        xmlErrMemory(ctxt);
9019
0
        return(NULL);
9020
0
    }
9021
9022
5.13M
    hlocalname = xmlParseQNameHashed(ctxt, &hprefix);
9023
5.13M
    if (hlocalname.name == NULL) {
9024
297k
  xmlFatalErrMsg(ctxt, XML_ERR_NAME_REQUIRED,
9025
297k
           "StartTag: invalid element name\n");
9026
297k
        return(NULL);
9027
297k
    }
9028
4.83M
    localname = hlocalname.name;
9029
4.83M
    prefix = hprefix.name;
9030
9031
    /*
9032
     * Now parse the attributes, it ends up with the ending
9033
     *
9034
     * (S Attribute)* S?
9035
     */
9036
4.83M
    SKIP_BLANKS;
9037
4.83M
    GROW;
9038
9039
    /*
9040
     * The ctxt->atts array will be ultimately passed to the SAX callback
9041
     * containing five xmlChar pointers for each attribute:
9042
     *
9043
     * [0] attribute name
9044
     * [1] attribute prefix
9045
     * [2] namespace URI
9046
     * [3] attribute value
9047
     * [4] end of attribute value
9048
     *
9049
     * To save memory, we reuse this array temporarily and store integers
9050
     * in these pointer variables.
9051
     *
9052
     * [0] attribute name
9053
     * [1] attribute prefix
9054
     * [2] hash value of attribute prefix, and later namespace index
9055
     * [3] for non-allocated values: ptrdiff_t offset into input buffer
9056
     * [4] for non-allocated values: ptrdiff_t offset into input buffer
9057
     *
9058
     * The ctxt->attallocs array contains an additional unsigned int for
9059
     * each attribute, containing the hash value of the attribute name
9060
     * and the alloc flag in bit 31.
9061
     */
9062
9063
6.22M
    while (((RAW != '>') &&
9064
5.07M
     ((RAW != '/') || (NXT(1) != '>')) &&
9065
4.85M
     (IS_BYTE_CHAR(RAW))) && (PARSER_STOPPED(ctxt) == 0)) {
9066
4.82M
  int len = -1;
9067
9068
4.82M
  hattname = xmlParseAttribute2(ctxt, prefix, localname,
9069
4.82M
                                          &haprefix, &attvalue, &len,
9070
4.82M
                                          &alloc);
9071
4.82M
        if (hattname.name == NULL)
9072
1.24M
      break;
9073
3.57M
        if (attvalue == NULL)
9074
62.5k
            goto next_attr;
9075
3.51M
        attname = hattname.name;
9076
3.51M
        aprefix = haprefix.name;
9077
3.51M
  if (len < 0) len = xmlStrlen(attvalue);
9078
9079
3.51M
        if ((attname == ctxt->str_xmlns) && (aprefix == NULL)) {
9080
59.6k
            xmlHashedString huri;
9081
59.6k
            xmlURIPtr parsedUri;
9082
9083
59.6k
            huri = xmlDictLookupHashed(ctxt->dict, attvalue, len);
9084
59.6k
            uri = huri.name;
9085
59.6k
            if (uri == NULL) {
9086
1
                xmlErrMemory(ctxt);
9087
1
                goto next_attr;
9088
1
            }
9089
59.6k
            if (*uri != 0) {
9090
53.0k
                if (xmlParseURISafe((const char *) uri, &parsedUri) < 0) {
9091
6
                    xmlErrMemory(ctxt);
9092
6
                    goto next_attr;
9093
6
                }
9094
53.0k
                if (parsedUri == NULL) {
9095
26.8k
                    xmlNsErr(ctxt, XML_WAR_NS_URI,
9096
26.8k
                             "xmlns: '%s' is not a valid URI\n",
9097
26.8k
                                       uri, NULL, NULL);
9098
26.8k
                } else {
9099
26.1k
                    if (parsedUri->scheme == NULL) {
9100
19.0k
                        xmlNsWarn(ctxt, XML_WAR_NS_URI_RELATIVE,
9101
19.0k
                                  "xmlns: URI %s is not absolute\n",
9102
19.0k
                                  uri, NULL, NULL);
9103
19.0k
                    }
9104
26.1k
                    xmlFreeURI(parsedUri);
9105
26.1k
                }
9106
53.0k
                if (uri == ctxt->str_xml_ns) {
9107
57
                    if (attname != ctxt->str_xml) {
9108
57
                        xmlNsErr(ctxt, XML_NS_ERR_XML_NAMESPACE,
9109
57
                     "xml namespace URI cannot be the default namespace\n",
9110
57
                                 NULL, NULL, NULL);
9111
57
                    }
9112
57
                    goto next_attr;
9113
57
                }
9114
53.0k
                if ((len == 29) &&
9115
5.31k
                    (xmlStrEqual(uri,
9116
5.31k
                             BAD_CAST "http://www.w3.org/2000/xmlns/"))) {
9117
257
                    xmlNsErr(ctxt, XML_NS_ERR_XML_NAMESPACE,
9118
257
                         "reuse of the xmlns namespace name is forbidden\n",
9119
257
                             NULL, NULL, NULL);
9120
257
                    goto next_attr;
9121
257
                }
9122
53.0k
            }
9123
9124
59.3k
            if (xmlParserNsPush(ctxt, NULL, &huri, NULL, 0) > 0)
9125
58.6k
                nbNs++;
9126
3.45M
        } else if (aprefix == ctxt->str_xmlns) {
9127
598k
            xmlHashedString huri;
9128
598k
            xmlURIPtr parsedUri;
9129
9130
598k
            huri = xmlDictLookupHashed(ctxt->dict, attvalue, len);
9131
598k
            uri = huri.name;
9132
598k
            if (uri == NULL) {
9133
1
                xmlErrMemory(ctxt);
9134
1
                goto next_attr;
9135
1
            }
9136
9137
598k
            if (attname == ctxt->str_xml) {
9138
451
                if (uri != ctxt->str_xml_ns) {
9139
225
                    xmlNsErr(ctxt, XML_NS_ERR_XML_NAMESPACE,
9140
225
                             "xml namespace prefix mapped to wrong URI\n",
9141
225
                             NULL, NULL, NULL);
9142
225
                }
9143
                /*
9144
                 * Do not keep a namespace definition node
9145
                 */
9146
451
                goto next_attr;
9147
451
            }
9148
598k
            if (uri == ctxt->str_xml_ns) {
9149
264
                if (attname != ctxt->str_xml) {
9150
264
                    xmlNsErr(ctxt, XML_NS_ERR_XML_NAMESPACE,
9151
264
                             "xml namespace URI mapped to wrong prefix\n",
9152
264
                             NULL, NULL, NULL);
9153
264
                }
9154
264
                goto next_attr;
9155
264
            }
9156
597k
            if (attname == ctxt->str_xmlns) {
9157
491
                xmlNsErr(ctxt, XML_NS_ERR_XML_NAMESPACE,
9158
491
                         "redefinition of the xmlns prefix is forbidden\n",
9159
491
                         NULL, NULL, NULL);
9160
491
                goto next_attr;
9161
491
            }
9162
597k
            if ((len == 29) &&
9163
3.60k
                (xmlStrEqual(uri,
9164
3.60k
                             BAD_CAST "http://www.w3.org/2000/xmlns/"))) {
9165
287
                xmlNsErr(ctxt, XML_NS_ERR_XML_NAMESPACE,
9166
287
                         "reuse of the xmlns namespace name is forbidden\n",
9167
287
                         NULL, NULL, NULL);
9168
287
                goto next_attr;
9169
287
            }
9170
597k
            if ((uri == NULL) || (uri[0] == 0)) {
9171
1.91k
                xmlNsErr(ctxt, XML_NS_ERR_XML_NAMESPACE,
9172
1.91k
                         "xmlns:%s: Empty XML namespace is not allowed\n",
9173
1.91k
                              attname, NULL, NULL);
9174
1.91k
                goto next_attr;
9175
595k
            } else {
9176
595k
                if (xmlParseURISafe((const char *) uri, &parsedUri) < 0) {
9177
118
                    xmlErrMemory(ctxt);
9178
118
                    goto next_attr;
9179
118
                }
9180
595k
                if (parsedUri == NULL) {
9181
57.3k
                    xmlNsErr(ctxt, XML_WAR_NS_URI,
9182
57.3k
                         "xmlns:%s: '%s' is not a valid URI\n",
9183
57.3k
                                       attname, uri, NULL);
9184
537k
                } else {
9185
537k
                    if ((ctxt->pedantic) && (parsedUri->scheme == NULL)) {
9186
0
                        xmlNsWarn(ctxt, XML_WAR_NS_URI_RELATIVE,
9187
0
                                  "xmlns:%s: URI %s is not absolute\n",
9188
0
                                  attname, uri, NULL);
9189
0
                    }
9190
537k
                    xmlFreeURI(parsedUri);
9191
537k
                }
9192
595k
            }
9193
9194
595k
            if (xmlParserNsPush(ctxt, &hattname, &huri, NULL, 0) > 0)
9195
594k
                nbNs++;
9196
2.85M
        } else {
9197
            /*
9198
             * Populate attributes array, see above for repurposing
9199
             * of xmlChar pointers.
9200
             */
9201
2.85M
            if ((atts == NULL) || (nbatts + 5 > maxatts)) {
9202
675k
                int res = xmlCtxtGrowAttrs(ctxt);
9203
9204
675k
                maxatts = ctxt->maxatts;
9205
675k
                atts = ctxt->atts;
9206
9207
675k
                if (res < 0)
9208
95
                    goto next_attr;
9209
675k
            }
9210
2.85M
            ctxt->attallocs[nratts++] = (hattname.hashValue & 0x7FFFFFFF) |
9211
2.85M
                                        ((unsigned) alloc << 31);
9212
2.85M
            atts[nbatts++] = attname;
9213
2.85M
            atts[nbatts++] = aprefix;
9214
2.85M
            atts[nbatts++] = (const xmlChar *) (size_t) haprefix.hashValue;
9215
2.85M
            if (alloc) {
9216
91.8k
                atts[nbatts++] = attvalue;
9217
91.8k
                attvalue += len;
9218
91.8k
                atts[nbatts++] = attvalue;
9219
2.76M
            } else {
9220
                /*
9221
                 * attvalue points into the input buffer which can be
9222
                 * reallocated. Store differences to input->base instead.
9223
                 * The pointers will be reconstructed later.
9224
                 */
9225
2.76M
                atts[nbatts++] = (void *) (attvalue - BASE_PTR);
9226
2.76M
                attvalue += len;
9227
2.76M
                atts[nbatts++] = (void *) (attvalue - BASE_PTR);
9228
2.76M
            }
9229
            /*
9230
             * tag if some deallocation is needed
9231
             */
9232
2.85M
            if (alloc != 0) attval = 1;
9233
2.85M
            attvalue = NULL; /* moved into atts */
9234
2.85M
        }
9235
9236
3.57M
next_attr:
9237
3.57M
        if ((attvalue != NULL) && (alloc != 0)) {
9238
57.2k
            xmlFree(attvalue);
9239
57.2k
            attvalue = NULL;
9240
57.2k
        }
9241
9242
3.57M
  GROW
9243
3.57M
  if ((RAW == '>') || (((RAW == '/') && (NXT(1) == '>'))))
9244
2.08M
      break;
9245
1.49M
  if (SKIP_BLANKS == 0) {
9246
101k
      xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED,
9247
101k
         "attributes construct error\n");
9248
101k
      break;
9249
101k
  }
9250
1.38M
        GROW;
9251
1.38M
    }
9252
9253
    /*
9254
     * Namespaces from default attributes
9255
     */
9256
4.83M
    if (ctxt->attsDefault != NULL) {
9257
403k
        xmlDefAttrsPtr defaults;
9258
9259
403k
  defaults = xmlHashLookup2(ctxt->attsDefault, localname, prefix);
9260
403k
  if (defaults != NULL) {
9261
2.39M
      for (i = 0; i < defaults->nbAttrs; i++) {
9262
2.07M
                xmlDefAttr *attr = &defaults->attrs[i];
9263
9264
2.07M
          attname = attr->name.name;
9265
2.07M
    aprefix = attr->prefix.name;
9266
9267
2.07M
    if ((attname == ctxt->str_xmlns) && (aprefix == NULL)) {
9268
242k
                    xmlParserEntityCheck(ctxt, attr->expandedSize);
9269
9270
242k
                    if (xmlParserNsPush(ctxt, NULL, &attr->value, NULL, 1) > 0)
9271
241k
                        nbNs++;
9272
1.83M
    } else if (aprefix == ctxt->str_xmlns) {
9273
634k
                    xmlParserEntityCheck(ctxt, attr->expandedSize);
9274
9275
634k
                    if (xmlParserNsPush(ctxt, &attr->name, &attr->value,
9276
634k
                                      NULL, 1) > 0)
9277
633k
                        nbNs++;
9278
1.19M
    } else {
9279
1.19M
                    if (nratts + nbTotalDef >= XML_MAX_ATTRS) {
9280
0
                        xmlFatalErr(ctxt, XML_ERR_RESOURCE_LIMIT,
9281
0
                                    "Maximum number of attributes exceeded");
9282
0
                        break;
9283
0
                    }
9284
1.19M
                    nbTotalDef += 1;
9285
1.19M
                }
9286
2.07M
      }
9287
316k
  }
9288
403k
    }
9289
9290
    /*
9291
     * Resolve attribute namespaces
9292
     */
9293
7.69M
    for (i = 0; i < nbatts; i += 5) {
9294
2.85M
        attname = atts[i];
9295
2.85M
        aprefix = atts[i+1];
9296
9297
        /*
9298
  * The default namespace does not apply to attribute names.
9299
  */
9300
2.85M
  if (aprefix == NULL) {
9301
2.76M
            nsIndex = NS_INDEX_EMPTY;
9302
2.76M
        } else if (aprefix == ctxt->str_xml) {
9303
42.4k
            nsIndex = NS_INDEX_XML;
9304
44.4k
        } else {
9305
44.4k
            haprefix.name = aprefix;
9306
44.4k
            haprefix.hashValue = (size_t) atts[i+2];
9307
44.4k
            nsIndex = xmlParserNsLookup(ctxt, &haprefix, NULL);
9308
9309
44.4k
      if ((nsIndex == INT_MAX) || (nsIndex < ctxt->nsdb->minNsIndex)) {
9310
26.4k
                xmlNsErr(ctxt, XML_NS_ERR_UNDEFINED_NAMESPACE,
9311
26.4k
        "Namespace prefix %s for %s on %s is not defined\n",
9312
26.4k
        aprefix, attname, localname);
9313
26.4k
                nsIndex = NS_INDEX_EMPTY;
9314
26.4k
            }
9315
44.4k
        }
9316
9317
2.85M
        atts[i+2] = XML_INT_TO_PTR(nsIndex);
9318
2.85M
    }
9319
9320
    /*
9321
     * Maximum number of attributes including default attributes.
9322
     */
9323
4.83M
    maxAtts = nratts + nbTotalDef;
9324
9325
    /*
9326
     * Verify that attribute names are unique.
9327
     */
9328
4.83M
    if (maxAtts > 1) {
9329
563k
        attrHashSize = 4;
9330
979k
        while (attrHashSize / 2 < (unsigned) maxAtts)
9331
415k
            attrHashSize *= 2;
9332
9333
563k
        if (attrHashSize > ctxt->attrHashMax) {
9334
135k
            xmlAttrHashBucket *tmp;
9335
9336
135k
            tmp = xmlRealloc(ctxt->attrHash, attrHashSize * sizeof(tmp[0]));
9337
135k
            if (tmp == NULL) {
9338
35
                xmlErrMemory(ctxt);
9339
35
                goto done;
9340
35
            }
9341
9342
135k
            ctxt->attrHash = tmp;
9343
135k
            ctxt->attrHashMax = attrHashSize;
9344
135k
        }
9345
9346
563k
        memset(ctxt->attrHash, -1, attrHashSize * sizeof(ctxt->attrHash[0]));
9347
9348
1.21M
        for (i = 0, j = 0; j < nratts; i += 5, j++) {
9349
653k
            const xmlChar *nsuri;
9350
653k
            unsigned hashValue, nameHashValue, uriHashValue;
9351
653k
            int res;
9352
9353
653k
            attname = atts[i];
9354
653k
            aprefix = atts[i+1];
9355
653k
            nsIndex = XML_PTR_TO_INT(atts[i+2]);
9356
            /* Hash values always have bit 31 set, see dict.c */
9357
653k
            nameHashValue = ctxt->attallocs[j] | 0x80000000;
9358
9359
653k
            if (nsIndex == NS_INDEX_EMPTY) {
9360
                /*
9361
                 * Prefix with empty namespace means an undeclared
9362
                 * prefix which was already reported above.
9363
                 */
9364
598k
                if (aprefix != NULL)
9365
19.9k
                    continue;
9366
578k
                nsuri = NULL;
9367
578k
                uriHashValue = URI_HASH_EMPTY;
9368
578k
            } else if (nsIndex == NS_INDEX_XML) {
9369
39.5k
                nsuri = ctxt->str_xml_ns;
9370
39.5k
                uriHashValue = URI_HASH_XML;
9371
39.5k
            } else {
9372
15.9k
                nsuri = ctxt->nsTab[nsIndex * 2 + 1];
9373
15.9k
                uriHashValue = ctxt->nsdb->extra[nsIndex].uriHashValue;
9374
15.9k
            }
9375
9376
633k
            hashValue = xmlDictCombineHash(nameHashValue, uriHashValue);
9377
633k
            res = xmlAttrHashInsert(ctxt, attrHashSize, attname, nsuri,
9378
633k
                                    hashValue, i);
9379
633k
            if (res < 0)
9380
0
                continue;
9381
9382
            /*
9383
             * [ WFC: Unique Att Spec ]
9384
             * No attribute name may appear more than once in the same
9385
             * start-tag or empty-element tag.
9386
             * As extended by the Namespace in XML REC.
9387
             */
9388
633k
            if (res < INT_MAX) {
9389
6.40k
                if (aprefix == atts[res+1]) {
9390
3.42k
                    xmlErrAttributeDup(ctxt, aprefix, attname);
9391
3.42k
                    numDupErr += 1;
9392
3.42k
                } else {
9393
2.97k
                    xmlNsErr(ctxt, XML_NS_ERR_ATTRIBUTE_REDEFINED,
9394
2.97k
                             "Namespaced Attribute %s in '%s' redefined\n",
9395
2.97k
                             attname, nsuri, NULL);
9396
2.97k
                    numNsErr += 1;
9397
2.97k
                }
9398
6.40k
            }
9399
633k
        }
9400
563k
    }
9401
9402
    /*
9403
     * Default attributes
9404
     */
9405
4.83M
    if (ctxt->attsDefault != NULL) {
9406
403k
        xmlDefAttrsPtr defaults;
9407
9408
403k
  defaults = xmlHashLookup2(ctxt->attsDefault, localname, prefix);
9409
403k
  if (defaults != NULL) {
9410
2.39M
      for (i = 0; i < defaults->nbAttrs; i++) {
9411
2.07M
                xmlDefAttr *attr = &defaults->attrs[i];
9412
2.07M
                const xmlChar *nsuri = NULL;
9413
2.07M
                unsigned hashValue, uriHashValue = 0;
9414
2.07M
                int res;
9415
9416
2.07M
          attname = attr->name.name;
9417
2.07M
    aprefix = attr->prefix.name;
9418
9419
2.07M
    if ((attname == ctxt->str_xmlns) && (aprefix == NULL))
9420
242k
                    continue;
9421
1.83M
    if (aprefix == ctxt->str_xmlns)
9422
634k
                    continue;
9423
9424
1.19M
                if (aprefix == NULL) {
9425
728k
                    nsIndex = NS_INDEX_EMPTY;
9426
728k
                    nsuri = NULL;
9427
728k
                    uriHashValue = URI_HASH_EMPTY;
9428
728k
                } else if (aprefix == ctxt->str_xml) {
9429
21.7k
                    nsIndex = NS_INDEX_XML;
9430
21.7k
                    nsuri = ctxt->str_xml_ns;
9431
21.7k
                    uriHashValue = URI_HASH_XML;
9432
446k
                } else {
9433
446k
                    nsIndex = xmlParserNsLookup(ctxt, &attr->prefix, NULL);
9434
446k
                    if ((nsIndex == INT_MAX) ||
9435
442k
                        (nsIndex < ctxt->nsdb->minNsIndex)) {
9436
442k
                        xmlNsErr(ctxt, XML_NS_ERR_UNDEFINED_NAMESPACE,
9437
442k
                                 "Namespace prefix %s for %s on %s is not "
9438
442k
                                 "defined\n",
9439
442k
                                 aprefix, attname, localname);
9440
442k
                        nsIndex = NS_INDEX_EMPTY;
9441
442k
                        nsuri = NULL;
9442
442k
                        uriHashValue = URI_HASH_EMPTY;
9443
442k
                    } else {
9444
4.12k
                        nsuri = ctxt->nsTab[nsIndex * 2 + 1];
9445
4.12k
                        uriHashValue = ctxt->nsdb->extra[nsIndex].uriHashValue;
9446
4.12k
                    }
9447
446k
                }
9448
9449
                /*
9450
                 * Check whether the attribute exists
9451
                 */
9452
1.19M
                if (maxAtts > 1) {
9453
1.17M
                    hashValue = xmlDictCombineHash(attr->name.hashValue,
9454
1.17M
                                                   uriHashValue);
9455
1.17M
                    res = xmlAttrHashInsert(ctxt, attrHashSize, attname, nsuri,
9456
1.17M
                                            hashValue, nbatts);
9457
1.17M
                    if (res < 0)
9458
0
                        continue;
9459
1.17M
                    if (res < INT_MAX) {
9460
18.8k
                        if (aprefix == atts[res+1])
9461
1.40k
                            continue;
9462
17.4k
                        xmlNsErr(ctxt, XML_NS_ERR_ATTRIBUTE_REDEFINED,
9463
17.4k
                                 "Namespaced Attribute %s in '%s' redefined\n",
9464
17.4k
                                 attname, nsuri, NULL);
9465
17.4k
                    }
9466
1.17M
                }
9467
9468
1.19M
                xmlParserEntityCheck(ctxt, attr->expandedSize);
9469
9470
1.19M
                if ((atts == NULL) || (nbatts + 5 > maxatts)) {
9471
13.2k
                    res = xmlCtxtGrowAttrs(ctxt);
9472
9473
13.2k
                    maxatts = ctxt->maxatts;
9474
13.2k
                    atts = ctxt->atts;
9475
9476
13.2k
                    if (res < 0) {
9477
3
                        localname = NULL;
9478
3
                        goto done;
9479
3
                    }
9480
13.2k
                }
9481
9482
1.19M
                atts[nbatts++] = attname;
9483
1.19M
                atts[nbatts++] = aprefix;
9484
1.19M
                atts[nbatts++] = XML_INT_TO_PTR(nsIndex);
9485
1.19M
                atts[nbatts++] = attr->value.name;
9486
1.19M
                atts[nbatts++] = attr->valueEnd;
9487
1.19M
                if ((ctxt->standalone == 1) && (attr->external != 0)) {
9488
0
                    xmlValidityError(ctxt, XML_DTD_STANDALONE_DEFAULTED,
9489
0
                            "standalone: attribute %s on %s defaulted "
9490
0
                            "from external subset\n",
9491
0
                            attname, localname);
9492
0
                }
9493
1.19M
                nbdef++;
9494
1.19M
      }
9495
316k
  }
9496
403k
    }
9497
9498
    /*
9499
     * Using a single hash table for nsUri/localName pairs cannot
9500
     * detect duplicate QNames reliably. The following example will
9501
     * only result in two namespace errors.
9502
     *
9503
     * <doc xmlns:a="a" xmlns:b="a">
9504
     *   <elem a:a="" b:a="" b:a=""/>
9505
     * </doc>
9506
     *
9507
     * If we saw more than one namespace error but no duplicate QNames
9508
     * were found, we have to scan for duplicate QNames.
9509
     */
9510
4.83M
    if ((numDupErr == 0) && (numNsErr > 1)) {
9511
1.13k
        memset(ctxt->attrHash, -1,
9512
1.13k
               attrHashSize * sizeof(ctxt->attrHash[0]));
9513
9514
7.40k
        for (i = 0, j = 0; j < nratts; i += 5, j++) {
9515
6.27k
            unsigned hashValue, nameHashValue, prefixHashValue;
9516
6.27k
            int res;
9517
9518
6.27k
            aprefix = atts[i+1];
9519
6.27k
            if (aprefix == NULL)
9520
1.36k
                continue;
9521
9522
4.90k
            attname = atts[i];
9523
            /* Hash values always have bit 31 set, see dict.c */
9524
4.90k
            nameHashValue = ctxt->attallocs[j] | 0x80000000;
9525
4.90k
            prefixHashValue = xmlDictComputeHash(ctxt->dict, aprefix);
9526
9527
4.90k
            hashValue = xmlDictCombineHash(nameHashValue, prefixHashValue);
9528
4.90k
            res = xmlAttrHashInsertQName(ctxt, attrHashSize, attname,
9529
4.90k
                                         aprefix, hashValue, i);
9530
4.90k
            if (res < INT_MAX)
9531
1.33k
                xmlErrAttributeDup(ctxt, aprefix, attname);
9532
4.90k
        }
9533
1.13k
    }
9534
9535
    /*
9536
     * Reconstruct attribute pointers
9537
     */
9538
8.88M
    for (i = 0, j = 0; i < nbatts; i += 5, j++) {
9539
        /* namespace URI */
9540
4.05M
        nsIndex = XML_PTR_TO_INT(atts[i+2]);
9541
4.05M
        if (nsIndex == INT_MAX)
9542
3.96M
            atts[i+2] = NULL;
9543
86.1k
        else if (nsIndex == INT_MAX - 1)
9544
64.0k
            atts[i+2] = ctxt->str_xml_ns;
9545
22.1k
        else
9546
22.1k
            atts[i+2] = ctxt->nsTab[nsIndex * 2 + 1];
9547
9548
4.05M
        if ((j < nratts) && (ctxt->attallocs[j] & 0x80000000) == 0) {
9549
2.76M
            atts[i+3] = BASE_PTR + XML_PTR_TO_INT(atts[i+3]);  /* value */
9550
2.76M
            atts[i+4] = BASE_PTR + XML_PTR_TO_INT(atts[i+4]);  /* valuend */
9551
2.76M
        }
9552
4.05M
    }
9553
9554
4.83M
    uri = xmlParserNsLookupUri(ctxt, &hprefix);
9555
4.83M
    if ((prefix != NULL) && (uri == NULL)) {
9556
217k
  xmlNsErr(ctxt, XML_NS_ERR_UNDEFINED_NAMESPACE,
9557
217k
           "Namespace prefix %s on %s is not defined\n",
9558
217k
     prefix, localname, NULL);
9559
217k
    }
9560
4.83M
    *pref = prefix;
9561
4.83M
    *URI = uri;
9562
9563
    /*
9564
     * SAX callback
9565
     */
9566
4.83M
    if ((ctxt->sax != NULL) && (ctxt->sax->startElementNs != NULL) &&
9567
4.83M
  (!ctxt->disableSAX)) {
9568
3.93M
  if (nbNs > 0)
9569
489k
      ctxt->sax->startElementNs(ctxt->userData, localname, prefix, uri,
9570
489k
                          nbNs, ctxt->nsTab + 2 * (ctxt->nsNr - nbNs),
9571
489k
        nbatts / 5, nbdef, atts);
9572
3.44M
  else
9573
3.44M
      ctxt->sax->startElementNs(ctxt->userData, localname, prefix, uri,
9574
3.44M
                          0, NULL, nbatts / 5, nbdef, atts);
9575
3.93M
    }
9576
9577
4.83M
done:
9578
    /*
9579
     * Free allocated attribute values
9580
     */
9581
4.83M
    if (attval != 0) {
9582
217k
  for (i = 0, j = 0; j < nratts; i += 5, j++)
9583
128k
      if (ctxt->attallocs[j] & 0x80000000)
9584
91.8k
          xmlFree((xmlChar *) atts[i+3]);
9585
89.0k
    }
9586
9587
4.83M
    *nbNsPtr = nbNs;
9588
4.83M
    return(localname);
9589
4.83M
}
9590
9591
/**
9592
 * xmlParseEndTag2:
9593
 * @ctxt:  an XML parser context
9594
 * @line:  line of the start tag
9595
 * @nsNr:  number of namespaces on the start tag
9596
 *
9597
 * Parse an end tag. Always consumes '</'.
9598
 *
9599
 * [42] ETag ::= '</' Name S? '>'
9600
 *
9601
 * With namespace
9602
 *
9603
 * [NS 9] ETag ::= '</' QName S? '>'
9604
 */
9605
9606
static void
9607
1.14M
xmlParseEndTag2(xmlParserCtxtPtr ctxt, const xmlStartTag *tag) {
9608
1.14M
    const xmlChar *name;
9609
9610
1.14M
    GROW;
9611
1.14M
    if ((RAW != '<') || (NXT(1) != '/')) {
9612
2.44k
  xmlFatalErr(ctxt, XML_ERR_LTSLASH_REQUIRED, NULL);
9613
2.44k
  return;
9614
2.44k
    }
9615
1.13M
    SKIP(2);
9616
9617
1.13M
    if (tag->prefix == NULL)
9618
332k
        name = xmlParseNameAndCompare(ctxt, ctxt->name);
9619
805k
    else
9620
805k
        name = xmlParseQNameAndCompare(ctxt, ctxt->name, tag->prefix);
9621
9622
    /*
9623
     * We should definitely be at the ending "S? '>'" part
9624
     */
9625
1.13M
    GROW;
9626
1.13M
    SKIP_BLANKS;
9627
1.13M
    if ((!IS_BYTE_CHAR(RAW)) || (RAW != '>')) {
9628
59.3k
  xmlFatalErr(ctxt, XML_ERR_GT_REQUIRED, NULL);
9629
59.3k
    } else
9630
1.07M
  NEXT1;
9631
9632
    /*
9633
     * [ WFC: Element Type Match ]
9634
     * The Name in an element's end-tag must match the element type in the
9635
     * start-tag.
9636
     *
9637
     */
9638
1.13M
    if (name != (xmlChar*)1) {
9639
90.8k
        if (name == NULL) name = BAD_CAST "unparsable";
9640
90.8k
        xmlFatalErrMsgStrIntStr(ctxt, XML_ERR_TAG_NAME_MISMATCH,
9641
90.8k
         "Opening and ending tag mismatch: %s line %d and %s\n",
9642
90.8k
                    ctxt->name, tag->line, name);
9643
90.8k
    }
9644
9645
    /*
9646
     * SAX: End of Tag
9647
     */
9648
1.13M
    if ((ctxt->sax != NULL) && (ctxt->sax->endElementNs != NULL) &&
9649
1.13M
  (!ctxt->disableSAX))
9650
964k
  ctxt->sax->endElementNs(ctxt->userData, ctxt->name, tag->prefix,
9651
964k
                                tag->URI);
9652
9653
1.13M
    spacePop(ctxt);
9654
1.13M
    if (tag->nsNr != 0)
9655
462k
  xmlParserNsPop(ctxt, tag->nsNr);
9656
1.13M
}
9657
9658
/**
9659
 * xmlParseCDSect:
9660
 * @ctxt:  an XML parser context
9661
 *
9662
 * DEPRECATED: Internal function, don't use.
9663
 *
9664
 * Parse escaped pure raw content. Always consumes '<!['.
9665
 *
9666
 * [18] CDSect ::= CDStart CData CDEnd
9667
 *
9668
 * [19] CDStart ::= '<![CDATA['
9669
 *
9670
 * [20] Data ::= (Char* - (Char* ']]>' Char*))
9671
 *
9672
 * [21] CDEnd ::= ']]>'
9673
 */
9674
void
9675
114k
xmlParseCDSect(xmlParserCtxtPtr ctxt) {
9676
114k
    xmlChar *buf = NULL;
9677
114k
    int len = 0;
9678
114k
    int size = XML_PARSER_BUFFER_SIZE;
9679
114k
    int r, rl;
9680
114k
    int s, sl;
9681
114k
    int cur, l;
9682
114k
    int maxLength = (ctxt->options & XML_PARSE_HUGE) ?
9683
0
                    XML_MAX_HUGE_LENGTH :
9684
114k
                    XML_MAX_TEXT_LENGTH;
9685
9686
114k
    if ((CUR != '<') || (NXT(1) != '!') || (NXT(2) != '['))
9687
0
        return;
9688
114k
    SKIP(3);
9689
9690
114k
    if (!CMP6(CUR_PTR, 'C', 'D', 'A', 'T', 'A', '['))
9691
0
        return;
9692
114k
    SKIP(6);
9693
9694
114k
    r = xmlCurrentCharRecover(ctxt, &rl);
9695
114k
    if (!IS_CHAR(r)) {
9696
1.04k
  xmlFatalErr(ctxt, XML_ERR_CDATA_NOT_FINISHED, NULL);
9697
1.04k
        goto out;
9698
1.04k
    }
9699
113k
    NEXTL(rl);
9700
113k
    s = xmlCurrentCharRecover(ctxt, &sl);
9701
113k
    if (!IS_CHAR(s)) {
9702
930
  xmlFatalErr(ctxt, XML_ERR_CDATA_NOT_FINISHED, NULL);
9703
930
        goto out;
9704
930
    }
9705
112k
    NEXTL(sl);
9706
112k
    cur = xmlCurrentCharRecover(ctxt, &l);
9707
112k
    buf = xmlMalloc(size);
9708
112k
    if (buf == NULL) {
9709
2
  xmlErrMemory(ctxt);
9710
2
        goto out;
9711
2
    }
9712
4.36M
    while (IS_CHAR(cur) &&
9713
4.36M
           ((r != ']') || (s != ']') || (cur != '>'))) {
9714
4.25M
  if (len + 5 >= size) {
9715
6.77k
      xmlChar *tmp;
9716
6.77k
            int newSize;
9717
9718
6.77k
            newSize = xmlGrowCapacity(size, 1, 1, maxLength);
9719
6.77k
            if (newSize < 0) {
9720
0
                xmlFatalErrMsg(ctxt, XML_ERR_CDATA_NOT_FINISHED,
9721
0
                               "CData section too big found\n");
9722
0
                goto out;
9723
0
            }
9724
6.77k
      tmp = xmlRealloc(buf, newSize);
9725
6.77k
      if (tmp == NULL) {
9726
2
    xmlErrMemory(ctxt);
9727
2
                goto out;
9728
2
      }
9729
6.76k
      buf = tmp;
9730
6.76k
      size = newSize;
9731
6.76k
  }
9732
4.25M
  COPY_BUF(buf, len, r);
9733
4.25M
  r = s;
9734
4.25M
  rl = sl;
9735
4.25M
  s = cur;
9736
4.25M
  sl = l;
9737
4.25M
  NEXTL(l);
9738
4.25M
  cur = xmlCurrentCharRecover(ctxt, &l);
9739
4.25M
    }
9740
112k
    buf[len] = 0;
9741
112k
    if (cur != '>') {
9742
5.81k
  xmlFatalErrMsgStr(ctxt, XML_ERR_CDATA_NOT_FINISHED,
9743
5.81k
                       "CData section not finished\n%.50s\n", buf);
9744
5.81k
        goto out;
9745
5.81k
    }
9746
106k
    NEXTL(l);
9747
9748
    /*
9749
     * OK the buffer is to be consumed as cdata.
9750
     */
9751
106k
    if ((ctxt->sax != NULL) && (!ctxt->disableSAX)) {
9752
102k
        if ((ctxt->sax->cdataBlock != NULL) &&
9753
102k
            ((ctxt->options & XML_PARSE_NOCDATA) == 0)) {
9754
2.35k
            ctxt->sax->cdataBlock(ctxt->userData, buf, len);
9755
99.8k
        } else if (ctxt->sax->characters != NULL) {
9756
99.8k
            ctxt->sax->characters(ctxt->userData, buf, len);
9757
99.8k
        }
9758
102k
    }
9759
9760
114k
out:
9761
114k
    xmlFree(buf);
9762
114k
}
9763
9764
/**
9765
 * xmlParseContentInternal:
9766
 * @ctxt:  an XML parser context
9767
 *
9768
 * Parse a content sequence. Stops at EOF or '</'. Leaves checking of
9769
 * unexpected EOF to the caller.
9770
 */
9771
9772
static void
9773
536k
xmlParseContentInternal(xmlParserCtxtPtr ctxt) {
9774
536k
    int oldNameNr = ctxt->nameNr;
9775
536k
    int oldSpaceNr = ctxt->spaceNr;
9776
536k
    int oldNodeNr = ctxt->nodeNr;
9777
9778
536k
    GROW;
9779
19.4M
    while ((ctxt->input->cur < ctxt->input->end) &&
9780
19.4M
     (PARSER_STOPPED(ctxt) == 0)) {
9781
19.4M
  const xmlChar *cur = ctxt->input->cur;
9782
9783
  /*
9784
   * First case : a Processing Instruction.
9785
   */
9786
19.4M
  if ((*cur == '<') && (cur[1] == '?')) {
9787
50.3k
      xmlParsePI(ctxt);
9788
50.3k
  }
9789
9790
  /*
9791
   * Second case : a CDSection
9792
   */
9793
  /* 2.6.0 test was *cur not RAW */
9794
19.3M
  else if (CMP9(CUR_PTR, '<', '!', '[', 'C', 'D', 'A', 'T', 'A', '[')) {
9795
114k
      xmlParseCDSect(ctxt);
9796
114k
  }
9797
9798
  /*
9799
   * Third case :  a comment
9800
   */
9801
19.2M
  else if ((*cur == '<') && (NXT(1) == '!') &&
9802
87.3k
     (NXT(2) == '-') && (NXT(3) == '-')) {
9803
54.9k
      xmlParseComment(ctxt);
9804
54.9k
  }
9805
9806
  /*
9807
   * Fourth case :  a sub-element.
9808
   */
9809
19.2M
  else if (*cur == '<') {
9810
5.70M
            if (NXT(1) == '/') {
9811
1.13M
                if (ctxt->nameNr <= oldNameNr)
9812
472k
                    break;
9813
665k
          xmlParseElementEnd(ctxt);
9814
4.56M
            } else {
9815
4.56M
          xmlParseElementStart(ctxt);
9816
4.56M
            }
9817
5.70M
  }
9818
9819
  /*
9820
   * Fifth case : a reference. If if has not been resolved,
9821
   *    parsing returns it's Name, create the node
9822
   */
9823
9824
13.4M
  else if (*cur == '&') {
9825
373k
      xmlParseReference(ctxt);
9826
373k
  }
9827
9828
  /*
9829
   * Last case, text. Note that References are handled directly.
9830
   */
9831
13.1M
  else {
9832
13.1M
      xmlParseCharDataInternal(ctxt, 0);
9833
13.1M
  }
9834
9835
18.9M
  SHRINK;
9836
18.9M
  GROW;
9837
18.9M
    }
9838
9839
536k
    if ((ctxt->nameNr > oldNameNr) &&
9840
32.0k
        (ctxt->input->cur >= ctxt->input->end) &&
9841
30.5k
        (ctxt->wellFormed)) {
9842
691
        const xmlChar *name = ctxt->nameTab[ctxt->nameNr - 1];
9843
691
        int line = ctxt->pushTab[ctxt->nameNr - 1].line;
9844
691
        xmlFatalErrMsgStrIntStr(ctxt, XML_ERR_TAG_NOT_FINISHED,
9845
691
                "Premature end of data in tag %s line %d\n",
9846
691
                name, line, NULL);
9847
691
    }
9848
9849
    /*
9850
     * Clean up in error case
9851
     */
9852
9853
724k
    while (ctxt->nodeNr > oldNodeNr)
9854
188k
        nodePop(ctxt);
9855
9856
937k
    while (ctxt->nameNr > oldNameNr) {
9857
401k
        xmlStartTag *tag = &ctxt->pushTab[ctxt->nameNr - 1];
9858
9859
401k
        if (tag->nsNr != 0)
9860
53.5k
            xmlParserNsPop(ctxt, tag->nsNr);
9861
9862
401k
        namePop(ctxt);
9863
401k
    }
9864
9865
937k
    while (ctxt->spaceNr > oldSpaceNr)
9866
401k
        spacePop(ctxt);
9867
536k
}
9868
9869
/**
9870
 * xmlParseContent:
9871
 * @ctxt:  an XML parser context
9872
 *
9873
 * Parse XML element content. This is useful if you're only interested
9874
 * in custom SAX callbacks. If you want a node list, use
9875
 * xmlCtxtParseContent.
9876
 */
9877
void
9878
0
xmlParseContent(xmlParserCtxtPtr ctxt) {
9879
0
    if ((ctxt == NULL) || (ctxt->input == NULL))
9880
0
        return;
9881
9882
0
    xmlCtxtInitializeLate(ctxt);
9883
9884
0
    xmlParseContentInternal(ctxt);
9885
9886
0
    xmlParserCheckEOF(ctxt, XML_ERR_NOT_WELL_BALANCED);
9887
0
}
9888
9889
/**
9890
 * xmlParseElement:
9891
 * @ctxt:  an XML parser context
9892
 *
9893
 * DEPRECATED: Internal function, don't use.
9894
 *
9895
 * parse an XML element
9896
 *
9897
 * [39] element ::= EmptyElemTag | STag content ETag
9898
 *
9899
 * [ WFC: Element Type Match ]
9900
 * The Name in an element's end-tag must match the element type in the
9901
 * start-tag.
9902
 *
9903
 */
9904
9905
void
9906
567k
xmlParseElement(xmlParserCtxtPtr ctxt) {
9907
567k
    if (xmlParseElementStart(ctxt) != 0)
9908
41.3k
        return;
9909
9910
525k
    xmlParseContentInternal(ctxt);
9911
9912
525k
    if (ctxt->input->cur >= ctxt->input->end) {
9913
50.8k
        if (ctxt->wellFormed) {
9914
1.02k
            const xmlChar *name = ctxt->nameTab[ctxt->nameNr - 1];
9915
1.02k
            int line = ctxt->pushTab[ctxt->nameNr - 1].line;
9916
1.02k
            xmlFatalErrMsgStrIntStr(ctxt, XML_ERR_TAG_NOT_FINISHED,
9917
1.02k
                    "Premature end of data in tag %s line %d\n",
9918
1.02k
                    name, line, NULL);
9919
1.02k
        }
9920
50.8k
        return;
9921
50.8k
    }
9922
9923
475k
    xmlParseElementEnd(ctxt);
9924
475k
}
9925
9926
/**
9927
 * xmlParseElementStart:
9928
 * @ctxt:  an XML parser context
9929
 *
9930
 * Parse the start of an XML element. Returns -1 in case of error, 0 if an
9931
 * opening tag was parsed, 1 if an empty element was parsed.
9932
 *
9933
 * Always consumes '<'.
9934
 */
9935
static int
9936
5.13M
xmlParseElementStart(xmlParserCtxtPtr ctxt) {
9937
5.13M
    int maxDepth = (ctxt->options & XML_PARSE_HUGE) ? 2048 : 256;
9938
5.13M
    const xmlChar *name;
9939
5.13M
    const xmlChar *prefix = NULL;
9940
5.13M
    const xmlChar *URI = NULL;
9941
5.13M
    xmlParserNodeInfo node_info;
9942
5.13M
    int line;
9943
5.13M
    xmlNodePtr cur;
9944
5.13M
    int nbNs = 0;
9945
9946
5.13M
    if (ctxt->nameNr > maxDepth) {
9947
250
        xmlFatalErrMsgInt(ctxt, XML_ERR_RESOURCE_LIMIT,
9948
250
                "Excessive depth in document: %d use XML_PARSE_HUGE option\n",
9949
250
                ctxt->nameNr);
9950
250
  xmlHaltParser(ctxt);
9951
250
  return(-1);
9952
250
    }
9953
9954
    /* Capture start position */
9955
5.13M
    if (ctxt->record_info) {
9956
0
        node_info.begin_pos = ctxt->input->consumed +
9957
0
                          (CUR_PTR - ctxt->input->base);
9958
0
  node_info.begin_line = ctxt->input->line;
9959
0
    }
9960
9961
5.13M
    if (ctxt->spaceNr == 0)
9962
0
  spacePush(ctxt, -1);
9963
5.13M
    else if (*ctxt->space == -2)
9964
0
  spacePush(ctxt, -1);
9965
5.13M
    else
9966
5.13M
  spacePush(ctxt, *ctxt->space);
9967
9968
5.13M
    line = ctxt->input->line;
9969
#ifdef LIBXML_SAX1_ENABLED
9970
    if (ctxt->sax2)
9971
#endif /* LIBXML_SAX1_ENABLED */
9972
5.13M
        name = xmlParseStartTag2(ctxt, &prefix, &URI, &nbNs);
9973
#ifdef LIBXML_SAX1_ENABLED
9974
    else
9975
  name = xmlParseStartTag(ctxt);
9976
#endif /* LIBXML_SAX1_ENABLED */
9977
5.13M
    if (name == NULL) {
9978
297k
  spacePop(ctxt);
9979
297k
        return(-1);
9980
297k
    }
9981
4.83M
    nameNsPush(ctxt, name, prefix, URI, line, nbNs);
9982
4.83M
    cur = ctxt->node;
9983
9984
#ifdef LIBXML_VALID_ENABLED
9985
    /*
9986
     * [ VC: Root Element Type ]
9987
     * The Name in the document type declaration must match the element
9988
     * type of the root element.
9989
     */
9990
    if (ctxt->validate && ctxt->wellFormed && ctxt->myDoc &&
9991
        ctxt->node && (ctxt->node == ctxt->myDoc->children))
9992
        ctxt->valid &= xmlValidateRoot(&ctxt->vctxt, ctxt->myDoc);
9993
#endif /* LIBXML_VALID_ENABLED */
9994
9995
    /*
9996
     * Check for an Empty Element.
9997
     */
9998
4.83M
    if ((RAW == '/') && (NXT(1) == '>')) {
9999
1.85M
        SKIP(2);
10000
1.85M
  if (ctxt->sax2) {
10001
1.85M
      if ((ctxt->sax != NULL) && (ctxt->sax->endElementNs != NULL) &&
10002
1.85M
    (!ctxt->disableSAX))
10003
1.80M
    ctxt->sax->endElementNs(ctxt->userData, name, prefix, URI);
10004
#ifdef LIBXML_SAX1_ENABLED
10005
  } else {
10006
      if ((ctxt->sax != NULL) && (ctxt->sax->endElement != NULL) &&
10007
    (!ctxt->disableSAX))
10008
    ctxt->sax->endElement(ctxt->userData, name);
10009
#endif /* LIBXML_SAX1_ENABLED */
10010
1.85M
  }
10011
1.85M
  namePop(ctxt);
10012
1.85M
  spacePop(ctxt);
10013
1.85M
  if (nbNs > 0)
10014
18.4k
      xmlParserNsPop(ctxt, nbNs);
10015
1.85M
  if (cur != NULL && ctxt->record_info) {
10016
0
            node_info.node = cur;
10017
0
            node_info.end_pos = ctxt->input->consumed +
10018
0
                                (CUR_PTR - ctxt->input->base);
10019
0
            node_info.end_line = ctxt->input->line;
10020
0
            xmlParserAddNodeInfo(ctxt, &node_info);
10021
0
  }
10022
1.85M
  return(1);
10023
1.85M
    }
10024
2.97M
    if (RAW == '>') {
10025
1.59M
        NEXT1;
10026
1.59M
        if (cur != NULL && ctxt->record_info) {
10027
0
            node_info.node = cur;
10028
0
            node_info.end_pos = 0;
10029
0
            node_info.end_line = 0;
10030
0
            xmlParserAddNodeInfo(ctxt, &node_info);
10031
0
        }
10032
1.59M
    } else {
10033
1.38M
        xmlFatalErrMsgStrIntStr(ctxt, XML_ERR_GT_REQUIRED,
10034
1.38M
         "Couldn't find end of Start Tag %s line %d\n",
10035
1.38M
                    name, line, NULL);
10036
10037
  /*
10038
   * end of parsing of this node.
10039
   */
10040
1.38M
  nodePop(ctxt);
10041
1.38M
  namePop(ctxt);
10042
1.38M
  spacePop(ctxt);
10043
1.38M
  if (nbNs > 0)
10044
255k
      xmlParserNsPop(ctxt, nbNs);
10045
1.38M
  return(-1);
10046
1.38M
    }
10047
10048
1.59M
    return(0);
10049
2.97M
}
10050
10051
/**
10052
 * xmlParseElementEnd:
10053
 * @ctxt:  an XML parser context
10054
 *
10055
 * Parse the end of an XML element. Always consumes '</'.
10056
 */
10057
static void
10058
1.14M
xmlParseElementEnd(xmlParserCtxtPtr ctxt) {
10059
1.14M
    xmlNodePtr cur = ctxt->node;
10060
10061
1.14M
    if (ctxt->nameNr <= 0) {
10062
667
        if ((RAW == '<') && (NXT(1) == '/'))
10063
3
            SKIP(2);
10064
667
        return;
10065
667
    }
10066
10067
    /*
10068
     * parse the end of tag: '</' should be here.
10069
     */
10070
1.14M
    if (ctxt->sax2) {
10071
1.14M
  xmlParseEndTag2(ctxt, &ctxt->pushTab[ctxt->nameNr - 1]);
10072
1.14M
  namePop(ctxt);
10073
1.14M
    }
10074
#ifdef LIBXML_SAX1_ENABLED
10075
    else
10076
  xmlParseEndTag1(ctxt, 0);
10077
#endif /* LIBXML_SAX1_ENABLED */
10078
10079
    /*
10080
     * Capture end position
10081
     */
10082
1.14M
    if (cur != NULL && ctxt->record_info) {
10083
0
        xmlParserNodeInfoPtr node_info;
10084
10085
0
        node_info = (xmlParserNodeInfoPtr) xmlParserFindNodeInfo(ctxt, cur);
10086
0
        if (node_info != NULL) {
10087
0
            node_info->end_pos = ctxt->input->consumed +
10088
0
                                 (CUR_PTR - ctxt->input->base);
10089
0
            node_info->end_line = ctxt->input->line;
10090
0
        }
10091
0
    }
10092
1.14M
}
10093
10094
/**
10095
 * xmlParseVersionNum:
10096
 * @ctxt:  an XML parser context
10097
 *
10098
 * DEPRECATED: Internal function, don't use.
10099
 *
10100
 * parse the XML version value.
10101
 *
10102
 * [26] VersionNum ::= '1.' [0-9]+
10103
 *
10104
 * In practice allow [0-9].[0-9]+ at that level
10105
 *
10106
 * Returns the string giving the XML version number, or NULL
10107
 */
10108
xmlChar *
10109
138k
xmlParseVersionNum(xmlParserCtxtPtr ctxt) {
10110
138k
    xmlChar *buf = NULL;
10111
138k
    int len = 0;
10112
138k
    int size = 10;
10113
138k
    int maxLength = (ctxt->options & XML_PARSE_HUGE) ?
10114
0
                    XML_MAX_TEXT_LENGTH :
10115
138k
                    XML_MAX_NAME_LENGTH;
10116
138k
    xmlChar cur;
10117
10118
138k
    buf = xmlMalloc(size);
10119
138k
    if (buf == NULL) {
10120
12
  xmlErrMemory(ctxt);
10121
12
  return(NULL);
10122
12
    }
10123
138k
    cur = CUR;
10124
138k
    if (!((cur >= '0') && (cur <= '9'))) {
10125
2.56k
  xmlFree(buf);
10126
2.56k
  return(NULL);
10127
2.56k
    }
10128
135k
    buf[len++] = cur;
10129
135k
    NEXT;
10130
135k
    cur=CUR;
10131
135k
    if (cur != '.') {
10132
579
  xmlFree(buf);
10133
579
  return(NULL);
10134
579
    }
10135
135k
    buf[len++] = cur;
10136
135k
    NEXT;
10137
135k
    cur=CUR;
10138
267k
    while ((cur >= '0') && (cur <= '9')) {
10139
131k
  if (len + 1 >= size) {
10140
1.03k
      xmlChar *tmp;
10141
1.03k
            int newSize;
10142
10143
1.03k
            newSize = xmlGrowCapacity(size, 1, 1, maxLength);
10144
1.03k
            if (newSize < 0) {
10145
0
                xmlFatalErr(ctxt, XML_ERR_NAME_TOO_LONG, "VersionNum");
10146
0
                xmlFree(buf);
10147
0
                return(NULL);
10148
0
            }
10149
1.03k
      tmp = xmlRealloc(buf, newSize);
10150
1.03k
      if (tmp == NULL) {
10151
1
    xmlErrMemory(ctxt);
10152
1
          xmlFree(buf);
10153
1
    return(NULL);
10154
1
      }
10155
1.03k
      buf = tmp;
10156
1.03k
            size = newSize;
10157
1.03k
  }
10158
131k
  buf[len++] = cur;
10159
131k
  NEXT;
10160
131k
  cur=CUR;
10161
131k
    }
10162
135k
    buf[len] = 0;
10163
135k
    return(buf);
10164
135k
}
10165
10166
/**
10167
 * xmlParseVersionInfo:
10168
 * @ctxt:  an XML parser context
10169
 *
10170
 * DEPRECATED: Internal function, don't use.
10171
 *
10172
 * parse the XML version.
10173
 *
10174
 * [24] VersionInfo ::= S 'version' Eq (' VersionNum ' | " VersionNum ")
10175
 *
10176
 * [25] Eq ::= S? '=' S?
10177
 *
10178
 * Returns the version string, e.g. "1.0"
10179
 */
10180
10181
xmlChar *
10182
172k
xmlParseVersionInfo(xmlParserCtxtPtr ctxt) {
10183
172k
    xmlChar *version = NULL;
10184
10185
172k
    if (CMP7(CUR_PTR, 'v', 'e', 'r', 's', 'i', 'o', 'n')) {
10186
143k
  SKIP(7);
10187
143k
  SKIP_BLANKS;
10188
143k
  if (RAW != '=') {
10189
4.26k
      xmlFatalErr(ctxt, XML_ERR_EQUAL_REQUIRED, NULL);
10190
4.26k
      return(NULL);
10191
4.26k
        }
10192
139k
  NEXT;
10193
139k
  SKIP_BLANKS;
10194
139k
  if (RAW == '"') {
10195
132k
      NEXT;
10196
132k
      version = xmlParseVersionNum(ctxt);
10197
132k
      if (RAW != '"') {
10198
7.77k
    xmlFatalErr(ctxt, XML_ERR_STRING_NOT_CLOSED, NULL);
10199
7.77k
      } else
10200
124k
          NEXT;
10201
132k
  } else if (RAW == '\''){
10202
5.87k
      NEXT;
10203
5.87k
      version = xmlParseVersionNum(ctxt);
10204
5.87k
      if (RAW != '\'') {
10205
250
    xmlFatalErr(ctxt, XML_ERR_STRING_NOT_CLOSED, NULL);
10206
250
      } else
10207
5.62k
          NEXT;
10208
5.87k
  } else {
10209
1.12k
      xmlFatalErr(ctxt, XML_ERR_STRING_NOT_STARTED, NULL);
10210
1.12k
  }
10211
139k
    }
10212
168k
    return(version);
10213
172k
}
10214
10215
/**
10216
 * xmlParseEncName:
10217
 * @ctxt:  an XML parser context
10218
 *
10219
 * DEPRECATED: Internal function, don't use.
10220
 *
10221
 * parse the XML encoding name
10222
 *
10223
 * [81] EncName ::= [A-Za-z] ([A-Za-z0-9._] | '-')*
10224
 *
10225
 * Returns the encoding name value or NULL
10226
 */
10227
xmlChar *
10228
94.9k
xmlParseEncName(xmlParserCtxtPtr ctxt) {
10229
94.9k
    xmlChar *buf = NULL;
10230
94.9k
    int len = 0;
10231
94.9k
    int size = 10;
10232
94.9k
    int maxLength = (ctxt->options & XML_PARSE_HUGE) ?
10233
0
                    XML_MAX_TEXT_LENGTH :
10234
94.9k
                    XML_MAX_NAME_LENGTH;
10235
94.9k
    xmlChar cur;
10236
10237
94.9k
    cur = CUR;
10238
94.9k
    if (((cur >= 'a') && (cur <= 'z')) ||
10239
92.3k
        ((cur >= 'A') && (cur <= 'Z'))) {
10240
92.3k
  buf = xmlMalloc(size);
10241
92.3k
  if (buf == NULL) {
10242
19
      xmlErrMemory(ctxt);
10243
19
      return(NULL);
10244
19
  }
10245
10246
92.3k
  buf[len++] = cur;
10247
92.3k
  NEXT;
10248
92.3k
  cur = CUR;
10249
50.3M
  while (((cur >= 'a') && (cur <= 'z')) ||
10250
662k
         ((cur >= 'A') && (cur <= 'Z')) ||
10251
613k
         ((cur >= '0') && (cur <= '9')) ||
10252
222k
         (cur == '.') || (cur == '_') ||
10253
50.2M
         (cur == '-')) {
10254
50.2M
      if (len + 1 >= size) {
10255
92.4k
          xmlChar *tmp;
10256
92.4k
                int newSize;
10257
10258
92.4k
                newSize = xmlGrowCapacity(size, 1, 1, maxLength);
10259
92.4k
                if (newSize < 0) {
10260
247
                    xmlFatalErr(ctxt, XML_ERR_NAME_TOO_LONG, "EncName");
10261
247
                    xmlFree(buf);
10262
247
                    return(NULL);
10263
247
                }
10264
92.1k
    tmp = xmlRealloc(buf, newSize);
10265
92.1k
    if (tmp == NULL) {
10266
6
        xmlErrMemory(ctxt);
10267
6
        xmlFree(buf);
10268
6
        return(NULL);
10269
6
    }
10270
92.1k
    buf = tmp;
10271
92.1k
                size = newSize;
10272
92.1k
      }
10273
50.2M
      buf[len++] = cur;
10274
50.2M
      NEXT;
10275
50.2M
      cur = CUR;
10276
50.2M
        }
10277
92.0k
  buf[len] = 0;
10278
92.0k
    } else {
10279
2.58k
  xmlFatalErr(ctxt, XML_ERR_ENCODING_NAME, NULL);
10280
2.58k
    }
10281
94.6k
    return(buf);
10282
94.9k
}
10283
10284
/**
10285
 * xmlParseEncodingDecl:
10286
 * @ctxt:  an XML parser context
10287
 *
10288
 * DEPRECATED: Internal function, don't use.
10289
 *
10290
 * parse the XML encoding declaration
10291
 *
10292
 * [80] EncodingDecl ::= S 'encoding' Eq ('"' EncName '"' |  "'" EncName "'")
10293
 *
10294
 * this setups the conversion filters.
10295
 *
10296
 * Returns the encoding value or NULL
10297
 */
10298
10299
const xmlChar *
10300
144k
xmlParseEncodingDecl(xmlParserCtxtPtr ctxt) {
10301
144k
    xmlChar *encoding = NULL;
10302
10303
144k
    SKIP_BLANKS;
10304
144k
    if (CMP8(CUR_PTR, 'e', 'n', 'c', 'o', 'd', 'i', 'n', 'g') == 0)
10305
48.9k
        return(NULL);
10306
10307
95.8k
    SKIP(8);
10308
95.8k
    SKIP_BLANKS;
10309
95.8k
    if (RAW != '=') {
10310
430
        xmlFatalErr(ctxt, XML_ERR_EQUAL_REQUIRED, NULL);
10311
430
        return(NULL);
10312
430
    }
10313
95.4k
    NEXT;
10314
95.4k
    SKIP_BLANKS;
10315
95.4k
    if (RAW == '"') {
10316
92.5k
        NEXT;
10317
92.5k
        encoding = xmlParseEncName(ctxt);
10318
92.5k
        if (RAW != '"') {
10319
4.67k
            xmlFatalErr(ctxt, XML_ERR_STRING_NOT_CLOSED, NULL);
10320
4.67k
            xmlFree((xmlChar *) encoding);
10321
4.67k
            return(NULL);
10322
4.67k
        } else
10323
87.8k
            NEXT;
10324
92.5k
    } else if (RAW == '\''){
10325
2.36k
        NEXT;
10326
2.36k
        encoding = xmlParseEncName(ctxt);
10327
2.36k
        if (RAW != '\'') {
10328
273
            xmlFatalErr(ctxt, XML_ERR_STRING_NOT_CLOSED, NULL);
10329
273
            xmlFree((xmlChar *) encoding);
10330
273
            return(NULL);
10331
273
        } else
10332
2.09k
            NEXT;
10333
2.36k
    } else {
10334
471
        xmlFatalErr(ctxt, XML_ERR_STRING_NOT_STARTED, NULL);
10335
471
    }
10336
10337
90.4k
    if (encoding == NULL)
10338
624
        return(NULL);
10339
10340
89.8k
    xmlSetDeclaredEncoding(ctxt, encoding);
10341
10342
89.8k
    return(ctxt->encoding);
10343
90.4k
}
10344
10345
/**
10346
 * xmlParseSDDecl:
10347
 * @ctxt:  an XML parser context
10348
 *
10349
 * DEPRECATED: Internal function, don't use.
10350
 *
10351
 * parse the XML standalone declaration
10352
 *
10353
 * [32] SDDecl ::= S 'standalone' Eq
10354
 *                 (("'" ('yes' | 'no') "'") | ('"' ('yes' | 'no')'"'))
10355
 *
10356
 * [ VC: Standalone Document Declaration ]
10357
 * TODO The standalone document declaration must have the value "no"
10358
 * if any external markup declarations contain declarations of:
10359
 *  - attributes with default values, if elements to which these
10360
 *    attributes apply appear in the document without specifications
10361
 *    of values for these attributes, or
10362
 *  - entities (other than amp, lt, gt, apos, quot), if references
10363
 *    to those entities appear in the document, or
10364
 *  - attributes with values subject to normalization, where the
10365
 *    attribute appears in the document with a value which will change
10366
 *    as a result of normalization, or
10367
 *  - element types with element content, if white space occurs directly
10368
 *    within any instance of those types.
10369
 *
10370
 * Returns:
10371
 *   1 if standalone="yes"
10372
 *   0 if standalone="no"
10373
 *  -2 if standalone attribute is missing or invalid
10374
 *    (A standalone value of -2 means that the XML declaration was found,
10375
 *     but no value was specified for the standalone attribute).
10376
 */
10377
10378
int
10379
63.6k
xmlParseSDDecl(xmlParserCtxtPtr ctxt) {
10380
63.6k
    int standalone = -2;
10381
10382
63.6k
    SKIP_BLANKS;
10383
63.6k
    if (CMP10(CUR_PTR, 's', 't', 'a', 'n', 'd', 'a', 'l', 'o', 'n', 'e')) {
10384
18.7k
  SKIP(10);
10385
18.7k
        SKIP_BLANKS;
10386
18.7k
  if (RAW != '=') {
10387
445
      xmlFatalErr(ctxt, XML_ERR_EQUAL_REQUIRED, NULL);
10388
445
      return(standalone);
10389
445
        }
10390
18.2k
  NEXT;
10391
18.2k
  SKIP_BLANKS;
10392
18.2k
        if (RAW == '\''){
10393
3.84k
      NEXT;
10394
3.84k
      if ((RAW == 'n') && (NXT(1) == 'o')) {
10395
322
          standalone = 0;
10396
322
                SKIP(2);
10397
3.52k
      } else if ((RAW == 'y') && (NXT(1) == 'e') &&
10398
941
                 (NXT(2) == 's')) {
10399
676
          standalone = 1;
10400
676
    SKIP(3);
10401
2.85k
            } else {
10402
2.85k
    xmlFatalErr(ctxt, XML_ERR_STANDALONE_VALUE, NULL);
10403
2.85k
      }
10404
3.84k
      if (RAW != '\'') {
10405
3.61k
    xmlFatalErr(ctxt, XML_ERR_STRING_NOT_CLOSED, NULL);
10406
3.61k
      } else
10407
232
          NEXT;
10408
14.4k
  } else if (RAW == '"'){
10409
12.5k
      NEXT;
10410
12.5k
      if ((RAW == 'n') && (NXT(1) == 'o')) {
10411
10.4k
          standalone = 0;
10412
10.4k
    SKIP(2);
10413
10.4k
      } else if ((RAW == 'y') && (NXT(1) == 'e') &&
10414
1.06k
                 (NXT(2) == 's')) {
10415
718
          standalone = 1;
10416
718
                SKIP(3);
10417
1.43k
            } else {
10418
1.43k
    xmlFatalErr(ctxt, XML_ERR_STANDALONE_VALUE, NULL);
10419
1.43k
      }
10420
12.5k
      if (RAW != '"') {
10421
1.98k
    xmlFatalErr(ctxt, XML_ERR_STRING_NOT_CLOSED, NULL);
10422
1.98k
      } else
10423
10.6k
          NEXT;
10424
12.5k
  } else {
10425
1.83k
      xmlFatalErr(ctxt, XML_ERR_STRING_NOT_STARTED, NULL);
10426
1.83k
        }
10427
18.2k
    }
10428
63.1k
    return(standalone);
10429
63.6k
}
10430
10431
/**
10432
 * xmlParseXMLDecl:
10433
 * @ctxt:  an XML parser context
10434
 *
10435
 * DEPRECATED: Internal function, don't use.
10436
 *
10437
 * parse an XML declaration header
10438
 *
10439
 * [23] XMLDecl ::= '<?xml' VersionInfo EncodingDecl? SDDecl? S? '?>'
10440
 */
10441
10442
void
10443
146k
xmlParseXMLDecl(xmlParserCtxtPtr ctxt) {
10444
146k
    xmlChar *version;
10445
10446
    /*
10447
     * This value for standalone indicates that the document has an
10448
     * XML declaration but it does not have a standalone attribute.
10449
     * It will be overwritten later if a standalone attribute is found.
10450
     */
10451
10452
146k
    ctxt->standalone = -2;
10453
10454
    /*
10455
     * We know that '<?xml' is here.
10456
     */
10457
146k
    SKIP(5);
10458
10459
146k
    if (!IS_BLANK_CH(RAW)) {
10460
0
  xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED,
10461
0
                 "Blank needed after '<?xml'\n");
10462
0
    }
10463
146k
    SKIP_BLANKS;
10464
10465
    /*
10466
     * We must have the VersionInfo here.
10467
     */
10468
146k
    version = xmlParseVersionInfo(ctxt);
10469
146k
    if (version == NULL) {
10470
19.9k
  xmlFatalErr(ctxt, XML_ERR_VERSION_MISSING, NULL);
10471
126k
    } else {
10472
126k
  if (!xmlStrEqual(version, (const xmlChar *) XML_DEFAULT_VERSION)) {
10473
      /*
10474
       * Changed here for XML-1.0 5th edition
10475
       */
10476
42.6k
      if (ctxt->options & XML_PARSE_OLD10) {
10477
0
    xmlFatalErrMsgStr(ctxt, XML_ERR_UNKNOWN_VERSION,
10478
0
                "Unsupported version '%s'\n",
10479
0
                version);
10480
42.6k
      } else {
10481
42.6k
          if ((version[0] == '1') && ((version[1] == '.'))) {
10482
34.4k
        xmlWarningMsg(ctxt, XML_WAR_UNKNOWN_VERSION,
10483
34.4k
                      "Unsupported version '%s'\n",
10484
34.4k
          version, NULL);
10485
34.4k
    } else {
10486
8.21k
        xmlFatalErrMsgStr(ctxt, XML_ERR_UNKNOWN_VERSION,
10487
8.21k
              "Unsupported version '%s'\n",
10488
8.21k
              version);
10489
8.21k
    }
10490
42.6k
      }
10491
42.6k
  }
10492
126k
  if (ctxt->version != NULL)
10493
0
      xmlFree((void *) ctxt->version);
10494
126k
  ctxt->version = version;
10495
126k
    }
10496
10497
    /*
10498
     * We may have the encoding declaration
10499
     */
10500
146k
    if (!IS_BLANK_CH(RAW)) {
10501
48.2k
        if ((RAW == '?') && (NXT(1) == '>')) {
10502
28.0k
      SKIP(2);
10503
28.0k
      return;
10504
28.0k
  }
10505
20.1k
  xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED, "Blank needed here\n");
10506
20.1k
    }
10507
118k
    xmlParseEncodingDecl(ctxt);
10508
10509
    /*
10510
     * We may have the standalone status.
10511
     */
10512
118k
    if ((ctxt->encoding != NULL) && (!IS_BLANK_CH(RAW))) {
10513
57.3k
        if ((RAW == '?') && (NXT(1) == '>')) {
10514
55.1k
      SKIP(2);
10515
55.1k
      return;
10516
55.1k
  }
10517
2.21k
  xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED, "Blank needed here\n");
10518
2.21k
    }
10519
10520
    /*
10521
     * We can grow the input buffer freely at that point
10522
     */
10523
63.6k
    GROW;
10524
10525
63.6k
    SKIP_BLANKS;
10526
63.6k
    ctxt->standalone = xmlParseSDDecl(ctxt);
10527
10528
63.6k
    SKIP_BLANKS;
10529
63.6k
    if ((RAW == '?') && (NXT(1) == '>')) {
10530
19.6k
        SKIP(2);
10531
43.9k
    } else if (RAW == '>') {
10532
        /* Deprecated old WD ... */
10533
792
  xmlFatalErr(ctxt, XML_ERR_XMLDECL_NOT_FINISHED, NULL);
10534
792
  NEXT;
10535
43.1k
    } else {
10536
43.1k
        int c;
10537
10538
43.1k
  xmlFatalErr(ctxt, XML_ERR_XMLDECL_NOT_FINISHED, NULL);
10539
5.28M
        while ((PARSER_STOPPED(ctxt) == 0) &&
10540
5.28M
               ((c = CUR) != 0)) {
10541
5.27M
            NEXT;
10542
5.27M
            if (c == '>')
10543
34.1k
                break;
10544
5.27M
        }
10545
43.1k
    }
10546
63.6k
}
10547
10548
/**
10549
 * xmlCtxtGetVersion:
10550
 * @ctxt:  parser context
10551
 *
10552
 * Available since 2.14.0.
10553
 *
10554
 * Returns the version from the XML declaration.
10555
 */
10556
const xmlChar *
10557
0
xmlCtxtGetVersion(xmlParserCtxtPtr ctxt) {
10558
0
    if (ctxt == NULL)
10559
0
        return(NULL);
10560
10561
0
    return(ctxt->version);
10562
0
}
10563
10564
/**
10565
 * xmlCtxtGetStandalone:
10566
 * @ctxt:  parser context
10567
 *
10568
 * Available since 2.14.0.
10569
 *
10570
 * Returns the value from the standalone document declaration.
10571
 */
10572
int
10573
0
xmlCtxtGetStandalone(xmlParserCtxtPtr ctxt) {
10574
0
    if (ctxt == NULL)
10575
0
        return(0);
10576
10577
0
    return(ctxt->standalone);
10578
0
}
10579
10580
/**
10581
 * xmlParseMisc:
10582
 * @ctxt:  an XML parser context
10583
 *
10584
 * DEPRECATED: Internal function, don't use.
10585
 *
10586
 * parse an XML Misc* optional field.
10587
 *
10588
 * [27] Misc ::= Comment | PI |  S
10589
 */
10590
10591
void
10592
1.44M
xmlParseMisc(xmlParserCtxtPtr ctxt) {
10593
1.52M
    while (PARSER_STOPPED(ctxt) == 0) {
10594
1.47M
        SKIP_BLANKS;
10595
1.47M
        GROW;
10596
1.47M
        if ((RAW == '<') && (NXT(1) == '?')) {
10597
69.2k
      xmlParsePI(ctxt);
10598
1.40M
        } else if (CMP4(CUR_PTR, '<', '!', '-', '-')) {
10599
13.3k
      xmlParseComment(ctxt);
10600
1.38M
        } else {
10601
1.38M
            break;
10602
1.38M
        }
10603
1.47M
    }
10604
1.44M
}
10605
10606
static void
10607
713k
xmlFinishDocument(xmlParserCtxtPtr ctxt) {
10608
713k
    xmlDocPtr doc;
10609
10610
    /*
10611
     * SAX: end of the document processing.
10612
     */
10613
713k
    if ((ctxt->sax) && (ctxt->sax->endDocument != NULL))
10614
713k
        ctxt->sax->endDocument(ctxt->userData);
10615
10616
713k
    doc = ctxt->myDoc;
10617
713k
    if (doc != NULL) {
10618
680k
        if (ctxt->wellFormed) {
10619
470k
            doc->properties |= XML_DOC_WELLFORMED;
10620
470k
            if (ctxt->valid)
10621
468k
                doc->properties |= XML_DOC_DTDVALID;
10622
470k
            if (ctxt->nsWellFormed)
10623
368k
                doc->properties |= XML_DOC_NSVALID;
10624
470k
        }
10625
10626
680k
        if (ctxt->options & XML_PARSE_OLD10)
10627
0
            doc->properties |= XML_DOC_OLD10;
10628
10629
        /*
10630
         * Remove locally kept entity definitions if the tree was not built
10631
         */
10632
680k
  if (xmlStrEqual(doc->version, SAX_COMPAT_MODE)) {
10633
14.7k
            xmlFreeDoc(doc);
10634
14.7k
            ctxt->myDoc = NULL;
10635
14.7k
        }
10636
680k
    }
10637
713k
}
10638
10639
/**
10640
 * xmlParseDocument:
10641
 * @ctxt:  an XML parser context
10642
 *
10643
 * Parse an XML document and invoke the SAX handlers. This is useful
10644
 * if you're only interested in custom SAX callbacks. If you want a
10645
 * document tree, use xmlCtxtParseDocument.
10646
 *
10647
 * Returns 0, -1 in case of error.
10648
 */
10649
10650
int
10651
714k
xmlParseDocument(xmlParserCtxtPtr ctxt) {
10652
714k
    if ((ctxt == NULL) || (ctxt->input == NULL))
10653
0
        return(-1);
10654
10655
714k
    GROW;
10656
10657
    /*
10658
     * SAX: detecting the level.
10659
     */
10660
714k
    xmlCtxtInitializeLate(ctxt);
10661
10662
714k
    if ((ctxt->sax) && (ctxt->sax->setDocumentLocator)) {
10663
714k
        ctxt->sax->setDocumentLocator(ctxt->userData,
10664
714k
                (xmlSAXLocator *) &xmlDefaultSAXLocator);
10665
714k
    }
10666
10667
714k
    xmlDetectEncoding(ctxt);
10668
10669
714k
    if (CUR == 0) {
10670
1.04k
  xmlFatalErr(ctxt, XML_ERR_DOCUMENT_EMPTY, NULL);
10671
1.04k
  return(-1);
10672
1.04k
    }
10673
10674
713k
    GROW;
10675
713k
    if ((CMP5(CUR_PTR, '<', '?', 'x', 'm', 'l')) && (IS_BLANK_CH(NXT(5)))) {
10676
10677
  /*
10678
   * Note that we will switch encoding on the fly.
10679
   */
10680
146k
  xmlParseXMLDecl(ctxt);
10681
146k
  SKIP_BLANKS;
10682
566k
    } else {
10683
566k
  ctxt->version = xmlCharStrdup(XML_DEFAULT_VERSION);
10684
566k
        if (ctxt->version == NULL) {
10685
63
            xmlErrMemory(ctxt);
10686
63
            return(-1);
10687
63
        }
10688
566k
    }
10689
713k
    if ((ctxt->sax) && (ctxt->sax->startDocument) && (!ctxt->disableSAX))
10690
665k
        ctxt->sax->startDocument(ctxt->userData);
10691
713k
    if ((ctxt->myDoc != NULL) && (ctxt->input != NULL) &&
10692
665k
        (ctxt->input->buf != NULL) && (ctxt->input->buf->compressed >= 0)) {
10693
0
  ctxt->myDoc->compression = ctxt->input->buf->compressed;
10694
0
    }
10695
10696
    /*
10697
     * The Misc part of the Prolog
10698
     */
10699
713k
    xmlParseMisc(ctxt);
10700
10701
    /*
10702
     * Then possibly doc type declaration(s) and more Misc
10703
     * (doctypedecl Misc*)?
10704
     */
10705
713k
    GROW;
10706
713k
    if (CMP9(CUR_PTR, '<', '!', 'D', 'O', 'C', 'T', 'Y', 'P', 'E')) {
10707
10708
165k
  ctxt->inSubset = 1;
10709
165k
  xmlParseDocTypeDecl(ctxt);
10710
165k
  if (RAW == '[') {
10711
156k
      xmlParseInternalSubset(ctxt);
10712
156k
  } else if (RAW == '>') {
10713
4.70k
            NEXT;
10714
4.70k
        }
10715
10716
  /*
10717
   * Create and update the external subset.
10718
   */
10719
165k
  ctxt->inSubset = 2;
10720
165k
  if ((ctxt->sax != NULL) && (ctxt->sax->externalSubset != NULL) &&
10721
165k
      (!ctxt->disableSAX))
10722
41.1k
      ctxt->sax->externalSubset(ctxt->userData, ctxt->intSubName,
10723
41.1k
                                ctxt->extSubSystem, ctxt->extSubURI);
10724
165k
  ctxt->inSubset = 0;
10725
10726
165k
        xmlCleanSpecialAttr(ctxt);
10727
10728
165k
  xmlParseMisc(ctxt);
10729
165k
    }
10730
10731
    /*
10732
     * Time to start parsing the tree itself
10733
     */
10734
713k
    GROW;
10735
713k
    if (RAW != '<') {
10736
146k
        if (ctxt->wellFormed)
10737
5.17k
            xmlFatalErrMsg(ctxt, XML_ERR_DOCUMENT_EMPTY,
10738
5.17k
                           "Start tag expected, '<' not found\n");
10739
567k
    } else {
10740
567k
  xmlParseElement(ctxt);
10741
10742
  /*
10743
   * The Misc part at the end
10744
   */
10745
567k
  xmlParseMisc(ctxt);
10746
10747
567k
        xmlParserCheckEOF(ctxt, XML_ERR_DOCUMENT_END);
10748
567k
    }
10749
10750
713k
    ctxt->instate = XML_PARSER_EOF;
10751
713k
    xmlFinishDocument(ctxt);
10752
10753
713k
    if (! ctxt->wellFormed) {
10754
243k
  ctxt->valid = 0;
10755
243k
  return(-1);
10756
243k
    }
10757
10758
470k
    return(0);
10759
713k
}
10760
10761
/**
10762
 * xmlParseExtParsedEnt:
10763
 * @ctxt:  an XML parser context
10764
 *
10765
 * DEPRECATED: Internal function, don't use.
10766
 *
10767
 * parse a general parsed entity
10768
 * An external general parsed entity is well-formed if it matches the
10769
 * production labeled extParsedEnt.
10770
 *
10771
 * [78] extParsedEnt ::= TextDecl? content
10772
 *
10773
 * Returns 0, -1 in case of error. the parser context is augmented
10774
 *                as a result of the parsing.
10775
 */
10776
10777
int
10778
0
xmlParseExtParsedEnt(xmlParserCtxtPtr ctxt) {
10779
0
    if ((ctxt == NULL) || (ctxt->input == NULL))
10780
0
        return(-1);
10781
10782
0
    xmlCtxtInitializeLate(ctxt);
10783
10784
0
    if ((ctxt->sax) && (ctxt->sax->setDocumentLocator)) {
10785
0
        ctxt->sax->setDocumentLocator(ctxt->userData,
10786
0
                (xmlSAXLocator *) &xmlDefaultSAXLocator);
10787
0
    }
10788
10789
0
    xmlDetectEncoding(ctxt);
10790
10791
0
    if (CUR == 0) {
10792
0
  xmlFatalErr(ctxt, XML_ERR_DOCUMENT_EMPTY, NULL);
10793
0
    }
10794
10795
    /*
10796
     * Check for the XMLDecl in the Prolog.
10797
     */
10798
0
    GROW;
10799
0
    if ((CMP5(CUR_PTR, '<', '?', 'x', 'm', 'l')) && (IS_BLANK_CH(NXT(5)))) {
10800
10801
  /*
10802
   * Note that we will switch encoding on the fly.
10803
   */
10804
0
  xmlParseXMLDecl(ctxt);
10805
0
  SKIP_BLANKS;
10806
0
    } else {
10807
0
  ctxt->version = xmlCharStrdup(XML_DEFAULT_VERSION);
10808
0
    }
10809
0
    if ((ctxt->sax) && (ctxt->sax->startDocument) && (!ctxt->disableSAX))
10810
0
        ctxt->sax->startDocument(ctxt->userData);
10811
10812
    /*
10813
     * Doing validity checking on chunk doesn't make sense
10814
     */
10815
0
    ctxt->options &= ~XML_PARSE_DTDVALID;
10816
0
    ctxt->validate = 0;
10817
0
    ctxt->depth = 0;
10818
10819
0
    xmlParseContentInternal(ctxt);
10820
10821
0
    if (ctxt->input->cur < ctxt->input->end)
10822
0
  xmlFatalErr(ctxt, XML_ERR_NOT_WELL_BALANCED, NULL);
10823
10824
    /*
10825
     * SAX: end of the document processing.
10826
     */
10827
0
    if ((ctxt->sax) && (ctxt->sax->endDocument != NULL))
10828
0
        ctxt->sax->endDocument(ctxt->userData);
10829
10830
0
    if (! ctxt->wellFormed) return(-1);
10831
0
    return(0);
10832
0
}
10833
10834
#ifdef LIBXML_PUSH_ENABLED
10835
/************************************************************************
10836
 *                  *
10837
 *    Progressive parsing interfaces        *
10838
 *                  *
10839
 ************************************************************************/
10840
10841
/**
10842
 * xmlParseLookupChar:
10843
 * @ctxt:  an XML parser context
10844
 * @c:  character
10845
 *
10846
 * Check whether the input buffer contains a character.
10847
 */
10848
static int
10849
xmlParseLookupChar(xmlParserCtxtPtr ctxt, int c) {
10850
    const xmlChar *cur;
10851
10852
    if (ctxt->checkIndex == 0) {
10853
        cur = ctxt->input->cur + 1;
10854
    } else {
10855
        cur = ctxt->input->cur + ctxt->checkIndex;
10856
    }
10857
10858
    if (memchr(cur, c, ctxt->input->end - cur) == NULL) {
10859
        size_t index = ctxt->input->end - ctxt->input->cur;
10860
10861
        if (index > LONG_MAX) {
10862
            ctxt->checkIndex = 0;
10863
            return(1);
10864
        }
10865
        ctxt->checkIndex = index;
10866
        return(0);
10867
    } else {
10868
        ctxt->checkIndex = 0;
10869
        return(1);
10870
    }
10871
}
10872
10873
/**
10874
 * xmlParseLookupString:
10875
 * @ctxt:  an XML parser context
10876
 * @startDelta: delta to apply at the start
10877
 * @str:  string
10878
 * @strLen:  length of string
10879
 *
10880
 * Check whether the input buffer contains a string.
10881
 */
10882
static const xmlChar *
10883
xmlParseLookupString(xmlParserCtxtPtr ctxt, size_t startDelta,
10884
                     const char *str, size_t strLen) {
10885
    const xmlChar *cur, *term;
10886
10887
    if (ctxt->checkIndex == 0) {
10888
        cur = ctxt->input->cur + startDelta;
10889
    } else {
10890
        cur = ctxt->input->cur + ctxt->checkIndex;
10891
    }
10892
10893
    term = BAD_CAST strstr((const char *) cur, str);
10894
    if (term == NULL) {
10895
        const xmlChar *end = ctxt->input->end;
10896
        size_t index;
10897
10898
        /* Rescan (strLen - 1) characters. */
10899
        if ((size_t) (end - cur) < strLen)
10900
            end = cur;
10901
        else
10902
            end -= strLen - 1;
10903
        index = end - ctxt->input->cur;
10904
        if (index > LONG_MAX) {
10905
            ctxt->checkIndex = 0;
10906
            return(ctxt->input->end - strLen);
10907
        }
10908
        ctxt->checkIndex = index;
10909
    } else {
10910
        ctxt->checkIndex = 0;
10911
    }
10912
10913
    return(term);
10914
}
10915
10916
/**
10917
 * xmlParseLookupCharData:
10918
 * @ctxt:  an XML parser context
10919
 *
10920
 * Check whether the input buffer contains terminated char data.
10921
 */
10922
static int
10923
xmlParseLookupCharData(xmlParserCtxtPtr ctxt) {
10924
    const xmlChar *cur = ctxt->input->cur + ctxt->checkIndex;
10925
    const xmlChar *end = ctxt->input->end;
10926
    size_t index;
10927
10928
    while (cur < end) {
10929
        if ((*cur == '<') || (*cur == '&')) {
10930
            ctxt->checkIndex = 0;
10931
            return(1);
10932
        }
10933
        cur++;
10934
    }
10935
10936
    index = cur - ctxt->input->cur;
10937
    if (index > LONG_MAX) {
10938
        ctxt->checkIndex = 0;
10939
        return(1);
10940
    }
10941
    ctxt->checkIndex = index;
10942
    return(0);
10943
}
10944
10945
/**
10946
 * xmlParseLookupGt:
10947
 * @ctxt:  an XML parser context
10948
 *
10949
 * Check whether there's enough data in the input buffer to finish parsing
10950
 * a start tag. This has to take quotes into account.
10951
 */
10952
static int
10953
xmlParseLookupGt(xmlParserCtxtPtr ctxt) {
10954
    const xmlChar *cur;
10955
    const xmlChar *end = ctxt->input->end;
10956
    int state = ctxt->endCheckState;
10957
    size_t index;
10958
10959
    if (ctxt->checkIndex == 0)
10960
        cur = ctxt->input->cur + 1;
10961
    else
10962
        cur = ctxt->input->cur + ctxt->checkIndex;
10963
10964
    while (cur < end) {
10965
        if (state) {
10966
            if (*cur == state)
10967
                state = 0;
10968
        } else if (*cur == '\'' || *cur == '"') {
10969
            state = *cur;
10970
        } else if (*cur == '>') {
10971
            ctxt->checkIndex = 0;
10972
            ctxt->endCheckState = 0;
10973
            return(1);
10974
        }
10975
        cur++;
10976
    }
10977
10978
    index = cur - ctxt->input->cur;
10979
    if (index > LONG_MAX) {
10980
        ctxt->checkIndex = 0;
10981
        ctxt->endCheckState = 0;
10982
        return(1);
10983
    }
10984
    ctxt->checkIndex = index;
10985
    ctxt->endCheckState = state;
10986
    return(0);
10987
}
10988
10989
/**
10990
 * xmlParseLookupInternalSubset:
10991
 * @ctxt:  an XML parser context
10992
 *
10993
 * Check whether there's enough data in the input buffer to finish parsing
10994
 * the internal subset.
10995
 */
10996
static int
10997
xmlParseLookupInternalSubset(xmlParserCtxtPtr ctxt) {
10998
    /*
10999
     * Sorry, but progressive parsing of the internal subset is not
11000
     * supported. We first check that the full content of the internal
11001
     * subset is available and parsing is launched only at that point.
11002
     * Internal subset ends with "']' S? '>'" in an unescaped section and
11003
     * not in a ']]>' sequence which are conditional sections.
11004
     */
11005
    const xmlChar *cur, *start;
11006
    const xmlChar *end = ctxt->input->end;
11007
    int state = ctxt->endCheckState;
11008
    size_t index;
11009
11010
    if (ctxt->checkIndex == 0) {
11011
        cur = ctxt->input->cur + 1;
11012
    } else {
11013
        cur = ctxt->input->cur + ctxt->checkIndex;
11014
    }
11015
    start = cur;
11016
11017
    while (cur < end) {
11018
        if (state == '-') {
11019
            if ((*cur == '-') &&
11020
                (cur[1] == '-') &&
11021
                (cur[2] == '>')) {
11022
                state = 0;
11023
                cur += 3;
11024
                start = cur;
11025
                continue;
11026
            }
11027
        }
11028
        else if (state == ']') {
11029
            if (*cur == '>') {
11030
                ctxt->checkIndex = 0;
11031
                ctxt->endCheckState = 0;
11032
                return(1);
11033
            }
11034
            if (IS_BLANK_CH(*cur)) {
11035
                state = ' ';
11036
            } else if (*cur != ']') {
11037
                state = 0;
11038
                start = cur;
11039
                continue;
11040
            }
11041
        }
11042
        else if (state == ' ') {
11043
            if (*cur == '>') {
11044
                ctxt->checkIndex = 0;
11045
                ctxt->endCheckState = 0;
11046
                return(1);
11047
            }
11048
            if (!IS_BLANK_CH(*cur)) {
11049
                state = 0;
11050
                start = cur;
11051
                continue;
11052
            }
11053
        }
11054
        else if (state != 0) {
11055
            if (*cur == state) {
11056
                state = 0;
11057
                start = cur + 1;
11058
            }
11059
        }
11060
        else if (*cur == '<') {
11061
            if ((cur[1] == '!') &&
11062
                (cur[2] == '-') &&
11063
                (cur[3] == '-')) {
11064
                state = '-';
11065
                cur += 4;
11066
                /* Don't treat <!--> as comment */
11067
                start = cur;
11068
                continue;
11069
            }
11070
        }
11071
        else if ((*cur == '"') || (*cur == '\'') || (*cur == ']')) {
11072
            state = *cur;
11073
        }
11074
11075
        cur++;
11076
    }
11077
11078
    /*
11079
     * Rescan the three last characters to detect "<!--" and "-->"
11080
     * split across chunks.
11081
     */
11082
    if ((state == 0) || (state == '-')) {
11083
        if (cur - start < 3)
11084
            cur = start;
11085
        else
11086
            cur -= 3;
11087
    }
11088
    index = cur - ctxt->input->cur;
11089
    if (index > LONG_MAX) {
11090
        ctxt->checkIndex = 0;
11091
        ctxt->endCheckState = 0;
11092
        return(1);
11093
    }
11094
    ctxt->checkIndex = index;
11095
    ctxt->endCheckState = state;
11096
    return(0);
11097
}
11098
11099
/**
11100
 * xmlParseTryOrFinish:
11101
 * @ctxt:  an XML parser context
11102
 * @terminate:  last chunk indicator
11103
 *
11104
 * Try to progress on parsing
11105
 *
11106
 * Returns zero if no parsing was possible
11107
 */
11108
static int
11109
xmlParseTryOrFinish(xmlParserCtxtPtr ctxt, int terminate) {
11110
    int ret = 0;
11111
    size_t avail;
11112
    xmlChar cur, next;
11113
11114
    if (ctxt->input == NULL)
11115
        return(0);
11116
11117
    if ((ctxt->input != NULL) &&
11118
        (ctxt->input->cur - ctxt->input->base > 4096)) {
11119
        xmlParserShrink(ctxt);
11120
    }
11121
11122
    while (ctxt->disableSAX == 0) {
11123
        avail = ctxt->input->end - ctxt->input->cur;
11124
        if (avail < 1)
11125
      goto done;
11126
        switch (ctxt->instate) {
11127
            case XML_PARSER_EOF:
11128
          /*
11129
     * Document parsing is done !
11130
     */
11131
          goto done;
11132
            case XML_PARSER_START:
11133
                /*
11134
                 * Very first chars read from the document flow.
11135
                 */
11136
                if ((!terminate) && (avail < 4))
11137
                    goto done;
11138
11139
                /*
11140
                 * We need more bytes to detect EBCDIC code pages.
11141
                 * See xmlDetectEBCDIC.
11142
                 */
11143
                if ((CMP4(CUR_PTR, 0x4C, 0x6F, 0xA7, 0x94)) &&
11144
                    (!terminate) && (avail < 200))
11145
                    goto done;
11146
11147
                xmlDetectEncoding(ctxt);
11148
                ctxt->instate = XML_PARSER_XML_DECL;
11149
    break;
11150
11151
            case XML_PARSER_XML_DECL:
11152
    if ((!terminate) && (avail < 2))
11153
        goto done;
11154
    cur = ctxt->input->cur[0];
11155
    next = ctxt->input->cur[1];
11156
          if ((cur == '<') && (next == '?')) {
11157
        /* PI or XML decl */
11158
        if ((!terminate) &&
11159
                        (!xmlParseLookupString(ctxt, 2, "?>", 2)))
11160
      goto done;
11161
        if ((ctxt->input->cur[2] == 'x') &&
11162
      (ctxt->input->cur[3] == 'm') &&
11163
      (ctxt->input->cur[4] == 'l') &&
11164
      (IS_BLANK_CH(ctxt->input->cur[5]))) {
11165
      ret += 5;
11166
      xmlParseXMLDecl(ctxt);
11167
        } else {
11168
      ctxt->version = xmlCharStrdup(XML_DEFAULT_VERSION);
11169
                        if (ctxt->version == NULL) {
11170
                            xmlErrMemory(ctxt);
11171
                            break;
11172
                        }
11173
        }
11174
    } else {
11175
        ctxt->version = xmlCharStrdup(XML_DEFAULT_VERSION);
11176
        if (ctxt->version == NULL) {
11177
            xmlErrMemory(ctxt);
11178
      break;
11179
        }
11180
    }
11181
                if ((ctxt->sax) && (ctxt->sax->setDocumentLocator)) {
11182
                    ctxt->sax->setDocumentLocator(ctxt->userData,
11183
                            (xmlSAXLocator *) &xmlDefaultSAXLocator);
11184
                }
11185
                if ((ctxt->sax) && (ctxt->sax->startDocument) &&
11186
                    (!ctxt->disableSAX))
11187
                    ctxt->sax->startDocument(ctxt->userData);
11188
                ctxt->instate = XML_PARSER_MISC;
11189
    break;
11190
            case XML_PARSER_START_TAG: {
11191
          const xmlChar *name;
11192
    const xmlChar *prefix = NULL;
11193
    const xmlChar *URI = NULL;
11194
                int line = ctxt->input->line;
11195
    int nbNs = 0;
11196
11197
    if ((!terminate) && (avail < 2))
11198
        goto done;
11199
    cur = ctxt->input->cur[0];
11200
          if (cur != '<') {
11201
        xmlFatalErrMsg(ctxt, XML_ERR_DOCUMENT_EMPTY,
11202
                                   "Start tag expected, '<' not found");
11203
                    ctxt->instate = XML_PARSER_EOF;
11204
                    xmlFinishDocument(ctxt);
11205
        goto done;
11206
    }
11207
    if ((!terminate) && (!xmlParseLookupGt(ctxt)))
11208
                    goto done;
11209
    if (ctxt->spaceNr == 0)
11210
        spacePush(ctxt, -1);
11211
    else if (*ctxt->space == -2)
11212
        spacePush(ctxt, -1);
11213
    else
11214
        spacePush(ctxt, *ctxt->space);
11215
#ifdef LIBXML_SAX1_ENABLED
11216
    if (ctxt->sax2)
11217
#endif /* LIBXML_SAX1_ENABLED */
11218
        name = xmlParseStartTag2(ctxt, &prefix, &URI, &nbNs);
11219
#ifdef LIBXML_SAX1_ENABLED
11220
    else
11221
        name = xmlParseStartTag(ctxt);
11222
#endif /* LIBXML_SAX1_ENABLED */
11223
    if (name == NULL) {
11224
        spacePop(ctxt);
11225
                    ctxt->instate = XML_PARSER_EOF;
11226
                    xmlFinishDocument(ctxt);
11227
        goto done;
11228
    }
11229
#ifdef LIBXML_VALID_ENABLED
11230
    /*
11231
     * [ VC: Root Element Type ]
11232
     * The Name in the document type declaration must match
11233
     * the element type of the root element.
11234
     */
11235
    if (ctxt->validate && ctxt->wellFormed && ctxt->myDoc &&
11236
        ctxt->node && (ctxt->node == ctxt->myDoc->children))
11237
        ctxt->valid &= xmlValidateRoot(&ctxt->vctxt, ctxt->myDoc);
11238
#endif /* LIBXML_VALID_ENABLED */
11239
11240
    /*
11241
     * Check for an Empty Element.
11242
     */
11243
    if ((RAW == '/') && (NXT(1) == '>')) {
11244
        SKIP(2);
11245
11246
        if (ctxt->sax2) {
11247
      if ((ctxt->sax != NULL) &&
11248
          (ctxt->sax->endElementNs != NULL) &&
11249
          (!ctxt->disableSAX))
11250
          ctxt->sax->endElementNs(ctxt->userData, name,
11251
                                  prefix, URI);
11252
      if (nbNs > 0)
11253
          xmlParserNsPop(ctxt, nbNs);
11254
#ifdef LIBXML_SAX1_ENABLED
11255
        } else {
11256
      if ((ctxt->sax != NULL) &&
11257
          (ctxt->sax->endElement != NULL) &&
11258
          (!ctxt->disableSAX))
11259
          ctxt->sax->endElement(ctxt->userData, name);
11260
#endif /* LIBXML_SAX1_ENABLED */
11261
        }
11262
        spacePop(ctxt);
11263
    } else if (RAW == '>') {
11264
        NEXT;
11265
                    nameNsPush(ctxt, name, prefix, URI, line, nbNs);
11266
    } else {
11267
        xmlFatalErrMsgStr(ctxt, XML_ERR_GT_REQUIRED,
11268
           "Couldn't find end of Start Tag %s\n",
11269
           name);
11270
        nodePop(ctxt);
11271
        spacePop(ctxt);
11272
                    if (nbNs > 0)
11273
                        xmlParserNsPop(ctxt, nbNs);
11274
    }
11275
11276
                if (ctxt->nameNr == 0)
11277
                    ctxt->instate = XML_PARSER_EPILOG;
11278
                else
11279
                    ctxt->instate = XML_PARSER_CONTENT;
11280
                break;
11281
      }
11282
            case XML_PARSER_CONTENT: {
11283
    cur = ctxt->input->cur[0];
11284
11285
    if (cur == '<') {
11286
                    if ((!terminate) && (avail < 2))
11287
                        goto done;
11288
        next = ctxt->input->cur[1];
11289
11290
                    if (next == '/') {
11291
                        ctxt->instate = XML_PARSER_END_TAG;
11292
                        break;
11293
                    } else if (next == '?') {
11294
                        if ((!terminate) &&
11295
                            (!xmlParseLookupString(ctxt, 2, "?>", 2)))
11296
                            goto done;
11297
                        xmlParsePI(ctxt);
11298
                        ctxt->instate = XML_PARSER_CONTENT;
11299
                        break;
11300
                    } else if (next == '!') {
11301
                        if ((!terminate) && (avail < 3))
11302
                            goto done;
11303
                        next = ctxt->input->cur[2];
11304
11305
                        if (next == '-') {
11306
                            if ((!terminate) && (avail < 4))
11307
                                goto done;
11308
                            if (ctxt->input->cur[3] == '-') {
11309
                                if ((!terminate) &&
11310
                                    (!xmlParseLookupString(ctxt, 4, "-->", 3)))
11311
                                    goto done;
11312
                                xmlParseComment(ctxt);
11313
                                ctxt->instate = XML_PARSER_CONTENT;
11314
                                break;
11315
                            }
11316
                        } else if (next == '[') {
11317
                            if ((!terminate) && (avail < 9))
11318
                                goto done;
11319
                            if ((ctxt->input->cur[2] == '[') &&
11320
                                (ctxt->input->cur[3] == 'C') &&
11321
                                (ctxt->input->cur[4] == 'D') &&
11322
                                (ctxt->input->cur[5] == 'A') &&
11323
                                (ctxt->input->cur[6] == 'T') &&
11324
                                (ctxt->input->cur[7] == 'A') &&
11325
                                (ctxt->input->cur[8] == '[')) {
11326
                                if ((!terminate) &&
11327
                                    (!xmlParseLookupString(ctxt, 9, "]]>", 3)))
11328
                                    goto done;
11329
                                ctxt->instate = XML_PARSER_CDATA_SECTION;
11330
                                xmlParseCDSect(ctxt);
11331
                                ctxt->instate = XML_PARSER_CONTENT;
11332
                                break;
11333
                            }
11334
                        }
11335
                    }
11336
    } else if (cur == '&') {
11337
        if ((!terminate) && (!xmlParseLookupChar(ctxt, ';')))
11338
      goto done;
11339
        xmlParseReference(ctxt);
11340
                    break;
11341
    } else {
11342
        /* TODO Avoid the extra copy, handle directly !!! */
11343
        /*
11344
         * Goal of the following test is:
11345
         *  - minimize calls to the SAX 'character' callback
11346
         *    when they are mergeable
11347
         *  - handle an problem for isBlank when we only parse
11348
         *    a sequence of blank chars and the next one is
11349
         *    not available to check against '<' presence.
11350
         *  - tries to homogenize the differences in SAX
11351
         *    callbacks between the push and pull versions
11352
         *    of the parser.
11353
         */
11354
        if (avail < XML_PARSER_BIG_BUFFER_SIZE) {
11355
      if ((!terminate) && (!xmlParseLookupCharData(ctxt)))
11356
          goto done;
11357
                    }
11358
                    ctxt->checkIndex = 0;
11359
        xmlParseCharDataInternal(ctxt, !terminate);
11360
                    break;
11361
    }
11362
11363
                ctxt->instate = XML_PARSER_START_TAG;
11364
    break;
11365
      }
11366
            case XML_PARSER_END_TAG:
11367
    if ((!terminate) && (!xmlParseLookupChar(ctxt, '>')))
11368
        goto done;
11369
    if (ctxt->sax2) {
11370
              xmlParseEndTag2(ctxt, &ctxt->pushTab[ctxt->nameNr - 1]);
11371
        nameNsPop(ctxt);
11372
    }
11373
#ifdef LIBXML_SAX1_ENABLED
11374
      else
11375
        xmlParseEndTag1(ctxt, 0);
11376
#endif /* LIBXML_SAX1_ENABLED */
11377
    if (ctxt->nameNr == 0) {
11378
        ctxt->instate = XML_PARSER_EPILOG;
11379
    } else {
11380
        ctxt->instate = XML_PARSER_CONTENT;
11381
    }
11382
    break;
11383
            case XML_PARSER_MISC:
11384
            case XML_PARSER_PROLOG:
11385
            case XML_PARSER_EPILOG:
11386
    SKIP_BLANKS;
11387
                avail = ctxt->input->end - ctxt->input->cur;
11388
    if (avail < 1)
11389
        goto done;
11390
    if (ctxt->input->cur[0] == '<') {
11391
                    if ((!terminate) && (avail < 2))
11392
                        goto done;
11393
                    next = ctxt->input->cur[1];
11394
                    if (next == '?') {
11395
                        if ((!terminate) &&
11396
                            (!xmlParseLookupString(ctxt, 2, "?>", 2)))
11397
                            goto done;
11398
                        xmlParsePI(ctxt);
11399
                        break;
11400
                    } else if (next == '!') {
11401
                        if ((!terminate) && (avail < 3))
11402
                            goto done;
11403
11404
                        if (ctxt->input->cur[2] == '-') {
11405
                            if ((!terminate) && (avail < 4))
11406
                                goto done;
11407
                            if (ctxt->input->cur[3] == '-') {
11408
                                if ((!terminate) &&
11409
                                    (!xmlParseLookupString(ctxt, 4, "-->", 3)))
11410
                                    goto done;
11411
                                xmlParseComment(ctxt);
11412
                                break;
11413
                            }
11414
                        } else if (ctxt->instate == XML_PARSER_MISC) {
11415
                            if ((!terminate) && (avail < 9))
11416
                                goto done;
11417
                            if ((ctxt->input->cur[2] == 'D') &&
11418
                                (ctxt->input->cur[3] == 'O') &&
11419
                                (ctxt->input->cur[4] == 'C') &&
11420
                                (ctxt->input->cur[5] == 'T') &&
11421
                                (ctxt->input->cur[6] == 'Y') &&
11422
                                (ctxt->input->cur[7] == 'P') &&
11423
                                (ctxt->input->cur[8] == 'E')) {
11424
                                if ((!terminate) && (!xmlParseLookupGt(ctxt)))
11425
                                    goto done;
11426
                                ctxt->inSubset = 1;
11427
                                xmlParseDocTypeDecl(ctxt);
11428
                                if (RAW == '[') {
11429
                                    ctxt->instate = XML_PARSER_DTD;
11430
                                } else {
11431
                                    if (RAW == '>')
11432
                                        NEXT;
11433
                                    /*
11434
                                     * Create and update the external subset.
11435
                                     */
11436
                                    ctxt->inSubset = 2;
11437
                                    if ((ctxt->sax != NULL) &&
11438
                                        (!ctxt->disableSAX) &&
11439
                                        (ctxt->sax->externalSubset != NULL))
11440
                                        ctxt->sax->externalSubset(
11441
                                                ctxt->userData,
11442
                                                ctxt->intSubName,
11443
                                                ctxt->extSubSystem,
11444
                                                ctxt->extSubURI);
11445
                                    ctxt->inSubset = 0;
11446
                                    xmlCleanSpecialAttr(ctxt);
11447
                                    ctxt->instate = XML_PARSER_PROLOG;
11448
                                }
11449
                                break;
11450
                            }
11451
                        }
11452
                    }
11453
                }
11454
11455
                if (ctxt->instate == XML_PARSER_EPILOG) {
11456
                    if (ctxt->errNo == XML_ERR_OK)
11457
                        xmlFatalErr(ctxt, XML_ERR_DOCUMENT_END, NULL);
11458
        ctxt->instate = XML_PARSER_EOF;
11459
                    xmlFinishDocument(ctxt);
11460
                } else {
11461
        ctxt->instate = XML_PARSER_START_TAG;
11462
    }
11463
    break;
11464
            case XML_PARSER_DTD: {
11465
                if ((!terminate) && (!xmlParseLookupInternalSubset(ctxt)))
11466
                    goto done;
11467
    xmlParseInternalSubset(ctxt);
11468
    ctxt->inSubset = 2;
11469
    if ((ctxt->sax != NULL) && (!ctxt->disableSAX) &&
11470
        (ctxt->sax->externalSubset != NULL))
11471
        ctxt->sax->externalSubset(ctxt->userData, ctxt->intSubName,
11472
          ctxt->extSubSystem, ctxt->extSubURI);
11473
    ctxt->inSubset = 0;
11474
    xmlCleanSpecialAttr(ctxt);
11475
    ctxt->instate = XML_PARSER_PROLOG;
11476
                break;
11477
      }
11478
            default:
11479
                xmlFatalErrMsg(ctxt, XML_ERR_INTERNAL_ERROR,
11480
      "PP: internal error\n");
11481
    ctxt->instate = XML_PARSER_EOF;
11482
    break;
11483
  }
11484
    }
11485
done:
11486
    return(ret);
11487
}
11488
11489
/**
11490
 * xmlParseChunk:
11491
 * @ctxt:  an XML parser context
11492
 * @chunk:  chunk of memory
11493
 * @size:  size of chunk in bytes
11494
 * @terminate:  last chunk indicator
11495
 *
11496
 * Parse a chunk of memory in push parser mode.
11497
 *
11498
 * Assumes that the parser context was initialized with
11499
 * xmlCreatePushParserCtxt.
11500
 *
11501
 * The last chunk, which will often be empty, must be marked with
11502
 * the @terminate flag. With the default SAX callbacks, the resulting
11503
 * document will be available in ctxt->myDoc. This pointer will not
11504
 * be freed when calling xmlFreeParserCtxt and must be freed by the
11505
 * caller. If the document isn't well-formed, it will still be returned
11506
 * in ctxt->myDoc.
11507
 *
11508
 * As an exception, xmlCtxtResetPush will free the document in
11509
 * ctxt->myDoc. So ctxt->myDoc should be set to NULL after extracting
11510
 * the document.
11511
 *
11512
 * Returns an xmlParserErrors code (0 on success).
11513
 */
11514
int
11515
xmlParseChunk(xmlParserCtxtPtr ctxt, const char *chunk, int size,
11516
              int terminate) {
11517
    size_t curBase;
11518
    size_t maxLength;
11519
    size_t pos;
11520
    int end_in_lf = 0;
11521
    int res;
11522
11523
    if ((ctxt == NULL) || (size < 0))
11524
        return(XML_ERR_ARGUMENT);
11525
    if ((chunk == NULL) && (size > 0))
11526
        return(XML_ERR_ARGUMENT);
11527
    if ((ctxt->input == NULL) || (ctxt->input->buf == NULL))
11528
        return(XML_ERR_ARGUMENT);
11529
    if (ctxt->disableSAX != 0)
11530
        return(ctxt->errNo);
11531
11532
    ctxt->input->flags |= XML_INPUT_PROGRESSIVE;
11533
    if (ctxt->instate == XML_PARSER_START)
11534
        xmlCtxtInitializeLate(ctxt);
11535
    if ((size > 0) && (chunk != NULL) && (!terminate) &&
11536
        (chunk[size - 1] == '\r')) {
11537
  end_in_lf = 1;
11538
  size--;
11539
    }
11540
11541
    /*
11542
     * Also push an empty chunk to make sure that the raw buffer
11543
     * will be flushed if there is an encoder.
11544
     */
11545
    pos = ctxt->input->cur - ctxt->input->base;
11546
    res = xmlParserInputBufferPush(ctxt->input->buf, size, chunk);
11547
    xmlBufUpdateInput(ctxt->input->buf->buffer, ctxt->input, pos);
11548
    if (res < 0) {
11549
        xmlCtxtErrIO(ctxt, ctxt->input->buf->error, NULL);
11550
        xmlHaltParser(ctxt);
11551
        return(ctxt->errNo);
11552
    }
11553
11554
    xmlParseTryOrFinish(ctxt, terminate);
11555
11556
    curBase = ctxt->input->cur - ctxt->input->base;
11557
    maxLength = (ctxt->options & XML_PARSE_HUGE) ?
11558
                XML_MAX_HUGE_LENGTH :
11559
                XML_MAX_LOOKUP_LIMIT;
11560
    if (curBase > maxLength) {
11561
        xmlFatalErr(ctxt, XML_ERR_RESOURCE_LIMIT,
11562
                    "Buffer size limit exceeded, try XML_PARSE_HUGE\n");
11563
        xmlHaltParser(ctxt);
11564
    }
11565
11566
    if ((ctxt->errNo != XML_ERR_OK) && (ctxt->disableSAX != 0))
11567
        return(ctxt->errNo);
11568
11569
    if (end_in_lf == 1) {
11570
  pos = ctxt->input->cur - ctxt->input->base;
11571
  res = xmlParserInputBufferPush(ctxt->input->buf, 1, "\r");
11572
  xmlBufUpdateInput(ctxt->input->buf->buffer, ctxt->input, pos);
11573
        if (res < 0) {
11574
            xmlCtxtErrIO(ctxt, ctxt->input->buf->error, NULL);
11575
            xmlHaltParser(ctxt);
11576
            return(ctxt->errNo);
11577
        }
11578
    }
11579
    if (terminate) {
11580
  /*
11581
   * Check for termination
11582
   */
11583
        if ((ctxt->instate != XML_PARSER_EOF) &&
11584
            (ctxt->instate != XML_PARSER_EPILOG)) {
11585
            if (ctxt->nameNr > 0) {
11586
                const xmlChar *name = ctxt->nameTab[ctxt->nameNr - 1];
11587
                int line = ctxt->pushTab[ctxt->nameNr - 1].line;
11588
                xmlFatalErrMsgStrIntStr(ctxt, XML_ERR_TAG_NOT_FINISHED,
11589
                        "Premature end of data in tag %s line %d\n",
11590
                        name, line, NULL);
11591
            } else if (ctxt->instate == XML_PARSER_START) {
11592
                xmlFatalErr(ctxt, XML_ERR_DOCUMENT_EMPTY, NULL);
11593
            } else {
11594
                xmlFatalErrMsg(ctxt, XML_ERR_DOCUMENT_EMPTY,
11595
                               "Start tag expected, '<' not found\n");
11596
            }
11597
        } else {
11598
            xmlParserCheckEOF(ctxt, XML_ERR_DOCUMENT_END);
11599
        }
11600
  if (ctxt->instate != XML_PARSER_EOF) {
11601
            ctxt->instate = XML_PARSER_EOF;
11602
            xmlFinishDocument(ctxt);
11603
  }
11604
    }
11605
    if (ctxt->wellFormed == 0)
11606
  return((xmlParserErrors) ctxt->errNo);
11607
    else
11608
        return(0);
11609
}
11610
11611
/************************************************************************
11612
 *                  *
11613
 *    I/O front end functions to the parser     *
11614
 *                  *
11615
 ************************************************************************/
11616
11617
/**
11618
 * xmlCreatePushParserCtxt:
11619
 * @sax:  a SAX handler (optional)
11620
 * @user_data:  user data for SAX callbacks (optional)
11621
 * @chunk:  initial chunk (optional, deprecated)
11622
 * @size:  size of initial chunk in bytes
11623
 * @filename:  file name or URI (optional)
11624
 *
11625
 * Create a parser context for using the XML parser in push mode.
11626
 * See xmlParseChunk.
11627
 *
11628
 * Passing an initial chunk is useless and deprecated.
11629
 *
11630
 * The push parser doesn't support recovery mode or the
11631
 * XML_PARSE_NOBLANKS option.
11632
 *
11633
 * @filename is used as base URI to fetch external entities and for
11634
 * error reports.
11635
 *
11636
 * Returns the new parser context or NULL if a memory allocation
11637
 * failed.
11638
 */
11639
11640
xmlParserCtxtPtr
11641
xmlCreatePushParserCtxt(xmlSAXHandlerPtr sax, void *user_data,
11642
                        const char *chunk, int size, const char *filename) {
11643
    xmlParserCtxtPtr ctxt;
11644
    xmlParserInputPtr input;
11645
11646
    ctxt = xmlNewSAXParserCtxt(sax, user_data);
11647
    if (ctxt == NULL)
11648
  return(NULL);
11649
11650
    ctxt->options &= ~XML_PARSE_NODICT;
11651
    ctxt->dictNames = 1;
11652
11653
    input = xmlNewPushInput(filename, chunk, size);
11654
    if (input == NULL) {
11655
  xmlFreeParserCtxt(ctxt);
11656
  return(NULL);
11657
    }
11658
    if (xmlCtxtPushInput(ctxt, input) < 0) {
11659
        xmlFreeInputStream(input);
11660
        xmlFreeParserCtxt(ctxt);
11661
        return(NULL);
11662
    }
11663
11664
    return(ctxt);
11665
}
11666
#endif /* LIBXML_PUSH_ENABLED */
11667
11668
/**
11669
 * xmlStopParser:
11670
 * @ctxt:  an XML parser context
11671
 *
11672
 * Blocks further parser processing
11673
 */
11674
void
11675
23.5M
xmlStopParser(xmlParserCtxtPtr ctxt) {
11676
23.5M
    if (ctxt == NULL)
11677
23.5M
        return;
11678
0
    xmlHaltParser(ctxt);
11679
0
    if (ctxt->errNo != XML_ERR_NO_MEMORY)
11680
0
        ctxt->errNo = XML_ERR_USER_STOP;
11681
0
}
11682
11683
/**
11684
 * xmlCreateIOParserCtxt:
11685
 * @sax:  a SAX handler (optional)
11686
 * @user_data:  user data for SAX callbacks (optional)
11687
 * @ioread:  an I/O read function
11688
 * @ioclose:  an I/O close function (optional)
11689
 * @ioctx:  an I/O handler
11690
 * @enc:  the charset encoding if known (deprecated)
11691
 *
11692
 * Create a parser context for using the XML parser with an existing
11693
 * I/O stream
11694
 *
11695
 * Returns the new parser context or NULL
11696
 */
11697
xmlParserCtxtPtr
11698
xmlCreateIOParserCtxt(xmlSAXHandlerPtr sax, void *user_data,
11699
                      xmlInputReadCallback ioread,
11700
                      xmlInputCloseCallback ioclose,
11701
0
                      void *ioctx, xmlCharEncoding enc) {
11702
0
    xmlParserCtxtPtr ctxt;
11703
0
    xmlParserInputPtr input;
11704
0
    const char *encoding;
11705
11706
0
    ctxt = xmlNewSAXParserCtxt(sax, user_data);
11707
0
    if (ctxt == NULL)
11708
0
  return(NULL);
11709
11710
0
    encoding = xmlGetCharEncodingName(enc);
11711
0
    input = xmlCtxtNewInputFromIO(ctxt, NULL, ioread, ioclose, ioctx,
11712
0
                                  encoding, 0);
11713
0
    if (input == NULL) {
11714
0
  xmlFreeParserCtxt(ctxt);
11715
0
        return (NULL);
11716
0
    }
11717
0
    if (xmlCtxtPushInput(ctxt, input) < 0) {
11718
0
        xmlFreeInputStream(input);
11719
0
        xmlFreeParserCtxt(ctxt);
11720
0
        return(NULL);
11721
0
    }
11722
11723
0
    return(ctxt);
11724
0
}
11725
11726
#ifdef LIBXML_VALID_ENABLED
11727
/************************************************************************
11728
 *                  *
11729
 *    Front ends when parsing a DTD       *
11730
 *                  *
11731
 ************************************************************************/
11732
11733
/**
11734
 * xmlCtxtParseDtd:
11735
 * @ctxt:  a parser context
11736
 * @input:  a parser input
11737
 * @publicId:  public ID of the DTD (optional)
11738
 * @systemId:  system ID of the DTD (optional)
11739
 *
11740
 * Parse a DTD.
11741
 *
11742
 * Option XML_PARSE_DTDLOAD should be enabled in the parser context
11743
 * to make external entities work.
11744
 *
11745
 * Availabe since 2.14.0.
11746
 *
11747
 * Returns the resulting xmlDtdPtr or NULL in case of error.
11748
 * @input will be freed by the function in any case.
11749
 */
11750
xmlDtdPtr
11751
xmlCtxtParseDtd(xmlParserCtxtPtr ctxt, xmlParserInputPtr input,
11752
                const xmlChar *publicId, const xmlChar *systemId) {
11753
    xmlDtdPtr ret = NULL;
11754
11755
    if ((ctxt == NULL) || (input == NULL)) {
11756
        xmlFatalErr(ctxt, XML_ERR_ARGUMENT, NULL);
11757
        xmlFreeInputStream(input);
11758
        return(NULL);
11759
    }
11760
11761
    if (xmlCtxtPushInput(ctxt, input) < 0) {
11762
        xmlFreeInputStream(input);
11763
        return(NULL);
11764
    }
11765
11766
    if (publicId == NULL)
11767
        publicId = BAD_CAST "none";
11768
    if (systemId == NULL)
11769
        systemId = BAD_CAST "none";
11770
11771
    ctxt->myDoc = xmlNewDoc(BAD_CAST "1.0");
11772
    if (ctxt->myDoc == NULL) {
11773
        xmlErrMemory(ctxt);
11774
        goto error;
11775
    }
11776
    ctxt->myDoc->properties = XML_DOC_INTERNAL;
11777
    ctxt->myDoc->extSubset = xmlNewDtd(ctxt->myDoc, BAD_CAST "none",
11778
                                       publicId, systemId);
11779
    if (ctxt->myDoc->extSubset == NULL) {
11780
        xmlErrMemory(ctxt);
11781
        xmlFreeDoc(ctxt->myDoc);
11782
        goto error;
11783
    }
11784
11785
    xmlParseExternalSubset(ctxt, publicId, systemId);
11786
11787
    if (ctxt->wellFormed) {
11788
        ret = ctxt->myDoc->extSubset;
11789
        ctxt->myDoc->extSubset = NULL;
11790
        if (ret != NULL) {
11791
            xmlNodePtr tmp;
11792
11793
            ret->doc = NULL;
11794
            tmp = ret->children;
11795
            while (tmp != NULL) {
11796
                tmp->doc = NULL;
11797
                tmp = tmp->next;
11798
            }
11799
        }
11800
    } else {
11801
        ret = NULL;
11802
    }
11803
    xmlFreeDoc(ctxt->myDoc);
11804
    ctxt->myDoc = NULL;
11805
11806
error:
11807
    xmlFreeInputStream(xmlCtxtPopInput(ctxt));
11808
11809
    return(ret);
11810
}
11811
11812
/**
11813
 * xmlIOParseDTD:
11814
 * @sax:  the SAX handler block or NULL
11815
 * @input:  an Input Buffer
11816
 * @enc:  the charset encoding if known
11817
 *
11818
 * DEPRECATED: Use xmlCtxtParseDtd.
11819
 *
11820
 * Load and parse a DTD
11821
 *
11822
 * Returns the resulting xmlDtdPtr or NULL in case of error.
11823
 * @input will be freed by the function in any case.
11824
 */
11825
11826
xmlDtdPtr
11827
xmlIOParseDTD(xmlSAXHandlerPtr sax, xmlParserInputBufferPtr input,
11828
        xmlCharEncoding enc) {
11829
    xmlDtdPtr ret = NULL;
11830
    xmlParserCtxtPtr ctxt;
11831
    xmlParserInputPtr pinput = NULL;
11832
11833
    if (input == NULL)
11834
  return(NULL);
11835
11836
    ctxt = xmlNewSAXParserCtxt(sax, NULL);
11837
    if (ctxt == NULL) {
11838
        xmlFreeParserInputBuffer(input);
11839
  return(NULL);
11840
    }
11841
    xmlCtxtSetOptions(ctxt, XML_PARSE_DTDLOAD);
11842
11843
    /*
11844
     * generate a parser input from the I/O handler
11845
     */
11846
11847
    pinput = xmlNewIOInputStream(ctxt, input, XML_CHAR_ENCODING_NONE);
11848
    if (pinput == NULL) {
11849
        xmlFreeParserInputBuffer(input);
11850
  xmlFreeParserCtxt(ctxt);
11851
  return(NULL);
11852
    }
11853
11854
    if (enc != XML_CHAR_ENCODING_NONE) {
11855
        xmlSwitchEncoding(ctxt, enc);
11856
    }
11857
11858
    ret = xmlCtxtParseDtd(ctxt, pinput, NULL, NULL);
11859
11860
    xmlFreeParserCtxt(ctxt);
11861
    return(ret);
11862
}
11863
11864
/**
11865
 * xmlSAXParseDTD:
11866
 * @sax:  the SAX handler block
11867
 * @ExternalID:  a NAME* containing the External ID of the DTD
11868
 * @SystemID:  a NAME* containing the URL to the DTD
11869
 *
11870
 * DEPRECATED: Use xmlCtxtParseDtd.
11871
 *
11872
 * Load and parse an external subset.
11873
 *
11874
 * Returns the resulting xmlDtdPtr or NULL in case of error.
11875
 */
11876
11877
xmlDtdPtr
11878
xmlSAXParseDTD(xmlSAXHandlerPtr sax, const xmlChar *ExternalID,
11879
                          const xmlChar *SystemID) {
11880
    xmlDtdPtr ret = NULL;
11881
    xmlParserCtxtPtr ctxt;
11882
    xmlParserInputPtr input = NULL;
11883
    xmlChar* systemIdCanonic;
11884
11885
    if ((ExternalID == NULL) && (SystemID == NULL)) return(NULL);
11886
11887
    ctxt = xmlNewSAXParserCtxt(sax, NULL);
11888
    if (ctxt == NULL) {
11889
  return(NULL);
11890
    }
11891
    xmlCtxtSetOptions(ctxt, XML_PARSE_DTDLOAD);
11892
11893
    /*
11894
     * Canonicalise the system ID
11895
     */
11896
    systemIdCanonic = xmlCanonicPath(SystemID);
11897
    if ((SystemID != NULL) && (systemIdCanonic == NULL)) {
11898
  xmlFreeParserCtxt(ctxt);
11899
  return(NULL);
11900
    }
11901
11902
    /*
11903
     * Ask the Entity resolver to load the damn thing
11904
     */
11905
11906
    if ((ctxt->sax != NULL) && (ctxt->sax->resolveEntity != NULL))
11907
  input = ctxt->sax->resolveEntity(ctxt->userData, ExternalID,
11908
                                   systemIdCanonic);
11909
    if (input == NULL) {
11910
  xmlFreeParserCtxt(ctxt);
11911
  if (systemIdCanonic != NULL)
11912
      xmlFree(systemIdCanonic);
11913
  return(NULL);
11914
    }
11915
11916
    if (input->filename == NULL)
11917
  input->filename = (char *) systemIdCanonic;
11918
    else
11919
  xmlFree(systemIdCanonic);
11920
11921
    ret = xmlCtxtParseDtd(ctxt, input, ExternalID, SystemID);
11922
11923
    xmlFreeParserCtxt(ctxt);
11924
    return(ret);
11925
}
11926
11927
11928
/**
11929
 * xmlParseDTD:
11930
 * @ExternalID:  a NAME* containing the External ID of the DTD
11931
 * @SystemID:  a NAME* containing the URL to the DTD
11932
 *
11933
 * Load and parse an external subset.
11934
 *
11935
 * Returns the resulting xmlDtdPtr or NULL in case of error.
11936
 */
11937
11938
xmlDtdPtr
11939
xmlParseDTD(const xmlChar *ExternalID, const xmlChar *SystemID) {
11940
    return(xmlSAXParseDTD(NULL, ExternalID, SystemID));
11941
}
11942
#endif /* LIBXML_VALID_ENABLED */
11943
11944
/************************************************************************
11945
 *                  *
11946
 *    Front ends when parsing an Entity     *
11947
 *                  *
11948
 ************************************************************************/
11949
11950
static xmlNodePtr
11951
xmlCtxtParseContentInternal(xmlParserCtxtPtr ctxt, xmlParserInputPtr input,
11952
10.5k
                            int hasTextDecl, int buildTree) {
11953
10.5k
    xmlNodePtr root = NULL;
11954
10.5k
    xmlNodePtr list = NULL;
11955
10.5k
    xmlChar *rootName = BAD_CAST "#root";
11956
10.5k
    int result;
11957
11958
10.5k
    if (buildTree) {
11959
10.5k
        root = xmlNewDocNode(ctxt->myDoc, NULL, rootName, NULL);
11960
10.5k
        if (root == NULL) {
11961
1
            xmlErrMemory(ctxt);
11962
1
            goto error;
11963
1
        }
11964
10.5k
    }
11965
11966
10.5k
    if (xmlCtxtPushInput(ctxt, input) < 0)
11967
1
        goto error;
11968
11969
10.5k
    nameNsPush(ctxt, rootName, NULL, NULL, 0, 0);
11970
10.5k
    spacePush(ctxt, -1);
11971
11972
10.5k
    if (buildTree)
11973
10.5k
        nodePush(ctxt, root);
11974
11975
10.5k
    if (hasTextDecl) {
11976
9.00k
        xmlDetectEncoding(ctxt);
11977
11978
        /*
11979
         * Parse a possible text declaration first
11980
         */
11981
9.00k
        if ((CMP5(CUR_PTR, '<', '?', 'x', 'm', 'l')) &&
11982
3.79k
            (IS_BLANK_CH(NXT(5)))) {
11983
3.36k
            xmlParseTextDecl(ctxt);
11984
            /*
11985
             * An XML-1.0 document can't reference an entity not XML-1.0
11986
             */
11987
3.36k
            if ((xmlStrEqual(ctxt->version, BAD_CAST "1.0")) &&
11988
3.29k
                (!xmlStrEqual(ctxt->input->version, BAD_CAST "1.0"))) {
11989
1.01k
                xmlFatalErrMsg(ctxt, XML_ERR_VERSION_MISMATCH,
11990
1.01k
                               "Version mismatch between document and "
11991
1.01k
                               "entity\n");
11992
1.01k
            }
11993
3.36k
        }
11994
9.00k
    }
11995
11996
10.5k
    xmlParseContentInternal(ctxt);
11997
11998
10.5k
    if (ctxt->input->cur < ctxt->input->end)
11999
1.31k
  xmlFatalErr(ctxt, XML_ERR_NOT_WELL_BALANCED, NULL);
12000
12001
10.5k
    if ((ctxt->wellFormed) ||
12002
8.01k
        ((ctxt->recovery) && (!xmlCtxtIsCatastrophicError(ctxt)))) {
12003
2.54k
        if (root != NULL) {
12004
2.54k
            xmlNodePtr cur;
12005
12006
            /*
12007
             * Unlink newly created node list.
12008
             */
12009
2.54k
            list = root->children;
12010
2.54k
            root->children = NULL;
12011
2.54k
            root->last = NULL;
12012
6.39k
            for (cur = list; cur != NULL; cur = cur->next)
12013
3.85k
                cur->parent = NULL;
12014
2.54k
        }
12015
2.54k
    }
12016
12017
    /*
12018
     * Read the rest of the stream in case of errors. We want
12019
     * to account for the whole entity size.
12020
     */
12021
29.7k
    do {
12022
29.7k
        ctxt->input->cur = ctxt->input->end;
12023
29.7k
        xmlParserShrink(ctxt);
12024
29.7k
        result = xmlParserGrow(ctxt);
12025
29.7k
    } while (result > 0);
12026
12027
10.5k
    if (buildTree)
12028
10.5k
        nodePop(ctxt);
12029
12030
10.5k
    namePop(ctxt);
12031
10.5k
    spacePop(ctxt);
12032
12033
10.5k
    xmlCtxtPopInput(ctxt);
12034
12035
10.5k
error:
12036
10.5k
    xmlFreeNode(root);
12037
12038
10.5k
    return(list);
12039
10.5k
}
12040
12041
static void
12042
11.6k
xmlCtxtParseEntity(xmlParserCtxtPtr ctxt, xmlEntityPtr ent) {
12043
11.6k
    xmlParserInputPtr input;
12044
11.6k
    xmlNodePtr list;
12045
11.6k
    unsigned long consumed;
12046
11.6k
    int isExternal;
12047
11.6k
    int buildTree;
12048
11.6k
    int oldMinNsIndex;
12049
11.6k
    int oldNodelen, oldNodemem;
12050
12051
11.6k
    isExternal = (ent->etype == XML_EXTERNAL_GENERAL_PARSED_ENTITY);
12052
11.6k
    buildTree = (ctxt->node != NULL);
12053
12054
    /*
12055
     * Recursion check
12056
     */
12057
11.6k
    if (ent->flags & XML_ENT_EXPANDING) {
12058
238
        xmlFatalErr(ctxt, XML_ERR_ENTITY_LOOP, NULL);
12059
238
        xmlHaltParser(ctxt);
12060
238
        goto error;
12061
238
    }
12062
12063
    /*
12064
     * Load entity
12065
     */
12066
11.3k
    input = xmlNewEntityInputStream(ctxt, ent);
12067
11.3k
    if (input == NULL)
12068
850
        goto error;
12069
12070
    /*
12071
     * When building a tree, we need to limit the scope of namespace
12072
     * declarations, so that entities don't reference xmlNs structs
12073
     * from the parent of a reference.
12074
     */
12075
10.5k
    oldMinNsIndex = ctxt->nsdb->minNsIndex;
12076
10.5k
    if (buildTree)
12077
10.5k
        ctxt->nsdb->minNsIndex = ctxt->nsNr;
12078
12079
10.5k
    oldNodelen = ctxt->nodelen;
12080
10.5k
    oldNodemem = ctxt->nodemem;
12081
10.5k
    ctxt->nodelen = 0;
12082
10.5k
    ctxt->nodemem = 0;
12083
12084
    /*
12085
     * Parse content
12086
     *
12087
     * This initiates a recursive call chain:
12088
     *
12089
     * - xmlCtxtParseContentInternal
12090
     * - xmlParseContentInternal
12091
     * - xmlParseReference
12092
     * - xmlCtxtParseEntity
12093
     *
12094
     * The nesting depth is limited by the maximum number of inputs,
12095
     * see xmlCtxtPushInput.
12096
     *
12097
     * It's possible to make this non-recursive (minNsIndex must be
12098
     * stored in the input struct) at the expense of code readability.
12099
     */
12100
12101
10.5k
    ent->flags |= XML_ENT_EXPANDING;
12102
12103
10.5k
    list = xmlCtxtParseContentInternal(ctxt, input, isExternal, buildTree);
12104
12105
10.5k
    ent->flags &= ~XML_ENT_EXPANDING;
12106
12107
10.5k
    ctxt->nsdb->minNsIndex = oldMinNsIndex;
12108
10.5k
    ctxt->nodelen = oldNodelen;
12109
10.5k
    ctxt->nodemem = oldNodemem;
12110
12111
    /*
12112
     * Entity size accounting
12113
     */
12114
10.5k
    consumed = input->consumed;
12115
10.5k
    xmlSaturatedAddSizeT(&consumed, input->end - input->base);
12116
12117
10.5k
    if ((ent->flags & XML_ENT_CHECKED) == 0)
12118
10.0k
        xmlSaturatedAdd(&ent->expandedSize, consumed);
12119
12120
10.5k
    if ((ent->flags & XML_ENT_PARSED) == 0) {
12121
10.0k
        if (isExternal)
12122
8.79k
            xmlSaturatedAdd(&ctxt->sizeentities, consumed);
12123
12124
10.0k
        ent->children = list;
12125
12126
13.9k
        while (list != NULL) {
12127
3.85k
            list->parent = (xmlNodePtr) ent;
12128
12129
            /*
12130
             * Downstream code like the nginx xslt module can set
12131
             * ctxt->myDoc->extSubset to a separate DTD, so the entity
12132
             * might have a different or a NULL document.
12133
             */
12134
3.85k
            if (list->doc != ent->doc)
12135
0
                xmlSetTreeDoc(list, ent->doc);
12136
12137
3.85k
            if (list->next == NULL)
12138
2.18k
                ent->last = list;
12139
3.85k
            list = list->next;
12140
3.85k
        }
12141
10.0k
    } else {
12142
489
        xmlFreeNodeList(list);
12143
489
    }
12144
12145
10.5k
    xmlFreeInputStream(input);
12146
12147
11.6k
error:
12148
11.6k
    ent->flags |= XML_ENT_PARSED | XML_ENT_CHECKED;
12149
11.6k
}
12150
12151
/**
12152
 * xmlParseCtxtExternalEntity:
12153
 * @ctxt:  the existing parsing context
12154
 * @URL:  the URL for the entity to load
12155
 * @ID:  the System ID for the entity to load
12156
 * @listOut:  the return value for the set of parsed nodes
12157
 *
12158
 * Parse an external general entity within an existing parsing context
12159
 * An external general parsed entity is well-formed if it matches the
12160
 * production labeled extParsedEnt.
12161
 *
12162
 * [78] extParsedEnt ::= TextDecl? content
12163
 *
12164
 * Returns 0 if the entity is well formed, -1 in case of args problem and
12165
 *    the parser error code otherwise
12166
 */
12167
12168
int
12169
xmlParseCtxtExternalEntity(xmlParserCtxtPtr ctxt, const xmlChar *URL,
12170
0
                           const xmlChar *ID, xmlNodePtr *listOut) {
12171
0
    xmlParserInputPtr input;
12172
0
    xmlNodePtr list;
12173
12174
0
    if (listOut != NULL)
12175
0
        *listOut = NULL;
12176
12177
0
    if (ctxt == NULL)
12178
0
        return(XML_ERR_ARGUMENT);
12179
12180
0
    input = xmlLoadResource(ctxt, (char *) URL, (char *) ID,
12181
0
                            XML_RESOURCE_GENERAL_ENTITY);
12182
0
    if (input == NULL)
12183
0
        return(ctxt->errNo);
12184
12185
0
    xmlCtxtInitializeLate(ctxt);
12186
12187
0
    list = xmlCtxtParseContentInternal(ctxt, input, /* hasTextDecl */ 1, 1);
12188
0
    if (listOut != NULL)
12189
0
        *listOut = list;
12190
0
    else
12191
0
        xmlFreeNodeList(list);
12192
12193
0
    xmlFreeInputStream(input);
12194
0
    return(ctxt->errNo);
12195
0
}
12196
12197
#ifdef LIBXML_SAX1_ENABLED
12198
/**
12199
 * xmlParseExternalEntity:
12200
 * @doc:  the document the chunk pertains to
12201
 * @sax:  the SAX handler block (possibly NULL)
12202
 * @user_data:  The user data returned on SAX callbacks (possibly NULL)
12203
 * @depth:  Used for loop detection, use 0
12204
 * @URL:  the URL for the entity to load
12205
 * @ID:  the System ID for the entity to load
12206
 * @list:  the return value for the set of parsed nodes
12207
 *
12208
 * DEPRECATED: Use xmlParseCtxtExternalEntity.
12209
 *
12210
 * Parse an external general entity
12211
 * An external general parsed entity is well-formed if it matches the
12212
 * production labeled extParsedEnt.
12213
 *
12214
 * [78] extParsedEnt ::= TextDecl? content
12215
 *
12216
 * Returns 0 if the entity is well formed, -1 in case of args problem and
12217
 *    the parser error code otherwise
12218
 */
12219
12220
int
12221
xmlParseExternalEntity(xmlDocPtr doc, xmlSAXHandlerPtr sax, void *user_data,
12222
    int depth, const xmlChar *URL, const xmlChar *ID, xmlNodePtr *list) {
12223
    xmlParserCtxtPtr ctxt;
12224
    int ret;
12225
12226
    if (list != NULL)
12227
        *list = NULL;
12228
12229
    if (doc == NULL)
12230
        return(XML_ERR_ARGUMENT);
12231
12232
    ctxt = xmlNewSAXParserCtxt(sax, user_data);
12233
    if (ctxt == NULL)
12234
        return(XML_ERR_NO_MEMORY);
12235
12236
    ctxt->depth = depth;
12237
    ctxt->myDoc = doc;
12238
    ret = xmlParseCtxtExternalEntity(ctxt, URL, ID, list);
12239
12240
    xmlFreeParserCtxt(ctxt);
12241
    return(ret);
12242
}
12243
12244
/**
12245
 * xmlParseBalancedChunkMemory:
12246
 * @doc:  the document the chunk pertains to (must not be NULL)
12247
 * @sax:  the SAX handler block (possibly NULL)
12248
 * @user_data:  The user data returned on SAX callbacks (possibly NULL)
12249
 * @depth:  Used for loop detection, use 0
12250
 * @string:  the input string in UTF8 or ISO-Latin (zero terminated)
12251
 * @lst:  the return value for the set of parsed nodes
12252
 *
12253
 * Parse a well-balanced chunk of an XML document
12254
 * called by the parser
12255
 * The allowed sequence for the Well Balanced Chunk is the one defined by
12256
 * the content production in the XML grammar:
12257
 *
12258
 * [43] content ::= (element | CharData | Reference | CDSect | PI | Comment)*
12259
 *
12260
 * Returns 0 if the chunk is well balanced, -1 in case of args problem and
12261
 *    the parser error code otherwise
12262
 */
12263
12264
int
12265
xmlParseBalancedChunkMemory(xmlDocPtr doc, xmlSAXHandlerPtr sax,
12266
     void *user_data, int depth, const xmlChar *string, xmlNodePtr *lst) {
12267
    return xmlParseBalancedChunkMemoryRecover( doc, sax, user_data,
12268
                                                depth, string, lst, 0 );
12269
}
12270
#endif /* LIBXML_SAX1_ENABLED */
12271
12272
/**
12273
 * xmlCtxtParseContent:
12274
 * @ctxt:  parser context
12275
 * @input:  parser input
12276
 * @node:  target node or document
12277
 * @hasTextDecl:  whether to parse text declaration
12278
 *
12279
 * Parse a well-balanced chunk of XML matching the 'content' production.
12280
 *
12281
 * Namespaces in scope of @node and entities of @node's document are
12282
 * recognized. When validating, the DTD of @node's document is used.
12283
 *
12284
 * Always consumes @input even in error case.
12285
 *
12286
 * Available since 2.14.0.
12287
 *
12288
 * Returns a node list or NULL in case of error.
12289
 */
12290
xmlNodePtr
12291
xmlCtxtParseContent(xmlParserCtxtPtr ctxt, xmlParserInputPtr input,
12292
0
                    xmlNodePtr node, int hasTextDecl) {
12293
0
    xmlDocPtr doc;
12294
0
    xmlNodePtr cur, list = NULL;
12295
0
    int nsnr = 0;
12296
0
    xmlDictPtr oldDict;
12297
0
    int oldOptions, oldDictNames, oldLoadSubset;
12298
12299
0
    if ((ctxt == NULL) || (input == NULL) || (node == NULL)) {
12300
0
        xmlFatalErr(ctxt, XML_ERR_ARGUMENT, NULL);
12301
0
        goto exit;
12302
0
    }
12303
12304
0
    doc = node->doc;
12305
0
    if (doc == NULL) {
12306
0
        xmlFatalErr(ctxt, XML_ERR_ARGUMENT, NULL);
12307
0
        goto exit;
12308
0
    }
12309
12310
0
    switch (node->type) {
12311
0
        case XML_ELEMENT_NODE:
12312
0
        case XML_DOCUMENT_NODE:
12313
0
        case XML_HTML_DOCUMENT_NODE:
12314
0
            break;
12315
12316
0
        case XML_ATTRIBUTE_NODE:
12317
0
        case XML_TEXT_NODE:
12318
0
        case XML_CDATA_SECTION_NODE:
12319
0
        case XML_ENTITY_REF_NODE:
12320
0
        case XML_PI_NODE:
12321
0
        case XML_COMMENT_NODE:
12322
0
            for (cur = node->parent; cur != NULL; cur = node->parent) {
12323
0
                if ((cur->type == XML_ELEMENT_NODE) ||
12324
0
                    (cur->type == XML_DOCUMENT_NODE) ||
12325
0
                    (cur->type == XML_HTML_DOCUMENT_NODE)) {
12326
0
                    node = cur;
12327
0
                    break;
12328
0
                }
12329
0
            }
12330
0
            break;
12331
12332
0
        default:
12333
0
            xmlFatalErr(ctxt, XML_ERR_ARGUMENT, NULL);
12334
0
            goto exit;
12335
0
    }
12336
12337
0
#ifdef LIBXML_HTML_ENABLED
12338
0
    if (ctxt->html)
12339
0
        htmlCtxtReset(ctxt);
12340
0
    else
12341
0
#endif
12342
0
        xmlCtxtReset(ctxt);
12343
12344
0
    oldDict = ctxt->dict;
12345
0
    oldOptions = ctxt->options;
12346
0
    oldDictNames = ctxt->dictNames;
12347
0
    oldLoadSubset = ctxt->loadsubset;
12348
12349
    /*
12350
     * Use input doc's dict if present, else assure XML_PARSE_NODICT is set.
12351
     */
12352
0
    if (doc->dict != NULL) {
12353
0
        ctxt->dict = doc->dict;
12354
0
    } else {
12355
0
        ctxt->options |= XML_PARSE_NODICT;
12356
0
        ctxt->dictNames = 0;
12357
0
    }
12358
12359
    /*
12360
     * Disable IDs
12361
     */
12362
0
    ctxt->loadsubset |= XML_SKIP_IDS;
12363
12364
0
    ctxt->myDoc = doc;
12365
12366
0
#ifdef LIBXML_HTML_ENABLED
12367
0
    if (ctxt->html) {
12368
        /*
12369
         * When parsing in context, it makes no sense to add implied
12370
         * elements like html/body/etc...
12371
         */
12372
0
        ctxt->options |= HTML_PARSE_NOIMPLIED;
12373
12374
0
        list = htmlCtxtParseContentInternal(ctxt, input);
12375
0
    } else
12376
0
#endif
12377
0
    {
12378
0
        xmlCtxtInitializeLate(ctxt);
12379
12380
        /*
12381
         * initialize the SAX2 namespaces stack
12382
         */
12383
0
        cur = node;
12384
0
        while ((cur != NULL) && (cur->type == XML_ELEMENT_NODE)) {
12385
0
            xmlNsPtr ns = cur->nsDef;
12386
0
            xmlHashedString hprefix, huri;
12387
12388
0
            while (ns != NULL) {
12389
0
                hprefix = xmlDictLookupHashed(ctxt->dict, ns->prefix, -1);
12390
0
                huri = xmlDictLookupHashed(ctxt->dict, ns->href, -1);
12391
0
                if (xmlParserNsPush(ctxt, &hprefix, &huri, ns, 1) > 0)
12392
0
                    nsnr++;
12393
0
                ns = ns->next;
12394
0
            }
12395
0
            cur = cur->parent;
12396
0
        }
12397
12398
0
        list = xmlCtxtParseContentInternal(ctxt, input, hasTextDecl, 1);
12399
12400
0
        if (nsnr > 0)
12401
0
            xmlParserNsPop(ctxt, nsnr);
12402
0
    }
12403
12404
0
    ctxt->dict = oldDict;
12405
0
    ctxt->options = oldOptions;
12406
0
    ctxt->dictNames = oldDictNames;
12407
0
    ctxt->loadsubset = oldLoadSubset;
12408
0
    ctxt->myDoc = NULL;
12409
0
    ctxt->node = NULL;
12410
12411
0
exit:
12412
0
    xmlFreeInputStream(input);
12413
0
    return(list);
12414
0
}
12415
12416
/**
12417
 * xmlParseInNodeContext:
12418
 * @node:  the context node
12419
 * @data:  the input string
12420
 * @datalen:  the input string length in bytes
12421
 * @options:  a combination of xmlParserOption
12422
 * @listOut:  the return value for the set of parsed nodes
12423
 *
12424
 * Parse a well-balanced chunk of an XML document
12425
 * within the context (DTD, namespaces, etc ...) of the given node.
12426
 *
12427
 * The allowed sequence for the data is a Well Balanced Chunk defined by
12428
 * the content production in the XML grammar:
12429
 *
12430
 * [43] content ::= (element | CharData | Reference | CDSect | PI | Comment)*
12431
 *
12432
 * This function assumes the encoding of @node's document which is
12433
 * typically not what you want. A better alternative is
12434
 * xmlCtxtParseContent.
12435
 *
12436
 * Returns XML_ERR_OK if the chunk is well balanced, and the parser
12437
 * error code otherwise
12438
 */
12439
xmlParserErrors
12440
xmlParseInNodeContext(xmlNodePtr node, const char *data, int datalen,
12441
0
                      int options, xmlNodePtr *listOut) {
12442
0
    xmlParserCtxtPtr ctxt;
12443
0
    xmlParserInputPtr input;
12444
0
    xmlDocPtr doc;
12445
0
    xmlNodePtr list;
12446
0
    xmlParserErrors ret;
12447
12448
0
    if (listOut == NULL)
12449
0
        return(XML_ERR_INTERNAL_ERROR);
12450
0
    *listOut = NULL;
12451
12452
0
    if ((node == NULL) || (data == NULL) || (datalen < 0))
12453
0
        return(XML_ERR_INTERNAL_ERROR);
12454
12455
0
    doc = node->doc;
12456
0
    if (doc == NULL)
12457
0
        return(XML_ERR_INTERNAL_ERROR);
12458
12459
0
#ifdef LIBXML_HTML_ENABLED
12460
0
    if (doc->type == XML_HTML_DOCUMENT_NODE) {
12461
0
        ctxt = htmlNewParserCtxt();
12462
0
    }
12463
0
    else
12464
0
#endif
12465
0
        ctxt = xmlNewParserCtxt();
12466
12467
0
    if (ctxt == NULL)
12468
0
        return(XML_ERR_NO_MEMORY);
12469
12470
0
    input = xmlCtxtNewInputFromMemory(ctxt, NULL, data, datalen,
12471
0
                                      (const char *) doc->encoding,
12472
0
                                      XML_INPUT_BUF_STATIC);
12473
0
    if (input == NULL) {
12474
0
        xmlFreeParserCtxt(ctxt);
12475
0
        return(XML_ERR_NO_MEMORY);
12476
0
    }
12477
12478
0
    xmlCtxtUseOptions(ctxt, options);
12479
12480
0
    list = xmlCtxtParseContent(ctxt, input, node, /* hasTextDecl */ 0);
12481
12482
0
    if (list == NULL) {
12483
0
        ret = ctxt->errNo;
12484
0
        if (ret == XML_ERR_ARGUMENT)
12485
0
            ret = XML_ERR_INTERNAL_ERROR;
12486
0
    } else {
12487
0
        ret = XML_ERR_OK;
12488
0
        *listOut = list;
12489
0
    }
12490
12491
0
    xmlFreeParserCtxt(ctxt);
12492
12493
0
    return(ret);
12494
0
}
12495
12496
#ifdef LIBXML_SAX1_ENABLED
12497
/**
12498
 * xmlParseBalancedChunkMemoryRecover:
12499
 * @doc:  the document the chunk pertains to (must not be NULL)
12500
 * @sax:  the SAX handler block (possibly NULL)
12501
 * @user_data:  The user data returned on SAX callbacks (possibly NULL)
12502
 * @depth:  Used for loop detection, use 0
12503
 * @string:  the input string in UTF8 or ISO-Latin (zero terminated)
12504
 * @listOut:  the return value for the set of parsed nodes
12505
 * @recover: return nodes even if the data is broken (use 0)
12506
 *
12507
 * Parse a well-balanced chunk of an XML document
12508
 *
12509
 * The allowed sequence for the Well Balanced Chunk is the one defined by
12510
 * the content production in the XML grammar:
12511
 *
12512
 * [43] content ::= (element | CharData | Reference | CDSect | PI | Comment)*
12513
 *
12514
 * Returns 0 if the chunk is well balanced, or thehe parser error code
12515
 * otherwise.
12516
 *
12517
 * In case recover is set to 1, the nodelist will not be empty even if
12518
 * the parsed chunk is not well balanced, assuming the parsing succeeded to
12519
 * some extent.
12520
 */
12521
int
12522
xmlParseBalancedChunkMemoryRecover(xmlDocPtr doc, xmlSAXHandlerPtr sax,
12523
     void *user_data, int depth, const xmlChar *string, xmlNodePtr *listOut,
12524
     int recover) {
12525
    xmlParserCtxtPtr ctxt;
12526
    xmlParserInputPtr input;
12527
    xmlNodePtr list;
12528
    int ret;
12529
12530
    if (listOut != NULL)
12531
        *listOut = NULL;
12532
12533
    if (string == NULL)
12534
        return(XML_ERR_ARGUMENT);
12535
12536
    ctxt = xmlNewSAXParserCtxt(sax, user_data);
12537
    if (ctxt == NULL)
12538
        return(XML_ERR_NO_MEMORY);
12539
12540
    xmlCtxtInitializeLate(ctxt);
12541
12542
    ctxt->depth = depth;
12543
    ctxt->myDoc = doc;
12544
    if (recover) {
12545
        ctxt->options |= XML_PARSE_RECOVER;
12546
        ctxt->recovery = 1;
12547
    }
12548
12549
    input = xmlNewStringInputStream(ctxt, string);
12550
    if (input == NULL) {
12551
        ret = ctxt->errNo;
12552
        goto error;
12553
    }
12554
12555
    list = xmlCtxtParseContentInternal(ctxt, input, /* hasTextDecl */ 0, 1);
12556
    if (listOut != NULL)
12557
        *listOut = list;
12558
    else
12559
        xmlFreeNodeList(list);
12560
12561
    if (!ctxt->wellFormed)
12562
        ret = ctxt->errNo;
12563
    else
12564
        ret = XML_ERR_OK;
12565
12566
error:
12567
    xmlFreeInputStream(input);
12568
    xmlFreeParserCtxt(ctxt);
12569
    return(ret);
12570
}
12571
12572
/**
12573
 * xmlSAXParseEntity:
12574
 * @sax:  the SAX handler block
12575
 * @filename:  the filename
12576
 *
12577
 * DEPRECATED: Don't use.
12578
 *
12579
 * parse an XML external entity out of context and build a tree.
12580
 * It use the given SAX function block to handle the parsing callback.
12581
 * If sax is NULL, fallback to the default DOM tree building routines.
12582
 *
12583
 * [78] extParsedEnt ::= TextDecl? content
12584
 *
12585
 * This correspond to a "Well Balanced" chunk
12586
 *
12587
 * Returns the resulting document tree
12588
 */
12589
12590
xmlDocPtr
12591
xmlSAXParseEntity(xmlSAXHandlerPtr sax, const char *filename) {
12592
    xmlDocPtr ret;
12593
    xmlParserCtxtPtr ctxt;
12594
12595
    ctxt = xmlCreateFileParserCtxt(filename);
12596
    if (ctxt == NULL) {
12597
  return(NULL);
12598
    }
12599
    if (sax != NULL) {
12600
        if (sax->initialized == XML_SAX2_MAGIC) {
12601
            *ctxt->sax = *sax;
12602
        } else {
12603
            memset(ctxt->sax, 0, sizeof(*ctxt->sax));
12604
            memcpy(ctxt->sax, sax, sizeof(xmlSAXHandlerV1));
12605
        }
12606
        ctxt->userData = NULL;
12607
    }
12608
12609
    xmlParseExtParsedEnt(ctxt);
12610
12611
    if (ctxt->wellFormed) {
12612
  ret = ctxt->myDoc;
12613
    } else {
12614
        ret = NULL;
12615
        xmlFreeDoc(ctxt->myDoc);
12616
    }
12617
12618
    xmlFreeParserCtxt(ctxt);
12619
12620
    return(ret);
12621
}
12622
12623
/**
12624
 * xmlParseEntity:
12625
 * @filename:  the filename
12626
 *
12627
 * parse an XML external entity out of context and build a tree.
12628
 *
12629
 * [78] extParsedEnt ::= TextDecl? content
12630
 *
12631
 * This correspond to a "Well Balanced" chunk
12632
 *
12633
 * Returns the resulting document tree
12634
 */
12635
12636
xmlDocPtr
12637
xmlParseEntity(const char *filename) {
12638
    return(xmlSAXParseEntity(NULL, filename));
12639
}
12640
#endif /* LIBXML_SAX1_ENABLED */
12641
12642
/**
12643
 * xmlCreateEntityParserCtxt:
12644
 * @URL:  the entity URL
12645
 * @ID:  the entity PUBLIC ID
12646
 * @base:  a possible base for the target URI
12647
 *
12648
 * DEPRECATED: Don't use.
12649
 *
12650
 * Create a parser context for an external entity
12651
 * Automatic support for ZLIB/Compress compressed document is provided
12652
 * by default if found at compile-time.
12653
 *
12654
 * Returns the new parser context or NULL
12655
 */
12656
xmlParserCtxtPtr
12657
xmlCreateEntityParserCtxt(const xmlChar *URL, const xmlChar *ID,
12658
0
                    const xmlChar *base) {
12659
0
    xmlParserCtxtPtr ctxt;
12660
0
    xmlParserInputPtr input;
12661
0
    xmlChar *uri = NULL;
12662
12663
0
    ctxt = xmlNewParserCtxt();
12664
0
    if (ctxt == NULL)
12665
0
  return(NULL);
12666
12667
0
    if (base != NULL) {
12668
0
        if (xmlBuildURISafe(URL, base, &uri) < 0)
12669
0
            goto error;
12670
0
        if (uri != NULL)
12671
0
            URL = uri;
12672
0
    }
12673
12674
0
    input = xmlLoadResource(ctxt, (char *) URL, (char *) ID,
12675
0
                            XML_RESOURCE_UNKNOWN);
12676
0
    if (input == NULL)
12677
0
        goto error;
12678
12679
0
    if (xmlCtxtPushInput(ctxt, input) < 0) {
12680
0
        xmlFreeInputStream(input);
12681
0
        goto error;
12682
0
    }
12683
12684
0
    xmlFree(uri);
12685
0
    return(ctxt);
12686
12687
0
error:
12688
0
    xmlFree(uri);
12689
0
    xmlFreeParserCtxt(ctxt);
12690
0
    return(NULL);
12691
0
}
12692
12693
/************************************************************************
12694
 *                  *
12695
 *    Front ends when parsing from a file     *
12696
 *                  *
12697
 ************************************************************************/
12698
12699
/**
12700
 * xmlCreateURLParserCtxt:
12701
 * @filename:  the filename or URL
12702
 * @options:  a combination of xmlParserOption
12703
 *
12704
 * DEPRECATED: Use xmlNewParserCtxt and xmlCtxtReadFile.
12705
 *
12706
 * Create a parser context for a file or URL content.
12707
 * Automatic support for ZLIB/Compress compressed document is provided
12708
 * by default if found at compile-time and for file accesses
12709
 *
12710
 * Returns the new parser context or NULL
12711
 */
12712
xmlParserCtxtPtr
12713
xmlCreateURLParserCtxt(const char *filename, int options)
12714
0
{
12715
0
    xmlParserCtxtPtr ctxt;
12716
0
    xmlParserInputPtr input;
12717
12718
0
    ctxt = xmlNewParserCtxt();
12719
0
    if (ctxt == NULL)
12720
0
  return(NULL);
12721
12722
0
    options |= XML_PARSE_UNZIP;
12723
12724
0
    xmlCtxtUseOptions(ctxt, options);
12725
0
    ctxt->linenumbers = 1;
12726
12727
0
    input = xmlLoadResource(ctxt, filename, NULL, XML_RESOURCE_MAIN_DOCUMENT);
12728
0
    if (input == NULL) {
12729
0
  xmlFreeParserCtxt(ctxt);
12730
0
  return(NULL);
12731
0
    }
12732
0
    if (xmlCtxtPushInput(ctxt, input) < 0) {
12733
0
        xmlFreeInputStream(input);
12734
0
        xmlFreeParserCtxt(ctxt);
12735
0
        return(NULL);
12736
0
    }
12737
12738
0
    return(ctxt);
12739
0
}
12740
12741
/**
12742
 * xmlCreateFileParserCtxt:
12743
 * @filename:  the filename
12744
 *
12745
 * DEPRECATED: Use xmlNewParserCtxt and xmlCtxtReadFile.
12746
 *
12747
 * Create a parser context for a file content.
12748
 * Automatic support for ZLIB/Compress compressed document is provided
12749
 * by default if found at compile-time.
12750
 *
12751
 * Returns the new parser context or NULL
12752
 */
12753
xmlParserCtxtPtr
12754
xmlCreateFileParserCtxt(const char *filename)
12755
0
{
12756
0
    return(xmlCreateURLParserCtxt(filename, 0));
12757
0
}
12758
12759
#ifdef LIBXML_SAX1_ENABLED
12760
/**
12761
 * xmlSAXParseFileWithData:
12762
 * @sax:  the SAX handler block
12763
 * @filename:  the filename
12764
 * @recovery:  work in recovery mode, i.e. tries to read no Well Formed
12765
 *             documents
12766
 * @data:  the userdata
12767
 *
12768
 * DEPRECATED: Use xmlNewSAXParserCtxt and xmlCtxtReadFile.
12769
 *
12770
 * parse an XML file and build a tree. Automatic support for ZLIB/Compress
12771
 * compressed document is provided by default if found at compile-time.
12772
 * It use the given SAX function block to handle the parsing callback.
12773
 * If sax is NULL, fallback to the default DOM tree building routines.
12774
 *
12775
 * User data (void *) is stored within the parser context in the
12776
 * context's _private member, so it is available nearly everywhere in libxml
12777
 *
12778
 * Returns the resulting document tree
12779
 */
12780
12781
xmlDocPtr
12782
xmlSAXParseFileWithData(xmlSAXHandlerPtr sax, const char *filename,
12783
                        int recovery, void *data) {
12784
    xmlDocPtr ret = NULL;
12785
    xmlParserCtxtPtr ctxt;
12786
    xmlParserInputPtr input;
12787
12788
    ctxt = xmlNewSAXParserCtxt(sax, NULL);
12789
    if (ctxt == NULL)
12790
  return(NULL);
12791
12792
    if (data != NULL)
12793
  ctxt->_private = data;
12794
12795
    if (recovery) {
12796
        ctxt->options |= XML_PARSE_RECOVER;
12797
        ctxt->recovery = 1;
12798
    }
12799
12800
    if ((filename != NULL) && (filename[0] == '-') && (filename[1] == 0))
12801
        input = xmlCtxtNewInputFromFd(ctxt, filename, STDIN_FILENO, NULL, 0);
12802
    else
12803
        input = xmlCtxtNewInputFromUrl(ctxt, filename, NULL, NULL, 0);
12804
12805
    if (input != NULL)
12806
        ret = xmlCtxtParseDocument(ctxt, input);
12807
12808
    xmlFreeParserCtxt(ctxt);
12809
    return(ret);
12810
}
12811
12812
/**
12813
 * xmlSAXParseFile:
12814
 * @sax:  the SAX handler block
12815
 * @filename:  the filename
12816
 * @recovery:  work in recovery mode, i.e. tries to read no Well Formed
12817
 *             documents
12818
 *
12819
 * DEPRECATED: Use xmlNewSAXParserCtxt and xmlCtxtReadFile.
12820
 *
12821
 * parse an XML file and build a tree. Automatic support for ZLIB/Compress
12822
 * compressed document is provided by default if found at compile-time.
12823
 * It use the given SAX function block to handle the parsing callback.
12824
 * If sax is NULL, fallback to the default DOM tree building routines.
12825
 *
12826
 * Returns the resulting document tree
12827
 */
12828
12829
xmlDocPtr
12830
xmlSAXParseFile(xmlSAXHandlerPtr sax, const char *filename,
12831
                          int recovery) {
12832
    return(xmlSAXParseFileWithData(sax,filename,recovery,NULL));
12833
}
12834
12835
/**
12836
 * xmlRecoverDoc:
12837
 * @cur:  a pointer to an array of xmlChar
12838
 *
12839
 * DEPRECATED: Use xmlReadDoc with XML_PARSE_RECOVER.
12840
 *
12841
 * parse an XML in-memory document and build a tree.
12842
 * In the case the document is not Well Formed, a attempt to build a
12843
 * tree is tried anyway
12844
 *
12845
 * Returns the resulting document tree or NULL in case of failure
12846
 */
12847
12848
xmlDocPtr
12849
xmlRecoverDoc(const xmlChar *cur) {
12850
    return(xmlSAXParseDoc(NULL, cur, 1));
12851
}
12852
12853
/**
12854
 * xmlParseFile:
12855
 * @filename:  the filename
12856
 *
12857
 * DEPRECATED: Use xmlReadFile.
12858
 *
12859
 * parse an XML file and build a tree. Automatic support for ZLIB/Compress
12860
 * compressed document is provided by default if found at compile-time.
12861
 *
12862
 * Returns the resulting document tree if the file was wellformed,
12863
 * NULL otherwise.
12864
 */
12865
12866
xmlDocPtr
12867
xmlParseFile(const char *filename) {
12868
    return(xmlSAXParseFile(NULL, filename, 0));
12869
}
12870
12871
/**
12872
 * xmlRecoverFile:
12873
 * @filename:  the filename
12874
 *
12875
 * DEPRECATED: Use xmlReadFile with XML_PARSE_RECOVER.
12876
 *
12877
 * parse an XML file and build a tree. Automatic support for ZLIB/Compress
12878
 * compressed document is provided by default if found at compile-time.
12879
 * In the case the document is not Well Formed, it attempts to build
12880
 * a tree anyway
12881
 *
12882
 * Returns the resulting document tree or NULL in case of failure
12883
 */
12884
12885
xmlDocPtr
12886
xmlRecoverFile(const char *filename) {
12887
    return(xmlSAXParseFile(NULL, filename, 1));
12888
}
12889
12890
12891
/**
12892
 * xmlSetupParserForBuffer:
12893
 * @ctxt:  an XML parser context
12894
 * @buffer:  a xmlChar * buffer
12895
 * @filename:  a file name
12896
 *
12897
 * DEPRECATED: Don't use.
12898
 *
12899
 * Setup the parser context to parse a new buffer; Clears any prior
12900
 * contents from the parser context. The buffer parameter must not be
12901
 * NULL, but the filename parameter can be
12902
 */
12903
void
12904
xmlSetupParserForBuffer(xmlParserCtxtPtr ctxt, const xmlChar* buffer,
12905
                             const char* filename)
12906
{
12907
    xmlParserInputPtr input;
12908
12909
    if ((ctxt == NULL) || (buffer == NULL))
12910
        return;
12911
12912
    xmlClearParserCtxt(ctxt);
12913
12914
    input = xmlCtxtNewInputFromString(ctxt, filename, (const char *) buffer,
12915
                                      NULL, 0);
12916
    if (input == NULL)
12917
        return;
12918
    if (xmlCtxtPushInput(ctxt, input) < 0)
12919
        xmlFreeInputStream(input);
12920
}
12921
12922
/**
12923
 * xmlSAXUserParseFile:
12924
 * @sax:  a SAX handler
12925
 * @user_data:  The user data returned on SAX callbacks
12926
 * @filename:  a file name
12927
 *
12928
 * DEPRECATED: Use xmlNewSAXParserCtxt and xmlCtxtReadFile.
12929
 *
12930
 * parse an XML file and call the given SAX handler routines.
12931
 * Automatic support for ZLIB/Compress compressed document is provided
12932
 *
12933
 * Returns 0 in case of success or a error number otherwise
12934
 */
12935
int
12936
xmlSAXUserParseFile(xmlSAXHandlerPtr sax, void *user_data,
12937
                    const char *filename) {
12938
    int ret = 0;
12939
    xmlParserCtxtPtr ctxt;
12940
12941
    ctxt = xmlCreateFileParserCtxt(filename);
12942
    if (ctxt == NULL) return -1;
12943
    if (sax != NULL) {
12944
        if (sax->initialized == XML_SAX2_MAGIC) {
12945
            *ctxt->sax = *sax;
12946
        } else {
12947
            memset(ctxt->sax, 0, sizeof(*ctxt->sax));
12948
            memcpy(ctxt->sax, sax, sizeof(xmlSAXHandlerV1));
12949
        }
12950
  ctxt->userData = user_data;
12951
    }
12952
12953
    xmlParseDocument(ctxt);
12954
12955
    if (ctxt->wellFormed)
12956
  ret = 0;
12957
    else {
12958
        if (ctxt->errNo != 0)
12959
      ret = ctxt->errNo;
12960
  else
12961
      ret = -1;
12962
    }
12963
    if (ctxt->myDoc != NULL) {
12964
        xmlFreeDoc(ctxt->myDoc);
12965
  ctxt->myDoc = NULL;
12966
    }
12967
    xmlFreeParserCtxt(ctxt);
12968
12969
    return ret;
12970
}
12971
#endif /* LIBXML_SAX1_ENABLED */
12972
12973
/************************************************************************
12974
 *                  *
12975
 *    Front ends when parsing from memory     *
12976
 *                  *
12977
 ************************************************************************/
12978
12979
/**
12980
 * xmlCreateMemoryParserCtxt:
12981
 * @buffer:  a pointer to a char array
12982
 * @size:  the size of the array
12983
 *
12984
 * Create a parser context for an XML in-memory document. The input buffer
12985
 * must not contain a terminating null byte.
12986
 *
12987
 * Returns the new parser context or NULL
12988
 */
12989
xmlParserCtxtPtr
12990
0
xmlCreateMemoryParserCtxt(const char *buffer, int size) {
12991
0
    xmlParserCtxtPtr ctxt;
12992
0
    xmlParserInputPtr input;
12993
12994
0
    if (size < 0)
12995
0
  return(NULL);
12996
12997
0
    ctxt = xmlNewParserCtxt();
12998
0
    if (ctxt == NULL)
12999
0
  return(NULL);
13000
13001
0
    input = xmlCtxtNewInputFromMemory(ctxt, NULL, buffer, size, NULL, 0);
13002
0
    if (input == NULL) {
13003
0
  xmlFreeParserCtxt(ctxt);
13004
0
  return(NULL);
13005
0
    }
13006
0
    if (xmlCtxtPushInput(ctxt, input) < 0) {
13007
0
        xmlFreeInputStream(input);
13008
0
        xmlFreeParserCtxt(ctxt);
13009
0
        return(NULL);
13010
0
    }
13011
13012
0
    return(ctxt);
13013
0
}
13014
13015
#ifdef LIBXML_SAX1_ENABLED
13016
/**
13017
 * xmlSAXParseMemoryWithData:
13018
 * @sax:  the SAX handler block
13019
 * @buffer:  an pointer to a char array
13020
 * @size:  the size of the array
13021
 * @recovery:  work in recovery mode, i.e. tries to read no Well Formed
13022
 *             documents
13023
 * @data:  the userdata
13024
 *
13025
 * DEPRECATED: Use xmlNewSAXParserCtxt and xmlCtxtReadMemory.
13026
 *
13027
 * parse an XML in-memory block and use the given SAX function block
13028
 * to handle the parsing callback. If sax is NULL, fallback to the default
13029
 * DOM tree building routines.
13030
 *
13031
 * User data (void *) is stored within the parser context in the
13032
 * context's _private member, so it is available nearly everywhere in libxml
13033
 *
13034
 * Returns the resulting document tree
13035
 */
13036
13037
xmlDocPtr
13038
xmlSAXParseMemoryWithData(xmlSAXHandlerPtr sax, const char *buffer,
13039
                          int size, int recovery, void *data) {
13040
    xmlDocPtr ret = NULL;
13041
    xmlParserCtxtPtr ctxt;
13042
    xmlParserInputPtr input;
13043
13044
    if (size < 0)
13045
        return(NULL);
13046
13047
    ctxt = xmlNewSAXParserCtxt(sax, NULL);
13048
    if (ctxt == NULL)
13049
        return(NULL);
13050
13051
    if (data != NULL)
13052
  ctxt->_private=data;
13053
13054
    if (recovery) {
13055
        ctxt->options |= XML_PARSE_RECOVER;
13056
        ctxt->recovery = 1;
13057
    }
13058
13059
    input = xmlCtxtNewInputFromMemory(ctxt, NULL, buffer, size, NULL,
13060
                                      XML_INPUT_BUF_STATIC);
13061
13062
    if (input != NULL)
13063
        ret = xmlCtxtParseDocument(ctxt, input);
13064
13065
    xmlFreeParserCtxt(ctxt);
13066
    return(ret);
13067
}
13068
13069
/**
13070
 * xmlSAXParseMemory:
13071
 * @sax:  the SAX handler block
13072
 * @buffer:  an pointer to a char array
13073
 * @size:  the size of the array
13074
 * @recovery:  work in recovery mode, i.e. tries to read not Well Formed
13075
 *             documents
13076
 *
13077
 * DEPRECATED: Use xmlNewSAXParserCtxt and xmlCtxtReadMemory.
13078
 *
13079
 * parse an XML in-memory block and use the given SAX function block
13080
 * to handle the parsing callback. If sax is NULL, fallback to the default
13081
 * DOM tree building routines.
13082
 *
13083
 * Returns the resulting document tree
13084
 */
13085
xmlDocPtr
13086
xmlSAXParseMemory(xmlSAXHandlerPtr sax, const char *buffer,
13087
            int size, int recovery) {
13088
    return xmlSAXParseMemoryWithData(sax, buffer, size, recovery, NULL);
13089
}
13090
13091
/**
13092
 * xmlParseMemory:
13093
 * @buffer:  an pointer to a char array
13094
 * @size:  the size of the array
13095
 *
13096
 * DEPRECATED: Use xmlReadMemory.
13097
 *
13098
 * parse an XML in-memory block and build a tree.
13099
 *
13100
 * Returns the resulting document tree
13101
 */
13102
13103
xmlDocPtr xmlParseMemory(const char *buffer, int size) {
13104
   return(xmlSAXParseMemory(NULL, buffer, size, 0));
13105
}
13106
13107
/**
13108
 * xmlRecoverMemory:
13109
 * @buffer:  an pointer to a char array
13110
 * @size:  the size of the array
13111
 *
13112
 * DEPRECATED: Use xmlReadMemory with XML_PARSE_RECOVER.
13113
 *
13114
 * parse an XML in-memory block and build a tree.
13115
 * In the case the document is not Well Formed, an attempt to
13116
 * build a tree is tried anyway
13117
 *
13118
 * Returns the resulting document tree or NULL in case of error
13119
 */
13120
13121
xmlDocPtr xmlRecoverMemory(const char *buffer, int size) {
13122
   return(xmlSAXParseMemory(NULL, buffer, size, 1));
13123
}
13124
13125
/**
13126
 * xmlSAXUserParseMemory:
13127
 * @sax:  a SAX handler
13128
 * @user_data:  The user data returned on SAX callbacks
13129
 * @buffer:  an in-memory XML document input
13130
 * @size:  the length of the XML document in bytes
13131
 *
13132
 * DEPRECATED: Use xmlNewSAXParserCtxt and xmlCtxtReadMemory.
13133
 *
13134
 * parse an XML in-memory buffer and call the given SAX handler routines.
13135
 *
13136
 * Returns 0 in case of success or a error number otherwise
13137
 */
13138
int xmlSAXUserParseMemory(xmlSAXHandlerPtr sax, void *user_data,
13139
        const char *buffer, int size) {
13140
    int ret = 0;
13141
    xmlParserCtxtPtr ctxt;
13142
13143
    ctxt = xmlCreateMemoryParserCtxt(buffer, size);
13144
    if (ctxt == NULL) return -1;
13145
    if (sax != NULL) {
13146
        if (sax->initialized == XML_SAX2_MAGIC) {
13147
            *ctxt->sax = *sax;
13148
        } else {
13149
            memset(ctxt->sax, 0, sizeof(*ctxt->sax));
13150
            memcpy(ctxt->sax, sax, sizeof(xmlSAXHandlerV1));
13151
        }
13152
  ctxt->userData = user_data;
13153
    }
13154
13155
    xmlParseDocument(ctxt);
13156
13157
    if (ctxt->wellFormed)
13158
  ret = 0;
13159
    else {
13160
        if (ctxt->errNo != 0)
13161
      ret = ctxt->errNo;
13162
  else
13163
      ret = -1;
13164
    }
13165
    if (ctxt->myDoc != NULL) {
13166
        xmlFreeDoc(ctxt->myDoc);
13167
  ctxt->myDoc = NULL;
13168
    }
13169
    xmlFreeParserCtxt(ctxt);
13170
13171
    return ret;
13172
}
13173
#endif /* LIBXML_SAX1_ENABLED */
13174
13175
/**
13176
 * xmlCreateDocParserCtxt:
13177
 * @str:  a pointer to an array of xmlChar
13178
 *
13179
 * Creates a parser context for an XML in-memory document.
13180
 *
13181
 * Returns the new parser context or NULL
13182
 */
13183
xmlParserCtxtPtr
13184
0
xmlCreateDocParserCtxt(const xmlChar *str) {
13185
0
    xmlParserCtxtPtr ctxt;
13186
0
    xmlParserInputPtr input;
13187
13188
0
    ctxt = xmlNewParserCtxt();
13189
0
    if (ctxt == NULL)
13190
0
  return(NULL);
13191
13192
0
    input = xmlCtxtNewInputFromString(ctxt, NULL, (const char *) str, NULL, 0);
13193
0
    if (input == NULL) {
13194
0
  xmlFreeParserCtxt(ctxt);
13195
0
  return(NULL);
13196
0
    }
13197
0
    if (xmlCtxtPushInput(ctxt, input) < 0) {
13198
0
        xmlFreeInputStream(input);
13199
0
        xmlFreeParserCtxt(ctxt);
13200
0
        return(NULL);
13201
0
    }
13202
13203
0
    return(ctxt);
13204
0
}
13205
13206
#ifdef LIBXML_SAX1_ENABLED
13207
/**
13208
 * xmlSAXParseDoc:
13209
 * @sax:  the SAX handler block
13210
 * @cur:  a pointer to an array of xmlChar
13211
 * @recovery:  work in recovery mode, i.e. tries to read no Well Formed
13212
 *             documents
13213
 *
13214
 * DEPRECATED: Use xmlNewSAXParserCtxt and xmlCtxtReadDoc.
13215
 *
13216
 * parse an XML in-memory document and build a tree.
13217
 * It use the given SAX function block to handle the parsing callback.
13218
 * If sax is NULL, fallback to the default DOM tree building routines.
13219
 *
13220
 * Returns the resulting document tree
13221
 */
13222
13223
xmlDocPtr
13224
xmlSAXParseDoc(xmlSAXHandlerPtr sax, const xmlChar *cur, int recovery) {
13225
    xmlDocPtr ret;
13226
    xmlParserCtxtPtr ctxt;
13227
    xmlSAXHandlerPtr oldsax = NULL;
13228
13229
    if (cur == NULL) return(NULL);
13230
13231
13232
    ctxt = xmlCreateDocParserCtxt(cur);
13233
    if (ctxt == NULL) return(NULL);
13234
    if (sax != NULL) {
13235
        oldsax = ctxt->sax;
13236
        ctxt->sax = sax;
13237
        ctxt->userData = NULL;
13238
    }
13239
13240
    xmlParseDocument(ctxt);
13241
    if ((ctxt->wellFormed) || recovery) ret = ctxt->myDoc;
13242
    else {
13243
       ret = NULL;
13244
       xmlFreeDoc(ctxt->myDoc);
13245
       ctxt->myDoc = NULL;
13246
    }
13247
    if (sax != NULL)
13248
  ctxt->sax = oldsax;
13249
    xmlFreeParserCtxt(ctxt);
13250
13251
    return(ret);
13252
}
13253
13254
/**
13255
 * xmlParseDoc:
13256
 * @cur:  a pointer to an array of xmlChar
13257
 *
13258
 * DEPRECATED: Use xmlReadDoc.
13259
 *
13260
 * parse an XML in-memory document and build a tree.
13261
 *
13262
 * Returns the resulting document tree
13263
 */
13264
13265
xmlDocPtr
13266
xmlParseDoc(const xmlChar *cur) {
13267
    return(xmlSAXParseDoc(NULL, cur, 0));
13268
}
13269
#endif /* LIBXML_SAX1_ENABLED */
13270
13271
/************************************************************************
13272
 *                  *
13273
 *  New set (2.6.0) of simpler and more flexible APIs   *
13274
 *                  *
13275
 ************************************************************************/
13276
13277
/**
13278
 * DICT_FREE:
13279
 * @str:  a string
13280
 *
13281
 * Free a string if it is not owned by the "dict" dictionary in the
13282
 * current scope
13283
 */
13284
#define DICT_FREE(str)            \
13285
0
  if ((str) && ((!dict) ||       \
13286
0
      (xmlDictOwns(dict, (const xmlChar *)(str)) == 0)))  \
13287
0
      xmlFree((char *)(str));
13288
13289
/**
13290
 * xmlCtxtReset:
13291
 * @ctxt: an XML parser context
13292
 *
13293
 * Reset a parser context
13294
 */
13295
void
13296
xmlCtxtReset(xmlParserCtxtPtr ctxt)
13297
0
{
13298
0
    xmlParserInputPtr input;
13299
0
    xmlDictPtr dict;
13300
13301
0
    if (ctxt == NULL)
13302
0
        return;
13303
13304
0
    dict = ctxt->dict;
13305
13306
0
    while ((input = xmlCtxtPopInput(ctxt)) != NULL) { /* Non consuming */
13307
0
        xmlFreeInputStream(input);
13308
0
    }
13309
0
    ctxt->inputNr = 0;
13310
0
    ctxt->input = NULL;
13311
13312
0
    ctxt->spaceNr = 0;
13313
0
    if (ctxt->spaceTab != NULL) {
13314
0
  ctxt->spaceTab[0] = -1;
13315
0
  ctxt->space = &ctxt->spaceTab[0];
13316
0
    } else {
13317
0
        ctxt->space = NULL;
13318
0
    }
13319
13320
13321
0
    ctxt->nodeNr = 0;
13322
0
    ctxt->node = NULL;
13323
13324
0
    ctxt->nameNr = 0;
13325
0
    ctxt->name = NULL;
13326
13327
0
    ctxt->nsNr = 0;
13328
0
    xmlParserNsReset(ctxt->nsdb);
13329
13330
0
    DICT_FREE(ctxt->version);
13331
0
    ctxt->version = NULL;
13332
0
    DICT_FREE(ctxt->encoding);
13333
0
    ctxt->encoding = NULL;
13334
0
    DICT_FREE(ctxt->extSubURI);
13335
0
    ctxt->extSubURI = NULL;
13336
0
    DICT_FREE(ctxt->extSubSystem);
13337
0
    ctxt->extSubSystem = NULL;
13338
13339
0
    if (ctxt->directory != NULL) {
13340
0
        xmlFree(ctxt->directory);
13341
0
        ctxt->directory = NULL;
13342
0
    }
13343
13344
0
    if (ctxt->myDoc != NULL)
13345
0
        xmlFreeDoc(ctxt->myDoc);
13346
0
    ctxt->myDoc = NULL;
13347
13348
0
    ctxt->standalone = -1;
13349
0
    ctxt->hasExternalSubset = 0;
13350
0
    ctxt->hasPErefs = 0;
13351
0
    ctxt->html = 0;
13352
0
    ctxt->instate = XML_PARSER_START;
13353
13354
0
    ctxt->wellFormed = 1;
13355
0
    ctxt->nsWellFormed = 1;
13356
0
    ctxt->disableSAX = 0;
13357
0
    ctxt->valid = 1;
13358
0
    ctxt->record_info = 0;
13359
0
    ctxt->checkIndex = 0;
13360
0
    ctxt->endCheckState = 0;
13361
0
    ctxt->inSubset = 0;
13362
0
    ctxt->errNo = XML_ERR_OK;
13363
0
    ctxt->depth = 0;
13364
0
    ctxt->catalogs = NULL;
13365
0
    ctxt->sizeentities = 0;
13366
0
    ctxt->sizeentcopy = 0;
13367
0
    xmlInitNodeInfoSeq(&ctxt->node_seq);
13368
13369
0
    if (ctxt->attsDefault != NULL) {
13370
0
        xmlHashFree(ctxt->attsDefault, xmlHashDefaultDeallocator);
13371
0
        ctxt->attsDefault = NULL;
13372
0
    }
13373
0
    if (ctxt->attsSpecial != NULL) {
13374
0
        xmlHashFree(ctxt->attsSpecial, NULL);
13375
0
        ctxt->attsSpecial = NULL;
13376
0
    }
13377
13378
0
#ifdef LIBXML_CATALOG_ENABLED
13379
0
    if (ctxt->catalogs != NULL)
13380
0
  xmlCatalogFreeLocal(ctxt->catalogs);
13381
0
#endif
13382
0
    ctxt->nbErrors = 0;
13383
0
    ctxt->nbWarnings = 0;
13384
0
    if (ctxt->lastError.code != XML_ERR_OK)
13385
0
        xmlResetError(&ctxt->lastError);
13386
0
}
13387
13388
/**
13389
 * xmlCtxtResetPush:
13390
 * @ctxt: an XML parser context
13391
 * @chunk:  a pointer to an array of chars
13392
 * @size:  number of chars in the array
13393
 * @filename:  an optional file name or URI
13394
 * @encoding:  the document encoding, or NULL
13395
 *
13396
 * Reset a push parser context
13397
 *
13398
 * Returns 0 in case of success and 1 in case of error
13399
 */
13400
int
13401
xmlCtxtResetPush(xmlParserCtxtPtr ctxt, const char *chunk,
13402
                 int size, const char *filename, const char *encoding)
13403
0
{
13404
0
    xmlParserInputPtr input;
13405
13406
0
    if (ctxt == NULL)
13407
0
        return(1);
13408
13409
0
    xmlCtxtReset(ctxt);
13410
13411
0
    input = xmlNewPushInput(filename, chunk, size);
13412
0
    if (input == NULL)
13413
0
        return(1);
13414
13415
0
    if (xmlCtxtPushInput(ctxt, input) < 0) {
13416
0
        xmlFreeInputStream(input);
13417
0
        return(1);
13418
0
    }
13419
13420
0
    if (encoding != NULL)
13421
0
        xmlSwitchEncodingName(ctxt, encoding);
13422
13423
0
    return(0);
13424
0
}
13425
13426
static int
13427
xmlCtxtSetOptionsInternal(xmlParserCtxtPtr ctxt, int options, int keepMask)
13428
875k
{
13429
875k
    int allMask;
13430
13431
875k
    if (ctxt == NULL)
13432
0
        return(-1);
13433
13434
    /*
13435
     * XInclude options aren't handled by the parser.
13436
     *
13437
     * XML_PARSE_XINCLUDE
13438
     * XML_PARSE_NOXINCNODE
13439
     * XML_PARSE_NOBASEFIX
13440
     */
13441
875k
    allMask = XML_PARSE_RECOVER |
13442
875k
              XML_PARSE_NOENT |
13443
875k
              XML_PARSE_DTDLOAD |
13444
875k
              XML_PARSE_DTDATTR |
13445
875k
              XML_PARSE_DTDVALID |
13446
875k
              XML_PARSE_NOERROR |
13447
875k
              XML_PARSE_NOWARNING |
13448
875k
              XML_PARSE_PEDANTIC |
13449
875k
              XML_PARSE_NOBLANKS |
13450
#ifdef LIBXML_SAX1_ENABLED
13451
              XML_PARSE_SAX1 |
13452
#endif
13453
875k
              XML_PARSE_NONET |
13454
875k
              XML_PARSE_NODICT |
13455
875k
              XML_PARSE_NSCLEAN |
13456
875k
              XML_PARSE_NOCDATA |
13457
875k
              XML_PARSE_COMPACT |
13458
875k
              XML_PARSE_OLD10 |
13459
875k
              XML_PARSE_HUGE |
13460
875k
              XML_PARSE_OLDSAX |
13461
875k
              XML_PARSE_IGNORE_ENC |
13462
875k
              XML_PARSE_BIG_LINES |
13463
875k
              XML_PARSE_NO_XXE |
13464
875k
              XML_PARSE_UNZIP |
13465
875k
              XML_PARSE_NO_SYS_CATALOG |
13466
875k
              XML_PARSE_CATALOG_PI;
13467
13468
875k
    ctxt->options = (ctxt->options & keepMask) | (options & allMask);
13469
13470
    /*
13471
     * For some options, struct members are historically the source
13472
     * of truth. The values are initalized from global variables and
13473
     * old code could also modify them directly. Several older API
13474
     * functions that don't take an options argument rely on these
13475
     * deprecated mechanisms.
13476
     *
13477
     * Once public access to struct members and the globals are
13478
     * disabled, we can use the options bitmask as source of
13479
     * truth, making all these struct members obsolete.
13480
     *
13481
     * The XML_DETECT_IDS flags is misnamed. It simply enables
13482
     * loading of the external subset.
13483
     */
13484
875k
    ctxt->recovery = (options & XML_PARSE_RECOVER) ? 1 : 0;
13485
875k
    ctxt->replaceEntities = (options & XML_PARSE_NOENT) ? 1 : 0;
13486
875k
    ctxt->loadsubset = (options & XML_PARSE_DTDLOAD) ? XML_DETECT_IDS : 0;
13487
875k
    ctxt->loadsubset |= (options & XML_PARSE_DTDATTR) ? XML_COMPLETE_ATTRS : 0;
13488
875k
    ctxt->validate = (options & XML_PARSE_DTDVALID) ? 1 : 0;
13489
875k
    ctxt->pedantic = (options & XML_PARSE_PEDANTIC) ? 1 : 0;
13490
875k
    ctxt->keepBlanks = (options & XML_PARSE_NOBLANKS) ? 0 : 1;
13491
875k
    ctxt->dictNames = (options & XML_PARSE_NODICT) ? 0 : 1;
13492
13493
875k
    if (options & XML_PARSE_HUGE) {
13494
0
        if (ctxt->dict != NULL)
13495
0
            xmlDictSetLimit(ctxt->dict, 0);
13496
0
    }
13497
13498
875k
    ctxt->linenumbers = 1;
13499
13500
875k
    return(options & ~allMask);
13501
875k
}
13502
13503
/**
13504
 * xmlCtxtSetOptions:
13505
 * @ctxt: an XML parser context
13506
 * @options:  a bitmask of xmlParserOption values
13507
 *
13508
 * Applies the options to the parser context. Unset options are
13509
 * cleared.
13510
 *
13511
 * Available since 2.13.0. With older versions, you can use
13512
 * xmlCtxtUseOptions.
13513
 *
13514
 * XML_PARSE_RECOVER
13515
 *
13516
 * Enable "recovery" mode which allows non-wellformed documents.
13517
 * How this mode behaves exactly is unspecified and may change
13518
 * without further notice. Use of this feature is DISCOURAGED.
13519
 *
13520
 * Not supported by the push parser.
13521
 *
13522
 * XML_PARSE_NOENT
13523
 *
13524
 * Despite the confusing name, this option enables substitution
13525
 * of entities. The resulting tree won't contain any entity
13526
 * reference nodes.
13527
 *
13528
 * This option also enables loading of external entities (both
13529
 * general and parameter entities) which is dangerous. If you
13530
 * process untrusted data, it's recommended to set the
13531
 * XML_PARSE_NO_XXE option to disable loading of external
13532
 * entities.
13533
 *
13534
 * XML_PARSE_DTDLOAD
13535
 *
13536
 * Enables loading of an external DTD and the loading and
13537
 * substitution of external parameter entities. Has no effect
13538
 * if XML_PARSE_NO_XXE is set.
13539
 *
13540
 * XML_PARSE_DTDATTR
13541
 *
13542
 * Adds default attributes from the DTD to the result document.
13543
 *
13544
 * Implies XML_PARSE_DTDLOAD, but loading of external content
13545
 * can be disabled with XML_PARSE_NO_XXE.
13546
 *
13547
 * XML_PARSE_DTDVALID
13548
 *
13549
 * This option enables DTD validation which requires to load
13550
 * external DTDs and external entities (both general and
13551
 * parameter entities) unless XML_PARSE_NO_XXE was set.
13552
 *
13553
 * XML_PARSE_NO_XXE
13554
 *
13555
 * Disables loading of external DTDs or entities.
13556
 *
13557
 * Available since 2.13.0.
13558
 *
13559
 * XML_PARSE_NOERROR
13560
 *
13561
 * Disable error and warning reports to the error handlers.
13562
 * Errors are still accessible with xmlCtxtGetLastError.
13563
 *
13564
 * XML_PARSE_NOWARNING
13565
 *
13566
 * Disable warning reports.
13567
 *
13568
 * XML_PARSE_PEDANTIC
13569
 *
13570
 * Enable some pedantic warnings.
13571
 *
13572
 * XML_PARSE_NOBLANKS
13573
 *
13574
 * Remove some whitespace from the result document. Where to
13575
 * remove whitespace depends on DTD element declarations or a
13576
 * broken heuristic with unfixable bugs. Use of this option is
13577
 * DISCOURAGED.
13578
 *
13579
 * Not supported by the push parser.
13580
 *
13581
 * XML_PARSE_SAX1
13582
 *
13583
 * Always invoke the deprecated SAX1 startElement and endElement
13584
 * handlers. This option is DEPRECATED.
13585
 *
13586
 * XML_PARSE_NONET
13587
 *
13588
 * Disable network access with the builtin HTTP client.
13589
 *
13590
 * XML_PARSE_NODICT
13591
 *
13592
 * Create a document without interned strings, making all
13593
 * strings separate memory allocations.
13594
 *
13595
 * XML_PARSE_NSCLEAN
13596
 *
13597
 * Remove redundant namespace declarations from the result
13598
 * document.
13599
 *
13600
 * XML_PARSE_NOCDATA
13601
 *
13602
 * Output normal text nodes instead of CDATA nodes.
13603
 *
13604
 * XML_PARSE_COMPACT
13605
 *
13606
 * Store small strings directly in the node struct to save
13607
 * memory.
13608
 *
13609
 * XML_PARSE_OLD10
13610
 *
13611
 * Use old Name productions from before XML 1.0 Fifth Edition.
13612
 * This options is DEPRECATED.
13613
 *
13614
 * XML_PARSE_HUGE
13615
 *
13616
 * Relax some internal limits.
13617
 *
13618
 * Maximum size of text nodes, tags, comments, processing instructions,
13619
 * CDATA sections, entity values
13620
 *
13621
 * normal: 10M
13622
 * huge:    1B
13623
 *
13624
 * Maximum size of names, system literals, pubid literals
13625
 *
13626
 * normal: 50K
13627
 * huge:   10M
13628
 *
13629
 * Maximum nesting depth of elements
13630
 *
13631
 * normal:  256
13632
 * huge:   2048
13633
 *
13634
 * Maximum nesting depth of entities
13635
 *
13636
 * normal: 20
13637
 * huge:   40
13638
 *
13639
 * XML_PARSE_OLDSAX
13640
 *
13641
 * Enable an unspecified legacy mode for SAX parsers. This
13642
 * option is DEPRECATED.
13643
 *
13644
 * XML_PARSE_IGNORE_ENC
13645
 *
13646
 * Ignore the encoding in the XML declaration. This option is
13647
 * mostly unneeded these days. The only effect is to enforce
13648
 * UTF-8 decoding of ASCII-like data.
13649
 *
13650
 * XML_PARSE_BIG_LINES
13651
 *
13652
 * Enable reporting of line numbers larger than 65535.
13653
 *
13654
 * XML_PARSE_UNZIP
13655
 *
13656
 * Enable input decompression. Setting this option is discouraged
13657
 * to avoid zip bombs.
13658
 *
13659
 * Available since 2.14.0.
13660
 *
13661
 * XML_PARSE_NO_SYS_CATALOG
13662
 *
13663
 * Disables the global system XML catalog.
13664
 *
13665
 * Available since 2.14.0.
13666
 *
13667
 * XML_PARSE_CATALOG_PI
13668
 *
13669
 * Enable XML catalog processing instructions.
13670
 *
13671
 * Available since 2.14.0.
13672
 *
13673
 * Returns 0 in case of success, the set of unknown or unimplemented options
13674
 *         in case of error.
13675
 */
13676
int
13677
xmlCtxtSetOptions(xmlParserCtxtPtr ctxt, int options)
13678
0
{
13679
0
#ifdef LIBXML_HTML_ENABLED
13680
0
    if ((ctxt != NULL) && (ctxt->html))
13681
0
        return(htmlCtxtSetOptions(ctxt, options));
13682
0
#endif
13683
13684
0
    return(xmlCtxtSetOptionsInternal(ctxt, options, 0));
13685
0
}
13686
13687
/**
13688
 * xmlCtxtGetOptions:
13689
 * @ctxt: an XML parser context
13690
 *
13691
 * Get the current options of the parser context.
13692
 *
13693
 * Available since 2.14.0.
13694
 *
13695
 * Returns the current options set in the parser context, or -1 if ctxt is NULL.
13696
 */
13697
int
13698
xmlCtxtGetOptions(xmlParserCtxtPtr ctxt)
13699
0
{
13700
0
    if (ctxt == NULL)
13701
0
        return(-1);
13702
13703
0
    return(ctxt->options);
13704
0
}
13705
13706
/**
13707
 * xmlCtxtUseOptions:
13708
 * @ctxt: an XML parser context
13709
 * @options:  a combination of xmlParserOption
13710
 *
13711
 * DEPRECATED: Use xmlCtxtSetOptions.
13712
 *
13713
 * Applies the options to the parser context. The following options
13714
 * are never cleared and can only be enabled:
13715
 *
13716
 * XML_PARSE_NOERROR
13717
 * XML_PARSE_NOWARNING
13718
 * XML_PARSE_NONET
13719
 * XML_PARSE_NSCLEAN
13720
 * XML_PARSE_NOCDATA
13721
 * XML_PARSE_COMPACT
13722
 * XML_PARSE_OLD10
13723
 * XML_PARSE_HUGE
13724
 * XML_PARSE_OLDSAX
13725
 * XML_PARSE_IGNORE_ENC
13726
 * XML_PARSE_BIG_LINES
13727
 *
13728
 * Returns 0 in case of success, the set of unknown or unimplemented options
13729
 *         in case of error.
13730
 */
13731
int
13732
xmlCtxtUseOptions(xmlParserCtxtPtr ctxt, int options)
13733
875k
{
13734
875k
    int keepMask;
13735
13736
875k
#ifdef LIBXML_HTML_ENABLED
13737
875k
    if ((ctxt != NULL) && (ctxt->html))
13738
0
        return(htmlCtxtUseOptions(ctxt, options));
13739
875k
#endif
13740
13741
    /*
13742
     * For historic reasons, some options can only be enabled.
13743
     */
13744
875k
    keepMask = XML_PARSE_NOERROR |
13745
875k
               XML_PARSE_NOWARNING |
13746
875k
               XML_PARSE_NONET |
13747
875k
               XML_PARSE_NSCLEAN |
13748
875k
               XML_PARSE_NOCDATA |
13749
875k
               XML_PARSE_COMPACT |
13750
875k
               XML_PARSE_OLD10 |
13751
875k
               XML_PARSE_HUGE |
13752
875k
               XML_PARSE_OLDSAX |
13753
875k
               XML_PARSE_IGNORE_ENC |
13754
875k
               XML_PARSE_BIG_LINES;
13755
13756
875k
    return(xmlCtxtSetOptionsInternal(ctxt, options, keepMask));
13757
875k
}
13758
13759
/**
13760
 * xmlCtxtSetMaxAmplification:
13761
 * @ctxt: an XML parser context
13762
 * @maxAmpl:  maximum amplification factor
13763
 *
13764
 * To protect against exponential entity expansion ("billion laughs"), the
13765
 * size of serialized output is (roughly) limited to the input size
13766
 * multiplied by this factor. The default value is 5.
13767
 *
13768
 * When working with documents making heavy use of entity expansion, it can
13769
 * be necessary to increase the value. For security reasons, this should only
13770
 * be considered when processing trusted input.
13771
 */
13772
void
13773
xmlCtxtSetMaxAmplification(xmlParserCtxtPtr ctxt, unsigned maxAmpl)
13774
0
{
13775
0
    ctxt->maxAmpl = maxAmpl;
13776
0
}
13777
13778
/**
13779
 * xmlCtxtParseDocument:
13780
 * @ctxt:  an XML parser context
13781
 * @input:  parser input
13782
 *
13783
 * Parse an XML document and return the resulting document tree.
13784
 * Takes ownership of the input object.
13785
 *
13786
 * Available since 2.13.0.
13787
 *
13788
 * Returns the resulting document tree or NULL
13789
 */
13790
xmlDocPtr
13791
xmlCtxtParseDocument(xmlParserCtxtPtr ctxt, xmlParserInputPtr input)
13792
714k
{
13793
714k
    xmlDocPtr ret = NULL;
13794
13795
714k
    if ((ctxt == NULL) || (input == NULL)) {
13796
0
        xmlFatalErr(ctxt, XML_ERR_ARGUMENT, NULL);
13797
0
        xmlFreeInputStream(input);
13798
0
        return(NULL);
13799
0
    }
13800
13801
    /* assert(ctxt->inputNr == 0); */
13802
714k
    while (ctxt->inputNr > 0)
13803
0
        xmlFreeInputStream(xmlCtxtPopInput(ctxt));
13804
13805
714k
    if (xmlCtxtPushInput(ctxt, input) < 0) {
13806
0
        xmlFreeInputStream(input);
13807
0
        return(NULL);
13808
0
    }
13809
13810
714k
    xmlParseDocument(ctxt);
13811
13812
714k
    ret = xmlCtxtGetDocument(ctxt);
13813
13814
    /* assert(ctxt->inputNr == 1); */
13815
1.42M
    while (ctxt->inputNr > 0)
13816
714k
        xmlFreeInputStream(xmlCtxtPopInput(ctxt));
13817
13818
714k
    return(ret);
13819
714k
}
13820
13821
/**
13822
 * xmlReadDoc:
13823
 * @cur:  a pointer to a zero terminated string
13824
 * @URL:  base URL (optional)
13825
 * @encoding:  the document encoding (optional)
13826
 * @options:  a combination of xmlParserOption
13827
 *
13828
 * Convenience function to parse an XML document from a
13829
 * zero-terminated string.
13830
 *
13831
 * See xmlCtxtReadDoc for details.
13832
 *
13833
 * Returns the resulting document tree
13834
 */
13835
xmlDocPtr
13836
xmlReadDoc(const xmlChar *cur, const char *URL, const char *encoding,
13837
           int options)
13838
0
{
13839
0
    xmlParserCtxtPtr ctxt;
13840
0
    xmlParserInputPtr input;
13841
0
    xmlDocPtr doc = NULL;
13842
13843
0
    ctxt = xmlNewParserCtxt();
13844
0
    if (ctxt == NULL)
13845
0
        return(NULL);
13846
13847
0
    xmlCtxtUseOptions(ctxt, options);
13848
13849
0
    input = xmlCtxtNewInputFromString(ctxt, URL, (const char *) cur, encoding,
13850
0
                                      XML_INPUT_BUF_STATIC);
13851
13852
0
    if (input != NULL)
13853
0
        doc = xmlCtxtParseDocument(ctxt, input);
13854
13855
0
    xmlFreeParserCtxt(ctxt);
13856
0
    return(doc);
13857
0
}
13858
13859
/**
13860
 * xmlReadFile:
13861
 * @filename:  a file or URL
13862
 * @encoding:  the document encoding (optional)
13863
 * @options:  a combination of xmlParserOption
13864
 *
13865
 * Convenience function to parse an XML file from the filesystem,
13866
 * the network or a global user-define resource loader.
13867
 *
13868
 * This function always enables the XML_PARSE_UNZIP option for
13869
 * backward compatibility. If a "-" filename is passed, it will
13870
 * read from stdin. Both of these features are potentially
13871
 * insecure and might be removed from later versions.
13872
 *
13873
 * See xmlCtxtReadFile for details.
13874
 *
13875
 * Returns the resulting document tree
13876
 */
13877
xmlDocPtr
13878
xmlReadFile(const char *filename, const char *encoding, int options)
13879
0
{
13880
0
    xmlParserCtxtPtr ctxt;
13881
0
    xmlParserInputPtr input;
13882
0
    xmlDocPtr doc = NULL;
13883
13884
0
    ctxt = xmlNewParserCtxt();
13885
0
    if (ctxt == NULL)
13886
0
        return(NULL);
13887
13888
0
    options |= XML_PARSE_UNZIP;
13889
13890
0
    xmlCtxtUseOptions(ctxt, options);
13891
13892
    /*
13893
     * Backward compatibility for users of command line utilities like
13894
     * xmlstarlet expecting "-" to mean stdin. This is dangerous and
13895
     * should be removed at some point.
13896
     */
13897
0
    if ((filename != NULL) && (filename[0] == '-') && (filename[1] == 0))
13898
0
        input = xmlCtxtNewInputFromFd(ctxt, filename, STDIN_FILENO,
13899
0
                                      encoding, 0);
13900
0
    else
13901
0
        input = xmlCtxtNewInputFromUrl(ctxt, filename, NULL, encoding, 0);
13902
13903
0
    if (input != NULL)
13904
0
        doc = xmlCtxtParseDocument(ctxt, input);
13905
13906
0
    xmlFreeParserCtxt(ctxt);
13907
0
    return(doc);
13908
0
}
13909
13910
/**
13911
 * xmlReadMemory:
13912
 * @buffer:  a pointer to a char array
13913
 * @size:  the size of the array
13914
 * @url:  base URL (optional)
13915
 * @encoding:  the document encoding (optional)
13916
 * @options:  a combination of xmlParserOption
13917
 *
13918
 * Parse an XML in-memory document and build a tree. The input buffer must
13919
 * not contain a terminating null byte.
13920
 *
13921
 * See xmlCtxtReadMemory for details.
13922
 *
13923
 * Returns the resulting document tree
13924
 */
13925
xmlDocPtr
13926
xmlReadMemory(const char *buffer, int size, const char *url,
13927
              const char *encoding, int options)
13928
63.0k
{
13929
63.0k
    xmlParserCtxtPtr ctxt;
13930
63.0k
    xmlParserInputPtr input;
13931
63.0k
    xmlDocPtr doc = NULL;
13932
13933
63.0k
    if (size < 0)
13934
0
  return(NULL);
13935
13936
63.0k
    ctxt = xmlNewParserCtxt();
13937
63.0k
    if (ctxt == NULL)
13938
0
        return(NULL);
13939
13940
63.0k
    xmlCtxtUseOptions(ctxt, options);
13941
13942
63.0k
    input = xmlCtxtNewInputFromMemory(ctxt, url, buffer, size, encoding,
13943
63.0k
                                      XML_INPUT_BUF_STATIC);
13944
13945
63.0k
    if (input != NULL)
13946
63.0k
        doc = xmlCtxtParseDocument(ctxt, input);
13947
13948
63.0k
    xmlFreeParserCtxt(ctxt);
13949
63.0k
    return(doc);
13950
63.0k
}
13951
13952
/**
13953
 * xmlReadFd:
13954
 * @fd:  an open file descriptor
13955
 * @URL:  base URL (optional)
13956
 * @encoding:  the document encoding (optional)
13957
 * @options:  a combination of xmlParserOption
13958
 *
13959
 * Parse an XML from a file descriptor and build a tree.
13960
 *
13961
 * See xmlCtxtReadFd for details.
13962
 *
13963
 * NOTE that the file descriptor will not be closed when the
13964
 * context is freed or reset.
13965
 *
13966
 * Returns the resulting document tree
13967
 */
13968
xmlDocPtr
13969
xmlReadFd(int fd, const char *URL, const char *encoding, int options)
13970
0
{
13971
0
    xmlParserCtxtPtr ctxt;
13972
0
    xmlParserInputPtr input;
13973
0
    xmlDocPtr doc = NULL;
13974
13975
0
    ctxt = xmlNewParserCtxt();
13976
0
    if (ctxt == NULL)
13977
0
        return(NULL);
13978
13979
0
    xmlCtxtUseOptions(ctxt, options);
13980
13981
0
    input = xmlCtxtNewInputFromFd(ctxt, URL, fd, encoding, 0);
13982
13983
0
    if (input != NULL)
13984
0
        doc = xmlCtxtParseDocument(ctxt, input);
13985
13986
0
    xmlFreeParserCtxt(ctxt);
13987
0
    return(doc);
13988
0
}
13989
13990
/**
13991
 * xmlReadIO:
13992
 * @ioread:  an I/O read function
13993
 * @ioclose:  an I/O close function (optional)
13994
 * @ioctx:  an I/O handler
13995
 * @URL:  base URL (optional)
13996
 * @encoding:  the document encoding (optional)
13997
 * @options:  a combination of xmlParserOption
13998
 *
13999
 * Parse an XML document from I/O functions and context and build a tree.
14000
 *
14001
 * See xmlCtxtReadIO for details.
14002
 *
14003
 * Returns the resulting document tree
14004
 */
14005
xmlDocPtr
14006
xmlReadIO(xmlInputReadCallback ioread, xmlInputCloseCallback ioclose,
14007
          void *ioctx, const char *URL, const char *encoding, int options)
14008
0
{
14009
0
    xmlParserCtxtPtr ctxt;
14010
0
    xmlParserInputPtr input;
14011
0
    xmlDocPtr doc = NULL;
14012
14013
0
    ctxt = xmlNewParserCtxt();
14014
0
    if (ctxt == NULL)
14015
0
        return(NULL);
14016
14017
0
    xmlCtxtUseOptions(ctxt, options);
14018
14019
0
    input = xmlCtxtNewInputFromIO(ctxt, URL, ioread, ioclose, ioctx,
14020
0
                                  encoding, 0);
14021
14022
0
    if (input != NULL)
14023
0
        doc = xmlCtxtParseDocument(ctxt, input);
14024
14025
0
    xmlFreeParserCtxt(ctxt);
14026
0
    return(doc);
14027
0
}
14028
14029
/**
14030
 * xmlCtxtReadDoc:
14031
 * @ctxt:  an XML parser context
14032
 * @str:  a pointer to a zero terminated string
14033
 * @URL:  base URL (optional)
14034
 * @encoding:  the document encoding (optional)
14035
 * @options:  a combination of xmlParserOption
14036
 *
14037
 * Parse an XML in-memory document and build a tree.
14038
 *
14039
 * @URL is used as base to resolve external entities and for error
14040
 * reporting.
14041
 *
14042
 * See xmlCtxtUseOptions for details.
14043
 *
14044
 * Returns the resulting document tree
14045
 */
14046
xmlDocPtr
14047
xmlCtxtReadDoc(xmlParserCtxtPtr ctxt, const xmlChar *str,
14048
               const char *URL, const char *encoding, int options)
14049
0
{
14050
0
    xmlParserInputPtr input;
14051
14052
0
    if (ctxt == NULL)
14053
0
        return(NULL);
14054
14055
0
    xmlCtxtReset(ctxt);
14056
0
    xmlCtxtUseOptions(ctxt, options);
14057
14058
0
    input = xmlCtxtNewInputFromString(ctxt, URL, (const char *) str, encoding,
14059
0
                                      XML_INPUT_BUF_STATIC);
14060
0
    if (input == NULL)
14061
0
        return(NULL);
14062
14063
0
    return(xmlCtxtParseDocument(ctxt, input));
14064
0
}
14065
14066
/**
14067
 * xmlCtxtReadFile:
14068
 * @ctxt:  an XML parser context
14069
 * @filename:  a file or URL
14070
 * @encoding:  the document encoding (optional)
14071
 * @options:  a combination of xmlParserOption
14072
 *
14073
 * Parse an XML file from the filesystem, the network or a user-defined
14074
 * resource loader.
14075
 *
14076
 * This function always enables the XML_PARSE_UNZIP option for
14077
 * backward compatibility. This feature is potentially insecure
14078
 * and might be removed from later versions.
14079
 *
14080
 * Returns the resulting document tree
14081
 */
14082
xmlDocPtr
14083
xmlCtxtReadFile(xmlParserCtxtPtr ctxt, const char *filename,
14084
                const char *encoding, int options)
14085
0
{
14086
0
    xmlParserInputPtr input;
14087
14088
0
    if (ctxt == NULL)
14089
0
        return(NULL);
14090
14091
0
    options |= XML_PARSE_UNZIP;
14092
14093
0
    xmlCtxtReset(ctxt);
14094
0
    xmlCtxtUseOptions(ctxt, options);
14095
14096
0
    input = xmlCtxtNewInputFromUrl(ctxt, filename, NULL, encoding, 0);
14097
0
    if (input == NULL)
14098
0
        return(NULL);
14099
14100
0
    return(xmlCtxtParseDocument(ctxt, input));
14101
0
}
14102
14103
/**
14104
 * xmlCtxtReadMemory:
14105
 * @ctxt:  an XML parser context
14106
 * @buffer:  a pointer to a char array
14107
 * @size:  the size of the array
14108
 * @URL:  base URL (optional)
14109
 * @encoding:  the document encoding (optional)
14110
 * @options:  a combination of xmlParserOption
14111
 *
14112
 * Parse an XML in-memory document and build a tree. The input buffer must
14113
 * not contain a terminating null byte.
14114
 *
14115
 * @URL is used as base to resolve external entities and for error
14116
 * reporting.
14117
 *
14118
 * See xmlCtxtUseOptions for details.
14119
 *
14120
 * Returns the resulting document tree
14121
 */
14122
xmlDocPtr
14123
xmlCtxtReadMemory(xmlParserCtxtPtr ctxt, const char *buffer, int size,
14124
                  const char *URL, const char *encoding, int options)
14125
0
{
14126
0
    xmlParserInputPtr input;
14127
14128
0
    if ((ctxt == NULL) || (size < 0))
14129
0
        return(NULL);
14130
14131
0
    xmlCtxtReset(ctxt);
14132
0
    xmlCtxtUseOptions(ctxt, options);
14133
14134
0
    input = xmlCtxtNewInputFromMemory(ctxt, URL, buffer, size, encoding,
14135
0
                                      XML_INPUT_BUF_STATIC);
14136
0
    if (input == NULL)
14137
0
        return(NULL);
14138
14139
0
    return(xmlCtxtParseDocument(ctxt, input));
14140
0
}
14141
14142
/**
14143
 * xmlCtxtReadFd:
14144
 * @ctxt:  an XML parser context
14145
 * @fd:  an open file descriptor
14146
 * @URL:  base URL (optional)
14147
 * @encoding:  the document encoding (optional)
14148
 * @options:  a combination of xmlParserOption
14149
 *
14150
 * Parse an XML document from a file descriptor and build a tree.
14151
 *
14152
 * NOTE that the file descriptor will not be closed when the
14153
 * context is freed or reset.
14154
 *
14155
 * @URL is used as base to resolve external entities and for error
14156
 * reporting.
14157
 *
14158
 * See xmlCtxtUseOptions for details.
14159
 *
14160
 * Returns the resulting document tree
14161
 */
14162
xmlDocPtr
14163
xmlCtxtReadFd(xmlParserCtxtPtr ctxt, int fd,
14164
              const char *URL, const char *encoding, int options)
14165
0
{
14166
0
    xmlParserInputPtr input;
14167
14168
0
    if (ctxt == NULL)
14169
0
        return(NULL);
14170
14171
0
    xmlCtxtReset(ctxt);
14172
0
    xmlCtxtUseOptions(ctxt, options);
14173
14174
0
    input = xmlCtxtNewInputFromFd(ctxt, URL, fd, encoding, 0);
14175
0
    if (input == NULL)
14176
0
        return(NULL);
14177
14178
0
    return(xmlCtxtParseDocument(ctxt, input));
14179
0
}
14180
14181
/**
14182
 * xmlCtxtReadIO:
14183
 * @ctxt:  an XML parser context
14184
 * @ioread:  an I/O read function
14185
 * @ioclose:  an I/O close function
14186
 * @ioctx:  an I/O handler
14187
 * @URL:  the base URL to use for the document
14188
 * @encoding:  the document encoding, or NULL
14189
 * @options:  a combination of xmlParserOption
14190
 *
14191
 * parse an XML document from I/O functions and source and build a tree.
14192
 * This reuses the existing @ctxt parser context
14193
 *
14194
 * @URL is used as base to resolve external entities and for error
14195
 * reporting.
14196
 *
14197
 * See xmlCtxtUseOptions for details.
14198
 *
14199
 * Returns the resulting document tree
14200
 */
14201
xmlDocPtr
14202
xmlCtxtReadIO(xmlParserCtxtPtr ctxt, xmlInputReadCallback ioread,
14203
              xmlInputCloseCallback ioclose, void *ioctx,
14204
        const char *URL,
14205
              const char *encoding, int options)
14206
0
{
14207
0
    xmlParserInputPtr input;
14208
14209
0
    if (ctxt == NULL)
14210
0
        return(NULL);
14211
14212
0
    xmlCtxtReset(ctxt);
14213
0
    xmlCtxtUseOptions(ctxt, options);
14214
14215
0
    input = xmlCtxtNewInputFromIO(ctxt, URL, ioread, ioclose, ioctx,
14216
0
                                  encoding, 0);
14217
0
    if (input == NULL)
14218
0
        return(NULL);
14219
14220
0
    return(xmlCtxtParseDocument(ctxt, input));
14221
0
}
14222