Coverage Report

Created: 2025-07-01 06:27

/src/libxml2/parser.c
Line
Count
Source (jump to first uncovered line)
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
 * Author: Daniel Veillard
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
#include "private/tree.h"
79
80
0
#define NS_INDEX_EMPTY  INT_MAX
81
0
#define NS_INDEX_XML    (INT_MAX - 1)
82
0
#define URI_HASH_EMPTY  0xD943A04E
83
0
#define URI_HASH_XML    0xF0451F02
84
85
#ifndef STDIN_FILENO
86
0
  #define STDIN_FILENO 0
87
#endif
88
89
#ifndef SIZE_MAX
90
  #define SIZE_MAX ((size_t) -1)
91
#endif
92
93
0
#define XML_MAX_ATTRS 100000000 /* 100 million */
94
95
0
#define XML_SPECIAL_EXTERNAL    (1 << 20)
96
0
#define XML_SPECIAL_TYPE_MASK   (XML_SPECIAL_EXTERNAL - 1)
97
98
0
#define XML_ATTVAL_ALLOC        (1 << 0)
99
0
#define XML_ATTVAL_NORM_CHANGE  (1 << 1)
100
101
struct _xmlStartTag {
102
    const xmlChar *prefix;
103
    const xmlChar *URI;
104
    int line;
105
    int nsNr;
106
};
107
108
typedef struct {
109
    void *saxData;
110
    unsigned prefixHashValue;
111
    unsigned uriHashValue;
112
    unsigned elementId;
113
    int oldIndex;
114
} xmlParserNsExtra;
115
116
typedef struct {
117
    unsigned hashValue;
118
    int index;
119
} xmlParserNsBucket;
120
121
struct _xmlParserNsData {
122
    xmlParserNsExtra *extra;
123
124
    unsigned hashSize;
125
    unsigned hashElems;
126
    xmlParserNsBucket *hash;
127
128
    unsigned elementId;
129
    int defaultNsIndex;
130
    int minNsIndex;
131
};
132
133
static int
134
xmlParseElementStart(xmlParserCtxtPtr ctxt);
135
136
static void
137
xmlParseElementEnd(xmlParserCtxtPtr ctxt);
138
139
static xmlEntityPtr
140
xmlLookupGeneralEntity(xmlParserCtxtPtr ctxt, const xmlChar *name, int inAttr);
141
142
static const xmlChar *
143
xmlParseEntityRefInternal(xmlParserCtxtPtr ctxt);
144
145
/************************************************************************
146
 *                  *
147
 *  Arbitrary limits set in the parser. See XML_PARSE_HUGE    *
148
 *                  *
149
 ************************************************************************/
150
151
#define XML_PARSER_BIG_ENTITY 1000
152
#define XML_PARSER_LOT_ENTITY 5000
153
154
/*
155
 * Constants for protection against abusive entity expansion
156
 * ("billion laughs").
157
 */
158
159
/*
160
 * A certain amount of entity expansion which is always allowed.
161
 */
162
0
#define XML_PARSER_ALLOWED_EXPANSION 1000000
163
164
/*
165
 * Fixed cost for each entity reference. This crudely models processing time
166
 * as well to protect, for example, against exponential expansion of empty
167
 * or very short entities.
168
 */
169
0
#define XML_ENT_FIXED_COST 20
170
171
0
#define XML_PARSER_BIG_BUFFER_SIZE 300
172
0
#define XML_PARSER_BUFFER_SIZE 100
173
0
#define SAX_COMPAT_MODE BAD_CAST "SAX compatibility mode document"
174
175
/**
176
 * XML_PARSER_CHUNK_SIZE
177
 *
178
 * When calling GROW that's the minimal amount of data
179
 * the parser expected to have received. It is not a hard
180
 * limit but an optimization when reading strings like Names
181
 * It is not strictly needed as long as inputs available characters
182
 * are followed by 0, which should be provided by the I/O level
183
 */
184
#define XML_PARSER_CHUNK_SIZE 100
185
186
/**
187
 * Constant string describing the version of the library used at
188
 * run-time.
189
 */
190
const char *const
191
xmlParserVersion = LIBXML_VERSION_STRING LIBXML_VERSION_EXTRA;
192
193
/*
194
 * List of XML prefixed PI allowed by W3C specs
195
 */
196
197
static const char* const xmlW3CPIs[] = {
198
    "xml-stylesheet",
199
    "xml-model",
200
    NULL
201
};
202
203
204
/* DEPR void xmlParserHandleReference(xmlParserCtxtPtr ctxt); */
205
static xmlEntityPtr xmlParseStringPEReference(xmlParserCtxtPtr ctxt,
206
                                              const xmlChar **str);
207
208
static void
209
xmlCtxtParseEntity(xmlParserCtxtPtr ctxt, xmlEntityPtr ent);
210
211
static int
212
xmlLoadEntityContent(xmlParserCtxtPtr ctxt, xmlEntityPtr entity);
213
214
static void
215
xmlParsePERefInternal(xmlParserCtxt *ctxt, int markupDecl);
216
217
/************************************************************************
218
 *                  *
219
 *    Some factorized error routines        *
220
 *                  *
221
 ************************************************************************/
222
223
static void
224
0
xmlErrMemory(xmlParserCtxtPtr ctxt) {
225
0
    xmlCtxtErrMemory(ctxt);
226
0
}
227
228
/**
229
 * Handle a redefinition of attribute error
230
 *
231
 * @param ctxt  an XML parser context
232
 * @param prefix  the attribute prefix
233
 * @param localname  the attribute localname
234
 */
235
static void
236
xmlErrAttributeDup(xmlParserCtxtPtr ctxt, const xmlChar * prefix,
237
                   const xmlChar * localname)
238
0
{
239
0
    if (prefix == NULL)
240
0
        xmlCtxtErr(ctxt, NULL, XML_FROM_PARSER, XML_ERR_ATTRIBUTE_REDEFINED,
241
0
                   XML_ERR_FATAL, localname, NULL, NULL, 0,
242
0
                   "Attribute %s redefined\n", localname);
243
0
    else
244
0
        xmlCtxtErr(ctxt, NULL, XML_FROM_PARSER, XML_ERR_ATTRIBUTE_REDEFINED,
245
0
                   XML_ERR_FATAL, prefix, localname, NULL, 0,
246
0
                   "Attribute %s:%s redefined\n", prefix, localname);
247
0
}
248
249
/**
250
 * Handle a fatal parser error, i.e. violating Well-Formedness constraints
251
 *
252
 * @param ctxt  an XML parser context
253
 * @param error  the error number
254
 * @param msg  the error message
255
 */
256
static void LIBXML_ATTR_FORMAT(3,0)
257
xmlFatalErrMsg(xmlParserCtxtPtr ctxt, xmlParserErrors error,
258
               const char *msg)
259
0
{
260
0
    xmlCtxtErr(ctxt, NULL, XML_FROM_PARSER, error, XML_ERR_FATAL,
261
0
               NULL, NULL, NULL, 0, "%s", msg);
262
0
}
263
264
/**
265
 * Handle a warning.
266
 *
267
 * @param ctxt  an XML parser context
268
 * @param error  the error number
269
 * @param msg  the error message
270
 * @param str1  extra data
271
 * @param str2  extra data
272
 */
273
void LIBXML_ATTR_FORMAT(3,0)
274
xmlWarningMsg(xmlParserCtxtPtr ctxt, xmlParserErrors error,
275
              const char *msg, const xmlChar *str1, const xmlChar *str2)
276
0
{
277
0
    xmlCtxtErr(ctxt, NULL, XML_FROM_PARSER, error, XML_ERR_WARNING,
278
0
               str1, str2, NULL, 0, msg, str1, str2);
279
0
}
280
281
#ifdef LIBXML_VALID_ENABLED
282
/**
283
 * Handle a validity error.
284
 *
285
 * @param ctxt  an XML parser context
286
 * @param error  the error number
287
 * @param msg  the error message
288
 * @param str1  extra data
289
 * @param str2  extra data
290
 */
291
static void LIBXML_ATTR_FORMAT(3,0)
292
xmlValidityError(xmlParserCtxtPtr ctxt, xmlParserErrors error,
293
              const char *msg, const xmlChar *str1, const xmlChar *str2)
294
0
{
295
0
    ctxt->valid = 0;
296
297
0
    xmlCtxtErr(ctxt, NULL, XML_FROM_DTD, error, XML_ERR_ERROR,
298
0
               str1, str2, NULL, 0, msg, str1, str2);
299
0
}
300
#endif
301
302
/**
303
 * Handle a fatal parser error, i.e. violating Well-Formedness constraints
304
 *
305
 * @param ctxt  an XML parser context
306
 * @param error  the error number
307
 * @param msg  the error message
308
 * @param val  an integer value
309
 */
310
static void LIBXML_ATTR_FORMAT(3,0)
311
xmlFatalErrMsgInt(xmlParserCtxtPtr ctxt, xmlParserErrors error,
312
                  const char *msg, int val)
313
0
{
314
0
    xmlCtxtErr(ctxt, NULL, XML_FROM_PARSER, error, XML_ERR_FATAL,
315
0
               NULL, NULL, NULL, val, msg, val);
316
0
}
317
318
/**
319
 * Handle a fatal parser error, i.e. violating Well-Formedness constraints
320
 *
321
 * @param ctxt  an XML parser context
322
 * @param error  the error number
323
 * @param msg  the error message
324
 * @param str1  an string info
325
 * @param val  an integer value
326
 * @param str2  an string info
327
 */
328
static void LIBXML_ATTR_FORMAT(3,0)
329
xmlFatalErrMsgStrIntStr(xmlParserCtxtPtr ctxt, xmlParserErrors error,
330
                  const char *msg, const xmlChar *str1, int val,
331
      const xmlChar *str2)
332
0
{
333
0
    xmlCtxtErr(ctxt, NULL, XML_FROM_PARSER, error, XML_ERR_FATAL,
334
0
               str1, str2, NULL, val, msg, str1, val, str2);
335
0
}
336
337
/**
338
 * Handle a fatal parser error, i.e. violating Well-Formedness constraints
339
 *
340
 * @param ctxt  an XML parser context
341
 * @param error  the error number
342
 * @param msg  the error message
343
 * @param val  a string value
344
 */
345
static void LIBXML_ATTR_FORMAT(3,0)
346
xmlFatalErrMsgStr(xmlParserCtxtPtr ctxt, xmlParserErrors error,
347
                  const char *msg, const xmlChar * val)
348
0
{
349
0
    xmlCtxtErr(ctxt, NULL, XML_FROM_PARSER, error, XML_ERR_FATAL,
350
0
               val, NULL, NULL, 0, msg, val);
351
0
}
352
353
/**
354
 * Handle a non fatal parser error
355
 *
356
 * @param ctxt  an XML parser context
357
 * @param error  the error number
358
 * @param msg  the error message
359
 * @param val  a string value
360
 */
361
static void LIBXML_ATTR_FORMAT(3,0)
362
xmlErrMsgStr(xmlParserCtxtPtr ctxt, xmlParserErrors error,
363
                  const char *msg, const xmlChar * val)
364
0
{
365
0
    xmlCtxtErr(ctxt, NULL, XML_FROM_PARSER, error, XML_ERR_ERROR,
366
0
               val, NULL, NULL, 0, msg, val);
367
0
}
368
369
/**
370
 * Handle a fatal parser error, i.e. violating Well-Formedness constraints
371
 *
372
 * @param ctxt  an XML parser context
373
 * @param error  the error number
374
 * @param msg  the message
375
 * @param info1  extra information string
376
 * @param info2  extra information string
377
 * @param info3  extra information string
378
 */
379
static void LIBXML_ATTR_FORMAT(3,0)
380
xmlNsErr(xmlParserCtxtPtr ctxt, xmlParserErrors error,
381
         const char *msg,
382
         const xmlChar * info1, const xmlChar * info2,
383
         const xmlChar * info3)
384
0
{
385
0
    ctxt->nsWellFormed = 0;
386
387
0
    xmlCtxtErr(ctxt, NULL, XML_FROM_NAMESPACE, error, XML_ERR_ERROR,
388
0
               info1, info2, info3, 0, msg, info1, info2, info3);
389
0
}
390
391
/**
392
 * Handle a namespace warning error
393
 *
394
 * @param ctxt  an XML parser context
395
 * @param error  the error number
396
 * @param msg  the message
397
 * @param info1  extra information string
398
 * @param info2  extra information string
399
 * @param info3  extra information string
400
 */
401
static void LIBXML_ATTR_FORMAT(3,0)
402
xmlNsWarn(xmlParserCtxtPtr ctxt, xmlParserErrors error,
403
         const char *msg,
404
         const xmlChar * info1, const xmlChar * info2,
405
         const xmlChar * info3)
406
0
{
407
0
    xmlCtxtErr(ctxt, NULL, XML_FROM_NAMESPACE, error, XML_ERR_WARNING,
408
0
               info1, info2, info3, 0, msg, info1, info2, info3);
409
0
}
410
411
static void
412
0
xmlSaturatedAdd(unsigned long *dst, unsigned long val) {
413
0
    if (val > ULONG_MAX - *dst)
414
0
        *dst = ULONG_MAX;
415
0
    else
416
0
        *dst += val;
417
0
}
418
419
static void
420
0
xmlSaturatedAddSizeT(unsigned long *dst, unsigned long val) {
421
0
    if (val > ULONG_MAX - *dst)
422
0
        *dst = ULONG_MAX;
423
0
    else
424
0
        *dst += val;
425
0
}
426
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
 * @param ctxt  parser context
446
 * @param extra  sum of unexpanded entity sizes
447
 * @returns 1 on error, 0 on success.
448
 */
449
static int
450
xmlParserEntityCheck(xmlParserCtxtPtr ctxt, unsigned long extra)
451
0
{
452
0
    unsigned long consumed;
453
0
    unsigned long *expandedSize;
454
0
    xmlParserInputPtr input = ctxt->input;
455
0
    xmlEntityPtr entity = input->entity;
456
457
0
    if ((entity) && (entity->flags & XML_ENT_CHECKED))
458
0
        return(0);
459
460
    /*
461
     * Compute total consumed bytes so far, including input streams of
462
     * external entities.
463
     */
464
0
    consumed = input->consumed;
465
0
    xmlSaturatedAddSizeT(&consumed, input->cur - input->base);
466
0
    xmlSaturatedAdd(&consumed, ctxt->sizeentities);
467
468
0
    if (entity)
469
0
        expandedSize = &entity->expandedSize;
470
0
    else
471
0
        expandedSize = &ctxt->sizeentcopy;
472
473
    /*
474
     * Add extra cost and some fixed cost.
475
     */
476
0
    xmlSaturatedAdd(expandedSize, extra);
477
0
    xmlSaturatedAdd(expandedSize, XML_ENT_FIXED_COST);
478
479
    /*
480
     * It's important to always use saturation arithmetic when tracking
481
     * entity sizes to make the size checks reliable. If "sizeentcopy"
482
     * overflows, we have to abort.
483
     */
484
0
    if ((*expandedSize > XML_PARSER_ALLOWED_EXPANSION) &&
485
0
        ((*expandedSize >= ULONG_MAX) ||
486
0
         (*expandedSize / ctxt->maxAmpl > consumed))) {
487
0
        xmlFatalErrMsg(ctxt, XML_ERR_RESOURCE_LIMIT,
488
0
                       "Maximum entity amplification factor exceeded, see "
489
0
                       "xmlCtxtSetMaxAmplification.\n");
490
0
        xmlHaltParser(ctxt);
491
0
        return(1);
492
0
    }
493
494
0
    return(0);
495
0
}
496
497
/************************************************************************
498
 *                  *
499
 *    Library wide options          *
500
 *                  *
501
 ************************************************************************/
502
503
/**
504
 * Examines if the library has been compiled with a given feature.
505
 *
506
 * @param feature  the feature to be examined
507
 * @returns zero (0) if the feature does not exist or an unknown
508
 * feature is requested, non-zero otherwise.
509
 */
510
int
511
xmlHasFeature(xmlFeature feature)
512
70.5k
{
513
70.5k
    switch (feature) {
514
2.82k
  case XML_WITH_THREAD:
515
2.82k
#ifdef LIBXML_THREAD_ENABLED
516
2.82k
      return(1);
517
#else
518
      return(0);
519
#endif
520
0
        case XML_WITH_TREE:
521
0
            return(1);
522
2.82k
        case XML_WITH_OUTPUT:
523
2.82k
#ifdef LIBXML_OUTPUT_ENABLED
524
2.82k
            return(1);
525
#else
526
            return(0);
527
#endif
528
2.82k
        case XML_WITH_PUSH:
529
2.82k
#ifdef LIBXML_PUSH_ENABLED
530
2.82k
            return(1);
531
#else
532
            return(0);
533
#endif
534
2.82k
        case XML_WITH_READER:
535
2.82k
#ifdef LIBXML_READER_ENABLED
536
2.82k
            return(1);
537
#else
538
            return(0);
539
#endif
540
2.82k
        case XML_WITH_PATTERN:
541
2.82k
#ifdef LIBXML_PATTERN_ENABLED
542
2.82k
            return(1);
543
#else
544
            return(0);
545
#endif
546
2.82k
        case XML_WITH_WRITER:
547
2.82k
#ifdef LIBXML_WRITER_ENABLED
548
2.82k
            return(1);
549
#else
550
            return(0);
551
#endif
552
2.82k
        case XML_WITH_SAX1:
553
2.82k
#ifdef LIBXML_SAX1_ENABLED
554
2.82k
            return(1);
555
#else
556
            return(0);
557
#endif
558
0
        case XML_WITH_HTTP:
559
0
            return(0);
560
2.82k
        case XML_WITH_VALID:
561
2.82k
#ifdef LIBXML_VALID_ENABLED
562
2.82k
            return(1);
563
#else
564
            return(0);
565
#endif
566
2.82k
        case XML_WITH_HTML:
567
2.82k
#ifdef LIBXML_HTML_ENABLED
568
2.82k
            return(1);
569
#else
570
            return(0);
571
#endif
572
0
        case XML_WITH_LEGACY:
573
0
            return(0);
574
2.82k
        case XML_WITH_C14N:
575
2.82k
#ifdef LIBXML_C14N_ENABLED
576
2.82k
            return(1);
577
#else
578
            return(0);
579
#endif
580
2.82k
        case XML_WITH_CATALOG:
581
2.82k
#ifdef LIBXML_CATALOG_ENABLED
582
2.82k
            return(1);
583
#else
584
            return(0);
585
#endif
586
2.82k
        case XML_WITH_XPATH:
587
2.82k
#ifdef LIBXML_XPATH_ENABLED
588
2.82k
            return(1);
589
#else
590
            return(0);
591
#endif
592
2.82k
        case XML_WITH_XPTR:
593
2.82k
#ifdef LIBXML_XPTR_ENABLED
594
2.82k
            return(1);
595
#else
596
            return(0);
597
#endif
598
2.82k
        case XML_WITH_XINCLUDE:
599
2.82k
#ifdef LIBXML_XINCLUDE_ENABLED
600
2.82k
            return(1);
601
#else
602
            return(0);
603
#endif
604
2.82k
        case XML_WITH_ICONV:
605
2.82k
#ifdef LIBXML_ICONV_ENABLED
606
2.82k
            return(1);
607
#else
608
            return(0);
609
#endif
610
2.82k
        case XML_WITH_ISO8859X:
611
2.82k
#ifdef LIBXML_ISO8859X_ENABLED
612
2.82k
            return(1);
613
#else
614
            return(0);
615
#endif
616
0
        case XML_WITH_UNICODE:
617
0
            return(0);
618
2.82k
        case XML_WITH_REGEXP:
619
2.82k
#ifdef LIBXML_REGEXP_ENABLED
620
2.82k
            return(1);
621
#else
622
            return(0);
623
#endif
624
0
        case XML_WITH_AUTOMATA:
625
0
#ifdef LIBXML_REGEXP_ENABLED
626
0
            return(1);
627
#else
628
            return(0);
629
#endif
630
0
        case XML_WITH_EXPR:
631
0
            return(0);
632
2.82k
        case XML_WITH_RELAXNG:
633
2.82k
#ifdef LIBXML_RELAXNG_ENABLED
634
2.82k
            return(1);
635
#else
636
            return(0);
637
#endif
638
2.82k
        case XML_WITH_SCHEMAS:
639
2.82k
#ifdef LIBXML_SCHEMAS_ENABLED
640
2.82k
            return(1);
641
#else
642
            return(0);
643
#endif
644
2.82k
        case XML_WITH_SCHEMATRON:
645
#ifdef LIBXML_SCHEMATRON_ENABLED
646
            return(1);
647
#else
648
2.82k
            return(0);
649
0
#endif
650
2.82k
        case XML_WITH_MODULES:
651
2.82k
#ifdef LIBXML_MODULES_ENABLED
652
2.82k
            return(1);
653
#else
654
            return(0);
655
#endif
656
2.82k
        case XML_WITH_DEBUG:
657
#ifdef LIBXML_DEBUG_ENABLED
658
            return(1);
659
#else
660
2.82k
            return(0);
661
0
#endif
662
0
        case XML_WITH_DEBUG_MEM:
663
0
            return(0);
664
2.82k
        case XML_WITH_ZLIB:
665
2.82k
#ifdef LIBXML_ZLIB_ENABLED
666
2.82k
            return(1);
667
#else
668
            return(0);
669
#endif
670
2.82k
        case XML_WITH_LZMA:
671
2.82k
#ifdef LIBXML_LZMA_ENABLED
672
2.82k
            return(1);
673
#else
674
            return(0);
675
#endif
676
2.82k
        case XML_WITH_ICU:
677
#ifdef LIBXML_ICU_ENABLED
678
            return(1);
679
#else
680
2.82k
            return(0);
681
0
#endif
682
0
        default:
683
0
      break;
684
70.5k
     }
685
0
     return(0);
686
70.5k
}
687
688
/************************************************************************
689
 *                  *
690
 *      Simple string buffer        *
691
 *                  *
692
 ************************************************************************/
693
694
typedef struct {
695
    xmlChar *mem;
696
    unsigned size;
697
    unsigned cap; /* size < cap */
698
    unsigned max; /* size <= max */
699
    xmlParserErrors code;
700
} xmlSBuf;
701
702
static void
703
0
xmlSBufInit(xmlSBuf *buf, unsigned max) {
704
0
    buf->mem = NULL;
705
0
    buf->size = 0;
706
0
    buf->cap = 0;
707
0
    buf->max = max;
708
0
    buf->code = XML_ERR_OK;
709
0
}
710
711
static int
712
0
xmlSBufGrow(xmlSBuf *buf, unsigned len) {
713
0
    xmlChar *mem;
714
0
    unsigned cap;
715
716
0
    if (len >= UINT_MAX / 2 - buf->size) {
717
0
        if (buf->code == XML_ERR_OK)
718
0
            buf->code = XML_ERR_RESOURCE_LIMIT;
719
0
        return(-1);
720
0
    }
721
722
0
    cap = (buf->size + len) * 2;
723
0
    if (cap < 240)
724
0
        cap = 240;
725
726
0
    mem = xmlRealloc(buf->mem, cap);
727
0
    if (mem == NULL) {
728
0
        buf->code = XML_ERR_NO_MEMORY;
729
0
        return(-1);
730
0
    }
731
732
0
    buf->mem = mem;
733
0
    buf->cap = cap;
734
735
0
    return(0);
736
0
}
737
738
static void
739
0
xmlSBufAddString(xmlSBuf *buf, const xmlChar *str, unsigned len) {
740
0
    if (buf->max - buf->size < len) {
741
0
        if (buf->code == XML_ERR_OK)
742
0
            buf->code = XML_ERR_RESOURCE_LIMIT;
743
0
        return;
744
0
    }
745
746
0
    if (buf->cap - buf->size <= len) {
747
0
        if (xmlSBufGrow(buf, len) < 0)
748
0
            return;
749
0
    }
750
751
0
    if (len > 0)
752
0
        memcpy(buf->mem + buf->size, str, len);
753
0
    buf->size += len;
754
0
}
755
756
static void
757
0
xmlSBufAddCString(xmlSBuf *buf, const char *str, unsigned len) {
758
0
    xmlSBufAddString(buf, (const xmlChar *) str, len);
759
0
}
760
761
static void
762
0
xmlSBufAddChar(xmlSBuf *buf, int c) {
763
0
    xmlChar *end;
764
765
0
    if (buf->max - buf->size < 4) {
766
0
        if (buf->code == XML_ERR_OK)
767
0
            buf->code = XML_ERR_RESOURCE_LIMIT;
768
0
        return;
769
0
    }
770
771
0
    if (buf->cap - buf->size <= 4) {
772
0
        if (xmlSBufGrow(buf, 4) < 0)
773
0
            return;
774
0
    }
775
776
0
    end = buf->mem + buf->size;
777
778
0
    if (c < 0x80) {
779
0
        *end = (xmlChar) c;
780
0
        buf->size += 1;
781
0
    } else {
782
0
        buf->size += xmlCopyCharMultiByte(end, c);
783
0
    }
784
0
}
785
786
static void
787
0
xmlSBufAddReplChar(xmlSBuf *buf) {
788
0
    xmlSBufAddCString(buf, "\xEF\xBF\xBD", 3);
789
0
}
790
791
static void
792
0
xmlSBufReportError(xmlSBuf *buf, xmlParserCtxtPtr ctxt, const char *errMsg) {
793
0
    if (buf->code == XML_ERR_NO_MEMORY)
794
0
        xmlCtxtErrMemory(ctxt);
795
0
    else
796
0
        xmlFatalErr(ctxt, buf->code, errMsg);
797
0
}
798
799
static xmlChar *
800
xmlSBufFinish(xmlSBuf *buf, int *sizeOut, xmlParserCtxtPtr ctxt,
801
0
              const char *errMsg) {
802
0
    if (buf->mem == NULL) {
803
0
        buf->mem = xmlMalloc(1);
804
0
        if (buf->mem == NULL) {
805
0
            buf->code = XML_ERR_NO_MEMORY;
806
0
        } else {
807
0
            buf->mem[0] = 0;
808
0
        }
809
0
    } else {
810
0
        buf->mem[buf->size] = 0;
811
0
    }
812
813
0
    if (buf->code == XML_ERR_OK) {
814
0
        if (sizeOut != NULL)
815
0
            *sizeOut = buf->size;
816
0
        return(buf->mem);
817
0
    }
818
819
0
    xmlSBufReportError(buf, ctxt, errMsg);
820
821
0
    xmlFree(buf->mem);
822
823
0
    if (sizeOut != NULL)
824
0
        *sizeOut = 0;
825
0
    return(NULL);
826
0
}
827
828
static void
829
0
xmlSBufCleanup(xmlSBuf *buf, xmlParserCtxtPtr ctxt, const char *errMsg) {
830
0
    if (buf->code != XML_ERR_OK)
831
0
        xmlSBufReportError(buf, ctxt, errMsg);
832
833
0
    xmlFree(buf->mem);
834
0
}
835
836
static int
837
xmlUTF8MultibyteLen(xmlParserCtxtPtr ctxt, const xmlChar *str,
838
0
                    const char *errMsg) {
839
0
    int c = str[0];
840
0
    int c1 = str[1];
841
842
0
    if ((c1 & 0xC0) != 0x80)
843
0
        goto encoding_error;
844
845
0
    if (c < 0xE0) {
846
        /* 2-byte sequence */
847
0
        if (c < 0xC2)
848
0
            goto encoding_error;
849
850
0
        return(2);
851
0
    } else {
852
0
        int c2 = str[2];
853
854
0
        if ((c2 & 0xC0) != 0x80)
855
0
            goto encoding_error;
856
857
0
        if (c < 0xF0) {
858
            /* 3-byte sequence */
859
0
            if (c == 0xE0) {
860
                /* overlong */
861
0
                if (c1 < 0xA0)
862
0
                    goto encoding_error;
863
0
            } else if (c == 0xED) {
864
                /* surrogate */
865
0
                if (c1 >= 0xA0)
866
0
                    goto encoding_error;
867
0
            } else if (c == 0xEF) {
868
                /* U+FFFE and U+FFFF are invalid Chars */
869
0
                if ((c1 == 0xBF) && (c2 >= 0xBE))
870
0
                    xmlFatalErrMsg(ctxt, XML_ERR_INVALID_CHAR, errMsg);
871
0
            }
872
873
0
            return(3);
874
0
        } else {
875
            /* 4-byte sequence */
876
0
            if ((str[3] & 0xC0) != 0x80)
877
0
                goto encoding_error;
878
0
            if (c == 0xF0) {
879
                /* overlong */
880
0
                if (c1 < 0x90)
881
0
                    goto encoding_error;
882
0
            } else if (c >= 0xF4) {
883
                /* greater than 0x10FFFF */
884
0
                if ((c > 0xF4) || (c1 >= 0x90))
885
0
                    goto encoding_error;
886
0
            }
887
888
0
            return(4);
889
0
        }
890
0
    }
891
892
0
encoding_error:
893
    /* Only report the first error */
894
0
    if ((ctxt->input->flags & XML_INPUT_ENCODING_ERROR) == 0) {
895
0
        xmlCtxtErrIO(ctxt, XML_ERR_INVALID_ENCODING, NULL);
896
0
        ctxt->input->flags |= XML_INPUT_ENCODING_ERROR;
897
0
    }
898
899
0
    return(0);
900
0
}
901
902
/************************************************************************
903
 *                  *
904
 *    SAX2 defaulted attributes handling      *
905
 *                  *
906
 ************************************************************************/
907
908
/**
909
 * Final initialization of the parser context before starting to parse.
910
 *
911
 * This accounts for users modifying struct members of parser context
912
 * directly.
913
 *
914
 * @param ctxt  an XML parser context
915
 */
916
static void
917
0
xmlCtxtInitializeLate(xmlParserCtxtPtr ctxt) {
918
0
    xmlSAXHandlerPtr sax;
919
920
    /* Avoid unused variable warning if features are disabled. */
921
0
    (void) sax;
922
923
    /*
924
     * Changing the SAX struct directly is still widespread practice
925
     * in internal and external code.
926
     */
927
0
    if (ctxt == NULL) return;
928
0
    sax = ctxt->sax;
929
0
#ifdef LIBXML_SAX1_ENABLED
930
    /*
931
     * Only enable SAX2 if there SAX2 element handlers, except when there
932
     * are no element handlers at all.
933
     */
934
0
    if (((ctxt->options & XML_PARSE_SAX1) == 0) &&
935
0
        (sax) &&
936
0
        (sax->initialized == XML_SAX2_MAGIC) &&
937
0
        ((sax->startElementNs != NULL) ||
938
0
         (sax->endElementNs != NULL) ||
939
0
         ((sax->startElement == NULL) && (sax->endElement == NULL))))
940
0
        ctxt->sax2 = 1;
941
#else
942
    ctxt->sax2 = 1;
943
#endif /* LIBXML_SAX1_ENABLED */
944
945
    /*
946
     * Some users replace the dictionary directly in the context struct.
947
     * We really need an API function to do that cleanly.
948
     */
949
0
    ctxt->str_xml = xmlDictLookup(ctxt->dict, BAD_CAST "xml", 3);
950
0
    ctxt->str_xmlns = xmlDictLookup(ctxt->dict, BAD_CAST "xmlns", 5);
951
0
    ctxt->str_xml_ns = xmlDictLookup(ctxt->dict, XML_XML_NAMESPACE, 36);
952
0
    if ((ctxt->str_xml==NULL) || (ctxt->str_xmlns==NULL) ||
953
0
    (ctxt->str_xml_ns == NULL)) {
954
0
        xmlErrMemory(ctxt);
955
0
    }
956
957
0
    xmlDictSetLimit(ctxt->dict,
958
0
                    (ctxt->options & XML_PARSE_HUGE) ?
959
0
                        0 :
960
0
                        XML_MAX_DICTIONARY_LIMIT);
961
962
0
#ifdef LIBXML_VALID_ENABLED
963
0
    if (ctxt->validate)
964
0
        ctxt->vctxt.flags |= XML_VCTXT_VALIDATE;
965
0
    else
966
0
        ctxt->vctxt.flags &= ~XML_VCTXT_VALIDATE;
967
0
#endif /* LIBXML_VALID_ENABLED */
968
0
}
969
970
typedef struct {
971
    xmlHashedString prefix;
972
    xmlHashedString name;
973
    xmlHashedString value;
974
    const xmlChar *valueEnd;
975
    int external;
976
    int expandedSize;
977
} xmlDefAttr;
978
979
typedef struct _xmlDefAttrs xmlDefAttrs;
980
typedef xmlDefAttrs *xmlDefAttrsPtr;
981
struct _xmlDefAttrs {
982
    int nbAttrs;  /* number of defaulted attributes on that element */
983
    int maxAttrs;       /* the size of the array */
984
#if __STDC_VERSION__ >= 199901L
985
    /* Using a C99 flexible array member avoids UBSan errors. */
986
    xmlDefAttr attrs[] ATTRIBUTE_COUNTED_BY(maxAttrs);
987
#else
988
    xmlDefAttr attrs[1];
989
#endif
990
};
991
992
/**
993
 * Normalize the space in non CDATA attribute values:
994
 * If the attribute type is not CDATA, then the XML processor MUST further
995
 * process the normalized attribute value by discarding any leading and
996
 * trailing space (\#x20) characters, and by replacing sequences of space
997
 * (\#x20) characters by a single space (\#x20) character.
998
 * Note that the size of dst need to be at least src, and if one doesn't need
999
 * to preserve dst (and it doesn't come from a dictionary or read-only) then
1000
 * passing src as dst is just fine.
1001
 *
1002
 * @param src  the source string
1003
 * @param dst  the target string
1004
 * @returns a pointer to the normalized value (dst) or NULL if no conversion
1005
 *         is needed.
1006
 */
1007
static xmlChar *
1008
xmlAttrNormalizeSpace(const xmlChar *src, xmlChar *dst)
1009
0
{
1010
0
    if ((src == NULL) || (dst == NULL))
1011
0
        return(NULL);
1012
1013
0
    while (*src == 0x20) src++;
1014
0
    while (*src != 0) {
1015
0
  if (*src == 0x20) {
1016
0
      while (*src == 0x20) src++;
1017
0
      if (*src != 0)
1018
0
    *dst++ = 0x20;
1019
0
  } else {
1020
0
      *dst++ = *src++;
1021
0
  }
1022
0
    }
1023
0
    *dst = 0;
1024
0
    if (dst == src)
1025
0
       return(NULL);
1026
0
    return(dst);
1027
0
}
1028
1029
/**
1030
 * Add a defaulted attribute for an element
1031
 *
1032
 * @param ctxt  an XML parser context
1033
 * @param fullname  the element fullname
1034
 * @param fullattr  the attribute fullname
1035
 * @param value  the attribute value
1036
 */
1037
static void
1038
xmlAddDefAttrs(xmlParserCtxtPtr ctxt,
1039
               const xmlChar *fullname,
1040
               const xmlChar *fullattr,
1041
0
               const xmlChar *value) {
1042
0
    xmlDefAttrsPtr defaults;
1043
0
    xmlDefAttr *attr;
1044
0
    int len, expandedSize;
1045
0
    xmlHashedString name;
1046
0
    xmlHashedString prefix;
1047
0
    xmlHashedString hvalue;
1048
0
    const xmlChar *localname;
1049
1050
    /*
1051
     * Allows to detect attribute redefinitions
1052
     */
1053
0
    if (ctxt->attsSpecial != NULL) {
1054
0
        if (xmlHashLookup2(ctxt->attsSpecial, fullname, fullattr) != NULL)
1055
0
      return;
1056
0
    }
1057
1058
0
    if (ctxt->attsDefault == NULL) {
1059
0
        ctxt->attsDefault = xmlHashCreateDict(10, ctxt->dict);
1060
0
  if (ctxt->attsDefault == NULL)
1061
0
      goto mem_error;
1062
0
    }
1063
1064
    /*
1065
     * split the element name into prefix:localname , the string found
1066
     * are within the DTD and then not associated to namespace names.
1067
     */
1068
0
    localname = xmlSplitQName3(fullname, &len);
1069
0
    if (localname == NULL) {
1070
0
        name = xmlDictLookupHashed(ctxt->dict, fullname, -1);
1071
0
  prefix.name = NULL;
1072
0
    } else {
1073
0
        name = xmlDictLookupHashed(ctxt->dict, localname, -1);
1074
0
  prefix = xmlDictLookupHashed(ctxt->dict, fullname, len);
1075
0
        if (prefix.name == NULL)
1076
0
            goto mem_error;
1077
0
    }
1078
0
    if (name.name == NULL)
1079
0
        goto mem_error;
1080
1081
    /*
1082
     * make sure there is some storage
1083
     */
1084
0
    defaults = xmlHashLookup2(ctxt->attsDefault, name.name, prefix.name);
1085
0
    if ((defaults == NULL) ||
1086
0
        (defaults->nbAttrs >= defaults->maxAttrs)) {
1087
0
        xmlDefAttrsPtr temp;
1088
0
        int newSize;
1089
1090
0
        if (defaults == NULL) {
1091
0
            newSize = 4;
1092
0
        } else {
1093
0
            if ((defaults->maxAttrs >= XML_MAX_ATTRS) ||
1094
0
                ((size_t) defaults->maxAttrs >
1095
0
                     SIZE_MAX / 2 / sizeof(temp[0]) - sizeof(*defaults)))
1096
0
                goto mem_error;
1097
1098
0
            if (defaults->maxAttrs > XML_MAX_ATTRS / 2)
1099
0
                newSize = XML_MAX_ATTRS;
1100
0
            else
1101
0
                newSize = defaults->maxAttrs * 2;
1102
0
        }
1103
0
        temp = xmlRealloc(defaults,
1104
0
                          sizeof(*defaults) + newSize * sizeof(xmlDefAttr));
1105
0
  if (temp == NULL)
1106
0
      goto mem_error;
1107
0
        if (defaults == NULL)
1108
0
            temp->nbAttrs = 0;
1109
0
  temp->maxAttrs = newSize;
1110
0
        defaults = temp;
1111
0
  if (xmlHashUpdateEntry2(ctxt->attsDefault, name.name, prefix.name,
1112
0
                          defaults, NULL) < 0) {
1113
0
      xmlFree(defaults);
1114
0
      goto mem_error;
1115
0
  }
1116
0
    }
1117
1118
    /*
1119
     * Split the attribute name into prefix:localname , the string found
1120
     * are within the DTD and hen not associated to namespace names.
1121
     */
1122
0
    localname = xmlSplitQName3(fullattr, &len);
1123
0
    if (localname == NULL) {
1124
0
        name = xmlDictLookupHashed(ctxt->dict, fullattr, -1);
1125
0
  prefix.name = NULL;
1126
0
    } else {
1127
0
        name = xmlDictLookupHashed(ctxt->dict, localname, -1);
1128
0
  prefix = xmlDictLookupHashed(ctxt->dict, fullattr, len);
1129
0
        if (prefix.name == NULL)
1130
0
            goto mem_error;
1131
0
    }
1132
0
    if (name.name == NULL)
1133
0
        goto mem_error;
1134
1135
    /* intern the string and precompute the end */
1136
0
    len = strlen((const char *) value);
1137
0
    hvalue = xmlDictLookupHashed(ctxt->dict, value, len);
1138
0
    if (hvalue.name == NULL)
1139
0
        goto mem_error;
1140
1141
0
    expandedSize = strlen((const char *) name.name);
1142
0
    if (prefix.name != NULL)
1143
0
        expandedSize += strlen((const char *) prefix.name);
1144
0
    expandedSize += len;
1145
1146
0
    attr = &defaults->attrs[defaults->nbAttrs++];
1147
0
    attr->name = name;
1148
0
    attr->prefix = prefix;
1149
0
    attr->value = hvalue;
1150
0
    attr->valueEnd = hvalue.name + len;
1151
0
    attr->external = PARSER_EXTERNAL(ctxt);
1152
0
    attr->expandedSize = expandedSize;
1153
1154
0
    return;
1155
1156
0
mem_error:
1157
0
    xmlErrMemory(ctxt);
1158
0
}
1159
1160
/**
1161
 * Register this attribute type
1162
 *
1163
 * @param ctxt  an XML parser context
1164
 * @param fullname  the element fullname
1165
 * @param fullattr  the attribute fullname
1166
 * @param type  the attribute type
1167
 */
1168
static void
1169
xmlAddSpecialAttr(xmlParserCtxtPtr ctxt,
1170
      const xmlChar *fullname,
1171
      const xmlChar *fullattr,
1172
      int type)
1173
0
{
1174
0
    if (ctxt->attsSpecial == NULL) {
1175
0
        ctxt->attsSpecial = xmlHashCreateDict(10, ctxt->dict);
1176
0
  if (ctxt->attsSpecial == NULL)
1177
0
      goto mem_error;
1178
0
    }
1179
1180
0
    if (PARSER_EXTERNAL(ctxt))
1181
0
        type |= XML_SPECIAL_EXTERNAL;
1182
1183
0
    if (xmlHashAdd2(ctxt->attsSpecial, fullname, fullattr,
1184
0
                    XML_INT_TO_PTR(type)) < 0)
1185
0
        goto mem_error;
1186
0
    return;
1187
1188
0
mem_error:
1189
0
    xmlErrMemory(ctxt);
1190
0
}
1191
1192
/**
1193
 * Removes CDATA attributes from the special attribute table
1194
 */
1195
static void
1196
xmlCleanSpecialAttrCallback(void *payload, void *data,
1197
                            const xmlChar *fullname, const xmlChar *fullattr,
1198
0
                            const xmlChar *unused ATTRIBUTE_UNUSED) {
1199
0
    xmlParserCtxtPtr ctxt = (xmlParserCtxtPtr) data;
1200
1201
0
    if (XML_PTR_TO_INT(payload) == XML_ATTRIBUTE_CDATA) {
1202
0
        xmlHashRemoveEntry2(ctxt->attsSpecial, fullname, fullattr, NULL);
1203
0
    }
1204
0
}
1205
1206
/**
1207
 * Trim the list of attributes defined to remove all those of type
1208
 * CDATA as they are not special. This call should be done when finishing
1209
 * to parse the DTD and before starting to parse the document root.
1210
 *
1211
 * @param ctxt  an XML parser context
1212
 */
1213
static void
1214
xmlCleanSpecialAttr(xmlParserCtxtPtr ctxt)
1215
0
{
1216
0
    if (ctxt->attsSpecial == NULL)
1217
0
        return;
1218
1219
0
    xmlHashScanFull(ctxt->attsSpecial, xmlCleanSpecialAttrCallback, ctxt);
1220
1221
0
    if (xmlHashSize(ctxt->attsSpecial) == 0) {
1222
0
        xmlHashFree(ctxt->attsSpecial, NULL);
1223
0
        ctxt->attsSpecial = NULL;
1224
0
    }
1225
0
}
1226
1227
/**
1228
 * Checks that the value conforms to the LanguageID production:
1229
 *
1230
 * @deprecated Internal function, do not use.
1231
 *
1232
 * NOTE: this is somewhat deprecated, those productions were removed from
1233
 * the XML Second edition.
1234
 *
1235
 *     [33] LanguageID ::= Langcode ('-' Subcode)*
1236
 *     [34] Langcode ::= ISO639Code |  IanaCode |  UserCode
1237
 *     [35] ISO639Code ::= ([a-z] | [A-Z]) ([a-z] | [A-Z])
1238
 *     [36] IanaCode ::= ('i' | 'I') '-' ([a-z] | [A-Z])+
1239
 *     [37] UserCode ::= ('x' | 'X') '-' ([a-z] | [A-Z])+
1240
 *     [38] Subcode ::= ([a-z] | [A-Z])+
1241
 *
1242
 * The current REC reference the successors of RFC 1766, currently 5646
1243
 *
1244
 * http://www.rfc-editor.org/rfc/rfc5646.txt
1245
 *
1246
 *     langtag       = language
1247
 *                     ["-" script]
1248
 *                     ["-" region]
1249
 *                     *("-" variant)
1250
 *                     *("-" extension)
1251
 *                     ["-" privateuse]
1252
 *     language      = 2*3ALPHA            ; shortest ISO 639 code
1253
 *                     ["-" extlang]       ; sometimes followed by
1254
 *                                         ; extended language subtags
1255
 *                   / 4ALPHA              ; or reserved for future use
1256
 *                   / 5*8ALPHA            ; or registered language subtag
1257
 *
1258
 *     extlang       = 3ALPHA              ; selected ISO 639 codes
1259
 *                     *2("-" 3ALPHA)      ; permanently reserved
1260
 *
1261
 *     script        = 4ALPHA              ; ISO 15924 code
1262
 *
1263
 *     region        = 2ALPHA              ; ISO 3166-1 code
1264
 *                   / 3DIGIT              ; UN M.49 code
1265
 *
1266
 *     variant       = 5*8alphanum         ; registered variants
1267
 *                   / (DIGIT 3alphanum)
1268
 *
1269
 *     extension     = singleton 1*("-" (2*8alphanum))
1270
 *
1271
 *                                         ; Single alphanumerics
1272
 *                                         ; "x" reserved for private use
1273
 *     singleton     = DIGIT               ; 0 - 9
1274
 *                   / %x41-57             ; A - W
1275
 *                   / %x59-5A             ; Y - Z
1276
 *                   / %x61-77             ; a - w
1277
 *                   / %x79-7A             ; y - z
1278
 *
1279
 * it sounds right to still allow Irregular i-xxx IANA and user codes too
1280
 * The parser below doesn't try to cope with extension or privateuse
1281
 * that could be added but that's not interoperable anyway
1282
 *
1283
 * @param lang  pointer to the string value
1284
 * @returns 1 if correct 0 otherwise
1285
 **/
1286
int
1287
xmlCheckLanguageID(const xmlChar * lang)
1288
0
{
1289
0
    const xmlChar *cur = lang, *nxt;
1290
1291
0
    if (cur == NULL)
1292
0
        return (0);
1293
0
    if (((cur[0] == 'i') && (cur[1] == '-')) ||
1294
0
        ((cur[0] == 'I') && (cur[1] == '-')) ||
1295
0
        ((cur[0] == 'x') && (cur[1] == '-')) ||
1296
0
        ((cur[0] == 'X') && (cur[1] == '-'))) {
1297
        /*
1298
         * Still allow IANA code and user code which were coming
1299
         * from the previous version of the XML-1.0 specification
1300
         * it's deprecated but we should not fail
1301
         */
1302
0
        cur += 2;
1303
0
        while (((cur[0] >= 'A') && (cur[0] <= 'Z')) ||
1304
0
               ((cur[0] >= 'a') && (cur[0] <= 'z')))
1305
0
            cur++;
1306
0
        return(cur[0] == 0);
1307
0
    }
1308
0
    nxt = cur;
1309
0
    while (((nxt[0] >= 'A') && (nxt[0] <= 'Z')) ||
1310
0
           ((nxt[0] >= 'a') && (nxt[0] <= 'z')))
1311
0
           nxt++;
1312
0
    if (nxt - cur >= 4) {
1313
        /*
1314
         * Reserved
1315
         */
1316
0
        if ((nxt - cur > 8) || (nxt[0] != 0))
1317
0
            return(0);
1318
0
        return(1);
1319
0
    }
1320
0
    if (nxt - cur < 2)
1321
0
        return(0);
1322
    /* we got an ISO 639 code */
1323
0
    if (nxt[0] == 0)
1324
0
        return(1);
1325
0
    if (nxt[0] != '-')
1326
0
        return(0);
1327
1328
0
    nxt++;
1329
0
    cur = nxt;
1330
    /* now we can have extlang or script or region or variant */
1331
0
    if ((nxt[0] >= '0') && (nxt[0] <= '9'))
1332
0
        goto region_m49;
1333
1334
0
    while (((nxt[0] >= 'A') && (nxt[0] <= 'Z')) ||
1335
0
           ((nxt[0] >= 'a') && (nxt[0] <= 'z')))
1336
0
           nxt++;
1337
0
    if (nxt - cur == 4)
1338
0
        goto script;
1339
0
    if (nxt - cur == 2)
1340
0
        goto region;
1341
0
    if ((nxt - cur >= 5) && (nxt - cur <= 8))
1342
0
        goto variant;
1343
0
    if (nxt - cur != 3)
1344
0
        return(0);
1345
    /* we parsed an extlang */
1346
0
    if (nxt[0] == 0)
1347
0
        return(1);
1348
0
    if (nxt[0] != '-')
1349
0
        return(0);
1350
1351
0
    nxt++;
1352
0
    cur = nxt;
1353
    /* now we can have script or region or variant */
1354
0
    if ((nxt[0] >= '0') && (nxt[0] <= '9'))
1355
0
        goto region_m49;
1356
1357
0
    while (((nxt[0] >= 'A') && (nxt[0] <= 'Z')) ||
1358
0
           ((nxt[0] >= 'a') && (nxt[0] <= 'z')))
1359
0
           nxt++;
1360
0
    if (nxt - cur == 2)
1361
0
        goto region;
1362
0
    if ((nxt - cur >= 5) && (nxt - cur <= 8))
1363
0
        goto variant;
1364
0
    if (nxt - cur != 4)
1365
0
        return(0);
1366
    /* we parsed a script */
1367
0
script:
1368
0
    if (nxt[0] == 0)
1369
0
        return(1);
1370
0
    if (nxt[0] != '-')
1371
0
        return(0);
1372
1373
0
    nxt++;
1374
0
    cur = nxt;
1375
    /* now we can have region or variant */
1376
0
    if ((nxt[0] >= '0') && (nxt[0] <= '9'))
1377
0
        goto region_m49;
1378
1379
0
    while (((nxt[0] >= 'A') && (nxt[0] <= 'Z')) ||
1380
0
           ((nxt[0] >= 'a') && (nxt[0] <= 'z')))
1381
0
           nxt++;
1382
1383
0
    if ((nxt - cur >= 5) && (nxt - cur <= 8))
1384
0
        goto variant;
1385
0
    if (nxt - cur != 2)
1386
0
        return(0);
1387
    /* we parsed a region */
1388
0
region:
1389
0
    if (nxt[0] == 0)
1390
0
        return(1);
1391
0
    if (nxt[0] != '-')
1392
0
        return(0);
1393
1394
0
    nxt++;
1395
0
    cur = nxt;
1396
    /* now we can just have a variant */
1397
0
    while (((nxt[0] >= 'A') && (nxt[0] <= 'Z')) ||
1398
0
           ((nxt[0] >= 'a') && (nxt[0] <= 'z')))
1399
0
           nxt++;
1400
1401
0
    if ((nxt - cur < 5) || (nxt - cur > 8))
1402
0
        return(0);
1403
1404
    /* we parsed a variant */
1405
0
variant:
1406
0
    if (nxt[0] == 0)
1407
0
        return(1);
1408
0
    if (nxt[0] != '-')
1409
0
        return(0);
1410
    /* extensions and private use subtags not checked */
1411
0
    return (1);
1412
1413
0
region_m49:
1414
0
    if (((nxt[1] >= '0') && (nxt[1] <= '9')) &&
1415
0
        ((nxt[2] >= '0') && (nxt[2] <= '9'))) {
1416
0
        nxt += 3;
1417
0
        goto region;
1418
0
    }
1419
0
    return(0);
1420
0
}
1421
1422
/************************************************************************
1423
 *                  *
1424
 *    Parser stacks related functions and macros    *
1425
 *                  *
1426
 ************************************************************************/
1427
1428
static xmlChar *
1429
xmlParseStringEntityRef(xmlParserCtxtPtr ctxt, const xmlChar **str);
1430
1431
/**
1432
 * Create a new namespace database.
1433
 *
1434
 * @returns the new obejct.
1435
 */
1436
xmlParserNsData *
1437
5.63k
xmlParserNsCreate(void) {
1438
5.63k
    xmlParserNsData *nsdb = xmlMalloc(sizeof(*nsdb));
1439
1440
5.63k
    if (nsdb == NULL)
1441
0
        return(NULL);
1442
5.63k
    memset(nsdb, 0, sizeof(*nsdb));
1443
5.63k
    nsdb->defaultNsIndex = INT_MAX;
1444
1445
5.63k
    return(nsdb);
1446
5.63k
}
1447
1448
/**
1449
 * Free a namespace database.
1450
 *
1451
 * @param nsdb  namespace database
1452
 */
1453
void
1454
5.63k
xmlParserNsFree(xmlParserNsData *nsdb) {
1455
5.63k
    if (nsdb == NULL)
1456
0
        return;
1457
1458
5.63k
    xmlFree(nsdb->extra);
1459
5.63k
    xmlFree(nsdb->hash);
1460
5.63k
    xmlFree(nsdb);
1461
5.63k
}
1462
1463
/**
1464
 * Reset a namespace database.
1465
 *
1466
 * @param nsdb  namespace database
1467
 */
1468
static void
1469
8.14k
xmlParserNsReset(xmlParserNsData *nsdb) {
1470
8.14k
    if (nsdb == NULL)
1471
1.47k
        return;
1472
1473
6.66k
    nsdb->hashElems = 0;
1474
6.66k
    nsdb->elementId = 0;
1475
6.66k
    nsdb->defaultNsIndex = INT_MAX;
1476
1477
6.66k
    if (nsdb->hash)
1478
0
        memset(nsdb->hash, 0, nsdb->hashSize * sizeof(nsdb->hash[0]));
1479
6.66k
}
1480
1481
/**
1482
 * Signal that a new element has started.
1483
 *
1484
 * @param nsdb  namespace database
1485
 * @returns 0 on success, -1 if the element counter overflowed.
1486
 */
1487
static int
1488
0
xmlParserNsStartElement(xmlParserNsData *nsdb) {
1489
0
    if (nsdb->elementId == UINT_MAX)
1490
0
        return(-1);
1491
0
    nsdb->elementId++;
1492
1493
0
    return(0);
1494
0
}
1495
1496
/**
1497
 * Lookup namespace with given prefix. If `bucketPtr` is non-NULL, it will
1498
 * be set to the matching bucket, or the first empty bucket if no match
1499
 * was found.
1500
 *
1501
 * @param ctxt  parser context
1502
 * @param prefix  namespace prefix
1503
 * @param bucketPtr  optional bucket (return value)
1504
 * @returns the namespace index on success, INT_MAX if no namespace was
1505
 * found.
1506
 */
1507
static int
1508
xmlParserNsLookup(xmlParserCtxtPtr ctxt, const xmlHashedString *prefix,
1509
0
                  xmlParserNsBucket **bucketPtr) {
1510
0
    xmlParserNsBucket *bucket, *tombstone;
1511
0
    unsigned index, hashValue;
1512
1513
0
    if (prefix->name == NULL)
1514
0
        return(ctxt->nsdb->defaultNsIndex);
1515
1516
0
    if (ctxt->nsdb->hashSize == 0)
1517
0
        return(INT_MAX);
1518
1519
0
    hashValue = prefix->hashValue;
1520
0
    index = hashValue & (ctxt->nsdb->hashSize - 1);
1521
0
    bucket = &ctxt->nsdb->hash[index];
1522
0
    tombstone = NULL;
1523
1524
0
    while (bucket->hashValue) {
1525
0
        if (bucket->index == INT_MAX) {
1526
0
            if (tombstone == NULL)
1527
0
                tombstone = bucket;
1528
0
        } else if (bucket->hashValue == hashValue) {
1529
0
            if (ctxt->nsTab[bucket->index * 2] == prefix->name) {
1530
0
                if (bucketPtr != NULL)
1531
0
                    *bucketPtr = bucket;
1532
0
                return(bucket->index);
1533
0
            }
1534
0
        }
1535
1536
0
        index++;
1537
0
        bucket++;
1538
0
        if (index == ctxt->nsdb->hashSize) {
1539
0
            index = 0;
1540
0
            bucket = ctxt->nsdb->hash;
1541
0
        }
1542
0
    }
1543
1544
0
    if (bucketPtr != NULL)
1545
0
        *bucketPtr = tombstone ? tombstone : bucket;
1546
0
    return(INT_MAX);
1547
0
}
1548
1549
/**
1550
 * Lookup namespace URI with given prefix.
1551
 *
1552
 * @param ctxt  parser context
1553
 * @param prefix  namespace prefix
1554
 * @returns the namespace URI on success, NULL if no namespace was found.
1555
 */
1556
static const xmlChar *
1557
0
xmlParserNsLookupUri(xmlParserCtxtPtr ctxt, const xmlHashedString *prefix) {
1558
0
    const xmlChar *ret;
1559
0
    int nsIndex;
1560
1561
0
    if (prefix->name == ctxt->str_xml)
1562
0
        return(ctxt->str_xml_ns);
1563
1564
    /*
1565
     * minNsIndex is used when building an entity tree. We must
1566
     * ignore namespaces declared outside the entity.
1567
     */
1568
0
    nsIndex = xmlParserNsLookup(ctxt, prefix, NULL);
1569
0
    if ((nsIndex == INT_MAX) || (nsIndex < ctxt->nsdb->minNsIndex))
1570
0
        return(NULL);
1571
1572
0
    ret = ctxt->nsTab[nsIndex * 2 + 1];
1573
0
    if (ret[0] == 0)
1574
0
        ret = NULL;
1575
0
    return(ret);
1576
0
}
1577
1578
/**
1579
 * Lookup extra data for the given prefix. This returns data stored
1580
 * with xmlParserNsUdpateSax.
1581
 *
1582
 * @param ctxt  parser context
1583
 * @param prefix  namespace prefix
1584
 * @returns the data on success, NULL if no namespace was found.
1585
 */
1586
void *
1587
0
xmlParserNsLookupSax(xmlParserCtxt *ctxt, const xmlChar *prefix) {
1588
0
    xmlHashedString hprefix;
1589
0
    int nsIndex;
1590
1591
0
    if (prefix == ctxt->str_xml)
1592
0
        return(NULL);
1593
1594
0
    hprefix.name = prefix;
1595
0
    if (prefix != NULL)
1596
0
        hprefix.hashValue = xmlDictComputeHash(ctxt->dict, prefix);
1597
0
    else
1598
0
        hprefix.hashValue = 0;
1599
0
    nsIndex = xmlParserNsLookup(ctxt, &hprefix, NULL);
1600
0
    if ((nsIndex == INT_MAX) || (nsIndex < ctxt->nsdb->minNsIndex))
1601
0
        return(NULL);
1602
1603
0
    return(ctxt->nsdb->extra[nsIndex].saxData);
1604
0
}
1605
1606
/**
1607
 * Sets or updates extra data for the given prefix. This value will be
1608
 * returned by xmlParserNsLookupSax as long as the namespace with the
1609
 * given prefix is in scope.
1610
 *
1611
 * @param ctxt  parser context
1612
 * @param prefix  namespace prefix
1613
 * @param saxData  extra data for SAX handler
1614
 * @returns the data on success, NULL if no namespace was found.
1615
 */
1616
int
1617
xmlParserNsUpdateSax(xmlParserCtxt *ctxt, const xmlChar *prefix,
1618
0
                     void *saxData) {
1619
0
    xmlHashedString hprefix;
1620
0
    int nsIndex;
1621
1622
0
    if (prefix == ctxt->str_xml)
1623
0
        return(-1);
1624
1625
0
    hprefix.name = prefix;
1626
0
    if (prefix != NULL)
1627
0
        hprefix.hashValue = xmlDictComputeHash(ctxt->dict, prefix);
1628
0
    else
1629
0
        hprefix.hashValue = 0;
1630
0
    nsIndex = xmlParserNsLookup(ctxt, &hprefix, NULL);
1631
0
    if ((nsIndex == INT_MAX) || (nsIndex < ctxt->nsdb->minNsIndex))
1632
0
        return(-1);
1633
1634
0
    ctxt->nsdb->extra[nsIndex].saxData = saxData;
1635
0
    return(0);
1636
0
}
1637
1638
/**
1639
 * Grows the namespace tables.
1640
 *
1641
 * @param ctxt  parser context
1642
 * @returns 0 on success, -1 if a memory allocation failed.
1643
 */
1644
static int
1645
0
xmlParserNsGrow(xmlParserCtxtPtr ctxt) {
1646
0
    const xmlChar **table;
1647
0
    xmlParserNsExtra *extra;
1648
0
    int newSize;
1649
1650
0
    newSize = xmlGrowCapacity(ctxt->nsMax,
1651
0
                              sizeof(table[0]) + sizeof(extra[0]),
1652
0
                              16, XML_MAX_ITEMS);
1653
0
    if (newSize < 0)
1654
0
        goto error;
1655
1656
0
    table = xmlRealloc(ctxt->nsTab, 2 * newSize * sizeof(table[0]));
1657
0
    if (table == NULL)
1658
0
        goto error;
1659
0
    ctxt->nsTab = table;
1660
1661
0
    extra = xmlRealloc(ctxt->nsdb->extra, newSize * sizeof(extra[0]));
1662
0
    if (extra == NULL)
1663
0
        goto error;
1664
0
    ctxt->nsdb->extra = extra;
1665
1666
0
    ctxt->nsMax = newSize;
1667
0
    return(0);
1668
1669
0
error:
1670
0
    xmlErrMemory(ctxt);
1671
0
    return(-1);
1672
0
}
1673
1674
/**
1675
 * Push a new namespace on the table.
1676
 *
1677
 * @param ctxt  parser context
1678
 * @param prefix  prefix with hash value
1679
 * @param uri  uri with hash value
1680
 * @param saxData  extra data for SAX handler
1681
 * @param defAttr  whether the namespace comes from a default attribute
1682
 * @returns 1 if the namespace was pushed, 0 if the namespace was ignored,
1683
 * -1 if a memory allocation failed.
1684
 */
1685
static int
1686
xmlParserNsPush(xmlParserCtxtPtr ctxt, const xmlHashedString *prefix,
1687
0
                const xmlHashedString *uri, void *saxData, int defAttr) {
1688
0
    xmlParserNsBucket *bucket = NULL;
1689
0
    xmlParserNsExtra *extra;
1690
0
    const xmlChar **ns;
1691
0
    unsigned hashValue, nsIndex, oldIndex;
1692
1693
0
    if ((prefix != NULL) && (prefix->name == ctxt->str_xml))
1694
0
        return(0);
1695
1696
0
    if ((ctxt->nsNr >= ctxt->nsMax) && (xmlParserNsGrow(ctxt) < 0)) {
1697
0
        xmlErrMemory(ctxt);
1698
0
        return(-1);
1699
0
    }
1700
1701
    /*
1702
     * Default namespace and 'xml' namespace
1703
     */
1704
0
    if ((prefix == NULL) || (prefix->name == NULL)) {
1705
0
        oldIndex = ctxt->nsdb->defaultNsIndex;
1706
1707
0
        if (oldIndex != INT_MAX) {
1708
0
            extra = &ctxt->nsdb->extra[oldIndex];
1709
1710
0
            if (extra->elementId == ctxt->nsdb->elementId) {
1711
0
                if (defAttr == 0)
1712
0
                    xmlErrAttributeDup(ctxt, NULL, BAD_CAST "xmlns");
1713
0
                return(0);
1714
0
            }
1715
1716
0
            if ((ctxt->options & XML_PARSE_NSCLEAN) &&
1717
0
                (uri->name == ctxt->nsTab[oldIndex * 2 + 1]))
1718
0
                return(0);
1719
0
        }
1720
1721
0
        ctxt->nsdb->defaultNsIndex = ctxt->nsNr;
1722
0
        goto populate_entry;
1723
0
    }
1724
1725
    /*
1726
     * Hash table lookup
1727
     */
1728
0
    oldIndex = xmlParserNsLookup(ctxt, prefix, &bucket);
1729
0
    if (oldIndex != INT_MAX) {
1730
0
        extra = &ctxt->nsdb->extra[oldIndex];
1731
1732
        /*
1733
         * Check for duplicate definitions on the same element.
1734
         */
1735
0
        if (extra->elementId == ctxt->nsdb->elementId) {
1736
0
            if (defAttr == 0)
1737
0
                xmlErrAttributeDup(ctxt, BAD_CAST "xmlns", prefix->name);
1738
0
            return(0);
1739
0
        }
1740
1741
0
        if ((ctxt->options & XML_PARSE_NSCLEAN) &&
1742
0
            (uri->name == ctxt->nsTab[bucket->index * 2 + 1]))
1743
0
            return(0);
1744
1745
0
        bucket->index = ctxt->nsNr;
1746
0
        goto populate_entry;
1747
0
    }
1748
1749
    /*
1750
     * Insert new bucket
1751
     */
1752
1753
0
    hashValue = prefix->hashValue;
1754
1755
    /*
1756
     * Grow hash table, 50% fill factor
1757
     */
1758
0
    if (ctxt->nsdb->hashElems + 1 > ctxt->nsdb->hashSize / 2) {
1759
0
        xmlParserNsBucket *newHash;
1760
0
        unsigned newSize, i, index;
1761
1762
0
        if (ctxt->nsdb->hashSize > UINT_MAX / 2) {
1763
0
            xmlErrMemory(ctxt);
1764
0
            return(-1);
1765
0
        }
1766
0
        newSize = ctxt->nsdb->hashSize ? ctxt->nsdb->hashSize * 2 : 16;
1767
0
        newHash = xmlMalloc(newSize * sizeof(newHash[0]));
1768
0
        if (newHash == NULL) {
1769
0
            xmlErrMemory(ctxt);
1770
0
            return(-1);
1771
0
        }
1772
0
        memset(newHash, 0, newSize * sizeof(newHash[0]));
1773
1774
0
        for (i = 0; i < ctxt->nsdb->hashSize; i++) {
1775
0
            unsigned hv = ctxt->nsdb->hash[i].hashValue;
1776
0
            unsigned newIndex;
1777
1778
0
            if ((hv == 0) || (ctxt->nsdb->hash[i].index == INT_MAX))
1779
0
                continue;
1780
0
            newIndex = hv & (newSize - 1);
1781
1782
0
            while (newHash[newIndex].hashValue != 0) {
1783
0
                newIndex++;
1784
0
                if (newIndex == newSize)
1785
0
                    newIndex = 0;
1786
0
            }
1787
1788
0
            newHash[newIndex] = ctxt->nsdb->hash[i];
1789
0
        }
1790
1791
0
        xmlFree(ctxt->nsdb->hash);
1792
0
        ctxt->nsdb->hash = newHash;
1793
0
        ctxt->nsdb->hashSize = newSize;
1794
1795
        /*
1796
         * Relookup
1797
         */
1798
0
        index = hashValue & (newSize - 1);
1799
1800
0
        while (newHash[index].hashValue != 0) {
1801
0
            index++;
1802
0
            if (index == newSize)
1803
0
                index = 0;
1804
0
        }
1805
1806
0
        bucket = &newHash[index];
1807
0
    }
1808
1809
0
    bucket->hashValue = hashValue;
1810
0
    bucket->index = ctxt->nsNr;
1811
0
    ctxt->nsdb->hashElems++;
1812
0
    oldIndex = INT_MAX;
1813
1814
0
populate_entry:
1815
0
    nsIndex = ctxt->nsNr;
1816
1817
0
    ns = &ctxt->nsTab[nsIndex * 2];
1818
0
    ns[0] = prefix ? prefix->name : NULL;
1819
0
    ns[1] = uri->name;
1820
1821
0
    extra = &ctxt->nsdb->extra[nsIndex];
1822
0
    extra->saxData = saxData;
1823
0
    extra->prefixHashValue = prefix ? prefix->hashValue : 0;
1824
0
    extra->uriHashValue = uri->hashValue;
1825
0
    extra->elementId = ctxt->nsdb->elementId;
1826
0
    extra->oldIndex = oldIndex;
1827
1828
0
    ctxt->nsNr++;
1829
1830
0
    return(1);
1831
0
}
1832
1833
/**
1834
 * Pops the top `nr` namespaces and restores the hash table.
1835
 *
1836
 * @param ctxt  an XML parser context
1837
 * @param nr  the number to pop
1838
 * @returns the number of namespaces popped.
1839
 */
1840
static int
1841
xmlParserNsPop(xmlParserCtxtPtr ctxt, int nr)
1842
0
{
1843
0
    int i;
1844
1845
    /* assert(nr <= ctxt->nsNr); */
1846
1847
0
    for (i = ctxt->nsNr - 1; i >= ctxt->nsNr - nr; i--) {
1848
0
        const xmlChar *prefix = ctxt->nsTab[i * 2];
1849
0
        xmlParserNsExtra *extra = &ctxt->nsdb->extra[i];
1850
1851
0
        if (prefix == NULL) {
1852
0
            ctxt->nsdb->defaultNsIndex = extra->oldIndex;
1853
0
        } else {
1854
0
            xmlHashedString hprefix;
1855
0
            xmlParserNsBucket *bucket = NULL;
1856
1857
0
            hprefix.name = prefix;
1858
0
            hprefix.hashValue = extra->prefixHashValue;
1859
0
            xmlParserNsLookup(ctxt, &hprefix, &bucket);
1860
            /* assert(bucket && bucket->hashValue); */
1861
0
            bucket->index = extra->oldIndex;
1862
0
        }
1863
0
    }
1864
1865
0
    ctxt->nsNr -= nr;
1866
0
    return(nr);
1867
0
}
1868
1869
static int
1870
0
xmlCtxtGrowAttrs(xmlParserCtxtPtr ctxt) {
1871
0
    const xmlChar **atts;
1872
0
    unsigned *attallocs;
1873
0
    int newSize;
1874
1875
0
    newSize = xmlGrowCapacity(ctxt->maxatts / 5,
1876
0
                              sizeof(atts[0]) * 5 + sizeof(attallocs[0]),
1877
0
                              10, XML_MAX_ATTRS);
1878
0
    if (newSize < 0) {
1879
0
        xmlFatalErr(ctxt, XML_ERR_RESOURCE_LIMIT,
1880
0
                    "Maximum number of attributes exceeded");
1881
0
        return(-1);
1882
0
    }
1883
1884
0
    atts = xmlRealloc(ctxt->atts, newSize * sizeof(atts[0]) * 5);
1885
0
    if (atts == NULL)
1886
0
        goto mem_error;
1887
0
    ctxt->atts = atts;
1888
1889
0
    attallocs = xmlRealloc(ctxt->attallocs,
1890
0
                           newSize * sizeof(attallocs[0]));
1891
0
    if (attallocs == NULL)
1892
0
        goto mem_error;
1893
0
    ctxt->attallocs = attallocs;
1894
1895
0
    ctxt->maxatts = newSize * 5;
1896
1897
0
    return(0);
1898
1899
0
mem_error:
1900
0
    xmlErrMemory(ctxt);
1901
0
    return(-1);
1902
0
}
1903
1904
/**
1905
 * Pushes a new parser input on top of the input stack
1906
 *
1907
 * @param ctxt  an XML parser context
1908
 * @param value  the parser input
1909
 * @returns -1 in case of error, the index in the stack otherwise
1910
 */
1911
int
1912
xmlCtxtPushInput(xmlParserCtxt *ctxt, xmlParserInput *value)
1913
0
{
1914
0
    char *directory = NULL;
1915
0
    int maxDepth;
1916
1917
0
    if ((ctxt == NULL) || (value == NULL))
1918
0
        return(-1);
1919
1920
0
    maxDepth = (ctxt->options & XML_PARSE_HUGE) ? 40 : 20;
1921
1922
0
    if (ctxt->inputNr >= ctxt->inputMax) {
1923
0
        xmlParserInputPtr *tmp;
1924
0
        int newSize;
1925
1926
0
        newSize = xmlGrowCapacity(ctxt->inputMax, sizeof(tmp[0]),
1927
0
                                  5, maxDepth);
1928
0
        if (newSize < 0) {
1929
0
            xmlFatalErrMsg(ctxt, XML_ERR_RESOURCE_LIMIT,
1930
0
                           "Maximum entity nesting depth exceeded");
1931
0
            xmlHaltParser(ctxt);
1932
0
            return(-1);
1933
0
        }
1934
0
        tmp = xmlRealloc(ctxt->inputTab, newSize * sizeof(tmp[0]));
1935
0
        if (tmp == NULL) {
1936
0
            xmlErrMemory(ctxt);
1937
0
            return(-1);
1938
0
        }
1939
0
        ctxt->inputTab = tmp;
1940
0
        ctxt->inputMax = newSize;
1941
0
    }
1942
1943
0
    if ((ctxt->inputNr == 0) && (value->filename != NULL)) {
1944
0
        directory = xmlParserGetDirectory(value->filename);
1945
0
        if (directory == NULL) {
1946
0
            xmlErrMemory(ctxt);
1947
0
            return(-1);
1948
0
        }
1949
0
    }
1950
1951
0
    if (ctxt->input_id >= INT_MAX) {
1952
0
        xmlFatalErrMsg(ctxt, XML_ERR_RESOURCE_LIMIT, "Input ID overflow\n");
1953
0
        return(-1);
1954
0
    }
1955
1956
0
    ctxt->inputTab[ctxt->inputNr] = value;
1957
0
    ctxt->input = value;
1958
1959
0
    if (ctxt->inputNr == 0) {
1960
0
        xmlFree(ctxt->directory);
1961
0
        ctxt->directory = directory;
1962
0
    }
1963
1964
    /*
1965
     * The input ID is unused internally, but there are entity
1966
     * loaders in downstream code that detect the main document
1967
     * by checking for "input_id == 1".
1968
     */
1969
0
    value->id = ctxt->input_id++;
1970
1971
0
    return(ctxt->inputNr++);
1972
0
}
1973
1974
/**
1975
 * Pops the top parser input from the input stack
1976
 *
1977
 * @param ctxt  an XML parser context
1978
 * @returns the input just removed
1979
 */
1980
xmlParserInput *
1981
xmlCtxtPopInput(xmlParserCtxt *ctxt)
1982
20.6k
{
1983
20.6k
    xmlParserInputPtr ret;
1984
1985
20.6k
    if (ctxt == NULL)
1986
0
        return(NULL);
1987
20.6k
    if (ctxt->inputNr <= 0)
1988
20.6k
        return (NULL);
1989
0
    ctxt->inputNr--;
1990
0
    if (ctxt->inputNr > 0)
1991
0
        ctxt->input = ctxt->inputTab[ctxt->inputNr - 1];
1992
0
    else
1993
0
        ctxt->input = NULL;
1994
0
    ret = ctxt->inputTab[ctxt->inputNr];
1995
0
    ctxt->inputTab[ctxt->inputNr] = NULL;
1996
0
    return (ret);
1997
20.6k
}
1998
1999
/**
2000
 * Pushes a new element node on top of the node stack
2001
 *
2002
 * @deprecated Internal function, do not use.
2003
 *
2004
 * @param ctxt  an XML parser context
2005
 * @param value  the element node
2006
 * @returns -1 in case of error, the index in the stack otherwise
2007
 */
2008
int
2009
nodePush(xmlParserCtxt *ctxt, xmlNode *value)
2010
0
{
2011
0
    if (ctxt == NULL)
2012
0
        return(0);
2013
2014
0
    if (ctxt->nodeNr >= ctxt->nodeMax) {
2015
0
        int maxDepth = (ctxt->options & XML_PARSE_HUGE) ? 2048 : 256;
2016
0
        xmlNodePtr *tmp;
2017
0
        int newSize;
2018
2019
0
        newSize = xmlGrowCapacity(ctxt->nodeMax, sizeof(tmp[0]),
2020
0
                                  10, maxDepth);
2021
0
        if (newSize < 0) {
2022
0
            xmlFatalErrMsgInt(ctxt, XML_ERR_RESOURCE_LIMIT,
2023
0
                    "Excessive depth in document: %d,"
2024
0
                    " use XML_PARSE_HUGE option\n",
2025
0
                    ctxt->nodeNr);
2026
0
            xmlHaltParser(ctxt);
2027
0
            return(-1);
2028
0
        }
2029
2030
0
  tmp = xmlRealloc(ctxt->nodeTab, newSize * sizeof(tmp[0]));
2031
0
        if (tmp == NULL) {
2032
0
            xmlErrMemory(ctxt);
2033
0
            return (-1);
2034
0
        }
2035
0
        ctxt->nodeTab = tmp;
2036
0
  ctxt->nodeMax = newSize;
2037
0
    }
2038
2039
0
    ctxt->nodeTab[ctxt->nodeNr] = value;
2040
0
    ctxt->node = value;
2041
0
    return (ctxt->nodeNr++);
2042
0
}
2043
2044
/**
2045
 * Pops the top element node from the node stack
2046
 *
2047
 * @deprecated Internal function, do not use.
2048
 *
2049
 * @param ctxt  an XML parser context
2050
 * @returns the node just removed
2051
 */
2052
xmlNode *
2053
nodePop(xmlParserCtxt *ctxt)
2054
0
{
2055
0
    xmlNodePtr ret;
2056
2057
0
    if (ctxt == NULL) return(NULL);
2058
0
    if (ctxt->nodeNr <= 0)
2059
0
        return (NULL);
2060
0
    ctxt->nodeNr--;
2061
0
    if (ctxt->nodeNr > 0)
2062
0
        ctxt->node = ctxt->nodeTab[ctxt->nodeNr - 1];
2063
0
    else
2064
0
        ctxt->node = NULL;
2065
0
    ret = ctxt->nodeTab[ctxt->nodeNr];
2066
0
    ctxt->nodeTab[ctxt->nodeNr] = NULL;
2067
0
    return (ret);
2068
0
}
2069
2070
/**
2071
 * Pushes a new element name/prefix/URL on top of the name stack
2072
 *
2073
 * @param ctxt  an XML parser context
2074
 * @param value  the element name
2075
 * @param prefix  the element prefix
2076
 * @param URI  the element namespace name
2077
 * @param line  the current line number for error messages
2078
 * @param nsNr  the number of namespaces pushed on the namespace table
2079
 * @returns -1 in case of error, the index in the stack otherwise
2080
 */
2081
static int
2082
nameNsPush(xmlParserCtxtPtr ctxt, const xmlChar * value,
2083
           const xmlChar *prefix, const xmlChar *URI, int line, int nsNr)
2084
0
{
2085
0
    xmlStartTag *tag;
2086
2087
0
    if (ctxt->nameNr >= ctxt->nameMax) {
2088
0
        const xmlChar **tmp;
2089
0
        xmlStartTag *tmp2;
2090
0
        int newSize;
2091
2092
0
        newSize = xmlGrowCapacity(ctxt->nameMax,
2093
0
                                  sizeof(tmp[0]) + sizeof(tmp2[0]),
2094
0
                                  10, XML_MAX_ITEMS);
2095
0
        if (newSize < 0)
2096
0
            goto mem_error;
2097
2098
0
        tmp = xmlRealloc(ctxt->nameTab, newSize * sizeof(tmp[0]));
2099
0
        if (tmp == NULL)
2100
0
      goto mem_error;
2101
0
  ctxt->nameTab = tmp;
2102
2103
0
        tmp2 = xmlRealloc(ctxt->pushTab, newSize * sizeof(tmp2[0]));
2104
0
        if (tmp2 == NULL)
2105
0
      goto mem_error;
2106
0
  ctxt->pushTab = tmp2;
2107
2108
0
        ctxt->nameMax = newSize;
2109
0
    } else if (ctxt->pushTab == NULL) {
2110
0
        ctxt->pushTab = xmlMalloc(ctxt->nameMax * sizeof(ctxt->pushTab[0]));
2111
0
        if (ctxt->pushTab == NULL)
2112
0
            goto mem_error;
2113
0
    }
2114
0
    ctxt->nameTab[ctxt->nameNr] = value;
2115
0
    ctxt->name = value;
2116
0
    tag = &ctxt->pushTab[ctxt->nameNr];
2117
0
    tag->prefix = prefix;
2118
0
    tag->URI = URI;
2119
0
    tag->line = line;
2120
0
    tag->nsNr = nsNr;
2121
0
    return (ctxt->nameNr++);
2122
0
mem_error:
2123
0
    xmlErrMemory(ctxt);
2124
0
    return (-1);
2125
0
}
2126
#ifdef LIBXML_PUSH_ENABLED
2127
/**
2128
 * Pops the top element/prefix/URI name from the name stack
2129
 *
2130
 * @param ctxt  an XML parser context
2131
 * @returns the name just removed
2132
 */
2133
static const xmlChar *
2134
nameNsPop(xmlParserCtxtPtr ctxt)
2135
0
{
2136
0
    const xmlChar *ret;
2137
2138
0
    if (ctxt->nameNr <= 0)
2139
0
        return (NULL);
2140
0
    ctxt->nameNr--;
2141
0
    if (ctxt->nameNr > 0)
2142
0
        ctxt->name = ctxt->nameTab[ctxt->nameNr - 1];
2143
0
    else
2144
0
        ctxt->name = NULL;
2145
0
    ret = ctxt->nameTab[ctxt->nameNr];
2146
0
    ctxt->nameTab[ctxt->nameNr] = NULL;
2147
0
    return (ret);
2148
0
}
2149
#endif /* LIBXML_PUSH_ENABLED */
2150
2151
/**
2152
 * Pops the top element name from the name stack
2153
 *
2154
 * @deprecated Internal function, do not use.
2155
 *
2156
 * @param ctxt  an XML parser context
2157
 * @returns the name just removed
2158
 */
2159
static const xmlChar *
2160
namePop(xmlParserCtxtPtr ctxt)
2161
0
{
2162
0
    const xmlChar *ret;
2163
2164
0
    if ((ctxt == NULL) || (ctxt->nameNr <= 0))
2165
0
        return (NULL);
2166
0
    ctxt->nameNr--;
2167
0
    if (ctxt->nameNr > 0)
2168
0
        ctxt->name = ctxt->nameTab[ctxt->nameNr - 1];
2169
0
    else
2170
0
        ctxt->name = NULL;
2171
0
    ret = ctxt->nameTab[ctxt->nameNr];
2172
0
    ctxt->nameTab[ctxt->nameNr] = NULL;
2173
0
    return (ret);
2174
0
}
2175
2176
0
static int spacePush(xmlParserCtxtPtr ctxt, int val) {
2177
0
    if (ctxt->spaceNr >= ctxt->spaceMax) {
2178
0
        int *tmp;
2179
0
        int newSize;
2180
2181
0
        newSize = xmlGrowCapacity(ctxt->spaceMax, sizeof(tmp[0]),
2182
0
                                  10, XML_MAX_ITEMS);
2183
0
        if (newSize < 0) {
2184
0
      xmlErrMemory(ctxt);
2185
0
      return(-1);
2186
0
        }
2187
2188
0
        tmp = xmlRealloc(ctxt->spaceTab, newSize * sizeof(tmp[0]));
2189
0
        if (tmp == NULL) {
2190
0
      xmlErrMemory(ctxt);
2191
0
      return(-1);
2192
0
  }
2193
0
  ctxt->spaceTab = tmp;
2194
2195
0
        ctxt->spaceMax = newSize;
2196
0
    }
2197
0
    ctxt->spaceTab[ctxt->spaceNr] = val;
2198
0
    ctxt->space = &ctxt->spaceTab[ctxt->spaceNr];
2199
0
    return(ctxt->spaceNr++);
2200
0
}
2201
2202
0
static int spacePop(xmlParserCtxtPtr ctxt) {
2203
0
    int ret;
2204
0
    if (ctxt->spaceNr <= 0) return(0);
2205
0
    ctxt->spaceNr--;
2206
0
    if (ctxt->spaceNr > 0)
2207
0
  ctxt->space = &ctxt->spaceTab[ctxt->spaceNr - 1];
2208
0
    else
2209
0
        ctxt->space = &ctxt->spaceTab[0];
2210
0
    ret = ctxt->spaceTab[ctxt->spaceNr];
2211
0
    ctxt->spaceTab[ctxt->spaceNr] = -1;
2212
0
    return(ret);
2213
0
}
2214
2215
/*
2216
 * Macros for accessing the content. Those should be used only by the parser,
2217
 * and not exported.
2218
 *
2219
 * Dirty macros, i.e. one often need to make assumption on the context to
2220
 * use them
2221
 *
2222
 *   CUR_PTR return the current pointer to the xmlChar to be parsed.
2223
 *           To be used with extreme caution since operations consuming
2224
 *           characters may move the input buffer to a different location !
2225
 *   CUR     returns the current xmlChar value, i.e. a 8 bit value if compiled
2226
 *           This should be used internally by the parser
2227
 *           only to compare to ASCII values otherwise it would break when
2228
 *           running with UTF-8 encoding.
2229
 *   RAW     same as CUR but in the input buffer, bypass any token
2230
 *           extraction that may have been done
2231
 *   NXT(n)  returns the n'th next xmlChar. Same as CUR is should be used only
2232
 *           to compare on ASCII based substring.
2233
 *   SKIP(n) Skip n xmlChar, and must also be used only to skip ASCII defined
2234
 *           strings without newlines within the parser.
2235
 *   NEXT1(l) Skip 1 xmlChar, and must also be used only to skip 1 non-newline ASCII
2236
 *           defined char within the parser.
2237
 * Clean macros, not dependent of an ASCII context, expect UTF-8 encoding
2238
 *
2239
 *   NEXT    Skip to the next character, this does the proper decoding
2240
 *           in UTF-8 mode. It also pop-up unfinished entities on the fly.
2241
 *   NEXTL(l) Skip the current unicode character of l xmlChars long.
2242
 *   COPY_BUF  copy the current unicode char to the target buffer, increment
2243
 *            the index
2244
 *   GROW, SHRINK  handling of input buffers
2245
 */
2246
2247
0
#define RAW (*ctxt->input->cur)
2248
0
#define CUR (*ctxt->input->cur)
2249
0
#define NXT(val) ctxt->input->cur[(val)]
2250
0
#define CUR_PTR ctxt->input->cur
2251
0
#define BASE_PTR ctxt->input->base
2252
2253
#define CMP4( s, c1, c2, c3, c4 ) \
2254
0
  ( ((unsigned char *) s)[ 0 ] == c1 && ((unsigned char *) s)[ 1 ] == c2 && \
2255
0
    ((unsigned char *) s)[ 2 ] == c3 && ((unsigned char *) s)[ 3 ] == c4 )
2256
#define CMP5( s, c1, c2, c3, c4, c5 ) \
2257
0
  ( CMP4( s, c1, c2, c3, c4 ) && ((unsigned char *) s)[ 4 ] == c5 )
2258
#define CMP6( s, c1, c2, c3, c4, c5, c6 ) \
2259
0
  ( CMP5( s, c1, c2, c3, c4, c5 ) && ((unsigned char *) s)[ 5 ] == c6 )
2260
#define CMP7( s, c1, c2, c3, c4, c5, c6, c7 ) \
2261
0
  ( CMP6( s, c1, c2, c3, c4, c5, c6 ) && ((unsigned char *) s)[ 6 ] == c7 )
2262
#define CMP8( s, c1, c2, c3, c4, c5, c6, c7, c8 ) \
2263
0
  ( CMP7( s, c1, c2, c3, c4, c5, c6, c7 ) && ((unsigned char *) s)[ 7 ] == c8 )
2264
#define CMP9( s, c1, c2, c3, c4, c5, c6, c7, c8, c9 ) \
2265
0
  ( CMP8( s, c1, c2, c3, c4, c5, c6, c7, c8 ) && \
2266
0
    ((unsigned char *) s)[ 8 ] == c9 )
2267
#define CMP10( s, c1, c2, c3, c4, c5, c6, c7, c8, c9, c10 ) \
2268
0
  ( CMP9( s, c1, c2, c3, c4, c5, c6, c7, c8, c9 ) && \
2269
0
    ((unsigned char *) s)[ 9 ] == c10 )
2270
2271
0
#define SKIP(val) do {             \
2272
0
    ctxt->input->cur += (val),ctxt->input->col+=(val);      \
2273
0
    if (*ctxt->input->cur == 0)           \
2274
0
        xmlParserGrow(ctxt);           \
2275
0
  } while (0)
2276
2277
#define SKIPL(val) do {             \
2278
    int skipl;                \
2279
    for(skipl=0; skipl<val; skipl++) {          \
2280
  if (*(ctxt->input->cur) == '\n') {        \
2281
  ctxt->input->line++; ctxt->input->col = 1;      \
2282
  } else ctxt->input->col++;          \
2283
  ctxt->input->cur++;           \
2284
    }                 \
2285
    if (*ctxt->input->cur == 0)           \
2286
        xmlParserGrow(ctxt);            \
2287
  } while (0)
2288
2289
#define SHRINK \
2290
0
    if (!PARSER_PROGRESSIVE(ctxt)) \
2291
0
  xmlParserShrink(ctxt);
2292
2293
#define GROW \
2294
0
    if ((!PARSER_PROGRESSIVE(ctxt)) && \
2295
0
        (ctxt->input->end - ctxt->input->cur < INPUT_CHUNK)) \
2296
0
  xmlParserGrow(ctxt);
2297
2298
0
#define SKIP_BLANKS xmlSkipBlankChars(ctxt)
2299
2300
0
#define SKIP_BLANKS_PE xmlSkipBlankCharsPE(ctxt)
2301
2302
0
#define NEXT xmlNextChar(ctxt)
2303
2304
0
#define NEXT1 {               \
2305
0
  ctxt->input->col++;           \
2306
0
  ctxt->input->cur++;           \
2307
0
  if (*ctxt->input->cur == 0)         \
2308
0
      xmlParserGrow(ctxt);           \
2309
0
    }
2310
2311
0
#define NEXTL(l) do {             \
2312
0
    if (*(ctxt->input->cur) == '\n') {         \
2313
0
  ctxt->input->line++; ctxt->input->col = 1;      \
2314
0
    } else ctxt->input->col++;           \
2315
0
    ctxt->input->cur += l;        \
2316
0
  } while (0)
2317
2318
#define COPY_BUF(b, i, v)           \
2319
0
    if (v < 0x80) b[i++] = v;           \
2320
0
    else i += xmlCopyCharMultiByte(&b[i],v)
2321
2322
static int
2323
0
xmlCurrentCharRecover(xmlParserCtxtPtr ctxt, int *len) {
2324
0
    int c = xmlCurrentChar(ctxt, len);
2325
2326
0
    if (c == XML_INVALID_CHAR)
2327
0
        c = 0xFFFD; /* replacement character */
2328
2329
0
    return(c);
2330
0
}
2331
2332
/**
2333
 * Skip whitespace in the input stream.
2334
 *
2335
 * @deprecated Internal function, do not use.
2336
 *
2337
 * @param ctxt  the XML parser context
2338
 * @returns the number of space chars skipped
2339
 */
2340
int
2341
0
xmlSkipBlankChars(xmlParserCtxt *ctxt) {
2342
0
    const xmlChar *cur;
2343
0
    int res = 0;
2344
2345
0
    cur = ctxt->input->cur;
2346
0
    while (IS_BLANK_CH(*cur)) {
2347
0
        if (*cur == '\n') {
2348
0
            ctxt->input->line++; ctxt->input->col = 1;
2349
0
        } else {
2350
0
            ctxt->input->col++;
2351
0
        }
2352
0
        cur++;
2353
0
        if (res < INT_MAX)
2354
0
            res++;
2355
0
        if (*cur == 0) {
2356
0
            ctxt->input->cur = cur;
2357
0
            xmlParserGrow(ctxt);
2358
0
            cur = ctxt->input->cur;
2359
0
        }
2360
0
    }
2361
0
    ctxt->input->cur = cur;
2362
2363
0
    if (res > 4)
2364
0
        GROW;
2365
2366
0
    return(res);
2367
0
}
2368
2369
static void
2370
0
xmlPopPE(xmlParserCtxtPtr ctxt) {
2371
0
    unsigned long consumed;
2372
0
    xmlEntityPtr ent;
2373
2374
0
    ent = ctxt->input->entity;
2375
2376
0
    ent->flags &= ~XML_ENT_EXPANDING;
2377
2378
0
    if ((ent->flags & XML_ENT_CHECKED) == 0) {
2379
0
        int result;
2380
2381
        /*
2382
         * Read the rest of the stream in case of errors. We want
2383
         * to account for the whole entity size.
2384
         */
2385
0
        do {
2386
0
            ctxt->input->cur = ctxt->input->end;
2387
0
            xmlParserShrink(ctxt);
2388
0
            result = xmlParserGrow(ctxt);
2389
0
        } while (result > 0);
2390
2391
0
        consumed = ctxt->input->consumed;
2392
0
        xmlSaturatedAddSizeT(&consumed,
2393
0
                             ctxt->input->end - ctxt->input->base);
2394
2395
0
        xmlSaturatedAdd(&ent->expandedSize, consumed);
2396
2397
        /*
2398
         * Add to sizeentities when parsing an external entity
2399
         * for the first time.
2400
         */
2401
0
        if (ent->etype == XML_EXTERNAL_PARAMETER_ENTITY) {
2402
0
            xmlSaturatedAdd(&ctxt->sizeentities, consumed);
2403
0
        }
2404
2405
0
        ent->flags |= XML_ENT_CHECKED;
2406
0
    }
2407
2408
0
    xmlFreeInputStream(xmlCtxtPopInput(ctxt));
2409
2410
0
    xmlParserEntityCheck(ctxt, ent->expandedSize);
2411
2412
0
    GROW;
2413
0
}
2414
2415
/**
2416
 * Skip whitespace in the input stream, also handling parameter
2417
 * entities.
2418
 *
2419
 * @param ctxt  the XML parser context
2420
 * @returns the number of space chars skipped
2421
 */
2422
static int
2423
0
xmlSkipBlankCharsPE(xmlParserCtxtPtr ctxt) {
2424
0
    int res = 0;
2425
0
    int inParam;
2426
0
    int expandParam;
2427
2428
0
    inParam = PARSER_IN_PE(ctxt);
2429
0
    expandParam = PARSER_EXTERNAL(ctxt);
2430
2431
0
    if (!inParam && !expandParam)
2432
0
        return(xmlSkipBlankChars(ctxt));
2433
2434
    /*
2435
     * It's Okay to use CUR/NEXT here since all the blanks are on
2436
     * the ASCII range.
2437
     */
2438
0
    while (PARSER_STOPPED(ctxt) == 0) {
2439
0
        if (IS_BLANK_CH(CUR)) { /* CHECKED tstblanks.xml */
2440
0
            NEXT;
2441
0
        } else if (CUR == '%') {
2442
0
            if ((expandParam == 0) ||
2443
0
                (IS_BLANK_CH(NXT(1))) || (NXT(1) == 0))
2444
0
                break;
2445
2446
            /*
2447
             * Expand parameter entity. We continue to consume
2448
             * whitespace at the start of the entity and possible
2449
             * even consume the whole entity and pop it. We might
2450
             * even pop multiple PEs in this loop.
2451
             */
2452
0
            xmlParsePERefInternal(ctxt, 0);
2453
2454
0
            inParam = PARSER_IN_PE(ctxt);
2455
0
            expandParam = PARSER_EXTERNAL(ctxt);
2456
0
        } else if (CUR == 0) {
2457
0
            if (inParam == 0)
2458
0
                break;
2459
2460
            /*
2461
             * Don't pop parameter entities that start a markup
2462
             * declaration to detect Well-formedness constraint:
2463
             * PE Between Declarations.
2464
             */
2465
0
            if (ctxt->input->flags & XML_INPUT_MARKUP_DECL)
2466
0
                break;
2467
2468
0
            xmlPopPE(ctxt);
2469
2470
0
            inParam = PARSER_IN_PE(ctxt);
2471
0
            expandParam = PARSER_EXTERNAL(ctxt);
2472
0
        } else {
2473
0
            break;
2474
0
        }
2475
2476
        /*
2477
         * Also increase the counter when entering or exiting a PERef.
2478
         * The spec says: "When a parameter-entity reference is recognized
2479
         * in the DTD and included, its replacement text MUST be enlarged
2480
         * by the attachment of one leading and one following space (#x20)
2481
         * character."
2482
         */
2483
0
        if (res < INT_MAX)
2484
0
            res++;
2485
0
    }
2486
2487
0
    return(res);
2488
0
}
2489
2490
/************************************************************************
2491
 *                  *
2492
 *    Commodity functions to handle entities      *
2493
 *                  *
2494
 ************************************************************************/
2495
2496
/**
2497
 * @deprecated Internal function, don't use.
2498
 *
2499
 * @param ctxt  an XML parser context
2500
 * @returns the current xmlChar in the parser context
2501
 */
2502
xmlChar
2503
0
xmlPopInput(xmlParserCtxt *ctxt) {
2504
0
    xmlParserInputPtr input;
2505
2506
0
    if ((ctxt == NULL) || (ctxt->inputNr <= 1)) return(0);
2507
0
    input = xmlCtxtPopInput(ctxt);
2508
0
    xmlFreeInputStream(input);
2509
0
    if (*ctxt->input->cur == 0)
2510
0
        xmlParserGrow(ctxt);
2511
0
    return(CUR);
2512
0
}
2513
2514
/**
2515
 * Push an input stream onto the stack.
2516
 *
2517
 * @deprecated Internal function, don't use.
2518
 *
2519
 * @param ctxt  an XML parser context
2520
 * @param input  an XML parser input fragment (entity, XML fragment ...).
2521
 * @returns -1 in case of error or the index in the input stack
2522
 */
2523
int
2524
0
xmlPushInput(xmlParserCtxt *ctxt, xmlParserInput *input) {
2525
0
    int ret;
2526
2527
0
    if ((ctxt == NULL) || (input == NULL))
2528
0
        return(-1);
2529
2530
0
    ret = xmlCtxtPushInput(ctxt, input);
2531
0
    if (ret >= 0)
2532
0
        GROW;
2533
0
    return(ret);
2534
0
}
2535
2536
/**
2537
 * Parse a numeric character reference. Always consumes '&'.
2538
 *
2539
 * @deprecated Internal function, don't use.
2540
 *
2541
 *     [66] CharRef ::= '&#' [0-9]+ ';' |
2542
 *                      '&#x' [0-9a-fA-F]+ ';'
2543
 *
2544
 * [ WFC: Legal Character ]
2545
 * Characters referred to using character references must match the
2546
 * production for Char.
2547
 *
2548
 * @param ctxt  an XML parser context
2549
 * @returns the value parsed (as an int), 0 in case of error
2550
 */
2551
int
2552
0
xmlParseCharRef(xmlParserCtxt *ctxt) {
2553
0
    int val = 0;
2554
0
    int count = 0;
2555
2556
    /*
2557
     * Using RAW/CUR/NEXT is okay since we are working on ASCII range here
2558
     */
2559
0
    if ((RAW == '&') && (NXT(1) == '#') &&
2560
0
        (NXT(2) == 'x')) {
2561
0
  SKIP(3);
2562
0
  GROW;
2563
0
  while ((RAW != ';') && (PARSER_STOPPED(ctxt) == 0)) {
2564
0
      if (count++ > 20) {
2565
0
    count = 0;
2566
0
    GROW;
2567
0
      }
2568
0
      if ((RAW >= '0') && (RAW <= '9'))
2569
0
          val = val * 16 + (CUR - '0');
2570
0
      else if ((RAW >= 'a') && (RAW <= 'f') && (count < 20))
2571
0
          val = val * 16 + (CUR - 'a') + 10;
2572
0
      else if ((RAW >= 'A') && (RAW <= 'F') && (count < 20))
2573
0
          val = val * 16 + (CUR - 'A') + 10;
2574
0
      else {
2575
0
    xmlFatalErr(ctxt, XML_ERR_INVALID_HEX_CHARREF, NULL);
2576
0
    val = 0;
2577
0
    break;
2578
0
      }
2579
0
      if (val > 0x110000)
2580
0
          val = 0x110000;
2581
2582
0
      NEXT;
2583
0
      count++;
2584
0
  }
2585
0
  if (RAW == ';') {
2586
      /* on purpose to avoid reentrancy problems with NEXT and SKIP */
2587
0
      ctxt->input->col++;
2588
0
      ctxt->input->cur++;
2589
0
  }
2590
0
    } else if  ((RAW == '&') && (NXT(1) == '#')) {
2591
0
  SKIP(2);
2592
0
  GROW;
2593
0
  while (RAW != ';') { /* loop blocked by count */
2594
0
      if (count++ > 20) {
2595
0
    count = 0;
2596
0
    GROW;
2597
0
      }
2598
0
      if ((RAW >= '0') && (RAW <= '9'))
2599
0
          val = val * 10 + (CUR - '0');
2600
0
      else {
2601
0
    xmlFatalErr(ctxt, XML_ERR_INVALID_DEC_CHARREF, NULL);
2602
0
    val = 0;
2603
0
    break;
2604
0
      }
2605
0
      if (val > 0x110000)
2606
0
          val = 0x110000;
2607
2608
0
      NEXT;
2609
0
      count++;
2610
0
  }
2611
0
  if (RAW == ';') {
2612
      /* on purpose to avoid reentrancy problems with NEXT and SKIP */
2613
0
      ctxt->input->col++;
2614
0
      ctxt->input->cur++;
2615
0
  }
2616
0
    } else {
2617
0
        if (RAW == '&')
2618
0
            SKIP(1);
2619
0
        xmlFatalErr(ctxt, XML_ERR_INVALID_CHARREF, NULL);
2620
0
    }
2621
2622
    /*
2623
     * [ WFC: Legal Character ]
2624
     * Characters referred to using character references must match the
2625
     * production for Char.
2626
     */
2627
0
    if (val >= 0x110000) {
2628
0
        xmlFatalErrMsgInt(ctxt, XML_ERR_INVALID_CHAR,
2629
0
                "xmlParseCharRef: character reference out of bounds\n",
2630
0
          val);
2631
0
    } else if (IS_CHAR(val)) {
2632
0
        return(val);
2633
0
    } else {
2634
0
        xmlFatalErrMsgInt(ctxt, XML_ERR_INVALID_CHAR,
2635
0
                          "xmlParseCharRef: invalid xmlChar value %d\n",
2636
0
                    val);
2637
0
    }
2638
0
    return(0);
2639
0
}
2640
2641
/**
2642
 * parse Reference declarations, variant parsing from a string rather
2643
 * than an an input flow.
2644
 *
2645
 *     [66] CharRef ::= '&#' [0-9]+ ';' |
2646
 *                      '&#x' [0-9a-fA-F]+ ';'
2647
 *
2648
 * [ WFC: Legal Character ]
2649
 * Characters referred to using character references must match the
2650
 * production for Char.
2651
 *
2652
 * @param ctxt  an XML parser context
2653
 * @param str  a pointer to an index in the string
2654
 * @returns the value parsed (as an int), 0 in case of error, str will be
2655
 *         updated to the current value of the index
2656
 */
2657
static int
2658
0
xmlParseStringCharRef(xmlParserCtxtPtr ctxt, const xmlChar **str) {
2659
0
    const xmlChar *ptr;
2660
0
    xmlChar cur;
2661
0
    int val = 0;
2662
2663
0
    if ((str == NULL) || (*str == NULL)) return(0);
2664
0
    ptr = *str;
2665
0
    cur = *ptr;
2666
0
    if ((cur == '&') && (ptr[1] == '#') && (ptr[2] == 'x')) {
2667
0
  ptr += 3;
2668
0
  cur = *ptr;
2669
0
  while (cur != ';') { /* Non input consuming loop */
2670
0
      if ((cur >= '0') && (cur <= '9'))
2671
0
          val = val * 16 + (cur - '0');
2672
0
      else if ((cur >= 'a') && (cur <= 'f'))
2673
0
          val = val * 16 + (cur - 'a') + 10;
2674
0
      else if ((cur >= 'A') && (cur <= 'F'))
2675
0
          val = val * 16 + (cur - 'A') + 10;
2676
0
      else {
2677
0
    xmlFatalErr(ctxt, XML_ERR_INVALID_HEX_CHARREF, NULL);
2678
0
    val = 0;
2679
0
    break;
2680
0
      }
2681
0
      if (val > 0x110000)
2682
0
          val = 0x110000;
2683
2684
0
      ptr++;
2685
0
      cur = *ptr;
2686
0
  }
2687
0
  if (cur == ';')
2688
0
      ptr++;
2689
0
    } else if  ((cur == '&') && (ptr[1] == '#')){
2690
0
  ptr += 2;
2691
0
  cur = *ptr;
2692
0
  while (cur != ';') { /* Non input consuming loops */
2693
0
      if ((cur >= '0') && (cur <= '9'))
2694
0
          val = val * 10 + (cur - '0');
2695
0
      else {
2696
0
    xmlFatalErr(ctxt, XML_ERR_INVALID_DEC_CHARREF, NULL);
2697
0
    val = 0;
2698
0
    break;
2699
0
      }
2700
0
      if (val > 0x110000)
2701
0
          val = 0x110000;
2702
2703
0
      ptr++;
2704
0
      cur = *ptr;
2705
0
  }
2706
0
  if (cur == ';')
2707
0
      ptr++;
2708
0
    } else {
2709
0
  xmlFatalErr(ctxt, XML_ERR_INVALID_CHARREF, NULL);
2710
0
  return(0);
2711
0
    }
2712
0
    *str = ptr;
2713
2714
    /*
2715
     * [ WFC: Legal Character ]
2716
     * Characters referred to using character references must match the
2717
     * production for Char.
2718
     */
2719
0
    if (val >= 0x110000) {
2720
0
        xmlFatalErrMsgInt(ctxt, XML_ERR_INVALID_CHAR,
2721
0
                "xmlParseStringCharRef: character reference out of bounds\n",
2722
0
                val);
2723
0
    } else if (IS_CHAR(val)) {
2724
0
        return(val);
2725
0
    } else {
2726
0
        xmlFatalErrMsgInt(ctxt, XML_ERR_INVALID_CHAR,
2727
0
        "xmlParseStringCharRef: invalid xmlChar value %d\n",
2728
0
        val);
2729
0
    }
2730
0
    return(0);
2731
0
}
2732
2733
/**
2734
 *     [69] PEReference ::= '%' Name ';'
2735
 *
2736
 * @deprecated Internal function, do not use.
2737
 *
2738
 * [ WFC: No Recursion ]
2739
 * A parsed entity must not contain a recursive
2740
 * reference to itself, either directly or indirectly.
2741
 *
2742
 * [ WFC: Entity Declared ]
2743
 * In a document without any DTD, a document with only an internal DTD
2744
 * subset which contains no parameter entity references, or a document
2745
 * with "standalone='yes'", ...  ... The declaration of a parameter
2746
 * entity must precede any reference to it...
2747
 *
2748
 * [ VC: Entity Declared ]
2749
 * In a document with an external subset or external parameter entities
2750
 * with "standalone='no'", ...  ... The declaration of a parameter entity
2751
 * must precede any reference to it...
2752
 *
2753
 * [ WFC: In DTD ]
2754
 * Parameter-entity references may only appear in the DTD.
2755
 * NOTE: misleading but this is handled.
2756
 *
2757
 * A PEReference may have been detected in the current input stream
2758
 * the handling is done accordingly to
2759
 *      http://www.w3.org/TR/REC-xml#entproc
2760
 * i.e.
2761
 *   - Included in literal in entity values
2762
 *   - Included as Parameter Entity reference within DTDs
2763
 * @param ctxt  the parser context
2764
 */
2765
void
2766
0
xmlParserHandlePEReference(xmlParserCtxt *ctxt) {
2767
0
    xmlParsePERefInternal(ctxt, 0);
2768
0
}
2769
2770
/**
2771
 * @deprecated Internal function, don't use.
2772
 *
2773
 * @param ctxt  the parser context
2774
 * @param str  the input string
2775
 * @param len  the string length
2776
 * @param what  combination of XML_SUBSTITUTE_REF and XML_SUBSTITUTE_PEREF
2777
 * @param end  an end marker xmlChar, 0 if none
2778
 * @param end2  an end marker xmlChar, 0 if none
2779
 * @param end3  an end marker xmlChar, 0 if none
2780
 * @returns A newly allocated string with the substitution done. The caller
2781
 *      must deallocate it !
2782
 */
2783
xmlChar *
2784
xmlStringLenDecodeEntities(xmlParserCtxt *ctxt, const xmlChar *str, int len,
2785
                           int what ATTRIBUTE_UNUSED,
2786
0
                           xmlChar end, xmlChar end2, xmlChar end3) {
2787
0
    if ((ctxt == NULL) || (str == NULL) || (len < 0))
2788
0
        return(NULL);
2789
2790
0
    if ((str[len] != 0) ||
2791
0
        (end != 0) || (end2 != 0) || (end3 != 0))
2792
0
        return(NULL);
2793
2794
0
    return(xmlExpandEntitiesInAttValue(ctxt, str, 0));
2795
0
}
2796
2797
/**
2798
 * @deprecated Internal function, don't use.
2799
 *
2800
 * @param ctxt  the parser context
2801
 * @param str  the input string
2802
 * @param what  combination of XML_SUBSTITUTE_REF and XML_SUBSTITUTE_PEREF
2803
 * @param end  an end marker xmlChar, 0 if none
2804
 * @param end2  an end marker xmlChar, 0 if none
2805
 * @param end3  an end marker xmlChar, 0 if none
2806
 * @returns A newly allocated string with the substitution done. The caller
2807
 *      must deallocate it !
2808
 */
2809
xmlChar *
2810
xmlStringDecodeEntities(xmlParserCtxt *ctxt, const xmlChar *str,
2811
                        int what ATTRIBUTE_UNUSED,
2812
0
            xmlChar end, xmlChar  end2, xmlChar end3) {
2813
0
    if ((ctxt == NULL) || (str == NULL))
2814
0
        return(NULL);
2815
2816
0
    if ((end != 0) || (end2 != 0) || (end3 != 0))
2817
0
        return(NULL);
2818
2819
0
    return(xmlExpandEntitiesInAttValue(ctxt, str, 0));
2820
0
}
2821
2822
/************************************************************************
2823
 *                  *
2824
 *    Commodity functions, cleanup needed ?     *
2825
 *                  *
2826
 ************************************************************************/
2827
2828
/**
2829
 * Is this a sequence of blank chars that one can ignore ?
2830
 *
2831
 * @param ctxt  an XML parser context
2832
 * @param str  a xmlChar *
2833
 * @param len  the size of `str`
2834
 * @param blank_chars  we know the chars are blanks
2835
 * @returns 1 if ignorable 0 otherwise.
2836
 */
2837
2838
static int areBlanks(xmlParserCtxtPtr ctxt, const xmlChar *str, int len,
2839
0
                     int blank_chars) {
2840
0
    int i;
2841
0
    xmlNodePtr lastChild;
2842
2843
    /*
2844
     * Check for xml:space value.
2845
     */
2846
0
    if ((ctxt->space == NULL) || (*(ctxt->space) == 1) ||
2847
0
        (*(ctxt->space) == -2))
2848
0
  return(0);
2849
2850
    /*
2851
     * Check that the string is made of blanks
2852
     */
2853
0
    if (blank_chars == 0) {
2854
0
  for (i = 0;i < len;i++)
2855
0
      if (!(IS_BLANK_CH(str[i]))) return(0);
2856
0
    }
2857
2858
    /*
2859
     * Look if the element is mixed content in the DTD if available
2860
     */
2861
0
    if (ctxt->node == NULL) return(0);
2862
0
    if (ctxt->myDoc != NULL) {
2863
0
        xmlElementPtr elemDecl = NULL;
2864
0
        xmlDocPtr doc = ctxt->myDoc;
2865
0
        const xmlChar *prefix = NULL;
2866
2867
0
        if (ctxt->node->ns)
2868
0
            prefix = ctxt->node->ns->prefix;
2869
0
        if (doc->intSubset != NULL)
2870
0
            elemDecl = xmlHashLookup2(doc->intSubset->elements, ctxt->node->name,
2871
0
                                      prefix);
2872
0
        if ((elemDecl == NULL) && (doc->extSubset != NULL))
2873
0
            elemDecl = xmlHashLookup2(doc->extSubset->elements, ctxt->node->name,
2874
0
                                      prefix);
2875
0
        if (elemDecl != NULL) {
2876
0
            if (elemDecl->etype == XML_ELEMENT_TYPE_ELEMENT)
2877
0
                return(1);
2878
0
            if ((elemDecl->etype == XML_ELEMENT_TYPE_ANY) ||
2879
0
                (elemDecl->etype == XML_ELEMENT_TYPE_MIXED))
2880
0
                return(0);
2881
0
        }
2882
0
    }
2883
2884
    /*
2885
     * Otherwise, heuristic :-\
2886
     *
2887
     * When push parsing, we could be at the end of a chunk.
2888
     * This makes the look-ahead and consequently the NOBLANKS
2889
     * option unreliable.
2890
     */
2891
0
    if ((RAW != '<') && (RAW != 0xD)) return(0);
2892
0
    if ((ctxt->node->children == NULL) &&
2893
0
  (RAW == '<') && (NXT(1) == '/')) return(0);
2894
2895
0
    lastChild = xmlGetLastChild(ctxt->node);
2896
0
    if (lastChild == NULL) {
2897
0
        if ((ctxt->node->type != XML_ELEMENT_NODE) &&
2898
0
            (ctxt->node->content != NULL)) return(0);
2899
0
    } else if (xmlNodeIsText(lastChild))
2900
0
        return(0);
2901
0
    else if ((ctxt->node->children != NULL) &&
2902
0
             (xmlNodeIsText(ctxt->node->children)))
2903
0
        return(0);
2904
0
    return(1);
2905
0
}
2906
2907
/************************************************************************
2908
 *                  *
2909
 *    Extra stuff for namespace support     *
2910
 *  Relates to http://www.w3.org/TR/WD-xml-names      *
2911
 *                  *
2912
 ************************************************************************/
2913
2914
/**
2915
 * parse an UTF8 encoded XML qualified name string
2916
 *
2917
 * @deprecated Don't use.
2918
 *
2919
 * @param ctxt  an XML parser context
2920
 * @param name  an XML parser context
2921
 * @param prefixOut  a xmlChar **
2922
 * @returns the local part, and prefix is updated
2923
 *   to get the Prefix if any.
2924
 */
2925
2926
xmlChar *
2927
0
xmlSplitQName(xmlParserCtxt *ctxt, const xmlChar *name, xmlChar **prefixOut) {
2928
0
    xmlChar *ret;
2929
0
    const xmlChar *localname;
2930
2931
0
    localname = xmlSplitQName4(name, prefixOut);
2932
0
    if (localname == NULL) {
2933
0
        xmlCtxtErrMemory(ctxt);
2934
0
        return(NULL);
2935
0
    }
2936
2937
0
    ret = xmlStrdup(localname);
2938
0
    if (ret == NULL) {
2939
0
        xmlCtxtErrMemory(ctxt);
2940
0
        xmlFree(*prefixOut);
2941
0
    }
2942
2943
0
    return(ret);
2944
0
}
2945
2946
/************************************************************************
2947
 *                  *
2948
 *      The parser itself       *
2949
 *  Relates to http://www.w3.org/TR/REC-xml       *
2950
 *                  *
2951
 ************************************************************************/
2952
2953
/************************************************************************
2954
 *                  *
2955
 *  Routines to parse Name, NCName and NmToken      *
2956
 *                  *
2957
 ************************************************************************/
2958
2959
/*
2960
 * The two following functions are related to the change of accepted
2961
 * characters for Name and NmToken in the Revision 5 of XML-1.0
2962
 * They correspond to the modified production [4] and the new production [4a]
2963
 * changes in that revision. Also note that the macros used for the
2964
 * productions Letter, Digit, CombiningChar and Extender are not needed
2965
 * anymore.
2966
 * We still keep compatibility to pre-revision5 parsing semantic if the
2967
 * new XML_PARSE_OLD10 option is given to the parser.
2968
 */
2969
2970
static int
2971
19.9M
xmlIsNameStartCharNew(int c) {
2972
    /*
2973
     * Use the new checks of production [4] [4a] amd [5] of the
2974
     * Update 5 of XML-1.0
2975
     */
2976
19.9M
    if ((c != ' ') && (c != '>') && (c != '/') && /* accelerators */
2977
19.9M
        (((c >= 'a') && (c <= 'z')) ||
2978
19.9M
         ((c >= 'A') && (c <= 'Z')) ||
2979
19.9M
         (c == '_') || (c == ':') ||
2980
19.9M
         ((c >= 0xC0) && (c <= 0xD6)) ||
2981
19.9M
         ((c >= 0xD8) && (c <= 0xF6)) ||
2982
19.9M
         ((c >= 0xF8) && (c <= 0x2FF)) ||
2983
19.9M
         ((c >= 0x370) && (c <= 0x37D)) ||
2984
19.9M
         ((c >= 0x37F) && (c <= 0x1FFF)) ||
2985
19.9M
         ((c >= 0x200C) && (c <= 0x200D)) ||
2986
19.9M
         ((c >= 0x2070) && (c <= 0x218F)) ||
2987
19.9M
         ((c >= 0x2C00) && (c <= 0x2FEF)) ||
2988
19.9M
         ((c >= 0x3001) && (c <= 0xD7FF)) ||
2989
19.9M
         ((c >= 0xF900) && (c <= 0xFDCF)) ||
2990
19.9M
         ((c >= 0xFDF0) && (c <= 0xFFFD)) ||
2991
19.9M
         ((c >= 0x10000) && (c <= 0xEFFFF))))
2992
6.01M
        return(1);
2993
13.9M
    return(0);
2994
19.9M
}
2995
2996
static int
2997
8.74M
xmlIsNameCharNew(int c) {
2998
    /*
2999
     * Use the new checks of production [4] [4a] amd [5] of the
3000
     * Update 5 of XML-1.0
3001
     */
3002
8.74M
    if ((c != ' ') && (c != '>') && (c != '/') && /* accelerators */
3003
8.74M
        (((c >= 'a') && (c <= 'z')) ||
3004
5.41M
         ((c >= 'A') && (c <= 'Z')) ||
3005
5.41M
         ((c >= '0') && (c <= '9')) || /* !start */
3006
5.41M
         (c == '_') || (c == ':') ||
3007
5.41M
         (c == '-') || (c == '.') || (c == 0xB7) || /* !start */
3008
5.41M
         ((c >= 0xC0) && (c <= 0xD6)) ||
3009
5.41M
         ((c >= 0xD8) && (c <= 0xF6)) ||
3010
5.41M
         ((c >= 0xF8) && (c <= 0x2FF)) ||
3011
5.41M
         ((c >= 0x300) && (c <= 0x36F)) || /* !start */
3012
5.41M
         ((c >= 0x370) && (c <= 0x37D)) ||
3013
5.41M
         ((c >= 0x37F) && (c <= 0x1FFF)) ||
3014
5.41M
         ((c >= 0x200C) && (c <= 0x200D)) ||
3015
5.41M
         ((c >= 0x203F) && (c <= 0x2040)) || /* !start */
3016
5.41M
         ((c >= 0x2070) && (c <= 0x218F)) ||
3017
5.41M
         ((c >= 0x2C00) && (c <= 0x2FEF)) ||
3018
5.41M
         ((c >= 0x3001) && (c <= 0xD7FF)) ||
3019
5.41M
         ((c >= 0xF900) && (c <= 0xFDCF)) ||
3020
5.41M
         ((c >= 0xFDF0) && (c <= 0xFFFD)) ||
3021
5.41M
         ((c >= 0x10000) && (c <= 0xEFFFF))))
3022
2.85M
         return(1);
3023
5.89M
    return(0);
3024
8.74M
}
3025
3026
static int
3027
0
xmlIsNameStartCharOld(int c) {
3028
0
    if ((c != ' ') && (c != '>') && (c != '/') && /* accelerators */
3029
0
        ((IS_LETTER(c) || (c == '_') || (c == ':'))))
3030
0
        return(1);
3031
0
    return(0);
3032
0
}
3033
3034
static int
3035
0
xmlIsNameCharOld(int c) {
3036
0
    if ((c != ' ') && (c != '>') && (c != '/') && /* accelerators */
3037
0
        ((IS_LETTER(c)) || (IS_DIGIT(c)) ||
3038
0
         (c == '.') || (c == '-') ||
3039
0
         (c == '_') || (c == ':') ||
3040
0
         (IS_COMBINING(c)) ||
3041
0
         (IS_EXTENDER(c))))
3042
0
        return(1);
3043
0
    return(0);
3044
0
}
3045
3046
static int
3047
19.9M
xmlIsNameStartChar(int c, int old10) {
3048
19.9M
    if (!old10)
3049
19.9M
        return(xmlIsNameStartCharNew(c));
3050
0
    else
3051
0
        return(xmlIsNameStartCharOld(c));
3052
19.9M
}
3053
3054
static int
3055
8.74M
xmlIsNameChar(int c, int old10) {
3056
8.74M
    if (!old10)
3057
8.74M
        return(xmlIsNameCharNew(c));
3058
0
    else
3059
0
        return(xmlIsNameCharOld(c));
3060
8.74M
}
3061
3062
/*
3063
 * Scan an XML Name, NCName or Nmtoken.
3064
 *
3065
 * Returns a pointer to the end of the name on success. If the
3066
 * name is invalid, returns `ptr`. If the name is longer than
3067
 * `maxSize` bytes, returns NULL.
3068
 *
3069
 * @param ptr  pointer to the start of the name
3070
 * @param maxSize  maximum size in bytes
3071
 * @param flags  XML_SCAN_* flags
3072
 * @returns a pointer to the end of the name or NULL
3073
 */
3074
const xmlChar *
3075
19.9M
xmlScanName(const xmlChar *ptr, size_t maxSize, int flags) {
3076
19.9M
    int stop = flags & XML_SCAN_NC ? ':' : 0;
3077
19.9M
    int old10 = flags & XML_SCAN_OLD10 ? 1 : 0;
3078
3079
28.8M
    while (1) {
3080
28.8M
        int c, len;
3081
3082
28.8M
        c = *ptr;
3083
28.8M
        if (c < 0x80) {
3084
28.8M
            if (c == stop)
3085
124k
                break;
3086
28.7M
            len = 1;
3087
28.7M
        } else {
3088
14.7k
            len = 4;
3089
14.7k
            c = xmlGetUTF8Char(ptr, &len);
3090
14.7k
            if (c < 0)
3091
521
                break;
3092
14.7k
        }
3093
3094
28.7M
        if (flags & XML_SCAN_NMTOKEN ?
3095
8.74M
                !xmlIsNameChar(c, old10) :
3096
28.7M
                !xmlIsNameStartChar(c, old10))
3097
19.8M
            break;
3098
3099
8.87M
        if ((size_t) len > maxSize)
3100
7
            return(NULL);
3101
8.87M
        ptr += len;
3102
8.87M
        maxSize -= len;
3103
8.87M
        flags |= XML_SCAN_NMTOKEN;
3104
8.87M
    }
3105
3106
19.9M
    return(ptr);
3107
19.9M
}
3108
3109
static const xmlChar *
3110
0
xmlParseNameComplex(xmlParserCtxtPtr ctxt) {
3111
0
    const xmlChar *ret;
3112
0
    int len = 0, l;
3113
0
    int c;
3114
0
    int maxLength = (ctxt->options & XML_PARSE_HUGE) ?
3115
0
                    XML_MAX_TEXT_LENGTH :
3116
0
                    XML_MAX_NAME_LENGTH;
3117
0
    int old10 = (ctxt->options & XML_PARSE_OLD10) ? 1 : 0;
3118
3119
    /*
3120
     * Handler for more complex cases
3121
     */
3122
0
    c = xmlCurrentChar(ctxt, &l);
3123
0
    if (!xmlIsNameStartChar(c, old10))
3124
0
        return(NULL);
3125
0
    len += l;
3126
0
    NEXTL(l);
3127
0
    c = xmlCurrentChar(ctxt, &l);
3128
0
    while (xmlIsNameChar(c, old10)) {
3129
0
        if (len <= INT_MAX - l)
3130
0
            len += l;
3131
0
        NEXTL(l);
3132
0
        c = xmlCurrentChar(ctxt, &l);
3133
0
    }
3134
0
    if (len > maxLength) {
3135
0
        xmlFatalErr(ctxt, XML_ERR_NAME_TOO_LONG, "Name");
3136
0
        return(NULL);
3137
0
    }
3138
0
    if (ctxt->input->cur - ctxt->input->base < len) {
3139
        /*
3140
         * There were a couple of bugs where PERefs lead to to a change
3141
         * of the buffer. Check the buffer size to avoid passing an invalid
3142
         * pointer to xmlDictLookup.
3143
         */
3144
0
        xmlFatalErr(ctxt, XML_ERR_INTERNAL_ERROR,
3145
0
                    "unexpected change of input buffer");
3146
0
        return (NULL);
3147
0
    }
3148
0
    if ((*ctxt->input->cur == '\n') && (ctxt->input->cur[-1] == '\r'))
3149
0
        ret = xmlDictLookup(ctxt->dict, ctxt->input->cur - (len + 1), len);
3150
0
    else
3151
0
        ret = xmlDictLookup(ctxt->dict, ctxt->input->cur - len, len);
3152
0
    if (ret == NULL)
3153
0
        xmlErrMemory(ctxt);
3154
0
    return(ret);
3155
0
}
3156
3157
/**
3158
 * parse an XML name.
3159
 *
3160
 * @deprecated Internal function, don't use.
3161
 *
3162
 *     [4] NameChar ::= Letter | Digit | '.' | '-' | '_' | ':' |
3163
 *                      CombiningChar | Extender
3164
 *
3165
 *     [5] Name ::= (Letter | '_' | ':') (NameChar)*
3166
 *
3167
 *     [6] Names ::= Name (#x20 Name)*
3168
 *
3169
 * @param ctxt  an XML parser context
3170
 * @returns the Name parsed or NULL
3171
 */
3172
3173
const xmlChar *
3174
0
xmlParseName(xmlParserCtxt *ctxt) {
3175
0
    const xmlChar *in;
3176
0
    const xmlChar *ret;
3177
0
    size_t count = 0;
3178
0
    size_t maxLength = (ctxt->options & XML_PARSE_HUGE) ?
3179
0
                       XML_MAX_TEXT_LENGTH :
3180
0
                       XML_MAX_NAME_LENGTH;
3181
3182
0
    GROW;
3183
3184
    /*
3185
     * Accelerator for simple ASCII names
3186
     */
3187
0
    in = ctxt->input->cur;
3188
0
    if (((*in >= 0x61) && (*in <= 0x7A)) ||
3189
0
  ((*in >= 0x41) && (*in <= 0x5A)) ||
3190
0
  (*in == '_') || (*in == ':')) {
3191
0
  in++;
3192
0
  while (((*in >= 0x61) && (*in <= 0x7A)) ||
3193
0
         ((*in >= 0x41) && (*in <= 0x5A)) ||
3194
0
         ((*in >= 0x30) && (*in <= 0x39)) ||
3195
0
         (*in == '_') || (*in == '-') ||
3196
0
         (*in == ':') || (*in == '.'))
3197
0
      in++;
3198
0
  if ((*in > 0) && (*in < 0x80)) {
3199
0
      count = in - ctxt->input->cur;
3200
0
            if (count > maxLength) {
3201
0
                xmlFatalErr(ctxt, XML_ERR_NAME_TOO_LONG, "Name");
3202
0
                return(NULL);
3203
0
            }
3204
0
      ret = xmlDictLookup(ctxt->dict, ctxt->input->cur, count);
3205
0
      ctxt->input->cur = in;
3206
0
      ctxt->input->col += count;
3207
0
      if (ret == NULL)
3208
0
          xmlErrMemory(ctxt);
3209
0
      return(ret);
3210
0
  }
3211
0
    }
3212
    /* accelerator for special cases */
3213
0
    return(xmlParseNameComplex(ctxt));
3214
0
}
3215
3216
static xmlHashedString
3217
0
xmlParseNCNameComplex(xmlParserCtxtPtr ctxt) {
3218
0
    xmlHashedString ret;
3219
0
    int len = 0, l;
3220
0
    int c;
3221
0
    int maxLength = (ctxt->options & XML_PARSE_HUGE) ?
3222
0
                    XML_MAX_TEXT_LENGTH :
3223
0
                    XML_MAX_NAME_LENGTH;
3224
0
    int old10 = (ctxt->options & XML_PARSE_OLD10) ? 1 : 0;
3225
0
    size_t startPosition = 0;
3226
3227
0
    ret.name = NULL;
3228
0
    ret.hashValue = 0;
3229
3230
    /*
3231
     * Handler for more complex cases
3232
     */
3233
0
    startPosition = CUR_PTR - BASE_PTR;
3234
0
    c = xmlCurrentChar(ctxt, &l);
3235
0
    if ((c == ' ') || (c == '>') || (c == '/') || /* accelerators */
3236
0
  (!xmlIsNameStartChar(c, old10) || (c == ':'))) {
3237
0
  return(ret);
3238
0
    }
3239
3240
0
    while ((c != ' ') && (c != '>') && (c != '/') && /* test bigname.xml */
3241
0
     (xmlIsNameChar(c, old10) && (c != ':'))) {
3242
0
        if (len <= INT_MAX - l)
3243
0
      len += l;
3244
0
  NEXTL(l);
3245
0
  c = xmlCurrentChar(ctxt, &l);
3246
0
    }
3247
0
    if (len > maxLength) {
3248
0
        xmlFatalErr(ctxt, XML_ERR_NAME_TOO_LONG, "NCName");
3249
0
        return(ret);
3250
0
    }
3251
0
    ret = xmlDictLookupHashed(ctxt->dict, (BASE_PTR + startPosition), len);
3252
0
    if (ret.name == NULL)
3253
0
        xmlErrMemory(ctxt);
3254
0
    return(ret);
3255
0
}
3256
3257
/**
3258
 * parse an XML name.
3259
 *
3260
 *     [4NS] NCNameChar ::= Letter | Digit | '.' | '-' | '_' |
3261
 *                          CombiningChar | Extender
3262
 *
3263
 *     [5NS] NCName ::= (Letter | '_') (NCNameChar)*
3264
 *
3265
 * @param ctxt  an XML parser context
3266
 * @returns the Name parsed or NULL
3267
 */
3268
3269
static xmlHashedString
3270
0
xmlParseNCName(xmlParserCtxtPtr ctxt) {
3271
0
    const xmlChar *in, *e;
3272
0
    xmlHashedString ret;
3273
0
    size_t count = 0;
3274
0
    size_t maxLength = (ctxt->options & XML_PARSE_HUGE) ?
3275
0
                       XML_MAX_TEXT_LENGTH :
3276
0
                       XML_MAX_NAME_LENGTH;
3277
3278
0
    ret.name = NULL;
3279
3280
    /*
3281
     * Accelerator for simple ASCII names
3282
     */
3283
0
    in = ctxt->input->cur;
3284
0
    e = ctxt->input->end;
3285
0
    if ((((*in >= 0x61) && (*in <= 0x7A)) ||
3286
0
   ((*in >= 0x41) && (*in <= 0x5A)) ||
3287
0
   (*in == '_')) && (in < e)) {
3288
0
  in++;
3289
0
  while ((((*in >= 0x61) && (*in <= 0x7A)) ||
3290
0
          ((*in >= 0x41) && (*in <= 0x5A)) ||
3291
0
          ((*in >= 0x30) && (*in <= 0x39)) ||
3292
0
          (*in == '_') || (*in == '-') ||
3293
0
          (*in == '.')) && (in < e))
3294
0
      in++;
3295
0
  if (in >= e)
3296
0
      goto complex;
3297
0
  if ((*in > 0) && (*in < 0x80)) {
3298
0
      count = in - ctxt->input->cur;
3299
0
            if (count > maxLength) {
3300
0
                xmlFatalErr(ctxt, XML_ERR_NAME_TOO_LONG, "NCName");
3301
0
                return(ret);
3302
0
            }
3303
0
      ret = xmlDictLookupHashed(ctxt->dict, ctxt->input->cur, count);
3304
0
      ctxt->input->cur = in;
3305
0
      ctxt->input->col += count;
3306
0
      if (ret.name == NULL) {
3307
0
          xmlErrMemory(ctxt);
3308
0
      }
3309
0
      return(ret);
3310
0
  }
3311
0
    }
3312
0
complex:
3313
0
    return(xmlParseNCNameComplex(ctxt));
3314
0
}
3315
3316
/**
3317
 * parse an XML name and compares for match
3318
 * (specialized for endtag parsing)
3319
 *
3320
 * @param ctxt  an XML parser context
3321
 * @param other  the name to compare with
3322
 * @returns NULL for an illegal name, (xmlChar*) 1 for success
3323
 * and the name for mismatch
3324
 */
3325
3326
static const xmlChar *
3327
0
xmlParseNameAndCompare(xmlParserCtxtPtr ctxt, xmlChar const *other) {
3328
0
    register const xmlChar *cmp = other;
3329
0
    register const xmlChar *in;
3330
0
    const xmlChar *ret;
3331
3332
0
    GROW;
3333
3334
0
    in = ctxt->input->cur;
3335
0
    while (*in != 0 && *in == *cmp) {
3336
0
  ++in;
3337
0
  ++cmp;
3338
0
    }
3339
0
    if (*cmp == 0 && (*in == '>' || IS_BLANK_CH (*in))) {
3340
  /* success */
3341
0
  ctxt->input->col += in - ctxt->input->cur;
3342
0
  ctxt->input->cur = in;
3343
0
  return (const xmlChar*) 1;
3344
0
    }
3345
    /* failure (or end of input buffer), check with full function */
3346
0
    ret = xmlParseName (ctxt);
3347
    /* strings coming from the dictionary direct compare possible */
3348
0
    if (ret == other) {
3349
0
  return (const xmlChar*) 1;
3350
0
    }
3351
0
    return ret;
3352
0
}
3353
3354
/**
3355
 * Parse an XML name.
3356
 *
3357
 * @param ctxt  an XML parser context
3358
 * @param str  a pointer to the string pointer (IN/OUT)
3359
 * @returns the Name parsed or NULL. The `str` pointer
3360
 * is updated to the current location in the string.
3361
 */
3362
3363
static xmlChar *
3364
0
xmlParseStringName(xmlParserCtxtPtr ctxt, const xmlChar** str) {
3365
0
    xmlChar *ret;
3366
0
    const xmlChar *cur = *str;
3367
0
    int flags = 0;
3368
0
    int maxLength = (ctxt->options & XML_PARSE_HUGE) ?
3369
0
                    XML_MAX_TEXT_LENGTH :
3370
0
                    XML_MAX_NAME_LENGTH;
3371
3372
0
    if (ctxt->options & XML_PARSE_OLD10)
3373
0
        flags |= XML_SCAN_OLD10;
3374
3375
0
    cur = xmlScanName(*str, maxLength, flags);
3376
0
    if (cur == NULL) {
3377
0
        xmlFatalErr(ctxt, XML_ERR_NAME_TOO_LONG, "NCName");
3378
0
        return(NULL);
3379
0
    }
3380
0
    if (cur == *str)
3381
0
        return(NULL);
3382
3383
0
    ret = xmlStrndup(*str, cur - *str);
3384
0
    if (ret == NULL)
3385
0
        xmlErrMemory(ctxt);
3386
0
    *str = cur;
3387
0
    return(ret);
3388
0
}
3389
3390
/**
3391
 * parse an XML Nmtoken.
3392
 *
3393
 * @deprecated Internal function, don't use.
3394
 *
3395
 *     [7] Nmtoken ::= (NameChar)+
3396
 *
3397
 *     [8] Nmtokens ::= Nmtoken (#x20 Nmtoken)*
3398
 *
3399
 * @param ctxt  an XML parser context
3400
 * @returns the Nmtoken parsed or NULL
3401
 */
3402
3403
xmlChar *
3404
0
xmlParseNmtoken(xmlParserCtxt *ctxt) {
3405
0
    xmlChar buf[XML_MAX_NAMELEN + 5];
3406
0
    xmlChar *ret;
3407
0
    int len = 0, l;
3408
0
    int c;
3409
0
    int maxLength = (ctxt->options & XML_PARSE_HUGE) ?
3410
0
                    XML_MAX_TEXT_LENGTH :
3411
0
                    XML_MAX_NAME_LENGTH;
3412
0
    int old10 = (ctxt->options & XML_PARSE_OLD10) ? 1 : 0;
3413
3414
0
    c = xmlCurrentChar(ctxt, &l);
3415
3416
0
    while (xmlIsNameChar(c, old10)) {
3417
0
  COPY_BUF(buf, len, c);
3418
0
  NEXTL(l);
3419
0
  c = xmlCurrentChar(ctxt, &l);
3420
0
  if (len >= XML_MAX_NAMELEN) {
3421
      /*
3422
       * Okay someone managed to make a huge token, so he's ready to pay
3423
       * for the processing speed.
3424
       */
3425
0
      xmlChar *buffer;
3426
0
      int max = len * 2;
3427
3428
0
      buffer = xmlMalloc(max);
3429
0
      if (buffer == NULL) {
3430
0
          xmlErrMemory(ctxt);
3431
0
    return(NULL);
3432
0
      }
3433
0
      memcpy(buffer, buf, len);
3434
0
      while (xmlIsNameChar(c, old10)) {
3435
0
    if (len + 10 > max) {
3436
0
        xmlChar *tmp;
3437
0
                    int newSize;
3438
3439
0
                    newSize = xmlGrowCapacity(max, 1, 1, maxLength);
3440
0
                    if (newSize < 0) {
3441
0
                        xmlFatalErr(ctxt, XML_ERR_NAME_TOO_LONG, "NmToken");
3442
0
                        xmlFree(buffer);
3443
0
                        return(NULL);
3444
0
                    }
3445
0
        tmp = xmlRealloc(buffer, newSize);
3446
0
        if (tmp == NULL) {
3447
0
      xmlErrMemory(ctxt);
3448
0
      xmlFree(buffer);
3449
0
      return(NULL);
3450
0
        }
3451
0
        buffer = tmp;
3452
0
                    max = newSize;
3453
0
    }
3454
0
    COPY_BUF(buffer, len, c);
3455
0
    NEXTL(l);
3456
0
    c = xmlCurrentChar(ctxt, &l);
3457
0
      }
3458
0
      buffer[len] = 0;
3459
0
      return(buffer);
3460
0
  }
3461
0
    }
3462
0
    if (len == 0)
3463
0
        return(NULL);
3464
0
    if (len > maxLength) {
3465
0
        xmlFatalErr(ctxt, XML_ERR_NAME_TOO_LONG, "NmToken");
3466
0
        return(NULL);
3467
0
    }
3468
0
    ret = xmlStrndup(buf, len);
3469
0
    if (ret == NULL)
3470
0
        xmlErrMemory(ctxt);
3471
0
    return(ret);
3472
0
}
3473
3474
/**
3475
 * Validate an entity value and expand parameter entities.
3476
 *
3477
 * @param ctxt  parser context
3478
 * @param buf  string buffer
3479
 * @param str  entity value
3480
 * @param length  size of entity value
3481
 * @param depth  nesting depth
3482
 */
3483
static void
3484
xmlExpandPEsInEntityValue(xmlParserCtxtPtr ctxt, xmlSBuf *buf,
3485
0
                          const xmlChar *str, int length, int depth) {
3486
0
    int maxDepth = (ctxt->options & XML_PARSE_HUGE) ? 40 : 20;
3487
0
    const xmlChar *end, *chunk;
3488
0
    int c, l;
3489
3490
0
    if (str == NULL)
3491
0
        return;
3492
3493
0
    depth += 1;
3494
0
    if (depth > maxDepth) {
3495
0
  xmlFatalErrMsg(ctxt, XML_ERR_RESOURCE_LIMIT,
3496
0
                       "Maximum entity nesting depth exceeded");
3497
0
  return;
3498
0
    }
3499
3500
0
    end = str + length;
3501
0
    chunk = str;
3502
3503
0
    while ((str < end) && (!PARSER_STOPPED(ctxt))) {
3504
0
        c = *str;
3505
3506
0
        if (c >= 0x80) {
3507
0
            l = xmlUTF8MultibyteLen(ctxt, str,
3508
0
                    "invalid character in entity value\n");
3509
0
            if (l == 0) {
3510
0
                if (chunk < str)
3511
0
                    xmlSBufAddString(buf, chunk, str - chunk);
3512
0
                xmlSBufAddReplChar(buf);
3513
0
                str += 1;
3514
0
                chunk = str;
3515
0
            } else {
3516
0
                str += l;
3517
0
            }
3518
0
        } else if (c == '&') {
3519
0
            if (str[1] == '#') {
3520
0
                if (chunk < str)
3521
0
                    xmlSBufAddString(buf, chunk, str - chunk);
3522
3523
0
                c = xmlParseStringCharRef(ctxt, &str);
3524
0
                if (c == 0)
3525
0
                    return;
3526
3527
0
                xmlSBufAddChar(buf, c);
3528
3529
0
                chunk = str;
3530
0
            } else {
3531
0
                xmlChar *name;
3532
3533
                /*
3534
                 * General entity references are checked for
3535
                 * syntactic validity.
3536
                 */
3537
0
                str++;
3538
0
                name = xmlParseStringName(ctxt, &str);
3539
3540
0
                if ((name == NULL) || (*str++ != ';')) {
3541
0
                    xmlFatalErrMsg(ctxt, XML_ERR_ENTITY_CHAR_ERROR,
3542
0
                            "EntityValue: '&' forbidden except for entities "
3543
0
                            "references\n");
3544
0
                    xmlFree(name);
3545
0
                    return;
3546
0
                }
3547
3548
0
                xmlFree(name);
3549
0
            }
3550
0
        } else if (c == '%') {
3551
0
            xmlEntityPtr ent;
3552
3553
0
            if (chunk < str)
3554
0
                xmlSBufAddString(buf, chunk, str - chunk);
3555
3556
0
            ent = xmlParseStringPEReference(ctxt, &str);
3557
0
            if (ent == NULL)
3558
0
                return;
3559
3560
0
            if (!PARSER_EXTERNAL(ctxt)) {
3561
0
                xmlFatalErr(ctxt, XML_ERR_ENTITY_PE_INTERNAL, NULL);
3562
0
                return;
3563
0
            }
3564
3565
0
            if (ent->content == NULL) {
3566
                /*
3567
                 * Note: external parsed entities will not be loaded,
3568
                 * it is not required for a non-validating parser to
3569
                 * complete external PEReferences coming from the
3570
                 * internal subset
3571
                 */
3572
0
                if (((ctxt->options & XML_PARSE_NO_XXE) == 0) &&
3573
0
                    ((ctxt->replaceEntities) ||
3574
0
                     (ctxt->validate))) {
3575
0
                    xmlLoadEntityContent(ctxt, ent);
3576
0
                } else {
3577
0
                    xmlWarningMsg(ctxt, XML_ERR_ENTITY_PROCESSING,
3578
0
                                  "not validating will not read content for "
3579
0
                                  "PE entity %s\n", ent->name, NULL);
3580
0
                }
3581
0
            }
3582
3583
            /*
3584
             * TODO: Skip if ent->content is still NULL.
3585
             */
3586
3587
0
            if (xmlParserEntityCheck(ctxt, ent->length))
3588
0
                return;
3589
3590
0
            if (ent->flags & XML_ENT_EXPANDING) {
3591
0
                xmlFatalErr(ctxt, XML_ERR_ENTITY_LOOP, NULL);
3592
0
                xmlHaltParser(ctxt);
3593
0
                return;
3594
0
            }
3595
3596
0
            ent->flags |= XML_ENT_EXPANDING;
3597
0
            xmlExpandPEsInEntityValue(ctxt, buf, ent->content, ent->length,
3598
0
                                      depth);
3599
0
            ent->flags &= ~XML_ENT_EXPANDING;
3600
3601
0
            chunk = str;
3602
0
        } else {
3603
            /* Normal ASCII char */
3604
0
            if (!IS_BYTE_CHAR(c)) {
3605
0
                xmlFatalErrMsg(ctxt, XML_ERR_INVALID_CHAR,
3606
0
                        "invalid character in entity value\n");
3607
0
                if (chunk < str)
3608
0
                    xmlSBufAddString(buf, chunk, str - chunk);
3609
0
                xmlSBufAddReplChar(buf);
3610
0
                str += 1;
3611
0
                chunk = str;
3612
0
            } else {
3613
0
                str += 1;
3614
0
            }
3615
0
        }
3616
0
    }
3617
3618
0
    if (chunk < str)
3619
0
        xmlSBufAddString(buf, chunk, str - chunk);
3620
0
}
3621
3622
/**
3623
 * parse a value for ENTITY declarations
3624
 *
3625
 * @deprecated Internal function, don't use.
3626
 *
3627
 *     [9] EntityValue ::= '"' ([^%&"] | PEReference | Reference)* '"' |
3628
 *                         "'" ([^%&'] | PEReference | Reference)* "'"
3629
 *
3630
 * @param ctxt  an XML parser context
3631
 * @param orig  if non-NULL store a copy of the original entity value
3632
 * @returns the EntityValue parsed with reference substituted or NULL
3633
 */
3634
xmlChar *
3635
0
xmlParseEntityValue(xmlParserCtxt *ctxt, xmlChar **orig) {
3636
0
    unsigned maxLength = (ctxt->options & XML_PARSE_HUGE) ?
3637
0
                         XML_MAX_HUGE_LENGTH :
3638
0
                         XML_MAX_TEXT_LENGTH;
3639
0
    xmlSBuf buf;
3640
0
    const xmlChar *start;
3641
0
    int quote, length;
3642
3643
0
    xmlSBufInit(&buf, maxLength);
3644
3645
0
    GROW;
3646
3647
0
    quote = CUR;
3648
0
    if ((quote != '"') && (quote != '\'')) {
3649
0
  xmlFatalErr(ctxt, XML_ERR_ATTRIBUTE_NOT_STARTED, NULL);
3650
0
  return(NULL);
3651
0
    }
3652
0
    CUR_PTR++;
3653
3654
0
    length = 0;
3655
3656
    /*
3657
     * Copy raw content of the entity into a buffer
3658
     */
3659
0
    while (1) {
3660
0
        int c;
3661
3662
0
        if (PARSER_STOPPED(ctxt))
3663
0
            goto error;
3664
3665
0
        if (CUR_PTR >= ctxt->input->end) {
3666
0
            xmlFatalErrMsg(ctxt, XML_ERR_ENTITY_NOT_FINISHED, NULL);
3667
0
            goto error;
3668
0
        }
3669
3670
0
        c = CUR;
3671
3672
0
        if (c == 0) {
3673
0
            xmlFatalErrMsg(ctxt, XML_ERR_INVALID_CHAR,
3674
0
                    "invalid character in entity value\n");
3675
0
            goto error;
3676
0
        }
3677
0
        if (c == quote)
3678
0
            break;
3679
0
        NEXTL(1);
3680
0
        length += 1;
3681
3682
        /*
3683
         * TODO: Check growth threshold
3684
         */
3685
0
        if (ctxt->input->end - CUR_PTR < 10)
3686
0
            GROW;
3687
0
    }
3688
3689
0
    start = CUR_PTR - length;
3690
3691
0
    if (orig != NULL) {
3692
0
        *orig = xmlStrndup(start, length);
3693
0
        if (*orig == NULL)
3694
0
            xmlErrMemory(ctxt);
3695
0
    }
3696
3697
0
    xmlExpandPEsInEntityValue(ctxt, &buf, start, length, ctxt->inputNr);
3698
3699
0
    NEXTL(1);
3700
3701
0
    return(xmlSBufFinish(&buf, NULL, ctxt, "entity length too long"));
3702
3703
0
error:
3704
0
    xmlSBufCleanup(&buf, ctxt, "entity length too long");
3705
0
    return(NULL);
3706
0
}
3707
3708
/**
3709
 * Check an entity reference in an attribute value for validity
3710
 * without expanding it.
3711
 *
3712
 * @param ctxt  parser context
3713
 * @param pent  entity
3714
 * @param depth  nesting depth
3715
 */
3716
static void
3717
0
xmlCheckEntityInAttValue(xmlParserCtxtPtr ctxt, xmlEntityPtr pent, int depth) {
3718
0
    int maxDepth = (ctxt->options & XML_PARSE_HUGE) ? 40 : 20;
3719
0
    const xmlChar *str;
3720
0
    unsigned long expandedSize = pent->length;
3721
0
    int c, flags;
3722
3723
0
    depth += 1;
3724
0
    if (depth > maxDepth) {
3725
0
  xmlFatalErrMsg(ctxt, XML_ERR_RESOURCE_LIMIT,
3726
0
                       "Maximum entity nesting depth exceeded");
3727
0
  return;
3728
0
    }
3729
3730
0
    if (pent->flags & XML_ENT_EXPANDING) {
3731
0
        xmlFatalErr(ctxt, XML_ERR_ENTITY_LOOP, NULL);
3732
0
        xmlHaltParser(ctxt);
3733
0
        return;
3734
0
    }
3735
3736
    /*
3737
     * If we're parsing a default attribute value in DTD content,
3738
     * the entity might reference other entities which weren't
3739
     * defined yet, so the check isn't reliable.
3740
     */
3741
0
    if (ctxt->inSubset == 0)
3742
0
        flags = XML_ENT_CHECKED | XML_ENT_VALIDATED;
3743
0
    else
3744
0
        flags = XML_ENT_VALIDATED;
3745
3746
0
    str = pent->content;
3747
0
    if (str == NULL)
3748
0
        goto done;
3749
3750
    /*
3751
     * Note that entity values are already validated. We only check
3752
     * for illegal less-than signs and compute the expanded size
3753
     * of the entity. No special handling for multi-byte characters
3754
     * is needed.
3755
     */
3756
0
    while (!PARSER_STOPPED(ctxt)) {
3757
0
        c = *str;
3758
3759
0
  if (c != '&') {
3760
0
            if (c == 0)
3761
0
                break;
3762
3763
0
            if (c == '<')
3764
0
                xmlFatalErrMsgStr(ctxt, XML_ERR_LT_IN_ATTRIBUTE,
3765
0
                        "'<' in entity '%s' is not allowed in attributes "
3766
0
                        "values\n", pent->name);
3767
3768
0
            str += 1;
3769
0
        } else if (str[1] == '#') {
3770
0
            int val;
3771
3772
0
      val = xmlParseStringCharRef(ctxt, &str);
3773
0
      if (val == 0) {
3774
0
                pent->content[0] = 0;
3775
0
                break;
3776
0
            }
3777
0
  } else {
3778
0
            xmlChar *name;
3779
0
            xmlEntityPtr ent;
3780
3781
0
      name = xmlParseStringEntityRef(ctxt, &str);
3782
0
      if (name == NULL) {
3783
0
                pent->content[0] = 0;
3784
0
                break;
3785
0
            }
3786
3787
0
            ent = xmlLookupGeneralEntity(ctxt, name, /* inAttr */ 1);
3788
0
            xmlFree(name);
3789
3790
0
            if ((ent != NULL) &&
3791
0
                (ent->etype != XML_INTERNAL_PREDEFINED_ENTITY)) {
3792
0
                if ((ent->flags & flags) != flags) {
3793
0
                    pent->flags |= XML_ENT_EXPANDING;
3794
0
                    xmlCheckEntityInAttValue(ctxt, ent, depth);
3795
0
                    pent->flags &= ~XML_ENT_EXPANDING;
3796
0
                }
3797
3798
0
                xmlSaturatedAdd(&expandedSize, ent->expandedSize);
3799
0
                xmlSaturatedAdd(&expandedSize, XML_ENT_FIXED_COST);
3800
0
            }
3801
0
        }
3802
0
    }
3803
3804
0
done:
3805
0
    if (ctxt->inSubset == 0)
3806
0
        pent->expandedSize = expandedSize;
3807
3808
0
    pent->flags |= flags;
3809
0
}
3810
3811
/**
3812
 * Expand general entity references in an entity or attribute value.
3813
 * Perform attribute value normalization.
3814
 *
3815
 * @param ctxt  parser context
3816
 * @param buf  string buffer
3817
 * @param str  entity or attribute value
3818
 * @param pent  entity for entity value, NULL for attribute values
3819
 * @param normalize  whether to collapse whitespace
3820
 * @param inSpace  whitespace state
3821
 * @param depth  nesting depth
3822
 * @param check  whether to check for amplification
3823
 * @returns  whether there was a normalization change
3824
 */
3825
static int
3826
xmlExpandEntityInAttValue(xmlParserCtxtPtr ctxt, xmlSBuf *buf,
3827
                          const xmlChar *str, xmlEntityPtr pent, int normalize,
3828
0
                          int *inSpace, int depth, int check) {
3829
0
    int maxDepth = (ctxt->options & XML_PARSE_HUGE) ? 40 : 20;
3830
0
    int c, chunkSize;
3831
0
    int normChange = 0;
3832
3833
0
    if (str == NULL)
3834
0
        return(0);
3835
3836
0
    depth += 1;
3837
0
    if (depth > maxDepth) {
3838
0
  xmlFatalErrMsg(ctxt, XML_ERR_RESOURCE_LIMIT,
3839
0
                       "Maximum entity nesting depth exceeded");
3840
0
  return(0);
3841
0
    }
3842
3843
0
    if (pent != NULL) {
3844
0
        if (pent->flags & XML_ENT_EXPANDING) {
3845
0
            xmlFatalErr(ctxt, XML_ERR_ENTITY_LOOP, NULL);
3846
0
            xmlHaltParser(ctxt);
3847
0
            return(0);
3848
0
        }
3849
3850
0
        if (check) {
3851
0
            if (xmlParserEntityCheck(ctxt, pent->length))
3852
0
                return(0);
3853
0
        }
3854
0
    }
3855
3856
0
    chunkSize = 0;
3857
3858
    /*
3859
     * Note that entity values are already validated. No special
3860
     * handling for multi-byte characters is needed.
3861
     */
3862
0
    while (!PARSER_STOPPED(ctxt)) {
3863
0
        c = *str;
3864
3865
0
  if (c != '&') {
3866
0
            if (c == 0)
3867
0
                break;
3868
3869
            /*
3870
             * If this function is called without an entity, it is used to
3871
             * expand entities in an attribute content where less-than was
3872
             * already unscaped and is allowed.
3873
             */
3874
0
            if ((pent != NULL) && (c == '<')) {
3875
0
                xmlFatalErrMsgStr(ctxt, XML_ERR_LT_IN_ATTRIBUTE,
3876
0
                        "'<' in entity '%s' is not allowed in attributes "
3877
0
                        "values\n", pent->name);
3878
0
                break;
3879
0
            }
3880
3881
0
            if (c <= 0x20) {
3882
0
                if ((normalize) && (*inSpace)) {
3883
                    /* Skip char */
3884
0
                    if (chunkSize > 0) {
3885
0
                        xmlSBufAddString(buf, str - chunkSize, chunkSize);
3886
0
                        chunkSize = 0;
3887
0
                    }
3888
0
                    normChange = 1;
3889
0
                } else if (c < 0x20) {
3890
0
                    if (chunkSize > 0) {
3891
0
                        xmlSBufAddString(buf, str - chunkSize, chunkSize);
3892
0
                        chunkSize = 0;
3893
0
                    }
3894
3895
0
                    xmlSBufAddCString(buf, " ", 1);
3896
0
                } else {
3897
0
                    chunkSize += 1;
3898
0
                }
3899
3900
0
                *inSpace = 1;
3901
0
            } else {
3902
0
                chunkSize += 1;
3903
0
                *inSpace = 0;
3904
0
            }
3905
3906
0
            str += 1;
3907
0
        } else if (str[1] == '#') {
3908
0
            int val;
3909
3910
0
            if (chunkSize > 0) {
3911
0
                xmlSBufAddString(buf, str - chunkSize, chunkSize);
3912
0
                chunkSize = 0;
3913
0
            }
3914
3915
0
      val = xmlParseStringCharRef(ctxt, &str);
3916
0
      if (val == 0) {
3917
0
                if (pent != NULL)
3918
0
                    pent->content[0] = 0;
3919
0
                break;
3920
0
            }
3921
3922
0
            if (val == ' ') {
3923
0
                if ((normalize) && (*inSpace))
3924
0
                    normChange = 1;
3925
0
                else
3926
0
                    xmlSBufAddCString(buf, " ", 1);
3927
0
                *inSpace = 1;
3928
0
            } else {
3929
0
                xmlSBufAddChar(buf, val);
3930
0
                *inSpace = 0;
3931
0
            }
3932
0
  } else {
3933
0
            xmlChar *name;
3934
0
            xmlEntityPtr ent;
3935
3936
0
            if (chunkSize > 0) {
3937
0
                xmlSBufAddString(buf, str - chunkSize, chunkSize);
3938
0
                chunkSize = 0;
3939
0
            }
3940
3941
0
      name = xmlParseStringEntityRef(ctxt, &str);
3942
0
            if (name == NULL) {
3943
0
                if (pent != NULL)
3944
0
                    pent->content[0] = 0;
3945
0
                break;
3946
0
            }
3947
3948
0
            ent = xmlLookupGeneralEntity(ctxt, name, /* inAttr */ 1);
3949
0
            xmlFree(name);
3950
3951
0
      if ((ent != NULL) &&
3952
0
    (ent->etype == XML_INTERNAL_PREDEFINED_ENTITY)) {
3953
0
    if (ent->content == NULL) {
3954
0
        xmlFatalErrMsg(ctxt, XML_ERR_INTERNAL_ERROR,
3955
0
          "predefined entity has no content\n");
3956
0
                    break;
3957
0
                }
3958
3959
0
                xmlSBufAddString(buf, ent->content, ent->length);
3960
3961
0
                *inSpace = 0;
3962
0
      } else if ((ent != NULL) && (ent->content != NULL)) {
3963
0
                if (pent != NULL)
3964
0
                    pent->flags |= XML_ENT_EXPANDING;
3965
0
    normChange |= xmlExpandEntityInAttValue(ctxt, buf,
3966
0
                        ent->content, ent, normalize, inSpace, depth, check);
3967
0
                if (pent != NULL)
3968
0
                    pent->flags &= ~XML_ENT_EXPANDING;
3969
0
      }
3970
0
        }
3971
0
    }
3972
3973
0
    if (chunkSize > 0)
3974
0
        xmlSBufAddString(buf, str - chunkSize, chunkSize);
3975
3976
0
    return(normChange);
3977
0
}
3978
3979
/**
3980
 * Expand general entity references in an entity or attribute value.
3981
 * Perform attribute value normalization.
3982
 *
3983
 * @param ctxt  parser context
3984
 * @param str  entity or attribute value
3985
 * @param normalize  whether to collapse whitespace
3986
 * @returns the expanded attribtue value.
3987
 */
3988
xmlChar *
3989
xmlExpandEntitiesInAttValue(xmlParserCtxt *ctxt, const xmlChar *str,
3990
0
                            int normalize) {
3991
0
    unsigned maxLength = (ctxt->options & XML_PARSE_HUGE) ?
3992
0
                         XML_MAX_HUGE_LENGTH :
3993
0
                         XML_MAX_TEXT_LENGTH;
3994
0
    xmlSBuf buf;
3995
0
    int inSpace = 1;
3996
3997
0
    xmlSBufInit(&buf, maxLength);
3998
3999
0
    xmlExpandEntityInAttValue(ctxt, &buf, str, NULL, normalize, &inSpace,
4000
0
                              ctxt->inputNr, /* check */ 0);
4001
4002
0
    if ((normalize) && (inSpace) && (buf.size > 0))
4003
0
        buf.size--;
4004
4005
0
    return(xmlSBufFinish(&buf, NULL, ctxt, "AttValue length too long"));
4006
0
}
4007
4008
/**
4009
 * parse a value for an attribute.
4010
 *
4011
 * NOTE: if no normalization is needed, the routine will return pointers
4012
 * directly from the data buffer.
4013
 *
4014
 * 3.3.3 Attribute-Value Normalization:
4015
 *
4016
 * Before the value of an attribute is passed to the application or
4017
 * checked for validity, the XML processor must normalize it as follows:
4018
 *
4019
 * - a character reference is processed by appending the referenced
4020
 *   character to the attribute value
4021
 * - an entity reference is processed by recursively processing the
4022
 *   replacement text of the entity
4023
 * - a whitespace character (\#x20, \#xD, \#xA, \#x9) is processed by
4024
 *   appending \#x20 to the normalized value, except that only a single
4025
 *   \#x20 is appended for a "#xD#xA" sequence that is part of an external
4026
 *   parsed entity or the literal entity value of an internal parsed entity
4027
 * - other characters are processed by appending them to the normalized value
4028
 *
4029
 * If the declared value is not CDATA, then the XML processor must further
4030
 * process the normalized attribute value by discarding any leading and
4031
 * trailing space (\#x20) characters, and by replacing sequences of space
4032
 * (\#x20) characters by a single space (\#x20) character.
4033
 * All attributes for which no declaration has been read should be treated
4034
 * by a non-validating parser as if declared CDATA.
4035
 *
4036
 * @param ctxt  an XML parser context
4037
 * @param attlen  attribute len result
4038
 * @param outFlags  resulting XML_ATTVAL_* flags
4039
 * @param special  value from attsSpecial
4040
 * @param isNamespace  whether this is a namespace declaration
4041
 * @returns the AttValue parsed or NULL. The value has to be freed by the
4042
 *     caller if it was copied, this can be detected by val[*len] == 0.
4043
 */
4044
static xmlChar *
4045
xmlParseAttValueInternal(xmlParserCtxtPtr ctxt, int *attlen, int *outFlags,
4046
0
                         int special, int isNamespace) {
4047
0
    unsigned maxLength = (ctxt->options & XML_PARSE_HUGE) ?
4048
0
                         XML_MAX_HUGE_LENGTH :
4049
0
                         XML_MAX_TEXT_LENGTH;
4050
0
    xmlSBuf buf;
4051
0
    xmlChar *ret;
4052
0
    int c, l, quote, entFlags, chunkSize;
4053
0
    int inSpace = 1;
4054
0
    int replaceEntities;
4055
0
    int normalize = (special & XML_SPECIAL_TYPE_MASK) != 0;
4056
0
    int attvalFlags = 0;
4057
4058
    /* Always expand namespace URIs */
4059
0
    replaceEntities = (ctxt->replaceEntities) || (isNamespace);
4060
4061
0
    xmlSBufInit(&buf, maxLength);
4062
4063
0
    GROW;
4064
4065
0
    quote = CUR;
4066
0
    if ((quote != '"') && (quote != '\'')) {
4067
0
  xmlFatalErr(ctxt, XML_ERR_ATTRIBUTE_NOT_STARTED, NULL);
4068
0
  return(NULL);
4069
0
    }
4070
0
    NEXTL(1);
4071
4072
0
    if (ctxt->inSubset == 0)
4073
0
        entFlags = XML_ENT_CHECKED | XML_ENT_VALIDATED;
4074
0
    else
4075
0
        entFlags = XML_ENT_VALIDATED;
4076
4077
0
    inSpace = 1;
4078
0
    chunkSize = 0;
4079
4080
0
    while (1) {
4081
0
        if (PARSER_STOPPED(ctxt))
4082
0
            goto error;
4083
4084
0
        if (CUR_PTR >= ctxt->input->end) {
4085
0
            xmlFatalErrMsg(ctxt, XML_ERR_ATTRIBUTE_NOT_FINISHED,
4086
0
                           "AttValue: ' expected\n");
4087
0
            goto error;
4088
0
        }
4089
4090
        /*
4091
         * TODO: Check growth threshold
4092
         */
4093
0
        if (ctxt->input->end - CUR_PTR < 10)
4094
0
            GROW;
4095
4096
0
        c = CUR;
4097
4098
0
        if (c >= 0x80) {
4099
0
            l = xmlUTF8MultibyteLen(ctxt, CUR_PTR,
4100
0
                    "invalid character in attribute value\n");
4101
0
            if (l == 0) {
4102
0
                if (chunkSize > 0) {
4103
0
                    xmlSBufAddString(&buf, CUR_PTR - chunkSize, chunkSize);
4104
0
                    chunkSize = 0;
4105
0
                }
4106
0
                xmlSBufAddReplChar(&buf);
4107
0
                NEXTL(1);
4108
0
            } else {
4109
0
                chunkSize += l;
4110
0
                NEXTL(l);
4111
0
            }
4112
4113
0
            inSpace = 0;
4114
0
        } else if (c != '&') {
4115
0
            if (c > 0x20) {
4116
0
                if (c == quote)
4117
0
                    break;
4118
4119
0
                if (c == '<')
4120
0
                    xmlFatalErr(ctxt, XML_ERR_LT_IN_ATTRIBUTE, NULL);
4121
4122
0
                chunkSize += 1;
4123
0
                inSpace = 0;
4124
0
            } else if (!IS_BYTE_CHAR(c)) {
4125
0
                xmlFatalErrMsg(ctxt, XML_ERR_INVALID_CHAR,
4126
0
                        "invalid character in attribute value\n");
4127
0
                if (chunkSize > 0) {
4128
0
                    xmlSBufAddString(&buf, CUR_PTR - chunkSize, chunkSize);
4129
0
                    chunkSize = 0;
4130
0
                }
4131
0
                xmlSBufAddReplChar(&buf);
4132
0
                inSpace = 0;
4133
0
            } else {
4134
                /* Whitespace */
4135
0
                if ((normalize) && (inSpace)) {
4136
                    /* Skip char */
4137
0
                    if (chunkSize > 0) {
4138
0
                        xmlSBufAddString(&buf, CUR_PTR - chunkSize, chunkSize);
4139
0
                        chunkSize = 0;
4140
0
                    }
4141
0
                    attvalFlags |= XML_ATTVAL_NORM_CHANGE;
4142
0
                } else if (c < 0x20) {
4143
                    /* Convert to space */
4144
0
                    if (chunkSize > 0) {
4145
0
                        xmlSBufAddString(&buf, CUR_PTR - chunkSize, chunkSize);
4146
0
                        chunkSize = 0;
4147
0
                    }
4148
4149
0
                    xmlSBufAddCString(&buf, " ", 1);
4150
0
                } else {
4151
0
                    chunkSize += 1;
4152
0
                }
4153
4154
0
                inSpace = 1;
4155
4156
0
                if ((c == 0xD) && (NXT(1) == 0xA))
4157
0
                    CUR_PTR++;
4158
0
            }
4159
4160
0
            NEXTL(1);
4161
0
        } else if (NXT(1) == '#') {
4162
0
            int val;
4163
4164
0
            if (chunkSize > 0) {
4165
0
                xmlSBufAddString(&buf, CUR_PTR - chunkSize, chunkSize);
4166
0
                chunkSize = 0;
4167
0
            }
4168
4169
0
            val = xmlParseCharRef(ctxt);
4170
0
            if (val == 0)
4171
0
                goto error;
4172
4173
0
            if ((val == '&') && (!replaceEntities)) {
4174
                /*
4175
                 * The reparsing will be done in xmlNodeParseContent()
4176
                 * called from SAX2.c
4177
                 */
4178
0
                xmlSBufAddCString(&buf, "&#38;", 5);
4179
0
                inSpace = 0;
4180
0
            } else if (val == ' ') {
4181
0
                if ((normalize) && (inSpace))
4182
0
                    attvalFlags |= XML_ATTVAL_NORM_CHANGE;
4183
0
                else
4184
0
                    xmlSBufAddCString(&buf, " ", 1);
4185
0
                inSpace = 1;
4186
0
            } else {
4187
0
                xmlSBufAddChar(&buf, val);
4188
0
                inSpace = 0;
4189
0
            }
4190
0
        } else {
4191
0
            const xmlChar *name;
4192
0
            xmlEntityPtr ent;
4193
4194
0
            if (chunkSize > 0) {
4195
0
                xmlSBufAddString(&buf, CUR_PTR - chunkSize, chunkSize);
4196
0
                chunkSize = 0;
4197
0
            }
4198
4199
0
            name = xmlParseEntityRefInternal(ctxt);
4200
0
            if (name == NULL) {
4201
                /*
4202
                 * Probably a literal '&' which wasn't escaped.
4203
                 * TODO: Handle gracefully in recovery mode.
4204
                 */
4205
0
                continue;
4206
0
            }
4207
4208
0
            ent = xmlLookupGeneralEntity(ctxt, name, /* isAttr */ 1);
4209
0
            if (ent == NULL)
4210
0
                continue;
4211
4212
0
            if (ent->etype == XML_INTERNAL_PREDEFINED_ENTITY) {
4213
0
                if ((ent->content[0] == '&') && (!replaceEntities))
4214
0
                    xmlSBufAddCString(&buf, "&#38;", 5);
4215
0
                else
4216
0
                    xmlSBufAddString(&buf, ent->content, ent->length);
4217
0
                inSpace = 0;
4218
0
            } else if (replaceEntities) {
4219
0
                if (xmlExpandEntityInAttValue(ctxt, &buf,
4220
0
                        ent->content, ent, normalize, &inSpace, ctxt->inputNr,
4221
0
                        /* check */ 1) > 0)
4222
0
                    attvalFlags |= XML_ATTVAL_NORM_CHANGE;
4223
0
            } else {
4224
0
                if ((ent->flags & entFlags) != entFlags)
4225
0
                    xmlCheckEntityInAttValue(ctxt, ent, ctxt->inputNr);
4226
4227
0
                if (xmlParserEntityCheck(ctxt, ent->expandedSize)) {
4228
0
                    ent->content[0] = 0;
4229
0
                    goto error;
4230
0
                }
4231
4232
                /*
4233
                 * Just output the reference
4234
                 */
4235
0
                xmlSBufAddCString(&buf, "&", 1);
4236
0
                xmlSBufAddString(&buf, ent->name, xmlStrlen(ent->name));
4237
0
                xmlSBufAddCString(&buf, ";", 1);
4238
4239
0
                inSpace = 0;
4240
0
            }
4241
0
  }
4242
0
    }
4243
4244
0
    if ((buf.mem == NULL) && (outFlags != NULL)) {
4245
0
        ret = (xmlChar *) CUR_PTR - chunkSize;
4246
4247
0
        if (attlen != NULL)
4248
0
            *attlen = chunkSize;
4249
0
        if ((normalize) && (inSpace) && (chunkSize > 0)) {
4250
0
            attvalFlags |= XML_ATTVAL_NORM_CHANGE;
4251
0
            *attlen -= 1;
4252
0
        }
4253
4254
        /* Report potential error */
4255
0
        xmlSBufCleanup(&buf, ctxt, "AttValue length too long");
4256
0
    } else {
4257
0
        if (chunkSize > 0)
4258
0
            xmlSBufAddString(&buf, CUR_PTR - chunkSize, chunkSize);
4259
4260
0
        if ((normalize) && (inSpace) && (buf.size > 0)) {
4261
0
            attvalFlags |= XML_ATTVAL_NORM_CHANGE;
4262
0
            buf.size--;
4263
0
        }
4264
4265
0
        ret = xmlSBufFinish(&buf, attlen, ctxt, "AttValue length too long");
4266
0
        attvalFlags |= XML_ATTVAL_ALLOC;
4267
4268
0
        if (ret != NULL) {
4269
0
            if (attlen != NULL)
4270
0
                *attlen = buf.size;
4271
0
        }
4272
0
    }
4273
4274
0
    if (outFlags != NULL)
4275
0
        *outFlags = attvalFlags;
4276
4277
0
    NEXTL(1);
4278
4279
0
    return(ret);
4280
4281
0
error:
4282
0
    xmlSBufCleanup(&buf, ctxt, "AttValue length too long");
4283
0
    return(NULL);
4284
0
}
4285
4286
/**
4287
 * parse a value for an attribute
4288
 * Note: the parser won't do substitution of entities here, this
4289
 * will be handled later in #xmlStringGetNodeList
4290
 *
4291
 * @deprecated Internal function, don't use.
4292
 *
4293
 *     [10] AttValue ::= '"' ([^<&"] | Reference)* '"' |
4294
 *                       "'" ([^<&'] | Reference)* "'"
4295
 *
4296
 * 3.3.3 Attribute-Value Normalization:
4297
 *
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
 *
4301
 * - a character reference is processed by appending the referenced
4302
 *   character to the attribute value
4303
 * - an entity reference is processed by recursively processing the
4304
 *   replacement text of the entity
4305
 * - a whitespace character (\#x20, \#xD, \#xA, \#x9) is processed by
4306
 *   appending \#x20 to the normalized value, except that only a single
4307
 *   \#x20 is appended for a "#xD#xA" sequence that is part of an external
4308
 *   parsed entity or the literal entity value of an internal parsed entity
4309
 * - other characters are processed by appending them to the normalized value
4310
 *
4311
 * If the declared value is not CDATA, then the XML processor must further
4312
 * process the normalized attribute value by discarding any leading and
4313
 * trailing space (\#x20) characters, and by replacing sequences of space
4314
 * (\#x20) characters by a single space (\#x20) character.
4315
 * All attributes for which no declaration has been read should be treated
4316
 * by a non-validating parser as if declared CDATA.
4317
 *
4318
 * @param ctxt  an XML parser context
4319
 * @returns the AttValue parsed or NULL. The value has to be freed by the
4320
 * caller.
4321
 */
4322
xmlChar *
4323
0
xmlParseAttValue(xmlParserCtxt *ctxt) {
4324
0
    if ((ctxt == NULL) || (ctxt->input == NULL)) return(NULL);
4325
0
    return(xmlParseAttValueInternal(ctxt, NULL, NULL, 0, 0));
4326
0
}
4327
4328
/**
4329
 * parse an XML Literal
4330
 *
4331
 * @deprecated Internal function, don't use.
4332
 *
4333
 *     [11] SystemLiteral ::= ('"' [^"]* '"') | ("'" [^']* "'")
4334
 *
4335
 * @param ctxt  an XML parser context
4336
 * @returns the SystemLiteral parsed or NULL
4337
 */
4338
4339
xmlChar *
4340
0
xmlParseSystemLiteral(xmlParserCtxt *ctxt) {
4341
0
    xmlChar *buf = NULL;
4342
0
    int len = 0;
4343
0
    int size = XML_PARSER_BUFFER_SIZE;
4344
0
    int cur, l;
4345
0
    int maxLength = (ctxt->options & XML_PARSE_HUGE) ?
4346
0
                    XML_MAX_TEXT_LENGTH :
4347
0
                    XML_MAX_NAME_LENGTH;
4348
0
    xmlChar stop;
4349
4350
0
    if (RAW == '"') {
4351
0
        NEXT;
4352
0
  stop = '"';
4353
0
    } else if (RAW == '\'') {
4354
0
        NEXT;
4355
0
  stop = '\'';
4356
0
    } else {
4357
0
  xmlFatalErr(ctxt, XML_ERR_LITERAL_NOT_STARTED, NULL);
4358
0
  return(NULL);
4359
0
    }
4360
4361
0
    buf = xmlMalloc(size);
4362
0
    if (buf == NULL) {
4363
0
        xmlErrMemory(ctxt);
4364
0
  return(NULL);
4365
0
    }
4366
0
    cur = xmlCurrentCharRecover(ctxt, &l);
4367
0
    while ((IS_CHAR(cur)) && (cur != stop)) { /* checked */
4368
0
  if (len + 5 >= size) {
4369
0
      xmlChar *tmp;
4370
0
            int newSize;
4371
4372
0
            newSize = xmlGrowCapacity(size, 1, 1, maxLength);
4373
0
            if (newSize < 0) {
4374
0
                xmlFatalErr(ctxt, XML_ERR_NAME_TOO_LONG, "SystemLiteral");
4375
0
                xmlFree(buf);
4376
0
                return(NULL);
4377
0
            }
4378
0
      tmp = xmlRealloc(buf, newSize);
4379
0
      if (tmp == NULL) {
4380
0
          xmlFree(buf);
4381
0
    xmlErrMemory(ctxt);
4382
0
    return(NULL);
4383
0
      }
4384
0
      buf = tmp;
4385
0
            size = newSize;
4386
0
  }
4387
0
  COPY_BUF(buf, len, cur);
4388
0
  NEXTL(l);
4389
0
  cur = xmlCurrentCharRecover(ctxt, &l);
4390
0
    }
4391
0
    buf[len] = 0;
4392
0
    if (!IS_CHAR(cur)) {
4393
0
  xmlFatalErr(ctxt, XML_ERR_LITERAL_NOT_FINISHED, NULL);
4394
0
    } else {
4395
0
  NEXT;
4396
0
    }
4397
0
    return(buf);
4398
0
}
4399
4400
/**
4401
 * parse an XML public literal
4402
 *
4403
 * @deprecated Internal function, don't use.
4404
 *
4405
 *     [12] PubidLiteral ::= '"' PubidChar* '"' | "'" (PubidChar - "'")* "'"
4406
 *
4407
 * @param ctxt  an XML parser context
4408
 * @returns the PubidLiteral parsed or NULL.
4409
 */
4410
4411
xmlChar *
4412
0
xmlParsePubidLiteral(xmlParserCtxt *ctxt) {
4413
0
    xmlChar *buf = NULL;
4414
0
    int len = 0;
4415
0
    int size = XML_PARSER_BUFFER_SIZE;
4416
0
    int maxLength = (ctxt->options & XML_PARSE_HUGE) ?
4417
0
                    XML_MAX_TEXT_LENGTH :
4418
0
                    XML_MAX_NAME_LENGTH;
4419
0
    xmlChar cur;
4420
0
    xmlChar stop;
4421
4422
0
    if (RAW == '"') {
4423
0
        NEXT;
4424
0
  stop = '"';
4425
0
    } else if (RAW == '\'') {
4426
0
        NEXT;
4427
0
  stop = '\'';
4428
0
    } else {
4429
0
  xmlFatalErr(ctxt, XML_ERR_LITERAL_NOT_STARTED, NULL);
4430
0
  return(NULL);
4431
0
    }
4432
0
    buf = xmlMalloc(size);
4433
0
    if (buf == NULL) {
4434
0
  xmlErrMemory(ctxt);
4435
0
  return(NULL);
4436
0
    }
4437
0
    cur = CUR;
4438
0
    while ((IS_PUBIDCHAR_CH(cur)) && (cur != stop) &&
4439
0
           (PARSER_STOPPED(ctxt) == 0)) { /* checked */
4440
0
  if (len + 1 >= size) {
4441
0
      xmlChar *tmp;
4442
0
            int newSize;
4443
4444
0
      newSize = xmlGrowCapacity(size, 1, 1, maxLength);
4445
0
            if (newSize < 0) {
4446
0
                xmlFatalErr(ctxt, XML_ERR_NAME_TOO_LONG, "Public ID");
4447
0
                xmlFree(buf);
4448
0
                return(NULL);
4449
0
            }
4450
0
      tmp = xmlRealloc(buf, newSize);
4451
0
      if (tmp == NULL) {
4452
0
    xmlErrMemory(ctxt);
4453
0
    xmlFree(buf);
4454
0
    return(NULL);
4455
0
      }
4456
0
      buf = tmp;
4457
0
            size = newSize;
4458
0
  }
4459
0
  buf[len++] = cur;
4460
0
  NEXT;
4461
0
  cur = CUR;
4462
0
    }
4463
0
    buf[len] = 0;
4464
0
    if (cur != stop) {
4465
0
  xmlFatalErr(ctxt, XML_ERR_LITERAL_NOT_FINISHED, NULL);
4466
0
    } else {
4467
0
  NEXTL(1);
4468
0
    }
4469
0
    return(buf);
4470
0
}
4471
4472
static void xmlParseCharDataComplex(xmlParserCtxtPtr ctxt, int partial);
4473
4474
/*
4475
 * used for the test in the inner loop of the char data testing
4476
 */
4477
static const unsigned char test_char_data[256] = {
4478
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
4479
    0x00, 0x09, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x9, CR/LF separated */
4480
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
4481
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
4482
    0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x00, 0x27, /* & */
4483
    0x28, 0x29, 0x2A, 0x2B, 0x2C, 0x2D, 0x2E, 0x2F,
4484
    0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37,
4485
    0x38, 0x39, 0x3A, 0x3B, 0x00, 0x3D, 0x3E, 0x3F, /* < */
4486
    0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47,
4487
    0x48, 0x49, 0x4A, 0x4B, 0x4C, 0x4D, 0x4E, 0x4F,
4488
    0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57,
4489
    0x58, 0x59, 0x5A, 0x5B, 0x5C, 0x00, 0x5E, 0x5F, /* ] */
4490
    0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67,
4491
    0x68, 0x69, 0x6A, 0x6B, 0x6C, 0x6D, 0x6E, 0x6F,
4492
    0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77,
4493
    0x78, 0x79, 0x7A, 0x7B, 0x7C, 0x7D, 0x7E, 0x7F,
4494
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* non-ascii */
4495
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
4496
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
4497
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
4498
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
4499
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
4500
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
4501
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
4502
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
4503
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
4504
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
4505
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
4506
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
4507
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
4508
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
4509
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
4510
};
4511
4512
static void
4513
xmlCharacters(xmlParserCtxtPtr ctxt, const xmlChar *buf, int size,
4514
0
              int isBlank) {
4515
0
    int checkBlanks;
4516
4517
0
    if ((ctxt->sax == NULL) || (ctxt->disableSAX))
4518
0
        return;
4519
4520
0
    checkBlanks = (!ctxt->keepBlanks) ||
4521
0
                  (ctxt->sax->ignorableWhitespace != ctxt->sax->characters);
4522
4523
    /*
4524
     * Calling areBlanks with only parts of a text node
4525
     * is fundamentally broken, making the NOBLANKS option
4526
     * essentially unusable.
4527
     */
4528
0
    if ((checkBlanks) &&
4529
0
        (areBlanks(ctxt, buf, size, isBlank))) {
4530
0
        if ((ctxt->sax->ignorableWhitespace != NULL) &&
4531
0
            (ctxt->keepBlanks))
4532
0
            ctxt->sax->ignorableWhitespace(ctxt->userData, buf, size);
4533
0
    } else {
4534
0
        if (ctxt->sax->characters != NULL)
4535
0
            ctxt->sax->characters(ctxt->userData, buf, size);
4536
4537
        /*
4538
         * The old code used to update this value for "complex" data
4539
         * even if checkBlanks was false. This was probably a bug.
4540
         */
4541
0
        if ((checkBlanks) && (*ctxt->space == -1))
4542
0
            *ctxt->space = -2;
4543
0
    }
4544
0
}
4545
4546
/**
4547
 * Parse character data. Always makes progress if the first char isn't
4548
 * '<' or '&'.
4549
 *
4550
 * The right angle bracket (>) may be represented using the string "&gt;",
4551
 * and must, for compatibility, be escaped using "&gt;" or a character
4552
 * reference when it appears in the string "]]>" in content, when that
4553
 * string is not marking the end of a CDATA section.
4554
 *
4555
 *     [14] CharData ::= [^<&]* - ([^<&]* ']]>' [^<&]*)
4556
 * @param ctxt  an XML parser context
4557
 * @param partial  buffer may contain partial UTF-8 sequences
4558
 */
4559
static void
4560
0
xmlParseCharDataInternal(xmlParserCtxtPtr ctxt, int partial) {
4561
0
    const xmlChar *in;
4562
0
    int line = ctxt->input->line;
4563
0
    int col = ctxt->input->col;
4564
0
    int ccol;
4565
0
    int terminate = 0;
4566
4567
0
    GROW;
4568
    /*
4569
     * Accelerated common case where input don't need to be
4570
     * modified before passing it to the handler.
4571
     */
4572
0
    in = ctxt->input->cur;
4573
0
    do {
4574
0
get_more_space:
4575
0
        while (*in == 0x20) { in++; ctxt->input->col++; }
4576
0
        if (*in == 0xA) {
4577
0
            do {
4578
0
                ctxt->input->line++; ctxt->input->col = 1;
4579
0
                in++;
4580
0
            } while (*in == 0xA);
4581
0
            goto get_more_space;
4582
0
        }
4583
0
        if (*in == '<') {
4584
0
            while (in > ctxt->input->cur) {
4585
0
                const xmlChar *tmp = ctxt->input->cur;
4586
0
                size_t nbchar = in - tmp;
4587
4588
0
                if (nbchar > XML_MAX_ITEMS)
4589
0
                    nbchar = XML_MAX_ITEMS;
4590
0
                ctxt->input->cur += nbchar;
4591
4592
0
                xmlCharacters(ctxt, tmp, nbchar, 1);
4593
0
            }
4594
0
            return;
4595
0
        }
4596
4597
0
get_more:
4598
0
        ccol = ctxt->input->col;
4599
0
        while (test_char_data[*in]) {
4600
0
            in++;
4601
0
            ccol++;
4602
0
        }
4603
0
        ctxt->input->col = ccol;
4604
0
        if (*in == 0xA) {
4605
0
            do {
4606
0
                ctxt->input->line++; ctxt->input->col = 1;
4607
0
                in++;
4608
0
            } while (*in == 0xA);
4609
0
            goto get_more;
4610
0
        }
4611
0
        if (*in == ']') {
4612
0
            size_t avail = ctxt->input->end - in;
4613
4614
0
            if (partial && avail < 2) {
4615
0
                terminate = 1;
4616
0
                goto invoke_callback;
4617
0
            }
4618
0
            if (in[1] == ']') {
4619
0
                if (partial && avail < 3) {
4620
0
                    terminate = 1;
4621
0
                    goto invoke_callback;
4622
0
                }
4623
0
                if (in[2] == '>')
4624
0
                    xmlFatalErr(ctxt, XML_ERR_MISPLACED_CDATA_END, NULL);
4625
0
            }
4626
4627
0
            in++;
4628
0
            ctxt->input->col++;
4629
0
            goto get_more;
4630
0
        }
4631
4632
0
invoke_callback:
4633
0
        while (in > ctxt->input->cur) {
4634
0
            const xmlChar *tmp = ctxt->input->cur;
4635
0
            size_t nbchar = in - tmp;
4636
4637
0
            if (nbchar > XML_MAX_ITEMS)
4638
0
                nbchar = XML_MAX_ITEMS;
4639
0
            ctxt->input->cur += nbchar;
4640
4641
0
            xmlCharacters(ctxt, tmp, nbchar, 0);
4642
4643
0
            line = ctxt->input->line;
4644
0
            col = ctxt->input->col;
4645
0
        }
4646
0
        ctxt->input->cur = in;
4647
0
        if (*in == 0xD) {
4648
0
            in++;
4649
0
            if (*in == 0xA) {
4650
0
                ctxt->input->cur = in;
4651
0
                in++;
4652
0
                ctxt->input->line++; ctxt->input->col = 1;
4653
0
                continue; /* while */
4654
0
            }
4655
0
            in--;
4656
0
        }
4657
0
        if (*in == '<') {
4658
0
            return;
4659
0
        }
4660
0
        if (*in == '&') {
4661
0
            return;
4662
0
        }
4663
0
        if (terminate) {
4664
0
            return;
4665
0
        }
4666
0
        SHRINK;
4667
0
        GROW;
4668
0
        in = ctxt->input->cur;
4669
0
    } while (((*in >= 0x20) && (*in <= 0x7F)) ||
4670
0
             (*in == 0x09) || (*in == 0x0a));
4671
0
    ctxt->input->line = line;
4672
0
    ctxt->input->col = col;
4673
0
    xmlParseCharDataComplex(ctxt, partial);
4674
0
}
4675
4676
/**
4677
 * Always makes progress if the first char isn't '<' or '&'.
4678
 *
4679
 * parse a CharData section.this is the fallback function
4680
 * of #xmlParseCharData when the parsing requires handling
4681
 * of non-ASCII characters.
4682
 *
4683
 * @param ctxt  an XML parser context
4684
 * @param partial  whether the input can end with truncated UTF-8
4685
 */
4686
static void
4687
0
xmlParseCharDataComplex(xmlParserCtxtPtr ctxt, int partial) {
4688
0
    xmlChar buf[XML_PARSER_BIG_BUFFER_SIZE + 5];
4689
0
    int nbchar = 0;
4690
0
    int cur, l;
4691
4692
0
    cur = xmlCurrentCharRecover(ctxt, &l);
4693
0
    while ((cur != '<') && /* checked */
4694
0
           (cur != '&') &&
4695
0
     (IS_CHAR(cur))) {
4696
0
        if (cur == ']') {
4697
0
            size_t avail = ctxt->input->end - ctxt->input->cur;
4698
4699
0
            if (partial && avail < 2)
4700
0
                break;
4701
0
            if (NXT(1) == ']') {
4702
0
                if (partial && avail < 3)
4703
0
                    break;
4704
0
                if (NXT(2) == '>')
4705
0
                    xmlFatalErr(ctxt, XML_ERR_MISPLACED_CDATA_END, NULL);
4706
0
            }
4707
0
        }
4708
4709
0
  COPY_BUF(buf, nbchar, cur);
4710
  /* move current position before possible calling of ctxt->sax->characters */
4711
0
  NEXTL(l);
4712
0
  if (nbchar >= XML_PARSER_BIG_BUFFER_SIZE) {
4713
0
      buf[nbchar] = 0;
4714
4715
0
            xmlCharacters(ctxt, buf, nbchar, 0);
4716
0
      nbchar = 0;
4717
0
            SHRINK;
4718
0
  }
4719
0
  cur = xmlCurrentCharRecover(ctxt, &l);
4720
0
    }
4721
0
    if (nbchar != 0) {
4722
0
        buf[nbchar] = 0;
4723
4724
0
        xmlCharacters(ctxt, buf, nbchar, 0);
4725
0
    }
4726
    /*
4727
     * cur == 0 can mean
4728
     *
4729
     * - End of buffer.
4730
     * - An actual 0 character.
4731
     * - An incomplete UTF-8 sequence. This is allowed if partial is set.
4732
     */
4733
0
    if (ctxt->input->cur < ctxt->input->end) {
4734
0
        if ((cur == 0) && (CUR != 0)) {
4735
0
            if (partial == 0) {
4736
0
                xmlFatalErrMsgInt(ctxt, XML_ERR_INVALID_CHAR,
4737
0
                        "Incomplete UTF-8 sequence starting with %02X\n", CUR);
4738
0
                NEXTL(1);
4739
0
            }
4740
0
        } else if ((cur != '<') && (cur != '&') && (cur != ']')) {
4741
            /* Generate the error and skip the offending character */
4742
0
            xmlFatalErrMsgInt(ctxt, XML_ERR_INVALID_CHAR,
4743
0
                              "PCDATA invalid Char value %d\n", cur);
4744
0
            NEXTL(l);
4745
0
        }
4746
0
    }
4747
0
}
4748
4749
/**
4750
 * @deprecated Internal function, don't use.
4751
 * @param ctxt  an XML parser context
4752
 * @param cdata  unused
4753
 */
4754
void
4755
0
xmlParseCharData(xmlParserCtxt *ctxt, ATTRIBUTE_UNUSED int cdata) {
4756
0
    xmlParseCharDataInternal(ctxt, 0);
4757
0
}
4758
4759
/**
4760
 * Parse an External ID or a Public ID
4761
 *
4762
 * @deprecated Internal function, don't use.
4763
 *
4764
 * NOTE: Productions [75] and [83] interact badly since [75] can generate
4765
 * `'PUBLIC' S PubidLiteral S SystemLiteral`
4766
 *
4767
 *     [75] ExternalID ::= 'SYSTEM' S SystemLiteral
4768
 *                       | 'PUBLIC' S PubidLiteral S SystemLiteral
4769
 *
4770
 *     [83] PublicID ::= 'PUBLIC' S PubidLiteral
4771
 *
4772
 * @param ctxt  an XML parser context
4773
 * @param publicId  a xmlChar** receiving PubidLiteral
4774
 * @param strict  indicate whether we should restrict parsing to only
4775
 *          production [75], see NOTE below
4776
 * @returns the function returns SystemLiteral and in the second
4777
 *                case publicID receives PubidLiteral, is strict is off
4778
 *                it is possible to return NULL and have publicID set.
4779
 */
4780
4781
xmlChar *
4782
0
xmlParseExternalID(xmlParserCtxt *ctxt, xmlChar **publicId, int strict) {
4783
0
    xmlChar *URI = NULL;
4784
4785
0
    *publicId = NULL;
4786
0
    if (CMP6(CUR_PTR, 'S', 'Y', 'S', 'T', 'E', 'M')) {
4787
0
        SKIP(6);
4788
0
  if (SKIP_BLANKS == 0) {
4789
0
      xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED,
4790
0
                     "Space required after 'SYSTEM'\n");
4791
0
  }
4792
0
  URI = xmlParseSystemLiteral(ctxt);
4793
0
  if (URI == NULL) {
4794
0
      xmlFatalErr(ctxt, XML_ERR_URI_REQUIRED, NULL);
4795
0
        }
4796
0
    } else if (CMP6(CUR_PTR, 'P', 'U', 'B', 'L', 'I', 'C')) {
4797
0
        SKIP(6);
4798
0
  if (SKIP_BLANKS == 0) {
4799
0
      xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED,
4800
0
        "Space required after 'PUBLIC'\n");
4801
0
  }
4802
0
  *publicId = xmlParsePubidLiteral(ctxt);
4803
0
  if (*publicId == NULL) {
4804
0
      xmlFatalErr(ctxt, XML_ERR_PUBID_REQUIRED, NULL);
4805
0
  }
4806
0
  if (strict) {
4807
      /*
4808
       * We don't handle [83] so "S SystemLiteral" is required.
4809
       */
4810
0
      if (SKIP_BLANKS == 0) {
4811
0
    xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED,
4812
0
      "Space required after the Public Identifier\n");
4813
0
      }
4814
0
  } else {
4815
      /*
4816
       * We handle [83] so we return immediately, if
4817
       * "S SystemLiteral" is not detected. We skip blanks if no
4818
             * system literal was found, but this is harmless since we must
4819
             * be at the end of a NotationDecl.
4820
       */
4821
0
      if (SKIP_BLANKS == 0) return(NULL);
4822
0
      if ((CUR != '\'') && (CUR != '"')) return(NULL);
4823
0
  }
4824
0
  URI = xmlParseSystemLiteral(ctxt);
4825
0
  if (URI == NULL) {
4826
0
      xmlFatalErr(ctxt, XML_ERR_URI_REQUIRED, NULL);
4827
0
        }
4828
0
    }
4829
0
    return(URI);
4830
0
}
4831
4832
/**
4833
 * Skip an XML (SGML) comment <!-- .... -->
4834
 *  The spec says that "For compatibility, the string "--" (double-hyphen)
4835
 *  must not occur within comments. "
4836
 * This is the slow routine in case the accelerator for ascii didn't work
4837
 *
4838
 *     [15] Comment ::= '<!--' ((Char - '-') | ('-' (Char - '-')))* '-->'
4839
 * @param ctxt  an XML parser context
4840
 * @param buf  the already parsed part of the buffer
4841
 * @param len  number of bytes in the buffer
4842
 * @param size  allocated size of the buffer
4843
 */
4844
static void
4845
xmlParseCommentComplex(xmlParserCtxtPtr ctxt, xmlChar *buf,
4846
0
                       size_t len, size_t size) {
4847
0
    int q, ql;
4848
0
    int r, rl;
4849
0
    int cur, l;
4850
0
    int maxLength = (ctxt->options & XML_PARSE_HUGE) ?
4851
0
                    XML_MAX_HUGE_LENGTH :
4852
0
                    XML_MAX_TEXT_LENGTH;
4853
4854
0
    if (buf == NULL) {
4855
0
        len = 0;
4856
0
  size = XML_PARSER_BUFFER_SIZE;
4857
0
  buf = xmlMalloc(size);
4858
0
  if (buf == NULL) {
4859
0
      xmlErrMemory(ctxt);
4860
0
      return;
4861
0
  }
4862
0
    }
4863
0
    q = xmlCurrentCharRecover(ctxt, &ql);
4864
0
    if (q == 0)
4865
0
        goto not_terminated;
4866
0
    if (!IS_CHAR(q)) {
4867
0
        xmlFatalErrMsgInt(ctxt, XML_ERR_INVALID_CHAR,
4868
0
                          "xmlParseComment: invalid xmlChar value %d\n",
4869
0
                    q);
4870
0
  xmlFree (buf);
4871
0
  return;
4872
0
    }
4873
0
    NEXTL(ql);
4874
0
    r = xmlCurrentCharRecover(ctxt, &rl);
4875
0
    if (r == 0)
4876
0
        goto not_terminated;
4877
0
    if (!IS_CHAR(r)) {
4878
0
        xmlFatalErrMsgInt(ctxt, XML_ERR_INVALID_CHAR,
4879
0
                          "xmlParseComment: invalid xmlChar value %d\n",
4880
0
                    r);
4881
0
  xmlFree (buf);
4882
0
  return;
4883
0
    }
4884
0
    NEXTL(rl);
4885
0
    cur = xmlCurrentCharRecover(ctxt, &l);
4886
0
    if (cur == 0)
4887
0
        goto not_terminated;
4888
0
    while (IS_CHAR(cur) && /* checked */
4889
0
           ((cur != '>') ||
4890
0
      (r != '-') || (q != '-'))) {
4891
0
  if ((r == '-') && (q == '-')) {
4892
0
      xmlFatalErr(ctxt, XML_ERR_HYPHEN_IN_COMMENT, NULL);
4893
0
  }
4894
0
  if (len + 5 >= size) {
4895
0
      xmlChar *tmp;
4896
0
            int newSize;
4897
4898
0
      newSize = xmlGrowCapacity(size, 1, 1, maxLength);
4899
0
            if (newSize < 0) {
4900
0
                xmlFatalErrMsgStr(ctxt, XML_ERR_COMMENT_NOT_FINISHED,
4901
0
                             "Comment too big found", NULL);
4902
0
                xmlFree (buf);
4903
0
                return;
4904
0
            }
4905
0
      tmp = xmlRealloc(buf, newSize);
4906
0
      if (tmp == NULL) {
4907
0
    xmlErrMemory(ctxt);
4908
0
    xmlFree(buf);
4909
0
    return;
4910
0
      }
4911
0
      buf = tmp;
4912
0
            size = newSize;
4913
0
  }
4914
0
  COPY_BUF(buf, len, q);
4915
4916
0
  q = r;
4917
0
  ql = rl;
4918
0
  r = cur;
4919
0
  rl = l;
4920
4921
0
  NEXTL(l);
4922
0
  cur = xmlCurrentCharRecover(ctxt, &l);
4923
4924
0
    }
4925
0
    buf[len] = 0;
4926
0
    if (cur == 0) {
4927
0
  xmlFatalErrMsgStr(ctxt, XML_ERR_COMMENT_NOT_FINISHED,
4928
0
                       "Comment not terminated \n<!--%.50s\n", buf);
4929
0
    } else if (!IS_CHAR(cur)) {
4930
0
        xmlFatalErrMsgInt(ctxt, XML_ERR_INVALID_CHAR,
4931
0
                          "xmlParseComment: invalid xmlChar value %d\n",
4932
0
                    cur);
4933
0
    } else {
4934
0
        NEXT;
4935
0
  if ((ctxt->sax != NULL) && (ctxt->sax->comment != NULL) &&
4936
0
      (!ctxt->disableSAX))
4937
0
      ctxt->sax->comment(ctxt->userData, buf);
4938
0
    }
4939
0
    xmlFree(buf);
4940
0
    return;
4941
0
not_terminated:
4942
0
    xmlFatalErrMsgStr(ctxt, XML_ERR_COMMENT_NOT_FINISHED,
4943
0
       "Comment not terminated\n", NULL);
4944
0
    xmlFree(buf);
4945
0
}
4946
4947
/**
4948
 * Parse an XML (SGML) comment. Always consumes '<!'.
4949
 *
4950
 * @deprecated Internal function, don't use.
4951
 *
4952
 *  The spec says that "For compatibility, the string "--" (double-hyphen)
4953
 *  must not occur within comments. "
4954
 *
4955
 *     [15] Comment ::= '<!--' ((Char - '-') | ('-' (Char - '-')))* '-->'
4956
 * @param ctxt  an XML parser context
4957
 */
4958
void
4959
0
xmlParseComment(xmlParserCtxt *ctxt) {
4960
0
    xmlChar *buf = NULL;
4961
0
    size_t size = XML_PARSER_BUFFER_SIZE;
4962
0
    size_t len = 0;
4963
0
    size_t maxLength = (ctxt->options & XML_PARSE_HUGE) ?
4964
0
                       XML_MAX_HUGE_LENGTH :
4965
0
                       XML_MAX_TEXT_LENGTH;
4966
0
    const xmlChar *in;
4967
0
    size_t nbchar = 0;
4968
0
    int ccol;
4969
4970
    /*
4971
     * Check that there is a comment right here.
4972
     */
4973
0
    if ((RAW != '<') || (NXT(1) != '!'))
4974
0
        return;
4975
0
    SKIP(2);
4976
0
    if ((RAW != '-') || (NXT(1) != '-'))
4977
0
        return;
4978
0
    SKIP(2);
4979
0
    GROW;
4980
4981
    /*
4982
     * Accelerated common case where input don't need to be
4983
     * modified before passing it to the handler.
4984
     */
4985
0
    in = ctxt->input->cur;
4986
0
    do {
4987
0
  if (*in == 0xA) {
4988
0
      do {
4989
0
    ctxt->input->line++; ctxt->input->col = 1;
4990
0
    in++;
4991
0
      } while (*in == 0xA);
4992
0
  }
4993
0
get_more:
4994
0
        ccol = ctxt->input->col;
4995
0
  while (((*in > '-') && (*in <= 0x7F)) ||
4996
0
         ((*in >= 0x20) && (*in < '-')) ||
4997
0
         (*in == 0x09)) {
4998
0
        in++;
4999
0
        ccol++;
5000
0
  }
5001
0
  ctxt->input->col = ccol;
5002
0
  if (*in == 0xA) {
5003
0
      do {
5004
0
    ctxt->input->line++; ctxt->input->col = 1;
5005
0
    in++;
5006
0
      } while (*in == 0xA);
5007
0
      goto get_more;
5008
0
  }
5009
0
  nbchar = in - ctxt->input->cur;
5010
  /*
5011
   * save current set of data
5012
   */
5013
0
  if (nbchar > 0) {
5014
0
            if (nbchar > maxLength - len) {
5015
0
                xmlFatalErrMsgStr(ctxt, XML_ERR_COMMENT_NOT_FINISHED,
5016
0
                                  "Comment too big found", NULL);
5017
0
                xmlFree(buf);
5018
0
                return;
5019
0
            }
5020
0
            if (buf == NULL) {
5021
0
                if ((*in == '-') && (in[1] == '-'))
5022
0
                    size = nbchar + 1;
5023
0
                else
5024
0
                    size = XML_PARSER_BUFFER_SIZE + nbchar;
5025
0
                buf = xmlMalloc(size);
5026
0
                if (buf == NULL) {
5027
0
                    xmlErrMemory(ctxt);
5028
0
                    return;
5029
0
                }
5030
0
                len = 0;
5031
0
            } else if (len + nbchar + 1 >= size) {
5032
0
                xmlChar *new_buf;
5033
0
                size += len + nbchar + XML_PARSER_BUFFER_SIZE;
5034
0
                new_buf = xmlRealloc(buf, size);
5035
0
                if (new_buf == NULL) {
5036
0
                    xmlErrMemory(ctxt);
5037
0
                    xmlFree(buf);
5038
0
                    return;
5039
0
                }
5040
0
                buf = new_buf;
5041
0
            }
5042
0
            memcpy(&buf[len], ctxt->input->cur, nbchar);
5043
0
            len += nbchar;
5044
0
            buf[len] = 0;
5045
0
  }
5046
0
  ctxt->input->cur = in;
5047
0
  if (*in == 0xA) {
5048
0
      in++;
5049
0
      ctxt->input->line++; ctxt->input->col = 1;
5050
0
  }
5051
0
  if (*in == 0xD) {
5052
0
      in++;
5053
0
      if (*in == 0xA) {
5054
0
    ctxt->input->cur = in;
5055
0
    in++;
5056
0
    ctxt->input->line++; ctxt->input->col = 1;
5057
0
    goto get_more;
5058
0
      }
5059
0
      in--;
5060
0
  }
5061
0
  SHRINK;
5062
0
  GROW;
5063
0
  in = ctxt->input->cur;
5064
0
  if (*in == '-') {
5065
0
      if (in[1] == '-') {
5066
0
          if (in[2] == '>') {
5067
0
        SKIP(3);
5068
0
        if ((ctxt->sax != NULL) && (ctxt->sax->comment != NULL) &&
5069
0
            (!ctxt->disableSAX)) {
5070
0
      if (buf != NULL)
5071
0
          ctxt->sax->comment(ctxt->userData, buf);
5072
0
      else
5073
0
          ctxt->sax->comment(ctxt->userData, BAD_CAST "");
5074
0
        }
5075
0
        if (buf != NULL)
5076
0
            xmlFree(buf);
5077
0
        return;
5078
0
    }
5079
0
    if (buf != NULL) {
5080
0
        xmlFatalErrMsgStr(ctxt, XML_ERR_HYPHEN_IN_COMMENT,
5081
0
                          "Double hyphen within comment: "
5082
0
                                      "<!--%.50s\n",
5083
0
              buf);
5084
0
    } else
5085
0
        xmlFatalErrMsgStr(ctxt, XML_ERR_HYPHEN_IN_COMMENT,
5086
0
                          "Double hyphen within comment\n", NULL);
5087
0
    in++;
5088
0
    ctxt->input->col++;
5089
0
      }
5090
0
      in++;
5091
0
      ctxt->input->col++;
5092
0
      goto get_more;
5093
0
  }
5094
0
    } while (((*in >= 0x20) && (*in <= 0x7F)) || (*in == 0x09) || (*in == 0x0a));
5095
0
    xmlParseCommentComplex(ctxt, buf, len, size);
5096
0
}
5097
5098
5099
/**
5100
 * parse the name of a PI
5101
 *
5102
 * @deprecated Internal function, don't use.
5103
 *
5104
 *     [17] PITarget ::= Name - (('X' | 'x') ('M' | 'm') ('L' | 'l'))
5105
 *
5106
 * @param ctxt  an XML parser context
5107
 * @returns the PITarget name or NULL
5108
 */
5109
5110
const xmlChar *
5111
0
xmlParsePITarget(xmlParserCtxt *ctxt) {
5112
0
    const xmlChar *name;
5113
5114
0
    name = xmlParseName(ctxt);
5115
0
    if ((name != NULL) &&
5116
0
        ((name[0] == 'x') || (name[0] == 'X')) &&
5117
0
        ((name[1] == 'm') || (name[1] == 'M')) &&
5118
0
        ((name[2] == 'l') || (name[2] == 'L'))) {
5119
0
  int i;
5120
0
  if ((name[0] == 'x') && (name[1] == 'm') &&
5121
0
      (name[2] == 'l') && (name[3] == 0)) {
5122
0
      xmlFatalErrMsg(ctxt, XML_ERR_RESERVED_XML_NAME,
5123
0
     "XML declaration allowed only at the start of the document\n");
5124
0
      return(name);
5125
0
  } else if (name[3] == 0) {
5126
0
      xmlFatalErr(ctxt, XML_ERR_RESERVED_XML_NAME, NULL);
5127
0
      return(name);
5128
0
  }
5129
0
  for (i = 0;;i++) {
5130
0
      if (xmlW3CPIs[i] == NULL) break;
5131
0
      if (xmlStrEqual(name, (const xmlChar *)xmlW3CPIs[i]))
5132
0
          return(name);
5133
0
  }
5134
0
  xmlWarningMsg(ctxt, XML_ERR_RESERVED_XML_NAME,
5135
0
          "xmlParsePITarget: invalid name prefix 'xml'\n",
5136
0
          NULL, NULL);
5137
0
    }
5138
0
    if ((name != NULL) && (xmlStrchr(name, ':') != NULL)) {
5139
0
  xmlNsErr(ctxt, XML_NS_ERR_COLON,
5140
0
     "colons are forbidden from PI names '%s'\n", name, NULL, NULL);
5141
0
    }
5142
0
    return(name);
5143
0
}
5144
5145
#ifdef LIBXML_CATALOG_ENABLED
5146
/**
5147
 * parse an XML Catalog Processing Instruction.
5148
 *
5149
 * <?oasis-xml-catalog catalog="http://example.com/catalog.xml"?>
5150
 *
5151
 * Occurs only if allowed by the user and if happening in the Misc
5152
 * part of the document before any doctype information
5153
 * This will add the given catalog to the parsing context in order
5154
 * to be used if there is a resolution need further down in the document
5155
 *
5156
 * @param ctxt  an XML parser context
5157
 * @param catalog  the PI value string
5158
 */
5159
5160
static void
5161
0
xmlParseCatalogPI(xmlParserCtxtPtr ctxt, const xmlChar *catalog) {
5162
0
    xmlChar *URL = NULL;
5163
0
    const xmlChar *tmp, *base;
5164
0
    xmlChar marker;
5165
5166
0
    tmp = catalog;
5167
0
    while (IS_BLANK_CH(*tmp)) tmp++;
5168
0
    if (xmlStrncmp(tmp, BAD_CAST"catalog", 7))
5169
0
  goto error;
5170
0
    tmp += 7;
5171
0
    while (IS_BLANK_CH(*tmp)) tmp++;
5172
0
    if (*tmp != '=') {
5173
0
  return;
5174
0
    }
5175
0
    tmp++;
5176
0
    while (IS_BLANK_CH(*tmp)) tmp++;
5177
0
    marker = *tmp;
5178
0
    if ((marker != '\'') && (marker != '"'))
5179
0
  goto error;
5180
0
    tmp++;
5181
0
    base = tmp;
5182
0
    while ((*tmp != 0) && (*tmp != marker)) tmp++;
5183
0
    if (*tmp == 0)
5184
0
  goto error;
5185
0
    URL = xmlStrndup(base, tmp - base);
5186
0
    tmp++;
5187
0
    while (IS_BLANK_CH(*tmp)) tmp++;
5188
0
    if (*tmp != 0)
5189
0
  goto error;
5190
5191
0
    if (URL != NULL) {
5192
        /*
5193
         * Unfortunately, the catalog API doesn't report OOM errors.
5194
         * xmlGetLastError isn't very helpful since we don't know
5195
         * where the last error came from. We'd have to reset it
5196
         * before this call and restore it afterwards.
5197
         */
5198
0
  ctxt->catalogs = xmlCatalogAddLocal(ctxt->catalogs, URL);
5199
0
  xmlFree(URL);
5200
0
    }
5201
0
    return;
5202
5203
0
error:
5204
0
    xmlWarningMsg(ctxt, XML_WAR_CATALOG_PI,
5205
0
            "Catalog PI syntax error: %s\n",
5206
0
      catalog, NULL);
5207
0
    if (URL != NULL)
5208
0
  xmlFree(URL);
5209
0
}
5210
#endif
5211
5212
/**
5213
 * parse an XML Processing Instruction.
5214
 *
5215
 * @deprecated Internal function, don't use.
5216
 *
5217
 *     [16] PI ::= '<?' PITarget (S (Char* - (Char* '?>' Char*)))? '?>'
5218
 *
5219
 * The processing is transferred to SAX once parsed.
5220
 *
5221
 * @param ctxt  an XML parser context
5222
 */
5223
5224
void
5225
0
xmlParsePI(xmlParserCtxt *ctxt) {
5226
0
    xmlChar *buf = NULL;
5227
0
    size_t len = 0;
5228
0
    size_t size = XML_PARSER_BUFFER_SIZE;
5229
0
    size_t maxLength = (ctxt->options & XML_PARSE_HUGE) ?
5230
0
                       XML_MAX_HUGE_LENGTH :
5231
0
                       XML_MAX_TEXT_LENGTH;
5232
0
    int cur, l;
5233
0
    const xmlChar *target;
5234
5235
0
    if ((RAW == '<') && (NXT(1) == '?')) {
5236
  /*
5237
   * this is a Processing Instruction.
5238
   */
5239
0
  SKIP(2);
5240
5241
  /*
5242
   * Parse the target name and check for special support like
5243
   * namespace.
5244
   */
5245
0
        target = xmlParsePITarget(ctxt);
5246
0
  if (target != NULL) {
5247
0
      if ((RAW == '?') && (NXT(1) == '>')) {
5248
0
    SKIP(2);
5249
5250
    /*
5251
     * SAX: PI detected.
5252
     */
5253
0
    if ((ctxt->sax) && (!ctxt->disableSAX) &&
5254
0
        (ctxt->sax->processingInstruction != NULL))
5255
0
        ctxt->sax->processingInstruction(ctxt->userData,
5256
0
                                         target, NULL);
5257
0
    return;
5258
0
      }
5259
0
      buf = xmlMalloc(size);
5260
0
      if (buf == NULL) {
5261
0
    xmlErrMemory(ctxt);
5262
0
    return;
5263
0
      }
5264
0
      if (SKIP_BLANKS == 0) {
5265
0
    xmlFatalErrMsgStr(ctxt, XML_ERR_SPACE_REQUIRED,
5266
0
        "ParsePI: PI %s space expected\n", target);
5267
0
      }
5268
0
      cur = xmlCurrentCharRecover(ctxt, &l);
5269
0
      while (IS_CHAR(cur) && /* checked */
5270
0
       ((cur != '?') || (NXT(1) != '>'))) {
5271
0
    if (len + 5 >= size) {
5272
0
        xmlChar *tmp;
5273
0
                    int newSize;
5274
5275
0
                    newSize = xmlGrowCapacity(size, 1, 1, maxLength);
5276
0
                    if (newSize < 0) {
5277
0
                        xmlFatalErrMsgStr(ctxt, XML_ERR_PI_NOT_FINISHED,
5278
0
                                          "PI %s too big found", target);
5279
0
                        xmlFree(buf);
5280
0
                        return;
5281
0
                    }
5282
0
        tmp = xmlRealloc(buf, newSize);
5283
0
        if (tmp == NULL) {
5284
0
      xmlErrMemory(ctxt);
5285
0
      xmlFree(buf);
5286
0
      return;
5287
0
        }
5288
0
        buf = tmp;
5289
0
                    size = newSize;
5290
0
    }
5291
0
    COPY_BUF(buf, len, cur);
5292
0
    NEXTL(l);
5293
0
    cur = xmlCurrentCharRecover(ctxt, &l);
5294
0
      }
5295
0
      buf[len] = 0;
5296
0
      if (cur != '?') {
5297
0
    xmlFatalErrMsgStr(ctxt, XML_ERR_PI_NOT_FINISHED,
5298
0
          "ParsePI: PI %s never end ...\n", target);
5299
0
      } else {
5300
0
    SKIP(2);
5301
5302
0
#ifdef LIBXML_CATALOG_ENABLED
5303
0
    if ((ctxt->inSubset == 0) &&
5304
0
        (xmlStrEqual(target, XML_CATALOG_PI))) {
5305
0
        xmlCatalogAllow allow = xmlCatalogGetDefaults();
5306
5307
0
        if ((ctxt->options & XML_PARSE_CATALOG_PI) &&
5308
0
                        ((allow == XML_CATA_ALLOW_DOCUMENT) ||
5309
0
       (allow == XML_CATA_ALLOW_ALL)))
5310
0
      xmlParseCatalogPI(ctxt, buf);
5311
0
    }
5312
0
#endif
5313
5314
    /*
5315
     * SAX: PI detected.
5316
     */
5317
0
    if ((ctxt->sax) && (!ctxt->disableSAX) &&
5318
0
        (ctxt->sax->processingInstruction != NULL))
5319
0
        ctxt->sax->processingInstruction(ctxt->userData,
5320
0
                                         target, buf);
5321
0
      }
5322
0
      xmlFree(buf);
5323
0
  } else {
5324
0
      xmlFatalErr(ctxt, XML_ERR_PI_NOT_STARTED, NULL);
5325
0
  }
5326
0
    }
5327
0
}
5328
5329
/**
5330
 * Parse a notation declaration. Always consumes '<!'.
5331
 *
5332
 * @deprecated Internal function, don't use.
5333
 *
5334
 *     [82] NotationDecl ::= '<!NOTATION' S Name S (ExternalID |  PublicID)
5335
 *                           S? '>'
5336
 *
5337
 * Hence there is actually 3 choices:
5338
 *
5339
 *     'PUBLIC' S PubidLiteral
5340
 *     'PUBLIC' S PubidLiteral S SystemLiteral
5341
 *     'SYSTEM' S SystemLiteral
5342
 *
5343
 * See the NOTE on #xmlParseExternalID.
5344
 *
5345
 * @param ctxt  an XML parser context
5346
 */
5347
5348
void
5349
0
xmlParseNotationDecl(xmlParserCtxt *ctxt) {
5350
0
    const xmlChar *name;
5351
0
    xmlChar *Pubid;
5352
0
    xmlChar *Systemid;
5353
5354
0
    if ((CUR != '<') || (NXT(1) != '!'))
5355
0
        return;
5356
0
    SKIP(2);
5357
5358
0
    if (CMP8(CUR_PTR, 'N', 'O', 'T', 'A', 'T', 'I', 'O', 'N')) {
5359
0
#ifdef LIBXML_VALID_ENABLED
5360
0
  int oldInputNr = ctxt->inputNr;
5361
0
#endif
5362
5363
0
  SKIP(8);
5364
0
  if (SKIP_BLANKS_PE == 0) {
5365
0
      xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED,
5366
0
         "Space required after '<!NOTATION'\n");
5367
0
      return;
5368
0
  }
5369
5370
0
        name = xmlParseName(ctxt);
5371
0
  if (name == NULL) {
5372
0
      xmlFatalErr(ctxt, XML_ERR_NOTATION_NOT_STARTED, NULL);
5373
0
      return;
5374
0
  }
5375
0
  if (xmlStrchr(name, ':') != NULL) {
5376
0
      xmlNsErr(ctxt, XML_NS_ERR_COLON,
5377
0
         "colons are forbidden from notation names '%s'\n",
5378
0
         name, NULL, NULL);
5379
0
  }
5380
0
  if (SKIP_BLANKS_PE == 0) {
5381
0
      xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED,
5382
0
         "Space required after the NOTATION name'\n");
5383
0
      return;
5384
0
  }
5385
5386
  /*
5387
   * Parse the IDs.
5388
   */
5389
0
  Systemid = xmlParseExternalID(ctxt, &Pubid, 0);
5390
0
  SKIP_BLANKS_PE;
5391
5392
0
  if (RAW == '>') {
5393
0
#ifdef LIBXML_VALID_ENABLED
5394
0
      if ((ctxt->validate) && (ctxt->inputNr > oldInputNr)) {
5395
0
    xmlValidityError(ctxt, XML_ERR_ENTITY_BOUNDARY,
5396
0
                           "Notation declaration doesn't start and stop"
5397
0
                                 " in the same entity\n",
5398
0
                                 NULL, NULL);
5399
0
      }
5400
0
#endif
5401
0
      NEXT;
5402
0
      if ((ctxt->sax != NULL) && (!ctxt->disableSAX) &&
5403
0
    (ctxt->sax->notationDecl != NULL))
5404
0
    ctxt->sax->notationDecl(ctxt->userData, name, Pubid, Systemid);
5405
0
  } else {
5406
0
      xmlFatalErr(ctxt, XML_ERR_NOTATION_NOT_FINISHED, NULL);
5407
0
  }
5408
0
  if (Systemid != NULL) xmlFree(Systemid);
5409
0
  if (Pubid != NULL) xmlFree(Pubid);
5410
0
    }
5411
0
}
5412
5413
/**
5414
 * Parse an entity declaration. Always consumes '<!'.
5415
 *
5416
 * @deprecated Internal function, don't use.
5417
 *
5418
 *     [70] EntityDecl ::= GEDecl | PEDecl
5419
 *
5420
 *     [71] GEDecl ::= '<!ENTITY' S Name S EntityDef S? '>'
5421
 *
5422
 *     [72] PEDecl ::= '<!ENTITY' S '%' S Name S PEDef S? '>'
5423
 *
5424
 *     [73] EntityDef ::= EntityValue | (ExternalID NDataDecl?)
5425
 *
5426
 *     [74] PEDef ::= EntityValue | ExternalID
5427
 *
5428
 *     [76] NDataDecl ::= S 'NDATA' S Name
5429
 *
5430
 * [ VC: Notation Declared ]
5431
 * The Name must match the declared name of a notation.
5432
 *
5433
 * @param ctxt  an XML parser context
5434
 */
5435
5436
void
5437
0
xmlParseEntityDecl(xmlParserCtxt *ctxt) {
5438
0
    const xmlChar *name = NULL;
5439
0
    xmlChar *value = NULL;
5440
0
    xmlChar *URI = NULL, *literal = NULL;
5441
0
    const xmlChar *ndata = NULL;
5442
0
    int isParameter = 0;
5443
0
    xmlChar *orig = NULL;
5444
5445
0
    if ((CUR != '<') || (NXT(1) != '!'))
5446
0
        return;
5447
0
    SKIP(2);
5448
5449
    /* GROW; done in the caller */
5450
0
    if (CMP6(CUR_PTR, 'E', 'N', 'T', 'I', 'T', 'Y')) {
5451
0
#ifdef LIBXML_VALID_ENABLED
5452
0
  int oldInputNr = ctxt->inputNr;
5453
0
#endif
5454
5455
0
  SKIP(6);
5456
0
  if (SKIP_BLANKS_PE == 0) {
5457
0
      xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED,
5458
0
         "Space required after '<!ENTITY'\n");
5459
0
  }
5460
5461
0
  if (RAW == '%') {
5462
0
      NEXT;
5463
0
      if (SKIP_BLANKS_PE == 0) {
5464
0
    xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED,
5465
0
             "Space required after '%%'\n");
5466
0
      }
5467
0
      isParameter = 1;
5468
0
  }
5469
5470
0
        name = xmlParseName(ctxt);
5471
0
  if (name == NULL) {
5472
0
      xmlFatalErrMsg(ctxt, XML_ERR_NAME_REQUIRED,
5473
0
                     "xmlParseEntityDecl: no name\n");
5474
0
            return;
5475
0
  }
5476
0
  if (xmlStrchr(name, ':') != NULL) {
5477
0
      xmlNsErr(ctxt, XML_NS_ERR_COLON,
5478
0
         "colons are forbidden from entities names '%s'\n",
5479
0
         name, NULL, NULL);
5480
0
  }
5481
0
  if (SKIP_BLANKS_PE == 0) {
5482
0
      xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED,
5483
0
         "Space required after the entity name\n");
5484
0
  }
5485
5486
  /*
5487
   * handle the various case of definitions...
5488
   */
5489
0
  if (isParameter) {
5490
0
      if ((RAW == '"') || (RAW == '\'')) {
5491
0
          value = xmlParseEntityValue(ctxt, &orig);
5492
0
    if (value) {
5493
0
        if ((ctxt->sax != NULL) &&
5494
0
      (!ctxt->disableSAX) && (ctxt->sax->entityDecl != NULL))
5495
0
      ctxt->sax->entityDecl(ctxt->userData, name,
5496
0
                        XML_INTERNAL_PARAMETER_ENTITY,
5497
0
            NULL, NULL, value);
5498
0
    }
5499
0
      } else {
5500
0
          URI = xmlParseExternalID(ctxt, &literal, 1);
5501
0
    if ((URI == NULL) && (literal == NULL)) {
5502
0
        xmlFatalErr(ctxt, XML_ERR_VALUE_REQUIRED, NULL);
5503
0
    }
5504
0
    if (URI) {
5505
0
                    if (xmlStrchr(URI, '#')) {
5506
0
                        xmlFatalErr(ctxt, XML_ERR_URI_FRAGMENT, NULL);
5507
0
                    } else {
5508
0
                        if ((ctxt->sax != NULL) &&
5509
0
                            (!ctxt->disableSAX) &&
5510
0
                            (ctxt->sax->entityDecl != NULL))
5511
0
                            ctxt->sax->entityDecl(ctxt->userData, name,
5512
0
                                        XML_EXTERNAL_PARAMETER_ENTITY,
5513
0
                                        literal, URI, NULL);
5514
0
                    }
5515
0
    }
5516
0
      }
5517
0
  } else {
5518
0
      if ((RAW == '"') || (RAW == '\'')) {
5519
0
          value = xmlParseEntityValue(ctxt, &orig);
5520
0
    if ((ctxt->sax != NULL) &&
5521
0
        (!ctxt->disableSAX) && (ctxt->sax->entityDecl != NULL))
5522
0
        ctxt->sax->entityDecl(ctxt->userData, name,
5523
0
        XML_INTERNAL_GENERAL_ENTITY,
5524
0
        NULL, NULL, value);
5525
    /*
5526
     * For expat compatibility in SAX mode.
5527
     */
5528
0
    if ((ctxt->myDoc == NULL) ||
5529
0
        (xmlStrEqual(ctxt->myDoc->version, SAX_COMPAT_MODE))) {
5530
0
        if (ctxt->myDoc == NULL) {
5531
0
      ctxt->myDoc = xmlNewDoc(SAX_COMPAT_MODE);
5532
0
      if (ctxt->myDoc == NULL) {
5533
0
          xmlErrMemory(ctxt);
5534
0
          goto done;
5535
0
      }
5536
0
      ctxt->myDoc->properties = XML_DOC_INTERNAL;
5537
0
        }
5538
0
        if (ctxt->myDoc->intSubset == NULL) {
5539
0
      ctxt->myDoc->intSubset = xmlNewDtd(ctxt->myDoc,
5540
0
              BAD_CAST "fake", NULL, NULL);
5541
0
                        if (ctxt->myDoc->intSubset == NULL) {
5542
0
                            xmlErrMemory(ctxt);
5543
0
                            goto done;
5544
0
                        }
5545
0
                    }
5546
5547
0
        xmlSAX2EntityDecl(ctxt, name, XML_INTERNAL_GENERAL_ENTITY,
5548
0
                    NULL, NULL, value);
5549
0
    }
5550
0
      } else {
5551
0
          URI = xmlParseExternalID(ctxt, &literal, 1);
5552
0
    if ((URI == NULL) && (literal == NULL)) {
5553
0
        xmlFatalErr(ctxt, XML_ERR_VALUE_REQUIRED, NULL);
5554
0
    }
5555
0
    if (URI) {
5556
0
                    if (xmlStrchr(URI, '#')) {
5557
0
                        xmlFatalErr(ctxt, XML_ERR_URI_FRAGMENT, NULL);
5558
0
                    }
5559
0
    }
5560
0
    if ((RAW != '>') && (SKIP_BLANKS_PE == 0)) {
5561
0
        xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED,
5562
0
           "Space required before 'NDATA'\n");
5563
0
    }
5564
0
    if (CMP5(CUR_PTR, 'N', 'D', 'A', 'T', 'A')) {
5565
0
        SKIP(5);
5566
0
        if (SKIP_BLANKS_PE == 0) {
5567
0
      xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED,
5568
0
               "Space required after 'NDATA'\n");
5569
0
        }
5570
0
        ndata = xmlParseName(ctxt);
5571
0
        if ((ctxt->sax != NULL) && (!ctxt->disableSAX) &&
5572
0
            (ctxt->sax->unparsedEntityDecl != NULL))
5573
0
      ctxt->sax->unparsedEntityDecl(ctxt->userData, name,
5574
0
            literal, URI, ndata);
5575
0
    } else {
5576
0
        if ((ctxt->sax != NULL) &&
5577
0
            (!ctxt->disableSAX) && (ctxt->sax->entityDecl != NULL))
5578
0
      ctxt->sax->entityDecl(ctxt->userData, name,
5579
0
            XML_EXTERNAL_GENERAL_PARSED_ENTITY,
5580
0
            literal, URI, NULL);
5581
        /*
5582
         * For expat compatibility in SAX mode.
5583
         * assuming the entity replacement was asked for
5584
         */
5585
0
        if ((ctxt->replaceEntities != 0) &&
5586
0
      ((ctxt->myDoc == NULL) ||
5587
0
      (xmlStrEqual(ctxt->myDoc->version, SAX_COMPAT_MODE)))) {
5588
0
      if (ctxt->myDoc == NULL) {
5589
0
          ctxt->myDoc = xmlNewDoc(SAX_COMPAT_MODE);
5590
0
          if (ctxt->myDoc == NULL) {
5591
0
              xmlErrMemory(ctxt);
5592
0
        goto done;
5593
0
          }
5594
0
          ctxt->myDoc->properties = XML_DOC_INTERNAL;
5595
0
      }
5596
5597
0
      if (ctxt->myDoc->intSubset == NULL) {
5598
0
          ctxt->myDoc->intSubset = xmlNewDtd(ctxt->myDoc,
5599
0
            BAD_CAST "fake", NULL, NULL);
5600
0
                            if (ctxt->myDoc->intSubset == NULL) {
5601
0
                                xmlErrMemory(ctxt);
5602
0
                                goto done;
5603
0
                            }
5604
0
                        }
5605
0
      xmlSAX2EntityDecl(ctxt, name,
5606
0
                  XML_EXTERNAL_GENERAL_PARSED_ENTITY,
5607
0
                  literal, URI, NULL);
5608
0
        }
5609
0
    }
5610
0
      }
5611
0
  }
5612
0
  SKIP_BLANKS_PE;
5613
0
  if (RAW != '>') {
5614
0
      xmlFatalErrMsgStr(ctxt, XML_ERR_ENTITY_NOT_FINISHED,
5615
0
              "xmlParseEntityDecl: entity %s not terminated\n", name);
5616
0
      xmlHaltParser(ctxt);
5617
0
  } else {
5618
0
#ifdef LIBXML_VALID_ENABLED
5619
0
      if ((ctxt->validate) && (ctxt->inputNr > oldInputNr)) {
5620
0
    xmlValidityError(ctxt, XML_ERR_ENTITY_BOUNDARY,
5621
0
                           "Entity declaration doesn't start and stop in"
5622
0
                                 " the same entity\n",
5623
0
                                 NULL, NULL);
5624
0
      }
5625
0
#endif
5626
0
      NEXT;
5627
0
  }
5628
0
  if (orig != NULL) {
5629
      /*
5630
       * Ugly mechanism to save the raw entity value.
5631
       */
5632
0
      xmlEntityPtr cur = NULL;
5633
5634
0
      if (isParameter) {
5635
0
          if ((ctxt->sax != NULL) &&
5636
0
        (ctxt->sax->getParameterEntity != NULL))
5637
0
        cur = ctxt->sax->getParameterEntity(ctxt->userData, name);
5638
0
      } else {
5639
0
          if ((ctxt->sax != NULL) &&
5640
0
        (ctxt->sax->getEntity != NULL))
5641
0
        cur = ctxt->sax->getEntity(ctxt->userData, name);
5642
0
    if ((cur == NULL) && (ctxt->userData==ctxt)) {
5643
0
        cur = xmlSAX2GetEntity(ctxt, name);
5644
0
    }
5645
0
      }
5646
0
            if ((cur != NULL) && (cur->orig == NULL)) {
5647
0
    cur->orig = orig;
5648
0
                orig = NULL;
5649
0
      }
5650
0
  }
5651
5652
0
done:
5653
0
  if (value != NULL) xmlFree(value);
5654
0
  if (URI != NULL) xmlFree(URI);
5655
0
  if (literal != NULL) xmlFree(literal);
5656
0
        if (orig != NULL) xmlFree(orig);
5657
0
    }
5658
0
}
5659
5660
/**
5661
 * Parse an attribute default declaration
5662
 *
5663
 * @deprecated Internal function, don't use.
5664
 *
5665
 *     [60] DefaultDecl ::= '#REQUIRED' | '#IMPLIED' | (('#FIXED' S)? AttValue)
5666
 *
5667
 * [ VC: Required Attribute ]
5668
 * if the default declaration is the keyword \#REQUIRED, then the
5669
 * attribute must be specified for all elements of the type in the
5670
 * attribute-list declaration.
5671
 *
5672
 * [ VC: Attribute Default Legal ]
5673
 * The declared default value must meet the lexical constraints of
5674
 * the declared attribute type c.f. #xmlValidateAttributeDecl
5675
 *
5676
 * [ VC: Fixed Attribute Default ]
5677
 * if an attribute has a default value declared with the \#FIXED
5678
 * keyword, instances of that attribute must match the default value.
5679
 *
5680
 * [ WFC: No < in Attribute Values ]
5681
 * handled in #xmlParseAttValue
5682
 *
5683
 * @param ctxt  an XML parser context
5684
 * @param value  Receive a possible fixed default value for the attribute
5685
 * @returns XML_ATTRIBUTE_NONE, XML_ATTRIBUTE_REQUIRED, XML_ATTRIBUTE_IMPLIED
5686
 *          or XML_ATTRIBUTE_FIXED.
5687
 */
5688
5689
int
5690
0
xmlParseDefaultDecl(xmlParserCtxt *ctxt, xmlChar **value) {
5691
0
    int val;
5692
0
    xmlChar *ret;
5693
5694
0
    *value = NULL;
5695
0
    if (CMP9(CUR_PTR, '#', 'R', 'E', 'Q', 'U', 'I', 'R', 'E', 'D')) {
5696
0
  SKIP(9);
5697
0
  return(XML_ATTRIBUTE_REQUIRED);
5698
0
    }
5699
0
    if (CMP8(CUR_PTR, '#', 'I', 'M', 'P', 'L', 'I', 'E', 'D')) {
5700
0
  SKIP(8);
5701
0
  return(XML_ATTRIBUTE_IMPLIED);
5702
0
    }
5703
0
    val = XML_ATTRIBUTE_NONE;
5704
0
    if (CMP6(CUR_PTR, '#', 'F', 'I', 'X', 'E', 'D')) {
5705
0
  SKIP(6);
5706
0
  val = XML_ATTRIBUTE_FIXED;
5707
0
  if (SKIP_BLANKS_PE == 0) {
5708
0
      xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED,
5709
0
         "Space required after '#FIXED'\n");
5710
0
  }
5711
0
    }
5712
0
    ret = xmlParseAttValue(ctxt);
5713
0
    if (ret == NULL) {
5714
0
  xmlFatalErrMsg(ctxt, (xmlParserErrors)ctxt->errNo,
5715
0
           "Attribute default value declaration error\n");
5716
0
    } else
5717
0
        *value = ret;
5718
0
    return(val);
5719
0
}
5720
5721
/**
5722
 * parse an Notation attribute type.
5723
 *
5724
 * @deprecated Internal function, don't use.
5725
 *
5726
 * Note: the leading 'NOTATION' S part has already being parsed...
5727
 *
5728
 *     [58] NotationType ::= 'NOTATION' S '(' S? Name (S? '|' S? Name)* S? ')'
5729
 *
5730
 * [ VC: Notation Attributes ]
5731
 * Values of this type must match one of the notation names included
5732
 * in the declaration; all notation names in the declaration must be declared.
5733
 *
5734
 * @param ctxt  an XML parser context
5735
 * @returns the notation attribute tree built while parsing
5736
 */
5737
5738
xmlEnumeration *
5739
0
xmlParseNotationType(xmlParserCtxt *ctxt) {
5740
0
    const xmlChar *name;
5741
0
    xmlEnumerationPtr ret = NULL, last = NULL, cur, tmp;
5742
5743
0
    if (RAW != '(') {
5744
0
  xmlFatalErr(ctxt, XML_ERR_NOTATION_NOT_STARTED, NULL);
5745
0
  return(NULL);
5746
0
    }
5747
0
    do {
5748
0
        NEXT;
5749
0
  SKIP_BLANKS_PE;
5750
0
        name = xmlParseName(ctxt);
5751
0
  if (name == NULL) {
5752
0
      xmlFatalErrMsg(ctxt, XML_ERR_NAME_REQUIRED,
5753
0
         "Name expected in NOTATION declaration\n");
5754
0
            xmlFreeEnumeration(ret);
5755
0
      return(NULL);
5756
0
  }
5757
0
        tmp = NULL;
5758
0
#ifdef LIBXML_VALID_ENABLED
5759
0
        if (ctxt->validate) {
5760
0
            tmp = ret;
5761
0
            while (tmp != NULL) {
5762
0
                if (xmlStrEqual(name, tmp->name)) {
5763
0
                    xmlValidityError(ctxt, XML_DTD_DUP_TOKEN,
5764
0
              "standalone: attribute notation value token %s duplicated\n",
5765
0
                                     name, NULL);
5766
0
                    if (!xmlDictOwns(ctxt->dict, name))
5767
0
                        xmlFree((xmlChar *) name);
5768
0
                    break;
5769
0
                }
5770
0
                tmp = tmp->next;
5771
0
            }
5772
0
        }
5773
0
#endif /* LIBXML_VALID_ENABLED */
5774
0
  if (tmp == NULL) {
5775
0
      cur = xmlCreateEnumeration(name);
5776
0
      if (cur == NULL) {
5777
0
                xmlErrMemory(ctxt);
5778
0
                xmlFreeEnumeration(ret);
5779
0
                return(NULL);
5780
0
            }
5781
0
      if (last == NULL) ret = last = cur;
5782
0
      else {
5783
0
    last->next = cur;
5784
0
    last = cur;
5785
0
      }
5786
0
  }
5787
0
  SKIP_BLANKS_PE;
5788
0
    } while (RAW == '|');
5789
0
    if (RAW != ')') {
5790
0
  xmlFatalErr(ctxt, XML_ERR_NOTATION_NOT_FINISHED, NULL);
5791
0
        xmlFreeEnumeration(ret);
5792
0
  return(NULL);
5793
0
    }
5794
0
    NEXT;
5795
0
    return(ret);
5796
0
}
5797
5798
/**
5799
 * parse an Enumeration attribute type.
5800
 *
5801
 * @deprecated Internal function, don't use.
5802
 *
5803
 *     [59] Enumeration ::= '(' S? Nmtoken (S? '|' S? Nmtoken)* S? ')'
5804
 *
5805
 * [ VC: Enumeration ]
5806
 * Values of this type must match one of the Nmtoken tokens in
5807
 * the declaration
5808
 *
5809
 * @param ctxt  an XML parser context
5810
 * @returns the enumeration attribute tree built while parsing
5811
 */
5812
5813
xmlEnumeration *
5814
0
xmlParseEnumerationType(xmlParserCtxt *ctxt) {
5815
0
    xmlChar *name;
5816
0
    xmlEnumerationPtr ret = NULL, last = NULL, cur, tmp;
5817
5818
0
    if (RAW != '(') {
5819
0
  xmlFatalErr(ctxt, XML_ERR_ATTLIST_NOT_STARTED, NULL);
5820
0
  return(NULL);
5821
0
    }
5822
0
    do {
5823
0
        NEXT;
5824
0
  SKIP_BLANKS_PE;
5825
0
        name = xmlParseNmtoken(ctxt);
5826
0
  if (name == NULL) {
5827
0
      xmlFatalErr(ctxt, XML_ERR_NMTOKEN_REQUIRED, NULL);
5828
0
      return(ret);
5829
0
  }
5830
0
        tmp = NULL;
5831
0
#ifdef LIBXML_VALID_ENABLED
5832
0
        if (ctxt->validate) {
5833
0
            tmp = ret;
5834
0
            while (tmp != NULL) {
5835
0
                if (xmlStrEqual(name, tmp->name)) {
5836
0
                    xmlValidityError(ctxt, XML_DTD_DUP_TOKEN,
5837
0
              "standalone: attribute enumeration value token %s duplicated\n",
5838
0
                                     name, NULL);
5839
0
                    if (!xmlDictOwns(ctxt->dict, name))
5840
0
                        xmlFree(name);
5841
0
                    break;
5842
0
                }
5843
0
                tmp = tmp->next;
5844
0
            }
5845
0
        }
5846
0
#endif /* LIBXML_VALID_ENABLED */
5847
0
  if (tmp == NULL) {
5848
0
      cur = xmlCreateEnumeration(name);
5849
0
      if (!xmlDictOwns(ctxt->dict, name))
5850
0
    xmlFree(name);
5851
0
      if (cur == NULL) {
5852
0
                xmlErrMemory(ctxt);
5853
0
                xmlFreeEnumeration(ret);
5854
0
                return(NULL);
5855
0
            }
5856
0
      if (last == NULL) ret = last = cur;
5857
0
      else {
5858
0
    last->next = cur;
5859
0
    last = cur;
5860
0
      }
5861
0
  }
5862
0
  SKIP_BLANKS_PE;
5863
0
    } while (RAW == '|');
5864
0
    if (RAW != ')') {
5865
0
  xmlFatalErr(ctxt, XML_ERR_ATTLIST_NOT_FINISHED, NULL);
5866
0
  return(ret);
5867
0
    }
5868
0
    NEXT;
5869
0
    return(ret);
5870
0
}
5871
5872
/**
5873
 * parse an Enumerated attribute type.
5874
 *
5875
 * @deprecated Internal function, don't use.
5876
 *
5877
 *     [57] EnumeratedType ::= NotationType | Enumeration
5878
 *
5879
 *     [58] NotationType ::= 'NOTATION' S '(' S? Name (S? '|' S? Name)* S? ')'
5880
 *
5881
 * @param ctxt  an XML parser context
5882
 * @param tree  the enumeration tree built while parsing
5883
 * @returns XML_ATTRIBUTE_ENUMERATION or XML_ATTRIBUTE_NOTATION
5884
 */
5885
5886
int
5887
0
xmlParseEnumeratedType(xmlParserCtxt *ctxt, xmlEnumeration **tree) {
5888
0
    if (CMP8(CUR_PTR, 'N', 'O', 'T', 'A', 'T', 'I', 'O', 'N')) {
5889
0
  SKIP(8);
5890
0
  if (SKIP_BLANKS_PE == 0) {
5891
0
      xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED,
5892
0
         "Space required after 'NOTATION'\n");
5893
0
      return(0);
5894
0
  }
5895
0
  *tree = xmlParseNotationType(ctxt);
5896
0
  if (*tree == NULL) return(0);
5897
0
  return(XML_ATTRIBUTE_NOTATION);
5898
0
    }
5899
0
    *tree = xmlParseEnumerationType(ctxt);
5900
0
    if (*tree == NULL) return(0);
5901
0
    return(XML_ATTRIBUTE_ENUMERATION);
5902
0
}
5903
5904
/**
5905
 * parse the Attribute list def for an element
5906
 *
5907
 * @deprecated Internal function, don't use.
5908
 *
5909
 *     [54] AttType ::= StringType | TokenizedType | EnumeratedType
5910
 *
5911
 *     [55] StringType ::= 'CDATA'
5912
 *
5913
 *     [56] TokenizedType ::= 'ID' | 'IDREF' | 'IDREFS' | 'ENTITY' |
5914
 *                            'ENTITIES' | 'NMTOKEN' | 'NMTOKENS'
5915
 *
5916
 * Validity constraints for attribute values syntax are checked in
5917
 * #xmlValidateAttributeValue
5918
 *
5919
 * [ VC: ID ]
5920
 * Values of type ID must match the Name production. A name must not
5921
 * appear more than once in an XML document as a value of this type;
5922
 * i.e., ID values must uniquely identify the elements which bear them.
5923
 *
5924
 * [ VC: One ID per Element Type ]
5925
 * No element type may have more than one ID attribute specified.
5926
 *
5927
 * [ VC: ID Attribute Default ]
5928
 * An ID attribute must have a declared default of \#IMPLIED or \#REQUIRED.
5929
 *
5930
 * [ VC: IDREF ]
5931
 * Values of type IDREF must match the Name production, and values
5932
 * of type IDREFS must match Names; each IDREF Name must match the value
5933
 * of an ID attribute on some element in the XML document; i.e. IDREF
5934
 * values must match the value of some ID attribute.
5935
 *
5936
 * [ VC: Entity Name ]
5937
 * Values of type ENTITY must match the Name production, values
5938
 * of type ENTITIES must match Names; each Entity Name must match the
5939
 * name of an unparsed entity declared in the DTD.
5940
 *
5941
 * [ VC: Name Token ]
5942
 * Values of type NMTOKEN must match the Nmtoken production; values
5943
 * of type NMTOKENS must match Nmtokens.
5944
 *
5945
 * @param ctxt  an XML parser context
5946
 * @param tree  the enumeration tree built while parsing
5947
 * @returns the attribute type
5948
 */
5949
int
5950
0
xmlParseAttributeType(xmlParserCtxt *ctxt, xmlEnumeration **tree) {
5951
0
    if (CMP5(CUR_PTR, 'C', 'D', 'A', 'T', 'A')) {
5952
0
  SKIP(5);
5953
0
  return(XML_ATTRIBUTE_CDATA);
5954
0
     } else if (CMP6(CUR_PTR, 'I', 'D', 'R', 'E', 'F', 'S')) {
5955
0
  SKIP(6);
5956
0
  return(XML_ATTRIBUTE_IDREFS);
5957
0
     } else if (CMP5(CUR_PTR, 'I', 'D', 'R', 'E', 'F')) {
5958
0
  SKIP(5);
5959
0
  return(XML_ATTRIBUTE_IDREF);
5960
0
     } else if ((RAW == 'I') && (NXT(1) == 'D')) {
5961
0
        SKIP(2);
5962
0
  return(XML_ATTRIBUTE_ID);
5963
0
     } else if (CMP6(CUR_PTR, 'E', 'N', 'T', 'I', 'T', 'Y')) {
5964
0
  SKIP(6);
5965
0
  return(XML_ATTRIBUTE_ENTITY);
5966
0
     } else if (CMP8(CUR_PTR, 'E', 'N', 'T', 'I', 'T', 'I', 'E', 'S')) {
5967
0
  SKIP(8);
5968
0
  return(XML_ATTRIBUTE_ENTITIES);
5969
0
     } else if (CMP8(CUR_PTR, 'N', 'M', 'T', 'O', 'K', 'E', 'N', 'S')) {
5970
0
  SKIP(8);
5971
0
  return(XML_ATTRIBUTE_NMTOKENS);
5972
0
     } else if (CMP7(CUR_PTR, 'N', 'M', 'T', 'O', 'K', 'E', 'N')) {
5973
0
  SKIP(7);
5974
0
  return(XML_ATTRIBUTE_NMTOKEN);
5975
0
     }
5976
0
     return(xmlParseEnumeratedType(ctxt, tree));
5977
0
}
5978
5979
/**
5980
 * Parse an attribute list declaration for an element. Always consumes '<!'.
5981
 *
5982
 * @deprecated Internal function, don't use.
5983
 *
5984
 *     [52] AttlistDecl ::= '<!ATTLIST' S Name AttDef* S? '>'
5985
 *
5986
 *     [53] AttDef ::= S Name S AttType S DefaultDecl
5987
 * @param ctxt  an XML parser context
5988
 */
5989
void
5990
0
xmlParseAttributeListDecl(xmlParserCtxt *ctxt) {
5991
0
    const xmlChar *elemName;
5992
0
    const xmlChar *attrName;
5993
0
    xmlEnumerationPtr tree;
5994
5995
0
    if ((CUR != '<') || (NXT(1) != '!'))
5996
0
        return;
5997
0
    SKIP(2);
5998
5999
0
    if (CMP7(CUR_PTR, 'A', 'T', 'T', 'L', 'I', 'S', 'T')) {
6000
0
#ifdef LIBXML_VALID_ENABLED
6001
0
  int oldInputNr = ctxt->inputNr;
6002
0
#endif
6003
6004
0
  SKIP(7);
6005
0
  if (SKIP_BLANKS_PE == 0) {
6006
0
      xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED,
6007
0
                     "Space required after '<!ATTLIST'\n");
6008
0
  }
6009
0
        elemName = xmlParseName(ctxt);
6010
0
  if (elemName == NULL) {
6011
0
      xmlFatalErrMsg(ctxt, XML_ERR_NAME_REQUIRED,
6012
0
         "ATTLIST: no name for Element\n");
6013
0
      return;
6014
0
  }
6015
0
  SKIP_BLANKS_PE;
6016
0
  GROW;
6017
0
  while ((RAW != '>') && (PARSER_STOPPED(ctxt) == 0)) {
6018
0
      int type;
6019
0
      int def;
6020
0
      xmlChar *defaultValue = NULL;
6021
6022
0
      GROW;
6023
0
            tree = NULL;
6024
0
      attrName = xmlParseName(ctxt);
6025
0
      if (attrName == NULL) {
6026
0
    xmlFatalErrMsg(ctxt, XML_ERR_NAME_REQUIRED,
6027
0
             "ATTLIST: no name for Attribute\n");
6028
0
    break;
6029
0
      }
6030
0
      GROW;
6031
0
      if (SKIP_BLANKS_PE == 0) {
6032
0
    xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED,
6033
0
            "Space required after the attribute name\n");
6034
0
    break;
6035
0
      }
6036
6037
0
      type = xmlParseAttributeType(ctxt, &tree);
6038
0
      if (type <= 0) {
6039
0
          break;
6040
0
      }
6041
6042
0
      GROW;
6043
0
      if (SKIP_BLANKS_PE == 0) {
6044
0
    xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED,
6045
0
             "Space required after the attribute type\n");
6046
0
          if (tree != NULL)
6047
0
        xmlFreeEnumeration(tree);
6048
0
    break;
6049
0
      }
6050
6051
0
      def = xmlParseDefaultDecl(ctxt, &defaultValue);
6052
0
      if (def <= 0) {
6053
0
                if (defaultValue != NULL)
6054
0
        xmlFree(defaultValue);
6055
0
          if (tree != NULL)
6056
0
        xmlFreeEnumeration(tree);
6057
0
          break;
6058
0
      }
6059
0
      if ((type != XML_ATTRIBUTE_CDATA) && (defaultValue != NULL))
6060
0
          xmlAttrNormalizeSpace(defaultValue, defaultValue);
6061
6062
0
      GROW;
6063
0
            if (RAW != '>') {
6064
0
    if (SKIP_BLANKS_PE == 0) {
6065
0
        xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED,
6066
0
      "Space required after the attribute default value\n");
6067
0
        if (defaultValue != NULL)
6068
0
      xmlFree(defaultValue);
6069
0
        if (tree != NULL)
6070
0
      xmlFreeEnumeration(tree);
6071
0
        break;
6072
0
    }
6073
0
      }
6074
0
      if ((ctxt->sax != NULL) && (!ctxt->disableSAX) &&
6075
0
    (ctxt->sax->attributeDecl != NULL))
6076
0
    ctxt->sax->attributeDecl(ctxt->userData, elemName, attrName,
6077
0
                          type, def, defaultValue, tree);
6078
0
      else if (tree != NULL)
6079
0
    xmlFreeEnumeration(tree);
6080
6081
0
      if ((ctxt->sax2) && (defaultValue != NULL) &&
6082
0
          (def != XML_ATTRIBUTE_IMPLIED) &&
6083
0
    (def != XML_ATTRIBUTE_REQUIRED)) {
6084
0
    xmlAddDefAttrs(ctxt, elemName, attrName, defaultValue);
6085
0
      }
6086
0
      if (ctxt->sax2) {
6087
0
    xmlAddSpecialAttr(ctxt, elemName, attrName, type);
6088
0
      }
6089
0
      if (defaultValue != NULL)
6090
0
          xmlFree(defaultValue);
6091
0
      GROW;
6092
0
  }
6093
0
  if (RAW == '>') {
6094
0
#ifdef LIBXML_VALID_ENABLED
6095
0
      if ((ctxt->validate) && (ctxt->inputNr > oldInputNr)) {
6096
0
    xmlValidityError(ctxt, XML_ERR_ENTITY_BOUNDARY,
6097
0
                                 "Attribute list declaration doesn't start and"
6098
0
                                 " stop in the same entity\n",
6099
0
                                 NULL, NULL);
6100
0
      }
6101
0
#endif
6102
0
      NEXT;
6103
0
  }
6104
0
    }
6105
0
}
6106
6107
/**
6108
 * Handle PEs and check that we don't pop the entity that started
6109
 * a balanced group.
6110
 *
6111
 * @param ctxt  parser context
6112
 * @param openInputNr  input nr of the entity with opening '('
6113
 */
6114
static void
6115
0
xmlSkipBlankCharsPEBalanced(xmlParserCtxt *ctxt, int openInputNr) {
6116
0
    SKIP_BLANKS;
6117
0
    GROW;
6118
6119
0
    (void) openInputNr;
6120
6121
0
    if (!PARSER_EXTERNAL(ctxt) && !PARSER_IN_PE(ctxt))
6122
0
        return;
6123
6124
0
    while (!PARSER_STOPPED(ctxt)) {
6125
0
        if (ctxt->input->cur >= ctxt->input->end) {
6126
0
#ifdef LIBXML_VALID_ENABLED
6127
0
            if ((ctxt->validate) && (ctxt->inputNr <= openInputNr)) {
6128
0
                xmlValidityError(ctxt, XML_ERR_ENTITY_BOUNDARY,
6129
0
                                 "Element content declaration doesn't start "
6130
0
                                 "and stop in the same entity\n",
6131
0
                                 NULL, NULL);
6132
0
            }
6133
0
#endif
6134
0
            if (PARSER_IN_PE(ctxt))
6135
0
                xmlPopPE(ctxt);
6136
0
            else
6137
0
                break;
6138
0
        } else if (RAW == '%') {
6139
0
            xmlParsePERefInternal(ctxt, 0);
6140
0
        } else {
6141
0
            break;
6142
0
        }
6143
6144
0
        SKIP_BLANKS;
6145
0
        GROW;
6146
0
    }
6147
0
}
6148
6149
/**
6150
 * parse the declaration for a Mixed Element content
6151
 * The leading '(' and spaces have been skipped in #xmlParseElementContentDecl
6152
 *
6153
 * @deprecated Internal function, don't use.
6154
 *
6155
 *     [51] Mixed ::= '(' S? '#PCDATA' (S? '|' S? Name)* S? ')*' |
6156
 *                    '(' S? '#PCDATA' S? ')'
6157
 *
6158
 * [ VC: Proper Group/PE Nesting ] applies to [51] too (see [49])
6159
 *
6160
 * [ VC: No Duplicate Types ]
6161
 * The same name must not appear more than once in a single
6162
 * mixed-content declaration.
6163
 *
6164
 * @param ctxt  an XML parser context
6165
 * @param openInputNr  the input used for the current entity, needed for
6166
 * boundary checks
6167
 * @returns the list of the xmlElementContent describing the element choices
6168
 */
6169
xmlElementContent *
6170
0
xmlParseElementMixedContentDecl(xmlParserCtxt *ctxt, int openInputNr) {
6171
0
    xmlElementContentPtr ret = NULL, cur = NULL, n;
6172
0
    const xmlChar *elem = NULL;
6173
6174
0
    GROW;
6175
0
    if (CMP7(CUR_PTR, '#', 'P', 'C', 'D', 'A', 'T', 'A')) {
6176
0
  SKIP(7);
6177
0
        xmlSkipBlankCharsPEBalanced(ctxt, openInputNr);
6178
0
  if (RAW == ')') {
6179
0
#ifdef LIBXML_VALID_ENABLED
6180
0
      if ((ctxt->validate) && (ctxt->inputNr > openInputNr)) {
6181
0
    xmlValidityError(ctxt, XML_ERR_ENTITY_BOUNDARY,
6182
0
                                 "Element content declaration doesn't start "
6183
0
                                 "and stop in the same entity\n",
6184
0
                                 NULL, NULL);
6185
0
      }
6186
0
#endif
6187
0
      NEXT;
6188
0
      ret = xmlNewDocElementContent(ctxt->myDoc, NULL, XML_ELEMENT_CONTENT_PCDATA);
6189
0
      if (ret == NULL)
6190
0
                goto mem_error;
6191
0
      if (RAW == '*') {
6192
0
    ret->ocur = XML_ELEMENT_CONTENT_MULT;
6193
0
    NEXT;
6194
0
      }
6195
0
      return(ret);
6196
0
  }
6197
0
  if ((RAW == '(') || (RAW == '|')) {
6198
0
      ret = cur = xmlNewDocElementContent(ctxt->myDoc, NULL, XML_ELEMENT_CONTENT_PCDATA);
6199
0
      if (ret == NULL)
6200
0
                goto mem_error;
6201
0
  }
6202
0
  while ((RAW == '|') && (PARSER_STOPPED(ctxt) == 0)) {
6203
0
      NEXT;
6204
0
            n = xmlNewDocElementContent(ctxt->myDoc, NULL, XML_ELEMENT_CONTENT_OR);
6205
0
            if (n == NULL)
6206
0
                goto mem_error;
6207
0
      if (elem == NULL) {
6208
0
    n->c1 = cur;
6209
0
    if (cur != NULL)
6210
0
        cur->parent = n;
6211
0
    ret = cur = n;
6212
0
      } else {
6213
0
          cur->c2 = n;
6214
0
    n->parent = cur;
6215
0
    n->c1 = xmlNewDocElementContent(ctxt->myDoc, elem, XML_ELEMENT_CONTENT_ELEMENT);
6216
0
                if (n->c1 == NULL)
6217
0
                    goto mem_error;
6218
0
    n->c1->parent = n;
6219
0
    cur = n;
6220
0
      }
6221
0
            xmlSkipBlankCharsPEBalanced(ctxt, openInputNr);
6222
0
      elem = xmlParseName(ctxt);
6223
0
      if (elem == NULL) {
6224
0
    xmlFatalErrMsg(ctxt, XML_ERR_NAME_REQUIRED,
6225
0
      "xmlParseElementMixedContentDecl : Name expected\n");
6226
0
    xmlFreeDocElementContent(ctxt->myDoc, ret);
6227
0
    return(NULL);
6228
0
      }
6229
0
            xmlSkipBlankCharsPEBalanced(ctxt, openInputNr);
6230
0
  }
6231
0
  if ((RAW == ')') && (NXT(1) == '*')) {
6232
0
      if (elem != NULL) {
6233
0
    cur->c2 = xmlNewDocElementContent(ctxt->myDoc, elem,
6234
0
                                   XML_ELEMENT_CONTENT_ELEMENT);
6235
0
    if (cur->c2 == NULL)
6236
0
                    goto mem_error;
6237
0
    cur->c2->parent = cur;
6238
0
            }
6239
0
            if (ret != NULL)
6240
0
                ret->ocur = XML_ELEMENT_CONTENT_MULT;
6241
0
#ifdef LIBXML_VALID_ENABLED
6242
0
      if ((ctxt->validate) && (ctxt->inputNr > openInputNr)) {
6243
0
    xmlValidityError(ctxt, XML_ERR_ENTITY_BOUNDARY,
6244
0
                                 "Element content declaration doesn't start "
6245
0
                                 "and stop in the same entity\n",
6246
0
                                 NULL, NULL);
6247
0
      }
6248
0
#endif
6249
0
      SKIP(2);
6250
0
  } else {
6251
0
      xmlFreeDocElementContent(ctxt->myDoc, ret);
6252
0
      xmlFatalErr(ctxt, XML_ERR_MIXED_NOT_STARTED, NULL);
6253
0
      return(NULL);
6254
0
  }
6255
6256
0
    } else {
6257
0
  xmlFatalErr(ctxt, XML_ERR_PCDATA_REQUIRED, NULL);
6258
0
    }
6259
0
    return(ret);
6260
6261
0
mem_error:
6262
0
    xmlErrMemory(ctxt);
6263
0
    xmlFreeDocElementContent(ctxt->myDoc, ret);
6264
0
    return(NULL);
6265
0
}
6266
6267
/**
6268
 * parse the declaration for a Mixed Element content
6269
 * The leading '(' and spaces have been skipped in #xmlParseElementContentDecl
6270
 *
6271
 *     [47] children ::= (choice | seq) ('?' | '*' | '+')?
6272
 *
6273
 *     [48] cp ::= (Name | choice | seq) ('?' | '*' | '+')?
6274
 *
6275
 *     [49] choice ::= '(' S? cp ( S? '|' S? cp )* S? ')'
6276
 *
6277
 *     [50] seq ::= '(' S? cp ( S? ',' S? cp )* S? ')'
6278
 *
6279
 * [ VC: Proper Group/PE Nesting ] applies to [49] and [50]
6280
 * TODO Parameter-entity replacement text must be properly nested
6281
 *  with parenthesized groups. That is to say, if either of the
6282
 *  opening or closing parentheses in a choice, seq, or Mixed
6283
 *  construct is contained in the replacement text for a parameter
6284
 *  entity, both must be contained in the same replacement text. For
6285
 *  interoperability, if a parameter-entity reference appears in a
6286
 *  choice, seq, or Mixed construct, its replacement text should not
6287
 *  be empty, and neither the first nor last non-blank character of
6288
 *  the replacement text should be a connector (| or ,).
6289
 *
6290
 * @param ctxt  an XML parser context
6291
 * @param openInputNr  the input used for the current entity, needed for
6292
 * boundary checks
6293
 * @param depth  the level of recursion
6294
 * @returns the tree of xmlElementContent describing the element
6295
 *          hierarchy.
6296
 */
6297
static xmlElementContentPtr
6298
xmlParseElementChildrenContentDeclPriv(xmlParserCtxtPtr ctxt, int openInputNr,
6299
0
                                       int depth) {
6300
0
    int maxDepth = (ctxt->options & XML_PARSE_HUGE) ? 2048 : 256;
6301
0
    xmlElementContentPtr ret = NULL, cur = NULL, last = NULL, op = NULL;
6302
0
    const xmlChar *elem;
6303
0
    xmlChar type = 0;
6304
6305
0
    if (depth > maxDepth) {
6306
0
        xmlFatalErrMsgInt(ctxt, XML_ERR_RESOURCE_LIMIT,
6307
0
                "xmlParseElementChildrenContentDecl : depth %d too deep, "
6308
0
                "use XML_PARSE_HUGE\n", depth);
6309
0
  return(NULL);
6310
0
    }
6311
0
    xmlSkipBlankCharsPEBalanced(ctxt, openInputNr);
6312
0
    if (RAW == '(') {
6313
0
        int newInputNr = ctxt->inputNr;
6314
6315
        /* Recurse on first child */
6316
0
  NEXT;
6317
0
        cur = ret = xmlParseElementChildrenContentDeclPriv(ctxt, newInputNr,
6318
0
                                                           depth + 1);
6319
0
        if (cur == NULL)
6320
0
            return(NULL);
6321
0
    } else {
6322
0
  elem = xmlParseName(ctxt);
6323
0
  if (elem == NULL) {
6324
0
      xmlFatalErr(ctxt, XML_ERR_ELEMCONTENT_NOT_STARTED, NULL);
6325
0
      return(NULL);
6326
0
  }
6327
0
        cur = ret = xmlNewDocElementContent(ctxt->myDoc, elem, XML_ELEMENT_CONTENT_ELEMENT);
6328
0
  if (cur == NULL) {
6329
0
      xmlErrMemory(ctxt);
6330
0
      return(NULL);
6331
0
  }
6332
0
  GROW;
6333
0
  if (RAW == '?') {
6334
0
      cur->ocur = XML_ELEMENT_CONTENT_OPT;
6335
0
      NEXT;
6336
0
  } else if (RAW == '*') {
6337
0
      cur->ocur = XML_ELEMENT_CONTENT_MULT;
6338
0
      NEXT;
6339
0
  } else if (RAW == '+') {
6340
0
      cur->ocur = XML_ELEMENT_CONTENT_PLUS;
6341
0
      NEXT;
6342
0
  } else {
6343
0
      cur->ocur = XML_ELEMENT_CONTENT_ONCE;
6344
0
  }
6345
0
  GROW;
6346
0
    }
6347
0
    while (!PARSER_STOPPED(ctxt)) {
6348
0
        xmlSkipBlankCharsPEBalanced(ctxt, openInputNr);
6349
0
        if (RAW == ')')
6350
0
            break;
6351
        /*
6352
   * Each loop we parse one separator and one element.
6353
   */
6354
0
        if (RAW == ',') {
6355
0
      if (type == 0) type = CUR;
6356
6357
      /*
6358
       * Detect "Name | Name , Name" error
6359
       */
6360
0
      else if (type != CUR) {
6361
0
    xmlFatalErrMsgInt(ctxt, XML_ERR_SEPARATOR_REQUIRED,
6362
0
        "xmlParseElementChildrenContentDecl : '%c' expected\n",
6363
0
                      type);
6364
0
    if ((last != NULL) && (last != ret))
6365
0
        xmlFreeDocElementContent(ctxt->myDoc, last);
6366
0
    if (ret != NULL)
6367
0
        xmlFreeDocElementContent(ctxt->myDoc, ret);
6368
0
    return(NULL);
6369
0
      }
6370
0
      NEXT;
6371
6372
0
      op = xmlNewDocElementContent(ctxt->myDoc, NULL, XML_ELEMENT_CONTENT_SEQ);
6373
0
      if (op == NULL) {
6374
0
                xmlErrMemory(ctxt);
6375
0
    if ((last != NULL) && (last != ret))
6376
0
        xmlFreeDocElementContent(ctxt->myDoc, last);
6377
0
          xmlFreeDocElementContent(ctxt->myDoc, ret);
6378
0
    return(NULL);
6379
0
      }
6380
0
      if (last == NULL) {
6381
0
    op->c1 = ret;
6382
0
    if (ret != NULL)
6383
0
        ret->parent = op;
6384
0
    ret = cur = op;
6385
0
      } else {
6386
0
          cur->c2 = op;
6387
0
    if (op != NULL)
6388
0
        op->parent = cur;
6389
0
    op->c1 = last;
6390
0
    if (last != NULL)
6391
0
        last->parent = op;
6392
0
    cur =op;
6393
0
    last = NULL;
6394
0
      }
6395
0
  } else if (RAW == '|') {
6396
0
      if (type == 0) type = CUR;
6397
6398
      /*
6399
       * Detect "Name , Name | Name" error
6400
       */
6401
0
      else if (type != CUR) {
6402
0
    xmlFatalErrMsgInt(ctxt, XML_ERR_SEPARATOR_REQUIRED,
6403
0
        "xmlParseElementChildrenContentDecl : '%c' expected\n",
6404
0
          type);
6405
0
    if ((last != NULL) && (last != ret))
6406
0
        xmlFreeDocElementContent(ctxt->myDoc, last);
6407
0
    if (ret != NULL)
6408
0
        xmlFreeDocElementContent(ctxt->myDoc, ret);
6409
0
    return(NULL);
6410
0
      }
6411
0
      NEXT;
6412
6413
0
      op = xmlNewDocElementContent(ctxt->myDoc, NULL, XML_ELEMENT_CONTENT_OR);
6414
0
      if (op == NULL) {
6415
0
                xmlErrMemory(ctxt);
6416
0
    if ((last != NULL) && (last != ret))
6417
0
        xmlFreeDocElementContent(ctxt->myDoc, last);
6418
0
    if (ret != NULL)
6419
0
        xmlFreeDocElementContent(ctxt->myDoc, ret);
6420
0
    return(NULL);
6421
0
      }
6422
0
      if (last == NULL) {
6423
0
    op->c1 = ret;
6424
0
    if (ret != NULL)
6425
0
        ret->parent = op;
6426
0
    ret = cur = op;
6427
0
      } else {
6428
0
          cur->c2 = op;
6429
0
    if (op != NULL)
6430
0
        op->parent = cur;
6431
0
    op->c1 = last;
6432
0
    if (last != NULL)
6433
0
        last->parent = op;
6434
0
    cur =op;
6435
0
    last = NULL;
6436
0
      }
6437
0
  } else {
6438
0
      xmlFatalErr(ctxt, XML_ERR_ELEMCONTENT_NOT_FINISHED, NULL);
6439
0
      if ((last != NULL) && (last != ret))
6440
0
          xmlFreeDocElementContent(ctxt->myDoc, last);
6441
0
      if (ret != NULL)
6442
0
    xmlFreeDocElementContent(ctxt->myDoc, ret);
6443
0
      return(NULL);
6444
0
  }
6445
0
        xmlSkipBlankCharsPEBalanced(ctxt, openInputNr);
6446
0
        if (RAW == '(') {
6447
0
            int newInputNr = ctxt->inputNr;
6448
6449
      /* Recurse on second child */
6450
0
      NEXT;
6451
0
      last = xmlParseElementChildrenContentDeclPriv(ctxt, newInputNr,
6452
0
                                                          depth + 1);
6453
0
            if (last == NULL) {
6454
0
    if (ret != NULL)
6455
0
        xmlFreeDocElementContent(ctxt->myDoc, ret);
6456
0
    return(NULL);
6457
0
            }
6458
0
  } else {
6459
0
      elem = xmlParseName(ctxt);
6460
0
      if (elem == NULL) {
6461
0
    xmlFatalErr(ctxt, XML_ERR_ELEMCONTENT_NOT_STARTED, NULL);
6462
0
    if (ret != NULL)
6463
0
        xmlFreeDocElementContent(ctxt->myDoc, ret);
6464
0
    return(NULL);
6465
0
      }
6466
0
      last = xmlNewDocElementContent(ctxt->myDoc, elem, XML_ELEMENT_CONTENT_ELEMENT);
6467
0
      if (last == NULL) {
6468
0
                xmlErrMemory(ctxt);
6469
0
    if (ret != NULL)
6470
0
        xmlFreeDocElementContent(ctxt->myDoc, ret);
6471
0
    return(NULL);
6472
0
      }
6473
0
      if (RAW == '?') {
6474
0
    last->ocur = XML_ELEMENT_CONTENT_OPT;
6475
0
    NEXT;
6476
0
      } else if (RAW == '*') {
6477
0
    last->ocur = XML_ELEMENT_CONTENT_MULT;
6478
0
    NEXT;
6479
0
      } else if (RAW == '+') {
6480
0
    last->ocur = XML_ELEMENT_CONTENT_PLUS;
6481
0
    NEXT;
6482
0
      } else {
6483
0
    last->ocur = XML_ELEMENT_CONTENT_ONCE;
6484
0
      }
6485
0
  }
6486
0
    }
6487
0
    if ((cur != NULL) && (last != NULL)) {
6488
0
        cur->c2 = last;
6489
0
  if (last != NULL)
6490
0
      last->parent = cur;
6491
0
    }
6492
0
#ifdef LIBXML_VALID_ENABLED
6493
0
    if ((ctxt->validate) && (ctxt->inputNr > openInputNr)) {
6494
0
        xmlValidityError(ctxt, XML_ERR_ENTITY_BOUNDARY,
6495
0
                         "Element content declaration doesn't start "
6496
0
                         "and stop in the same entity\n",
6497
0
                         NULL, NULL);
6498
0
    }
6499
0
#endif
6500
0
    NEXT;
6501
0
    if (RAW == '?') {
6502
0
  if (ret != NULL) {
6503
0
      if ((ret->ocur == XML_ELEMENT_CONTENT_PLUS) ||
6504
0
          (ret->ocur == XML_ELEMENT_CONTENT_MULT))
6505
0
          ret->ocur = XML_ELEMENT_CONTENT_MULT;
6506
0
      else
6507
0
          ret->ocur = XML_ELEMENT_CONTENT_OPT;
6508
0
  }
6509
0
  NEXT;
6510
0
    } else if (RAW == '*') {
6511
0
  if (ret != NULL) {
6512
0
      ret->ocur = XML_ELEMENT_CONTENT_MULT;
6513
0
      cur = ret;
6514
      /*
6515
       * Some normalization:
6516
       * (a | b* | c?)* == (a | b | c)*
6517
       */
6518
0
      while ((cur != NULL) && (cur->type == XML_ELEMENT_CONTENT_OR)) {
6519
0
    if ((cur->c1 != NULL) &&
6520
0
              ((cur->c1->ocur == XML_ELEMENT_CONTENT_OPT) ||
6521
0
         (cur->c1->ocur == XML_ELEMENT_CONTENT_MULT)))
6522
0
        cur->c1->ocur = XML_ELEMENT_CONTENT_ONCE;
6523
0
    if ((cur->c2 != NULL) &&
6524
0
              ((cur->c2->ocur == XML_ELEMENT_CONTENT_OPT) ||
6525
0
         (cur->c2->ocur == XML_ELEMENT_CONTENT_MULT)))
6526
0
        cur->c2->ocur = XML_ELEMENT_CONTENT_ONCE;
6527
0
    cur = cur->c2;
6528
0
      }
6529
0
  }
6530
0
  NEXT;
6531
0
    } else if (RAW == '+') {
6532
0
  if (ret != NULL) {
6533
0
      int found = 0;
6534
6535
0
      if ((ret->ocur == XML_ELEMENT_CONTENT_OPT) ||
6536
0
          (ret->ocur == XML_ELEMENT_CONTENT_MULT))
6537
0
          ret->ocur = XML_ELEMENT_CONTENT_MULT;
6538
0
      else
6539
0
          ret->ocur = XML_ELEMENT_CONTENT_PLUS;
6540
      /*
6541
       * Some normalization:
6542
       * (a | b*)+ == (a | b)*
6543
       * (a | b?)+ == (a | b)*
6544
       */
6545
0
      while ((cur != NULL) && (cur->type == XML_ELEMENT_CONTENT_OR)) {
6546
0
    if ((cur->c1 != NULL) &&
6547
0
              ((cur->c1->ocur == XML_ELEMENT_CONTENT_OPT) ||
6548
0
         (cur->c1->ocur == XML_ELEMENT_CONTENT_MULT))) {
6549
0
        cur->c1->ocur = XML_ELEMENT_CONTENT_ONCE;
6550
0
        found = 1;
6551
0
    }
6552
0
    if ((cur->c2 != NULL) &&
6553
0
              ((cur->c2->ocur == XML_ELEMENT_CONTENT_OPT) ||
6554
0
         (cur->c2->ocur == XML_ELEMENT_CONTENT_MULT))) {
6555
0
        cur->c2->ocur = XML_ELEMENT_CONTENT_ONCE;
6556
0
        found = 1;
6557
0
    }
6558
0
    cur = cur->c2;
6559
0
      }
6560
0
      if (found)
6561
0
    ret->ocur = XML_ELEMENT_CONTENT_MULT;
6562
0
  }
6563
0
  NEXT;
6564
0
    }
6565
0
    return(ret);
6566
0
}
6567
6568
/**
6569
 * parse the declaration for a Mixed Element content
6570
 * The leading '(' and spaces have been skipped in #xmlParseElementContentDecl
6571
 *
6572
 * @deprecated Internal function, don't use.
6573
 *
6574
 *     [47] children ::= (choice | seq) ('?' | '*' | '+')?
6575
 *
6576
 *     [48] cp ::= (Name | choice | seq) ('?' | '*' | '+')?
6577
 *
6578
 *     [49] choice ::= '(' S? cp ( S? '|' S? cp )* S? ')'
6579
 *
6580
 *     [50] seq ::= '(' S? cp ( S? ',' S? cp )* S? ')'
6581
 *
6582
 * [ VC: Proper Group/PE Nesting ] applies to [49] and [50]
6583
 * TODO Parameter-entity replacement text must be properly nested
6584
 *  with parenthesized groups. That is to say, if either of the
6585
 *  opening or closing parentheses in a choice, seq, or Mixed
6586
 *  construct is contained in the replacement text for a parameter
6587
 *  entity, both must be contained in the same replacement text. For
6588
 *  interoperability, if a parameter-entity reference appears in a
6589
 *  choice, seq, or Mixed construct, its replacement text should not
6590
 *  be empty, and neither the first nor last non-blank character of
6591
 *  the replacement text should be a connector (| or ,).
6592
 *
6593
 * @param ctxt  an XML parser context
6594
 * @param inputchk  the input used for the current entity, needed for boundary checks
6595
 * @returns the tree of xmlElementContent describing the element
6596
 *          hierarchy.
6597
 */
6598
xmlElementContent *
6599
0
xmlParseElementChildrenContentDecl(xmlParserCtxt *ctxt, int inputchk) {
6600
    /* stub left for API/ABI compat */
6601
0
    return(xmlParseElementChildrenContentDeclPriv(ctxt, inputchk, 1));
6602
0
}
6603
6604
/**
6605
 * parse the declaration for an Element content either Mixed or Children,
6606
 * the cases EMPTY and ANY are handled directly in #xmlParseElementDecl
6607
 *
6608
 * @deprecated Internal function, don't use.
6609
 *
6610
 *     [46] contentspec ::= 'EMPTY' | 'ANY' | Mixed | children
6611
 *
6612
 * @param ctxt  an XML parser context
6613
 * @param name  the name of the element being defined.
6614
 * @param result  the Element Content pointer will be stored here if any
6615
 * @returns an xmlElementTypeVal value or -1 on error
6616
 */
6617
6618
int
6619
xmlParseElementContentDecl(xmlParserCtxt *ctxt, const xmlChar *name,
6620
0
                           xmlElementContent **result) {
6621
6622
0
    xmlElementContentPtr tree = NULL;
6623
0
    int openInputNr = ctxt->inputNr;
6624
0
    int res;
6625
6626
0
    *result = NULL;
6627
6628
0
    if (RAW != '(') {
6629
0
  xmlFatalErrMsgStr(ctxt, XML_ERR_ELEMCONTENT_NOT_STARTED,
6630
0
    "xmlParseElementContentDecl : %s '(' expected\n", name);
6631
0
  return(-1);
6632
0
    }
6633
0
    NEXT;
6634
0
    xmlSkipBlankCharsPEBalanced(ctxt, openInputNr);
6635
0
    if (CMP7(CUR_PTR, '#', 'P', 'C', 'D', 'A', 'T', 'A')) {
6636
0
        tree = xmlParseElementMixedContentDecl(ctxt, openInputNr);
6637
0
  res = XML_ELEMENT_TYPE_MIXED;
6638
0
    } else {
6639
0
        tree = xmlParseElementChildrenContentDeclPriv(ctxt, openInputNr, 1);
6640
0
  res = XML_ELEMENT_TYPE_ELEMENT;
6641
0
    }
6642
0
    if (tree == NULL)
6643
0
        return(-1);
6644
0
    SKIP_BLANKS_PE;
6645
0
    *result = tree;
6646
0
    return(res);
6647
0
}
6648
6649
/**
6650
 * Parse an element declaration. Always consumes '<!'.
6651
 *
6652
 * @deprecated Internal function, don't use.
6653
 *
6654
 *     [45] elementdecl ::= '<!ELEMENT' S Name S contentspec S? '>'
6655
 *
6656
 * [ VC: Unique Element Type Declaration ]
6657
 * No element type may be declared more than once
6658
 *
6659
 * @param ctxt  an XML parser context
6660
 * @returns the type of the element, or -1 in case of error
6661
 */
6662
int
6663
0
xmlParseElementDecl(xmlParserCtxt *ctxt) {
6664
0
    const xmlChar *name;
6665
0
    int ret = -1;
6666
0
    xmlElementContentPtr content  = NULL;
6667
6668
0
    if ((CUR != '<') || (NXT(1) != '!'))
6669
0
        return(ret);
6670
0
    SKIP(2);
6671
6672
    /* GROW; done in the caller */
6673
0
    if (CMP7(CUR_PTR, 'E', 'L', 'E', 'M', 'E', 'N', 'T')) {
6674
0
#ifdef LIBXML_VALID_ENABLED
6675
0
  int oldInputNr = ctxt->inputNr;
6676
0
#endif
6677
6678
0
  SKIP(7);
6679
0
  if (SKIP_BLANKS_PE == 0) {
6680
0
      xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED,
6681
0
               "Space required after 'ELEMENT'\n");
6682
0
      return(-1);
6683
0
  }
6684
0
        name = xmlParseName(ctxt);
6685
0
  if (name == NULL) {
6686
0
      xmlFatalErrMsg(ctxt, XML_ERR_NAME_REQUIRED,
6687
0
         "xmlParseElementDecl: no name for Element\n");
6688
0
      return(-1);
6689
0
  }
6690
0
  if (SKIP_BLANKS_PE == 0) {
6691
0
      xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED,
6692
0
         "Space required after the element name\n");
6693
0
  }
6694
0
  if (CMP5(CUR_PTR, 'E', 'M', 'P', 'T', 'Y')) {
6695
0
      SKIP(5);
6696
      /*
6697
       * Element must always be empty.
6698
       */
6699
0
      ret = XML_ELEMENT_TYPE_EMPTY;
6700
0
  } else if ((RAW == 'A') && (NXT(1) == 'N') &&
6701
0
             (NXT(2) == 'Y')) {
6702
0
      SKIP(3);
6703
      /*
6704
       * Element is a generic container.
6705
       */
6706
0
      ret = XML_ELEMENT_TYPE_ANY;
6707
0
  } else if (RAW == '(') {
6708
0
      ret = xmlParseElementContentDecl(ctxt, name, &content);
6709
0
            if (ret <= 0)
6710
0
                return(-1);
6711
0
  } else {
6712
      /*
6713
       * [ WFC: PEs in Internal Subset ] error handling.
6714
       */
6715
0
            xmlFatalErrMsg(ctxt, XML_ERR_ELEMCONTENT_NOT_STARTED,
6716
0
                  "xmlParseElementDecl: 'EMPTY', 'ANY' or '(' expected\n");
6717
0
      return(-1);
6718
0
  }
6719
6720
0
  SKIP_BLANKS_PE;
6721
6722
0
  if (RAW != '>') {
6723
0
      xmlFatalErr(ctxt, XML_ERR_GT_REQUIRED, NULL);
6724
0
      if (content != NULL) {
6725
0
    xmlFreeDocElementContent(ctxt->myDoc, content);
6726
0
      }
6727
0
  } else {
6728
0
#ifdef LIBXML_VALID_ENABLED
6729
0
      if ((ctxt->validate) && (ctxt->inputNr > oldInputNr)) {
6730
0
    xmlValidityError(ctxt, XML_ERR_ENTITY_BOUNDARY,
6731
0
                                 "Element declaration doesn't start and stop in"
6732
0
                                 " the same entity\n",
6733
0
                                 NULL, NULL);
6734
0
      }
6735
0
#endif
6736
6737
0
      NEXT;
6738
0
      if ((ctxt->sax != NULL) && (!ctxt->disableSAX) &&
6739
0
    (ctxt->sax->elementDecl != NULL)) {
6740
0
    if (content != NULL)
6741
0
        content->parent = NULL;
6742
0
          ctxt->sax->elementDecl(ctxt->userData, name, ret,
6743
0
                           content);
6744
0
    if ((content != NULL) && (content->parent == NULL)) {
6745
        /*
6746
         * this is a trick: if xmlAddElementDecl is called,
6747
         * instead of copying the full tree it is plugged directly
6748
         * if called from the parser. Avoid duplicating the
6749
         * interfaces or change the API/ABI
6750
         */
6751
0
        xmlFreeDocElementContent(ctxt->myDoc, content);
6752
0
    }
6753
0
      } else if (content != NULL) {
6754
0
    xmlFreeDocElementContent(ctxt->myDoc, content);
6755
0
      }
6756
0
  }
6757
0
    }
6758
0
    return(ret);
6759
0
}
6760
6761
/**
6762
 * Parse a conditional section. Always consumes '<!['.
6763
 *
6764
 *     [61] conditionalSect ::= includeSect | ignoreSect
6765
 *     [62] includeSect ::= '<![' S? 'INCLUDE' S? '[' extSubsetDecl ']]>'
6766
 *     [63] ignoreSect ::= '<![' S? 'IGNORE' S? '[' ignoreSectContents* ']]>'
6767
 *     [64] ignoreSectContents ::= Ignore ('<![' ignoreSectContents ']]>'
6768
 *                                 Ignore)*
6769
 *     [65] Ignore ::= Char* - (Char* ('<![' | ']]>') Char*)
6770
 * @param ctxt  an XML parser context
6771
 */
6772
6773
static void
6774
0
xmlParseConditionalSections(xmlParserCtxtPtr ctxt) {
6775
0
    size_t depth = 0;
6776
0
    int isFreshPE = 0;
6777
0
    int oldInputNr = ctxt->inputNr;
6778
0
    int declInputNr = ctxt->inputNr;
6779
6780
0
    while (!PARSER_STOPPED(ctxt)) {
6781
0
        if (ctxt->input->cur >= ctxt->input->end) {
6782
0
            if (ctxt->inputNr <= oldInputNr) {
6783
0
                xmlFatalErr(ctxt, XML_ERR_EXT_SUBSET_NOT_FINISHED, NULL);
6784
0
                return;
6785
0
            }
6786
6787
0
            xmlPopPE(ctxt);
6788
0
            declInputNr = ctxt->inputNr;
6789
0
        } else if ((RAW == '<') && (NXT(1) == '!') && (NXT(2) == '[')) {
6790
0
            SKIP(3);
6791
0
            SKIP_BLANKS_PE;
6792
6793
0
            isFreshPE = 0;
6794
6795
0
            if (CMP7(CUR_PTR, 'I', 'N', 'C', 'L', 'U', 'D', 'E')) {
6796
0
                SKIP(7);
6797
0
                SKIP_BLANKS_PE;
6798
0
                if (RAW != '[') {
6799
0
                    xmlFatalErr(ctxt, XML_ERR_CONDSEC_INVALID, NULL);
6800
0
                    return;
6801
0
                }
6802
0
#ifdef LIBXML_VALID_ENABLED
6803
0
                if ((ctxt->validate) && (ctxt->inputNr > declInputNr)) {
6804
0
        xmlValidityError(ctxt, XML_ERR_ENTITY_BOUNDARY,
6805
0
                                     "All markup of the conditional section is"
6806
0
                                     " not in the same entity\n",
6807
0
                                     NULL, NULL);
6808
0
                }
6809
0
#endif
6810
0
                NEXT;
6811
6812
0
                depth++;
6813
0
            } else if (CMP6(CUR_PTR, 'I', 'G', 'N', 'O', 'R', 'E')) {
6814
0
                size_t ignoreDepth = 0;
6815
6816
0
                SKIP(6);
6817
0
                SKIP_BLANKS_PE;
6818
0
                if (RAW != '[') {
6819
0
                    xmlFatalErr(ctxt, XML_ERR_CONDSEC_INVALID, NULL);
6820
0
                    return;
6821
0
                }
6822
0
#ifdef LIBXML_VALID_ENABLED
6823
0
                if ((ctxt->validate) && (ctxt->inputNr > declInputNr)) {
6824
0
        xmlValidityError(ctxt, XML_ERR_ENTITY_BOUNDARY,
6825
0
                                     "All markup of the conditional section is"
6826
0
                                     " not in the same entity\n",
6827
0
                                     NULL, NULL);
6828
0
                }
6829
0
#endif
6830
0
                NEXT;
6831
6832
0
                while (PARSER_STOPPED(ctxt) == 0) {
6833
0
                    if (RAW == 0) {
6834
0
                        xmlFatalErr(ctxt, XML_ERR_CONDSEC_NOT_FINISHED, NULL);
6835
0
                        return;
6836
0
                    }
6837
0
                    if ((RAW == '<') && (NXT(1) == '!') && (NXT(2) == '[')) {
6838
0
                        SKIP(3);
6839
0
                        ignoreDepth++;
6840
                        /* Check for integer overflow */
6841
0
                        if (ignoreDepth == 0) {
6842
0
                            xmlErrMemory(ctxt);
6843
0
                            return;
6844
0
                        }
6845
0
                    } else if ((RAW == ']') && (NXT(1) == ']') &&
6846
0
                               (NXT(2) == '>')) {
6847
0
                        SKIP(3);
6848
0
                        if (ignoreDepth == 0)
6849
0
                            break;
6850
0
                        ignoreDepth--;
6851
0
                    } else {
6852
0
                        NEXT;
6853
0
                    }
6854
0
                }
6855
6856
0
#ifdef LIBXML_VALID_ENABLED
6857
0
                if ((ctxt->validate) && (ctxt->inputNr > declInputNr)) {
6858
0
        xmlValidityError(ctxt, XML_ERR_ENTITY_BOUNDARY,
6859
0
                                     "All markup of the conditional section is"
6860
0
                                     " not in the same entity\n",
6861
0
                                     NULL, NULL);
6862
0
                }
6863
0
#endif
6864
0
            } else {
6865
0
                xmlFatalErr(ctxt, XML_ERR_CONDSEC_INVALID_KEYWORD, NULL);
6866
0
                return;
6867
0
            }
6868
0
        } else if ((depth > 0) &&
6869
0
                   (RAW == ']') && (NXT(1) == ']') && (NXT(2) == '>')) {
6870
0
            if (isFreshPE) {
6871
0
                xmlFatalErrMsg(ctxt, XML_ERR_CONDSEC_INVALID,
6872
0
                               "Parameter entity must match "
6873
0
                               "extSubsetDecl\n");
6874
0
                return;
6875
0
            }
6876
6877
0
            depth--;
6878
0
#ifdef LIBXML_VALID_ENABLED
6879
0
            if ((ctxt->validate) && (ctxt->inputNr > declInputNr)) {
6880
0
    xmlValidityError(ctxt, XML_ERR_ENTITY_BOUNDARY,
6881
0
                                 "All markup of the conditional section is not"
6882
0
                                 " in the same entity\n",
6883
0
                                 NULL, NULL);
6884
0
            }
6885
0
#endif
6886
0
            SKIP(3);
6887
0
        } else if ((RAW == '<') && ((NXT(1) == '!') || (NXT(1) == '?'))) {
6888
0
            isFreshPE = 0;
6889
0
            xmlParseMarkupDecl(ctxt);
6890
0
        } else if (RAW == '%') {
6891
0
            xmlParsePERefInternal(ctxt, 1);
6892
0
            if (ctxt->inputNr > declInputNr) {
6893
0
                isFreshPE = 1;
6894
0
                declInputNr = ctxt->inputNr;
6895
0
            }
6896
0
        } else {
6897
0
            xmlFatalErr(ctxt, XML_ERR_EXT_SUBSET_NOT_FINISHED, NULL);
6898
0
            return;
6899
0
        }
6900
6901
0
        if (depth == 0)
6902
0
            break;
6903
6904
0
        SKIP_BLANKS;
6905
0
        SHRINK;
6906
0
        GROW;
6907
0
    }
6908
0
}
6909
6910
/**
6911
 * Parse markup declarations. Always consumes '<!' or '<?'.
6912
 *
6913
 * @deprecated Internal function, don't use.
6914
 *
6915
 *     [29] markupdecl ::= elementdecl | AttlistDecl | EntityDecl |
6916
 *                         NotationDecl | PI | Comment
6917
 *
6918
 * [ VC: Proper Declaration/PE Nesting ]
6919
 * Parameter-entity replacement text must be properly nested with
6920
 * markup declarations. That is to say, if either the first character
6921
 * or the last character of a markup declaration (markupdecl above) is
6922
 * contained in the replacement text for a parameter-entity reference,
6923
 * both must be contained in the same replacement text.
6924
 *
6925
 * [ WFC: PEs in Internal Subset ]
6926
 * In the internal DTD subset, parameter-entity references can occur
6927
 * only where markup declarations can occur, not within markup declarations.
6928
 * (This does not apply to references that occur in external parameter
6929
 * entities or to the external subset.)
6930
 *
6931
 * @param ctxt  an XML parser context
6932
 */
6933
void
6934
0
xmlParseMarkupDecl(xmlParserCtxt *ctxt) {
6935
0
    GROW;
6936
0
    if (CUR == '<') {
6937
0
        if (NXT(1) == '!') {
6938
0
      switch (NXT(2)) {
6939
0
          case 'E':
6940
0
        if (NXT(3) == 'L')
6941
0
      xmlParseElementDecl(ctxt);
6942
0
        else if (NXT(3) == 'N')
6943
0
      xmlParseEntityDecl(ctxt);
6944
0
                    else
6945
0
                        SKIP(2);
6946
0
        break;
6947
0
          case 'A':
6948
0
        xmlParseAttributeListDecl(ctxt);
6949
0
        break;
6950
0
          case 'N':
6951
0
        xmlParseNotationDecl(ctxt);
6952
0
        break;
6953
0
          case '-':
6954
0
        xmlParseComment(ctxt);
6955
0
        break;
6956
0
    default:
6957
0
                    xmlFatalErr(ctxt,
6958
0
                                ctxt->inSubset == 2 ?
6959
0
                                    XML_ERR_EXT_SUBSET_NOT_FINISHED :
6960
0
                                    XML_ERR_INT_SUBSET_NOT_FINISHED,
6961
0
                                NULL);
6962
0
                    SKIP(2);
6963
0
        break;
6964
0
      }
6965
0
  } else if (NXT(1) == '?') {
6966
0
      xmlParsePI(ctxt);
6967
0
  }
6968
0
    }
6969
0
}
6970
6971
/**
6972
 * parse an XML declaration header for external entities
6973
 *
6974
 * @deprecated Internal function, don't use.
6975
 *
6976
 *     [77] TextDecl ::= '<?xml' VersionInfo? EncodingDecl S? '?>'
6977
 * @param ctxt  an XML parser context
6978
 */
6979
6980
void
6981
0
xmlParseTextDecl(xmlParserCtxt *ctxt) {
6982
0
    xmlChar *version;
6983
6984
    /*
6985
     * We know that '<?xml' is here.
6986
     */
6987
0
    if ((CMP5(CUR_PTR, '<', '?', 'x', 'm', 'l')) && (IS_BLANK_CH(NXT(5)))) {
6988
0
  SKIP(5);
6989
0
    } else {
6990
0
  xmlFatalErr(ctxt, XML_ERR_XMLDECL_NOT_STARTED, NULL);
6991
0
  return;
6992
0
    }
6993
6994
0
    if (SKIP_BLANKS == 0) {
6995
0
  xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED,
6996
0
           "Space needed after '<?xml'\n");
6997
0
    }
6998
6999
    /*
7000
     * We may have the VersionInfo here.
7001
     */
7002
0
    version = xmlParseVersionInfo(ctxt);
7003
0
    if (version == NULL) {
7004
0
  version = xmlCharStrdup(XML_DEFAULT_VERSION);
7005
0
        if (version == NULL) {
7006
0
            xmlErrMemory(ctxt);
7007
0
            return;
7008
0
        }
7009
0
    } else {
7010
0
  if (SKIP_BLANKS == 0) {
7011
0
      xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED,
7012
0
               "Space needed here\n");
7013
0
  }
7014
0
    }
7015
0
    ctxt->input->version = version;
7016
7017
    /*
7018
     * We must have the encoding declaration
7019
     */
7020
0
    xmlParseEncodingDecl(ctxt);
7021
7022
0
    SKIP_BLANKS;
7023
0
    if ((RAW == '?') && (NXT(1) == '>')) {
7024
0
        SKIP(2);
7025
0
    } else if (RAW == '>') {
7026
        /* Deprecated old WD ... */
7027
0
  xmlFatalErr(ctxt, XML_ERR_XMLDECL_NOT_FINISHED, NULL);
7028
0
  NEXT;
7029
0
    } else {
7030
0
        int c;
7031
7032
0
  xmlFatalErr(ctxt, XML_ERR_XMLDECL_NOT_FINISHED, NULL);
7033
0
        while ((PARSER_STOPPED(ctxt) == 0) && ((c = CUR) != 0)) {
7034
0
            NEXT;
7035
0
            if (c == '>')
7036
0
                break;
7037
0
        }
7038
0
    }
7039
0
}
7040
7041
/**
7042
 * parse Markup declarations from an external subset
7043
 *
7044
 * @deprecated Internal function, don't use.
7045
 *
7046
 *     [30] extSubset ::= textDecl? extSubsetDecl
7047
 *
7048
 *     [31] extSubsetDecl ::= (markupdecl | conditionalSect |
7049
 *                             PEReference | S) *
7050
 * @param ctxt  an XML parser context
7051
 * @param publicId  the public identifier
7052
 * @param systemId  the system identifier (URL)
7053
 */
7054
void
7055
xmlParseExternalSubset(xmlParserCtxt *ctxt, const xmlChar *publicId,
7056
0
                       const xmlChar *systemId) {
7057
0
    int oldInputNr;
7058
7059
0
    xmlCtxtInitializeLate(ctxt);
7060
7061
0
    xmlDetectEncoding(ctxt);
7062
7063
0
    if (CMP5(CUR_PTR, '<', '?', 'x', 'm', 'l')) {
7064
0
  xmlParseTextDecl(ctxt);
7065
0
    }
7066
0
    if (ctxt->myDoc == NULL) {
7067
0
        ctxt->myDoc = xmlNewDoc(BAD_CAST "1.0");
7068
0
  if (ctxt->myDoc == NULL) {
7069
0
      xmlErrMemory(ctxt);
7070
0
      return;
7071
0
  }
7072
0
  ctxt->myDoc->properties = XML_DOC_INTERNAL;
7073
0
    }
7074
0
    if ((ctxt->myDoc->intSubset == NULL) &&
7075
0
        (xmlCreateIntSubset(ctxt->myDoc, NULL, publicId, systemId) == NULL)) {
7076
0
        xmlErrMemory(ctxt);
7077
0
    }
7078
7079
0
    ctxt->inSubset = 2;
7080
0
    oldInputNr = ctxt->inputNr;
7081
7082
0
    SKIP_BLANKS;
7083
0
    while (!PARSER_STOPPED(ctxt)) {
7084
0
        if (ctxt->input->cur >= ctxt->input->end) {
7085
0
            if (ctxt->inputNr <= oldInputNr) {
7086
0
                xmlParserCheckEOF(ctxt, XML_ERR_EXT_SUBSET_NOT_FINISHED);
7087
0
                break;
7088
0
            }
7089
7090
0
            xmlPopPE(ctxt);
7091
0
        } else if ((RAW == '<') && (NXT(1) == '!') && (NXT(2) == '[')) {
7092
0
            xmlParseConditionalSections(ctxt);
7093
0
        } else if ((RAW == '<') && ((NXT(1) == '!') || (NXT(1) == '?'))) {
7094
0
            xmlParseMarkupDecl(ctxt);
7095
0
        } else if (RAW == '%') {
7096
0
            xmlParsePERefInternal(ctxt, 1);
7097
0
        } else {
7098
0
            xmlFatalErr(ctxt, XML_ERR_EXT_SUBSET_NOT_FINISHED, NULL);
7099
7100
0
            while (ctxt->inputNr > oldInputNr)
7101
0
                xmlPopPE(ctxt);
7102
0
            break;
7103
0
        }
7104
0
        SKIP_BLANKS;
7105
0
        SHRINK;
7106
0
        GROW;
7107
0
    }
7108
0
}
7109
7110
/**
7111
 * parse and handle entity references in content, depending on the SAX
7112
 * interface, this may end-up in a call to character() if this is a
7113
 * CharRef, a predefined entity, if there is no reference() callback.
7114
 * or if the parser was asked to switch to that mode.
7115
 *
7116
 * @deprecated Internal function, don't use.
7117
 *
7118
 * Always consumes '&'.
7119
 *
7120
 *     [67] Reference ::= EntityRef | CharRef
7121
 * @param ctxt  an XML parser context
7122
 */
7123
void
7124
0
xmlParseReference(xmlParserCtxt *ctxt) {
7125
0
    xmlEntityPtr ent = NULL;
7126
0
    const xmlChar *name;
7127
0
    xmlChar *val;
7128
7129
0
    if (RAW != '&')
7130
0
        return;
7131
7132
    /*
7133
     * Simple case of a CharRef
7134
     */
7135
0
    if (NXT(1) == '#') {
7136
0
  int i = 0;
7137
0
  xmlChar out[16];
7138
0
  int value = xmlParseCharRef(ctxt);
7139
7140
0
  if (value == 0)
7141
0
      return;
7142
7143
        /*
7144
         * Just encode the value in UTF-8
7145
         */
7146
0
        COPY_BUF(out, i, value);
7147
0
        out[i] = 0;
7148
0
        if ((ctxt->sax != NULL) && (ctxt->sax->characters != NULL) &&
7149
0
            (!ctxt->disableSAX))
7150
0
            ctxt->sax->characters(ctxt->userData, out, i);
7151
0
  return;
7152
0
    }
7153
7154
    /*
7155
     * We are seeing an entity reference
7156
     */
7157
0
    name = xmlParseEntityRefInternal(ctxt);
7158
0
    if (name == NULL)
7159
0
        return;
7160
0
    ent = xmlLookupGeneralEntity(ctxt, name, /* isAttr */ 0);
7161
0
    if (ent == NULL) {
7162
        /*
7163
         * Create a reference for undeclared entities.
7164
         */
7165
0
        if ((ctxt->replaceEntities == 0) &&
7166
0
            (ctxt->sax != NULL) &&
7167
0
            (ctxt->disableSAX == 0) &&
7168
0
            (ctxt->sax->reference != NULL)) {
7169
0
            ctxt->sax->reference(ctxt->userData, name);
7170
0
        }
7171
0
        return;
7172
0
    }
7173
0
    if (!ctxt->wellFormed)
7174
0
  return;
7175
7176
    /* special case of predefined entities */
7177
0
    if ((ent->name == NULL) ||
7178
0
        (ent->etype == XML_INTERNAL_PREDEFINED_ENTITY)) {
7179
0
  val = ent->content;
7180
0
  if (val == NULL) return;
7181
  /*
7182
   * inline the entity.
7183
   */
7184
0
  if ((ctxt->sax != NULL) && (ctxt->sax->characters != NULL) &&
7185
0
      (!ctxt->disableSAX))
7186
0
      ctxt->sax->characters(ctxt->userData, val, xmlStrlen(val));
7187
0
  return;
7188
0
    }
7189
7190
    /*
7191
     * Some users try to parse entities on their own and used to set
7192
     * the renamed "checked" member. Fix the flags to cover this
7193
     * case.
7194
     */
7195
0
    if (((ent->flags & XML_ENT_PARSED) == 0) && (ent->children != NULL))
7196
0
        ent->flags |= XML_ENT_PARSED;
7197
7198
    /*
7199
     * The first reference to the entity trigger a parsing phase
7200
     * where the ent->children is filled with the result from
7201
     * the parsing.
7202
     * Note: external parsed entities will not be loaded, it is not
7203
     * required for a non-validating parser, unless the parsing option
7204
     * of validating, or substituting entities were given. Doing so is
7205
     * far more secure as the parser will only process data coming from
7206
     * the document entity by default.
7207
     *
7208
     * FIXME: This doesn't work correctly since entities can be
7209
     * expanded with different namespace declarations in scope.
7210
     * For example:
7211
     *
7212
     * <!DOCTYPE doc [
7213
     *   <!ENTITY ent "<ns:elem/>">
7214
     * ]>
7215
     * <doc>
7216
     *   <decl1 xmlns:ns="urn:ns1">
7217
     *     &ent;
7218
     *   </decl1>
7219
     *   <decl2 xmlns:ns="urn:ns2">
7220
     *     &ent;
7221
     *   </decl2>
7222
     * </doc>
7223
     *
7224
     * Proposed fix:
7225
     *
7226
     * - Ignore current namespace declarations when parsing the
7227
     *   entity. If a prefix can't be resolved, don't report an error
7228
     *   but mark it as unresolved.
7229
     * - Try to resolve these prefixes when expanding the entity.
7230
     *   This will require a specialized version of xmlStaticCopyNode
7231
     *   which can also make use of the namespace hash table to avoid
7232
     *   quadratic behavior.
7233
     *
7234
     * Alternatively, we could simply reparse the entity on each
7235
     * expansion like we already do with custom SAX callbacks.
7236
     * External entity content should be cached in this case.
7237
     */
7238
0
    if ((ent->etype == XML_INTERNAL_GENERAL_ENTITY) ||
7239
0
        (((ctxt->options & XML_PARSE_NO_XXE) == 0) &&
7240
0
         ((ctxt->replaceEntities) ||
7241
0
          (ctxt->validate)))) {
7242
0
        if ((ent->flags & XML_ENT_PARSED) == 0) {
7243
0
            xmlCtxtParseEntity(ctxt, ent);
7244
0
        } else if (ent->children == NULL) {
7245
            /*
7246
             * Probably running in SAX mode and the callbacks don't
7247
             * build the entity content. Parse the entity again.
7248
             *
7249
             * This will also be triggered in normal tree builder mode
7250
             * if an entity happens to be empty, causing unnecessary
7251
             * reloads. It's hard to come up with a reliable check in
7252
             * which mode we're running.
7253
             */
7254
0
            xmlCtxtParseEntity(ctxt, ent);
7255
0
        }
7256
0
    }
7257
7258
    /*
7259
     * We also check for amplification if entities aren't substituted.
7260
     * They might be expanded later.
7261
     */
7262
0
    if (xmlParserEntityCheck(ctxt, ent->expandedSize))
7263
0
        return;
7264
7265
0
    if ((ctxt->sax == NULL) || (ctxt->disableSAX))
7266
0
        return;
7267
7268
0
    if (ctxt->replaceEntities == 0) {
7269
  /*
7270
   * Create a reference
7271
   */
7272
0
        if (ctxt->sax->reference != NULL)
7273
0
      ctxt->sax->reference(ctxt->userData, ent->name);
7274
0
    } else if ((ent->children != NULL) && (ctxt->node != NULL)) {
7275
0
        xmlNodePtr copy, cur;
7276
7277
        /*
7278
         * Seems we are generating the DOM content, copy the tree
7279
   */
7280
0
        cur = ent->children;
7281
7282
        /*
7283
         * Handle first text node with SAX to coalesce text efficiently
7284
         */
7285
0
        if ((cur->type == XML_TEXT_NODE) ||
7286
0
            (cur->type == XML_CDATA_SECTION_NODE)) {
7287
0
            int len = xmlStrlen(cur->content);
7288
7289
0
            if ((cur->type == XML_TEXT_NODE) ||
7290
0
                (ctxt->options & XML_PARSE_NOCDATA)) {
7291
0
                if (ctxt->sax->characters != NULL)
7292
0
                    ctxt->sax->characters(ctxt, cur->content, len);
7293
0
            } else {
7294
0
                if (ctxt->sax->cdataBlock != NULL)
7295
0
                    ctxt->sax->cdataBlock(ctxt, cur->content, len);
7296
0
            }
7297
7298
0
            cur = cur->next;
7299
0
        }
7300
7301
0
        while (cur != NULL) {
7302
0
            xmlNodePtr last;
7303
7304
            /*
7305
             * Handle last text node with SAX to coalesce text efficiently
7306
             */
7307
0
            if ((cur->next == NULL) &&
7308
0
                ((cur->type == XML_TEXT_NODE) ||
7309
0
                 (cur->type == XML_CDATA_SECTION_NODE))) {
7310
0
                int len = xmlStrlen(cur->content);
7311
7312
0
                if ((cur->type == XML_TEXT_NODE) ||
7313
0
                    (ctxt->options & XML_PARSE_NOCDATA)) {
7314
0
                    if (ctxt->sax->characters != NULL)
7315
0
                        ctxt->sax->characters(ctxt, cur->content, len);
7316
0
                } else {
7317
0
                    if (ctxt->sax->cdataBlock != NULL)
7318
0
                        ctxt->sax->cdataBlock(ctxt, cur->content, len);
7319
0
                }
7320
7321
0
                break;
7322
0
            }
7323
7324
            /*
7325
             * Reset coalesce buffer stats only for non-text nodes.
7326
             */
7327
0
            ctxt->nodemem = 0;
7328
0
            ctxt->nodelen = 0;
7329
7330
0
            copy = xmlDocCopyNode(cur, ctxt->myDoc, 1);
7331
7332
0
            if (copy == NULL) {
7333
0
                xmlErrMemory(ctxt);
7334
0
                break;
7335
0
            }
7336
7337
0
            if (ctxt->parseMode == XML_PARSE_READER) {
7338
                /* Needed for reader */
7339
0
                copy->extra = cur->extra;
7340
                /* Maybe needed for reader */
7341
0
                copy->_private = cur->_private;
7342
0
            }
7343
7344
0
            copy->parent = ctxt->node;
7345
0
            last = ctxt->node->last;
7346
0
            if (last == NULL) {
7347
0
                ctxt->node->children = copy;
7348
0
            } else {
7349
0
                last->next = copy;
7350
0
                copy->prev = last;
7351
0
            }
7352
0
            ctxt->node->last = copy;
7353
7354
0
            cur = cur->next;
7355
0
        }
7356
0
    }
7357
0
}
7358
7359
static void
7360
0
xmlHandleUndeclaredEntity(xmlParserCtxtPtr ctxt, const xmlChar *name) {
7361
    /*
7362
     * [ WFC: Entity Declared ]
7363
     * In a document without any DTD, a document with only an
7364
     * internal DTD subset which contains no parameter entity
7365
     * references, or a document with "standalone='yes'", the
7366
     * Name given in the entity reference must match that in an
7367
     * entity declaration, except that well-formed documents
7368
     * need not declare any of the following entities: amp, lt,
7369
     * gt, apos, quot.
7370
     * The declaration of a parameter entity must precede any
7371
     * reference to it.
7372
     * Similarly, the declaration of a general entity must
7373
     * precede any reference to it which appears in a default
7374
     * value in an attribute-list declaration. Note that if
7375
     * entities are declared in the external subset or in
7376
     * external parameter entities, a non-validating processor
7377
     * is not obligated to read and process their declarations;
7378
     * for such documents, the rule that an entity must be
7379
     * declared is a well-formedness constraint only if
7380
     * standalone='yes'.
7381
     */
7382
0
    if ((ctxt->standalone == 1) ||
7383
0
        ((ctxt->hasExternalSubset == 0) &&
7384
0
         (ctxt->hasPErefs == 0))) {
7385
0
        xmlFatalErrMsgStr(ctxt, XML_ERR_UNDECLARED_ENTITY,
7386
0
                          "Entity '%s' not defined\n", name);
7387
0
#ifdef LIBXML_VALID_ENABLED
7388
0
    } else if (ctxt->validate) {
7389
        /*
7390
         * [ VC: Entity Declared ]
7391
         * In a document with an external subset or external
7392
         * parameter entities with "standalone='no'", ...
7393
         * ... The declaration of a parameter entity must
7394
         * precede any reference to it...
7395
         */
7396
0
        xmlValidityError(ctxt, XML_ERR_UNDECLARED_ENTITY,
7397
0
                         "Entity '%s' not defined\n", name, NULL);
7398
0
#endif
7399
0
    } else if ((ctxt->loadsubset & ~XML_SKIP_IDS) ||
7400
0
               ((ctxt->replaceEntities) &&
7401
0
                ((ctxt->options & XML_PARSE_NO_XXE) == 0))) {
7402
        /*
7403
         * Also raise a non-fatal error
7404
         *
7405
         * - if the external subset is loaded and all entity declarations
7406
         *   should be available, or
7407
         * - entity substition was requested without restricting
7408
         *   external entity access.
7409
         */
7410
0
        xmlErrMsgStr(ctxt, XML_WAR_UNDECLARED_ENTITY,
7411
0
                     "Entity '%s' not defined\n", name);
7412
0
    } else {
7413
0
        xmlWarningMsg(ctxt, XML_WAR_UNDECLARED_ENTITY,
7414
0
                      "Entity '%s' not defined\n", name, NULL);
7415
0
    }
7416
7417
0
    ctxt->valid = 0;
7418
0
}
7419
7420
static xmlEntityPtr
7421
0
xmlLookupGeneralEntity(xmlParserCtxtPtr ctxt, const xmlChar *name, int inAttr) {
7422
0
    xmlEntityPtr ent = NULL;
7423
7424
    /*
7425
     * Predefined entities override any extra definition
7426
     */
7427
0
    if ((ctxt->options & XML_PARSE_OLDSAX) == 0) {
7428
0
        ent = xmlGetPredefinedEntity(name);
7429
0
        if (ent != NULL)
7430
0
            return(ent);
7431
0
    }
7432
7433
    /*
7434
     * Ask first SAX for entity resolution, otherwise try the
7435
     * entities which may have stored in the parser context.
7436
     */
7437
0
    if (ctxt->sax != NULL) {
7438
0
  if (ctxt->sax->getEntity != NULL)
7439
0
      ent = ctxt->sax->getEntity(ctxt->userData, name);
7440
0
  if ((ctxt->wellFormed == 1 ) && (ent == NULL) &&
7441
0
      (ctxt->options & XML_PARSE_OLDSAX))
7442
0
      ent = xmlGetPredefinedEntity(name);
7443
0
  if ((ctxt->wellFormed == 1 ) && (ent == NULL) &&
7444
0
      (ctxt->userData==ctxt)) {
7445
0
      ent = xmlSAX2GetEntity(ctxt, name);
7446
0
  }
7447
0
    }
7448
7449
0
    if (ent == NULL) {
7450
0
        xmlHandleUndeclaredEntity(ctxt, name);
7451
0
    }
7452
7453
    /*
7454
     * [ WFC: Parsed Entity ]
7455
     * An entity reference must not contain the name of an
7456
     * unparsed entity
7457
     */
7458
0
    else if (ent->etype == XML_EXTERNAL_GENERAL_UNPARSED_ENTITY) {
7459
0
  xmlFatalErrMsgStr(ctxt, XML_ERR_UNPARSED_ENTITY,
7460
0
     "Entity reference to unparsed entity %s\n", name);
7461
0
        ent = NULL;
7462
0
    }
7463
7464
    /*
7465
     * [ WFC: No External Entity References ]
7466
     * Attribute values cannot contain direct or indirect
7467
     * entity references to external entities.
7468
     */
7469
0
    else if (ent->etype == XML_EXTERNAL_GENERAL_PARSED_ENTITY) {
7470
0
        if (inAttr) {
7471
0
            xmlFatalErrMsgStr(ctxt, XML_ERR_ENTITY_IS_EXTERNAL,
7472
0
                 "Attribute references external entity '%s'\n", name);
7473
0
            ent = NULL;
7474
0
        }
7475
0
    }
7476
7477
0
    return(ent);
7478
0
}
7479
7480
/**
7481
 * Parse an entity reference. Always consumes '&'.
7482
 *
7483
 *     [68] EntityRef ::= '&' Name ';'
7484
 *
7485
 * @param ctxt  an XML parser context
7486
 * @returns the name, or NULL in case of error.
7487
 */
7488
static const xmlChar *
7489
0
xmlParseEntityRefInternal(xmlParserCtxtPtr ctxt) {
7490
0
    const xmlChar *name;
7491
7492
0
    GROW;
7493
7494
0
    if (RAW != '&')
7495
0
        return(NULL);
7496
0
    NEXT;
7497
0
    name = xmlParseName(ctxt);
7498
0
    if (name == NULL) {
7499
0
  xmlFatalErrMsg(ctxt, XML_ERR_NAME_REQUIRED,
7500
0
           "xmlParseEntityRef: no name\n");
7501
0
        return(NULL);
7502
0
    }
7503
0
    if (RAW != ';') {
7504
0
  xmlFatalErr(ctxt, XML_ERR_ENTITYREF_SEMICOL_MISSING, NULL);
7505
0
  return(NULL);
7506
0
    }
7507
0
    NEXT;
7508
7509
0
    return(name);
7510
0
}
7511
7512
/**
7513
 * @deprecated Internal function, don't use.
7514
 *
7515
 * @param ctxt  an XML parser context
7516
 * @returns the xmlEntity if found, or NULL otherwise.
7517
 */
7518
xmlEntity *
7519
0
xmlParseEntityRef(xmlParserCtxt *ctxt) {
7520
0
    const xmlChar *name;
7521
7522
0
    if (ctxt == NULL)
7523
0
        return(NULL);
7524
7525
0
    name = xmlParseEntityRefInternal(ctxt);
7526
0
    if (name == NULL)
7527
0
        return(NULL);
7528
7529
0
    return(xmlLookupGeneralEntity(ctxt, name, /* inAttr */ 0));
7530
0
}
7531
7532
/**
7533
 * parse ENTITY references declarations, but this version parses it from
7534
 * a string value.
7535
 *
7536
 *     [68] EntityRef ::= '&' Name ';'
7537
 *
7538
 * [ WFC: Entity Declared ]
7539
 * In a document without any DTD, a document with only an internal DTD
7540
 * subset which contains no parameter entity references, or a document
7541
 * with "standalone='yes'", the Name given in the entity reference
7542
 * must match that in an entity declaration, except that well-formed
7543
 * documents need not declare any of the following entities: amp, lt,
7544
 * gt, apos, quot.  The declaration of a parameter entity must precede
7545
 * any reference to it.  Similarly, the declaration of a general entity
7546
 * must precede any reference to it which appears in a default value in an
7547
 * attribute-list declaration. Note that if entities are declared in the
7548
 * external subset or in external parameter entities, a non-validating
7549
 * processor is not obligated to read and process their declarations;
7550
 * for such documents, the rule that an entity must be declared is a
7551
 * well-formedness constraint only if standalone='yes'.
7552
 *
7553
 * [ WFC: Parsed Entity ]
7554
 * An entity reference must not contain the name of an unparsed entity
7555
 *
7556
 * @param ctxt  an XML parser context
7557
 * @param str  a pointer to an index in the string
7558
 * @returns the xmlEntity if found, or NULL otherwise. The str pointer
7559
 * is updated to the current location in the string.
7560
 */
7561
static xmlChar *
7562
0
xmlParseStringEntityRef(xmlParserCtxtPtr ctxt, const xmlChar ** str) {
7563
0
    xmlChar *name;
7564
0
    const xmlChar *ptr;
7565
0
    xmlChar cur;
7566
7567
0
    if ((str == NULL) || (*str == NULL))
7568
0
        return(NULL);
7569
0
    ptr = *str;
7570
0
    cur = *ptr;
7571
0
    if (cur != '&')
7572
0
  return(NULL);
7573
7574
0
    ptr++;
7575
0
    name = xmlParseStringName(ctxt, &ptr);
7576
0
    if (name == NULL) {
7577
0
  xmlFatalErrMsg(ctxt, XML_ERR_NAME_REQUIRED,
7578
0
           "xmlParseStringEntityRef: no name\n");
7579
0
  *str = ptr;
7580
0
  return(NULL);
7581
0
    }
7582
0
    if (*ptr != ';') {
7583
0
  xmlFatalErr(ctxt, XML_ERR_ENTITYREF_SEMICOL_MISSING, NULL);
7584
0
        xmlFree(name);
7585
0
  *str = ptr;
7586
0
  return(NULL);
7587
0
    }
7588
0
    ptr++;
7589
7590
0
    *str = ptr;
7591
0
    return(name);
7592
0
}
7593
7594
/**
7595
 * Parse a parameter entity reference. Always consumes '%'.
7596
 *
7597
 * The entity content is handled directly by pushing it's content as
7598
 * a new input stream.
7599
 *
7600
 *     [69] PEReference ::= '%' Name ';'
7601
 *
7602
 * [ WFC: No Recursion ]
7603
 * A parsed entity must not contain a recursive
7604
 * reference to itself, either directly or indirectly.
7605
 *
7606
 * [ WFC: Entity Declared ]
7607
 * In a document without any DTD, a document with only an internal DTD
7608
 * subset which contains no parameter entity references, or a document
7609
 * with "standalone='yes'", ...  ... The declaration of a parameter
7610
 * entity must precede any reference to it...
7611
 *
7612
 * [ VC: Entity Declared ]
7613
 * In a document with an external subset or external parameter entities
7614
 * with "standalone='no'", ...  ... The declaration of a parameter entity
7615
 * must precede any reference to it...
7616
 *
7617
 * [ WFC: In DTD ]
7618
 * Parameter-entity references may only appear in the DTD.
7619
 * NOTE: misleading but this is handled.
7620
 *
7621
 * @param ctxt  an XML parser context
7622
 * @param markupDecl  whether the PERef starts a markup declaration
7623
 */
7624
static void
7625
0
xmlParsePERefInternal(xmlParserCtxt *ctxt, int markupDecl) {
7626
0
    const xmlChar *name;
7627
0
    xmlEntityPtr entity = NULL;
7628
0
    xmlParserInputPtr input;
7629
7630
0
    if (RAW != '%')
7631
0
        return;
7632
0
    NEXT;
7633
0
    name = xmlParseName(ctxt);
7634
0
    if (name == NULL) {
7635
0
  xmlFatalErrMsg(ctxt, XML_ERR_PEREF_NO_NAME, "PEReference: no name\n");
7636
0
  return;
7637
0
    }
7638
0
    if (RAW != ';') {
7639
0
  xmlFatalErr(ctxt, XML_ERR_PEREF_SEMICOL_MISSING, NULL);
7640
0
        return;
7641
0
    }
7642
7643
0
    NEXT;
7644
7645
    /* Must be set before xmlHandleUndeclaredEntity */
7646
0
    ctxt->hasPErefs = 1;
7647
7648
    /*
7649
     * Request the entity from SAX
7650
     */
7651
0
    if ((ctxt->sax != NULL) &&
7652
0
  (ctxt->sax->getParameterEntity != NULL))
7653
0
  entity = ctxt->sax->getParameterEntity(ctxt->userData, name);
7654
7655
0
    if (entity == NULL) {
7656
0
        xmlHandleUndeclaredEntity(ctxt, name);
7657
0
    } else {
7658
  /*
7659
   * Internal checking in case the entity quest barfed
7660
   */
7661
0
  if ((entity->etype != XML_INTERNAL_PARAMETER_ENTITY) &&
7662
0
      (entity->etype != XML_EXTERNAL_PARAMETER_ENTITY)) {
7663
0
      xmlWarningMsg(ctxt, XML_WAR_UNDECLARED_ENTITY,
7664
0
      "Internal: %%%s; is not a parameter entity\n",
7665
0
        name, NULL);
7666
0
  } else {
7667
0
      if ((entity->etype == XML_EXTERNAL_PARAMETER_ENTITY) &&
7668
0
                ((ctxt->options & XML_PARSE_NO_XXE) ||
7669
0
     (((ctxt->loadsubset & ~XML_SKIP_IDS) == 0) &&
7670
0
      (ctxt->replaceEntities == 0) &&
7671
0
      (ctxt->validate == 0))))
7672
0
    return;
7673
7674
0
            if (entity->flags & XML_ENT_EXPANDING) {
7675
0
                xmlFatalErr(ctxt, XML_ERR_ENTITY_LOOP, NULL);
7676
0
                xmlHaltParser(ctxt);
7677
0
                return;
7678
0
            }
7679
7680
0
      input = xmlNewEntityInputStream(ctxt, entity);
7681
0
      if (xmlCtxtPushInput(ctxt, input) < 0) {
7682
0
                xmlFreeInputStream(input);
7683
0
    return;
7684
0
            }
7685
7686
0
            entity->flags |= XML_ENT_EXPANDING;
7687
7688
0
            if (markupDecl)
7689
0
                input->flags |= XML_INPUT_MARKUP_DECL;
7690
7691
0
            GROW;
7692
7693
0
      if (entity->etype == XML_EXTERNAL_PARAMETER_ENTITY) {
7694
0
                xmlDetectEncoding(ctxt);
7695
7696
0
                if ((CMP5(CUR_PTR, '<', '?', 'x', 'm', 'l')) &&
7697
0
                    (IS_BLANK_CH(NXT(5)))) {
7698
0
                    xmlParseTextDecl(ctxt);
7699
0
                }
7700
0
            }
7701
0
  }
7702
0
    }
7703
0
}
7704
7705
/**
7706
 * Parse a parameter entity reference.
7707
 *
7708
 * @deprecated Internal function, don't use.
7709
 *
7710
 * @param ctxt  an XML parser context
7711
 */
7712
void
7713
0
xmlParsePEReference(xmlParserCtxt *ctxt) {
7714
0
    xmlParsePERefInternal(ctxt, 0);
7715
0
}
7716
7717
/**
7718
 * Load the content of an entity.
7719
 *
7720
 * @param ctxt  an XML parser context
7721
 * @param entity  an unloaded system entity
7722
 * @returns 0 in case of success and -1 in case of failure
7723
 */
7724
static int
7725
0
xmlLoadEntityContent(xmlParserCtxtPtr ctxt, xmlEntityPtr entity) {
7726
0
    xmlParserInputPtr oldinput, input = NULL;
7727
0
    xmlParserInputPtr *oldinputTab;
7728
0
    xmlChar *oldencoding;
7729
0
    xmlChar *content = NULL;
7730
0
    xmlResourceType rtype;
7731
0
    size_t length, i;
7732
0
    int oldinputNr, oldinputMax;
7733
0
    int ret = -1;
7734
0
    int res;
7735
7736
0
    if ((ctxt == NULL) || (entity == NULL) ||
7737
0
        ((entity->etype != XML_EXTERNAL_PARAMETER_ENTITY) &&
7738
0
   (entity->etype != XML_EXTERNAL_GENERAL_PARSED_ENTITY)) ||
7739
0
  (entity->content != NULL)) {
7740
0
  xmlFatalErr(ctxt, XML_ERR_ARGUMENT,
7741
0
              "xmlLoadEntityContent parameter error");
7742
0
        return(-1);
7743
0
    }
7744
7745
0
    if (entity->etype == XML_EXTERNAL_PARAMETER_ENTITY)
7746
0
        rtype = XML_RESOURCE_PARAMETER_ENTITY;
7747
0
    else
7748
0
        rtype = XML_RESOURCE_GENERAL_ENTITY;
7749
7750
0
    input = xmlLoadResource(ctxt, (char *) entity->URI,
7751
0
                            (char *) entity->ExternalID, rtype);
7752
0
    if (input == NULL)
7753
0
        return(-1);
7754
7755
0
    oldinput = ctxt->input;
7756
0
    oldinputNr = ctxt->inputNr;
7757
0
    oldinputMax = ctxt->inputMax;
7758
0
    oldinputTab = ctxt->inputTab;
7759
0
    oldencoding = ctxt->encoding;
7760
7761
0
    ctxt->input = NULL;
7762
0
    ctxt->inputNr = 0;
7763
0
    ctxt->inputMax = 1;
7764
0
    ctxt->encoding = NULL;
7765
0
    ctxt->inputTab = xmlMalloc(sizeof(xmlParserInputPtr));
7766
0
    if (ctxt->inputTab == NULL) {
7767
0
        xmlErrMemory(ctxt);
7768
0
        xmlFreeInputStream(input);
7769
0
        goto error;
7770
0
    }
7771
7772
0
    xmlBufResetInput(input->buf->buffer, input);
7773
7774
0
    if (xmlCtxtPushInput(ctxt, input) < 0) {
7775
0
        xmlFreeInputStream(input);
7776
0
        goto error;
7777
0
    }
7778
7779
0
    xmlDetectEncoding(ctxt);
7780
7781
    /*
7782
     * Parse a possible text declaration first
7783
     */
7784
0
    if ((CMP5(CUR_PTR, '<', '?', 'x', 'm', 'l')) && (IS_BLANK_CH(NXT(5)))) {
7785
0
  xmlParseTextDecl(ctxt);
7786
        /*
7787
         * An XML-1.0 document can't reference an entity not XML-1.0
7788
         */
7789
0
        if ((xmlStrEqual(ctxt->version, BAD_CAST "1.0")) &&
7790
0
            (!xmlStrEqual(ctxt->input->version, BAD_CAST "1.0"))) {
7791
0
            xmlFatalErrMsg(ctxt, XML_ERR_VERSION_MISMATCH,
7792
0
                           "Version mismatch between document and entity\n");
7793
0
        }
7794
0
    }
7795
7796
0
    length = input->cur - input->base;
7797
0
    xmlBufShrink(input->buf->buffer, length);
7798
0
    xmlSaturatedAdd(&ctxt->sizeentities, length);
7799
7800
0
    while ((res = xmlParserInputBufferGrow(input->buf, 4096)) > 0)
7801
0
        ;
7802
7803
0
    xmlBufResetInput(input->buf->buffer, input);
7804
7805
0
    if (res < 0) {
7806
0
        xmlCtxtErrIO(ctxt, input->buf->error, NULL);
7807
0
        goto error;
7808
0
    }
7809
7810
0
    length = xmlBufUse(input->buf->buffer);
7811
0
    if (length > INT_MAX) {
7812
0
        xmlErrMemory(ctxt);
7813
0
        goto error;
7814
0
    }
7815
7816
0
    content = xmlStrndup(xmlBufContent(input->buf->buffer), length);
7817
0
    if (content == NULL) {
7818
0
        xmlErrMemory(ctxt);
7819
0
        goto error;
7820
0
    }
7821
7822
0
    for (i = 0; i < length; ) {
7823
0
        int clen = length - i;
7824
0
        int c = xmlGetUTF8Char(content + i, &clen);
7825
7826
0
        if ((c < 0) || (!IS_CHAR(c))) {
7827
0
            xmlFatalErrMsgInt(ctxt, XML_ERR_INVALID_CHAR,
7828
0
                              "xmlLoadEntityContent: invalid char value %d\n",
7829
0
                              content[i]);
7830
0
            goto error;
7831
0
        }
7832
0
        i += clen;
7833
0
    }
7834
7835
0
    xmlSaturatedAdd(&ctxt->sizeentities, length);
7836
0
    entity->content = content;
7837
0
    entity->length = length;
7838
0
    content = NULL;
7839
0
    ret = 0;
7840
7841
0
error:
7842
0
    while (ctxt->inputNr > 0)
7843
0
        xmlFreeInputStream(xmlCtxtPopInput(ctxt));
7844
0
    xmlFree(ctxt->inputTab);
7845
0
    xmlFree(ctxt->encoding);
7846
7847
0
    ctxt->input = oldinput;
7848
0
    ctxt->inputNr = oldinputNr;
7849
0
    ctxt->inputMax = oldinputMax;
7850
0
    ctxt->inputTab = oldinputTab;
7851
0
    ctxt->encoding = oldencoding;
7852
7853
0
    xmlFree(content);
7854
7855
0
    return(ret);
7856
0
}
7857
7858
/**
7859
 * parse PEReference declarations
7860
 *
7861
 *     [69] PEReference ::= '%' Name ';'
7862
 *
7863
 * [ WFC: No Recursion ]
7864
 * A parsed entity must not contain a recursive
7865
 * reference to itself, either directly or indirectly.
7866
 *
7867
 * [ WFC: Entity Declared ]
7868
 * In a document without any DTD, a document with only an internal DTD
7869
 * subset which contains no parameter entity references, or a document
7870
 * with "standalone='yes'", ...  ... The declaration of a parameter
7871
 * entity must precede any reference to it...
7872
 *
7873
 * [ VC: Entity Declared ]
7874
 * In a document with an external subset or external parameter entities
7875
 * with "standalone='no'", ...  ... The declaration of a parameter entity
7876
 * must precede any reference to it...
7877
 *
7878
 * [ WFC: In DTD ]
7879
 * Parameter-entity references may only appear in the DTD.
7880
 * NOTE: misleading but this is handled.
7881
 *
7882
 * @param ctxt  an XML parser context
7883
 * @param str  a pointer to an index in the string
7884
 * @returns the string of the entity content.
7885
 *         str is updated to the current value of the index
7886
 */
7887
static xmlEntityPtr
7888
0
xmlParseStringPEReference(xmlParserCtxtPtr ctxt, const xmlChar **str) {
7889
0
    const xmlChar *ptr;
7890
0
    xmlChar cur;
7891
0
    xmlChar *name;
7892
0
    xmlEntityPtr entity = NULL;
7893
7894
0
    if ((str == NULL) || (*str == NULL)) return(NULL);
7895
0
    ptr = *str;
7896
0
    cur = *ptr;
7897
0
    if (cur != '%')
7898
0
        return(NULL);
7899
0
    ptr++;
7900
0
    name = xmlParseStringName(ctxt, &ptr);
7901
0
    if (name == NULL) {
7902
0
  xmlFatalErrMsg(ctxt, XML_ERR_NAME_REQUIRED,
7903
0
           "xmlParseStringPEReference: no name\n");
7904
0
  *str = ptr;
7905
0
  return(NULL);
7906
0
    }
7907
0
    cur = *ptr;
7908
0
    if (cur != ';') {
7909
0
  xmlFatalErr(ctxt, XML_ERR_ENTITYREF_SEMICOL_MISSING, NULL);
7910
0
  xmlFree(name);
7911
0
  *str = ptr;
7912
0
  return(NULL);
7913
0
    }
7914
0
    ptr++;
7915
7916
    /* Must be set before xmlHandleUndeclaredEntity */
7917
0
    ctxt->hasPErefs = 1;
7918
7919
    /*
7920
     * Request the entity from SAX
7921
     */
7922
0
    if ((ctxt->sax != NULL) &&
7923
0
  (ctxt->sax->getParameterEntity != NULL))
7924
0
  entity = ctxt->sax->getParameterEntity(ctxt->userData, name);
7925
7926
0
    if (entity == NULL) {
7927
0
        xmlHandleUndeclaredEntity(ctxt, name);
7928
0
    } else {
7929
  /*
7930
   * Internal checking in case the entity quest barfed
7931
   */
7932
0
  if ((entity->etype != XML_INTERNAL_PARAMETER_ENTITY) &&
7933
0
      (entity->etype != XML_EXTERNAL_PARAMETER_ENTITY)) {
7934
0
      xmlWarningMsg(ctxt, XML_WAR_UNDECLARED_ENTITY,
7935
0
        "%%%s; is not a parameter entity\n",
7936
0
        name, NULL);
7937
0
  }
7938
0
    }
7939
7940
0
    xmlFree(name);
7941
0
    *str = ptr;
7942
0
    return(entity);
7943
0
}
7944
7945
/**
7946
 * parse a DOCTYPE declaration
7947
 *
7948
 * @deprecated Internal function, don't use.
7949
 *
7950
 *     [28] doctypedecl ::= '<!DOCTYPE' S Name (S ExternalID)? S?
7951
 *                          ('[' (markupdecl | PEReference | S)* ']' S?)? '>'
7952
 *
7953
 * [ VC: Root Element Type ]
7954
 * The Name in the document type declaration must match the element
7955
 * type of the root element.
7956
 *
7957
 * @param ctxt  an XML parser context
7958
 */
7959
7960
void
7961
0
xmlParseDocTypeDecl(xmlParserCtxt *ctxt) {
7962
0
    const xmlChar *name = NULL;
7963
0
    xmlChar *publicId = NULL;
7964
0
    xmlChar *URI = NULL;
7965
7966
    /*
7967
     * We know that '<!DOCTYPE' has been detected.
7968
     */
7969
0
    SKIP(9);
7970
7971
0
    if (SKIP_BLANKS == 0) {
7972
0
        xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED,
7973
0
                       "Space required after 'DOCTYPE'\n");
7974
0
    }
7975
7976
    /*
7977
     * Parse the DOCTYPE name.
7978
     */
7979
0
    name = xmlParseName(ctxt);
7980
0
    if (name == NULL) {
7981
0
  xmlFatalErrMsg(ctxt, XML_ERR_NAME_REQUIRED,
7982
0
           "xmlParseDocTypeDecl : no DOCTYPE name !\n");
7983
0
    }
7984
0
    ctxt->intSubName = name;
7985
7986
0
    SKIP_BLANKS;
7987
7988
    /*
7989
     * Check for public and system identifier (URI)
7990
     */
7991
0
    URI = xmlParseExternalID(ctxt, &publicId, 1);
7992
7993
0
    if ((URI != NULL) || (publicId != NULL)) {
7994
0
        ctxt->hasExternalSubset = 1;
7995
0
    }
7996
0
    ctxt->extSubURI = URI;
7997
0
    ctxt->extSubSystem = publicId;
7998
7999
0
    SKIP_BLANKS;
8000
8001
    /*
8002
     * Create and update the internal subset.
8003
     */
8004
0
    if ((ctxt->sax != NULL) && (ctxt->sax->internalSubset != NULL) &&
8005
0
  (!ctxt->disableSAX))
8006
0
  ctxt->sax->internalSubset(ctxt->userData, name, publicId, URI);
8007
8008
0
    if ((RAW != '[') && (RAW != '>')) {
8009
0
  xmlFatalErr(ctxt, XML_ERR_DOCTYPE_NOT_FINISHED, NULL);
8010
0
    }
8011
0
}
8012
8013
/**
8014
 * parse the internal subset declaration
8015
 *
8016
 *     [28 end] ('[' (markupdecl | PEReference | S)* ']' S?)? '>'
8017
 * @param ctxt  an XML parser context
8018
 */
8019
8020
static void
8021
0
xmlParseInternalSubset(xmlParserCtxtPtr ctxt) {
8022
    /*
8023
     * Is there any DTD definition ?
8024
     */
8025
0
    if (RAW == '[') {
8026
0
        int oldInputNr = ctxt->inputNr;
8027
8028
0
        NEXT;
8029
  /*
8030
   * Parse the succession of Markup declarations and
8031
   * PEReferences.
8032
   * Subsequence (markupdecl | PEReference | S)*
8033
   */
8034
0
  SKIP_BLANKS;
8035
0
        while (1) {
8036
0
            if (PARSER_STOPPED(ctxt)) {
8037
0
                return;
8038
0
            } else if (ctxt->input->cur >= ctxt->input->end) {
8039
0
                if (ctxt->inputNr <= oldInputNr) {
8040
0
                xmlFatalErr(ctxt, XML_ERR_INT_SUBSET_NOT_FINISHED, NULL);
8041
0
                    return;
8042
0
                }
8043
0
                xmlPopPE(ctxt);
8044
0
            } else if ((RAW == ']') && (ctxt->inputNr <= oldInputNr)) {
8045
0
                NEXT;
8046
0
                SKIP_BLANKS;
8047
0
                break;
8048
0
            } else if ((PARSER_EXTERNAL(ctxt)) &&
8049
0
                       (RAW == '<') && (NXT(1) == '!') && (NXT(2) == '[')) {
8050
                /*
8051
                 * Conditional sections are allowed in external entities
8052
                 * included by PE References in the internal subset.
8053
                 */
8054
0
                xmlParseConditionalSections(ctxt);
8055
0
            } else if ((RAW == '<') && ((NXT(1) == '!') || (NXT(1) == '?'))) {
8056
0
                xmlParseMarkupDecl(ctxt);
8057
0
            } else if (RAW == '%') {
8058
0
                xmlParsePERefInternal(ctxt, 1);
8059
0
            } else {
8060
0
                xmlFatalErr(ctxt, XML_ERR_INT_SUBSET_NOT_FINISHED, NULL);
8061
8062
0
                while (ctxt->inputNr > oldInputNr)
8063
0
                    xmlPopPE(ctxt);
8064
0
                return;
8065
0
            }
8066
0
            SKIP_BLANKS;
8067
0
            SHRINK;
8068
0
            GROW;
8069
0
        }
8070
0
    }
8071
8072
    /*
8073
     * We should be at the end of the DOCTYPE declaration.
8074
     */
8075
0
    if (RAW != '>') {
8076
0
        xmlFatalErr(ctxt, XML_ERR_DOCTYPE_NOT_FINISHED, NULL);
8077
0
        return;
8078
0
    }
8079
0
    NEXT;
8080
0
}
8081
8082
#ifdef LIBXML_SAX1_ENABLED
8083
/**
8084
 * parse an attribute
8085
 *
8086
 * @deprecated Internal function, don't use.
8087
 *
8088
 *     [41] Attribute ::= Name Eq AttValue
8089
 *
8090
 * [ WFC: No External Entity References ]
8091
 * Attribute values cannot contain direct or indirect entity references
8092
 * to external entities.
8093
 *
8094
 * [ WFC: No < in Attribute Values ]
8095
 * The replacement text of any entity referred to directly or indirectly in
8096
 * an attribute value (other than "&lt;") must not contain a <.
8097
 *
8098
 * [ VC: Attribute Value Type ]
8099
 * The attribute must have been declared; the value must be of the type
8100
 * declared for it.
8101
 *
8102
 *     [25] Eq ::= S? '=' S?
8103
 *
8104
 * With namespace:
8105
 *
8106
 *     [NS 11] Attribute ::= QName Eq AttValue
8107
 *
8108
 * Also the case QName == xmlns:??? is handled independently as a namespace
8109
 * definition.
8110
 *
8111
 * @param ctxt  an XML parser context
8112
 * @param value  a xmlChar ** used to store the value of the attribute
8113
 * @returns the attribute name, and the value in *value.
8114
 */
8115
8116
const xmlChar *
8117
0
xmlParseAttribute(xmlParserCtxt *ctxt, xmlChar **value) {
8118
0
    const xmlChar *name;
8119
0
    xmlChar *val;
8120
8121
0
    *value = NULL;
8122
0
    GROW;
8123
0
    name = xmlParseName(ctxt);
8124
0
    if (name == NULL) {
8125
0
  xmlFatalErrMsg(ctxt, XML_ERR_NAME_REQUIRED,
8126
0
                 "error parsing attribute name\n");
8127
0
        return(NULL);
8128
0
    }
8129
8130
    /*
8131
     * read the value
8132
     */
8133
0
    SKIP_BLANKS;
8134
0
    if (RAW == '=') {
8135
0
        NEXT;
8136
0
  SKIP_BLANKS;
8137
0
  val = xmlParseAttValue(ctxt);
8138
0
    } else {
8139
0
  xmlFatalErrMsgStr(ctxt, XML_ERR_ATTRIBUTE_WITHOUT_VALUE,
8140
0
         "Specification mandates value for attribute %s\n", name);
8141
0
  return(name);
8142
0
    }
8143
8144
    /*
8145
     * Check that xml:lang conforms to the specification
8146
     * No more registered as an error, just generate a warning now
8147
     * since this was deprecated in XML second edition
8148
     */
8149
0
    if ((ctxt->pedantic) && (xmlStrEqual(name, BAD_CAST "xml:lang"))) {
8150
0
  if (!xmlCheckLanguageID(val)) {
8151
0
      xmlWarningMsg(ctxt, XML_WAR_LANG_VALUE,
8152
0
              "Malformed value for xml:lang : %s\n",
8153
0
        val, NULL);
8154
0
  }
8155
0
    }
8156
8157
    /*
8158
     * Check that xml:space conforms to the specification
8159
     */
8160
0
    if (xmlStrEqual(name, BAD_CAST "xml:space")) {
8161
0
  if (xmlStrEqual(val, BAD_CAST "default"))
8162
0
      *(ctxt->space) = 0;
8163
0
  else if (xmlStrEqual(val, BAD_CAST "preserve"))
8164
0
      *(ctxt->space) = 1;
8165
0
  else {
8166
0
    xmlWarningMsg(ctxt, XML_WAR_SPACE_VALUE,
8167
0
"Invalid value \"%s\" for xml:space : \"default\" or \"preserve\" expected\n",
8168
0
                                 val, NULL);
8169
0
  }
8170
0
    }
8171
8172
0
    *value = val;
8173
0
    return(name);
8174
0
}
8175
8176
/**
8177
 * Parse a start tag. Always consumes '<'.
8178
 *
8179
 * @deprecated Internal function, don't use.
8180
 *
8181
 *     [40] STag ::= '<' Name (S Attribute)* S? '>'
8182
 *
8183
 * [ WFC: Unique Att Spec ]
8184
 * No attribute name may appear more than once in the same start-tag or
8185
 * empty-element tag.
8186
 *
8187
 *     [44] EmptyElemTag ::= '<' Name (S Attribute)* S? '/>'
8188
 *
8189
 * [ WFC: Unique Att Spec ]
8190
 * No attribute name may appear more than once in the same start-tag or
8191
 * empty-element tag.
8192
 *
8193
 * With namespace:
8194
 *
8195
 *     [NS 8] STag ::= '<' QName (S Attribute)* S? '>'
8196
 *
8197
 *     [NS 10] EmptyElement ::= '<' QName (S Attribute)* S? '/>'
8198
 *
8199
 * @param ctxt  an XML parser context
8200
 * @returns the element name parsed
8201
 */
8202
8203
const xmlChar *
8204
0
xmlParseStartTag(xmlParserCtxt *ctxt) {
8205
0
    const xmlChar *name;
8206
0
    const xmlChar *attname;
8207
0
    xmlChar *attvalue;
8208
0
    const xmlChar **atts = ctxt->atts;
8209
0
    int nbatts = 0;
8210
0
    int maxatts = ctxt->maxatts;
8211
0
    int i;
8212
8213
0
    if (RAW != '<') return(NULL);
8214
0
    NEXT1;
8215
8216
0
    name = xmlParseName(ctxt);
8217
0
    if (name == NULL) {
8218
0
  xmlFatalErrMsg(ctxt, XML_ERR_NAME_REQUIRED,
8219
0
       "xmlParseStartTag: invalid element name\n");
8220
0
        return(NULL);
8221
0
    }
8222
8223
    /*
8224
     * Now parse the attributes, it ends up with the ending
8225
     *
8226
     * (S Attribute)* S?
8227
     */
8228
0
    SKIP_BLANKS;
8229
0
    GROW;
8230
8231
0
    while (((RAW != '>') &&
8232
0
     ((RAW != '/') || (NXT(1) != '>')) &&
8233
0
     (IS_BYTE_CHAR(RAW))) && (PARSER_STOPPED(ctxt) == 0)) {
8234
0
  attname = xmlParseAttribute(ctxt, &attvalue);
8235
0
        if (attname == NULL)
8236
0
      break;
8237
0
        if (attvalue != NULL) {
8238
      /*
8239
       * [ WFC: Unique Att Spec ]
8240
       * No attribute name may appear more than once in the same
8241
       * start-tag or empty-element tag.
8242
       */
8243
0
      for (i = 0; i < nbatts;i += 2) {
8244
0
          if (xmlStrEqual(atts[i], attname)) {
8245
0
        xmlErrAttributeDup(ctxt, NULL, attname);
8246
0
        goto failed;
8247
0
    }
8248
0
      }
8249
      /*
8250
       * Add the pair to atts
8251
       */
8252
0
      if (nbatts + 4 > maxatts) {
8253
0
          const xmlChar **n;
8254
0
                int newSize;
8255
8256
0
                newSize = xmlGrowCapacity(maxatts, sizeof(n[0]) * 2,
8257
0
                                          11, XML_MAX_ATTRS);
8258
0
                if (newSize < 0) {
8259
0
        xmlErrMemory(ctxt);
8260
0
        goto failed;
8261
0
    }
8262
0
#ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
8263
0
                if (newSize < 2)
8264
0
                    newSize = 2;
8265
0
#endif
8266
0
          n = xmlRealloc(atts, newSize * sizeof(n[0]) * 2);
8267
0
    if (n == NULL) {
8268
0
        xmlErrMemory(ctxt);
8269
0
        goto failed;
8270
0
    }
8271
0
    atts = n;
8272
0
                maxatts = newSize * 2;
8273
0
    ctxt->atts = atts;
8274
0
    ctxt->maxatts = maxatts;
8275
0
      }
8276
8277
0
      atts[nbatts++] = attname;
8278
0
      atts[nbatts++] = attvalue;
8279
0
      atts[nbatts] = NULL;
8280
0
      atts[nbatts + 1] = NULL;
8281
8282
0
            attvalue = NULL;
8283
0
  }
8284
8285
0
failed:
8286
8287
0
        if (attvalue != NULL)
8288
0
            xmlFree(attvalue);
8289
8290
0
  GROW
8291
0
  if ((RAW == '>') || (((RAW == '/') && (NXT(1) == '>'))))
8292
0
      break;
8293
0
  if (SKIP_BLANKS == 0) {
8294
0
      xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED,
8295
0
         "attributes construct error\n");
8296
0
  }
8297
0
  SHRINK;
8298
0
        GROW;
8299
0
    }
8300
8301
    /*
8302
     * SAX: Start of Element !
8303
     */
8304
0
    if ((ctxt->sax != NULL) && (ctxt->sax->startElement != NULL) &&
8305
0
  (!ctxt->disableSAX)) {
8306
0
  if (nbatts > 0)
8307
0
      ctxt->sax->startElement(ctxt->userData, name, atts);
8308
0
  else
8309
0
      ctxt->sax->startElement(ctxt->userData, name, NULL);
8310
0
    }
8311
8312
0
    if (atts != NULL) {
8313
        /* Free only the content strings */
8314
0
        for (i = 1;i < nbatts;i+=2)
8315
0
      if (atts[i] != NULL)
8316
0
         xmlFree((xmlChar *) atts[i]);
8317
0
    }
8318
0
    return(name);
8319
0
}
8320
8321
/**
8322
 * Parse an end tag. Always consumes '</'.
8323
 *
8324
 *     [42] ETag ::= '</' Name S? '>'
8325
 *
8326
 * With namespace
8327
 *
8328
 *     [NS 9] ETag ::= '</' QName S? '>'
8329
 * @param ctxt  an XML parser context
8330
 * @param line  line of the start tag
8331
 */
8332
8333
static void
8334
0
xmlParseEndTag1(xmlParserCtxtPtr ctxt, int line) {
8335
0
    const xmlChar *name;
8336
8337
0
    GROW;
8338
0
    if ((RAW != '<') || (NXT(1) != '/')) {
8339
0
  xmlFatalErrMsg(ctxt, XML_ERR_LTSLASH_REQUIRED,
8340
0
           "xmlParseEndTag: '</' not found\n");
8341
0
  return;
8342
0
    }
8343
0
    SKIP(2);
8344
8345
0
    name = xmlParseNameAndCompare(ctxt,ctxt->name);
8346
8347
    /*
8348
     * We should definitely be at the ending "S? '>'" part
8349
     */
8350
0
    GROW;
8351
0
    SKIP_BLANKS;
8352
0
    if ((!IS_BYTE_CHAR(RAW)) || (RAW != '>')) {
8353
0
  xmlFatalErr(ctxt, XML_ERR_GT_REQUIRED, NULL);
8354
0
    } else
8355
0
  NEXT1;
8356
8357
    /*
8358
     * [ WFC: Element Type Match ]
8359
     * The Name in an element's end-tag must match the element type in the
8360
     * start-tag.
8361
     *
8362
     */
8363
0
    if (name != (xmlChar*)1) {
8364
0
        if (name == NULL) name = BAD_CAST "unparsable";
8365
0
        xmlFatalErrMsgStrIntStr(ctxt, XML_ERR_TAG_NAME_MISMATCH,
8366
0
         "Opening and ending tag mismatch: %s line %d and %s\n",
8367
0
                    ctxt->name, line, name);
8368
0
    }
8369
8370
    /*
8371
     * SAX: End of Tag
8372
     */
8373
0
    if ((ctxt->sax != NULL) && (ctxt->sax->endElement != NULL) &&
8374
0
  (!ctxt->disableSAX))
8375
0
        ctxt->sax->endElement(ctxt->userData, ctxt->name);
8376
8377
0
    namePop(ctxt);
8378
0
    spacePop(ctxt);
8379
0
}
8380
8381
/**
8382
 * parse an end of tag
8383
 *
8384
 * @deprecated Internal function, don't use.
8385
 *
8386
 *     [42] ETag ::= '</' Name S? '>'
8387
 *
8388
 * With namespace
8389
 *
8390
 *     [NS 9] ETag ::= '</' QName S? '>'
8391
 * @param ctxt  an XML parser context
8392
 */
8393
8394
void
8395
0
xmlParseEndTag(xmlParserCtxt *ctxt) {
8396
0
    xmlParseEndTag1(ctxt, 0);
8397
0
}
8398
#endif /* LIBXML_SAX1_ENABLED */
8399
8400
/************************************************************************
8401
 *                  *
8402
 *          SAX 2 specific operations       *
8403
 *                  *
8404
 ************************************************************************/
8405
8406
/**
8407
 * parse an XML Namespace QName
8408
 *
8409
 *     [6]  QName  ::= (Prefix ':')? LocalPart
8410
 *     [7]  Prefix  ::= NCName
8411
 *     [8]  LocalPart  ::= NCName
8412
 *
8413
 * @param ctxt  an XML parser context
8414
 * @param prefix  pointer to store the prefix part
8415
 * @returns the Name parsed or NULL
8416
 */
8417
8418
static xmlHashedString
8419
0
xmlParseQNameHashed(xmlParserCtxtPtr ctxt, xmlHashedString *prefix) {
8420
0
    xmlHashedString l, p;
8421
0
    int start, isNCName = 0;
8422
8423
0
    l.name = NULL;
8424
0
    p.name = NULL;
8425
8426
0
    GROW;
8427
0
    start = CUR_PTR - BASE_PTR;
8428
8429
0
    l = xmlParseNCName(ctxt);
8430
0
    if (l.name != NULL) {
8431
0
        isNCName = 1;
8432
0
        if (CUR == ':') {
8433
0
            NEXT;
8434
0
            p = l;
8435
0
            l = xmlParseNCName(ctxt);
8436
0
        }
8437
0
    }
8438
0
    if ((l.name == NULL) || (CUR == ':')) {
8439
0
        xmlChar *tmp;
8440
8441
0
        l.name = NULL;
8442
0
        p.name = NULL;
8443
0
        if ((isNCName == 0) && (CUR != ':'))
8444
0
            return(l);
8445
0
        tmp = xmlParseNmtoken(ctxt);
8446
0
        if (tmp != NULL)
8447
0
            xmlFree(tmp);
8448
0
        l = xmlDictLookupHashed(ctxt->dict, BASE_PTR + start,
8449
0
                                CUR_PTR - (BASE_PTR + start));
8450
0
        if (l.name == NULL) {
8451
0
            xmlErrMemory(ctxt);
8452
0
            return(l);
8453
0
        }
8454
0
        xmlNsErr(ctxt, XML_NS_ERR_QNAME,
8455
0
                 "Failed to parse QName '%s'\n", l.name, NULL, NULL);
8456
0
    }
8457
8458
0
    *prefix = p;
8459
0
    return(l);
8460
0
}
8461
8462
/**
8463
 * parse an XML Namespace QName
8464
 *
8465
 *     [6]  QName  ::= (Prefix ':')? LocalPart
8466
 *     [7]  Prefix  ::= NCName
8467
 *     [8]  LocalPart  ::= NCName
8468
 *
8469
 * @param ctxt  an XML parser context
8470
 * @param prefix  pointer to store the prefix part
8471
 * @returns the Name parsed or NULL
8472
 */
8473
8474
static const xmlChar *
8475
0
xmlParseQName(xmlParserCtxtPtr ctxt, const xmlChar **prefix) {
8476
0
    xmlHashedString n, p;
8477
8478
0
    n = xmlParseQNameHashed(ctxt, &p);
8479
0
    if (n.name == NULL)
8480
0
        return(NULL);
8481
0
    *prefix = p.name;
8482
0
    return(n.name);
8483
0
}
8484
8485
/**
8486
 * parse an XML name and compares for match
8487
 * (specialized for endtag parsing)
8488
 *
8489
 * @param ctxt  an XML parser context
8490
 * @param name  the localname
8491
 * @param prefix  the prefix, if any.
8492
 * @returns NULL for an illegal name, (xmlChar*) 1 for success
8493
 * and the name for mismatch
8494
 */
8495
8496
static const xmlChar *
8497
xmlParseQNameAndCompare(xmlParserCtxtPtr ctxt, xmlChar const *name,
8498
0
                        xmlChar const *prefix) {
8499
0
    const xmlChar *cmp;
8500
0
    const xmlChar *in;
8501
0
    const xmlChar *ret;
8502
0
    const xmlChar *prefix2;
8503
8504
0
    if (prefix == NULL) return(xmlParseNameAndCompare(ctxt, name));
8505
8506
0
    GROW;
8507
0
    in = ctxt->input->cur;
8508
8509
0
    cmp = prefix;
8510
0
    while (*in != 0 && *in == *cmp) {
8511
0
  ++in;
8512
0
  ++cmp;
8513
0
    }
8514
0
    if ((*cmp == 0) && (*in == ':')) {
8515
0
        in++;
8516
0
  cmp = name;
8517
0
  while (*in != 0 && *in == *cmp) {
8518
0
      ++in;
8519
0
      ++cmp;
8520
0
  }
8521
0
  if (*cmp == 0 && (*in == '>' || IS_BLANK_CH (*in))) {
8522
      /* success */
8523
0
            ctxt->input->col += in - ctxt->input->cur;
8524
0
      ctxt->input->cur = in;
8525
0
      return((const xmlChar*) 1);
8526
0
  }
8527
0
    }
8528
    /*
8529
     * all strings coms from the dictionary, equality can be done directly
8530
     */
8531
0
    ret = xmlParseQName (ctxt, &prefix2);
8532
0
    if (ret == NULL)
8533
0
        return(NULL);
8534
0
    if ((ret == name) && (prefix == prefix2))
8535
0
  return((const xmlChar*) 1);
8536
0
    return ret;
8537
0
}
8538
8539
/**
8540
 * parse an attribute in the new SAX2 framework.
8541
 *
8542
 * @param ctxt  an XML parser context
8543
 * @param pref  the element prefix
8544
 * @param elem  the element name
8545
 * @param hprefix  resulting attribute prefix
8546
 * @param value  resulting value of the attribute
8547
 * @param len  resulting length of the attribute
8548
 * @param alloc  resulting indicator if the attribute was allocated
8549
 * @returns the attribute name, and the value in *value, .
8550
 */
8551
8552
static xmlHashedString
8553
xmlParseAttribute2(xmlParserCtxtPtr ctxt,
8554
                   const xmlChar * pref, const xmlChar * elem,
8555
                   xmlHashedString * hprefix, xmlChar ** value,
8556
                   int *len, int *alloc)
8557
0
{
8558
0
    xmlHashedString hname;
8559
0
    const xmlChar *prefix, *name;
8560
0
    xmlChar *val = NULL, *internal_val = NULL;
8561
0
    int special = 0;
8562
0
    int isNamespace;
8563
0
    int flags;
8564
8565
0
    *value = NULL;
8566
0
    GROW;
8567
0
    hname = xmlParseQNameHashed(ctxt, hprefix);
8568
0
    if (hname.name == NULL) {
8569
0
        xmlFatalErrMsg(ctxt, XML_ERR_NAME_REQUIRED,
8570
0
                       "error parsing attribute name\n");
8571
0
        return(hname);
8572
0
    }
8573
0
    name = hname.name;
8574
0
    prefix = hprefix->name;
8575
8576
    /*
8577
     * get the type if needed
8578
     */
8579
0
    if (ctxt->attsSpecial != NULL) {
8580
0
        special = XML_PTR_TO_INT(xmlHashQLookup2(ctxt->attsSpecial, pref, elem,
8581
0
                                              prefix, name));
8582
0
    }
8583
8584
    /*
8585
     * read the value
8586
     */
8587
0
    SKIP_BLANKS;
8588
0
    if (RAW != '=') {
8589
0
        xmlFatalErrMsgStr(ctxt, XML_ERR_ATTRIBUTE_WITHOUT_VALUE,
8590
0
                          "Specification mandates value for attribute %s\n",
8591
0
                          name);
8592
0
        goto error;
8593
0
    }
8594
8595
8596
0
    NEXT;
8597
0
    SKIP_BLANKS;
8598
0
    flags = 0;
8599
0
    isNamespace = (((prefix == NULL) && (name == ctxt->str_xmlns)) ||
8600
0
                   (prefix == ctxt->str_xmlns));
8601
0
    val = xmlParseAttValueInternal(ctxt, len, &flags, special,
8602
0
                                   isNamespace);
8603
0
    if (val == NULL)
8604
0
        goto error;
8605
8606
0
    *alloc = (flags & XML_ATTVAL_ALLOC) != 0;
8607
8608
0
#ifdef LIBXML_VALID_ENABLED
8609
0
    if ((ctxt->validate) &&
8610
0
        (ctxt->standalone) &&
8611
0
        (special & XML_SPECIAL_EXTERNAL) &&
8612
0
        (flags & XML_ATTVAL_NORM_CHANGE)) {
8613
0
        xmlValidityError(ctxt, XML_DTD_NOT_STANDALONE,
8614
0
                         "standalone: normalization of attribute %s on %s "
8615
0
                         "by external subset declaration\n",
8616
0
                         name, elem);
8617
0
    }
8618
0
#endif
8619
8620
0
    if (prefix == ctxt->str_xml) {
8621
        /*
8622
         * Check that xml:lang conforms to the specification
8623
         * No more registered as an error, just generate a warning now
8624
         * since this was deprecated in XML second edition
8625
         */
8626
0
        if ((ctxt->pedantic) && (xmlStrEqual(name, BAD_CAST "lang"))) {
8627
0
            internal_val = xmlStrndup(val, *len);
8628
0
            if (internal_val == NULL)
8629
0
                goto mem_error;
8630
0
            if (!xmlCheckLanguageID(internal_val)) {
8631
0
                xmlWarningMsg(ctxt, XML_WAR_LANG_VALUE,
8632
0
                              "Malformed value for xml:lang : %s\n",
8633
0
                              internal_val, NULL);
8634
0
            }
8635
0
        }
8636
8637
        /*
8638
         * Check that xml:space conforms to the specification
8639
         */
8640
0
        if (xmlStrEqual(name, BAD_CAST "space")) {
8641
0
            internal_val = xmlStrndup(val, *len);
8642
0
            if (internal_val == NULL)
8643
0
                goto mem_error;
8644
0
            if (xmlStrEqual(internal_val, BAD_CAST "default"))
8645
0
                *(ctxt->space) = 0;
8646
0
            else if (xmlStrEqual(internal_val, BAD_CAST "preserve"))
8647
0
                *(ctxt->space) = 1;
8648
0
            else {
8649
0
                xmlWarningMsg(ctxt, XML_WAR_SPACE_VALUE,
8650
0
                              "Invalid value \"%s\" for xml:space : \"default\" or \"preserve\" expected\n",
8651
0
                              internal_val, NULL);
8652
0
            }
8653
0
        }
8654
0
        if (internal_val) {
8655
0
            xmlFree(internal_val);
8656
0
        }
8657
0
    }
8658
8659
0
    *value = val;
8660
0
    return (hname);
8661
8662
0
mem_error:
8663
0
    xmlErrMemory(ctxt);
8664
0
error:
8665
0
    if ((val != NULL) && (*alloc != 0))
8666
0
        xmlFree(val);
8667
0
    return(hname);
8668
0
}
8669
8670
/**
8671
 * Inserts a new attribute into the hash table.
8672
 *
8673
 * @param ctxt  parser context
8674
 * @param size  size of the hash table
8675
 * @param name  attribute name
8676
 * @param uri  namespace uri
8677
 * @param hashValue  combined hash value of name and uri
8678
 * @param aindex  attribute index (this is a multiple of 5)
8679
 * @returns INT_MAX if no existing attribute was found, the attribute
8680
 * index if an attribute was found, -1 if a memory allocation failed.
8681
 */
8682
static int
8683
xmlAttrHashInsert(xmlParserCtxtPtr ctxt, unsigned size, const xmlChar *name,
8684
0
                  const xmlChar *uri, unsigned hashValue, int aindex) {
8685
0
    xmlAttrHashBucket *table = ctxt->attrHash;
8686
0
    xmlAttrHashBucket *bucket;
8687
0
    unsigned hindex;
8688
8689
0
    hindex = hashValue & (size - 1);
8690
0
    bucket = &table[hindex];
8691
8692
0
    while (bucket->index >= 0) {
8693
0
        const xmlChar **atts = &ctxt->atts[bucket->index];
8694
8695
0
        if (name == atts[0]) {
8696
0
            int nsIndex = XML_PTR_TO_INT(atts[2]);
8697
8698
0
            if ((nsIndex == NS_INDEX_EMPTY) ? (uri == NULL) :
8699
0
                (nsIndex == NS_INDEX_XML) ? (uri == ctxt->str_xml_ns) :
8700
0
                (uri == ctxt->nsTab[nsIndex * 2 + 1]))
8701
0
                return(bucket->index);
8702
0
        }
8703
8704
0
        hindex++;
8705
0
        bucket++;
8706
0
        if (hindex >= size) {
8707
0
            hindex = 0;
8708
0
            bucket = table;
8709
0
        }
8710
0
    }
8711
8712
0
    bucket->index = aindex;
8713
8714
0
    return(INT_MAX);
8715
0
}
8716
8717
static int
8718
xmlAttrHashInsertQName(xmlParserCtxtPtr ctxt, unsigned size,
8719
                       const xmlChar *name, const xmlChar *prefix,
8720
0
                       unsigned hashValue, int aindex) {
8721
0
    xmlAttrHashBucket *table = ctxt->attrHash;
8722
0
    xmlAttrHashBucket *bucket;
8723
0
    unsigned hindex;
8724
8725
0
    hindex = hashValue & (size - 1);
8726
0
    bucket = &table[hindex];
8727
8728
0
    while (bucket->index >= 0) {
8729
0
        const xmlChar **atts = &ctxt->atts[bucket->index];
8730
8731
0
        if ((name == atts[0]) && (prefix == atts[1]))
8732
0
            return(bucket->index);
8733
8734
0
        hindex++;
8735
0
        bucket++;
8736
0
        if (hindex >= size) {
8737
0
            hindex = 0;
8738
0
            bucket = table;
8739
0
        }
8740
0
    }
8741
8742
0
    bucket->index = aindex;
8743
8744
0
    return(INT_MAX);
8745
0
}
8746
/**
8747
 * Parse a start tag. Always consumes '<'.
8748
 *
8749
 * This routine is called when running SAX2 parsing
8750
 *
8751
 *     [40] STag ::= '<' Name (S Attribute)* S? '>'
8752
 *
8753
 * [ WFC: Unique Att Spec ]
8754
 * No attribute name may appear more than once in the same start-tag or
8755
 * empty-element tag.
8756
 *
8757
 *     [44] EmptyElemTag ::= '<' Name (S Attribute)* S? '/>'
8758
 *
8759
 * [ WFC: Unique Att Spec ]
8760
 * No attribute name may appear more than once in the same start-tag or
8761
 * empty-element tag.
8762
 *
8763
 * With namespace:
8764
 *
8765
 *     [NS 8] STag ::= '<' QName (S Attribute)* S? '>'
8766
 *
8767
 *     [NS 10] EmptyElement ::= '<' QName (S Attribute)* S? '/>'
8768
 *
8769
 * @param ctxt  an XML parser context
8770
 * @param pref  resulting namespace prefix
8771
 * @param URI  resulting namespace URI
8772
 * @param nbNsPtr  resulting number of namespace declarations
8773
 * @returns the element name parsed
8774
 */
8775
8776
static const xmlChar *
8777
xmlParseStartTag2(xmlParserCtxtPtr ctxt, const xmlChar **pref,
8778
0
                  const xmlChar **URI, int *nbNsPtr) {
8779
0
    xmlHashedString hlocalname;
8780
0
    xmlHashedString hprefix;
8781
0
    xmlHashedString hattname;
8782
0
    xmlHashedString haprefix;
8783
0
    const xmlChar *localname;
8784
0
    const xmlChar *prefix;
8785
0
    const xmlChar *attname;
8786
0
    const xmlChar *aprefix;
8787
0
    const xmlChar *uri;
8788
0
    xmlChar *attvalue = NULL;
8789
0
    const xmlChar **atts = ctxt->atts;
8790
0
    unsigned attrHashSize = 0;
8791
0
    int maxatts = ctxt->maxatts;
8792
0
    int nratts, nbatts, nbdef;
8793
0
    int i, j, nbNs, nbTotalDef, attval, nsIndex, maxAtts;
8794
0
    int alloc = 0;
8795
0
    int numNsErr = 0;
8796
0
    int numDupErr = 0;
8797
8798
0
    if (RAW != '<') return(NULL);
8799
0
    NEXT1;
8800
8801
0
    nbatts = 0;
8802
0
    nratts = 0;
8803
0
    nbdef = 0;
8804
0
    nbNs = 0;
8805
0
    nbTotalDef = 0;
8806
0
    attval = 0;
8807
8808
0
    if (xmlParserNsStartElement(ctxt->nsdb) < 0) {
8809
0
        xmlErrMemory(ctxt);
8810
0
        return(NULL);
8811
0
    }
8812
8813
0
    hlocalname = xmlParseQNameHashed(ctxt, &hprefix);
8814
0
    if (hlocalname.name == NULL) {
8815
0
  xmlFatalErrMsg(ctxt, XML_ERR_NAME_REQUIRED,
8816
0
           "StartTag: invalid element name\n");
8817
0
        return(NULL);
8818
0
    }
8819
0
    localname = hlocalname.name;
8820
0
    prefix = hprefix.name;
8821
8822
    /*
8823
     * Now parse the attributes, it ends up with the ending
8824
     *
8825
     * (S Attribute)* S?
8826
     */
8827
0
    SKIP_BLANKS;
8828
0
    GROW;
8829
8830
    /*
8831
     * The ctxt->atts array will be ultimately passed to the SAX callback
8832
     * containing five xmlChar pointers for each attribute:
8833
     *
8834
     * [0] attribute name
8835
     * [1] attribute prefix
8836
     * [2] namespace URI
8837
     * [3] attribute value
8838
     * [4] end of attribute value
8839
     *
8840
     * To save memory, we reuse this array temporarily and store integers
8841
     * in these pointer variables.
8842
     *
8843
     * [0] attribute name
8844
     * [1] attribute prefix
8845
     * [2] hash value of attribute prefix, and later namespace index
8846
     * [3] for non-allocated values: ptrdiff_t offset into input buffer
8847
     * [4] for non-allocated values: ptrdiff_t offset into input buffer
8848
     *
8849
     * The ctxt->attallocs array contains an additional unsigned int for
8850
     * each attribute, containing the hash value of the attribute name
8851
     * and the alloc flag in bit 31.
8852
     */
8853
8854
0
    while (((RAW != '>') &&
8855
0
     ((RAW != '/') || (NXT(1) != '>')) &&
8856
0
     (IS_BYTE_CHAR(RAW))) && (PARSER_STOPPED(ctxt) == 0)) {
8857
0
  int len = -1;
8858
8859
0
  hattname = xmlParseAttribute2(ctxt, prefix, localname,
8860
0
                                          &haprefix, &attvalue, &len,
8861
0
                                          &alloc);
8862
0
        if (hattname.name == NULL)
8863
0
      break;
8864
0
        if (attvalue == NULL)
8865
0
            goto next_attr;
8866
0
        attname = hattname.name;
8867
0
        aprefix = haprefix.name;
8868
0
  if (len < 0) len = xmlStrlen(attvalue);
8869
8870
0
        if ((attname == ctxt->str_xmlns) && (aprefix == NULL)) {
8871
0
            xmlHashedString huri;
8872
0
            xmlURIPtr parsedUri;
8873
8874
0
            huri = xmlDictLookupHashed(ctxt->dict, attvalue, len);
8875
0
            uri = huri.name;
8876
0
            if (uri == NULL) {
8877
0
                xmlErrMemory(ctxt);
8878
0
                goto next_attr;
8879
0
            }
8880
0
            if (*uri != 0) {
8881
0
                if (xmlParseURISafe((const char *) uri, &parsedUri) < 0) {
8882
0
                    xmlErrMemory(ctxt);
8883
0
                    goto next_attr;
8884
0
                }
8885
0
                if (parsedUri == NULL) {
8886
0
                    xmlNsErr(ctxt, XML_WAR_NS_URI,
8887
0
                             "xmlns: '%s' is not a valid URI\n",
8888
0
                                       uri, NULL, NULL);
8889
0
                } else {
8890
0
                    if (parsedUri->scheme == NULL) {
8891
0
                        xmlNsWarn(ctxt, XML_WAR_NS_URI_RELATIVE,
8892
0
                                  "xmlns: URI %s is not absolute\n",
8893
0
                                  uri, NULL, NULL);
8894
0
                    }
8895
0
                    xmlFreeURI(parsedUri);
8896
0
                }
8897
0
                if (uri == ctxt->str_xml_ns) {
8898
0
                    if (attname != ctxt->str_xml) {
8899
0
                        xmlNsErr(ctxt, XML_NS_ERR_XML_NAMESPACE,
8900
0
                     "xml namespace URI cannot be the default namespace\n",
8901
0
                                 NULL, NULL, NULL);
8902
0
                    }
8903
0
                    goto next_attr;
8904
0
                }
8905
0
                if ((len == 29) &&
8906
0
                    (xmlStrEqual(uri,
8907
0
                             BAD_CAST "http://www.w3.org/2000/xmlns/"))) {
8908
0
                    xmlNsErr(ctxt, XML_NS_ERR_XML_NAMESPACE,
8909
0
                         "reuse of the xmlns namespace name is forbidden\n",
8910
0
                             NULL, NULL, NULL);
8911
0
                    goto next_attr;
8912
0
                }
8913
0
            }
8914
8915
0
            if (xmlParserNsPush(ctxt, NULL, &huri, NULL, 0) > 0)
8916
0
                nbNs++;
8917
0
        } else if (aprefix == ctxt->str_xmlns) {
8918
0
            xmlHashedString huri;
8919
0
            xmlURIPtr parsedUri;
8920
8921
0
            huri = xmlDictLookupHashed(ctxt->dict, attvalue, len);
8922
0
            uri = huri.name;
8923
0
            if (uri == NULL) {
8924
0
                xmlErrMemory(ctxt);
8925
0
                goto next_attr;
8926
0
            }
8927
8928
0
            if (attname == ctxt->str_xml) {
8929
0
                if (uri != ctxt->str_xml_ns) {
8930
0
                    xmlNsErr(ctxt, XML_NS_ERR_XML_NAMESPACE,
8931
0
                             "xml namespace prefix mapped to wrong URI\n",
8932
0
                             NULL, NULL, NULL);
8933
0
                }
8934
                /*
8935
                 * Do not keep a namespace definition node
8936
                 */
8937
0
                goto next_attr;
8938
0
            }
8939
0
            if (uri == ctxt->str_xml_ns) {
8940
0
                if (attname != ctxt->str_xml) {
8941
0
                    xmlNsErr(ctxt, XML_NS_ERR_XML_NAMESPACE,
8942
0
                             "xml namespace URI mapped to wrong prefix\n",
8943
0
                             NULL, NULL, NULL);
8944
0
                }
8945
0
                goto next_attr;
8946
0
            }
8947
0
            if (attname == ctxt->str_xmlns) {
8948
0
                xmlNsErr(ctxt, XML_NS_ERR_XML_NAMESPACE,
8949
0
                         "redefinition of the xmlns prefix is forbidden\n",
8950
0
                         NULL, NULL, NULL);
8951
0
                goto next_attr;
8952
0
            }
8953
0
            if ((len == 29) &&
8954
0
                (xmlStrEqual(uri,
8955
0
                             BAD_CAST "http://www.w3.org/2000/xmlns/"))) {
8956
0
                xmlNsErr(ctxt, XML_NS_ERR_XML_NAMESPACE,
8957
0
                         "reuse of the xmlns namespace name is forbidden\n",
8958
0
                         NULL, NULL, NULL);
8959
0
                goto next_attr;
8960
0
            }
8961
0
            if ((uri == NULL) || (uri[0] == 0)) {
8962
0
                xmlNsErr(ctxt, XML_NS_ERR_XML_NAMESPACE,
8963
0
                         "xmlns:%s: Empty XML namespace is not allowed\n",
8964
0
                              attname, NULL, NULL);
8965
0
                goto next_attr;
8966
0
            } else {
8967
0
                if (xmlParseURISafe((const char *) uri, &parsedUri) < 0) {
8968
0
                    xmlErrMemory(ctxt);
8969
0
                    goto next_attr;
8970
0
                }
8971
0
                if (parsedUri == NULL) {
8972
0
                    xmlNsErr(ctxt, XML_WAR_NS_URI,
8973
0
                         "xmlns:%s: '%s' is not a valid URI\n",
8974
0
                                       attname, uri, NULL);
8975
0
                } else {
8976
0
                    if ((ctxt->pedantic) && (parsedUri->scheme == NULL)) {
8977
0
                        xmlNsWarn(ctxt, XML_WAR_NS_URI_RELATIVE,
8978
0
                                  "xmlns:%s: URI %s is not absolute\n",
8979
0
                                  attname, uri, NULL);
8980
0
                    }
8981
0
                    xmlFreeURI(parsedUri);
8982
0
                }
8983
0
            }
8984
8985
0
            if (xmlParserNsPush(ctxt, &hattname, &huri, NULL, 0) > 0)
8986
0
                nbNs++;
8987
0
        } else {
8988
            /*
8989
             * Populate attributes array, see above for repurposing
8990
             * of xmlChar pointers.
8991
             */
8992
0
            if ((atts == NULL) || (nbatts + 5 > maxatts)) {
8993
0
                int res = xmlCtxtGrowAttrs(ctxt);
8994
8995
0
                maxatts = ctxt->maxatts;
8996
0
                atts = ctxt->atts;
8997
8998
0
                if (res < 0)
8999
0
                    goto next_attr;
9000
0
            }
9001
0
            ctxt->attallocs[nratts++] = (hattname.hashValue & 0x7FFFFFFF) |
9002
0
                                        ((unsigned) alloc << 31);
9003
0
            atts[nbatts++] = attname;
9004
0
            atts[nbatts++] = aprefix;
9005
0
            atts[nbatts++] = XML_INT_TO_PTR(haprefix.hashValue);
9006
0
            if (alloc) {
9007
0
                atts[nbatts++] = attvalue;
9008
0
                attvalue += len;
9009
0
                atts[nbatts++] = attvalue;
9010
0
            } else {
9011
                /*
9012
                 * attvalue points into the input buffer which can be
9013
                 * reallocated. Store differences to input->base instead.
9014
                 * The pointers will be reconstructed later.
9015
                 */
9016
0
                atts[nbatts++] = XML_INT_TO_PTR(attvalue - BASE_PTR);
9017
0
                attvalue += len;
9018
0
                atts[nbatts++] = XML_INT_TO_PTR(attvalue - BASE_PTR);
9019
0
            }
9020
            /*
9021
             * tag if some deallocation is needed
9022
             */
9023
0
            if (alloc != 0) attval = 1;
9024
0
            attvalue = NULL; /* moved into atts */
9025
0
        }
9026
9027
0
next_attr:
9028
0
        if ((attvalue != NULL) && (alloc != 0)) {
9029
0
            xmlFree(attvalue);
9030
0
            attvalue = NULL;
9031
0
        }
9032
9033
0
  GROW
9034
0
  if ((RAW == '>') || (((RAW == '/') && (NXT(1) == '>'))))
9035
0
      break;
9036
0
  if (SKIP_BLANKS == 0) {
9037
0
      xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED,
9038
0
         "attributes construct error\n");
9039
0
      break;
9040
0
  }
9041
0
        GROW;
9042
0
    }
9043
9044
    /*
9045
     * Namespaces from default attributes
9046
     */
9047
0
    if (ctxt->attsDefault != NULL) {
9048
0
        xmlDefAttrsPtr defaults;
9049
9050
0
  defaults = xmlHashLookup2(ctxt->attsDefault, localname, prefix);
9051
0
  if (defaults != NULL) {
9052
0
      for (i = 0; i < defaults->nbAttrs; i++) {
9053
0
                xmlDefAttr *attr = &defaults->attrs[i];
9054
9055
0
          attname = attr->name.name;
9056
0
    aprefix = attr->prefix.name;
9057
9058
0
    if ((attname == ctxt->str_xmlns) && (aprefix == NULL)) {
9059
0
                    xmlParserEntityCheck(ctxt, attr->expandedSize);
9060
9061
0
                    if (xmlParserNsPush(ctxt, NULL, &attr->value, NULL, 1) > 0)
9062
0
                        nbNs++;
9063
0
    } else if (aprefix == ctxt->str_xmlns) {
9064
0
                    xmlParserEntityCheck(ctxt, attr->expandedSize);
9065
9066
0
                    if (xmlParserNsPush(ctxt, &attr->name, &attr->value,
9067
0
                                      NULL, 1) > 0)
9068
0
                        nbNs++;
9069
0
    } else {
9070
0
                    if (nratts + nbTotalDef >= XML_MAX_ATTRS) {
9071
0
                        xmlFatalErr(ctxt, XML_ERR_RESOURCE_LIMIT,
9072
0
                                    "Maximum number of attributes exceeded");
9073
0
                        break;
9074
0
                    }
9075
0
                    nbTotalDef += 1;
9076
0
                }
9077
0
      }
9078
0
  }
9079
0
    }
9080
9081
    /*
9082
     * Resolve attribute namespaces
9083
     */
9084
0
    for (i = 0; i < nbatts; i += 5) {
9085
0
        attname = atts[i];
9086
0
        aprefix = atts[i+1];
9087
9088
        /*
9089
  * The default namespace does not apply to attribute names.
9090
  */
9091
0
  if (aprefix == NULL) {
9092
0
            nsIndex = NS_INDEX_EMPTY;
9093
0
        } else if (aprefix == ctxt->str_xml) {
9094
0
            nsIndex = NS_INDEX_XML;
9095
0
        } else {
9096
0
            haprefix.name = aprefix;
9097
0
            haprefix.hashValue = (size_t) atts[i+2];
9098
0
            nsIndex = xmlParserNsLookup(ctxt, &haprefix, NULL);
9099
9100
0
      if ((nsIndex == INT_MAX) || (nsIndex < ctxt->nsdb->minNsIndex)) {
9101
0
                xmlNsErr(ctxt, XML_NS_ERR_UNDEFINED_NAMESPACE,
9102
0
        "Namespace prefix %s for %s on %s is not defined\n",
9103
0
        aprefix, attname, localname);
9104
0
                nsIndex = NS_INDEX_EMPTY;
9105
0
            }
9106
0
        }
9107
9108
0
        atts[i+2] = XML_INT_TO_PTR(nsIndex);
9109
0
    }
9110
9111
    /*
9112
     * Maximum number of attributes including default attributes.
9113
     */
9114
0
    maxAtts = nratts + nbTotalDef;
9115
9116
    /*
9117
     * Verify that attribute names are unique.
9118
     */
9119
0
    if (maxAtts > 1) {
9120
0
        attrHashSize = 4;
9121
0
        while (attrHashSize / 2 < (unsigned) maxAtts)
9122
0
            attrHashSize *= 2;
9123
9124
0
        if (attrHashSize > ctxt->attrHashMax) {
9125
0
            xmlAttrHashBucket *tmp;
9126
9127
0
            tmp = xmlRealloc(ctxt->attrHash, attrHashSize * sizeof(tmp[0]));
9128
0
            if (tmp == NULL) {
9129
0
                xmlErrMemory(ctxt);
9130
0
                goto done;
9131
0
            }
9132
9133
0
            ctxt->attrHash = tmp;
9134
0
            ctxt->attrHashMax = attrHashSize;
9135
0
        }
9136
9137
0
        memset(ctxt->attrHash, -1, attrHashSize * sizeof(ctxt->attrHash[0]));
9138
9139
0
        for (i = 0, j = 0; j < nratts; i += 5, j++) {
9140
0
            const xmlChar *nsuri;
9141
0
            unsigned hashValue, nameHashValue, uriHashValue;
9142
0
            int res;
9143
9144
0
            attname = atts[i];
9145
0
            aprefix = atts[i+1];
9146
0
            nsIndex = XML_PTR_TO_INT(atts[i+2]);
9147
            /* Hash values always have bit 31 set, see dict.c */
9148
0
            nameHashValue = ctxt->attallocs[j] | 0x80000000;
9149
9150
0
            if (nsIndex == NS_INDEX_EMPTY) {
9151
                /*
9152
                 * Prefix with empty namespace means an undeclared
9153
                 * prefix which was already reported above.
9154
                 */
9155
0
                if (aprefix != NULL)
9156
0
                    continue;
9157
0
                nsuri = NULL;
9158
0
                uriHashValue = URI_HASH_EMPTY;
9159
0
            } else if (nsIndex == NS_INDEX_XML) {
9160
0
                nsuri = ctxt->str_xml_ns;
9161
0
                uriHashValue = URI_HASH_XML;
9162
0
            } else {
9163
0
                nsuri = ctxt->nsTab[nsIndex * 2 + 1];
9164
0
                uriHashValue = ctxt->nsdb->extra[nsIndex].uriHashValue;
9165
0
            }
9166
9167
0
            hashValue = xmlDictCombineHash(nameHashValue, uriHashValue);
9168
0
            res = xmlAttrHashInsert(ctxt, attrHashSize, attname, nsuri,
9169
0
                                    hashValue, i);
9170
0
            if (res < 0)
9171
0
                continue;
9172
9173
            /*
9174
             * [ WFC: Unique Att Spec ]
9175
             * No attribute name may appear more than once in the same
9176
             * start-tag or empty-element tag.
9177
             * As extended by the Namespace in XML REC.
9178
             */
9179
0
            if (res < INT_MAX) {
9180
0
                if (aprefix == atts[res+1]) {
9181
0
                    xmlErrAttributeDup(ctxt, aprefix, attname);
9182
0
                    numDupErr += 1;
9183
0
                } else {
9184
0
                    xmlNsErr(ctxt, XML_NS_ERR_ATTRIBUTE_REDEFINED,
9185
0
                             "Namespaced Attribute %s in '%s' redefined\n",
9186
0
                             attname, nsuri, NULL);
9187
0
                    numNsErr += 1;
9188
0
                }
9189
0
            }
9190
0
        }
9191
0
    }
9192
9193
    /*
9194
     * Default attributes
9195
     */
9196
0
    if (ctxt->attsDefault != NULL) {
9197
0
        xmlDefAttrsPtr defaults;
9198
9199
0
  defaults = xmlHashLookup2(ctxt->attsDefault, localname, prefix);
9200
0
  if (defaults != NULL) {
9201
0
      for (i = 0; i < defaults->nbAttrs; i++) {
9202
0
                xmlDefAttr *attr = &defaults->attrs[i];
9203
0
                const xmlChar *nsuri = NULL;
9204
0
                unsigned hashValue, uriHashValue = 0;
9205
0
                int res;
9206
9207
0
          attname = attr->name.name;
9208
0
    aprefix = attr->prefix.name;
9209
9210
0
    if ((attname == ctxt->str_xmlns) && (aprefix == NULL))
9211
0
                    continue;
9212
0
    if (aprefix == ctxt->str_xmlns)
9213
0
                    continue;
9214
9215
0
                if (aprefix == NULL) {
9216
0
                    nsIndex = NS_INDEX_EMPTY;
9217
0
                    nsuri = NULL;
9218
0
                    uriHashValue = URI_HASH_EMPTY;
9219
0
                } else if (aprefix == ctxt->str_xml) {
9220
0
                    nsIndex = NS_INDEX_XML;
9221
0
                    nsuri = ctxt->str_xml_ns;
9222
0
                    uriHashValue = URI_HASH_XML;
9223
0
                } else {
9224
0
                    nsIndex = xmlParserNsLookup(ctxt, &attr->prefix, NULL);
9225
0
                    if ((nsIndex == INT_MAX) ||
9226
0
                        (nsIndex < ctxt->nsdb->minNsIndex)) {
9227
0
                        xmlNsErr(ctxt, XML_NS_ERR_UNDEFINED_NAMESPACE,
9228
0
                                 "Namespace prefix %s for %s on %s is not "
9229
0
                                 "defined\n",
9230
0
                                 aprefix, attname, localname);
9231
0
                        nsIndex = NS_INDEX_EMPTY;
9232
0
                        nsuri = NULL;
9233
0
                        uriHashValue = URI_HASH_EMPTY;
9234
0
                    } else {
9235
0
                        nsuri = ctxt->nsTab[nsIndex * 2 + 1];
9236
0
                        uriHashValue = ctxt->nsdb->extra[nsIndex].uriHashValue;
9237
0
                    }
9238
0
                }
9239
9240
                /*
9241
                 * Check whether the attribute exists
9242
                 */
9243
0
                if (maxAtts > 1) {
9244
0
                    hashValue = xmlDictCombineHash(attr->name.hashValue,
9245
0
                                                   uriHashValue);
9246
0
                    res = xmlAttrHashInsert(ctxt, attrHashSize, attname, nsuri,
9247
0
                                            hashValue, nbatts);
9248
0
                    if (res < 0)
9249
0
                        continue;
9250
0
                    if (res < INT_MAX) {
9251
0
                        if (aprefix == atts[res+1])
9252
0
                            continue;
9253
0
                        xmlNsErr(ctxt, XML_NS_ERR_ATTRIBUTE_REDEFINED,
9254
0
                                 "Namespaced Attribute %s in '%s' redefined\n",
9255
0
                                 attname, nsuri, NULL);
9256
0
                    }
9257
0
                }
9258
9259
0
                xmlParserEntityCheck(ctxt, attr->expandedSize);
9260
9261
0
                if ((atts == NULL) || (nbatts + 5 > maxatts)) {
9262
0
                    res = xmlCtxtGrowAttrs(ctxt);
9263
9264
0
                    maxatts = ctxt->maxatts;
9265
0
                    atts = ctxt->atts;
9266
9267
0
                    if (res < 0) {
9268
0
                        localname = NULL;
9269
0
                        goto done;
9270
0
                    }
9271
0
                }
9272
9273
0
                atts[nbatts++] = attname;
9274
0
                atts[nbatts++] = aprefix;
9275
0
                atts[nbatts++] = XML_INT_TO_PTR(nsIndex);
9276
0
                atts[nbatts++] = attr->value.name;
9277
0
                atts[nbatts++] = attr->valueEnd;
9278
9279
0
#ifdef LIBXML_VALID_ENABLED
9280
                /*
9281
                 * This should be moved to valid.c, but we don't keep track
9282
                 * whether an attribute was defaulted.
9283
                 */
9284
0
                if ((ctxt->validate) &&
9285
0
                    (ctxt->standalone == 1) &&
9286
0
                    (attr->external != 0)) {
9287
0
                    xmlValidityError(ctxt, XML_DTD_STANDALONE_DEFAULTED,
9288
0
                            "standalone: attribute %s on %s defaulted "
9289
0
                            "from external subset\n",
9290
0
                            attname, localname);
9291
0
                }
9292
0
#endif
9293
0
                nbdef++;
9294
0
      }
9295
0
  }
9296
0
    }
9297
9298
    /*
9299
     * Using a single hash table for nsUri/localName pairs cannot
9300
     * detect duplicate QNames reliably. The following example will
9301
     * only result in two namespace errors.
9302
     *
9303
     * <doc xmlns:a="a" xmlns:b="a">
9304
     *   <elem a:a="" b:a="" b:a=""/>
9305
     * </doc>
9306
     *
9307
     * If we saw more than one namespace error but no duplicate QNames
9308
     * were found, we have to scan for duplicate QNames.
9309
     */
9310
0
    if ((numDupErr == 0) && (numNsErr > 1)) {
9311
0
        memset(ctxt->attrHash, -1,
9312
0
               attrHashSize * sizeof(ctxt->attrHash[0]));
9313
9314
0
        for (i = 0, j = 0; j < nratts; i += 5, j++) {
9315
0
            unsigned hashValue, nameHashValue, prefixHashValue;
9316
0
            int res;
9317
9318
0
            aprefix = atts[i+1];
9319
0
            if (aprefix == NULL)
9320
0
                continue;
9321
9322
0
            attname = atts[i];
9323
            /* Hash values always have bit 31 set, see dict.c */
9324
0
            nameHashValue = ctxt->attallocs[j] | 0x80000000;
9325
0
            prefixHashValue = xmlDictComputeHash(ctxt->dict, aprefix);
9326
9327
0
            hashValue = xmlDictCombineHash(nameHashValue, prefixHashValue);
9328
0
            res = xmlAttrHashInsertQName(ctxt, attrHashSize, attname,
9329
0
                                         aprefix, hashValue, i);
9330
0
            if (res < INT_MAX)
9331
0
                xmlErrAttributeDup(ctxt, aprefix, attname);
9332
0
        }
9333
0
    }
9334
9335
    /*
9336
     * Reconstruct attribute pointers
9337
     */
9338
0
    for (i = 0, j = 0; i < nbatts; i += 5, j++) {
9339
        /* namespace URI */
9340
0
        nsIndex = XML_PTR_TO_INT(atts[i+2]);
9341
0
        if (nsIndex == INT_MAX)
9342
0
            atts[i+2] = NULL;
9343
0
        else if (nsIndex == INT_MAX - 1)
9344
0
            atts[i+2] = ctxt->str_xml_ns;
9345
0
        else
9346
0
            atts[i+2] = ctxt->nsTab[nsIndex * 2 + 1];
9347
9348
0
        if ((j < nratts) && (ctxt->attallocs[j] & 0x80000000) == 0) {
9349
0
            atts[i+3] = BASE_PTR + XML_PTR_TO_INT(atts[i+3]);  /* value */
9350
0
            atts[i+4] = BASE_PTR + XML_PTR_TO_INT(atts[i+4]);  /* valuend */
9351
0
        }
9352
0
    }
9353
9354
0
    uri = xmlParserNsLookupUri(ctxt, &hprefix);
9355
0
    if ((prefix != NULL) && (uri == NULL)) {
9356
0
  xmlNsErr(ctxt, XML_NS_ERR_UNDEFINED_NAMESPACE,
9357
0
           "Namespace prefix %s on %s is not defined\n",
9358
0
     prefix, localname, NULL);
9359
0
    }
9360
0
    *pref = prefix;
9361
0
    *URI = uri;
9362
9363
    /*
9364
     * SAX callback
9365
     */
9366
0
    if ((ctxt->sax != NULL) && (ctxt->sax->startElementNs != NULL) &&
9367
0
  (!ctxt->disableSAX)) {
9368
0
  if (nbNs > 0)
9369
0
      ctxt->sax->startElementNs(ctxt->userData, localname, prefix, uri,
9370
0
                          nbNs, ctxt->nsTab + 2 * (ctxt->nsNr - nbNs),
9371
0
        nbatts / 5, nbdef, atts);
9372
0
  else
9373
0
      ctxt->sax->startElementNs(ctxt->userData, localname, prefix, uri,
9374
0
                          0, NULL, nbatts / 5, nbdef, atts);
9375
0
    }
9376
9377
0
done:
9378
    /*
9379
     * Free allocated attribute values
9380
     */
9381
0
    if (attval != 0) {
9382
0
  for (i = 0, j = 0; j < nratts; i += 5, j++)
9383
0
      if (ctxt->attallocs[j] & 0x80000000)
9384
0
          xmlFree((xmlChar *) atts[i+3]);
9385
0
    }
9386
9387
0
    *nbNsPtr = nbNs;
9388
0
    return(localname);
9389
0
}
9390
9391
/**
9392
 * Parse an end tag. Always consumes '</'.
9393
 *
9394
 *     [42] ETag ::= '</' Name S? '>'
9395
 *
9396
 * With namespace
9397
 *
9398
 *     [NS 9] ETag ::= '</' QName S? '>'
9399
 * @param ctxt  an XML parser context
9400
 * @param tag  the corresponding start tag
9401
 */
9402
9403
static void
9404
0
xmlParseEndTag2(xmlParserCtxtPtr ctxt, const xmlStartTag *tag) {
9405
0
    const xmlChar *name;
9406
9407
0
    GROW;
9408
0
    if ((RAW != '<') || (NXT(1) != '/')) {
9409
0
  xmlFatalErr(ctxt, XML_ERR_LTSLASH_REQUIRED, NULL);
9410
0
  return;
9411
0
    }
9412
0
    SKIP(2);
9413
9414
0
    if (tag->prefix == NULL)
9415
0
        name = xmlParseNameAndCompare(ctxt, ctxt->name);
9416
0
    else
9417
0
        name = xmlParseQNameAndCompare(ctxt, ctxt->name, tag->prefix);
9418
9419
    /*
9420
     * We should definitely be at the ending "S? '>'" part
9421
     */
9422
0
    GROW;
9423
0
    SKIP_BLANKS;
9424
0
    if ((!IS_BYTE_CHAR(RAW)) || (RAW != '>')) {
9425
0
  xmlFatalErr(ctxt, XML_ERR_GT_REQUIRED, NULL);
9426
0
    } else
9427
0
  NEXT1;
9428
9429
    /*
9430
     * [ WFC: Element Type Match ]
9431
     * The Name in an element's end-tag must match the element type in the
9432
     * start-tag.
9433
     *
9434
     */
9435
0
    if (name != (xmlChar*)1) {
9436
0
        if (name == NULL) name = BAD_CAST "unparsable";
9437
0
        xmlFatalErrMsgStrIntStr(ctxt, XML_ERR_TAG_NAME_MISMATCH,
9438
0
         "Opening and ending tag mismatch: %s line %d and %s\n",
9439
0
                    ctxt->name, tag->line, name);
9440
0
    }
9441
9442
    /*
9443
     * SAX: End of Tag
9444
     */
9445
0
    if ((ctxt->sax != NULL) && (ctxt->sax->endElementNs != NULL) &&
9446
0
  (!ctxt->disableSAX))
9447
0
  ctxt->sax->endElementNs(ctxt->userData, ctxt->name, tag->prefix,
9448
0
                                tag->URI);
9449
9450
0
    spacePop(ctxt);
9451
0
    if (tag->nsNr != 0)
9452
0
  xmlParserNsPop(ctxt, tag->nsNr);
9453
0
}
9454
9455
/**
9456
 * Parse escaped pure raw content. Always consumes '<!['.
9457
 *
9458
 * @deprecated Internal function, don't use.
9459
 *
9460
 *     [18] CDSect ::= CDStart CData CDEnd
9461
 *
9462
 *     [19] CDStart ::= '<![CDATA['
9463
 *
9464
 *     [20] Data ::= (Char* - (Char* ']]>' Char*))
9465
 *
9466
 *     [21] CDEnd ::= ']]>'
9467
 * @param ctxt  an XML parser context
9468
 */
9469
void
9470
0
xmlParseCDSect(xmlParserCtxt *ctxt) {
9471
0
    xmlChar *buf = NULL;
9472
0
    int len = 0;
9473
0
    int size = XML_PARSER_BUFFER_SIZE;
9474
0
    int r, rl;
9475
0
    int s, sl;
9476
0
    int cur, l;
9477
0
    int maxLength = (ctxt->options & XML_PARSE_HUGE) ?
9478
0
                    XML_MAX_HUGE_LENGTH :
9479
0
                    XML_MAX_TEXT_LENGTH;
9480
9481
0
    if ((CUR != '<') || (NXT(1) != '!') || (NXT(2) != '['))
9482
0
        return;
9483
0
    SKIP(3);
9484
9485
0
    if (!CMP6(CUR_PTR, 'C', 'D', 'A', 'T', 'A', '['))
9486
0
        return;
9487
0
    SKIP(6);
9488
9489
0
    r = xmlCurrentCharRecover(ctxt, &rl);
9490
0
    if (!IS_CHAR(r)) {
9491
0
  xmlFatalErr(ctxt, XML_ERR_CDATA_NOT_FINISHED, NULL);
9492
0
        goto out;
9493
0
    }
9494
0
    NEXTL(rl);
9495
0
    s = xmlCurrentCharRecover(ctxt, &sl);
9496
0
    if (!IS_CHAR(s)) {
9497
0
  xmlFatalErr(ctxt, XML_ERR_CDATA_NOT_FINISHED, NULL);
9498
0
        goto out;
9499
0
    }
9500
0
    NEXTL(sl);
9501
0
    cur = xmlCurrentCharRecover(ctxt, &l);
9502
0
    buf = xmlMalloc(size);
9503
0
    if (buf == NULL) {
9504
0
  xmlErrMemory(ctxt);
9505
0
        goto out;
9506
0
    }
9507
0
    while (IS_CHAR(cur) &&
9508
0
           ((r != ']') || (s != ']') || (cur != '>'))) {
9509
0
  if (len + 5 >= size) {
9510
0
      xmlChar *tmp;
9511
0
            int newSize;
9512
9513
0
            newSize = xmlGrowCapacity(size, 1, 1, maxLength);
9514
0
            if (newSize < 0) {
9515
0
                xmlFatalErrMsg(ctxt, XML_ERR_CDATA_NOT_FINISHED,
9516
0
                               "CData section too big found\n");
9517
0
                goto out;
9518
0
            }
9519
0
      tmp = xmlRealloc(buf, newSize);
9520
0
      if (tmp == NULL) {
9521
0
    xmlErrMemory(ctxt);
9522
0
                goto out;
9523
0
      }
9524
0
      buf = tmp;
9525
0
      size = newSize;
9526
0
  }
9527
0
  COPY_BUF(buf, len, r);
9528
0
  r = s;
9529
0
  rl = sl;
9530
0
  s = cur;
9531
0
  sl = l;
9532
0
  NEXTL(l);
9533
0
  cur = xmlCurrentCharRecover(ctxt, &l);
9534
0
    }
9535
0
    buf[len] = 0;
9536
0
    if (cur != '>') {
9537
0
  xmlFatalErrMsgStr(ctxt, XML_ERR_CDATA_NOT_FINISHED,
9538
0
                       "CData section not finished\n%.50s\n", buf);
9539
0
        goto out;
9540
0
    }
9541
0
    NEXTL(l);
9542
9543
    /*
9544
     * OK the buffer is to be consumed as cdata.
9545
     */
9546
0
    if ((ctxt->sax != NULL) && (!ctxt->disableSAX)) {
9547
0
        if ((ctxt->sax->cdataBlock != NULL) &&
9548
0
            ((ctxt->options & XML_PARSE_NOCDATA) == 0)) {
9549
0
            ctxt->sax->cdataBlock(ctxt->userData, buf, len);
9550
0
        } else if (ctxt->sax->characters != NULL) {
9551
0
            ctxt->sax->characters(ctxt->userData, buf, len);
9552
0
        }
9553
0
    }
9554
9555
0
out:
9556
0
    xmlFree(buf);
9557
0
}
9558
9559
/**
9560
 * Parse a content sequence. Stops at EOF or '</'. Leaves checking of
9561
 * unexpected EOF to the caller.
9562
 *
9563
 * @param ctxt  an XML parser context
9564
 */
9565
9566
static void
9567
0
xmlParseContentInternal(xmlParserCtxtPtr ctxt) {
9568
0
    int oldNameNr = ctxt->nameNr;
9569
0
    int oldSpaceNr = ctxt->spaceNr;
9570
0
    int oldNodeNr = ctxt->nodeNr;
9571
9572
0
    GROW;
9573
0
    while ((ctxt->input->cur < ctxt->input->end) &&
9574
0
     (PARSER_STOPPED(ctxt) == 0)) {
9575
0
  const xmlChar *cur = ctxt->input->cur;
9576
9577
  /*
9578
   * First case : a Processing Instruction.
9579
   */
9580
0
  if ((*cur == '<') && (cur[1] == '?')) {
9581
0
      xmlParsePI(ctxt);
9582
0
  }
9583
9584
  /*
9585
   * Second case : a CDSection
9586
   */
9587
  /* 2.6.0 test was *cur not RAW */
9588
0
  else if (CMP9(CUR_PTR, '<', '!', '[', 'C', 'D', 'A', 'T', 'A', '[')) {
9589
0
      xmlParseCDSect(ctxt);
9590
0
  }
9591
9592
  /*
9593
   * Third case :  a comment
9594
   */
9595
0
  else if ((*cur == '<') && (NXT(1) == '!') &&
9596
0
     (NXT(2) == '-') && (NXT(3) == '-')) {
9597
0
      xmlParseComment(ctxt);
9598
0
  }
9599
9600
  /*
9601
   * Fourth case :  a sub-element.
9602
   */
9603
0
  else if (*cur == '<') {
9604
0
            if (NXT(1) == '/') {
9605
0
                if (ctxt->nameNr <= oldNameNr)
9606
0
                    break;
9607
0
          xmlParseElementEnd(ctxt);
9608
0
            } else {
9609
0
          xmlParseElementStart(ctxt);
9610
0
            }
9611
0
  }
9612
9613
  /*
9614
   * Fifth case : a reference. If if has not been resolved,
9615
   *    parsing returns it's Name, create the node
9616
   */
9617
9618
0
  else if (*cur == '&') {
9619
0
      xmlParseReference(ctxt);
9620
0
  }
9621
9622
  /*
9623
   * Last case, text. Note that References are handled directly.
9624
   */
9625
0
  else {
9626
0
      xmlParseCharDataInternal(ctxt, 0);
9627
0
  }
9628
9629
0
  SHRINK;
9630
0
  GROW;
9631
0
    }
9632
9633
0
    if ((ctxt->nameNr > oldNameNr) &&
9634
0
        (ctxt->input->cur >= ctxt->input->end) &&
9635
0
        (ctxt->wellFormed)) {
9636
0
        const xmlChar *name = ctxt->nameTab[ctxt->nameNr - 1];
9637
0
        int line = ctxt->pushTab[ctxt->nameNr - 1].line;
9638
0
        xmlFatalErrMsgStrIntStr(ctxt, XML_ERR_TAG_NOT_FINISHED,
9639
0
                "Premature end of data in tag %s line %d\n",
9640
0
                name, line, NULL);
9641
0
    }
9642
9643
    /*
9644
     * Clean up in error case
9645
     */
9646
9647
0
    while (ctxt->nodeNr > oldNodeNr)
9648
0
        nodePop(ctxt);
9649
9650
0
    while (ctxt->nameNr > oldNameNr) {
9651
0
        xmlStartTag *tag = &ctxt->pushTab[ctxt->nameNr - 1];
9652
9653
0
        if (tag->nsNr != 0)
9654
0
            xmlParserNsPop(ctxt, tag->nsNr);
9655
9656
0
        namePop(ctxt);
9657
0
    }
9658
9659
0
    while (ctxt->spaceNr > oldSpaceNr)
9660
0
        spacePop(ctxt);
9661
0
}
9662
9663
/**
9664
 * Parse XML element content. This is useful if you're only interested
9665
 * in custom SAX callbacks. If you want a node list, use
9666
 * #xmlCtxtParseContent.
9667
 *
9668
 * @param ctxt  an XML parser context
9669
 */
9670
void
9671
0
xmlParseContent(xmlParserCtxt *ctxt) {
9672
0
    if ((ctxt == NULL) || (ctxt->input == NULL))
9673
0
        return;
9674
9675
0
    xmlCtxtInitializeLate(ctxt);
9676
9677
0
    xmlParseContentInternal(ctxt);
9678
9679
0
    xmlParserCheckEOF(ctxt, XML_ERR_NOT_WELL_BALANCED);
9680
0
}
9681
9682
/**
9683
 * parse an XML element
9684
 *
9685
 * @deprecated Internal function, don't use.
9686
 *
9687
 *     [39] element ::= EmptyElemTag | STag content ETag
9688
 *
9689
 * [ WFC: Element Type Match ]
9690
 * The Name in an element's end-tag must match the element type in the
9691
 * start-tag.
9692
 *
9693
 * @param ctxt  an XML parser context
9694
 */
9695
9696
void
9697
0
xmlParseElement(xmlParserCtxt *ctxt) {
9698
0
    if (xmlParseElementStart(ctxt) != 0)
9699
0
        return;
9700
9701
0
    xmlParseContentInternal(ctxt);
9702
9703
0
    if (ctxt->input->cur >= ctxt->input->end) {
9704
0
        if (ctxt->wellFormed) {
9705
0
            const xmlChar *name = ctxt->nameTab[ctxt->nameNr - 1];
9706
0
            int line = ctxt->pushTab[ctxt->nameNr - 1].line;
9707
0
            xmlFatalErrMsgStrIntStr(ctxt, XML_ERR_TAG_NOT_FINISHED,
9708
0
                    "Premature end of data in tag %s line %d\n",
9709
0
                    name, line, NULL);
9710
0
        }
9711
0
        return;
9712
0
    }
9713
9714
0
    xmlParseElementEnd(ctxt);
9715
0
}
9716
9717
/**
9718
 * Parse the start of an XML element. Returns -1 in case of error, 0 if an
9719
 * opening tag was parsed, 1 if an empty element was parsed.
9720
 *
9721
 * Always consumes '<'.
9722
 *
9723
 * @param ctxt  an XML parser context
9724
 */
9725
static int
9726
0
xmlParseElementStart(xmlParserCtxtPtr ctxt) {
9727
0
    int maxDepth = (ctxt->options & XML_PARSE_HUGE) ? 2048 : 256;
9728
0
    const xmlChar *name;
9729
0
    const xmlChar *prefix = NULL;
9730
0
    const xmlChar *URI = NULL;
9731
0
    xmlParserNodeInfo node_info;
9732
0
    int line;
9733
0
    xmlNodePtr cur;
9734
0
    int nbNs = 0;
9735
9736
0
    if (ctxt->nameNr > maxDepth) {
9737
0
        xmlFatalErrMsgInt(ctxt, XML_ERR_RESOURCE_LIMIT,
9738
0
                "Excessive depth in document: %d use XML_PARSE_HUGE option\n",
9739
0
                ctxt->nameNr);
9740
0
  xmlHaltParser(ctxt);
9741
0
  return(-1);
9742
0
    }
9743
9744
    /* Capture start position */
9745
0
    if (ctxt->record_info) {
9746
0
        node_info.begin_pos = ctxt->input->consumed +
9747
0
                          (CUR_PTR - ctxt->input->base);
9748
0
  node_info.begin_line = ctxt->input->line;
9749
0
    }
9750
9751
0
    if (ctxt->spaceNr == 0)
9752
0
  spacePush(ctxt, -1);
9753
0
    else if (*ctxt->space == -2)
9754
0
  spacePush(ctxt, -1);
9755
0
    else
9756
0
  spacePush(ctxt, *ctxt->space);
9757
9758
0
    line = ctxt->input->line;
9759
0
#ifdef LIBXML_SAX1_ENABLED
9760
0
    if (ctxt->sax2)
9761
0
#endif /* LIBXML_SAX1_ENABLED */
9762
0
        name = xmlParseStartTag2(ctxt, &prefix, &URI, &nbNs);
9763
0
#ifdef LIBXML_SAX1_ENABLED
9764
0
    else
9765
0
  name = xmlParseStartTag(ctxt);
9766
0
#endif /* LIBXML_SAX1_ENABLED */
9767
0
    if (name == NULL) {
9768
0
  spacePop(ctxt);
9769
0
        return(-1);
9770
0
    }
9771
0
    nameNsPush(ctxt, name, prefix, URI, line, nbNs);
9772
0
    cur = ctxt->node;
9773
9774
0
#ifdef LIBXML_VALID_ENABLED
9775
    /*
9776
     * [ VC: Root Element Type ]
9777
     * The Name in the document type declaration must match the element
9778
     * type of the root element.
9779
     */
9780
0
    if (ctxt->validate && ctxt->wellFormed && ctxt->myDoc &&
9781
0
        ctxt->node && (ctxt->node == ctxt->myDoc->children))
9782
0
        ctxt->valid &= xmlValidateRoot(&ctxt->vctxt, ctxt->myDoc);
9783
0
#endif /* LIBXML_VALID_ENABLED */
9784
9785
    /*
9786
     * Check for an Empty Element.
9787
     */
9788
0
    if ((RAW == '/') && (NXT(1) == '>')) {
9789
0
        SKIP(2);
9790
0
  if (ctxt->sax2) {
9791
0
      if ((ctxt->sax != NULL) && (ctxt->sax->endElementNs != NULL) &&
9792
0
    (!ctxt->disableSAX))
9793
0
    ctxt->sax->endElementNs(ctxt->userData, name, prefix, URI);
9794
0
#ifdef LIBXML_SAX1_ENABLED
9795
0
  } else {
9796
0
      if ((ctxt->sax != NULL) && (ctxt->sax->endElement != NULL) &&
9797
0
    (!ctxt->disableSAX))
9798
0
    ctxt->sax->endElement(ctxt->userData, name);
9799
0
#endif /* LIBXML_SAX1_ENABLED */
9800
0
  }
9801
0
  namePop(ctxt);
9802
0
  spacePop(ctxt);
9803
0
  if (nbNs > 0)
9804
0
      xmlParserNsPop(ctxt, nbNs);
9805
0
  if (cur != NULL && ctxt->record_info) {
9806
0
            node_info.node = cur;
9807
0
            node_info.end_pos = ctxt->input->consumed +
9808
0
                                (CUR_PTR - ctxt->input->base);
9809
0
            node_info.end_line = ctxt->input->line;
9810
0
            xmlParserAddNodeInfo(ctxt, &node_info);
9811
0
  }
9812
0
  return(1);
9813
0
    }
9814
0
    if (RAW == '>') {
9815
0
        NEXT1;
9816
0
        if (cur != NULL && ctxt->record_info) {
9817
0
            node_info.node = cur;
9818
0
            node_info.end_pos = 0;
9819
0
            node_info.end_line = 0;
9820
0
            xmlParserAddNodeInfo(ctxt, &node_info);
9821
0
        }
9822
0
    } else {
9823
0
        xmlFatalErrMsgStrIntStr(ctxt, XML_ERR_GT_REQUIRED,
9824
0
         "Couldn't find end of Start Tag %s line %d\n",
9825
0
                    name, line, NULL);
9826
9827
  /*
9828
   * end of parsing of this node.
9829
   */
9830
0
  nodePop(ctxt);
9831
0
  namePop(ctxt);
9832
0
  spacePop(ctxt);
9833
0
  if (nbNs > 0)
9834
0
      xmlParserNsPop(ctxt, nbNs);
9835
0
  return(-1);
9836
0
    }
9837
9838
0
    return(0);
9839
0
}
9840
9841
/**
9842
 * Parse the end of an XML element. Always consumes '</'.
9843
 *
9844
 * @param ctxt  an XML parser context
9845
 */
9846
static void
9847
0
xmlParseElementEnd(xmlParserCtxtPtr ctxt) {
9848
0
    xmlNodePtr cur = ctxt->node;
9849
9850
0
    if (ctxt->nameNr <= 0) {
9851
0
        if ((RAW == '<') && (NXT(1) == '/'))
9852
0
            SKIP(2);
9853
0
        return;
9854
0
    }
9855
9856
    /*
9857
     * parse the end of tag: '</' should be here.
9858
     */
9859
0
    if (ctxt->sax2) {
9860
0
  xmlParseEndTag2(ctxt, &ctxt->pushTab[ctxt->nameNr - 1]);
9861
0
  namePop(ctxt);
9862
0
    }
9863
0
#ifdef LIBXML_SAX1_ENABLED
9864
0
    else
9865
0
  xmlParseEndTag1(ctxt, 0);
9866
0
#endif /* LIBXML_SAX1_ENABLED */
9867
9868
    /*
9869
     * Capture end position
9870
     */
9871
0
    if (cur != NULL && ctxt->record_info) {
9872
0
        xmlParserNodeInfoPtr node_info;
9873
9874
0
        node_info = (xmlParserNodeInfoPtr) xmlParserFindNodeInfo(ctxt, cur);
9875
0
        if (node_info != NULL) {
9876
0
            node_info->end_pos = ctxt->input->consumed +
9877
0
                                 (CUR_PTR - ctxt->input->base);
9878
0
            node_info->end_line = ctxt->input->line;
9879
0
        }
9880
0
    }
9881
0
}
9882
9883
/**
9884
 * parse the XML version value.
9885
 *
9886
 * @deprecated Internal function, don't use.
9887
 *
9888
 *     [26] VersionNum ::= '1.' [0-9]+
9889
 *
9890
 * In practice allow [0-9].[0-9]+ at that level
9891
 *
9892
 * @param ctxt  an XML parser context
9893
 * @returns the string giving the XML version number, or NULL
9894
 */
9895
xmlChar *
9896
0
xmlParseVersionNum(xmlParserCtxt *ctxt) {
9897
0
    xmlChar *buf = NULL;
9898
0
    int len = 0;
9899
0
    int size = 10;
9900
0
    int maxLength = (ctxt->options & XML_PARSE_HUGE) ?
9901
0
                    XML_MAX_TEXT_LENGTH :
9902
0
                    XML_MAX_NAME_LENGTH;
9903
0
    xmlChar cur;
9904
9905
0
    buf = xmlMalloc(size);
9906
0
    if (buf == NULL) {
9907
0
  xmlErrMemory(ctxt);
9908
0
  return(NULL);
9909
0
    }
9910
0
    cur = CUR;
9911
0
    if (!((cur >= '0') && (cur <= '9'))) {
9912
0
  xmlFree(buf);
9913
0
  return(NULL);
9914
0
    }
9915
0
    buf[len++] = cur;
9916
0
    NEXT;
9917
0
    cur=CUR;
9918
0
    if (cur != '.') {
9919
0
  xmlFree(buf);
9920
0
  return(NULL);
9921
0
    }
9922
0
    buf[len++] = cur;
9923
0
    NEXT;
9924
0
    cur=CUR;
9925
0
    while ((cur >= '0') && (cur <= '9')) {
9926
0
  if (len + 1 >= size) {
9927
0
      xmlChar *tmp;
9928
0
            int newSize;
9929
9930
0
            newSize = xmlGrowCapacity(size, 1, 1, maxLength);
9931
0
            if (newSize < 0) {
9932
0
                xmlFatalErr(ctxt, XML_ERR_NAME_TOO_LONG, "VersionNum");
9933
0
                xmlFree(buf);
9934
0
                return(NULL);
9935
0
            }
9936
0
      tmp = xmlRealloc(buf, newSize);
9937
0
      if (tmp == NULL) {
9938
0
    xmlErrMemory(ctxt);
9939
0
          xmlFree(buf);
9940
0
    return(NULL);
9941
0
      }
9942
0
      buf = tmp;
9943
0
            size = newSize;
9944
0
  }
9945
0
  buf[len++] = cur;
9946
0
  NEXT;
9947
0
  cur=CUR;
9948
0
    }
9949
0
    buf[len] = 0;
9950
0
    return(buf);
9951
0
}
9952
9953
/**
9954
 * parse the XML version.
9955
 *
9956
 * @deprecated Internal function, don't use.
9957
 *
9958
 *     [24] VersionInfo ::= S 'version' Eq (' VersionNum ' | " VersionNum ")
9959
 *
9960
 *     [25] Eq ::= S? '=' S?
9961
 *
9962
 * @param ctxt  an XML parser context
9963
 * @returns the version string, e.g. "1.0"
9964
 */
9965
9966
xmlChar *
9967
0
xmlParseVersionInfo(xmlParserCtxt *ctxt) {
9968
0
    xmlChar *version = NULL;
9969
9970
0
    if (CMP7(CUR_PTR, 'v', 'e', 'r', 's', 'i', 'o', 'n')) {
9971
0
  SKIP(7);
9972
0
  SKIP_BLANKS;
9973
0
  if (RAW != '=') {
9974
0
      xmlFatalErr(ctxt, XML_ERR_EQUAL_REQUIRED, NULL);
9975
0
      return(NULL);
9976
0
        }
9977
0
  NEXT;
9978
0
  SKIP_BLANKS;
9979
0
  if (RAW == '"') {
9980
0
      NEXT;
9981
0
      version = xmlParseVersionNum(ctxt);
9982
0
      if (RAW != '"') {
9983
0
    xmlFatalErr(ctxt, XML_ERR_STRING_NOT_CLOSED, NULL);
9984
0
      } else
9985
0
          NEXT;
9986
0
  } else if (RAW == '\''){
9987
0
      NEXT;
9988
0
      version = xmlParseVersionNum(ctxt);
9989
0
      if (RAW != '\'') {
9990
0
    xmlFatalErr(ctxt, XML_ERR_STRING_NOT_CLOSED, NULL);
9991
0
      } else
9992
0
          NEXT;
9993
0
  } else {
9994
0
      xmlFatalErr(ctxt, XML_ERR_STRING_NOT_STARTED, NULL);
9995
0
  }
9996
0
    }
9997
0
    return(version);
9998
0
}
9999
10000
/**
10001
 * parse the XML encoding name
10002
 *
10003
 * @deprecated Internal function, don't use.
10004
 *
10005
 *     [81] EncName ::= [A-Za-z] ([A-Za-z0-9._] | '-')*
10006
 *
10007
 * @param ctxt  an XML parser context
10008
 * @returns the encoding name value or NULL
10009
 */
10010
xmlChar *
10011
0
xmlParseEncName(xmlParserCtxt *ctxt) {
10012
0
    xmlChar *buf = NULL;
10013
0
    int len = 0;
10014
0
    int size = 10;
10015
0
    int maxLength = (ctxt->options & XML_PARSE_HUGE) ?
10016
0
                    XML_MAX_TEXT_LENGTH :
10017
0
                    XML_MAX_NAME_LENGTH;
10018
0
    xmlChar cur;
10019
10020
0
    cur = CUR;
10021
0
    if (((cur >= 'a') && (cur <= 'z')) ||
10022
0
        ((cur >= 'A') && (cur <= 'Z'))) {
10023
0
  buf = xmlMalloc(size);
10024
0
  if (buf == NULL) {
10025
0
      xmlErrMemory(ctxt);
10026
0
      return(NULL);
10027
0
  }
10028
10029
0
  buf[len++] = cur;
10030
0
  NEXT;
10031
0
  cur = CUR;
10032
0
  while (((cur >= 'a') && (cur <= 'z')) ||
10033
0
         ((cur >= 'A') && (cur <= 'Z')) ||
10034
0
         ((cur >= '0') && (cur <= '9')) ||
10035
0
         (cur == '.') || (cur == '_') ||
10036
0
         (cur == '-')) {
10037
0
      if (len + 1 >= size) {
10038
0
          xmlChar *tmp;
10039
0
                int newSize;
10040
10041
0
                newSize = xmlGrowCapacity(size, 1, 1, maxLength);
10042
0
                if (newSize < 0) {
10043
0
                    xmlFatalErr(ctxt, XML_ERR_NAME_TOO_LONG, "EncName");
10044
0
                    xmlFree(buf);
10045
0
                    return(NULL);
10046
0
                }
10047
0
    tmp = xmlRealloc(buf, newSize);
10048
0
    if (tmp == NULL) {
10049
0
        xmlErrMemory(ctxt);
10050
0
        xmlFree(buf);
10051
0
        return(NULL);
10052
0
    }
10053
0
    buf = tmp;
10054
0
                size = newSize;
10055
0
      }
10056
0
      buf[len++] = cur;
10057
0
      NEXT;
10058
0
      cur = CUR;
10059
0
        }
10060
0
  buf[len] = 0;
10061
0
    } else {
10062
0
  xmlFatalErr(ctxt, XML_ERR_ENCODING_NAME, NULL);
10063
0
    }
10064
0
    return(buf);
10065
0
}
10066
10067
/**
10068
 * parse the XML encoding declaration
10069
 *
10070
 * @deprecated Internal function, don't use.
10071
 *
10072
 *     [80] EncodingDecl ::= S 'encoding' Eq ('"' EncName '"' | 
10073
 *                           "'" EncName "'")
10074
 *
10075
 * this setups the conversion filters.
10076
 *
10077
 * @param ctxt  an XML parser context
10078
 * @returns the encoding value or NULL
10079
 */
10080
10081
const xmlChar *
10082
0
xmlParseEncodingDecl(xmlParserCtxt *ctxt) {
10083
0
    xmlChar *encoding = NULL;
10084
10085
0
    SKIP_BLANKS;
10086
0
    if (CMP8(CUR_PTR, 'e', 'n', 'c', 'o', 'd', 'i', 'n', 'g') == 0)
10087
0
        return(NULL);
10088
10089
0
    SKIP(8);
10090
0
    SKIP_BLANKS;
10091
0
    if (RAW != '=') {
10092
0
        xmlFatalErr(ctxt, XML_ERR_EQUAL_REQUIRED, NULL);
10093
0
        return(NULL);
10094
0
    }
10095
0
    NEXT;
10096
0
    SKIP_BLANKS;
10097
0
    if (RAW == '"') {
10098
0
        NEXT;
10099
0
        encoding = xmlParseEncName(ctxt);
10100
0
        if (RAW != '"') {
10101
0
            xmlFatalErr(ctxt, XML_ERR_STRING_NOT_CLOSED, NULL);
10102
0
            xmlFree(encoding);
10103
0
            return(NULL);
10104
0
        } else
10105
0
            NEXT;
10106
0
    } else if (RAW == '\''){
10107
0
        NEXT;
10108
0
        encoding = xmlParseEncName(ctxt);
10109
0
        if (RAW != '\'') {
10110
0
            xmlFatalErr(ctxt, XML_ERR_STRING_NOT_CLOSED, NULL);
10111
0
            xmlFree(encoding);
10112
0
            return(NULL);
10113
0
        } else
10114
0
            NEXT;
10115
0
    } else {
10116
0
        xmlFatalErr(ctxt, XML_ERR_STRING_NOT_STARTED, NULL);
10117
0
    }
10118
10119
0
    if (encoding == NULL)
10120
0
        return(NULL);
10121
10122
0
    xmlSetDeclaredEncoding(ctxt, encoding);
10123
10124
0
    return(ctxt->encoding);
10125
0
}
10126
10127
/**
10128
 * parse the XML standalone declaration
10129
 *
10130
 * @deprecated Internal function, don't use.
10131
 *
10132
 *     [32] SDDecl ::= S 'standalone' Eq
10133
 *                     (("'" ('yes' | 'no') "'") | ('"' ('yes' | 'no')'"'))
10134
 *
10135
 * [ VC: Standalone Document Declaration ]
10136
 * TODO The standalone document declaration must have the value "no"
10137
 * if any external markup declarations contain declarations of:
10138
 *  - attributes with default values, if elements to which these
10139
 *    attributes apply appear in the document without specifications
10140
 *    of values for these attributes, or
10141
 *  - entities (other than amp, lt, gt, apos, quot), if references
10142
 *    to those entities appear in the document, or
10143
 *  - attributes with values subject to normalization, where the
10144
 *    attribute appears in the document with a value which will change
10145
 *    as a result of normalization, or
10146
 *  - element types with element content, if white space occurs directly
10147
 *    within any instance of those types.
10148
 *
10149
 * @param ctxt  an XML parser context
10150
 * @returns
10151
 *   1 if standalone="yes"
10152
 *   0 if standalone="no"
10153
 *  -2 if standalone attribute is missing or invalid
10154
 *    (A standalone value of -2 means that the XML declaration was found,
10155
 *     but no value was specified for the standalone attribute).
10156
 */
10157
10158
int
10159
0
xmlParseSDDecl(xmlParserCtxt *ctxt) {
10160
0
    int standalone = -2;
10161
10162
0
    SKIP_BLANKS;
10163
0
    if (CMP10(CUR_PTR, 's', 't', 'a', 'n', 'd', 'a', 'l', 'o', 'n', 'e')) {
10164
0
  SKIP(10);
10165
0
        SKIP_BLANKS;
10166
0
  if (RAW != '=') {
10167
0
      xmlFatalErr(ctxt, XML_ERR_EQUAL_REQUIRED, NULL);
10168
0
      return(standalone);
10169
0
        }
10170
0
  NEXT;
10171
0
  SKIP_BLANKS;
10172
0
        if (RAW == '\''){
10173
0
      NEXT;
10174
0
      if ((RAW == 'n') && (NXT(1) == 'o')) {
10175
0
          standalone = 0;
10176
0
                SKIP(2);
10177
0
      } else if ((RAW == 'y') && (NXT(1) == 'e') &&
10178
0
                 (NXT(2) == 's')) {
10179
0
          standalone = 1;
10180
0
    SKIP(3);
10181
0
            } else {
10182
0
    xmlFatalErr(ctxt, XML_ERR_STANDALONE_VALUE, NULL);
10183
0
      }
10184
0
      if (RAW != '\'') {
10185
0
    xmlFatalErr(ctxt, XML_ERR_STRING_NOT_CLOSED, NULL);
10186
0
      } else
10187
0
          NEXT;
10188
0
  } else if (RAW == '"'){
10189
0
      NEXT;
10190
0
      if ((RAW == 'n') && (NXT(1) == 'o')) {
10191
0
          standalone = 0;
10192
0
    SKIP(2);
10193
0
      } else if ((RAW == 'y') && (NXT(1) == 'e') &&
10194
0
                 (NXT(2) == 's')) {
10195
0
          standalone = 1;
10196
0
                SKIP(3);
10197
0
            } else {
10198
0
    xmlFatalErr(ctxt, XML_ERR_STANDALONE_VALUE, NULL);
10199
0
      }
10200
0
      if (RAW != '"') {
10201
0
    xmlFatalErr(ctxt, XML_ERR_STRING_NOT_CLOSED, NULL);
10202
0
      } else
10203
0
          NEXT;
10204
0
  } else {
10205
0
      xmlFatalErr(ctxt, XML_ERR_STRING_NOT_STARTED, NULL);
10206
0
        }
10207
0
    }
10208
0
    return(standalone);
10209
0
}
10210
10211
/**
10212
 * parse an XML declaration header
10213
 *
10214
 * @deprecated Internal function, don't use.
10215
 *
10216
 *     [23] XMLDecl ::= '<?xml' VersionInfo EncodingDecl? SDDecl? S? '?>'
10217
 * @param ctxt  an XML parser context
10218
 */
10219
10220
void
10221
0
xmlParseXMLDecl(xmlParserCtxt *ctxt) {
10222
0
    xmlChar *version;
10223
10224
    /*
10225
     * This value for standalone indicates that the document has an
10226
     * XML declaration but it does not have a standalone attribute.
10227
     * It will be overwritten later if a standalone attribute is found.
10228
     */
10229
10230
0
    ctxt->standalone = -2;
10231
10232
    /*
10233
     * We know that '<?xml' is here.
10234
     */
10235
0
    SKIP(5);
10236
10237
0
    if (!IS_BLANK_CH(RAW)) {
10238
0
  xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED,
10239
0
                 "Blank needed after '<?xml'\n");
10240
0
    }
10241
0
    SKIP_BLANKS;
10242
10243
    /*
10244
     * We must have the VersionInfo here.
10245
     */
10246
0
    version = xmlParseVersionInfo(ctxt);
10247
0
    if (version == NULL) {
10248
0
  xmlFatalErr(ctxt, XML_ERR_VERSION_MISSING, NULL);
10249
0
    } else {
10250
0
  if (!xmlStrEqual(version, (const xmlChar *) XML_DEFAULT_VERSION)) {
10251
      /*
10252
       * Changed here for XML-1.0 5th edition
10253
       */
10254
0
      if (ctxt->options & XML_PARSE_OLD10) {
10255
0
    xmlFatalErrMsgStr(ctxt, XML_ERR_UNKNOWN_VERSION,
10256
0
                "Unsupported version '%s'\n",
10257
0
                version);
10258
0
      } else {
10259
0
          if ((version[0] == '1') && ((version[1] == '.'))) {
10260
0
        xmlWarningMsg(ctxt, XML_WAR_UNKNOWN_VERSION,
10261
0
                      "Unsupported version '%s'\n",
10262
0
          version, NULL);
10263
0
    } else {
10264
0
        xmlFatalErrMsgStr(ctxt, XML_ERR_UNKNOWN_VERSION,
10265
0
              "Unsupported version '%s'\n",
10266
0
              version);
10267
0
    }
10268
0
      }
10269
0
  }
10270
0
  if (ctxt->version != NULL)
10271
0
      xmlFree(ctxt->version);
10272
0
  ctxt->version = version;
10273
0
    }
10274
10275
    /*
10276
     * We may have the encoding declaration
10277
     */
10278
0
    if (!IS_BLANK_CH(RAW)) {
10279
0
        if ((RAW == '?') && (NXT(1) == '>')) {
10280
0
      SKIP(2);
10281
0
      return;
10282
0
  }
10283
0
  xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED, "Blank needed here\n");
10284
0
    }
10285
0
    xmlParseEncodingDecl(ctxt);
10286
10287
    /*
10288
     * We may have the standalone status.
10289
     */
10290
0
    if ((ctxt->encoding != NULL) && (!IS_BLANK_CH(RAW))) {
10291
0
        if ((RAW == '?') && (NXT(1) == '>')) {
10292
0
      SKIP(2);
10293
0
      return;
10294
0
  }
10295
0
  xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED, "Blank needed here\n");
10296
0
    }
10297
10298
    /*
10299
     * We can grow the input buffer freely at that point
10300
     */
10301
0
    GROW;
10302
10303
0
    SKIP_BLANKS;
10304
0
    ctxt->standalone = xmlParseSDDecl(ctxt);
10305
10306
0
    SKIP_BLANKS;
10307
0
    if ((RAW == '?') && (NXT(1) == '>')) {
10308
0
        SKIP(2);
10309
0
    } else if (RAW == '>') {
10310
        /* Deprecated old WD ... */
10311
0
  xmlFatalErr(ctxt, XML_ERR_XMLDECL_NOT_FINISHED, NULL);
10312
0
  NEXT;
10313
0
    } else {
10314
0
        int c;
10315
10316
0
  xmlFatalErr(ctxt, XML_ERR_XMLDECL_NOT_FINISHED, NULL);
10317
0
        while ((PARSER_STOPPED(ctxt) == 0) &&
10318
0
               ((c = CUR) != 0)) {
10319
0
            NEXT;
10320
0
            if (c == '>')
10321
0
                break;
10322
0
        }
10323
0
    }
10324
0
}
10325
10326
/**
10327
 * @since 2.14.0
10328
 *
10329
 * @param ctxt  parser context
10330
 * @returns the version from the XML declaration.
10331
 */
10332
const xmlChar *
10333
0
xmlCtxtGetVersion(xmlParserCtxt *ctxt) {
10334
0
    if (ctxt == NULL)
10335
0
        return(NULL);
10336
10337
0
    return(ctxt->version);
10338
0
}
10339
10340
/**
10341
 * @since 2.14.0
10342
 *
10343
 * @param ctxt  parser context
10344
 * @returns the value from the standalone document declaration.
10345
 */
10346
int
10347
0
xmlCtxtGetStandalone(xmlParserCtxt *ctxt) {
10348
0
    if (ctxt == NULL)
10349
0
        return(0);
10350
10351
0
    return(ctxt->standalone);
10352
0
}
10353
10354
/**
10355
 * parse an XML Misc* optional field.
10356
 *
10357
 * @deprecated Internal function, don't use.
10358
 *
10359
 *     [27] Misc ::= Comment | PI |  S
10360
 * @param ctxt  an XML parser context
10361
 */
10362
10363
void
10364
0
xmlParseMisc(xmlParserCtxt *ctxt) {
10365
0
    while (PARSER_STOPPED(ctxt) == 0) {
10366
0
        SKIP_BLANKS;
10367
0
        GROW;
10368
0
        if ((RAW == '<') && (NXT(1) == '?')) {
10369
0
      xmlParsePI(ctxt);
10370
0
        } else if (CMP4(CUR_PTR, '<', '!', '-', '-')) {
10371
0
      xmlParseComment(ctxt);
10372
0
        } else {
10373
0
            break;
10374
0
        }
10375
0
    }
10376
0
}
10377
10378
static void
10379
0
xmlFinishDocument(xmlParserCtxtPtr ctxt) {
10380
0
    xmlDocPtr doc;
10381
10382
    /*
10383
     * SAX: end of the document processing.
10384
     */
10385
0
    if ((ctxt->sax) && (ctxt->sax->endDocument != NULL))
10386
0
        ctxt->sax->endDocument(ctxt->userData);
10387
10388
    /*
10389
     * Remove locally kept entity definitions if the tree was not built
10390
     */
10391
0
    doc = ctxt->myDoc;
10392
0
    if ((doc != NULL) &&
10393
0
        (xmlStrEqual(doc->version, SAX_COMPAT_MODE))) {
10394
0
        xmlFreeDoc(doc);
10395
0
        ctxt->myDoc = NULL;
10396
0
    }
10397
0
}
10398
10399
/**
10400
 * Parse an XML document and invoke the SAX handlers. This is useful
10401
 * if you're only interested in custom SAX callbacks. If you want a
10402
 * document tree, use #xmlCtxtParseDocument.
10403
 *
10404
 * @param ctxt  an XML parser context
10405
 * @returns 0, -1 in case of error.
10406
 */
10407
10408
int
10409
0
xmlParseDocument(xmlParserCtxt *ctxt) {
10410
0
    if ((ctxt == NULL) || (ctxt->input == NULL))
10411
0
        return(-1);
10412
10413
0
    GROW;
10414
10415
    /*
10416
     * SAX: detecting the level.
10417
     */
10418
0
    xmlCtxtInitializeLate(ctxt);
10419
10420
0
    if ((ctxt->sax) && (ctxt->sax->setDocumentLocator)) {
10421
0
        ctxt->sax->setDocumentLocator(ctxt->userData,
10422
0
                (xmlSAXLocator *) &xmlDefaultSAXLocator);
10423
0
    }
10424
10425
0
    xmlDetectEncoding(ctxt);
10426
10427
0
    if (CUR == 0) {
10428
0
  xmlFatalErr(ctxt, XML_ERR_DOCUMENT_EMPTY, NULL);
10429
0
  return(-1);
10430
0
    }
10431
10432
0
    GROW;
10433
0
    if ((CMP5(CUR_PTR, '<', '?', 'x', 'm', 'l')) && (IS_BLANK_CH(NXT(5)))) {
10434
10435
  /*
10436
   * Note that we will switch encoding on the fly.
10437
   */
10438
0
  xmlParseXMLDecl(ctxt);
10439
0
  SKIP_BLANKS;
10440
0
    } else {
10441
0
  ctxt->version = xmlCharStrdup(XML_DEFAULT_VERSION);
10442
0
        if (ctxt->version == NULL) {
10443
0
            xmlErrMemory(ctxt);
10444
0
            return(-1);
10445
0
        }
10446
0
    }
10447
0
    if ((ctxt->sax) && (ctxt->sax->startDocument) && (!ctxt->disableSAX))
10448
0
        ctxt->sax->startDocument(ctxt->userData);
10449
0
    if ((ctxt->myDoc != NULL) && (ctxt->input != NULL) &&
10450
0
        (ctxt->input->buf != NULL) && (ctxt->input->buf->compressed >= 0)) {
10451
0
  ctxt->myDoc->compression = ctxt->input->buf->compressed;
10452
0
    }
10453
10454
    /*
10455
     * The Misc part of the Prolog
10456
     */
10457
0
    xmlParseMisc(ctxt);
10458
10459
    /*
10460
     * Then possibly doc type declaration(s) and more Misc
10461
     * (doctypedecl Misc*)?
10462
     */
10463
0
    GROW;
10464
0
    if (CMP9(CUR_PTR, '<', '!', 'D', 'O', 'C', 'T', 'Y', 'P', 'E')) {
10465
10466
0
  ctxt->inSubset = 1;
10467
0
  xmlParseDocTypeDecl(ctxt);
10468
0
  if (RAW == '[') {
10469
0
      xmlParseInternalSubset(ctxt);
10470
0
  } else if (RAW == '>') {
10471
0
            NEXT;
10472
0
        }
10473
10474
  /*
10475
   * Create and update the external subset.
10476
   */
10477
0
  ctxt->inSubset = 2;
10478
0
  if ((ctxt->sax != NULL) && (ctxt->sax->externalSubset != NULL) &&
10479
0
      (!ctxt->disableSAX))
10480
0
      ctxt->sax->externalSubset(ctxt->userData, ctxt->intSubName,
10481
0
                                ctxt->extSubSystem, ctxt->extSubURI);
10482
0
  ctxt->inSubset = 0;
10483
10484
0
        xmlCleanSpecialAttr(ctxt);
10485
10486
0
  xmlParseMisc(ctxt);
10487
0
    }
10488
10489
    /*
10490
     * Time to start parsing the tree itself
10491
     */
10492
0
    GROW;
10493
0
    if (RAW != '<') {
10494
0
        if (ctxt->wellFormed)
10495
0
            xmlFatalErrMsg(ctxt, XML_ERR_DOCUMENT_EMPTY,
10496
0
                           "Start tag expected, '<' not found\n");
10497
0
    } else {
10498
0
  xmlParseElement(ctxt);
10499
10500
  /*
10501
   * The Misc part at the end
10502
   */
10503
0
  xmlParseMisc(ctxt);
10504
10505
0
        xmlParserCheckEOF(ctxt, XML_ERR_DOCUMENT_END);
10506
0
    }
10507
10508
0
    ctxt->instate = XML_PARSER_EOF;
10509
0
    xmlFinishDocument(ctxt);
10510
10511
0
    if (! ctxt->wellFormed) {
10512
0
  ctxt->valid = 0;
10513
0
  return(-1);
10514
0
    }
10515
10516
0
    return(0);
10517
0
}
10518
10519
/**
10520
 * parse a general parsed entity
10521
 * An external general parsed entity is well-formed if it matches the
10522
 * production labeled extParsedEnt.
10523
 *
10524
 * @deprecated Internal function, don't use.
10525
 *
10526
 *     [78] extParsedEnt ::= TextDecl? content
10527
 *
10528
 * @param ctxt  an XML parser context
10529
 * @returns 0, -1 in case of error. the parser context is augmented
10530
 *                as a result of the parsing.
10531
 */
10532
10533
int
10534
0
xmlParseExtParsedEnt(xmlParserCtxt *ctxt) {
10535
0
    if ((ctxt == NULL) || (ctxt->input == NULL))
10536
0
        return(-1);
10537
10538
0
    xmlCtxtInitializeLate(ctxt);
10539
10540
0
    if ((ctxt->sax) && (ctxt->sax->setDocumentLocator)) {
10541
0
        ctxt->sax->setDocumentLocator(ctxt->userData,
10542
0
                (xmlSAXLocator *) &xmlDefaultSAXLocator);
10543
0
    }
10544
10545
0
    xmlDetectEncoding(ctxt);
10546
10547
0
    if (CUR == 0) {
10548
0
  xmlFatalErr(ctxt, XML_ERR_DOCUMENT_EMPTY, NULL);
10549
0
    }
10550
10551
    /*
10552
     * Check for the XMLDecl in the Prolog.
10553
     */
10554
0
    GROW;
10555
0
    if ((CMP5(CUR_PTR, '<', '?', 'x', 'm', 'l')) && (IS_BLANK_CH(NXT(5)))) {
10556
10557
  /*
10558
   * Note that we will switch encoding on the fly.
10559
   */
10560
0
  xmlParseXMLDecl(ctxt);
10561
0
  SKIP_BLANKS;
10562
0
    } else {
10563
0
  ctxt->version = xmlCharStrdup(XML_DEFAULT_VERSION);
10564
0
    }
10565
0
    if ((ctxt->sax) && (ctxt->sax->startDocument) && (!ctxt->disableSAX))
10566
0
        ctxt->sax->startDocument(ctxt->userData);
10567
10568
    /*
10569
     * Doing validity checking on chunk doesn't make sense
10570
     */
10571
0
    ctxt->options &= ~XML_PARSE_DTDVALID;
10572
0
    ctxt->validate = 0;
10573
0
    ctxt->depth = 0;
10574
10575
0
    xmlParseContentInternal(ctxt);
10576
10577
0
    if (ctxt->input->cur < ctxt->input->end)
10578
0
  xmlFatalErr(ctxt, XML_ERR_NOT_WELL_BALANCED, NULL);
10579
10580
    /*
10581
     * SAX: end of the document processing.
10582
     */
10583
0
    if ((ctxt->sax) && (ctxt->sax->endDocument != NULL))
10584
0
        ctxt->sax->endDocument(ctxt->userData);
10585
10586
0
    if (! ctxt->wellFormed) return(-1);
10587
0
    return(0);
10588
0
}
10589
10590
#ifdef LIBXML_PUSH_ENABLED
10591
/************************************************************************
10592
 *                  *
10593
 *    Progressive parsing interfaces        *
10594
 *                  *
10595
 ************************************************************************/
10596
10597
/**
10598
 * Check whether the input buffer contains a character.
10599
 *
10600
 * @param ctxt  an XML parser context
10601
 * @param c  character
10602
 */
10603
static int
10604
0
xmlParseLookupChar(xmlParserCtxtPtr ctxt, int c) {
10605
0
    const xmlChar *cur;
10606
10607
0
    if (ctxt->checkIndex == 0) {
10608
0
        cur = ctxt->input->cur + 1;
10609
0
    } else {
10610
0
        cur = ctxt->input->cur + ctxt->checkIndex;
10611
0
    }
10612
10613
0
    if (memchr(cur, c, ctxt->input->end - cur) == NULL) {
10614
0
        size_t index = ctxt->input->end - ctxt->input->cur;
10615
10616
0
        if (index > LONG_MAX) {
10617
0
            ctxt->checkIndex = 0;
10618
0
            return(1);
10619
0
        }
10620
0
        ctxt->checkIndex = index;
10621
0
        return(0);
10622
0
    } else {
10623
0
        ctxt->checkIndex = 0;
10624
0
        return(1);
10625
0
    }
10626
0
}
10627
10628
/**
10629
 * Check whether the input buffer contains a string.
10630
 *
10631
 * @param ctxt  an XML parser context
10632
 * @param startDelta  delta to apply at the start
10633
 * @param str  string
10634
 * @param strLen  length of string
10635
 */
10636
static const xmlChar *
10637
xmlParseLookupString(xmlParserCtxtPtr ctxt, size_t startDelta,
10638
0
                     const char *str, size_t strLen) {
10639
0
    const xmlChar *cur, *term;
10640
10641
0
    if (ctxt->checkIndex == 0) {
10642
0
        cur = ctxt->input->cur + startDelta;
10643
0
    } else {
10644
0
        cur = ctxt->input->cur + ctxt->checkIndex;
10645
0
    }
10646
10647
0
    term = BAD_CAST strstr((const char *) cur, str);
10648
0
    if (term == NULL) {
10649
0
        const xmlChar *end = ctxt->input->end;
10650
0
        size_t index;
10651
10652
        /* Rescan (strLen - 1) characters. */
10653
0
        if ((size_t) (end - cur) < strLen)
10654
0
            end = cur;
10655
0
        else
10656
0
            end -= strLen - 1;
10657
0
        index = end - ctxt->input->cur;
10658
0
        if (index > LONG_MAX) {
10659
0
            ctxt->checkIndex = 0;
10660
0
            return(ctxt->input->end - strLen);
10661
0
        }
10662
0
        ctxt->checkIndex = index;
10663
0
    } else {
10664
0
        ctxt->checkIndex = 0;
10665
0
    }
10666
10667
0
    return(term);
10668
0
}
10669
10670
/**
10671
 * Check whether the input buffer contains terminated char data.
10672
 *
10673
 * @param ctxt  an XML parser context
10674
 */
10675
static int
10676
0
xmlParseLookupCharData(xmlParserCtxtPtr ctxt) {
10677
0
    const xmlChar *cur = ctxt->input->cur + ctxt->checkIndex;
10678
0
    const xmlChar *end = ctxt->input->end;
10679
0
    size_t index;
10680
10681
0
    while (cur < end) {
10682
0
        if ((*cur == '<') || (*cur == '&')) {
10683
0
            ctxt->checkIndex = 0;
10684
0
            return(1);
10685
0
        }
10686
0
        cur++;
10687
0
    }
10688
10689
0
    index = cur - ctxt->input->cur;
10690
0
    if (index > LONG_MAX) {
10691
0
        ctxt->checkIndex = 0;
10692
0
        return(1);
10693
0
    }
10694
0
    ctxt->checkIndex = index;
10695
0
    return(0);
10696
0
}
10697
10698
/**
10699
 * Check whether there's enough data in the input buffer to finish parsing
10700
 * a start tag. This has to take quotes into account.
10701
 *
10702
 * @param ctxt  an XML parser context
10703
 */
10704
static int
10705
0
xmlParseLookupGt(xmlParserCtxtPtr ctxt) {
10706
0
    const xmlChar *cur;
10707
0
    const xmlChar *end = ctxt->input->end;
10708
0
    int state = ctxt->endCheckState;
10709
0
    size_t index;
10710
10711
0
    if (ctxt->checkIndex == 0)
10712
0
        cur = ctxt->input->cur + 1;
10713
0
    else
10714
0
        cur = ctxt->input->cur + ctxt->checkIndex;
10715
10716
0
    while (cur < end) {
10717
0
        if (state) {
10718
0
            if (*cur == state)
10719
0
                state = 0;
10720
0
        } else if (*cur == '\'' || *cur == '"') {
10721
0
            state = *cur;
10722
0
        } else if (*cur == '>') {
10723
0
            ctxt->checkIndex = 0;
10724
0
            ctxt->endCheckState = 0;
10725
0
            return(1);
10726
0
        }
10727
0
        cur++;
10728
0
    }
10729
10730
0
    index = cur - ctxt->input->cur;
10731
0
    if (index > LONG_MAX) {
10732
0
        ctxt->checkIndex = 0;
10733
0
        ctxt->endCheckState = 0;
10734
0
        return(1);
10735
0
    }
10736
0
    ctxt->checkIndex = index;
10737
0
    ctxt->endCheckState = state;
10738
0
    return(0);
10739
0
}
10740
10741
/**
10742
 * Check whether there's enough data in the input buffer to finish parsing
10743
 * the internal subset.
10744
 *
10745
 * @param ctxt  an XML parser context
10746
 */
10747
static int
10748
0
xmlParseLookupInternalSubset(xmlParserCtxtPtr ctxt) {
10749
    /*
10750
     * Sorry, but progressive parsing of the internal subset is not
10751
     * supported. We first check that the full content of the internal
10752
     * subset is available and parsing is launched only at that point.
10753
     * Internal subset ends with "']' S? '>'" in an unescaped section and
10754
     * not in a ']]>' sequence which are conditional sections.
10755
     */
10756
0
    const xmlChar *cur, *start;
10757
0
    const xmlChar *end = ctxt->input->end;
10758
0
    int state = ctxt->endCheckState;
10759
0
    size_t index;
10760
10761
0
    if (ctxt->checkIndex == 0) {
10762
0
        cur = ctxt->input->cur + 1;
10763
0
    } else {
10764
0
        cur = ctxt->input->cur + ctxt->checkIndex;
10765
0
    }
10766
0
    start = cur;
10767
10768
0
    while (cur < end) {
10769
0
        if (state == '-') {
10770
0
            if ((*cur == '-') &&
10771
0
                (cur[1] == '-') &&
10772
0
                (cur[2] == '>')) {
10773
0
                state = 0;
10774
0
                cur += 3;
10775
0
                start = cur;
10776
0
                continue;
10777
0
            }
10778
0
        }
10779
0
        else if (state == ']') {
10780
0
            if (*cur == '>') {
10781
0
                ctxt->checkIndex = 0;
10782
0
                ctxt->endCheckState = 0;
10783
0
                return(1);
10784
0
            }
10785
0
            if (IS_BLANK_CH(*cur)) {
10786
0
                state = ' ';
10787
0
            } else if (*cur != ']') {
10788
0
                state = 0;
10789
0
                start = cur;
10790
0
                continue;
10791
0
            }
10792
0
        }
10793
0
        else if (state == ' ') {
10794
0
            if (*cur == '>') {
10795
0
                ctxt->checkIndex = 0;
10796
0
                ctxt->endCheckState = 0;
10797
0
                return(1);
10798
0
            }
10799
0
            if (!IS_BLANK_CH(*cur)) {
10800
0
                state = 0;
10801
0
                start = cur;
10802
0
                continue;
10803
0
            }
10804
0
        }
10805
0
        else if (state != 0) {
10806
0
            if (*cur == state) {
10807
0
                state = 0;
10808
0
                start = cur + 1;
10809
0
            }
10810
0
        }
10811
0
        else if (*cur == '<') {
10812
0
            if ((cur[1] == '!') &&
10813
0
                (cur[2] == '-') &&
10814
0
                (cur[3] == '-')) {
10815
0
                state = '-';
10816
0
                cur += 4;
10817
                /* Don't treat <!--> as comment */
10818
0
                start = cur;
10819
0
                continue;
10820
0
            }
10821
0
        }
10822
0
        else if ((*cur == '"') || (*cur == '\'') || (*cur == ']')) {
10823
0
            state = *cur;
10824
0
        }
10825
10826
0
        cur++;
10827
0
    }
10828
10829
    /*
10830
     * Rescan the three last characters to detect "<!--" and "-->"
10831
     * split across chunks.
10832
     */
10833
0
    if ((state == 0) || (state == '-')) {
10834
0
        if (cur - start < 3)
10835
0
            cur = start;
10836
0
        else
10837
0
            cur -= 3;
10838
0
    }
10839
0
    index = cur - ctxt->input->cur;
10840
0
    if (index > LONG_MAX) {
10841
0
        ctxt->checkIndex = 0;
10842
0
        ctxt->endCheckState = 0;
10843
0
        return(1);
10844
0
    }
10845
0
    ctxt->checkIndex = index;
10846
0
    ctxt->endCheckState = state;
10847
0
    return(0);
10848
0
}
10849
10850
/**
10851
 * Try to progress on parsing
10852
 *
10853
 * @param ctxt  an XML parser context
10854
 * @param terminate  last chunk indicator
10855
 * @returns zero if no parsing was possible
10856
 */
10857
static int
10858
0
xmlParseTryOrFinish(xmlParserCtxtPtr ctxt, int terminate) {
10859
0
    int ret = 0;
10860
0
    size_t avail;
10861
0
    xmlChar cur, next;
10862
10863
0
    if (ctxt->input == NULL)
10864
0
        return(0);
10865
10866
0
    if ((ctxt->input != NULL) &&
10867
0
        (ctxt->input->cur - ctxt->input->base > 4096)) {
10868
0
        xmlParserShrink(ctxt);
10869
0
    }
10870
10871
0
    while (ctxt->disableSAX == 0) {
10872
0
        avail = ctxt->input->end - ctxt->input->cur;
10873
0
        if (avail < 1)
10874
0
      goto done;
10875
0
        switch (ctxt->instate) {
10876
0
            case XML_PARSER_EOF:
10877
          /*
10878
     * Document parsing is done !
10879
     */
10880
0
          goto done;
10881
0
            case XML_PARSER_START:
10882
                /*
10883
                 * Very first chars read from the document flow.
10884
                 */
10885
0
                if ((!terminate) && (avail < 4))
10886
0
                    goto done;
10887
10888
                /*
10889
                 * We need more bytes to detect EBCDIC code pages.
10890
                 * See xmlDetectEBCDIC.
10891
                 */
10892
0
                if ((CMP4(CUR_PTR, 0x4C, 0x6F, 0xA7, 0x94)) &&
10893
0
                    (!terminate) && (avail < 200))
10894
0
                    goto done;
10895
10896
0
                xmlDetectEncoding(ctxt);
10897
0
                ctxt->instate = XML_PARSER_XML_DECL;
10898
0
    break;
10899
10900
0
            case XML_PARSER_XML_DECL:
10901
0
    if ((!terminate) && (avail < 2))
10902
0
        goto done;
10903
0
    cur = ctxt->input->cur[0];
10904
0
    next = ctxt->input->cur[1];
10905
0
          if ((cur == '<') && (next == '?')) {
10906
        /* PI or XML decl */
10907
0
        if ((!terminate) &&
10908
0
                        (!xmlParseLookupString(ctxt, 2, "?>", 2)))
10909
0
      goto done;
10910
0
        if ((ctxt->input->cur[2] == 'x') &&
10911
0
      (ctxt->input->cur[3] == 'm') &&
10912
0
      (ctxt->input->cur[4] == 'l') &&
10913
0
      (IS_BLANK_CH(ctxt->input->cur[5]))) {
10914
0
      ret += 5;
10915
0
      xmlParseXMLDecl(ctxt);
10916
0
        } else {
10917
0
      ctxt->version = xmlCharStrdup(XML_DEFAULT_VERSION);
10918
0
                        if (ctxt->version == NULL) {
10919
0
                            xmlErrMemory(ctxt);
10920
0
                            break;
10921
0
                        }
10922
0
        }
10923
0
    } else {
10924
0
        ctxt->version = xmlCharStrdup(XML_DEFAULT_VERSION);
10925
0
        if (ctxt->version == NULL) {
10926
0
            xmlErrMemory(ctxt);
10927
0
      break;
10928
0
        }
10929
0
    }
10930
0
                if ((ctxt->sax) && (ctxt->sax->setDocumentLocator)) {
10931
0
                    ctxt->sax->setDocumentLocator(ctxt->userData,
10932
0
                            (xmlSAXLocator *) &xmlDefaultSAXLocator);
10933
0
                }
10934
0
                if ((ctxt->sax) && (ctxt->sax->startDocument) &&
10935
0
                    (!ctxt->disableSAX))
10936
0
                    ctxt->sax->startDocument(ctxt->userData);
10937
0
                ctxt->instate = XML_PARSER_MISC;
10938
0
    break;
10939
0
            case XML_PARSER_START_TAG: {
10940
0
          const xmlChar *name;
10941
0
    const xmlChar *prefix = NULL;
10942
0
    const xmlChar *URI = NULL;
10943
0
                int line = ctxt->input->line;
10944
0
    int nbNs = 0;
10945
10946
0
    if ((!terminate) && (avail < 2))
10947
0
        goto done;
10948
0
    cur = ctxt->input->cur[0];
10949
0
          if (cur != '<') {
10950
0
        xmlFatalErrMsg(ctxt, XML_ERR_DOCUMENT_EMPTY,
10951
0
                                   "Start tag expected, '<' not found");
10952
0
                    ctxt->instate = XML_PARSER_EOF;
10953
0
                    xmlFinishDocument(ctxt);
10954
0
        goto done;
10955
0
    }
10956
0
    if ((!terminate) && (!xmlParseLookupGt(ctxt)))
10957
0
                    goto done;
10958
0
    if (ctxt->spaceNr == 0)
10959
0
        spacePush(ctxt, -1);
10960
0
    else if (*ctxt->space == -2)
10961
0
        spacePush(ctxt, -1);
10962
0
    else
10963
0
        spacePush(ctxt, *ctxt->space);
10964
0
#ifdef LIBXML_SAX1_ENABLED
10965
0
    if (ctxt->sax2)
10966
0
#endif /* LIBXML_SAX1_ENABLED */
10967
0
        name = xmlParseStartTag2(ctxt, &prefix, &URI, &nbNs);
10968
0
#ifdef LIBXML_SAX1_ENABLED
10969
0
    else
10970
0
        name = xmlParseStartTag(ctxt);
10971
0
#endif /* LIBXML_SAX1_ENABLED */
10972
0
    if (name == NULL) {
10973
0
        spacePop(ctxt);
10974
0
                    ctxt->instate = XML_PARSER_EOF;
10975
0
                    xmlFinishDocument(ctxt);
10976
0
        goto done;
10977
0
    }
10978
0
#ifdef LIBXML_VALID_ENABLED
10979
    /*
10980
     * [ VC: Root Element Type ]
10981
     * The Name in the document type declaration must match
10982
     * the element type of the root element.
10983
     */
10984
0
    if (ctxt->validate && ctxt->wellFormed && ctxt->myDoc &&
10985
0
        ctxt->node && (ctxt->node == ctxt->myDoc->children))
10986
0
        ctxt->valid &= xmlValidateRoot(&ctxt->vctxt, ctxt->myDoc);
10987
0
#endif /* LIBXML_VALID_ENABLED */
10988
10989
    /*
10990
     * Check for an Empty Element.
10991
     */
10992
0
    if ((RAW == '/') && (NXT(1) == '>')) {
10993
0
        SKIP(2);
10994
10995
0
        if (ctxt->sax2) {
10996
0
      if ((ctxt->sax != NULL) &&
10997
0
          (ctxt->sax->endElementNs != NULL) &&
10998
0
          (!ctxt->disableSAX))
10999
0
          ctxt->sax->endElementNs(ctxt->userData, name,
11000
0
                                  prefix, URI);
11001
0
      if (nbNs > 0)
11002
0
          xmlParserNsPop(ctxt, nbNs);
11003
0
#ifdef LIBXML_SAX1_ENABLED
11004
0
        } else {
11005
0
      if ((ctxt->sax != NULL) &&
11006
0
          (ctxt->sax->endElement != NULL) &&
11007
0
          (!ctxt->disableSAX))
11008
0
          ctxt->sax->endElement(ctxt->userData, name);
11009
0
#endif /* LIBXML_SAX1_ENABLED */
11010
0
        }
11011
0
        spacePop(ctxt);
11012
0
    } else if (RAW == '>') {
11013
0
        NEXT;
11014
0
                    nameNsPush(ctxt, name, prefix, URI, line, nbNs);
11015
0
    } else {
11016
0
        xmlFatalErrMsgStr(ctxt, XML_ERR_GT_REQUIRED,
11017
0
           "Couldn't find end of Start Tag %s\n",
11018
0
           name);
11019
0
        nodePop(ctxt);
11020
0
        spacePop(ctxt);
11021
0
                    if (nbNs > 0)
11022
0
                        xmlParserNsPop(ctxt, nbNs);
11023
0
    }
11024
11025
0
                if (ctxt->nameNr == 0)
11026
0
                    ctxt->instate = XML_PARSER_EPILOG;
11027
0
                else
11028
0
                    ctxt->instate = XML_PARSER_CONTENT;
11029
0
                break;
11030
0
      }
11031
0
            case XML_PARSER_CONTENT: {
11032
0
    cur = ctxt->input->cur[0];
11033
11034
0
    if (cur == '<') {
11035
0
                    if ((!terminate) && (avail < 2))
11036
0
                        goto done;
11037
0
        next = ctxt->input->cur[1];
11038
11039
0
                    if (next == '/') {
11040
0
                        ctxt->instate = XML_PARSER_END_TAG;
11041
0
                        break;
11042
0
                    } else if (next == '?') {
11043
0
                        if ((!terminate) &&
11044
0
                            (!xmlParseLookupString(ctxt, 2, "?>", 2)))
11045
0
                            goto done;
11046
0
                        xmlParsePI(ctxt);
11047
0
                        ctxt->instate = XML_PARSER_CONTENT;
11048
0
                        break;
11049
0
                    } else if (next == '!') {
11050
0
                        if ((!terminate) && (avail < 3))
11051
0
                            goto done;
11052
0
                        next = ctxt->input->cur[2];
11053
11054
0
                        if (next == '-') {
11055
0
                            if ((!terminate) && (avail < 4))
11056
0
                                goto done;
11057
0
                            if (ctxt->input->cur[3] == '-') {
11058
0
                                if ((!terminate) &&
11059
0
                                    (!xmlParseLookupString(ctxt, 4, "-->", 3)))
11060
0
                                    goto done;
11061
0
                                xmlParseComment(ctxt);
11062
0
                                ctxt->instate = XML_PARSER_CONTENT;
11063
0
                                break;
11064
0
                            }
11065
0
                        } else if (next == '[') {
11066
0
                            if ((!terminate) && (avail < 9))
11067
0
                                goto done;
11068
0
                            if ((ctxt->input->cur[2] == '[') &&
11069
0
                                (ctxt->input->cur[3] == 'C') &&
11070
0
                                (ctxt->input->cur[4] == 'D') &&
11071
0
                                (ctxt->input->cur[5] == 'A') &&
11072
0
                                (ctxt->input->cur[6] == 'T') &&
11073
0
                                (ctxt->input->cur[7] == 'A') &&
11074
0
                                (ctxt->input->cur[8] == '[')) {
11075
0
                                if ((!terminate) &&
11076
0
                                    (!xmlParseLookupString(ctxt, 9, "]]>", 3)))
11077
0
                                    goto done;
11078
0
                                ctxt->instate = XML_PARSER_CDATA_SECTION;
11079
0
                                xmlParseCDSect(ctxt);
11080
0
                                ctxt->instate = XML_PARSER_CONTENT;
11081
0
                                break;
11082
0
                            }
11083
0
                        }
11084
0
                    }
11085
0
    } else if (cur == '&') {
11086
0
        if ((!terminate) && (!xmlParseLookupChar(ctxt, ';')))
11087
0
      goto done;
11088
0
        xmlParseReference(ctxt);
11089
0
                    break;
11090
0
    } else {
11091
        /* TODO Avoid the extra copy, handle directly !!! */
11092
        /*
11093
         * Goal of the following test is:
11094
         *  - minimize calls to the SAX 'character' callback
11095
         *    when they are mergeable
11096
         *  - handle an problem for isBlank when we only parse
11097
         *    a sequence of blank chars and the next one is
11098
         *    not available to check against '<' presence.
11099
         *  - tries to homogenize the differences in SAX
11100
         *    callbacks between the push and pull versions
11101
         *    of the parser.
11102
         */
11103
0
        if (avail < XML_PARSER_BIG_BUFFER_SIZE) {
11104
0
      if ((!terminate) && (!xmlParseLookupCharData(ctxt)))
11105
0
          goto done;
11106
0
                    }
11107
0
                    ctxt->checkIndex = 0;
11108
0
        xmlParseCharDataInternal(ctxt, !terminate);
11109
0
                    break;
11110
0
    }
11111
11112
0
                ctxt->instate = XML_PARSER_START_TAG;
11113
0
    break;
11114
0
      }
11115
0
            case XML_PARSER_END_TAG:
11116
0
    if ((!terminate) && (!xmlParseLookupChar(ctxt, '>')))
11117
0
        goto done;
11118
0
    if (ctxt->sax2) {
11119
0
              xmlParseEndTag2(ctxt, &ctxt->pushTab[ctxt->nameNr - 1]);
11120
0
        nameNsPop(ctxt);
11121
0
    }
11122
0
#ifdef LIBXML_SAX1_ENABLED
11123
0
      else
11124
0
        xmlParseEndTag1(ctxt, 0);
11125
0
#endif /* LIBXML_SAX1_ENABLED */
11126
0
    if (ctxt->nameNr == 0) {
11127
0
        ctxt->instate = XML_PARSER_EPILOG;
11128
0
    } else {
11129
0
        ctxt->instate = XML_PARSER_CONTENT;
11130
0
    }
11131
0
    break;
11132
0
            case XML_PARSER_MISC:
11133
0
            case XML_PARSER_PROLOG:
11134
0
            case XML_PARSER_EPILOG:
11135
0
    SKIP_BLANKS;
11136
0
                avail = ctxt->input->end - ctxt->input->cur;
11137
0
    if (avail < 1)
11138
0
        goto done;
11139
0
    if (ctxt->input->cur[0] == '<') {
11140
0
                    if ((!terminate) && (avail < 2))
11141
0
                        goto done;
11142
0
                    next = ctxt->input->cur[1];
11143
0
                    if (next == '?') {
11144
0
                        if ((!terminate) &&
11145
0
                            (!xmlParseLookupString(ctxt, 2, "?>", 2)))
11146
0
                            goto done;
11147
0
                        xmlParsePI(ctxt);
11148
0
                        break;
11149
0
                    } else if (next == '!') {
11150
0
                        if ((!terminate) && (avail < 3))
11151
0
                            goto done;
11152
11153
0
                        if (ctxt->input->cur[2] == '-') {
11154
0
                            if ((!terminate) && (avail < 4))
11155
0
                                goto done;
11156
0
                            if (ctxt->input->cur[3] == '-') {
11157
0
                                if ((!terminate) &&
11158
0
                                    (!xmlParseLookupString(ctxt, 4, "-->", 3)))
11159
0
                                    goto done;
11160
0
                                xmlParseComment(ctxt);
11161
0
                                break;
11162
0
                            }
11163
0
                        } else if (ctxt->instate == XML_PARSER_MISC) {
11164
0
                            if ((!terminate) && (avail < 9))
11165
0
                                goto done;
11166
0
                            if ((ctxt->input->cur[2] == 'D') &&
11167
0
                                (ctxt->input->cur[3] == 'O') &&
11168
0
                                (ctxt->input->cur[4] == 'C') &&
11169
0
                                (ctxt->input->cur[5] == 'T') &&
11170
0
                                (ctxt->input->cur[6] == 'Y') &&
11171
0
                                (ctxt->input->cur[7] == 'P') &&
11172
0
                                (ctxt->input->cur[8] == 'E')) {
11173
0
                                if ((!terminate) && (!xmlParseLookupGt(ctxt)))
11174
0
                                    goto done;
11175
0
                                ctxt->inSubset = 1;
11176
0
                                xmlParseDocTypeDecl(ctxt);
11177
0
                                if (RAW == '[') {
11178
0
                                    ctxt->instate = XML_PARSER_DTD;
11179
0
                                } else {
11180
0
                                    if (RAW == '>')
11181
0
                                        NEXT;
11182
                                    /*
11183
                                     * Create and update the external subset.
11184
                                     */
11185
0
                                    ctxt->inSubset = 2;
11186
0
                                    if ((ctxt->sax != NULL) &&
11187
0
                                        (!ctxt->disableSAX) &&
11188
0
                                        (ctxt->sax->externalSubset != NULL))
11189
0
                                        ctxt->sax->externalSubset(
11190
0
                                                ctxt->userData,
11191
0
                                                ctxt->intSubName,
11192
0
                                                ctxt->extSubSystem,
11193
0
                                                ctxt->extSubURI);
11194
0
                                    ctxt->inSubset = 0;
11195
0
                                    xmlCleanSpecialAttr(ctxt);
11196
0
                                    ctxt->instate = XML_PARSER_PROLOG;
11197
0
                                }
11198
0
                                break;
11199
0
                            }
11200
0
                        }
11201
0
                    }
11202
0
                }
11203
11204
0
                if (ctxt->instate == XML_PARSER_EPILOG) {
11205
0
                    if (ctxt->errNo == XML_ERR_OK)
11206
0
                        xmlFatalErr(ctxt, XML_ERR_DOCUMENT_END, NULL);
11207
0
        ctxt->instate = XML_PARSER_EOF;
11208
0
                    xmlFinishDocument(ctxt);
11209
0
                } else {
11210
0
        ctxt->instate = XML_PARSER_START_TAG;
11211
0
    }
11212
0
    break;
11213
0
            case XML_PARSER_DTD: {
11214
0
                if ((!terminate) && (!xmlParseLookupInternalSubset(ctxt)))
11215
0
                    goto done;
11216
0
    xmlParseInternalSubset(ctxt);
11217
0
    ctxt->inSubset = 2;
11218
0
    if ((ctxt->sax != NULL) && (!ctxt->disableSAX) &&
11219
0
        (ctxt->sax->externalSubset != NULL))
11220
0
        ctxt->sax->externalSubset(ctxt->userData, ctxt->intSubName,
11221
0
          ctxt->extSubSystem, ctxt->extSubURI);
11222
0
    ctxt->inSubset = 0;
11223
0
    xmlCleanSpecialAttr(ctxt);
11224
0
    ctxt->instate = XML_PARSER_PROLOG;
11225
0
                break;
11226
0
      }
11227
0
            default:
11228
0
                xmlFatalErrMsg(ctxt, XML_ERR_INTERNAL_ERROR,
11229
0
      "PP: internal error\n");
11230
0
    ctxt->instate = XML_PARSER_EOF;
11231
0
    break;
11232
0
  }
11233
0
    }
11234
0
done:
11235
0
    return(ret);
11236
0
}
11237
11238
/**
11239
 * Parse a chunk of memory in push parser mode.
11240
 *
11241
 * Assumes that the parser context was initialized with
11242
 * #xmlCreatePushParserCtxt.
11243
 *
11244
 * The last chunk, which will often be empty, must be marked with
11245
 * the `terminate` flag. With the default SAX callbacks, the resulting
11246
 * document will be available in ctxt->myDoc. This pointer will not
11247
 * be freed when calling #xmlFreeParserCtxt and must be freed by the
11248
 * caller. If the document isn't well-formed, it will still be returned
11249
 * in ctxt->myDoc.
11250
 *
11251
 * As an exception, #xmlCtxtResetPush will free the document in
11252
 * ctxt->myDoc. So ctxt->myDoc should be set to NULL after extracting
11253
 * the document.
11254
 *
11255
 * Since 2.14.0, #xmlCtxtGetDocument can be used to retrieve the
11256
 * result document.
11257
 *
11258
 * @param ctxt  an XML parser context
11259
 * @param chunk  chunk of memory
11260
 * @param size  size of chunk in bytes
11261
 * @param terminate  last chunk indicator
11262
 * @returns an xmlParserErrors code (0 on success).
11263
 */
11264
int
11265
xmlParseChunk(xmlParserCtxt *ctxt, const char *chunk, int size,
11266
0
              int terminate) {
11267
0
    size_t curBase;
11268
0
    size_t maxLength;
11269
0
    size_t pos;
11270
0
    int end_in_lf = 0;
11271
0
    int res;
11272
11273
0
    if ((ctxt == NULL) || (size < 0))
11274
0
        return(XML_ERR_ARGUMENT);
11275
0
    if ((chunk == NULL) && (size > 0))
11276
0
        return(XML_ERR_ARGUMENT);
11277
0
    if ((ctxt->input == NULL) || (ctxt->input->buf == NULL))
11278
0
        return(XML_ERR_ARGUMENT);
11279
0
    if (ctxt->disableSAX != 0)
11280
0
        return(ctxt->errNo);
11281
11282
0
    ctxt->input->flags |= XML_INPUT_PROGRESSIVE;
11283
0
    if (ctxt->instate == XML_PARSER_START)
11284
0
        xmlCtxtInitializeLate(ctxt);
11285
0
    if ((size > 0) && (chunk != NULL) && (!terminate) &&
11286
0
        (chunk[size - 1] == '\r')) {
11287
0
  end_in_lf = 1;
11288
0
  size--;
11289
0
    }
11290
11291
    /*
11292
     * Also push an empty chunk to make sure that the raw buffer
11293
     * will be flushed if there is an encoder.
11294
     */
11295
0
    pos = ctxt->input->cur - ctxt->input->base;
11296
0
    res = xmlParserInputBufferPush(ctxt->input->buf, size, chunk);
11297
0
    xmlBufUpdateInput(ctxt->input->buf->buffer, ctxt->input, pos);
11298
0
    if (res < 0) {
11299
0
        xmlCtxtErrIO(ctxt, ctxt->input->buf->error, NULL);
11300
0
        xmlHaltParser(ctxt);
11301
0
        return(ctxt->errNo);
11302
0
    }
11303
11304
0
    xmlParseTryOrFinish(ctxt, terminate);
11305
11306
0
    curBase = ctxt->input->cur - ctxt->input->base;
11307
0
    maxLength = (ctxt->options & XML_PARSE_HUGE) ?
11308
0
                XML_MAX_HUGE_LENGTH :
11309
0
                XML_MAX_LOOKUP_LIMIT;
11310
0
    if (curBase > maxLength) {
11311
0
        xmlFatalErr(ctxt, XML_ERR_RESOURCE_LIMIT,
11312
0
                    "Buffer size limit exceeded, try XML_PARSE_HUGE\n");
11313
0
        xmlHaltParser(ctxt);
11314
0
    }
11315
11316
0
    if ((ctxt->errNo != XML_ERR_OK) && (ctxt->disableSAX != 0))
11317
0
        return(ctxt->errNo);
11318
11319
0
    if (end_in_lf == 1) {
11320
0
  pos = ctxt->input->cur - ctxt->input->base;
11321
0
  res = xmlParserInputBufferPush(ctxt->input->buf, 1, "\r");
11322
0
  xmlBufUpdateInput(ctxt->input->buf->buffer, ctxt->input, pos);
11323
0
        if (res < 0) {
11324
0
            xmlCtxtErrIO(ctxt, ctxt->input->buf->error, NULL);
11325
0
            xmlHaltParser(ctxt);
11326
0
            return(ctxt->errNo);
11327
0
        }
11328
0
    }
11329
0
    if (terminate) {
11330
  /*
11331
   * Check for termination
11332
   */
11333
0
        if ((ctxt->instate != XML_PARSER_EOF) &&
11334
0
            (ctxt->instate != XML_PARSER_EPILOG)) {
11335
0
            if (ctxt->nameNr > 0) {
11336
0
                const xmlChar *name = ctxt->nameTab[ctxt->nameNr - 1];
11337
0
                int line = ctxt->pushTab[ctxt->nameNr - 1].line;
11338
0
                xmlFatalErrMsgStrIntStr(ctxt, XML_ERR_TAG_NOT_FINISHED,
11339
0
                        "Premature end of data in tag %s line %d\n",
11340
0
                        name, line, NULL);
11341
0
            } else if (ctxt->instate == XML_PARSER_START) {
11342
0
                xmlFatalErr(ctxt, XML_ERR_DOCUMENT_EMPTY, NULL);
11343
0
            } else {
11344
0
                xmlFatalErrMsg(ctxt, XML_ERR_DOCUMENT_EMPTY,
11345
0
                               "Start tag expected, '<' not found\n");
11346
0
            }
11347
0
        } else {
11348
0
            xmlParserCheckEOF(ctxt, XML_ERR_DOCUMENT_END);
11349
0
        }
11350
0
  if (ctxt->instate != XML_PARSER_EOF) {
11351
0
            ctxt->instate = XML_PARSER_EOF;
11352
0
            xmlFinishDocument(ctxt);
11353
0
  }
11354
0
    }
11355
0
    if (ctxt->wellFormed == 0)
11356
0
  return((xmlParserErrors) ctxt->errNo);
11357
0
    else
11358
0
        return(0);
11359
0
}
11360
11361
/************************************************************************
11362
 *                  *
11363
 *    I/O front end functions to the parser     *
11364
 *                  *
11365
 ************************************************************************/
11366
11367
/**
11368
 * Create a parser context for using the XML parser in push mode.
11369
 * See #xmlParseChunk.
11370
 *
11371
 * Passing an initial chunk is useless and deprecated.
11372
 *
11373
 * The push parser doesn't support recovery mode or the
11374
 * XML_PARSE_NOBLANKS option.
11375
 *
11376
 * `filename` is used as base URI to fetch external entities and for
11377
 * error reports.
11378
 *
11379
 * @param sax  a SAX handler (optional)
11380
 * @param user_data  user data for SAX callbacks (optional)
11381
 * @param chunk  initial chunk (optional, deprecated)
11382
 * @param size  size of initial chunk in bytes
11383
 * @param filename  file name or URI (optional)
11384
 * @returns the new parser context or NULL if a memory allocation
11385
 * failed.
11386
 */
11387
11388
xmlParserCtxt *
11389
xmlCreatePushParserCtxt(xmlSAXHandler *sax, void *user_data,
11390
40
                        const char *chunk, int size, const char *filename) {
11391
40
    xmlParserCtxtPtr ctxt;
11392
40
    xmlParserInputPtr input;
11393
11394
40
    ctxt = xmlNewSAXParserCtxt(sax, user_data);
11395
40
    if (ctxt == NULL)
11396
13
  return(NULL);
11397
11398
27
    ctxt->options &= ~XML_PARSE_NODICT;
11399
27
    ctxt->dictNames = 1;
11400
11401
27
    input = xmlNewPushInput(filename, chunk, size);
11402
27
    if (input == NULL) {
11403
27
  xmlFreeParserCtxt(ctxt);
11404
27
  return(NULL);
11405
27
    }
11406
0
    if (xmlCtxtPushInput(ctxt, input) < 0) {
11407
0
        xmlFreeInputStream(input);
11408
0
        xmlFreeParserCtxt(ctxt);
11409
0
        return(NULL);
11410
0
    }
11411
11412
0
    return(ctxt);
11413
0
}
11414
#endif /* LIBXML_PUSH_ENABLED */
11415
11416
/**
11417
 * Blocks further parser processing
11418
 *
11419
 * @param ctxt  an XML parser context
11420
 */
11421
void
11422
0
xmlStopParser(xmlParserCtxt *ctxt) {
11423
0
    if (ctxt == NULL)
11424
0
        return;
11425
0
    xmlHaltParser(ctxt);
11426
    /*
11427
     * TODO: Update ctxt->lastError and ctxt->wellFormed?
11428
     */
11429
0
    if (ctxt->errNo != XML_ERR_NO_MEMORY)
11430
0
        ctxt->errNo = XML_ERR_USER_STOP;
11431
0
}
11432
11433
/**
11434
 * Create a parser context for using the XML parser with an existing
11435
 * I/O stream
11436
 *
11437
 * @param sax  a SAX handler (optional)
11438
 * @param user_data  user data for SAX callbacks (optional)
11439
 * @param ioread  an I/O read function
11440
 * @param ioclose  an I/O close function (optional)
11441
 * @param ioctx  an I/O handler
11442
 * @param enc  the charset encoding if known (deprecated)
11443
 * @returns the new parser context or NULL
11444
 */
11445
xmlParserCtxt *
11446
xmlCreateIOParserCtxt(xmlSAXHandler *sax, void *user_data,
11447
                      xmlInputReadCallback ioread,
11448
                      xmlInputCloseCallback ioclose,
11449
0
                      void *ioctx, xmlCharEncoding enc) {
11450
0
    xmlParserCtxtPtr ctxt;
11451
0
    xmlParserInputPtr input;
11452
0
    const char *encoding;
11453
11454
0
    ctxt = xmlNewSAXParserCtxt(sax, user_data);
11455
0
    if (ctxt == NULL)
11456
0
  return(NULL);
11457
11458
0
    encoding = xmlGetCharEncodingName(enc);
11459
0
    input = xmlCtxtNewInputFromIO(ctxt, NULL, ioread, ioclose, ioctx,
11460
0
                                  encoding, 0);
11461
0
    if (input == NULL) {
11462
0
  xmlFreeParserCtxt(ctxt);
11463
0
        return (NULL);
11464
0
    }
11465
0
    if (xmlCtxtPushInput(ctxt, input) < 0) {
11466
0
        xmlFreeInputStream(input);
11467
0
        xmlFreeParserCtxt(ctxt);
11468
0
        return(NULL);
11469
0
    }
11470
11471
0
    return(ctxt);
11472
0
}
11473
11474
#ifdef LIBXML_VALID_ENABLED
11475
/************************************************************************
11476
 *                  *
11477
 *    Front ends when parsing a DTD       *
11478
 *                  *
11479
 ************************************************************************/
11480
11481
/**
11482
 * Parse a DTD.
11483
 *
11484
 * Option XML_PARSE_DTDLOAD should be enabled in the parser context
11485
 * to make external entities work.
11486
 *
11487
 * @since 2.14.0
11488
 *
11489
 * @param ctxt  a parser context
11490
 * @param input  a parser input
11491
 * @param publicId  public ID of the DTD (optional)
11492
 * @param systemId  system ID of the DTD (optional)
11493
 * @returns the resulting xmlDtd or NULL in case of error.
11494
 * `input` will be freed by the function in any case.
11495
 */
11496
xmlDtd *
11497
xmlCtxtParseDtd(xmlParserCtxt *ctxt, xmlParserInput *input,
11498
0
                const xmlChar *publicId, const xmlChar *systemId) {
11499
0
    xmlDtdPtr ret = NULL;
11500
11501
0
    if ((ctxt == NULL) || (input == NULL)) {
11502
0
        xmlFatalErr(ctxt, XML_ERR_ARGUMENT, NULL);
11503
0
        xmlFreeInputStream(input);
11504
0
        return(NULL);
11505
0
    }
11506
11507
0
    if (xmlCtxtPushInput(ctxt, input) < 0) {
11508
0
        xmlFreeInputStream(input);
11509
0
        return(NULL);
11510
0
    }
11511
11512
0
    if (publicId == NULL)
11513
0
        publicId = BAD_CAST "none";
11514
0
    if (systemId == NULL)
11515
0
        systemId = BAD_CAST "none";
11516
11517
0
    ctxt->myDoc = xmlNewDoc(BAD_CAST "1.0");
11518
0
    if (ctxt->myDoc == NULL) {
11519
0
        xmlErrMemory(ctxt);
11520
0
        goto error;
11521
0
    }
11522
0
    ctxt->myDoc->properties = XML_DOC_INTERNAL;
11523
0
    ctxt->myDoc->extSubset = xmlNewDtd(ctxt->myDoc, BAD_CAST "none",
11524
0
                                       publicId, systemId);
11525
0
    if (ctxt->myDoc->extSubset == NULL) {
11526
0
        xmlErrMemory(ctxt);
11527
0
        xmlFreeDoc(ctxt->myDoc);
11528
0
        goto error;
11529
0
    }
11530
11531
0
    xmlParseExternalSubset(ctxt, publicId, systemId);
11532
11533
0
    if (ctxt->wellFormed) {
11534
0
        ret = ctxt->myDoc->extSubset;
11535
0
        ctxt->myDoc->extSubset = NULL;
11536
0
        if (ret != NULL) {
11537
0
            xmlNodePtr tmp;
11538
11539
0
            ret->doc = NULL;
11540
0
            tmp = ret->children;
11541
0
            while (tmp != NULL) {
11542
0
                tmp->doc = NULL;
11543
0
                tmp = tmp->next;
11544
0
            }
11545
0
        }
11546
0
    } else {
11547
0
        ret = NULL;
11548
0
    }
11549
0
    xmlFreeDoc(ctxt->myDoc);
11550
0
    ctxt->myDoc = NULL;
11551
11552
0
error:
11553
0
    xmlFreeInputStream(xmlCtxtPopInput(ctxt));
11554
11555
0
    return(ret);
11556
0
}
11557
11558
/**
11559
 * Load and parse a DTD
11560
 *
11561
 * @deprecated Use #xmlCtxtParseDtd.
11562
 *
11563
 * @param sax  the SAX handler block or NULL
11564
 * @param input  an Input Buffer
11565
 * @param enc  the charset encoding if known
11566
 * @returns the resulting xmlDtd or NULL in case of error.
11567
 * `input` will be freed by the function in any case.
11568
 */
11569
11570
xmlDtd *
11571
xmlIOParseDTD(xmlSAXHandler *sax, xmlParserInputBuffer *input,
11572
0
        xmlCharEncoding enc) {
11573
0
    xmlDtdPtr ret = NULL;
11574
0
    xmlParserCtxtPtr ctxt;
11575
0
    xmlParserInputPtr pinput = NULL;
11576
11577
0
    if (input == NULL)
11578
0
  return(NULL);
11579
11580
0
    ctxt = xmlNewSAXParserCtxt(sax, NULL);
11581
0
    if (ctxt == NULL) {
11582
0
        xmlFreeParserInputBuffer(input);
11583
0
  return(NULL);
11584
0
    }
11585
0
    xmlCtxtSetOptions(ctxt, XML_PARSE_DTDLOAD);
11586
11587
    /*
11588
     * generate a parser input from the I/O handler
11589
     */
11590
11591
0
    pinput = xmlNewIOInputStream(ctxt, input, XML_CHAR_ENCODING_NONE);
11592
0
    if (pinput == NULL) {
11593
0
        xmlFreeParserInputBuffer(input);
11594
0
  xmlFreeParserCtxt(ctxt);
11595
0
  return(NULL);
11596
0
    }
11597
11598
0
    if (enc != XML_CHAR_ENCODING_NONE) {
11599
0
        xmlSwitchEncoding(ctxt, enc);
11600
0
    }
11601
11602
0
    ret = xmlCtxtParseDtd(ctxt, pinput, NULL, NULL);
11603
11604
0
    xmlFreeParserCtxt(ctxt);
11605
0
    return(ret);
11606
0
}
11607
11608
/**
11609
 * Load and parse an external subset.
11610
 *
11611
 * @deprecated Use #xmlCtxtParseDtd.
11612
 *
11613
 * @param sax  the SAX handler block
11614
 * @param publicId  public identifier of the DTD (optional)
11615
 * @param systemId  system identifier (URL) of the DTD
11616
 * @returns the resulting xmlDtd or NULL in case of error.
11617
 */
11618
11619
xmlDtd *
11620
xmlSAXParseDTD(xmlSAXHandler *sax, const xmlChar *publicId,
11621
0
               const xmlChar *systemId) {
11622
0
    xmlDtdPtr ret = NULL;
11623
0
    xmlParserCtxtPtr ctxt;
11624
0
    xmlParserInputPtr input = NULL;
11625
0
    xmlChar* systemIdCanonic;
11626
11627
0
    if ((publicId == NULL) && (systemId == NULL)) return(NULL);
11628
11629
0
    ctxt = xmlNewSAXParserCtxt(sax, NULL);
11630
0
    if (ctxt == NULL) {
11631
0
  return(NULL);
11632
0
    }
11633
0
    xmlCtxtSetOptions(ctxt, XML_PARSE_DTDLOAD);
11634
11635
    /*
11636
     * Canonicalise the system ID
11637
     */
11638
0
    systemIdCanonic = xmlCanonicPath(systemId);
11639
0
    if ((systemId != NULL) && (systemIdCanonic == NULL)) {
11640
0
  xmlFreeParserCtxt(ctxt);
11641
0
  return(NULL);
11642
0
    }
11643
11644
    /*
11645
     * Ask the Entity resolver to load the damn thing
11646
     */
11647
11648
0
    if ((ctxt->sax != NULL) && (ctxt->sax->resolveEntity != NULL))
11649
0
  input = ctxt->sax->resolveEntity(ctxt->userData, publicId,
11650
0
                                   systemIdCanonic);
11651
0
    if (input == NULL) {
11652
0
  xmlFreeParserCtxt(ctxt);
11653
0
  if (systemIdCanonic != NULL)
11654
0
      xmlFree(systemIdCanonic);
11655
0
  return(NULL);
11656
0
    }
11657
11658
0
    if (input->filename == NULL)
11659
0
  input->filename = (char *) systemIdCanonic;
11660
0
    else
11661
0
  xmlFree(systemIdCanonic);
11662
11663
0
    ret = xmlCtxtParseDtd(ctxt, input, publicId, systemId);
11664
11665
0
    xmlFreeParserCtxt(ctxt);
11666
0
    return(ret);
11667
0
}
11668
11669
11670
/**
11671
 * Load and parse an external subset.
11672
 *
11673
 * @param publicId  public identifier of the DTD (optional)
11674
 * @param systemId  system identifier (URL) of the DTD
11675
 * @returns the resulting xmlDtd or NULL in case of error.
11676
 */
11677
11678
xmlDtd *
11679
0
xmlParseDTD(const xmlChar *publicId, const xmlChar *systemId) {
11680
0
    return(xmlSAXParseDTD(NULL, publicId, systemId));
11681
0
}
11682
#endif /* LIBXML_VALID_ENABLED */
11683
11684
/************************************************************************
11685
 *                  *
11686
 *    Front ends when parsing an Entity     *
11687
 *                  *
11688
 ************************************************************************/
11689
11690
static xmlNodePtr
11691
xmlCtxtParseContentInternal(xmlParserCtxtPtr ctxt, xmlParserInputPtr input,
11692
0
                            int hasTextDecl, int buildTree) {
11693
0
    xmlNodePtr root = NULL;
11694
0
    xmlNodePtr list = NULL;
11695
0
    xmlChar *rootName = BAD_CAST "#root";
11696
0
    int result;
11697
11698
0
    if (buildTree) {
11699
0
        root = xmlNewDocNode(ctxt->myDoc, NULL, rootName, NULL);
11700
0
        if (root == NULL) {
11701
0
            xmlErrMemory(ctxt);
11702
0
            goto error;
11703
0
        }
11704
0
    }
11705
11706
0
    if (xmlCtxtPushInput(ctxt, input) < 0)
11707
0
        goto error;
11708
11709
0
    nameNsPush(ctxt, rootName, NULL, NULL, 0, 0);
11710
0
    spacePush(ctxt, -1);
11711
11712
0
    if (buildTree)
11713
0
        nodePush(ctxt, root);
11714
11715
0
    if (hasTextDecl) {
11716
0
        xmlDetectEncoding(ctxt);
11717
11718
        /*
11719
         * Parse a possible text declaration first
11720
         */
11721
0
        if ((CMP5(CUR_PTR, '<', '?', 'x', 'm', 'l')) &&
11722
0
            (IS_BLANK_CH(NXT(5)))) {
11723
0
            xmlParseTextDecl(ctxt);
11724
            /*
11725
             * An XML-1.0 document can't reference an entity not XML-1.0
11726
             */
11727
0
            if ((xmlStrEqual(ctxt->version, BAD_CAST "1.0")) &&
11728
0
                (!xmlStrEqual(ctxt->input->version, BAD_CAST "1.0"))) {
11729
0
                xmlFatalErrMsg(ctxt, XML_ERR_VERSION_MISMATCH,
11730
0
                               "Version mismatch between document and "
11731
0
                               "entity\n");
11732
0
            }
11733
0
        }
11734
0
    }
11735
11736
0
    xmlParseContentInternal(ctxt);
11737
11738
0
    if (ctxt->input->cur < ctxt->input->end)
11739
0
  xmlFatalErr(ctxt, XML_ERR_NOT_WELL_BALANCED, NULL);
11740
11741
0
    if ((ctxt->wellFormed) ||
11742
0
        ((ctxt->recovery) && (!xmlCtxtIsCatastrophicError(ctxt)))) {
11743
0
        if (root != NULL) {
11744
0
            xmlNodePtr cur;
11745
11746
            /*
11747
             * Unlink newly created node list.
11748
             */
11749
0
            list = root->children;
11750
0
            root->children = NULL;
11751
0
            root->last = NULL;
11752
0
            for (cur = list; cur != NULL; cur = cur->next)
11753
0
                cur->parent = NULL;
11754
0
        }
11755
0
    }
11756
11757
    /*
11758
     * Read the rest of the stream in case of errors. We want
11759
     * to account for the whole entity size.
11760
     */
11761
0
    do {
11762
0
        ctxt->input->cur = ctxt->input->end;
11763
0
        xmlParserShrink(ctxt);
11764
0
        result = xmlParserGrow(ctxt);
11765
0
    } while (result > 0);
11766
11767
0
    if (buildTree)
11768
0
        nodePop(ctxt);
11769
11770
0
    namePop(ctxt);
11771
0
    spacePop(ctxt);
11772
11773
0
    xmlCtxtPopInput(ctxt);
11774
11775
0
error:
11776
0
    xmlFreeNode(root);
11777
11778
0
    return(list);
11779
0
}
11780
11781
static void
11782
0
xmlCtxtParseEntity(xmlParserCtxtPtr ctxt, xmlEntityPtr ent) {
11783
0
    xmlParserInputPtr input;
11784
0
    xmlNodePtr list;
11785
0
    unsigned long consumed;
11786
0
    int isExternal;
11787
0
    int buildTree;
11788
0
    int oldMinNsIndex;
11789
0
    int oldNodelen, oldNodemem;
11790
11791
0
    isExternal = (ent->etype == XML_EXTERNAL_GENERAL_PARSED_ENTITY);
11792
0
    buildTree = (ctxt->node != NULL);
11793
11794
    /*
11795
     * Recursion check
11796
     */
11797
0
    if (ent->flags & XML_ENT_EXPANDING) {
11798
0
        xmlFatalErr(ctxt, XML_ERR_ENTITY_LOOP, NULL);
11799
0
        xmlHaltParser(ctxt);
11800
0
        goto error;
11801
0
    }
11802
11803
    /*
11804
     * Load entity
11805
     */
11806
0
    input = xmlNewEntityInputStream(ctxt, ent);
11807
0
    if (input == NULL)
11808
0
        goto error;
11809
11810
    /*
11811
     * When building a tree, we need to limit the scope of namespace
11812
     * declarations, so that entities don't reference xmlNs structs
11813
     * from the parent of a reference.
11814
     */
11815
0
    oldMinNsIndex = ctxt->nsdb->minNsIndex;
11816
0
    if (buildTree)
11817
0
        ctxt->nsdb->minNsIndex = ctxt->nsNr;
11818
11819
0
    oldNodelen = ctxt->nodelen;
11820
0
    oldNodemem = ctxt->nodemem;
11821
0
    ctxt->nodelen = 0;
11822
0
    ctxt->nodemem = 0;
11823
11824
    /*
11825
     * Parse content
11826
     *
11827
     * This initiates a recursive call chain:
11828
     *
11829
     * - xmlCtxtParseContentInternal
11830
     * - xmlParseContentInternal
11831
     * - xmlParseReference
11832
     * - xmlCtxtParseEntity
11833
     *
11834
     * The nesting depth is limited by the maximum number of inputs,
11835
     * see xmlCtxtPushInput.
11836
     *
11837
     * It's possible to make this non-recursive (minNsIndex must be
11838
     * stored in the input struct) at the expense of code readability.
11839
     */
11840
11841
0
    ent->flags |= XML_ENT_EXPANDING;
11842
11843
0
    list = xmlCtxtParseContentInternal(ctxt, input, isExternal, buildTree);
11844
11845
0
    ent->flags &= ~XML_ENT_EXPANDING;
11846
11847
0
    ctxt->nsdb->minNsIndex = oldMinNsIndex;
11848
0
    ctxt->nodelen = oldNodelen;
11849
0
    ctxt->nodemem = oldNodemem;
11850
11851
    /*
11852
     * Entity size accounting
11853
     */
11854
0
    consumed = input->consumed;
11855
0
    xmlSaturatedAddSizeT(&consumed, input->end - input->base);
11856
11857
0
    if ((ent->flags & XML_ENT_CHECKED) == 0)
11858
0
        xmlSaturatedAdd(&ent->expandedSize, consumed);
11859
11860
0
    if ((ent->flags & XML_ENT_PARSED) == 0) {
11861
0
        if (isExternal)
11862
0
            xmlSaturatedAdd(&ctxt->sizeentities, consumed);
11863
11864
0
        ent->children = list;
11865
11866
0
        while (list != NULL) {
11867
0
            list->parent = (xmlNodePtr) ent;
11868
11869
            /*
11870
             * Downstream code like the nginx xslt module can set
11871
             * ctxt->myDoc->extSubset to a separate DTD, so the entity
11872
             * might have a different or a NULL document.
11873
             */
11874
0
            if (list->doc != ent->doc)
11875
0
                xmlSetTreeDoc(list, ent->doc);
11876
11877
0
            if (list->next == NULL)
11878
0
                ent->last = list;
11879
0
            list = list->next;
11880
0
        }
11881
0
    } else {
11882
0
        xmlFreeNodeList(list);
11883
0
    }
11884
11885
0
    xmlFreeInputStream(input);
11886
11887
0
error:
11888
0
    ent->flags |= XML_ENT_PARSED | XML_ENT_CHECKED;
11889
0
}
11890
11891
/**
11892
 * Parse an external general entity within an existing parsing context
11893
 * An external general parsed entity is well-formed if it matches the
11894
 * production labeled extParsedEnt.
11895
 *
11896
 *     [78] extParsedEnt ::= TextDecl? content
11897
 *
11898
 * @param ctxt  the existing parsing context
11899
 * @param URL  the URL for the entity to load
11900
 * @param ID  the System ID for the entity to load
11901
 * @param listOut  the return value for the set of parsed nodes
11902
 * @returns 0 if the entity is well formed, -1 in case of args problem and
11903
 *    the parser error code otherwise
11904
 */
11905
11906
int
11907
xmlParseCtxtExternalEntity(xmlParserCtxt *ctxt, const xmlChar *URL,
11908
0
                           const xmlChar *ID, xmlNode **listOut) {
11909
0
    xmlParserInputPtr input;
11910
0
    xmlNodePtr list;
11911
11912
0
    if (listOut != NULL)
11913
0
        *listOut = NULL;
11914
11915
0
    if (ctxt == NULL)
11916
0
        return(XML_ERR_ARGUMENT);
11917
11918
0
    input = xmlLoadResource(ctxt, (char *) URL, (char *) ID,
11919
0
                            XML_RESOURCE_GENERAL_ENTITY);
11920
0
    if (input == NULL)
11921
0
        return(ctxt->errNo);
11922
11923
0
    xmlCtxtInitializeLate(ctxt);
11924
11925
0
    list = xmlCtxtParseContentInternal(ctxt, input, /* hasTextDecl */ 1, 1);
11926
0
    if (listOut != NULL)
11927
0
        *listOut = list;
11928
0
    else
11929
0
        xmlFreeNodeList(list);
11930
11931
0
    xmlFreeInputStream(input);
11932
0
    return(ctxt->errNo);
11933
0
}
11934
11935
#ifdef LIBXML_SAX1_ENABLED
11936
/**
11937
 * Parse an external general entity
11938
 * An external general parsed entity is well-formed if it matches the
11939
 * production labeled extParsedEnt.
11940
 *
11941
 * @deprecated Use #xmlParseCtxtExternalEntity.
11942
 *
11943
 *     [78] extParsedEnt ::= TextDecl? content
11944
 *
11945
 * @param doc  the document the chunk pertains to
11946
 * @param sax  the SAX handler block (possibly NULL)
11947
 * @param user_data  The user data returned on SAX callbacks (possibly NULL)
11948
 * @param depth  Used for loop detection, use 0
11949
 * @param URL  the URL for the entity to load
11950
 * @param ID  the System ID for the entity to load
11951
 * @param list  the return value for the set of parsed nodes
11952
 * @returns 0 if the entity is well formed, -1 in case of args problem and
11953
 *    the parser error code otherwise
11954
 */
11955
11956
int
11957
xmlParseExternalEntity(xmlDoc *doc, xmlSAXHandler *sax, void *user_data,
11958
0
    int depth, const xmlChar *URL, const xmlChar *ID, xmlNode **list) {
11959
0
    xmlParserCtxtPtr ctxt;
11960
0
    int ret;
11961
11962
0
    if (list != NULL)
11963
0
        *list = NULL;
11964
11965
0
    if (doc == NULL)
11966
0
        return(XML_ERR_ARGUMENT);
11967
11968
0
    ctxt = xmlNewSAXParserCtxt(sax, user_data);
11969
0
    if (ctxt == NULL)
11970
0
        return(XML_ERR_NO_MEMORY);
11971
11972
0
    ctxt->depth = depth;
11973
0
    ctxt->myDoc = doc;
11974
0
    ret = xmlParseCtxtExternalEntity(ctxt, URL, ID, list);
11975
11976
0
    xmlFreeParserCtxt(ctxt);
11977
0
    return(ret);
11978
0
}
11979
11980
/**
11981
 * Parse a well-balanced chunk of an XML document
11982
 * called by the parser
11983
 * The allowed sequence for the Well Balanced Chunk is the one defined by
11984
 * the content production in the XML grammar:
11985
 *
11986
 *     [43] content ::= (element | CharData | Reference | CDSect | PI |
11987
 *                       Comment)*
11988
 *
11989
 * @param doc  the document the chunk pertains to (must not be NULL)
11990
 * @param sax  the SAX handler block (possibly NULL)
11991
 * @param user_data  The user data returned on SAX callbacks (possibly NULL)
11992
 * @param depth  Used for loop detection, use 0
11993
 * @param string  the input string in UTF8 or ISO-Latin (zero terminated)
11994
 * @param lst  the return value for the set of parsed nodes
11995
 * @returns 0 if the chunk is well balanced, -1 in case of args problem and
11996
 *    the parser error code otherwise
11997
 */
11998
11999
int
12000
xmlParseBalancedChunkMemory(xmlDoc *doc, xmlSAXHandler *sax,
12001
0
     void *user_data, int depth, const xmlChar *string, xmlNode **lst) {
12002
0
    return xmlParseBalancedChunkMemoryRecover( doc, sax, user_data,
12003
0
                                                depth, string, lst, 0 );
12004
0
}
12005
#endif /* LIBXML_SAX1_ENABLED */
12006
12007
/**
12008
 * Parse a well-balanced chunk of XML matching the 'content' production.
12009
 *
12010
 * Namespaces in scope of `node` and entities of `node`'s document are
12011
 * recognized. When validating, the DTD of `node`'s document is used.
12012
 *
12013
 * Always consumes `input` even in error case.
12014
 *
12015
 * @since 2.14.0
12016
 *
12017
 * @param ctxt  parser context
12018
 * @param input  parser input
12019
 * @param node  target node or document
12020
 * @param hasTextDecl  whether to parse text declaration
12021
 * @returns a node list or NULL in case of error.
12022
 */
12023
xmlNode *
12024
xmlCtxtParseContent(xmlParserCtxt *ctxt, xmlParserInput *input,
12025
0
                    xmlNode *node, int hasTextDecl) {
12026
0
    xmlDocPtr doc;
12027
0
    xmlNodePtr cur, list = NULL;
12028
0
    int nsnr = 0;
12029
0
    xmlDictPtr oldDict;
12030
0
    int oldOptions, oldDictNames, oldLoadSubset;
12031
12032
0
    if ((ctxt == NULL) || (input == NULL) || (node == NULL)) {
12033
0
        xmlFatalErr(ctxt, XML_ERR_ARGUMENT, NULL);
12034
0
        goto exit;
12035
0
    }
12036
12037
0
    doc = node->doc;
12038
0
    if (doc == NULL) {
12039
0
        xmlFatalErr(ctxt, XML_ERR_ARGUMENT, NULL);
12040
0
        goto exit;
12041
0
    }
12042
12043
0
    switch (node->type) {
12044
0
        case XML_ELEMENT_NODE:
12045
0
        case XML_DOCUMENT_NODE:
12046
0
        case XML_HTML_DOCUMENT_NODE:
12047
0
            break;
12048
12049
0
        case XML_ATTRIBUTE_NODE:
12050
0
        case XML_TEXT_NODE:
12051
0
        case XML_CDATA_SECTION_NODE:
12052
0
        case XML_ENTITY_REF_NODE:
12053
0
        case XML_PI_NODE:
12054
0
        case XML_COMMENT_NODE:
12055
0
            for (cur = node->parent; cur != NULL; cur = node->parent) {
12056
0
                if ((cur->type == XML_ELEMENT_NODE) ||
12057
0
                    (cur->type == XML_DOCUMENT_NODE) ||
12058
0
                    (cur->type == XML_HTML_DOCUMENT_NODE)) {
12059
0
                    node = cur;
12060
0
                    break;
12061
0
                }
12062
0
            }
12063
0
            break;
12064
12065
0
        default:
12066
0
            xmlFatalErr(ctxt, XML_ERR_ARGUMENT, NULL);
12067
0
            goto exit;
12068
0
    }
12069
12070
0
    xmlCtxtReset(ctxt);
12071
12072
0
    oldDict = ctxt->dict;
12073
0
    oldOptions = ctxt->options;
12074
0
    oldDictNames = ctxt->dictNames;
12075
0
    oldLoadSubset = ctxt->loadsubset;
12076
12077
    /*
12078
     * Use input doc's dict if present, else assure XML_PARSE_NODICT is set.
12079
     */
12080
0
    if (doc->dict != NULL) {
12081
0
        ctxt->dict = doc->dict;
12082
0
    } else {
12083
0
        ctxt->options |= XML_PARSE_NODICT;
12084
0
        ctxt->dictNames = 0;
12085
0
    }
12086
12087
    /*
12088
     * Disable IDs
12089
     */
12090
0
    ctxt->loadsubset |= XML_SKIP_IDS;
12091
0
    ctxt->options |= XML_PARSE_SKIP_IDS;
12092
12093
0
    ctxt->myDoc = doc;
12094
12095
0
#ifdef LIBXML_HTML_ENABLED
12096
0
    if (ctxt->html) {
12097
        /*
12098
         * When parsing in context, it makes no sense to add implied
12099
         * elements like html/body/etc...
12100
         */
12101
0
        ctxt->options |= HTML_PARSE_NOIMPLIED;
12102
12103
0
        list = htmlCtxtParseContentInternal(ctxt, input);
12104
0
    } else
12105
0
#endif
12106
0
    {
12107
0
        xmlCtxtInitializeLate(ctxt);
12108
12109
        /*
12110
         * initialize the SAX2 namespaces stack
12111
         */
12112
0
        cur = node;
12113
0
        while ((cur != NULL) && (cur->type == XML_ELEMENT_NODE)) {
12114
0
            xmlNsPtr ns = cur->nsDef;
12115
0
            xmlHashedString hprefix, huri;
12116
12117
0
            while (ns != NULL) {
12118
0
                hprefix = xmlDictLookupHashed(ctxt->dict, ns->prefix, -1);
12119
0
                huri = xmlDictLookupHashed(ctxt->dict, ns->href, -1);
12120
0
                if (xmlParserNsPush(ctxt, &hprefix, &huri, ns, 1) > 0)
12121
0
                    nsnr++;
12122
0
                ns = ns->next;
12123
0
            }
12124
0
            cur = cur->parent;
12125
0
        }
12126
12127
0
        list = xmlCtxtParseContentInternal(ctxt, input, hasTextDecl, 1);
12128
12129
0
        if (nsnr > 0)
12130
0
            xmlParserNsPop(ctxt, nsnr);
12131
0
    }
12132
12133
0
    ctxt->dict = oldDict;
12134
0
    ctxt->options = oldOptions;
12135
0
    ctxt->dictNames = oldDictNames;
12136
0
    ctxt->loadsubset = oldLoadSubset;
12137
0
    ctxt->myDoc = NULL;
12138
0
    ctxt->node = NULL;
12139
12140
0
exit:
12141
0
    xmlFreeInputStream(input);
12142
0
    return(list);
12143
0
}
12144
12145
/**
12146
 * Parse a well-balanced chunk of an XML document
12147
 * within the context (DTD, namespaces, etc ...) of the given node.
12148
 *
12149
 * The allowed sequence for the data is a Well Balanced Chunk defined by
12150
 * the content production in the XML grammar:
12151
 *
12152
 *     [43] content ::= (element | CharData | Reference | CDSect | PI |
12153
 *                       Comment)*
12154
 *
12155
 * This function assumes the encoding of `node`'s document which is
12156
 * typically not what you want. A better alternative is
12157
 * #xmlCtxtParseContent.
12158
 *
12159
 * @param node  the context node
12160
 * @param data  the input string
12161
 * @param datalen  the input string length in bytes
12162
 * @param options  a combination of xmlParserOption
12163
 * @param listOut  the return value for the set of parsed nodes
12164
 * @returns XML_ERR_OK if the chunk is well balanced, and the parser
12165
 * error code otherwise
12166
 */
12167
xmlParserErrors
12168
xmlParseInNodeContext(xmlNode *node, const char *data, int datalen,
12169
0
                      int options, xmlNode **listOut) {
12170
0
    xmlParserCtxtPtr ctxt;
12171
0
    xmlParserInputPtr input;
12172
0
    xmlDocPtr doc;
12173
0
    xmlNodePtr list;
12174
0
    xmlParserErrors ret;
12175
12176
0
    if (listOut == NULL)
12177
0
        return(XML_ERR_INTERNAL_ERROR);
12178
0
    *listOut = NULL;
12179
12180
0
    if ((node == NULL) || (data == NULL) || (datalen < 0))
12181
0
        return(XML_ERR_INTERNAL_ERROR);
12182
12183
0
    doc = node->doc;
12184
0
    if (doc == NULL)
12185
0
        return(XML_ERR_INTERNAL_ERROR);
12186
12187
0
#ifdef LIBXML_HTML_ENABLED
12188
0
    if (doc->type == XML_HTML_DOCUMENT_NODE) {
12189
0
        ctxt = htmlNewParserCtxt();
12190
0
    }
12191
0
    else
12192
0
#endif
12193
0
        ctxt = xmlNewParserCtxt();
12194
12195
0
    if (ctxt == NULL)
12196
0
        return(XML_ERR_NO_MEMORY);
12197
12198
0
    input = xmlCtxtNewInputFromMemory(ctxt, NULL, data, datalen,
12199
0
                                      (const char *) doc->encoding,
12200
0
                                      XML_INPUT_BUF_STATIC);
12201
0
    if (input == NULL) {
12202
0
        xmlFreeParserCtxt(ctxt);
12203
0
        return(XML_ERR_NO_MEMORY);
12204
0
    }
12205
12206
0
    xmlCtxtUseOptions(ctxt, options);
12207
12208
0
    list = xmlCtxtParseContent(ctxt, input, node, /* hasTextDecl */ 0);
12209
12210
0
    if (list == NULL) {
12211
0
        ret = ctxt->errNo;
12212
0
        if (ret == XML_ERR_ARGUMENT)
12213
0
            ret = XML_ERR_INTERNAL_ERROR;
12214
0
    } else {
12215
0
        ret = XML_ERR_OK;
12216
0
        *listOut = list;
12217
0
    }
12218
12219
0
    xmlFreeParserCtxt(ctxt);
12220
12221
0
    return(ret);
12222
0
}
12223
12224
#ifdef LIBXML_SAX1_ENABLED
12225
/**
12226
 * Parse a well-balanced chunk of an XML document
12227
 *
12228
 * The allowed sequence for the Well Balanced Chunk is the one defined by
12229
 * the content production in the XML grammar:
12230
 *
12231
 *     [43] content ::= (element | CharData | Reference | CDSect | PI |
12232
 *                       Comment)*
12233
 *
12234
 * In case recover is set to 1, the nodelist will not be empty even if
12235
 * the parsed chunk is not well balanced, assuming the parsing succeeded to
12236
 * some extent.
12237
 *
12238
 * @param doc  the document the chunk pertains to (must not be NULL)
12239
 * @param sax  the SAX handler block (possibly NULL)
12240
 * @param user_data  The user data returned on SAX callbacks (possibly NULL)
12241
 * @param depth  Used for loop detection, use 0
12242
 * @param string  the input string in UTF8 or ISO-Latin (zero terminated)
12243
 * @param listOut  the return value for the set of parsed nodes
12244
 * @param recover  return nodes even if the data is broken (use 0)
12245
 * @returns 0 if the chunk is well balanced, or thehe parser error code
12246
 * otherwise.
12247
 */
12248
int
12249
xmlParseBalancedChunkMemoryRecover(xmlDoc *doc, xmlSAXHandler *sax,
12250
     void *user_data, int depth, const xmlChar *string, xmlNode **listOut,
12251
0
     int recover) {
12252
0
    xmlParserCtxtPtr ctxt;
12253
0
    xmlParserInputPtr input;
12254
0
    xmlNodePtr list;
12255
0
    int ret;
12256
12257
0
    if (listOut != NULL)
12258
0
        *listOut = NULL;
12259
12260
0
    if (string == NULL)
12261
0
        return(XML_ERR_ARGUMENT);
12262
12263
0
    ctxt = xmlNewSAXParserCtxt(sax, user_data);
12264
0
    if (ctxt == NULL)
12265
0
        return(XML_ERR_NO_MEMORY);
12266
12267
0
    xmlCtxtInitializeLate(ctxt);
12268
12269
0
    ctxt->depth = depth;
12270
0
    ctxt->myDoc = doc;
12271
0
    if (recover) {
12272
0
        ctxt->options |= XML_PARSE_RECOVER;
12273
0
        ctxt->recovery = 1;
12274
0
    }
12275
12276
0
    input = xmlNewStringInputStream(ctxt, string);
12277
0
    if (input == NULL) {
12278
0
        ret = ctxt->errNo;
12279
0
        goto error;
12280
0
    }
12281
12282
0
    list = xmlCtxtParseContentInternal(ctxt, input, /* hasTextDecl */ 0, 1);
12283
0
    if (listOut != NULL)
12284
0
        *listOut = list;
12285
0
    else
12286
0
        xmlFreeNodeList(list);
12287
12288
0
    if (!ctxt->wellFormed)
12289
0
        ret = ctxt->errNo;
12290
0
    else
12291
0
        ret = XML_ERR_OK;
12292
12293
0
error:
12294
0
    xmlFreeInputStream(input);
12295
0
    xmlFreeParserCtxt(ctxt);
12296
0
    return(ret);
12297
0
}
12298
12299
/**
12300
 * parse an XML external entity out of context and build a tree.
12301
 * It use the given SAX function block to handle the parsing callback.
12302
 * If sax is NULL, fallback to the default DOM tree building routines.
12303
 *
12304
 * @deprecated Don't use.
12305
 *
12306
 *     [78] extParsedEnt ::= TextDecl? content
12307
 *
12308
 * This correspond to a "Well Balanced" chunk
12309
 *
12310
 * @param sax  the SAX handler block
12311
 * @param filename  the filename
12312
 * @returns the resulting document tree
12313
 */
12314
12315
xmlDoc *
12316
0
xmlSAXParseEntity(xmlSAXHandler *sax, const char *filename) {
12317
0
    xmlDocPtr ret;
12318
0
    xmlParserCtxtPtr ctxt;
12319
12320
0
    ctxt = xmlCreateFileParserCtxt(filename);
12321
0
    if (ctxt == NULL) {
12322
0
  return(NULL);
12323
0
    }
12324
0
    if (sax != NULL) {
12325
0
        if (sax->initialized == XML_SAX2_MAGIC) {
12326
0
            *ctxt->sax = *sax;
12327
0
        } else {
12328
0
            memset(ctxt->sax, 0, sizeof(*ctxt->sax));
12329
0
            memcpy(ctxt->sax, sax, sizeof(xmlSAXHandlerV1));
12330
0
        }
12331
0
        ctxt->userData = NULL;
12332
0
    }
12333
12334
0
    xmlParseExtParsedEnt(ctxt);
12335
12336
0
    if (ctxt->wellFormed) {
12337
0
  ret = ctxt->myDoc;
12338
0
    } else {
12339
0
        ret = NULL;
12340
0
        xmlFreeDoc(ctxt->myDoc);
12341
0
    }
12342
12343
0
    xmlFreeParserCtxt(ctxt);
12344
12345
0
    return(ret);
12346
0
}
12347
12348
/**
12349
 * parse an XML external entity out of context and build a tree.
12350
 *
12351
 *     [78] extParsedEnt ::= TextDecl? content
12352
 *
12353
 * This correspond to a "Well Balanced" chunk
12354
 *
12355
 * @param filename  the filename
12356
 * @returns the resulting document tree
12357
 */
12358
12359
xmlDoc *
12360
0
xmlParseEntity(const char *filename) {
12361
0
    return(xmlSAXParseEntity(NULL, filename));
12362
0
}
12363
#endif /* LIBXML_SAX1_ENABLED */
12364
12365
/**
12366
 * Create a parser context for an external entity
12367
 * Automatic support for ZLIB/Compress compressed document is provided
12368
 * by default if found at compile-time.
12369
 *
12370
 * @deprecated Don't use.
12371
 *
12372
 * @param URL  the entity URL
12373
 * @param ID  the entity PUBLIC ID
12374
 * @param base  a possible base for the target URI
12375
 * @returns the new parser context or NULL
12376
 */
12377
xmlParserCtxt *
12378
xmlCreateEntityParserCtxt(const xmlChar *URL, const xmlChar *ID,
12379
0
                    const xmlChar *base) {
12380
0
    xmlParserCtxtPtr ctxt;
12381
0
    xmlParserInputPtr input;
12382
0
    xmlChar *uri = NULL;
12383
12384
0
    ctxt = xmlNewParserCtxt();
12385
0
    if (ctxt == NULL)
12386
0
  return(NULL);
12387
12388
0
    if (base != NULL) {
12389
0
        if (xmlBuildURISafe(URL, base, &uri) < 0)
12390
0
            goto error;
12391
0
        if (uri != NULL)
12392
0
            URL = uri;
12393
0
    }
12394
12395
0
    input = xmlLoadResource(ctxt, (char *) URL, (char *) ID,
12396
0
                            XML_RESOURCE_UNKNOWN);
12397
0
    if (input == NULL)
12398
0
        goto error;
12399
12400
0
    if (xmlCtxtPushInput(ctxt, input) < 0) {
12401
0
        xmlFreeInputStream(input);
12402
0
        goto error;
12403
0
    }
12404
12405
0
    xmlFree(uri);
12406
0
    return(ctxt);
12407
12408
0
error:
12409
0
    xmlFree(uri);
12410
0
    xmlFreeParserCtxt(ctxt);
12411
0
    return(NULL);
12412
0
}
12413
12414
/************************************************************************
12415
 *                  *
12416
 *    Front ends when parsing from a file     *
12417
 *                  *
12418
 ************************************************************************/
12419
12420
/**
12421
 * Create a parser context for a file or URL content.
12422
 * Automatic support for ZLIB/Compress compressed document is provided
12423
 * by default if found at compile-time and for file accesses
12424
 *
12425
 * @deprecated Use #xmlNewParserCtxt and #xmlCtxtReadFile.
12426
 *
12427
 * @param filename  the filename or URL
12428
 * @param options  a combination of xmlParserOption
12429
 * @returns the new parser context or NULL
12430
 */
12431
xmlParserCtxt *
12432
xmlCreateURLParserCtxt(const char *filename, int options)
12433
0
{
12434
0
    xmlParserCtxtPtr ctxt;
12435
0
    xmlParserInputPtr input;
12436
12437
0
    ctxt = xmlNewParserCtxt();
12438
0
    if (ctxt == NULL)
12439
0
  return(NULL);
12440
12441
0
    options |= XML_PARSE_UNZIP;
12442
12443
0
    xmlCtxtUseOptions(ctxt, options);
12444
12445
0
    input = xmlLoadResource(ctxt, filename, NULL, XML_RESOURCE_MAIN_DOCUMENT);
12446
0
    if (input == NULL) {
12447
0
  xmlFreeParserCtxt(ctxt);
12448
0
  return(NULL);
12449
0
    }
12450
0
    if (xmlCtxtPushInput(ctxt, input) < 0) {
12451
0
        xmlFreeInputStream(input);
12452
0
        xmlFreeParserCtxt(ctxt);
12453
0
        return(NULL);
12454
0
    }
12455
12456
0
    return(ctxt);
12457
0
}
12458
12459
/**
12460
 * Create a parser context for a file content.
12461
 * Automatic support for ZLIB/Compress compressed document is provided
12462
 * by default if found at compile-time.
12463
 *
12464
 * @deprecated Use #xmlNewParserCtxt and #xmlCtxtReadFile.
12465
 *
12466
 * @param filename  the filename
12467
 * @returns the new parser context or NULL
12468
 */
12469
xmlParserCtxt *
12470
xmlCreateFileParserCtxt(const char *filename)
12471
0
{
12472
0
    return(xmlCreateURLParserCtxt(filename, 0));
12473
0
}
12474
12475
#ifdef LIBXML_SAX1_ENABLED
12476
/**
12477
 * parse an XML file and build a tree. Automatic support for ZLIB/Compress
12478
 * compressed document is provided by default if found at compile-time.
12479
 * It use the given SAX function block to handle the parsing callback.
12480
 * If sax is NULL, fallback to the default DOM tree building routines.
12481
 *
12482
 * @deprecated Use #xmlNewSAXParserCtxt and #xmlCtxtReadFile.
12483
 *
12484
 * User data (void *) is stored within the parser context in the
12485
 * context's _private member, so it is available nearly everywhere in libxml
12486
 *
12487
 * @param sax  the SAX handler block
12488
 * @param filename  the filename
12489
 * @param recovery  work in recovery mode, i.e. tries to read no Well Formed
12490
 *             documents
12491
 * @param data  the userdata
12492
 * @returns the resulting document tree
12493
 */
12494
12495
xmlDoc *
12496
xmlSAXParseFileWithData(xmlSAXHandler *sax, const char *filename,
12497
0
                        int recovery, void *data) {
12498
0
    xmlDocPtr ret = NULL;
12499
0
    xmlParserCtxtPtr ctxt;
12500
0
    xmlParserInputPtr input;
12501
12502
0
    ctxt = xmlNewSAXParserCtxt(sax, NULL);
12503
0
    if (ctxt == NULL)
12504
0
  return(NULL);
12505
12506
0
    if (data != NULL)
12507
0
  ctxt->_private = data;
12508
12509
0
    if (recovery) {
12510
0
        ctxt->options |= XML_PARSE_RECOVER;
12511
0
        ctxt->recovery = 1;
12512
0
    }
12513
12514
0
    if ((filename != NULL) && (filename[0] == '-') && (filename[1] == 0))
12515
0
        input = xmlCtxtNewInputFromFd(ctxt, filename, STDIN_FILENO, NULL, 0);
12516
0
    else
12517
0
        input = xmlCtxtNewInputFromUrl(ctxt, filename, NULL, NULL, 0);
12518
12519
0
    if (input != NULL)
12520
0
        ret = xmlCtxtParseDocument(ctxt, input);
12521
12522
0
    xmlFreeParserCtxt(ctxt);
12523
0
    return(ret);
12524
0
}
12525
12526
/**
12527
 * parse an XML file and build a tree. Automatic support for ZLIB/Compress
12528
 * compressed document is provided by default if found at compile-time.
12529
 * It use the given SAX function block to handle the parsing callback.
12530
 * If sax is NULL, fallback to the default DOM tree building routines.
12531
 *
12532
 * @deprecated Use #xmlNewSAXParserCtxt and #xmlCtxtReadFile.
12533
 *
12534
 * @param sax  the SAX handler block
12535
 * @param filename  the filename
12536
 * @param recovery  work in recovery mode, i.e. tries to read no Well Formed
12537
 *             documents
12538
 * @returns the resulting document tree
12539
 */
12540
12541
xmlDoc *
12542
xmlSAXParseFile(xmlSAXHandler *sax, const char *filename,
12543
0
                          int recovery) {
12544
0
    return(xmlSAXParseFileWithData(sax,filename,recovery,NULL));
12545
0
}
12546
12547
/**
12548
 * parse an XML in-memory document and build a tree.
12549
 * In the case the document is not Well Formed, a attempt to build a
12550
 * tree is tried anyway
12551
 *
12552
 * @deprecated Use #xmlReadDoc with XML_PARSE_RECOVER.
12553
 *
12554
 * @param cur  a pointer to an array of xmlChar
12555
 * @returns the resulting document tree or NULL in case of failure
12556
 */
12557
12558
xmlDoc *
12559
0
xmlRecoverDoc(const xmlChar *cur) {
12560
0
    return(xmlSAXParseDoc(NULL, cur, 1));
12561
0
}
12562
12563
/**
12564
 * parse an XML file and build a tree. Automatic support for ZLIB/Compress
12565
 * compressed document is provided by default if found at compile-time.
12566
 *
12567
 * @deprecated Use #xmlReadFile.
12568
 *
12569
 * @param filename  the filename
12570
 * @returns the resulting document tree if the file was wellformed,
12571
 * NULL otherwise.
12572
 */
12573
12574
xmlDoc *
12575
0
xmlParseFile(const char *filename) {
12576
0
    return(xmlSAXParseFile(NULL, filename, 0));
12577
0
}
12578
12579
/**
12580
 * parse an XML file and build a tree. Automatic support for ZLIB/Compress
12581
 * compressed document is provided by default if found at compile-time.
12582
 * In the case the document is not Well Formed, it attempts to build
12583
 * a tree anyway
12584
 *
12585
 * @deprecated Use #xmlReadFile with XML_PARSE_RECOVER.
12586
 *
12587
 * @param filename  the filename
12588
 * @returns the resulting document tree or NULL in case of failure
12589
 */
12590
12591
xmlDoc *
12592
0
xmlRecoverFile(const char *filename) {
12593
0
    return(xmlSAXParseFile(NULL, filename, 1));
12594
0
}
12595
12596
12597
/**
12598
 * Setup the parser context to parse a new buffer; Clears any prior
12599
 * contents from the parser context. The buffer parameter must not be
12600
 * NULL, but the filename parameter can be
12601
 *
12602
 * @deprecated Don't use.
12603
 *
12604
 * @param ctxt  an XML parser context
12605
 * @param buffer  a xmlChar * buffer
12606
 * @param filename  a file name
12607
 */
12608
void
12609
xmlSetupParserForBuffer(xmlParserCtxt *ctxt, const xmlChar* buffer,
12610
                             const char* filename)
12611
0
{
12612
0
    xmlParserInputPtr input;
12613
12614
0
    if ((ctxt == NULL) || (buffer == NULL))
12615
0
        return;
12616
12617
0
    xmlCtxtReset(ctxt);
12618
12619
0
    input = xmlCtxtNewInputFromString(ctxt, filename, (const char *) buffer,
12620
0
                                      NULL, 0);
12621
0
    if (input == NULL)
12622
0
        return;
12623
0
    if (xmlCtxtPushInput(ctxt, input) < 0)
12624
0
        xmlFreeInputStream(input);
12625
0
}
12626
12627
/**
12628
 * parse an XML file and call the given SAX handler routines.
12629
 * Automatic support for ZLIB/Compress compressed document is provided
12630
 *
12631
 * @deprecated Use #xmlNewSAXParserCtxt and #xmlCtxtReadFile.
12632
 *
12633
 * @param sax  a SAX handler
12634
 * @param user_data  The user data returned on SAX callbacks
12635
 * @param filename  a file name
12636
 * @returns 0 in case of success or a error number otherwise
12637
 */
12638
int
12639
xmlSAXUserParseFile(xmlSAXHandler *sax, void *user_data,
12640
0
                    const char *filename) {
12641
0
    int ret = 0;
12642
0
    xmlParserCtxtPtr ctxt;
12643
12644
0
    ctxt = xmlCreateFileParserCtxt(filename);
12645
0
    if (ctxt == NULL) return -1;
12646
0
    if (sax != NULL) {
12647
0
        if (sax->initialized == XML_SAX2_MAGIC) {
12648
0
            *ctxt->sax = *sax;
12649
0
        } else {
12650
0
            memset(ctxt->sax, 0, sizeof(*ctxt->sax));
12651
0
            memcpy(ctxt->sax, sax, sizeof(xmlSAXHandlerV1));
12652
0
        }
12653
0
  ctxt->userData = user_data;
12654
0
    }
12655
12656
0
    xmlParseDocument(ctxt);
12657
12658
0
    if (ctxt->wellFormed)
12659
0
  ret = 0;
12660
0
    else {
12661
0
        if (ctxt->errNo != 0)
12662
0
      ret = ctxt->errNo;
12663
0
  else
12664
0
      ret = -1;
12665
0
    }
12666
0
    if (ctxt->myDoc != NULL) {
12667
0
        xmlFreeDoc(ctxt->myDoc);
12668
0
  ctxt->myDoc = NULL;
12669
0
    }
12670
0
    xmlFreeParserCtxt(ctxt);
12671
12672
0
    return ret;
12673
0
}
12674
#endif /* LIBXML_SAX1_ENABLED */
12675
12676
/************************************************************************
12677
 *                  *
12678
 *    Front ends when parsing from memory     *
12679
 *                  *
12680
 ************************************************************************/
12681
12682
/**
12683
 * Create a parser context for an XML in-memory document. The input buffer
12684
 * must not contain a terminating null byte.
12685
 *
12686
 * @param buffer  a pointer to a char array
12687
 * @param size  the size of the array
12688
 * @returns the new parser context or NULL
12689
 */
12690
xmlParserCtxt *
12691
0
xmlCreateMemoryParserCtxt(const char *buffer, int size) {
12692
0
    xmlParserCtxtPtr ctxt;
12693
0
    xmlParserInputPtr input;
12694
12695
0
    if (size < 0)
12696
0
  return(NULL);
12697
12698
0
    ctxt = xmlNewParserCtxt();
12699
0
    if (ctxt == NULL)
12700
0
  return(NULL);
12701
12702
0
    input = xmlCtxtNewInputFromMemory(ctxt, NULL, buffer, size, NULL, 0);
12703
0
    if (input == NULL) {
12704
0
  xmlFreeParserCtxt(ctxt);
12705
0
  return(NULL);
12706
0
    }
12707
0
    if (xmlCtxtPushInput(ctxt, input) < 0) {
12708
0
        xmlFreeInputStream(input);
12709
0
        xmlFreeParserCtxt(ctxt);
12710
0
        return(NULL);
12711
0
    }
12712
12713
0
    return(ctxt);
12714
0
}
12715
12716
#ifdef LIBXML_SAX1_ENABLED
12717
/**
12718
 * parse an XML in-memory block and use the given SAX function block
12719
 * to handle the parsing callback. If sax is NULL, fallback to the default
12720
 * DOM tree building routines.
12721
 *
12722
 * @deprecated Use #xmlNewSAXParserCtxt and #xmlCtxtReadMemory.
12723
 *
12724
 * User data (void *) is stored within the parser context in the
12725
 * context's _private member, so it is available nearly everywhere in libxml
12726
 *
12727
 * @param sax  the SAX handler block
12728
 * @param buffer  an pointer to a char array
12729
 * @param size  the size of the array
12730
 * @param recovery  work in recovery mode, i.e. tries to read no Well Formed
12731
 *             documents
12732
 * @param data  the userdata
12733
 * @returns the resulting document tree
12734
 */
12735
12736
xmlDoc *
12737
xmlSAXParseMemoryWithData(xmlSAXHandler *sax, const char *buffer,
12738
0
                          int size, int recovery, void *data) {
12739
0
    xmlDocPtr ret = NULL;
12740
0
    xmlParserCtxtPtr ctxt;
12741
0
    xmlParserInputPtr input;
12742
12743
0
    if (size < 0)
12744
0
        return(NULL);
12745
12746
0
    ctxt = xmlNewSAXParserCtxt(sax, NULL);
12747
0
    if (ctxt == NULL)
12748
0
        return(NULL);
12749
12750
0
    if (data != NULL)
12751
0
  ctxt->_private=data;
12752
12753
0
    if (recovery) {
12754
0
        ctxt->options |= XML_PARSE_RECOVER;
12755
0
        ctxt->recovery = 1;
12756
0
    }
12757
12758
0
    input = xmlCtxtNewInputFromMemory(ctxt, NULL, buffer, size, NULL,
12759
0
                                      XML_INPUT_BUF_STATIC);
12760
12761
0
    if (input != NULL)
12762
0
        ret = xmlCtxtParseDocument(ctxt, input);
12763
12764
0
    xmlFreeParserCtxt(ctxt);
12765
0
    return(ret);
12766
0
}
12767
12768
/**
12769
 * parse an XML in-memory block and use the given SAX function block
12770
 * to handle the parsing callback. If sax is NULL, fallback to the default
12771
 * DOM tree building routines.
12772
 *
12773
 * @deprecated Use #xmlNewSAXParserCtxt and #xmlCtxtReadMemory.
12774
 *
12775
 * @param sax  the SAX handler block
12776
 * @param buffer  an pointer to a char array
12777
 * @param size  the size of the array
12778
 * @param recovery  work in recovery mode, i.e. tries to read not Well Formed
12779
 *             documents
12780
 * @returns the resulting document tree
12781
 */
12782
xmlDoc *
12783
xmlSAXParseMemory(xmlSAXHandler *sax, const char *buffer,
12784
0
            int size, int recovery) {
12785
0
    return xmlSAXParseMemoryWithData(sax, buffer, size, recovery, NULL);
12786
0
}
12787
12788
/**
12789
 * parse an XML in-memory block and build a tree.
12790
 *
12791
 * @deprecated Use #xmlReadMemory.
12792
 *
12793
 * @param buffer  an pointer to a char array
12794
 * @param size  the size of the array
12795
 * @returns the resulting document tree
12796
 */
12797
12798
0
xmlDoc *xmlParseMemory(const char *buffer, int size) {
12799
0
   return(xmlSAXParseMemory(NULL, buffer, size, 0));
12800
0
}
12801
12802
/**
12803
 * parse an XML in-memory block and build a tree.
12804
 * In the case the document is not Well Formed, an attempt to
12805
 * build a tree is tried anyway
12806
 *
12807
 * @deprecated Use #xmlReadMemory with XML_PARSE_RECOVER.
12808
 *
12809
 * @param buffer  an pointer to a char array
12810
 * @param size  the size of the array
12811
 * @returns the resulting document tree or NULL in case of error
12812
 */
12813
12814
0
xmlDoc *xmlRecoverMemory(const char *buffer, int size) {
12815
0
   return(xmlSAXParseMemory(NULL, buffer, size, 1));
12816
0
}
12817
12818
/**
12819
 * parse an XML in-memory buffer and call the given SAX handler routines.
12820
 *
12821
 * @deprecated Use #xmlNewSAXParserCtxt and #xmlCtxtReadMemory.
12822
 *
12823
 * @param sax  a SAX handler
12824
 * @param user_data  The user data returned on SAX callbacks
12825
 * @param buffer  an in-memory XML document input
12826
 * @param size  the length of the XML document in bytes
12827
 * @returns 0 in case of success or a error number otherwise
12828
 */
12829
int xmlSAXUserParseMemory(xmlSAXHandler *sax, void *user_data,
12830
0
        const char *buffer, int size) {
12831
0
    int ret = 0;
12832
0
    xmlParserCtxtPtr ctxt;
12833
12834
0
    ctxt = xmlCreateMemoryParserCtxt(buffer, size);
12835
0
    if (ctxt == NULL) return -1;
12836
0
    if (sax != NULL) {
12837
0
        if (sax->initialized == XML_SAX2_MAGIC) {
12838
0
            *ctxt->sax = *sax;
12839
0
        } else {
12840
0
            memset(ctxt->sax, 0, sizeof(*ctxt->sax));
12841
0
            memcpy(ctxt->sax, sax, sizeof(xmlSAXHandlerV1));
12842
0
        }
12843
0
  ctxt->userData = user_data;
12844
0
    }
12845
12846
0
    xmlParseDocument(ctxt);
12847
12848
0
    if (ctxt->wellFormed)
12849
0
  ret = 0;
12850
0
    else {
12851
0
        if (ctxt->errNo != 0)
12852
0
      ret = ctxt->errNo;
12853
0
  else
12854
0
      ret = -1;
12855
0
    }
12856
0
    if (ctxt->myDoc != NULL) {
12857
0
        xmlFreeDoc(ctxt->myDoc);
12858
0
  ctxt->myDoc = NULL;
12859
0
    }
12860
0
    xmlFreeParserCtxt(ctxt);
12861
12862
0
    return ret;
12863
0
}
12864
#endif /* LIBXML_SAX1_ENABLED */
12865
12866
/**
12867
 * Creates a parser context for an XML in-memory document.
12868
 *
12869
 * @param str  a pointer to an array of xmlChar
12870
 * @returns the new parser context or NULL
12871
 */
12872
xmlParserCtxt *
12873
0
xmlCreateDocParserCtxt(const xmlChar *str) {
12874
0
    xmlParserCtxtPtr ctxt;
12875
0
    xmlParserInputPtr input;
12876
12877
0
    ctxt = xmlNewParserCtxt();
12878
0
    if (ctxt == NULL)
12879
0
  return(NULL);
12880
12881
0
    input = xmlCtxtNewInputFromString(ctxt, NULL, (const char *) str, NULL, 0);
12882
0
    if (input == NULL) {
12883
0
  xmlFreeParserCtxt(ctxt);
12884
0
  return(NULL);
12885
0
    }
12886
0
    if (xmlCtxtPushInput(ctxt, input) < 0) {
12887
0
        xmlFreeInputStream(input);
12888
0
        xmlFreeParserCtxt(ctxt);
12889
0
        return(NULL);
12890
0
    }
12891
12892
0
    return(ctxt);
12893
0
}
12894
12895
#ifdef LIBXML_SAX1_ENABLED
12896
/**
12897
 * parse an XML in-memory document and build a tree.
12898
 * It use the given SAX function block to handle the parsing callback.
12899
 * If sax is NULL, fallback to the default DOM tree building routines.
12900
 *
12901
 * @deprecated Use #xmlNewSAXParserCtxt and #xmlCtxtReadDoc.
12902
 *
12903
 * @param sax  the SAX handler block
12904
 * @param cur  a pointer to an array of xmlChar
12905
 * @param recovery  work in recovery mode, i.e. tries to read no Well Formed
12906
 *             documents
12907
 * @returns the resulting document tree
12908
 */
12909
12910
xmlDoc *
12911
0
xmlSAXParseDoc(xmlSAXHandler *sax, const xmlChar *cur, int recovery) {
12912
0
    xmlDocPtr ret;
12913
0
    xmlParserCtxtPtr ctxt;
12914
0
    xmlSAXHandlerPtr oldsax = NULL;
12915
12916
0
    if (cur == NULL) return(NULL);
12917
12918
12919
0
    ctxt = xmlCreateDocParserCtxt(cur);
12920
0
    if (ctxt == NULL) return(NULL);
12921
0
    if (sax != NULL) {
12922
0
        oldsax = ctxt->sax;
12923
0
        ctxt->sax = sax;
12924
0
        ctxt->userData = NULL;
12925
0
    }
12926
12927
0
    xmlParseDocument(ctxt);
12928
0
    if ((ctxt->wellFormed) || recovery) ret = ctxt->myDoc;
12929
0
    else {
12930
0
       ret = NULL;
12931
0
       xmlFreeDoc(ctxt->myDoc);
12932
0
       ctxt->myDoc = NULL;
12933
0
    }
12934
0
    if (sax != NULL)
12935
0
  ctxt->sax = oldsax;
12936
0
    xmlFreeParserCtxt(ctxt);
12937
12938
0
    return(ret);
12939
0
}
12940
12941
/**
12942
 * parse an XML in-memory document and build a tree.
12943
 *
12944
 * @deprecated Use #xmlReadDoc.
12945
 *
12946
 * @param cur  a pointer to an array of xmlChar
12947
 * @returns the resulting document tree
12948
 */
12949
12950
xmlDoc *
12951
0
xmlParseDoc(const xmlChar *cur) {
12952
0
    return(xmlSAXParseDoc(NULL, cur, 0));
12953
0
}
12954
#endif /* LIBXML_SAX1_ENABLED */
12955
12956
/************************************************************************
12957
 *                  *
12958
 *  New set (2.6.0) of simpler and more flexible APIs   *
12959
 *                  *
12960
 ************************************************************************/
12961
12962
/**
12963
 * Reset a parser context
12964
 *
12965
 * @param ctxt  an XML parser context
12966
 */
12967
void
12968
xmlCtxtReset(xmlParserCtxt *ctxt)
12969
8.14k
{
12970
8.14k
    xmlParserInputPtr input;
12971
12972
8.14k
    if (ctxt == NULL)
12973
0
        return;
12974
12975
8.14k
    while ((input = xmlCtxtPopInput(ctxt)) != NULL) { /* Non consuming */
12976
0
        xmlFreeInputStream(input);
12977
0
    }
12978
8.14k
    ctxt->inputNr = 0;
12979
8.14k
    ctxt->input = NULL;
12980
12981
8.14k
    ctxt->spaceNr = 0;
12982
8.14k
    if (ctxt->spaceTab != NULL) {
12983
6.66k
  ctxt->spaceTab[0] = -1;
12984
6.66k
  ctxt->space = &ctxt->spaceTab[0];
12985
6.66k
    } else {
12986
1.47k
        ctxt->space = NULL;
12987
1.47k
    }
12988
12989
12990
8.14k
    ctxt->nodeNr = 0;
12991
8.14k
    ctxt->node = NULL;
12992
12993
8.14k
    ctxt->nameNr = 0;
12994
8.14k
    ctxt->name = NULL;
12995
12996
8.14k
    ctxt->nsNr = 0;
12997
8.14k
    xmlParserNsReset(ctxt->nsdb);
12998
12999
8.14k
    if (ctxt->version != NULL) {
13000
0
        xmlFree(ctxt->version);
13001
0
        ctxt->version = NULL;
13002
0
    }
13003
8.14k
    if (ctxt->encoding != NULL) {
13004
0
        xmlFree(ctxt->encoding);
13005
0
        ctxt->encoding = NULL;
13006
0
    }
13007
8.14k
    if (ctxt->extSubURI != NULL) {
13008
0
        xmlFree(ctxt->extSubURI);
13009
0
        ctxt->extSubURI = NULL;
13010
0
    }
13011
8.14k
    if (ctxt->extSubSystem != NULL) {
13012
0
        xmlFree(ctxt->extSubSystem);
13013
0
        ctxt->extSubSystem = NULL;
13014
0
    }
13015
8.14k
    if (ctxt->directory != NULL) {
13016
0
        xmlFree(ctxt->directory);
13017
0
        ctxt->directory = NULL;
13018
0
    }
13019
13020
8.14k
    if (ctxt->myDoc != NULL)
13021
0
        xmlFreeDoc(ctxt->myDoc);
13022
8.14k
    ctxt->myDoc = NULL;
13023
13024
8.14k
    ctxt->standalone = -1;
13025
8.14k
    ctxt->hasExternalSubset = 0;
13026
8.14k
    ctxt->hasPErefs = 0;
13027
8.14k
    ctxt->html = ctxt->html ? 1 : 0;
13028
8.14k
    ctxt->instate = XML_PARSER_START;
13029
13030
8.14k
    ctxt->wellFormed = 1;
13031
8.14k
    ctxt->nsWellFormed = 1;
13032
8.14k
    ctxt->disableSAX = 0;
13033
8.14k
    ctxt->valid = 1;
13034
8.14k
    ctxt->record_info = 0;
13035
8.14k
    ctxt->checkIndex = 0;
13036
8.14k
    ctxt->endCheckState = 0;
13037
8.14k
    ctxt->inSubset = 0;
13038
8.14k
    ctxt->errNo = XML_ERR_OK;
13039
8.14k
    ctxt->depth = 0;
13040
8.14k
    ctxt->catalogs = NULL;
13041
8.14k
    ctxt->sizeentities = 0;
13042
8.14k
    ctxt->sizeentcopy = 0;
13043
8.14k
    xmlInitNodeInfoSeq(&ctxt->node_seq);
13044
13045
8.14k
    if (ctxt->attsDefault != NULL) {
13046
0
        xmlHashFree(ctxt->attsDefault, xmlHashDefaultDeallocator);
13047
0
        ctxt->attsDefault = NULL;
13048
0
    }
13049
8.14k
    if (ctxt->attsSpecial != NULL) {
13050
0
        xmlHashFree(ctxt->attsSpecial, NULL);
13051
0
        ctxt->attsSpecial = NULL;
13052
0
    }
13053
13054
8.14k
#ifdef LIBXML_CATALOG_ENABLED
13055
8.14k
    if (ctxt->catalogs != NULL)
13056
0
  xmlCatalogFreeLocal(ctxt->catalogs);
13057
8.14k
#endif
13058
8.14k
    ctxt->nbErrors = 0;
13059
8.14k
    ctxt->nbWarnings = 0;
13060
8.14k
    if (ctxt->lastError.code != XML_ERR_OK)
13061
659
        xmlResetError(&ctxt->lastError);
13062
8.14k
}
13063
13064
/**
13065
 * Reset a push parser context
13066
 *
13067
 * @param ctxt  an XML parser context
13068
 * @param chunk  a pointer to an array of chars
13069
 * @param size  number of chars in the array
13070
 * @param filename  an optional file name or URI
13071
 * @param encoding  the document encoding, or NULL
13072
 * @returns 0 in case of success and 1 in case of error
13073
 */
13074
int
13075
xmlCtxtResetPush(xmlParserCtxt *ctxt, const char *chunk,
13076
                 int size, const char *filename, const char *encoding)
13077
0
{
13078
0
    xmlParserInputPtr input;
13079
13080
0
    if (ctxt == NULL)
13081
0
        return(1);
13082
13083
0
    xmlCtxtReset(ctxt);
13084
13085
0
    input = xmlNewPushInput(filename, chunk, size);
13086
0
    if (input == NULL)
13087
0
        return(1);
13088
13089
0
    if (xmlCtxtPushInput(ctxt, input) < 0) {
13090
0
        xmlFreeInputStream(input);
13091
0
        return(1);
13092
0
    }
13093
13094
0
    if (encoding != NULL)
13095
0
        xmlSwitchEncodingName(ctxt, encoding);
13096
13097
0
    return(0);
13098
0
}
13099
13100
static int
13101
xmlCtxtSetOptionsInternal(xmlParserCtxtPtr ctxt, int options, int keepMask)
13102
11.9k
{
13103
11.9k
    int allMask;
13104
13105
11.9k
    if (ctxt == NULL)
13106
184
        return(-1);
13107
13108
    /*
13109
     * XInclude options aren't handled by the parser.
13110
     *
13111
     * XML_PARSE_XINCLUDE
13112
     * XML_PARSE_NOXINCNODE
13113
     * XML_PARSE_NOBASEFIX
13114
     */
13115
11.7k
    allMask = XML_PARSE_RECOVER |
13116
11.7k
              XML_PARSE_NOENT |
13117
11.7k
              XML_PARSE_DTDLOAD |
13118
11.7k
              XML_PARSE_DTDATTR |
13119
11.7k
              XML_PARSE_DTDVALID |
13120
11.7k
              XML_PARSE_NOERROR |
13121
11.7k
              XML_PARSE_NOWARNING |
13122
11.7k
              XML_PARSE_PEDANTIC |
13123
11.7k
              XML_PARSE_NOBLANKS |
13124
11.7k
#ifdef LIBXML_SAX1_ENABLED
13125
11.7k
              XML_PARSE_SAX1 |
13126
11.7k
#endif
13127
11.7k
              XML_PARSE_NONET |
13128
11.7k
              XML_PARSE_NODICT |
13129
11.7k
              XML_PARSE_NSCLEAN |
13130
11.7k
              XML_PARSE_NOCDATA |
13131
11.7k
              XML_PARSE_COMPACT |
13132
11.7k
              XML_PARSE_OLD10 |
13133
11.7k
              XML_PARSE_HUGE |
13134
11.7k
              XML_PARSE_OLDSAX |
13135
11.7k
              XML_PARSE_IGNORE_ENC |
13136
11.7k
              XML_PARSE_BIG_LINES |
13137
11.7k
              XML_PARSE_NO_XXE |
13138
11.7k
              XML_PARSE_UNZIP |
13139
11.7k
              XML_PARSE_NO_SYS_CATALOG |
13140
11.7k
              XML_PARSE_CATALOG_PI;
13141
13142
11.7k
    ctxt->options = (ctxt->options & keepMask) | (options & allMask);
13143
13144
    /*
13145
     * For some options, struct members are historically the source
13146
     * of truth. The values are initalized from global variables and
13147
     * old code could also modify them directly. Several older API
13148
     * functions that don't take an options argument rely on these
13149
     * deprecated mechanisms.
13150
     *
13151
     * Once public access to struct members and the globals are
13152
     * disabled, we can use the options bitmask as source of
13153
     * truth, making all these struct members obsolete.
13154
     *
13155
     * The XML_DETECT_IDS flags is misnamed. It simply enables
13156
     * loading of the external subset.
13157
     */
13158
11.7k
    ctxt->recovery = (options & XML_PARSE_RECOVER) ? 1 : 0;
13159
11.7k
    ctxt->replaceEntities = (options & XML_PARSE_NOENT) ? 1 : 0;
13160
11.7k
    ctxt->loadsubset = (options & XML_PARSE_DTDLOAD) ? XML_DETECT_IDS : 0;
13161
11.7k
    ctxt->loadsubset |= (options & XML_PARSE_DTDATTR) ? XML_COMPLETE_ATTRS : 0;
13162
11.7k
    ctxt->loadsubset |= (options & XML_PARSE_SKIP_IDS) ? XML_SKIP_IDS : 0;
13163
11.7k
    ctxt->validate = (options & XML_PARSE_DTDVALID) ? 1 : 0;
13164
11.7k
    ctxt->pedantic = (options & XML_PARSE_PEDANTIC) ? 1 : 0;
13165
11.7k
    ctxt->keepBlanks = (options & XML_PARSE_NOBLANKS) ? 0 : 1;
13166
11.7k
    ctxt->dictNames = (options & XML_PARSE_NODICT) ? 0 : 1;
13167
13168
11.7k
    return(options & ~allMask);
13169
11.9k
}
13170
13171
/**
13172
 * Applies the options to the parser context. Unset options are
13173
 * cleared.
13174
 *
13175
 * @since 2.13.0
13176
 *
13177
 * With older versions, you can use #xmlCtxtUseOptions.
13178
 *
13179
 * @param ctxt  an XML parser context
13180
 * @param options  a bitmask of xmlParserOption values
13181
 * @returns 0 in case of success, the set of unknown or unimplemented options
13182
 *         in case of error.
13183
 */
13184
int
13185
xmlCtxtSetOptions(xmlParserCtxt *ctxt, int options)
13186
0
{
13187
0
#ifdef LIBXML_HTML_ENABLED
13188
0
    if ((ctxt != NULL) && (ctxt->html))
13189
0
        return(htmlCtxtSetOptions(ctxt, options));
13190
0
#endif
13191
13192
0
    return(xmlCtxtSetOptionsInternal(ctxt, options, 0));
13193
0
}
13194
13195
/**
13196
 * Get the current options of the parser context.
13197
 *
13198
 * @since 2.14.0
13199
 *
13200
 * @param ctxt  an XML parser context
13201
 * @returns the current options set in the parser context, or -1 if ctxt is NULL.
13202
 */
13203
int
13204
xmlCtxtGetOptions(xmlParserCtxt *ctxt)
13205
0
{
13206
0
    if (ctxt == NULL)
13207
0
        return(-1);
13208
13209
0
    return(ctxt->options);
13210
0
}
13211
13212
/**
13213
 * Applies the options to the parser context. The following options
13214
 * are never cleared and can only be enabled:
13215
 *
13216
 * - XML_PARSE_NOERROR
13217
 * - XML_PARSE_NOWARNING
13218
 * - XML_PARSE_NONET
13219
 * - XML_PARSE_NSCLEAN
13220
 * - XML_PARSE_NOCDATA
13221
 * - XML_PARSE_COMPACT
13222
 * - XML_PARSE_OLD10
13223
 * - XML_PARSE_HUGE
13224
 * - XML_PARSE_OLDSAX
13225
 * - XML_PARSE_IGNORE_ENC
13226
 * - XML_PARSE_BIG_LINES
13227
 *
13228
 * @deprecated Use #xmlCtxtSetOptions.
13229
 *
13230
 * @param ctxt  an XML parser context
13231
 * @param options  a combination of xmlParserOption
13232
 * @returns 0 in case of success, the set of unknown or unimplemented options
13233
 *         in case of error.
13234
 */
13235
int
13236
xmlCtxtUseOptions(xmlParserCtxt *ctxt, int options)
13237
11.9k
{
13238
11.9k
    int keepMask;
13239
13240
11.9k
#ifdef LIBXML_HTML_ENABLED
13241
11.9k
    if ((ctxt != NULL) && (ctxt->html))
13242
0
        return(htmlCtxtUseOptions(ctxt, options));
13243
11.9k
#endif
13244
13245
    /*
13246
     * For historic reasons, some options can only be enabled.
13247
     */
13248
11.9k
    keepMask = XML_PARSE_NOERROR |
13249
11.9k
               XML_PARSE_NOWARNING |
13250
11.9k
               XML_PARSE_NONET |
13251
11.9k
               XML_PARSE_NSCLEAN |
13252
11.9k
               XML_PARSE_NOCDATA |
13253
11.9k
               XML_PARSE_COMPACT |
13254
11.9k
               XML_PARSE_OLD10 |
13255
11.9k
               XML_PARSE_HUGE |
13256
11.9k
               XML_PARSE_OLDSAX |
13257
11.9k
               XML_PARSE_IGNORE_ENC |
13258
11.9k
               XML_PARSE_BIG_LINES;
13259
13260
11.9k
    return(xmlCtxtSetOptionsInternal(ctxt, options, keepMask));
13261
11.9k
}
13262
13263
/**
13264
 * To protect against exponential entity expansion ("billion laughs"), the
13265
 * size of serialized output is (roughly) limited to the input size
13266
 * multiplied by this factor. The default value is 5.
13267
 *
13268
 * When working with documents making heavy use of entity expansion, it can
13269
 * be necessary to increase the value. For security reasons, this should only
13270
 * be considered when processing trusted input.
13271
 *
13272
 * @param ctxt  an XML parser context
13273
 * @param maxAmpl  maximum amplification factor
13274
 */
13275
void
13276
xmlCtxtSetMaxAmplification(xmlParserCtxt *ctxt, unsigned maxAmpl)
13277
531
{
13278
531
    if (ctxt == NULL)
13279
0
        return;
13280
531
    ctxt->maxAmpl = maxAmpl;
13281
531
}
13282
13283
/**
13284
 * Parse an XML document and return the resulting document tree.
13285
 * Takes ownership of the input object.
13286
 *
13287
 * @since 2.13.0
13288
 *
13289
 * @param ctxt  an XML parser context
13290
 * @param input  parser input
13291
 * @returns the resulting document tree or NULL
13292
 */
13293
xmlDoc *
13294
xmlCtxtParseDocument(xmlParserCtxt *ctxt, xmlParserInput *input)
13295
0
{
13296
0
    xmlDocPtr ret = NULL;
13297
13298
0
    if ((ctxt == NULL) || (input == NULL)) {
13299
0
        xmlFatalErr(ctxt, XML_ERR_ARGUMENT, NULL);
13300
0
        xmlFreeInputStream(input);
13301
0
        return(NULL);
13302
0
    }
13303
13304
    /* assert(ctxt->inputNr == 0); */
13305
0
    while (ctxt->inputNr > 0)
13306
0
        xmlFreeInputStream(xmlCtxtPopInput(ctxt));
13307
13308
0
    if (xmlCtxtPushInput(ctxt, input) < 0) {
13309
0
        xmlFreeInputStream(input);
13310
0
        return(NULL);
13311
0
    }
13312
13313
0
    xmlParseDocument(ctxt);
13314
13315
0
    ret = xmlCtxtGetDocument(ctxt);
13316
13317
    /* assert(ctxt->inputNr == 1); */
13318
0
    while (ctxt->inputNr > 0)
13319
0
        xmlFreeInputStream(xmlCtxtPopInput(ctxt));
13320
13321
0
    return(ret);
13322
0
}
13323
13324
/**
13325
 * Convenience function to parse an XML document from a
13326
 * zero-terminated string.
13327
 *
13328
 * See #xmlCtxtReadDoc for details.
13329
 *
13330
 * @param cur  a pointer to a zero terminated string
13331
 * @param URL  base URL (optional)
13332
 * @param encoding  the document encoding (optional)
13333
 * @param options  a combination of xmlParserOption
13334
 * @returns the resulting document tree
13335
 */
13336
xmlDoc *
13337
xmlReadDoc(const xmlChar *cur, const char *URL, const char *encoding,
13338
           int options)
13339
0
{
13340
0
    xmlParserCtxtPtr ctxt;
13341
0
    xmlParserInputPtr input;
13342
0
    xmlDocPtr doc = NULL;
13343
13344
0
    ctxt = xmlNewParserCtxt();
13345
0
    if (ctxt == NULL)
13346
0
        return(NULL);
13347
13348
0
    xmlCtxtUseOptions(ctxt, options);
13349
13350
0
    input = xmlCtxtNewInputFromString(ctxt, URL, (const char *) cur, encoding,
13351
0
                                      XML_INPUT_BUF_STATIC);
13352
13353
0
    if (input != NULL)
13354
0
        doc = xmlCtxtParseDocument(ctxt, input);
13355
13356
0
    xmlFreeParserCtxt(ctxt);
13357
0
    return(doc);
13358
0
}
13359
13360
/**
13361
 * Convenience function to parse an XML file from the filesystem,
13362
 * the network or a global user-define resource loader.
13363
 *
13364
 * This function always enables the XML_PARSE_UNZIP option for
13365
 * backward compatibility. If a "-" filename is passed, it will
13366
 * read from stdin. Both of these features are potentially
13367
 * insecure and might be removed from later versions.
13368
 *
13369
 * See #xmlCtxtReadFile for details.
13370
 *
13371
 * @param filename  a file or URL
13372
 * @param encoding  the document encoding (optional)
13373
 * @param options  a combination of xmlParserOption
13374
 * @returns the resulting document tree
13375
 */
13376
xmlDoc *
13377
xmlReadFile(const char *filename, const char *encoding, int options)
13378
0
{
13379
0
    xmlParserCtxtPtr ctxt;
13380
0
    xmlParserInputPtr input;
13381
0
    xmlDocPtr doc = NULL;
13382
13383
0
    ctxt = xmlNewParserCtxt();
13384
0
    if (ctxt == NULL)
13385
0
        return(NULL);
13386
13387
0
    options |= XML_PARSE_UNZIP;
13388
13389
0
    xmlCtxtUseOptions(ctxt, options);
13390
13391
    /*
13392
     * Backward compatibility for users of command line utilities like
13393
     * xmlstarlet expecting "-" to mean stdin. This is dangerous and
13394
     * should be removed at some point.
13395
     */
13396
0
    if ((filename != NULL) && (filename[0] == '-') && (filename[1] == 0))
13397
0
        input = xmlCtxtNewInputFromFd(ctxt, filename, STDIN_FILENO,
13398
0
                                      encoding, 0);
13399
0
    else
13400
0
        input = xmlCtxtNewInputFromUrl(ctxt, filename, NULL, encoding, 0);
13401
13402
0
    if (input != NULL)
13403
0
        doc = xmlCtxtParseDocument(ctxt, input);
13404
13405
0
    xmlFreeParserCtxt(ctxt);
13406
0
    return(doc);
13407
0
}
13408
13409
/**
13410
 * Parse an XML in-memory document and build a tree. The input buffer must
13411
 * not contain a terminating null byte.
13412
 *
13413
 * See #xmlCtxtReadMemory for details.
13414
 *
13415
 * @param buffer  a pointer to a char array
13416
 * @param size  the size of the array
13417
 * @param url  base URL (optional)
13418
 * @param encoding  the document encoding (optional)
13419
 * @param options  a combination of xmlParserOption
13420
 * @returns the resulting document tree
13421
 */
13422
xmlDoc *
13423
xmlReadMemory(const char *buffer, int size, const char *url,
13424
              const char *encoding, int options)
13425
0
{
13426
0
    xmlParserCtxtPtr ctxt;
13427
0
    xmlParserInputPtr input;
13428
0
    xmlDocPtr doc = NULL;
13429
13430
0
    if (size < 0)
13431
0
  return(NULL);
13432
13433
0
    ctxt = xmlNewParserCtxt();
13434
0
    if (ctxt == NULL)
13435
0
        return(NULL);
13436
13437
0
    xmlCtxtUseOptions(ctxt, options);
13438
13439
0
    input = xmlCtxtNewInputFromMemory(ctxt, url, buffer, size, encoding,
13440
0
                                      XML_INPUT_BUF_STATIC);
13441
13442
0
    if (input != NULL)
13443
0
        doc = xmlCtxtParseDocument(ctxt, input);
13444
13445
0
    xmlFreeParserCtxt(ctxt);
13446
0
    return(doc);
13447
0
}
13448
13449
/**
13450
 * Parse an XML from a file descriptor and build a tree.
13451
 *
13452
 * See #xmlCtxtReadFd for details.
13453
 *
13454
 * NOTE that the file descriptor will not be closed when the
13455
 * context is freed or reset.
13456
 *
13457
 * @param fd  an open file descriptor
13458
 * @param URL  base URL (optional)
13459
 * @param encoding  the document encoding (optional)
13460
 * @param options  a combination of xmlParserOption
13461
 * @returns the resulting document tree
13462
 */
13463
xmlDoc *
13464
xmlReadFd(int fd, const char *URL, const char *encoding, int options)
13465
0
{
13466
0
    xmlParserCtxtPtr ctxt;
13467
0
    xmlParserInputPtr input;
13468
0
    xmlDocPtr doc = NULL;
13469
13470
0
    ctxt = xmlNewParserCtxt();
13471
0
    if (ctxt == NULL)
13472
0
        return(NULL);
13473
13474
0
    xmlCtxtUseOptions(ctxt, options);
13475
13476
0
    input = xmlCtxtNewInputFromFd(ctxt, URL, fd, encoding, 0);
13477
13478
0
    if (input != NULL)
13479
0
        doc = xmlCtxtParseDocument(ctxt, input);
13480
13481
0
    xmlFreeParserCtxt(ctxt);
13482
0
    return(doc);
13483
0
}
13484
13485
/**
13486
 * Parse an XML document from I/O functions and context and build a tree.
13487
 *
13488
 * See #xmlCtxtReadIO for details.
13489
 *
13490
 * @param ioread  an I/O read function
13491
 * @param ioclose  an I/O close function (optional)
13492
 * @param ioctx  an I/O handler
13493
 * @param URL  base URL (optional)
13494
 * @param encoding  the document encoding (optional)
13495
 * @param options  a combination of xmlParserOption
13496
 * @returns the resulting document tree
13497
 */
13498
xmlDoc *
13499
xmlReadIO(xmlInputReadCallback ioread, xmlInputCloseCallback ioclose,
13500
          void *ioctx, const char *URL, const char *encoding, int options)
13501
0
{
13502
0
    xmlParserCtxtPtr ctxt;
13503
0
    xmlParserInputPtr input;
13504
0
    xmlDocPtr doc = NULL;
13505
13506
0
    ctxt = xmlNewParserCtxt();
13507
0
    if (ctxt == NULL)
13508
0
        return(NULL);
13509
13510
0
    xmlCtxtUseOptions(ctxt, options);
13511
13512
0
    input = xmlCtxtNewInputFromIO(ctxt, URL, ioread, ioclose, ioctx,
13513
0
                                  encoding, 0);
13514
13515
0
    if (input != NULL)
13516
0
        doc = xmlCtxtParseDocument(ctxt, input);
13517
13518
0
    xmlFreeParserCtxt(ctxt);
13519
0
    return(doc);
13520
0
}
13521
13522
/**
13523
 * Parse an XML in-memory document and build a tree.
13524
 *
13525
 * `URL` is used as base to resolve external entities and for error
13526
 * reporting.
13527
 *
13528
 * See #xmlCtxtUseOptions for details.
13529
 *
13530
 * @param ctxt  an XML parser context
13531
 * @param str  a pointer to a zero terminated string
13532
 * @param URL  base URL (optional)
13533
 * @param encoding  the document encoding (optional)
13534
 * @param options  a combination of xmlParserOption
13535
 * @returns the resulting document tree
13536
 */
13537
xmlDoc *
13538
xmlCtxtReadDoc(xmlParserCtxt *ctxt, const xmlChar *str,
13539
               const char *URL, const char *encoding, int options)
13540
0
{
13541
0
    xmlParserInputPtr input;
13542
13543
0
    if (ctxt == NULL)
13544
0
        return(NULL);
13545
13546
0
    xmlCtxtReset(ctxt);
13547
0
    xmlCtxtUseOptions(ctxt, options);
13548
13549
0
    input = xmlCtxtNewInputFromString(ctxt, URL, (const char *) str, encoding,
13550
0
                                      XML_INPUT_BUF_STATIC);
13551
0
    if (input == NULL)
13552
0
        return(NULL);
13553
13554
0
    return(xmlCtxtParseDocument(ctxt, input));
13555
0
}
13556
13557
/**
13558
 * Parse an XML file from the filesystem, the network or a user-defined
13559
 * resource loader.
13560
 *
13561
 * This function always enables the XML_PARSE_UNZIP option for
13562
 * backward compatibility. This feature is potentially insecure
13563
 * and might be removed from later versions.
13564
 *
13565
 * @param ctxt  an XML parser context
13566
 * @param filename  a file or URL
13567
 * @param encoding  the document encoding (optional)
13568
 * @param options  a combination of xmlParserOption
13569
 * @returns the resulting document tree
13570
 */
13571
xmlDoc *
13572
xmlCtxtReadFile(xmlParserCtxt *ctxt, const char *filename,
13573
                const char *encoding, int options)
13574
6.14k
{
13575
6.14k
    xmlParserInputPtr input;
13576
13577
6.14k
    if (ctxt == NULL)
13578
0
        return(NULL);
13579
13580
6.14k
    options |= XML_PARSE_UNZIP;
13581
13582
6.14k
    xmlCtxtReset(ctxt);
13583
6.14k
    xmlCtxtUseOptions(ctxt, options);
13584
13585
6.14k
    input = xmlCtxtNewInputFromUrl(ctxt, filename, NULL, encoding, 0);
13586
6.14k
    if (input == NULL)
13587
6.14k
        return(NULL);
13588
13589
0
    return(xmlCtxtParseDocument(ctxt, input));
13590
6.14k
}
13591
13592
/**
13593
 * Parse an XML in-memory document and build a tree. The input buffer must
13594
 * not contain a terminating null byte.
13595
 *
13596
 * `URL` is used as base to resolve external entities and for error
13597
 * reporting.
13598
 *
13599
 * See #xmlCtxtUseOptions for details.
13600
 *
13601
 * @param ctxt  an XML parser context
13602
 * @param buffer  a pointer to a char array
13603
 * @param size  the size of the array
13604
 * @param URL  base URL (optional)
13605
 * @param encoding  the document encoding (optional)
13606
 * @param options  a combination of xmlParserOption
13607
 * @returns the resulting document tree
13608
 */
13609
xmlDoc *
13610
xmlCtxtReadMemory(xmlParserCtxt *ctxt, const char *buffer, int size,
13611
                  const char *URL, const char *encoding, int options)
13612
0
{
13613
0
    xmlParserInputPtr input;
13614
13615
0
    if ((ctxt == NULL) || (size < 0))
13616
0
        return(NULL);
13617
13618
0
    xmlCtxtReset(ctxt);
13619
0
    xmlCtxtUseOptions(ctxt, options);
13620
13621
0
    input = xmlCtxtNewInputFromMemory(ctxt, URL, buffer, size, encoding,
13622
0
                                      XML_INPUT_BUF_STATIC);
13623
0
    if (input == NULL)
13624
0
        return(NULL);
13625
13626
0
    return(xmlCtxtParseDocument(ctxt, input));
13627
0
}
13628
13629
/**
13630
 * Parse an XML document from a file descriptor and build a tree.
13631
 *
13632
 * NOTE that the file descriptor will not be closed when the
13633
 * context is freed or reset.
13634
 *
13635
 * `URL` is used as base to resolve external entities and for error
13636
 * reporting.
13637
 *
13638
 * See #xmlCtxtUseOptions for details.
13639
 *
13640
 * @param ctxt  an XML parser context
13641
 * @param fd  an open file descriptor
13642
 * @param URL  base URL (optional)
13643
 * @param encoding  the document encoding (optional)
13644
 * @param options  a combination of xmlParserOption
13645
 * @returns the resulting document tree
13646
 */
13647
xmlDoc *
13648
xmlCtxtReadFd(xmlParserCtxt *ctxt, int fd,
13649
              const char *URL, const char *encoding, int options)
13650
0
{
13651
0
    xmlParserInputPtr input;
13652
13653
0
    if (ctxt == NULL)
13654
0
        return(NULL);
13655
13656
0
    xmlCtxtReset(ctxt);
13657
0
    xmlCtxtUseOptions(ctxt, options);
13658
13659
0
    input = xmlCtxtNewInputFromFd(ctxt, URL, fd, encoding, 0);
13660
0
    if (input == NULL)
13661
0
        return(NULL);
13662
13663
0
    return(xmlCtxtParseDocument(ctxt, input));
13664
0
}
13665
13666
/**
13667
 * parse an XML document from I/O functions and source and build a tree.
13668
 * This reuses the existing `ctxt` parser context
13669
 *
13670
 * `URL` is used as base to resolve external entities and for error
13671
 * reporting.
13672
 *
13673
 * See #xmlCtxtUseOptions for details.
13674
 *
13675
 * @param ctxt  an XML parser context
13676
 * @param ioread  an I/O read function
13677
 * @param ioclose  an I/O close function
13678
 * @param ioctx  an I/O handler
13679
 * @param URL  the base URL to use for the document
13680
 * @param encoding  the document encoding, or NULL
13681
 * @param options  a combination of xmlParserOption
13682
 * @returns the resulting document tree
13683
 */
13684
xmlDoc *
13685
xmlCtxtReadIO(xmlParserCtxt *ctxt, xmlInputReadCallback ioread,
13686
              xmlInputCloseCallback ioclose, void *ioctx,
13687
        const char *URL,
13688
              const char *encoding, int options)
13689
0
{
13690
0
    xmlParserInputPtr input;
13691
13692
0
    if (ctxt == NULL)
13693
0
        return(NULL);
13694
13695
0
    xmlCtxtReset(ctxt);
13696
0
    xmlCtxtUseOptions(ctxt, options);
13697
13698
0
    input = xmlCtxtNewInputFromIO(ctxt, URL, ioread, ioclose, ioctx,
13699
0
                                  encoding, 0);
13700
0
    if (input == NULL)
13701
0
        return(NULL);
13702
13703
0
    return(xmlCtxtParseDocument(ctxt, input));
13704
0
}
13705