Coverage Report

Created: 2023-12-13 20:03

/src/libxml2/parserInternals.c
Line
Count
Source (jump to first uncovered line)
1
/*
2
 * parserInternals.c : Internal routines (and obsolete ones) needed for the
3
 *                     XML and HTML parsers.
4
 *
5
 * See Copyright for the status of this software.
6
 *
7
 * daniel@veillard.com
8
 */
9
10
#define IN_LIBXML
11
#include "libxml.h"
12
13
#if defined(_WIN32)
14
#define XML_DIR_SEP '\\'
15
#else
16
#define XML_DIR_SEP '/'
17
#endif
18
19
#include <string.h>
20
#include <ctype.h>
21
#include <stdlib.h>
22
23
#include <libxml/xmlmemory.h>
24
#include <libxml/tree.h>
25
#include <libxml/parser.h>
26
#include <libxml/parserInternals.h>
27
#include <libxml/valid.h>
28
#include <libxml/entities.h>
29
#include <libxml/xmlerror.h>
30
#include <libxml/encoding.h>
31
#include <libxml/valid.h>
32
#include <libxml/xmlIO.h>
33
#include <libxml/uri.h>
34
#include <libxml/dict.h>
35
#include <libxml/SAX.h>
36
#ifdef LIBXML_CATALOG_ENABLED
37
#include <libxml/catalog.h>
38
#endif
39
#include <libxml/globals.h>
40
#include <libxml/chvalid.h>
41
42
82.6M
#define CUR(ctxt) ctxt->input->cur
43
82.6M
#define END(ctxt) ctxt->input->end
44
82.6M
#define VALID_CTXT(ctxt) (CUR(ctxt) <= END(ctxt))
45
46
#include "private/buf.h"
47
#include "private/enc.h"
48
#include "private/error.h"
49
#include "private/io.h"
50
#include "private/parser.h"
51
52
/*
53
 * Various global defaults for parsing
54
 */
55
56
/**
57
 * xmlCheckVersion:
58
 * @version: the include version number
59
 *
60
 * check the compiled lib version against the include one.
61
 * This can warn or immediately kill the application
62
 */
63
void
64
0
xmlCheckVersion(int version) {
65
0
    int myversion = LIBXML_VERSION;
66
67
0
    xmlInitParser();
68
69
0
    if ((myversion / 10000) != (version / 10000)) {
70
0
  xmlGenericError(xmlGenericErrorContext,
71
0
    "Fatal: program compiled against libxml %d using libxml %d\n",
72
0
    (version / 10000), (myversion / 10000));
73
0
  fprintf(stderr,
74
0
    "Fatal: program compiled against libxml %d using libxml %d\n",
75
0
    (version / 10000), (myversion / 10000));
76
0
    }
77
0
    if ((myversion / 100) < (version / 100)) {
78
0
  xmlGenericError(xmlGenericErrorContext,
79
0
    "Warning: program compiled against libxml %d using older %d\n",
80
0
    (version / 100), (myversion / 100));
81
0
    }
82
0
}
83
84
85
/************************************************************************
86
 *                  *
87
 *    Some factorized error routines        *
88
 *                  *
89
 ************************************************************************/
90
91
92
/**
93
 * xmlErrMemory:
94
 * @ctxt:  an XML parser context
95
 * @extra:  extra information
96
 *
97
 * Handle a redefinition of attribute error
98
 */
99
void
100
xmlErrMemory(xmlParserCtxtPtr ctxt, const char *extra)
101
0
{
102
0
    if ((ctxt != NULL) && (ctxt->disableSAX != 0) &&
103
0
        (ctxt->instate == XML_PARSER_EOF))
104
0
  return;
105
0
    if (ctxt != NULL) {
106
0
        ctxt->errNo = XML_ERR_NO_MEMORY;
107
0
        ctxt->instate = XML_PARSER_EOF;
108
0
        ctxt->disableSAX = 1;
109
0
    }
110
0
    if (extra)
111
0
        __xmlRaiseError(NULL, NULL, NULL, ctxt, NULL, XML_FROM_PARSER,
112
0
                        XML_ERR_NO_MEMORY, XML_ERR_FATAL, NULL, 0, extra,
113
0
                        NULL, NULL, 0, 0,
114
0
                        "Memory allocation failed : %s\n", extra);
115
0
    else
116
0
        __xmlRaiseError(NULL, NULL, NULL, ctxt, NULL, XML_FROM_PARSER,
117
0
                        XML_ERR_NO_MEMORY, XML_ERR_FATAL, NULL, 0, NULL,
118
0
                        NULL, NULL, 0, 0, "Memory allocation failed\n");
119
0
}
120
121
/**
122
 * __xmlErrEncoding:
123
 * @ctxt:  an XML parser context
124
 * @xmlerr:  the error number
125
 * @msg:  the error message
126
 * @str1:  an string info
127
 * @str2:  an string info
128
 *
129
 * Handle an encoding error
130
 */
131
void
132
__xmlErrEncoding(xmlParserCtxtPtr ctxt, xmlParserErrors xmlerr,
133
                 const char *msg, const xmlChar * str1, const xmlChar * str2)
134
522k
{
135
522k
    if ((ctxt != NULL) && (ctxt->disableSAX != 0) &&
136
522k
        (ctxt->instate == XML_PARSER_EOF))
137
0
  return;
138
522k
    if (ctxt != NULL)
139
522k
        ctxt->errNo = xmlerr;
140
522k
    __xmlRaiseError(NULL, NULL, NULL,
141
522k
                    ctxt, NULL, XML_FROM_PARSER, xmlerr, XML_ERR_FATAL,
142
522k
                    NULL, 0, (const char *) str1, (const char *) str2,
143
522k
                    NULL, 0, 0, msg, str1, str2);
144
522k
    if (ctxt != NULL) {
145
522k
        ctxt->wellFormed = 0;
146
522k
        if (ctxt->recovery == 0)
147
150k
            ctxt->disableSAX = 1;
148
522k
    }
149
522k
}
150
151
/**
152
 * xmlErrInternal:
153
 * @ctxt:  an XML parser context
154
 * @msg:  the error message
155
 * @str:  error information
156
 *
157
 * Handle an internal error
158
 */
159
static void LIBXML_ATTR_FORMAT(2,0)
160
xmlErrInternal(xmlParserCtxtPtr ctxt, const char *msg, const xmlChar * str)
161
370
{
162
370
    if ((ctxt != NULL) && (ctxt->disableSAX != 0) &&
163
370
        (ctxt->instate == XML_PARSER_EOF))
164
0
  return;
165
370
    if (ctxt != NULL)
166
370
        ctxt->errNo = XML_ERR_INTERNAL_ERROR;
167
370
    __xmlRaiseError(NULL, NULL, NULL,
168
370
                    ctxt, NULL, XML_FROM_PARSER, XML_ERR_INTERNAL_ERROR,
169
370
                    XML_ERR_FATAL, NULL, 0, (const char *) str, NULL, NULL,
170
370
                    0, 0, msg, str);
171
370
    if (ctxt != NULL) {
172
370
        ctxt->wellFormed = 0;
173
370
        if (ctxt->recovery == 0)
174
216
            ctxt->disableSAX = 1;
175
370
    }
176
370
}
177
178
/**
179
 * xmlErrEncodingInt:
180
 * @ctxt:  an XML parser context
181
 * @error:  the error number
182
 * @msg:  the error message
183
 * @val:  an integer value
184
 *
185
 * n encoding error
186
 */
187
static void LIBXML_ATTR_FORMAT(3,0)
188
xmlErrEncodingInt(xmlParserCtxtPtr ctxt, xmlParserErrors error,
189
                  const char *msg, int val)
190
325k
{
191
325k
    if ((ctxt != NULL) && (ctxt->disableSAX != 0) &&
192
325k
        (ctxt->instate == XML_PARSER_EOF))
193
0
  return;
194
325k
    if (ctxt != NULL)
195
322k
        ctxt->errNo = error;
196
325k
    __xmlRaiseError(NULL, NULL, NULL,
197
325k
                    ctxt, NULL, XML_FROM_PARSER, error, XML_ERR_FATAL,
198
325k
                    NULL, 0, NULL, NULL, NULL, val, 0, msg, val);
199
325k
    if (ctxt != NULL) {
200
322k
        ctxt->wellFormed = 0;
201
322k
        if (ctxt->recovery == 0)
202
46.8k
            ctxt->disableSAX = 1;
203
322k
    }
204
325k
}
205
206
/**
207
 * xmlIsLetter:
208
 * @c:  an unicode character (int)
209
 *
210
 * Check whether the character is allowed by the production
211
 * [84] Letter ::= BaseChar | Ideographic
212
 *
213
 * Returns 0 if not, non-zero otherwise
214
 */
215
int
216
0
xmlIsLetter(int c) {
217
0
    return(IS_BASECHAR(c) || IS_IDEOGRAPHIC(c));
218
0
}
219
220
/************************************************************************
221
 *                  *
222
 *    Input handling functions for progressive parsing  *
223
 *                  *
224
 ************************************************************************/
225
226
/* #define DEBUG_INPUT */
227
/* #define DEBUG_STACK */
228
/* #define DEBUG_PUSH */
229
230
231
/* we need to keep enough input to show errors in context */
232
232k
#define LINE_LEN        80
233
234
#ifdef DEBUG_INPUT
235
#define CHECK_BUFFER(in) check_buffer(in)
236
237
static
238
void check_buffer(xmlParserInputPtr in) {
239
    if (in->base != xmlBufContent(in->buf->buffer)) {
240
        xmlGenericError(xmlGenericErrorContext,
241
    "xmlParserInput: base mismatch problem\n");
242
    }
243
    if (in->cur < in->base) {
244
        xmlGenericError(xmlGenericErrorContext,
245
    "xmlParserInput: cur < base problem\n");
246
    }
247
    if (in->cur > in->base + xmlBufUse(in->buf->buffer)) {
248
        xmlGenericError(xmlGenericErrorContext,
249
    "xmlParserInput: cur > base + use problem\n");
250
    }
251
    xmlGenericError(xmlGenericErrorContext,"buffer %p : content %x, cur %d, use %d\n",
252
            (void *) in, (int) xmlBufContent(in->buf->buffer),
253
            in->cur - in->base, xmlBufUse(in->buf->buffer));
254
}
255
256
#else
257
#define CHECK_BUFFER(in)
258
#endif
259
260
261
/**
262
 * xmlParserInputRead:
263
 * @in:  an XML parser input
264
 * @len:  an indicative size for the lookahead
265
 *
266
 * DEPRECATED: This function was internal and is deprecated.
267
 *
268
 * Returns -1 as this is an error to use it.
269
 */
270
int
271
0
xmlParserInputRead(xmlParserInputPtr in ATTRIBUTE_UNUSED, int len ATTRIBUTE_UNUSED) {
272
0
    return(-1);
273
0
}
274
275
/**
276
 * xmlParserInputGrow:
277
 * @in:  an XML parser input
278
 * @len:  an indicative size for the lookahead
279
 *
280
 * DEPRECATED: Don't use.
281
 *
282
 * This function increase the input for the parser. It tries to
283
 * preserve pointers to the input buffer, and keep already read data
284
 *
285
 * Returns the amount of char read, or -1 in case of error, 0 indicate the
286
 * end of this entity
287
 */
288
int
289
31.4M
xmlParserInputGrow(xmlParserInputPtr in, int len) {
290
31.4M
    int ret;
291
31.4M
    size_t indx;
292
293
31.4M
    if ((in == NULL) || (len < 0)) return(-1);
294
#ifdef DEBUG_INPUT
295
    xmlGenericError(xmlGenericErrorContext, "Grow\n");
296
#endif
297
31.4M
    if (in->buf == NULL) return(-1);
298
26.4M
    if (in->base == NULL) return(-1);
299
26.4M
    if (in->cur == NULL) return(-1);
300
26.4M
    if (in->buf->buffer == NULL) return(-1);
301
302
26.4M
    CHECK_BUFFER(in);
303
304
26.4M
    indx = in->cur - in->base;
305
26.4M
    if (xmlBufUse(in->buf->buffer) > (unsigned int) indx + INPUT_CHUNK) {
306
307
29.3k
  CHECK_BUFFER(in);
308
309
29.3k
        return(0);
310
29.3k
    }
311
26.4M
    if (in->buf->readcallback != NULL) {
312
23.0M
  ret = xmlParserInputBufferGrow(in->buf, len);
313
23.0M
    } else
314
3.43M
        return(0);
315
316
23.0M
    in->base = xmlBufContent(in->buf->buffer);
317
23.0M
    in->cur = in->base + indx;
318
23.0M
    in->end = xmlBufEnd(in->buf->buffer);
319
320
23.0M
    CHECK_BUFFER(in);
321
322
23.0M
    return(ret);
323
26.4M
}
324
325
/**
326
 * xmlParserInputShrink:
327
 * @in:  an XML parser input
328
 *
329
 * This function removes used input for the parser.
330
 */
331
void
332
233k
xmlParserInputShrink(xmlParserInputPtr in) {
333
233k
    size_t used;
334
233k
    size_t ret;
335
336
#ifdef DEBUG_INPUT
337
    xmlGenericError(xmlGenericErrorContext, "Shrink\n");
338
#endif
339
233k
    if (in == NULL) return;
340
233k
    if (in->buf == NULL) return;
341
232k
    if (in->base == NULL) return;
342
232k
    if (in->cur == NULL) return;
343
232k
    if (in->buf->buffer == NULL) return;
344
345
232k
    CHECK_BUFFER(in);
346
347
232k
    used = in->cur - in->base;
348
    /*
349
     * Do not shrink on large buffers whose only a tiny fraction
350
     * was consumed
351
     */
352
232k
    if (used > INPUT_CHUNK) {
353
232k
  ret = xmlBufShrink(in->buf->buffer, used - LINE_LEN);
354
232k
  if (ret > 0) {
355
232k
            used -= ret;
356
232k
      in->consumed += ret;
357
232k
  }
358
232k
    }
359
360
232k
    if (xmlBufUse(in->buf->buffer) <= INPUT_CHUNK) {
361
85.9k
        xmlParserInputBufferRead(in->buf, 2 * INPUT_CHUNK);
362
85.9k
    }
363
364
232k
    in->base = xmlBufContent(in->buf->buffer);
365
232k
    in->cur = in->base + used;
366
232k
    in->end = xmlBufEnd(in->buf->buffer);
367
368
232k
    CHECK_BUFFER(in);
369
232k
}
370
371
/************************************************************************
372
 *                  *
373
 *    UTF8 character input and related functions    *
374
 *                  *
375
 ************************************************************************/
376
377
/**
378
 * xmlNextChar:
379
 * @ctxt:  the XML parser context
380
 *
381
 * Skip to the next char input char.
382
 */
383
384
void
385
xmlNextChar(xmlParserCtxtPtr ctxt)
386
82.6M
{
387
82.6M
    if ((ctxt == NULL) || (ctxt->instate == XML_PARSER_EOF) ||
388
82.6M
        (ctxt->input == NULL))
389
0
        return;
390
391
82.6M
    if (!(VALID_CTXT(ctxt))) {
392
0
        xmlErrInternal(ctxt, "Parser input data memory error\n", NULL);
393
0
  ctxt->errNo = XML_ERR_INTERNAL_ERROR;
394
0
        xmlStopParser(ctxt);
395
0
  return;
396
0
    }
397
398
82.6M
    if ((*ctxt->input->cur == 0) &&
399
82.6M
        (xmlParserInputGrow(ctxt->input, INPUT_CHUNK) <= 0)) {
400
5.96k
        return;
401
5.96k
    }
402
403
82.6M
    if (ctxt->charset == XML_CHAR_ENCODING_UTF8) {
404
48.3M
        const unsigned char *cur;
405
48.3M
        unsigned char c;
406
407
        /*
408
         *   2.11 End-of-Line Handling
409
         *   the literal two-character sequence "#xD#xA" or a standalone
410
         *   literal #xD, an XML processor must pass to the application
411
         *   the single character #xA.
412
         */
413
48.3M
        if (*(ctxt->input->cur) == '\n') {
414
3.54M
            ctxt->input->line++; ctxt->input->col = 1;
415
3.54M
        } else
416
44.7M
            ctxt->input->col++;
417
418
        /*
419
         * We are supposed to handle UTF8, check it's valid
420
         * From rfc2044: encoding of the Unicode values on UTF-8:
421
         *
422
         * UCS-4 range (hex.)           UTF-8 octet sequence (binary)
423
         * 0000 0000-0000 007F   0xxxxxxx
424
         * 0000 0080-0000 07FF   110xxxxx 10xxxxxx
425
         * 0000 0800-0000 FFFF   1110xxxx 10xxxxxx 10xxxxxx
426
         *
427
         * Check for the 0x110000 limit too
428
         */
429
48.3M
        cur = ctxt->input->cur;
430
431
48.3M
        c = *cur;
432
48.3M
        if (c & 0x80) {
433
427k
            if (c == 0xC0)
434
483
          goto encoding_error;
435
426k
            if (cur[1] == 0) {
436
580
                xmlParserInputGrow(ctxt->input, INPUT_CHUNK);
437
580
                cur = ctxt->input->cur;
438
580
            }
439
426k
            if ((cur[1] & 0xc0) != 0x80)
440
55.5k
                goto encoding_error;
441
371k
            if ((c & 0xe0) == 0xe0) {
442
194k
                unsigned int val;
443
444
194k
                if (cur[2] == 0) {
445
146
                    xmlParserInputGrow(ctxt->input, INPUT_CHUNK);
446
146
                    cur = ctxt->input->cur;
447
146
                }
448
194k
                if ((cur[2] & 0xc0) != 0x80)
449
592
                    goto encoding_error;
450
193k
                if ((c & 0xf0) == 0xf0) {
451
12.1k
                    if (cur[3] == 0) {
452
129
                        xmlParserInputGrow(ctxt->input, INPUT_CHUNK);
453
129
                        cur = ctxt->input->cur;
454
129
                    }
455
12.1k
                    if (((c & 0xf8) != 0xf0) ||
456
12.1k
                        ((cur[3] & 0xc0) != 0x80))
457
545
                        goto encoding_error;
458
                    /* 4-byte code */
459
11.6k
                    ctxt->input->cur += 4;
460
11.6k
                    val = (cur[0] & 0x7) << 18;
461
11.6k
                    val |= (cur[1] & 0x3f) << 12;
462
11.6k
                    val |= (cur[2] & 0x3f) << 6;
463
11.6k
                    val |= cur[3] & 0x3f;
464
181k
                } else {
465
                    /* 3-byte code */
466
181k
                    ctxt->input->cur += 3;
467
181k
                    val = (cur[0] & 0xf) << 12;
468
181k
                    val |= (cur[1] & 0x3f) << 6;
469
181k
                    val |= cur[2] & 0x3f;
470
181k
                }
471
193k
                if (((val > 0xd7ff) && (val < 0xe000)) ||
472
193k
                    ((val > 0xfffd) && (val < 0x10000)) ||
473
193k
                    (val >= 0x110000)) {
474
14.2k
    xmlErrEncodingInt(ctxt, XML_ERR_INVALID_CHAR,
475
14.2k
          "Char 0x%X out of allowed range\n",
476
14.2k
          val);
477
14.2k
                }
478
193k
            } else
479
                /* 2-byte code */
480
176k
                ctxt->input->cur += 2;
481
371k
        } else
482
            /* 1-byte code */
483
47.8M
            ctxt->input->cur++;
484
48.3M
    } else {
485
        /*
486
         * Assume it's a fixed length encoding (1) with
487
         * a compatible encoding for the ASCII set, since
488
         * XML constructs only use < 128 chars
489
         */
490
491
34.3M
        if (*(ctxt->input->cur) == '\n') {
492
2.69M
            ctxt->input->line++; ctxt->input->col = 1;
493
2.69M
        } else
494
31.6M
            ctxt->input->col++;
495
34.3M
        ctxt->input->cur++;
496
34.3M
    }
497
82.5M
    if (*ctxt->input->cur == 0)
498
292k
        xmlParserInputGrow(ctxt->input, INPUT_CHUNK);
499
82.5M
    return;
500
57.2k
encoding_error:
501
    /*
502
     * If we detect an UTF8 error that probably mean that the
503
     * input encoding didn't get properly advertised in the
504
     * declaration header. Report the error and switch the encoding
505
     * to ISO-Latin-1 (if you don't like this policy, just declare the
506
     * encoding !)
507
     */
508
57.2k
    if ((ctxt == NULL) || (ctxt->input == NULL) ||
509
57.2k
        (ctxt->input->end - ctxt->input->cur < 4)) {
510
457
  __xmlErrEncoding(ctxt, XML_ERR_INVALID_CHAR,
511
457
         "Input is not proper UTF-8, indicate encoding !\n",
512
457
         NULL, NULL);
513
56.7k
    } else {
514
56.7k
        char buffer[150];
515
516
56.7k
  snprintf(buffer, 149, "Bytes: 0x%02X 0x%02X 0x%02X 0x%02X\n",
517
56.7k
      ctxt->input->cur[0], ctxt->input->cur[1],
518
56.7k
      ctxt->input->cur[2], ctxt->input->cur[3]);
519
56.7k
  __xmlErrEncoding(ctxt, XML_ERR_INVALID_CHAR,
520
56.7k
         "Input is not proper UTF-8, indicate encoding !\n%s",
521
56.7k
         BAD_CAST buffer, NULL);
522
56.7k
    }
523
57.2k
    ctxt->charset = XML_CHAR_ENCODING_8859_1;
524
57.2k
    ctxt->input->cur++;
525
57.2k
    return;
526
82.6M
}
527
528
/**
529
 * xmlCurrentChar:
530
 * @ctxt:  the XML parser context
531
 * @len:  pointer to the length of the char read
532
 *
533
 * The current char value, if using UTF-8 this may actually span multiple
534
 * bytes in the input buffer. Implement the end of line normalization:
535
 * 2.11 End-of-Line Handling
536
 * Wherever an external parsed entity or the literal entity value
537
 * of an internal parsed entity contains either the literal two-character
538
 * sequence "#xD#xA" or a standalone literal #xD, an XML processor
539
 * must pass to the application the single character #xA.
540
 * This behavior can conveniently be produced by normalizing all
541
 * line breaks to #xA on input, before parsing.)
542
 *
543
 * Returns the current char value and its length
544
 */
545
546
int
547
376M
xmlCurrentChar(xmlParserCtxtPtr ctxt, int *len) {
548
376M
    if ((ctxt == NULL) || (len == NULL) || (ctxt->input == NULL)) return(0);
549
376M
    if (ctxt->instate == XML_PARSER_EOF)
550
0
  return(0);
551
552
376M
    if ((*ctxt->input->cur >= 0x20) && (*ctxt->input->cur <= 0x7F)) {
553
267M
      *len = 1;
554
267M
      return(*ctxt->input->cur);
555
267M
    }
556
108M
    if (ctxt->charset == XML_CHAR_ENCODING_UTF8) {
557
  /*
558
   * We are supposed to handle UTF8, check it's valid
559
   * From rfc2044: encoding of the Unicode values on UTF-8:
560
   *
561
   * UCS-4 range (hex.)           UTF-8 octet sequence (binary)
562
   * 0000 0000-0000 007F   0xxxxxxx
563
   * 0000 0080-0000 07FF   110xxxxx 10xxxxxx
564
   * 0000 0800-0000 FFFF   1110xxxx 10xxxxxx 10xxxxxx
565
   *
566
   * Check for the 0x110000 limit too
567
   */
568
19.9M
  const unsigned char *cur = ctxt->input->cur;
569
19.9M
  unsigned char c;
570
19.9M
  unsigned int val;
571
572
19.9M
  c = *cur;
573
19.9M
  if (c & 0x80) {
574
13.9M
      if (((c & 0x40) == 0) || (c == 0xC0))
575
134k
    goto encoding_error;
576
13.7M
      if (cur[1] == 0) {
577
1.90k
    xmlParserInputGrow(ctxt->input, INPUT_CHUNK);
578
1.90k
                cur = ctxt->input->cur;
579
1.90k
            }
580
13.7M
      if ((cur[1] & 0xc0) != 0x80)
581
260k
    goto encoding_error;
582
13.5M
      if ((c & 0xe0) == 0xe0) {
583
6.04M
    if (cur[2] == 0) {
584
680
        xmlParserInputGrow(ctxt->input, INPUT_CHUNK);
585
680
                    cur = ctxt->input->cur;
586
680
                }
587
6.04M
    if ((cur[2] & 0xc0) != 0x80)
588
4.87k
        goto encoding_error;
589
6.04M
    if ((c & 0xf0) == 0xf0) {
590
333k
        if (cur[3] == 0) {
591
866
      xmlParserInputGrow(ctxt->input, INPUT_CHUNK);
592
866
                        cur = ctxt->input->cur;
593
866
                    }
594
333k
        if (((c & 0xf8) != 0xf0) ||
595
333k
      ((cur[3] & 0xc0) != 0x80))
596
2.21k
      goto encoding_error;
597
        /* 4-byte code */
598
331k
        *len = 4;
599
331k
        val = (cur[0] & 0x7) << 18;
600
331k
        val |= (cur[1] & 0x3f) << 12;
601
331k
        val |= (cur[2] & 0x3f) << 6;
602
331k
        val |= cur[3] & 0x3f;
603
331k
        if (val < 0x10000)
604
319
      goto encoding_error;
605
5.70M
    } else {
606
      /* 3-byte code */
607
5.70M
        *len = 3;
608
5.70M
        val = (cur[0] & 0xf) << 12;
609
5.70M
        val |= (cur[1] & 0x3f) << 6;
610
5.70M
        val |= cur[2] & 0x3f;
611
5.70M
        if (val < 0x800)
612
1.02k
      goto encoding_error;
613
5.70M
    }
614
7.48M
      } else {
615
        /* 2-byte code */
616
7.48M
    *len = 2;
617
7.48M
    val = (cur[0] & 0x1f) << 6;
618
7.48M
    val |= cur[1] & 0x3f;
619
7.48M
    if (val < 0x80)
620
1.13k
        goto encoding_error;
621
7.48M
      }
622
13.5M
      if (!IS_CHAR(val)) {
623
245k
          xmlErrEncodingInt(ctxt, XML_ERR_INVALID_CHAR,
624
245k
          "Char 0x%X out of allowed range\n", val);
625
245k
      }
626
13.5M
      return(val);
627
13.5M
  } else {
628
      /* 1-byte code */
629
6.01M
      *len = 1;
630
6.01M
      if (*ctxt->input->cur == 0)
631
233k
    xmlParserInputGrow(ctxt->input, INPUT_CHUNK);
632
6.01M
      if ((*ctxt->input->cur == 0) &&
633
6.01M
          (ctxt->input->end > ctxt->input->cur)) {
634
62.5k
          xmlErrEncodingInt(ctxt, XML_ERR_INVALID_CHAR,
635
62.5k
          "Char 0x0 out of allowed range\n", 0);
636
62.5k
      }
637
6.01M
      if (*ctxt->input->cur == 0xD) {
638
1.67M
    if (ctxt->input->cur[1] == 0xA) {
639
1.47M
        ctxt->input->cur++;
640
1.47M
    }
641
1.67M
    return(0xA);
642
1.67M
      }
643
4.34M
      return(*ctxt->input->cur);
644
6.01M
  }
645
19.9M
    }
646
    /*
647
     * Assume it's a fixed length encoding (1) with
648
     * a compatible encoding for the ASCII set, since
649
     * XML constructs only use < 128 chars
650
     */
651
88.8M
    *len = 1;
652
88.8M
    if (*ctxt->input->cur == 0xD) {
653
3.61M
  if (ctxt->input->cur[1] == 0xA) {
654
2.89M
      ctxt->input->cur++;
655
2.89M
  }
656
3.61M
  return(0xA);
657
3.61M
    }
658
85.2M
    return(*ctxt->input->cur);
659
404k
encoding_error:
660
    /*
661
     * An encoding problem may arise from a truncated input buffer
662
     * splitting a character in the middle. In that case do not raise
663
     * an error but return 0 to indicate an end of stream problem
664
     */
665
404k
    if (ctxt->input->end - ctxt->input->cur < 4) {
666
7.66k
  *len = 0;
667
7.66k
  return(0);
668
7.66k
    }
669
670
    /*
671
     * If we detect an UTF8 error that probably mean that the
672
     * input encoding didn't get properly advertised in the
673
     * declaration header. Report the error and switch the encoding
674
     * to ISO-Latin-1 (if you don't like this policy, just declare the
675
     * encoding !)
676
     */
677
397k
    {
678
397k
        char buffer[150];
679
680
397k
  snprintf(&buffer[0], 149, "Bytes: 0x%02X 0x%02X 0x%02X 0x%02X\n",
681
397k
      ctxt->input->cur[0], ctxt->input->cur[1],
682
397k
      ctxt->input->cur[2], ctxt->input->cur[3]);
683
397k
  __xmlErrEncoding(ctxt, XML_ERR_INVALID_CHAR,
684
397k
         "Input is not proper UTF-8, indicate encoding !\n%s",
685
397k
         BAD_CAST buffer, NULL);
686
397k
    }
687
397k
    ctxt->charset = XML_CHAR_ENCODING_8859_1;
688
397k
    *len = 1;
689
397k
    return(*ctxt->input->cur);
690
404k
}
691
692
/**
693
 * xmlStringCurrentChar:
694
 * @ctxt:  the XML parser context
695
 * @cur:  pointer to the beginning of the char
696
 * @len:  pointer to the length of the char read
697
 *
698
 * The current char value, if using UTF-8 this may actually span multiple
699
 * bytes in the input buffer.
700
 *
701
 * Returns the current char value and its length
702
 */
703
704
int
705
xmlStringCurrentChar(xmlParserCtxtPtr ctxt, const xmlChar * cur, int *len)
706
208M
{
707
208M
    if ((len == NULL) || (cur == NULL)) return(0);
708
208M
    if ((ctxt == NULL) || (ctxt->charset == XML_CHAR_ENCODING_UTF8)) {
709
        /*
710
         * We are supposed to handle UTF8, check it's valid
711
         * From rfc2044: encoding of the Unicode values on UTF-8:
712
         *
713
         * UCS-4 range (hex.)           UTF-8 octet sequence (binary)
714
         * 0000 0000-0000 007F   0xxxxxxx
715
         * 0000 0080-0000 07FF   110xxxxx 10xxxxxx
716
         * 0000 0800-0000 FFFF   1110xxxx 10xxxxxx 10xxxxxx
717
         *
718
         * Check for the 0x110000 limit too
719
         */
720
38.4M
        unsigned char c;
721
38.4M
        unsigned int val;
722
723
38.4M
        c = *cur;
724
38.4M
        if (c & 0x80) {
725
1.05M
            if ((cur[1] & 0xc0) != 0x80)
726
29.3k
                goto encoding_error;
727
1.02M
            if ((c & 0xe0) == 0xe0) {
728
729
32.8k
                if ((cur[2] & 0xc0) != 0x80)
730
1.25k
                    goto encoding_error;
731
31.6k
                if ((c & 0xf0) == 0xf0) {
732
6.77k
                    if (((c & 0xf8) != 0xf0) || ((cur[3] & 0xc0) != 0x80))
733
1.43k
                        goto encoding_error;
734
                    /* 4-byte code */
735
5.33k
                    *len = 4;
736
5.33k
                    val = (cur[0] & 0x7) << 18;
737
5.33k
                    val |= (cur[1] & 0x3f) << 12;
738
5.33k
                    val |= (cur[2] & 0x3f) << 6;
739
5.33k
                    val |= cur[3] & 0x3f;
740
24.8k
                } else {
741
                    /* 3-byte code */
742
24.8k
                    *len = 3;
743
24.8k
                    val = (cur[0] & 0xf) << 12;
744
24.8k
                    val |= (cur[1] & 0x3f) << 6;
745
24.8k
                    val |= cur[2] & 0x3f;
746
24.8k
                }
747
990k
            } else {
748
                /* 2-byte code */
749
990k
                *len = 2;
750
990k
                val = (cur[0] & 0x1f) << 6;
751
990k
                val |= cur[1] & 0x3f;
752
990k
            }
753
1.02M
            if (!IS_CHAR(val)) {
754
3.23k
          xmlErrEncodingInt(ctxt, XML_ERR_INVALID_CHAR,
755
3.23k
          "Char 0x%X out of allowed range\n", val);
756
3.23k
            }
757
1.02M
            return (val);
758
37.3M
        } else {
759
            /* 1-byte code */
760
37.3M
            *len = 1;
761
37.3M
            return (*cur);
762
37.3M
        }
763
38.4M
    }
764
    /*
765
     * Assume it's a fixed length encoding (1) with
766
     * a compatible encoding for the ASCII set, since
767
     * XML constructs only use < 128 chars
768
     */
769
170M
    *len = 1;
770
170M
    return (*cur);
771
32.0k
encoding_error:
772
773
    /*
774
     * An encoding problem may arise from a truncated input buffer
775
     * splitting a character in the middle. In that case do not raise
776
     * an error but return 0 to indicate an end of stream problem
777
     */
778
32.0k
    if ((ctxt == NULL) || (ctxt->input == NULL) ||
779
32.0k
        (ctxt->input->end - ctxt->input->cur < 4)) {
780
31.5k
  *len = 0;
781
31.5k
  return(0);
782
31.5k
    }
783
    /*
784
     * If we detect an UTF8 error that probably mean that the
785
     * input encoding didn't get properly advertised in the
786
     * declaration header. Report the error and switch the encoding
787
     * to ISO-Latin-1 (if you don't like this policy, just declare the
788
     * encoding !)
789
     */
790
554
    {
791
554
        char buffer[150];
792
793
554
  snprintf(buffer, 149, "Bytes: 0x%02X 0x%02X 0x%02X 0x%02X\n",
794
554
      ctxt->input->cur[0], ctxt->input->cur[1],
795
554
      ctxt->input->cur[2], ctxt->input->cur[3]);
796
554
  __xmlErrEncoding(ctxt, XML_ERR_INVALID_CHAR,
797
554
         "Input is not proper UTF-8, indicate encoding !\n%s",
798
554
         BAD_CAST buffer, NULL);
799
554
    }
800
554
    *len = 1;
801
554
    return (*cur);
802
32.0k
}
803
804
/**
805
 * xmlCopyCharMultiByte:
806
 * @out:  pointer to an array of xmlChar
807
 * @val:  the char value
808
 *
809
 * append the char value in the array
810
 *
811
 * Returns the number of xmlChar written
812
 */
813
int
814
12.2M
xmlCopyCharMultiByte(xmlChar *out, int val) {
815
12.2M
    if ((out == NULL) || (val < 0)) return(0);
816
    /*
817
     * We are supposed to handle UTF8, check it's valid
818
     * From rfc2044: encoding of the Unicode values on UTF-8:
819
     *
820
     * UCS-4 range (hex.)           UTF-8 octet sequence (binary)
821
     * 0000 0000-0000 007F   0xxxxxxx
822
     * 0000 0080-0000 07FF   110xxxxx 10xxxxxx
823
     * 0000 0800-0000 FFFF   1110xxxx 10xxxxxx 10xxxxxx
824
     */
825
12.2M
    if  (val >= 0x80) {
826
11.9M
  xmlChar *savedout = out;
827
11.9M
  int bits;
828
11.9M
  if (val <   0x800) { *out++= (val >>  6) | 0xC0;  bits=  0; }
829
4.29M
  else if (val < 0x10000) { *out++= (val >> 12) | 0xE0;  bits=  6;}
830
296k
  else if (val < 0x110000)  { *out++= (val >> 18) | 0xF0;  bits=  12; }
831
0
  else {
832
0
      xmlErrEncodingInt(NULL, XML_ERR_INVALID_CHAR,
833
0
        "Internal error, xmlCopyCharMultiByte 0x%X out of bound\n",
834
0
            val);
835
0
      return(0);
836
0
  }
837
28.5M
  for ( ; bits >= 0; bits-= 6)
838
16.5M
      *out++= ((val >> bits) & 0x3F) | 0x80 ;
839
11.9M
  return (out - savedout);
840
11.9M
    }
841
289k
    *out = val;
842
289k
    return 1;
843
12.2M
}
844
845
/**
846
 * xmlCopyChar:
847
 * @len:  Ignored, compatibility
848
 * @out:  pointer to an array of xmlChar
849
 * @val:  the char value
850
 *
851
 * append the char value in the array
852
 *
853
 * Returns the number of xmlChar written
854
 */
855
856
int
857
430k
xmlCopyChar(int len ATTRIBUTE_UNUSED, xmlChar *out, int val) {
858
430k
    if ((out == NULL) || (val < 0)) return(0);
859
    /* the len parameter is ignored */
860
430k
    if  (val >= 0x80) {
861
269k
  return(xmlCopyCharMultiByte (out, val));
862
269k
    }
863
161k
    *out = val;
864
161k
    return 1;
865
430k
}
866
867
/************************************************************************
868
 *                  *
869
 *    Commodity functions to switch encodings     *
870
 *                  *
871
 ************************************************************************/
872
873
static int
874
xmlSwitchInputEncodingInt(xmlParserCtxtPtr ctxt, xmlParserInputPtr input,
875
                          xmlCharEncodingHandlerPtr handler, int len);
876
/**
877
 * xmlSwitchEncoding:
878
 * @ctxt:  the parser context
879
 * @enc:  the encoding value (number)
880
 *
881
 * change the input functions when discovering the character encoding
882
 * of a given entity.
883
 *
884
 * Returns 0 in case of success, -1 otherwise
885
 */
886
int
887
xmlSwitchEncoding(xmlParserCtxtPtr ctxt, xmlCharEncoding enc)
888
722k
{
889
722k
    xmlCharEncodingHandlerPtr handler;
890
722k
    int len = -1;
891
722k
    int ret;
892
893
722k
    if (ctxt == NULL) return(-1);
894
722k
    switch (enc) {
895
0
  case XML_CHAR_ENCODING_ERROR:
896
0
      __xmlErrEncoding(ctxt, XML_ERR_UNKNOWN_ENCODING,
897
0
                     "encoding unknown\n", NULL, NULL);
898
0
      return(-1);
899
134k
  case XML_CHAR_ENCODING_NONE:
900
      /* let's assume it's UTF-8 without the XML decl */
901
134k
      ctxt->charset = XML_CHAR_ENCODING_UTF8;
902
134k
      return(0);
903
556k
  case XML_CHAR_ENCODING_UTF8:
904
      /* default encoding, no conversion should be needed */
905
556k
      ctxt->charset = XML_CHAR_ENCODING_UTF8;
906
907
      /*
908
       * Errata on XML-1.0 June 20 2001
909
       * Specific handling of the Byte Order Mark for
910
       * UTF-8
911
       */
912
556k
      if ((ctxt->input != NULL) &&
913
556k
    (ctxt->input->cur[0] == 0xEF) &&
914
556k
    (ctxt->input->cur[1] == 0xBB) &&
915
556k
    (ctxt->input->cur[2] == 0xBF)) {
916
10.4k
    ctxt->input->cur += 3;
917
10.4k
      }
918
556k
      return(0);
919
14.6k
    case XML_CHAR_ENCODING_UTF16LE:
920
28.5k
    case XML_CHAR_ENCODING_UTF16BE:
921
        /*The raw input characters are encoded
922
         *in UTF-16. As we expect this function
923
         *to be called after xmlCharEncInFunc, we expect
924
         *ctxt->input->cur to contain UTF-8 encoded characters.
925
         *So the raw UTF16 Byte Order Mark
926
         *has also been converted into
927
         *an UTF-8 BOM. Let's skip that BOM.
928
         */
929
28.5k
        if ((ctxt->input != NULL) && (ctxt->input->cur != NULL) &&
930
28.5k
            (ctxt->input->cur[0] == 0xEF) &&
931
28.5k
            (ctxt->input->cur[1] == 0xBB) &&
932
28.5k
            (ctxt->input->cur[2] == 0xBF)) {
933
5.73k
            ctxt->input->cur += 3;
934
5.73k
        }
935
28.5k
        len = 90;
936
28.5k
  break;
937
0
    case XML_CHAR_ENCODING_UCS2:
938
0
        len = 90;
939
0
  break;
940
711
    case XML_CHAR_ENCODING_UCS4BE:
941
2.54k
    case XML_CHAR_ENCODING_UCS4LE:
942
2.71k
    case XML_CHAR_ENCODING_UCS4_2143:
943
2.88k
    case XML_CHAR_ENCODING_UCS4_3412:
944
2.88k
        len = 180;
945
2.88k
  break;
946
60
    case XML_CHAR_ENCODING_EBCDIC:
947
60
    case XML_CHAR_ENCODING_8859_1:
948
60
    case XML_CHAR_ENCODING_8859_2:
949
60
    case XML_CHAR_ENCODING_8859_3:
950
60
    case XML_CHAR_ENCODING_8859_4:
951
60
    case XML_CHAR_ENCODING_8859_5:
952
60
    case XML_CHAR_ENCODING_8859_6:
953
60
    case XML_CHAR_ENCODING_8859_7:
954
60
    case XML_CHAR_ENCODING_8859_8:
955
60
    case XML_CHAR_ENCODING_8859_9:
956
60
    case XML_CHAR_ENCODING_ASCII:
957
60
    case XML_CHAR_ENCODING_2022_JP:
958
60
    case XML_CHAR_ENCODING_SHIFT_JIS:
959
60
    case XML_CHAR_ENCODING_EUC_JP:
960
60
        len = 45;
961
60
  break;
962
722k
    }
963
31.5k
    handler = xmlGetCharEncodingHandler(enc);
964
31.5k
    if (handler == NULL) {
965
  /*
966
   * Default handlers.
967
   */
968
340
  switch (enc) {
969
0
      case XML_CHAR_ENCODING_ASCII:
970
    /* default encoding, no conversion should be needed */
971
0
    ctxt->charset = XML_CHAR_ENCODING_UTF8;
972
0
    return(0);
973
0
      case XML_CHAR_ENCODING_8859_1:
974
0
    if ((ctxt->inputNr == 1) &&
975
0
        (ctxt->encoding == NULL) &&
976
0
        (ctxt->input != NULL) &&
977
0
        (ctxt->input->encoding != NULL)) {
978
0
        ctxt->encoding = xmlStrdup(ctxt->input->encoding);
979
0
    }
980
0
    ctxt->charset = enc;
981
0
    return(0);
982
340
      default:
983
340
    __xmlErrEncoding(ctxt, XML_ERR_UNSUPPORTED_ENCODING,
984
340
                        "encoding not supported: %s\n",
985
340
      BAD_CAST xmlGetCharEncodingName(enc), NULL);
986
                /*
987
                 * TODO: We could recover from errors in external entities
988
                 * if we didn't stop the parser. But most callers of this
989
                 * function don't check the return value.
990
                 */
991
340
                xmlStopParser(ctxt);
992
340
                return(-1);
993
340
        }
994
340
    }
995
31.1k
    ret = xmlSwitchInputEncodingInt(ctxt, ctxt->input, handler, len);
996
31.1k
    if ((ret < 0) || (ctxt->errNo == XML_I18N_CONV_FAILED)) {
997
        /*
998
   * on encoding conversion errors, stop the parser
999
   */
1000
133
        xmlStopParser(ctxt);
1001
133
  ctxt->errNo = XML_I18N_CONV_FAILED;
1002
133
    }
1003
31.1k
    return(ret);
1004
31.5k
}
1005
1006
/**
1007
 * xmlSwitchInputEncodingInt:
1008
 * @ctxt:  the parser context
1009
 * @input:  the input stream
1010
 * @handler:  the encoding handler
1011
 * @len:  the number of bytes to convert for the first line or -1
1012
 *
1013
 * change the input functions when discovering the character encoding
1014
 * of a given entity.
1015
 *
1016
 * Returns 0 in case of success, -1 otherwise
1017
 */
1018
static int
1019
xmlSwitchInputEncodingInt(xmlParserCtxtPtr ctxt, xmlParserInputPtr input,
1020
                          xmlCharEncodingHandlerPtr handler, int len)
1021
78.2k
{
1022
78.2k
    int nbchars;
1023
1024
78.2k
    if (handler == NULL)
1025
0
        return (-1);
1026
78.2k
    if (input == NULL)
1027
0
        return (-1);
1028
78.2k
    if (input->buf != NULL) {
1029
78.2k
  ctxt->charset = XML_CHAR_ENCODING_UTF8;
1030
1031
78.2k
        if (input->buf->encoder != NULL) {
1032
            /*
1033
             * Check in case the auto encoding detection triggered
1034
             * in already.
1035
             */
1036
9.84k
            if (input->buf->encoder == handler)
1037
9.20k
                return (0);
1038
1039
            /*
1040
             * "UTF-16" can be used for both LE and BE
1041
             if ((!xmlStrncmp(BAD_CAST input->buf->encoder->name,
1042
             BAD_CAST "UTF-16", 6)) &&
1043
             (!xmlStrncmp(BAD_CAST handler->name,
1044
             BAD_CAST "UTF-16", 6))) {
1045
             return(0);
1046
             }
1047
             */
1048
1049
            /*
1050
             * Note: this is a bit dangerous, but that's what it
1051
             * takes to use nearly compatible signature for different
1052
             * encodings.
1053
             *
1054
             * FIXME: Encoders might buffer partial byte sequences, so
1055
             * this probably can't work. We should return an error and
1056
             * make sure that callers never try to switch the encoding
1057
             * twice.
1058
             */
1059
634
            xmlCharEncCloseFunc(input->buf->encoder);
1060
634
            input->buf->encoder = handler;
1061
634
            return (0);
1062
9.84k
        }
1063
68.4k
        input->buf->encoder = handler;
1064
1065
        /*
1066
         * Is there already some content down the pipe to convert ?
1067
         */
1068
68.4k
        if (xmlBufIsEmpty(input->buf->buffer) == 0) {
1069
68.4k
            int processed;
1070
68.4k
      unsigned int use;
1071
1072
            /*
1073
             * Specific handling of the Byte Order Mark for
1074
             * UTF-16
1075
             */
1076
68.4k
            if ((handler->name != NULL) &&
1077
68.4k
                (!strcmp(handler->name, "UTF-16LE") ||
1078
68.4k
                 !strcmp(handler->name, "UTF-16")) &&
1079
68.4k
                (input->cur[0] == 0xFF) && (input->cur[1] == 0xFE)) {
1080
4.29k
                input->cur += 2;
1081
4.29k
            }
1082
68.4k
            if ((handler->name != NULL) &&
1083
68.4k
                (!strcmp(handler->name, "UTF-16BE")) &&
1084
68.4k
                (input->cur[0] == 0xFE) && (input->cur[1] == 0xFF)) {
1085
7.76k
                input->cur += 2;
1086
7.76k
            }
1087
            /*
1088
             * Errata on XML-1.0 June 20 2001
1089
             * Specific handling of the Byte Order Mark for
1090
             * UTF-8
1091
             */
1092
68.4k
            if ((handler->name != NULL) &&
1093
68.4k
                (!strcmp(handler->name, "UTF-8")) &&
1094
68.4k
                (input->cur[0] == 0xEF) &&
1095
68.4k
                (input->cur[1] == 0xBB) && (input->cur[2] == 0xBF)) {
1096
0
                input->cur += 3;
1097
0
            }
1098
1099
            /*
1100
             * Shrink the current input buffer.
1101
             * Move it as the raw buffer and create a new input buffer
1102
             */
1103
68.4k
            processed = input->cur - input->base;
1104
68.4k
            xmlBufShrink(input->buf->buffer, processed);
1105
68.4k
            input->buf->raw = input->buf->buffer;
1106
68.4k
            input->buf->buffer = xmlBufCreate();
1107
68.4k
      input->buf->rawconsumed = processed;
1108
68.4k
      use = xmlBufUse(input->buf->raw);
1109
1110
68.4k
            if (ctxt->html) {
1111
                /*
1112
                 * convert as much as possible of the buffer
1113
                 */
1114
0
                nbchars = xmlCharEncInput(input->buf, 1);
1115
68.4k
            } else {
1116
                /*
1117
                 * convert just enough to get
1118
                 * '<?xml version="1.0" encoding="xxx"?>'
1119
                 * parsed with the autodetected encoding
1120
                 * into the parser reading buffer.
1121
                 */
1122
68.4k
                nbchars = xmlCharEncFirstLineInput(input->buf, len);
1123
68.4k
            }
1124
68.4k
            xmlBufResetInput(input->buf->buffer, input);
1125
68.4k
            if (nbchars < 0) {
1126
370
                xmlErrInternal(ctxt,
1127
370
                               "switching encoding: encoder error\n",
1128
370
                               NULL);
1129
370
                return (-1);
1130
370
            }
1131
68.0k
      input->buf->rawconsumed += use - xmlBufUse(input->buf->raw);
1132
68.0k
        }
1133
68.0k
        return (0);
1134
68.4k
    } else {
1135
0
  xmlErrInternal(ctxt,
1136
0
                "static memory buffer doesn't support encoding\n", NULL);
1137
        /*
1138
         * Callers assume that the input buffer takes ownership of the
1139
         * encoding handler. xmlCharEncCloseFunc frees unregistered
1140
         * handlers and avoids a memory leak.
1141
         */
1142
0
        xmlCharEncCloseFunc(handler);
1143
0
  return (-1);
1144
0
    }
1145
78.2k
}
1146
1147
/**
1148
 * xmlSwitchInputEncoding:
1149
 * @ctxt:  the parser context
1150
 * @input:  the input stream
1151
 * @handler:  the encoding handler
1152
 *
1153
 * DEPRECATED: Use xmlSwitchToEncoding
1154
 *
1155
 * change the input functions when discovering the character encoding
1156
 * of a given entity.
1157
 *
1158
 * Returns 0 in case of success, -1 otherwise
1159
 */
1160
int
1161
xmlSwitchInputEncoding(xmlParserCtxtPtr ctxt, xmlParserInputPtr input,
1162
0
                          xmlCharEncodingHandlerPtr handler) {
1163
0
    return(xmlSwitchInputEncodingInt(ctxt, input, handler, -1));
1164
0
}
1165
1166
/**
1167
 * xmlSwitchToEncoding:
1168
 * @ctxt:  the parser context
1169
 * @handler:  the encoding handler
1170
 *
1171
 * change the input functions when discovering the character encoding
1172
 * of a given entity.
1173
 *
1174
 * Returns 0 in case of success, -1 otherwise
1175
 */
1176
int
1177
xmlSwitchToEncoding(xmlParserCtxtPtr ctxt, xmlCharEncodingHandlerPtr handler)
1178
47.1k
{
1179
47.1k
    if (ctxt == NULL)
1180
0
        return(-1);
1181
47.1k
    return(xmlSwitchInputEncodingInt(ctxt, ctxt->input, handler, -1));
1182
47.1k
}
1183
1184
/************************************************************************
1185
 *                  *
1186
 *  Commodity functions to handle entities processing   *
1187
 *                  *
1188
 ************************************************************************/
1189
1190
/**
1191
 * xmlFreeInputStream:
1192
 * @input:  an xmlParserInputPtr
1193
 *
1194
 * Free up an input stream.
1195
 */
1196
void
1197
2.05M
xmlFreeInputStream(xmlParserInputPtr input) {
1198
2.05M
    if (input == NULL) return;
1199
1200
2.05M
    if (input->filename != NULL) xmlFree((char *) input->filename);
1201
2.05M
    if (input->directory != NULL) xmlFree((char *) input->directory);
1202
2.05M
    if (input->encoding != NULL) xmlFree((char *) input->encoding);
1203
2.05M
    if (input->version != NULL) xmlFree((char *) input->version);
1204
2.05M
    if ((input->free != NULL) && (input->base != NULL))
1205
0
        input->free((xmlChar *) input->base);
1206
2.05M
    if (input->buf != NULL)
1207
798k
        xmlFreeParserInputBuffer(input->buf);
1208
2.05M
    xmlFree(input);
1209
2.05M
}
1210
1211
/**
1212
 * xmlNewInputStream:
1213
 * @ctxt:  an XML parser context
1214
 *
1215
 * Create a new input stream structure.
1216
 *
1217
 * Returns the new input stream or NULL
1218
 */
1219
xmlParserInputPtr
1220
2.05M
xmlNewInputStream(xmlParserCtxtPtr ctxt) {
1221
2.05M
    xmlParserInputPtr input;
1222
1223
2.05M
    input = (xmlParserInputPtr) xmlMalloc(sizeof(xmlParserInput));
1224
2.05M
    if (input == NULL) {
1225
0
        xmlErrMemory(ctxt,  "couldn't allocate a new input stream\n");
1226
0
  return(NULL);
1227
0
    }
1228
2.05M
    memset(input, 0, sizeof(xmlParserInput));
1229
2.05M
    input->line = 1;
1230
2.05M
    input->col = 1;
1231
2.05M
    input->standalone = -1;
1232
1233
    /*
1234
     * If the context is NULL the id cannot be initialized, but that
1235
     * should not happen while parsing which is the situation where
1236
     * the id is actually needed.
1237
     */
1238
2.05M
    if (ctxt != NULL)
1239
2.05M
        input->id = ctxt->input_id++;
1240
1241
2.05M
    return(input);
1242
2.05M
}
1243
1244
/**
1245
 * xmlNewIOInputStream:
1246
 * @ctxt:  an XML parser context
1247
 * @input:  an I/O Input
1248
 * @enc:  the charset encoding if known
1249
 *
1250
 * Create a new input stream structure encapsulating the @input into
1251
 * a stream suitable for the parser.
1252
 *
1253
 * Returns the new input stream or NULL
1254
 */
1255
xmlParserInputPtr
1256
xmlNewIOInputStream(xmlParserCtxtPtr ctxt, xmlParserInputBufferPtr input,
1257
0
              xmlCharEncoding enc) {
1258
0
    xmlParserInputPtr inputStream;
1259
1260
0
    if (input == NULL) return(NULL);
1261
0
    if (xmlParserDebugEntities)
1262
0
  xmlGenericError(xmlGenericErrorContext, "new input from I/O\n");
1263
0
    inputStream = xmlNewInputStream(ctxt);
1264
0
    if (inputStream == NULL) {
1265
0
  return(NULL);
1266
0
    }
1267
0
    inputStream->filename = NULL;
1268
0
    inputStream->buf = input;
1269
0
    xmlBufResetInput(inputStream->buf->buffer, inputStream);
1270
1271
0
    if (enc != XML_CHAR_ENCODING_NONE) {
1272
0
        xmlSwitchEncoding(ctxt, enc);
1273
0
    }
1274
1275
0
    return(inputStream);
1276
0
}
1277
1278
/**
1279
 * xmlNewEntityInputStream:
1280
 * @ctxt:  an XML parser context
1281
 * @entity:  an Entity pointer
1282
 *
1283
 * Create a new input stream based on an xmlEntityPtr
1284
 *
1285
 * Returns the new input stream or NULL
1286
 */
1287
xmlParserInputPtr
1288
528k
xmlNewEntityInputStream(xmlParserCtxtPtr ctxt, xmlEntityPtr entity) {
1289
528k
    xmlParserInputPtr input;
1290
1291
528k
    if (entity == NULL) {
1292
0
        xmlErrInternal(ctxt, "xmlNewEntityInputStream entity = NULL\n",
1293
0
                 NULL);
1294
0
  return(NULL);
1295
0
    }
1296
528k
    if (xmlParserDebugEntities)
1297
0
  xmlGenericError(xmlGenericErrorContext,
1298
0
    "new input from entity: %s\n", entity->name);
1299
528k
    if (entity->content == NULL) {
1300
126k
  switch (entity->etype) {
1301
0
            case XML_EXTERNAL_GENERAL_UNPARSED_ENTITY:
1302
0
          xmlErrInternal(ctxt, "Cannot parse entity %s\n",
1303
0
                   entity->name);
1304
0
                break;
1305
0
            case XML_EXTERNAL_GENERAL_PARSED_ENTITY:
1306
126k
            case XML_EXTERNAL_PARAMETER_ENTITY:
1307
126k
    return(xmlLoadExternalEntity((char *) entity->URI,
1308
126k
           (char *) entity->ExternalID, ctxt));
1309
0
            case XML_INTERNAL_GENERAL_ENTITY:
1310
0
          xmlErrInternal(ctxt,
1311
0
          "Internal entity %s without content !\n",
1312
0
                   entity->name);
1313
0
                break;
1314
0
            case XML_INTERNAL_PARAMETER_ENTITY:
1315
0
          xmlErrInternal(ctxt,
1316
0
          "Internal parameter entity %s without content !\n",
1317
0
                   entity->name);
1318
0
                break;
1319
0
            case XML_INTERNAL_PREDEFINED_ENTITY:
1320
0
          xmlErrInternal(ctxt,
1321
0
          "Predefined entity %s without content !\n",
1322
0
                   entity->name);
1323
0
                break;
1324
126k
  }
1325
0
  return(NULL);
1326
126k
    }
1327
401k
    input = xmlNewInputStream(ctxt);
1328
401k
    if (input == NULL) {
1329
0
  return(NULL);
1330
0
    }
1331
401k
    if (entity->URI != NULL)
1332
3
  input->filename = (char *) xmlStrdup((xmlChar *) entity->URI);
1333
401k
    input->base = entity->content;
1334
401k
    if (entity->length == 0)
1335
53
        entity->length = xmlStrlen(entity->content);
1336
401k
    input->cur = entity->content;
1337
401k
    input->length = entity->length;
1338
401k
    input->end = &entity->content[input->length];
1339
401k
    return(input);
1340
401k
}
1341
1342
/**
1343
 * xmlNewStringInputStream:
1344
 * @ctxt:  an XML parser context
1345
 * @buffer:  an memory buffer
1346
 *
1347
 * Create a new input stream based on a memory buffer.
1348
 * Returns the new input stream
1349
 */
1350
xmlParserInputPtr
1351
0
xmlNewStringInputStream(xmlParserCtxtPtr ctxt, const xmlChar *buffer) {
1352
0
    xmlParserInputPtr input;
1353
0
    xmlParserInputBufferPtr buf;
1354
1355
0
    if (buffer == NULL) {
1356
0
        xmlErrInternal(ctxt, "xmlNewStringInputStream string = NULL\n",
1357
0
                 NULL);
1358
0
  return(NULL);
1359
0
    }
1360
0
    if (xmlParserDebugEntities)
1361
0
  xmlGenericError(xmlGenericErrorContext,
1362
0
    "new fixed input: %.30s\n", buffer);
1363
0
    buf = xmlParserInputBufferCreateMem((const char *) buffer,
1364
0
                                        xmlStrlen(buffer),
1365
0
                                        XML_CHAR_ENCODING_NONE);
1366
0
    if (buf == NULL) {
1367
0
  xmlErrMemory(ctxt, NULL);
1368
0
        return(NULL);
1369
0
    }
1370
0
    input = xmlNewInputStream(ctxt);
1371
0
    if (input == NULL) {
1372
0
        xmlErrMemory(ctxt,  "couldn't allocate a new input stream\n");
1373
0
  xmlFreeParserInputBuffer(buf);
1374
0
  return(NULL);
1375
0
    }
1376
0
    input->buf = buf;
1377
0
    xmlBufResetInput(input->buf->buffer, input);
1378
0
    return(input);
1379
0
}
1380
1381
/**
1382
 * xmlNewInputFromFile:
1383
 * @ctxt:  an XML parser context
1384
 * @filename:  the filename to use as entity
1385
 *
1386
 * Create a new input stream based on a file or an URL.
1387
 *
1388
 * Returns the new input stream or NULL in case of error
1389
 */
1390
xmlParserInputPtr
1391
0
xmlNewInputFromFile(xmlParserCtxtPtr ctxt, const char *filename) {
1392
0
    xmlParserInputBufferPtr buf;
1393
0
    xmlParserInputPtr inputStream;
1394
0
    char *directory = NULL;
1395
0
    xmlChar *URI = NULL;
1396
1397
0
    if (xmlParserDebugEntities)
1398
0
  xmlGenericError(xmlGenericErrorContext,
1399
0
    "new input from file: %s\n", filename);
1400
0
    if (ctxt == NULL) return(NULL);
1401
0
    buf = xmlParserInputBufferCreateFilename(filename, XML_CHAR_ENCODING_NONE);
1402
0
    if (buf == NULL) {
1403
0
  if (filename == NULL)
1404
0
      __xmlLoaderErr(ctxt,
1405
0
                     "failed to load external entity: NULL filename \n",
1406
0
         NULL);
1407
0
  else
1408
0
      __xmlLoaderErr(ctxt, "failed to load external entity \"%s\"\n",
1409
0
         (const char *) filename);
1410
0
  return(NULL);
1411
0
    }
1412
1413
0
    inputStream = xmlNewInputStream(ctxt);
1414
0
    if (inputStream == NULL) {
1415
0
  xmlFreeParserInputBuffer(buf);
1416
0
  return(NULL);
1417
0
    }
1418
1419
0
    inputStream->buf = buf;
1420
0
    inputStream = xmlCheckHTTPInput(ctxt, inputStream);
1421
0
    if (inputStream == NULL)
1422
0
        return(NULL);
1423
1424
0
    if (inputStream->filename == NULL)
1425
0
  URI = xmlStrdup((xmlChar *) filename);
1426
0
    else
1427
0
  URI = xmlStrdup((xmlChar *) inputStream->filename);
1428
0
    directory = xmlParserGetDirectory((const char *) URI);
1429
0
    if (inputStream->filename != NULL) xmlFree((char *)inputStream->filename);
1430
0
    inputStream->filename = (char *) xmlCanonicPath((const xmlChar *) URI);
1431
0
    if (URI != NULL) xmlFree((char *) URI);
1432
0
    inputStream->directory = directory;
1433
1434
0
    xmlBufResetInput(inputStream->buf->buffer, inputStream);
1435
0
    if ((ctxt->directory == NULL) && (directory != NULL))
1436
0
        ctxt->directory = (char *) xmlStrdup((const xmlChar *) directory);
1437
0
    return(inputStream);
1438
0
}
1439
1440
/************************************************************************
1441
 *                  *
1442
 *    Commodity functions to handle parser contexts   *
1443
 *                  *
1444
 ************************************************************************/
1445
1446
/**
1447
 * xmlInitSAXParserCtxt:
1448
 * @ctxt:  XML parser context
1449
 * @sax:  SAX handlert
1450
 * @userData:  user data
1451
 *
1452
 * Initialize a SAX parser context
1453
 *
1454
 * Returns 0 in case of success and -1 in case of error
1455
 */
1456
1457
static int
1458
xmlInitSAXParserCtxt(xmlParserCtxtPtr ctxt, const xmlSAXHandler *sax,
1459
                     void *userData)
1460
1.65M
{
1461
1.65M
    xmlParserInputPtr input;
1462
1463
1.65M
    if(ctxt==NULL) {
1464
0
        xmlErrInternal(NULL, "Got NULL parser context\n", NULL);
1465
0
        return(-1);
1466
0
    }
1467
1468
1.65M
    xmlInitParser();
1469
1470
1.65M
    if (ctxt->dict == NULL)
1471
1.65M
  ctxt->dict = xmlDictCreate();
1472
1.65M
    if (ctxt->dict == NULL) {
1473
0
        xmlErrMemory(NULL, "cannot initialize parser context\n");
1474
0
  return(-1);
1475
0
    }
1476
1.65M
    xmlDictSetLimit(ctxt->dict, XML_MAX_DICTIONARY_LIMIT);
1477
1478
1.65M
    if (ctxt->sax == NULL)
1479
1.65M
  ctxt->sax = (xmlSAXHandler *) xmlMalloc(sizeof(xmlSAXHandler));
1480
1.65M
    if (ctxt->sax == NULL) {
1481
0
        xmlErrMemory(NULL, "cannot initialize parser context\n");
1482
0
  return(-1);
1483
0
    }
1484
1.65M
    if (sax == NULL) {
1485
905k
  memset(ctxt->sax, 0, sizeof(xmlSAXHandler));
1486
905k
        xmlSAXVersion(ctxt->sax, 2);
1487
905k
        ctxt->userData = ctxt;
1488
905k
    } else {
1489
750k
  if (sax->initialized == XML_SAX2_MAGIC) {
1490
556k
      memcpy(ctxt->sax, sax, sizeof(xmlSAXHandler));
1491
556k
        } else {
1492
194k
      memset(ctxt->sax, 0, sizeof(xmlSAXHandler));
1493
194k
      memcpy(ctxt->sax, sax, sizeof(xmlSAXHandlerV1));
1494
194k
        }
1495
750k
        ctxt->userData = userData ? userData : ctxt;
1496
750k
    }
1497
1498
1.65M
    ctxt->maxatts = 0;
1499
1.65M
    ctxt->atts = NULL;
1500
    /* Allocate the Input stack */
1501
1.65M
    if (ctxt->inputTab == NULL) {
1502
1.65M
  ctxt->inputTab = (xmlParserInputPtr *)
1503
1.65M
        xmlMalloc(5 * sizeof(xmlParserInputPtr));
1504
1.65M
  ctxt->inputMax = 5;
1505
1.65M
    }
1506
1.65M
    if (ctxt->inputTab == NULL) {
1507
0
        xmlErrMemory(NULL, "cannot initialize parser context\n");
1508
0
  ctxt->inputNr = 0;
1509
0
  ctxt->inputMax = 0;
1510
0
  ctxt->input = NULL;
1511
0
  return(-1);
1512
0
    }
1513
1.65M
    while ((input = inputPop(ctxt)) != NULL) { /* Non consuming */
1514
0
        xmlFreeInputStream(input);
1515
0
    }
1516
1.65M
    ctxt->inputNr = 0;
1517
1.65M
    ctxt->input = NULL;
1518
1519
1.65M
    ctxt->version = NULL;
1520
1.65M
    ctxt->encoding = NULL;
1521
1.65M
    ctxt->standalone = -1;
1522
1.65M
    ctxt->hasExternalSubset = 0;
1523
1.65M
    ctxt->hasPErefs = 0;
1524
1.65M
    ctxt->html = 0;
1525
1.65M
    ctxt->external = 0;
1526
1.65M
    ctxt->instate = XML_PARSER_START;
1527
1.65M
    ctxt->token = 0;
1528
1.65M
    ctxt->directory = NULL;
1529
1530
    /* Allocate the Node stack */
1531
1.65M
    if (ctxt->nodeTab == NULL) {
1532
1.65M
  ctxt->nodeTab = (xmlNodePtr *) xmlMalloc(10 * sizeof(xmlNodePtr));
1533
1.65M
  ctxt->nodeMax = 10;
1534
1.65M
    }
1535
1.65M
    if (ctxt->nodeTab == NULL) {
1536
0
        xmlErrMemory(NULL, "cannot initialize parser context\n");
1537
0
  ctxt->nodeNr = 0;
1538
0
  ctxt->nodeMax = 0;
1539
0
  ctxt->node = NULL;
1540
0
  ctxt->inputNr = 0;
1541
0
  ctxt->inputMax = 0;
1542
0
  ctxt->input = NULL;
1543
0
  return(-1);
1544
0
    }
1545
1.65M
    ctxt->nodeNr = 0;
1546
1.65M
    ctxt->node = NULL;
1547
1548
    /* Allocate the Name stack */
1549
1.65M
    if (ctxt->nameTab == NULL) {
1550
1.65M
  ctxt->nameTab = (const xmlChar **) xmlMalloc(10 * sizeof(xmlChar *));
1551
1.65M
  ctxt->nameMax = 10;
1552
1.65M
    }
1553
1.65M
    if (ctxt->nameTab == NULL) {
1554
0
        xmlErrMemory(NULL, "cannot initialize parser context\n");
1555
0
  ctxt->nodeNr = 0;
1556
0
  ctxt->nodeMax = 0;
1557
0
  ctxt->node = NULL;
1558
0
  ctxt->inputNr = 0;
1559
0
  ctxt->inputMax = 0;
1560
0
  ctxt->input = NULL;
1561
0
  ctxt->nameNr = 0;
1562
0
  ctxt->nameMax = 0;
1563
0
  ctxt->name = NULL;
1564
0
  return(-1);
1565
0
    }
1566
1.65M
    ctxt->nameNr = 0;
1567
1.65M
    ctxt->name = NULL;
1568
1569
    /* Allocate the space stack */
1570
1.65M
    if (ctxt->spaceTab == NULL) {
1571
1.65M
  ctxt->spaceTab = (int *) xmlMalloc(10 * sizeof(int));
1572
1.65M
  ctxt->spaceMax = 10;
1573
1.65M
    }
1574
1.65M
    if (ctxt->spaceTab == NULL) {
1575
0
        xmlErrMemory(NULL, "cannot initialize parser context\n");
1576
0
  ctxt->nodeNr = 0;
1577
0
  ctxt->nodeMax = 0;
1578
0
  ctxt->node = NULL;
1579
0
  ctxt->inputNr = 0;
1580
0
  ctxt->inputMax = 0;
1581
0
  ctxt->input = NULL;
1582
0
  ctxt->nameNr = 0;
1583
0
  ctxt->nameMax = 0;
1584
0
  ctxt->name = NULL;
1585
0
  ctxt->spaceNr = 0;
1586
0
  ctxt->spaceMax = 0;
1587
0
  ctxt->space = NULL;
1588
0
  return(-1);
1589
0
    }
1590
1.65M
    ctxt->spaceNr = 1;
1591
1.65M
    ctxt->spaceMax = 10;
1592
1.65M
    ctxt->spaceTab[0] = -1;
1593
1.65M
    ctxt->space = &ctxt->spaceTab[0];
1594
1.65M
    ctxt->myDoc = NULL;
1595
1.65M
    ctxt->wellFormed = 1;
1596
1.65M
    ctxt->nsWellFormed = 1;
1597
1.65M
    ctxt->valid = 1;
1598
1.65M
    ctxt->loadsubset = xmlLoadExtDtdDefaultValue;
1599
1.65M
    if (ctxt->loadsubset) {
1600
0
        ctxt->options |= XML_PARSE_DTDLOAD;
1601
0
    }
1602
1.65M
    ctxt->validate = xmlDoValidityCheckingDefaultValue;
1603
1.65M
    ctxt->pedantic = xmlPedanticParserDefaultValue;
1604
1.65M
    if (ctxt->pedantic) {
1605
0
        ctxt->options |= XML_PARSE_PEDANTIC;
1606
0
    }
1607
1.65M
    ctxt->linenumbers = xmlLineNumbersDefaultValue;
1608
1.65M
    ctxt->keepBlanks = xmlKeepBlanksDefaultValue;
1609
1.65M
    if (ctxt->keepBlanks == 0) {
1610
0
  ctxt->sax->ignorableWhitespace = xmlSAX2IgnorableWhitespace;
1611
0
  ctxt->options |= XML_PARSE_NOBLANKS;
1612
0
    }
1613
1614
1.65M
    ctxt->vctxt.flags = XML_VCTXT_USE_PCTXT;
1615
1.65M
    ctxt->vctxt.userData = ctxt;
1616
1.65M
    ctxt->vctxt.error = xmlParserValidityError;
1617
1.65M
    ctxt->vctxt.warning = xmlParserValidityWarning;
1618
1.65M
    if (ctxt->validate) {
1619
0
  if (xmlGetWarningsDefaultValue == 0)
1620
0
      ctxt->vctxt.warning = NULL;
1621
0
  else
1622
0
      ctxt->vctxt.warning = xmlParserValidityWarning;
1623
0
  ctxt->vctxt.nodeMax = 0;
1624
0
        ctxt->options |= XML_PARSE_DTDVALID;
1625
0
    }
1626
1.65M
    ctxt->replaceEntities = xmlSubstituteEntitiesDefaultValue;
1627
1.65M
    if (ctxt->replaceEntities) {
1628
0
        ctxt->options |= XML_PARSE_NOENT;
1629
0
    }
1630
1.65M
    ctxt->record_info = 0;
1631
1.65M
    ctxt->checkIndex = 0;
1632
1.65M
    ctxt->inSubset = 0;
1633
1.65M
    ctxt->errNo = XML_ERR_OK;
1634
1.65M
    ctxt->depth = 0;
1635
1.65M
    ctxt->charset = XML_CHAR_ENCODING_UTF8;
1636
1.65M
    ctxt->catalogs = NULL;
1637
1.65M
    ctxt->nbentities = 0;
1638
1.65M
    ctxt->sizeentities = 0;
1639
1.65M
    ctxt->sizeentcopy = 0;
1640
1.65M
    ctxt->input_id = 1;
1641
1.65M
    xmlInitNodeInfoSeq(&ctxt->node_seq);
1642
1.65M
    return(0);
1643
1.65M
}
1644
1645
/**
1646
 * xmlInitParserCtxt:
1647
 * @ctxt:  an XML parser context
1648
 *
1649
 * DEPRECATED: Internal function which will be made private in a future
1650
 * version.
1651
 *
1652
 * Initialize a parser context
1653
 *
1654
 * Returns 0 in case of success and -1 in case of error
1655
 */
1656
1657
int
1658
xmlInitParserCtxt(xmlParserCtxtPtr ctxt)
1659
0
{
1660
0
    return(xmlInitSAXParserCtxt(ctxt, NULL, NULL));
1661
0
}
1662
1663
/**
1664
 * xmlFreeParserCtxt:
1665
 * @ctxt:  an XML parser context
1666
 *
1667
 * Free all the memory used by a parser context. However the parsed
1668
 * document in ctxt->myDoc is not freed.
1669
 */
1670
1671
void
1672
xmlFreeParserCtxt(xmlParserCtxtPtr ctxt)
1673
1.65M
{
1674
1.65M
    xmlParserInputPtr input;
1675
1676
1.65M
    if (ctxt == NULL) return;
1677
1678
3.15M
    while ((input = inputPop(ctxt)) != NULL) { /* Non consuming */
1679
1.49M
        xmlFreeInputStream(input);
1680
1.49M
    }
1681
1.65M
    if (ctxt->spaceTab != NULL) xmlFree(ctxt->spaceTab);
1682
1.65M
    if (ctxt->nameTab != NULL) xmlFree((xmlChar * *)ctxt->nameTab);
1683
1.65M
    if (ctxt->nodeTab != NULL) xmlFree(ctxt->nodeTab);
1684
1.65M
    if (ctxt->nodeInfoTab != NULL) xmlFree(ctxt->nodeInfoTab);
1685
1.65M
    if (ctxt->inputTab != NULL) xmlFree(ctxt->inputTab);
1686
1.65M
    if (ctxt->version != NULL) xmlFree((char *) ctxt->version);
1687
1.65M
    if (ctxt->encoding != NULL) xmlFree((char *) ctxt->encoding);
1688
1.65M
    if (ctxt->extSubURI != NULL) xmlFree((char *) ctxt->extSubURI);
1689
1.65M
    if (ctxt->extSubSystem != NULL) xmlFree((char *) ctxt->extSubSystem);
1690
1.65M
#ifdef LIBXML_SAX1_ENABLED
1691
1.65M
    if ((ctxt->sax != NULL) &&
1692
1.65M
        (ctxt->sax != (xmlSAXHandlerPtr) &xmlDefaultSAXHandler))
1693
#else
1694
    if (ctxt->sax != NULL)
1695
#endif /* LIBXML_SAX1_ENABLED */
1696
1.65M
        xmlFree(ctxt->sax);
1697
1.65M
    if (ctxt->directory != NULL) xmlFree((char *) ctxt->directory);
1698
1.65M
    if (ctxt->vctxt.nodeTab != NULL) xmlFree(ctxt->vctxt.nodeTab);
1699
1.65M
    if (ctxt->atts != NULL) xmlFree((xmlChar * *)ctxt->atts);
1700
1.65M
    if (ctxt->dict != NULL) xmlDictFree(ctxt->dict);
1701
1.65M
    if (ctxt->nsTab != NULL) xmlFree((char *) ctxt->nsTab);
1702
1.65M
    if (ctxt->pushTab != NULL) xmlFree(ctxt->pushTab);
1703
1.65M
    if (ctxt->attallocs != NULL) xmlFree(ctxt->attallocs);
1704
1.65M
    if (ctxt->attsDefault != NULL)
1705
23.2k
        xmlHashFree(ctxt->attsDefault, xmlHashDefaultDeallocator);
1706
1.65M
    if (ctxt->attsSpecial != NULL)
1707
46.1k
        xmlHashFree(ctxt->attsSpecial, NULL);
1708
1.65M
    if (ctxt->freeElems != NULL) {
1709
182k
        xmlNodePtr cur, next;
1710
1711
182k
  cur = ctxt->freeElems;
1712
365k
  while (cur != NULL) {
1713
182k
      next = cur->next;
1714
182k
      xmlFree(cur);
1715
182k
      cur = next;
1716
182k
  }
1717
182k
    }
1718
1.65M
    if (ctxt->freeAttrs != NULL) {
1719
105k
        xmlAttrPtr cur, next;
1720
1721
105k
  cur = ctxt->freeAttrs;
1722
211k
  while (cur != NULL) {
1723
105k
      next = cur->next;
1724
105k
      xmlFree(cur);
1725
105k
      cur = next;
1726
105k
  }
1727
105k
    }
1728
    /*
1729
     * cleanup the error strings
1730
     */
1731
1.65M
    if (ctxt->lastError.message != NULL)
1732
1.43M
        xmlFree(ctxt->lastError.message);
1733
1.65M
    if (ctxt->lastError.file != NULL)
1734
629k
        xmlFree(ctxt->lastError.file);
1735
1.65M
    if (ctxt->lastError.str1 != NULL)
1736
486k
        xmlFree(ctxt->lastError.str1);
1737
1.65M
    if (ctxt->lastError.str2 != NULL)
1738
38.9k
        xmlFree(ctxt->lastError.str2);
1739
1.65M
    if (ctxt->lastError.str3 != NULL)
1740
2.26k
        xmlFree(ctxt->lastError.str3);
1741
1742
1.65M
#ifdef LIBXML_CATALOG_ENABLED
1743
1.65M
    if (ctxt->catalogs != NULL)
1744
0
  xmlCatalogFreeLocal(ctxt->catalogs);
1745
1.65M
#endif
1746
1.65M
    xmlFree(ctxt);
1747
1.65M
}
1748
1749
/**
1750
 * xmlNewParserCtxt:
1751
 *
1752
 * Allocate and initialize a new parser context.
1753
 *
1754
 * Returns the xmlParserCtxtPtr or NULL
1755
 */
1756
1757
xmlParserCtxtPtr
1758
xmlNewParserCtxt(void)
1759
583k
{
1760
583k
    return(xmlNewSAXParserCtxt(NULL, NULL));
1761
583k
}
1762
1763
/**
1764
 * xmlNewSAXParserCtxt:
1765
 * @sax:  SAX handler
1766
 * @userData:  user data
1767
 *
1768
 * Allocate and initialize a new SAX parser context. If userData is NULL,
1769
 * the parser context will be passed as user data.
1770
 *
1771
 * Returns the xmlParserCtxtPtr or NULL if memory allocation failed.
1772
 */
1773
1774
xmlParserCtxtPtr
1775
xmlNewSAXParserCtxt(const xmlSAXHandler *sax, void *userData)
1776
1.65M
{
1777
1.65M
    xmlParserCtxtPtr ctxt;
1778
1779
1.65M
    ctxt = (xmlParserCtxtPtr) xmlMalloc(sizeof(xmlParserCtxt));
1780
1.65M
    if (ctxt == NULL) {
1781
0
  xmlErrMemory(NULL, "cannot allocate parser context\n");
1782
0
  return(NULL);
1783
0
    }
1784
1.65M
    memset(ctxt, 0, sizeof(xmlParserCtxt));
1785
1.65M
    if (xmlInitSAXParserCtxt(ctxt, sax, userData) < 0) {
1786
0
        xmlFreeParserCtxt(ctxt);
1787
0
  return(NULL);
1788
0
    }
1789
1.65M
    return(ctxt);
1790
1.65M
}
1791
1792
/************************************************************************
1793
 *                  *
1794
 *    Handling of node information        *
1795
 *                  *
1796
 ************************************************************************/
1797
1798
/**
1799
 * xmlClearParserCtxt:
1800
 * @ctxt:  an XML parser context
1801
 *
1802
 * Clear (release owned resources) and reinitialize a parser context
1803
 */
1804
1805
void
1806
xmlClearParserCtxt(xmlParserCtxtPtr ctxt)
1807
0
{
1808
0
  if (ctxt==NULL)
1809
0
    return;
1810
0
  xmlClearNodeInfoSeq(&ctxt->node_seq);
1811
0
  xmlCtxtReset(ctxt);
1812
0
}
1813
1814
1815
/**
1816
 * xmlParserFindNodeInfo:
1817
 * @ctx:  an XML parser context
1818
 * @node:  an XML node within the tree
1819
 *
1820
 * DEPRECATED: Don't use.
1821
 *
1822
 * Find the parser node info struct for a given node
1823
 *
1824
 * Returns an xmlParserNodeInfo block pointer or NULL
1825
 */
1826
const xmlParserNodeInfo *
1827
xmlParserFindNodeInfo(const xmlParserCtxtPtr ctx, const xmlNodePtr node)
1828
0
{
1829
0
    unsigned long pos;
1830
1831
0
    if ((ctx == NULL) || (node == NULL))
1832
0
        return (NULL);
1833
    /* Find position where node should be at */
1834
0
    pos = xmlParserFindNodeInfoIndex(&ctx->node_seq, node);
1835
0
    if (pos < ctx->node_seq.length
1836
0
        && ctx->node_seq.buffer[pos].node == node)
1837
0
        return &ctx->node_seq.buffer[pos];
1838
0
    else
1839
0
        return NULL;
1840
0
}
1841
1842
1843
/**
1844
 * xmlInitNodeInfoSeq:
1845
 * @seq:  a node info sequence pointer
1846
 *
1847
 * DEPRECATED: Don't use.
1848
 *
1849
 * -- Initialize (set to initial state) node info sequence
1850
 */
1851
void
1852
xmlInitNodeInfoSeq(xmlParserNodeInfoSeqPtr seq)
1853
1.65M
{
1854
1.65M
    if (seq == NULL)
1855
0
        return;
1856
1.65M
    seq->length = 0;
1857
1.65M
    seq->maximum = 0;
1858
1.65M
    seq->buffer = NULL;
1859
1.65M
}
1860
1861
/**
1862
 * xmlClearNodeInfoSeq:
1863
 * @seq:  a node info sequence pointer
1864
 *
1865
 * DEPRECATED: Don't use.
1866
 *
1867
 * -- Clear (release memory and reinitialize) node
1868
 *   info sequence
1869
 */
1870
void
1871
xmlClearNodeInfoSeq(xmlParserNodeInfoSeqPtr seq)
1872
0
{
1873
0
    if (seq == NULL)
1874
0
        return;
1875
0
    if (seq->buffer != NULL)
1876
0
        xmlFree(seq->buffer);
1877
0
    xmlInitNodeInfoSeq(seq);
1878
0
}
1879
1880
/**
1881
 * xmlParserFindNodeInfoIndex:
1882
 * @seq:  a node info sequence pointer
1883
 * @node:  an XML node pointer
1884
 *
1885
 * DEPRECATED: Don't use.
1886
 *
1887
 * xmlParserFindNodeInfoIndex : Find the index that the info record for
1888
 *   the given node is or should be at in a sorted sequence
1889
 *
1890
 * Returns a long indicating the position of the record
1891
 */
1892
unsigned long
1893
xmlParserFindNodeInfoIndex(const xmlParserNodeInfoSeqPtr seq,
1894
                           const xmlNodePtr node)
1895
0
{
1896
0
    unsigned long upper, lower, middle;
1897
0
    int found = 0;
1898
1899
0
    if ((seq == NULL) || (node == NULL))
1900
0
        return ((unsigned long) -1);
1901
1902
    /* Do a binary search for the key */
1903
0
    lower = 1;
1904
0
    upper = seq->length;
1905
0
    middle = 0;
1906
0
    while (lower <= upper && !found) {
1907
0
        middle = lower + (upper - lower) / 2;
1908
0
        if (node == seq->buffer[middle - 1].node)
1909
0
            found = 1;
1910
0
        else if (node < seq->buffer[middle - 1].node)
1911
0
            upper = middle - 1;
1912
0
        else
1913
0
            lower = middle + 1;
1914
0
    }
1915
1916
    /* Return position */
1917
0
    if (middle == 0 || seq->buffer[middle - 1].node < node)
1918
0
        return middle;
1919
0
    else
1920
0
        return middle - 1;
1921
0
}
1922
1923
1924
/**
1925
 * xmlParserAddNodeInfo:
1926
 * @ctxt:  an XML parser context
1927
 * @info:  a node info sequence pointer
1928
 *
1929
 * DEPRECATED: Don't use.
1930
 *
1931
 * Insert node info record into the sorted sequence
1932
 */
1933
void
1934
xmlParserAddNodeInfo(xmlParserCtxtPtr ctxt,
1935
                     const xmlParserNodeInfoPtr info)
1936
0
{
1937
0
    unsigned long pos;
1938
1939
0
    if ((ctxt == NULL) || (info == NULL)) return;
1940
1941
    /* Find pos and check to see if node is already in the sequence */
1942
0
    pos = xmlParserFindNodeInfoIndex(&ctxt->node_seq, (xmlNodePtr)
1943
0
                                     info->node);
1944
1945
0
    if ((pos < ctxt->node_seq.length) &&
1946
0
        (ctxt->node_seq.buffer != NULL) &&
1947
0
        (ctxt->node_seq.buffer[pos].node == info->node)) {
1948
0
        ctxt->node_seq.buffer[pos] = *info;
1949
0
    }
1950
1951
    /* Otherwise, we need to add new node to buffer */
1952
0
    else {
1953
0
        if ((ctxt->node_seq.length + 1 > ctxt->node_seq.maximum) ||
1954
0
      (ctxt->node_seq.buffer == NULL)) {
1955
0
            xmlParserNodeInfo *tmp_buffer;
1956
0
            unsigned int byte_size;
1957
1958
0
            if (ctxt->node_seq.maximum == 0)
1959
0
                ctxt->node_seq.maximum = 2;
1960
0
            byte_size = (sizeof(*ctxt->node_seq.buffer) *
1961
0
      (2 * ctxt->node_seq.maximum));
1962
1963
0
            if (ctxt->node_seq.buffer == NULL)
1964
0
                tmp_buffer = (xmlParserNodeInfo *) xmlMalloc(byte_size);
1965
0
            else
1966
0
                tmp_buffer =
1967
0
                    (xmlParserNodeInfo *) xmlRealloc(ctxt->node_seq.buffer,
1968
0
                                                     byte_size);
1969
1970
0
            if (tmp_buffer == NULL) {
1971
0
    xmlErrMemory(ctxt, "failed to allocate buffer\n");
1972
0
                return;
1973
0
            }
1974
0
            ctxt->node_seq.buffer = tmp_buffer;
1975
0
            ctxt->node_seq.maximum *= 2;
1976
0
        }
1977
1978
        /* If position is not at end, move elements out of the way */
1979
0
        if (pos != ctxt->node_seq.length) {
1980
0
            unsigned long i;
1981
1982
0
            for (i = ctxt->node_seq.length; i > pos; i--)
1983
0
                ctxt->node_seq.buffer[i] = ctxt->node_seq.buffer[i - 1];
1984
0
        }
1985
1986
        /* Copy element and increase length */
1987
0
        ctxt->node_seq.buffer[pos] = *info;
1988
0
        ctxt->node_seq.length++;
1989
0
    }
1990
0
}
1991
1992
/************************************************************************
1993
 *                  *
1994
 *    Defaults settings         *
1995
 *                  *
1996
 ************************************************************************/
1997
/**
1998
 * xmlPedanticParserDefault:
1999
 * @val:  int 0 or 1
2000
 *
2001
 * DEPRECATED: Use the modern options API with XML_PARSE_PEDANTIC.
2002
 *
2003
 * Set and return the previous value for enabling pedantic warnings.
2004
 *
2005
 * Returns the last value for 0 for no substitution, 1 for substitution.
2006
 */
2007
2008
int
2009
0
xmlPedanticParserDefault(int val) {
2010
0
    int old = xmlPedanticParserDefaultValue;
2011
2012
0
    xmlPedanticParserDefaultValue = val;
2013
0
    return(old);
2014
0
}
2015
2016
/**
2017
 * xmlLineNumbersDefault:
2018
 * @val:  int 0 or 1
2019
 *
2020
 * DEPRECATED: The modern options API always enables line numbers.
2021
 *
2022
 * Set and return the previous value for enabling line numbers in elements
2023
 * contents. This may break on old application and is turned off by default.
2024
 *
2025
 * Returns the last value for 0 for no substitution, 1 for substitution.
2026
 */
2027
2028
int
2029
0
xmlLineNumbersDefault(int val) {
2030
0
    int old = xmlLineNumbersDefaultValue;
2031
2032
0
    xmlLineNumbersDefaultValue = val;
2033
0
    return(old);
2034
0
}
2035
2036
/**
2037
 * xmlSubstituteEntitiesDefault:
2038
 * @val:  int 0 or 1
2039
 *
2040
 * DEPRECATED: Use the modern options API with XML_PARSE_NOENT.
2041
 *
2042
 * Set and return the previous value for default entity support.
2043
 * Initially the parser always keep entity references instead of substituting
2044
 * entity values in the output. This function has to be used to change the
2045
 * default parser behavior
2046
 * SAX::substituteEntities() has to be used for changing that on a file by
2047
 * file basis.
2048
 *
2049
 * Returns the last value for 0 for no substitution, 1 for substitution.
2050
 */
2051
2052
int
2053
0
xmlSubstituteEntitiesDefault(int val) {
2054
0
    int old = xmlSubstituteEntitiesDefaultValue;
2055
2056
0
    xmlSubstituteEntitiesDefaultValue = val;
2057
0
    return(old);
2058
0
}
2059
2060
/**
2061
 * xmlKeepBlanksDefault:
2062
 * @val:  int 0 or 1
2063
 *
2064
 * DEPRECATED: Use the modern options API with XML_PARSE_NOBLANKS.
2065
 *
2066
 * Set and return the previous value for default blanks text nodes support.
2067
 * The 1.x version of the parser used an heuristic to try to detect
2068
 * ignorable white spaces. As a result the SAX callback was generating
2069
 * xmlSAX2IgnorableWhitespace() callbacks instead of characters() one, and when
2070
 * using the DOM output text nodes containing those blanks were not generated.
2071
 * The 2.x and later version will switch to the XML standard way and
2072
 * ignorableWhitespace() are only generated when running the parser in
2073
 * validating mode and when the current element doesn't allow CDATA or
2074
 * mixed content.
2075
 * This function is provided as a way to force the standard behavior
2076
 * on 1.X libs and to switch back to the old mode for compatibility when
2077
 * running 1.X client code on 2.X . Upgrade of 1.X code should be done
2078
 * by using xmlIsBlankNode() commodity function to detect the "empty"
2079
 * nodes generated.
2080
 * This value also affect autogeneration of indentation when saving code
2081
 * if blanks sections are kept, indentation is not generated.
2082
 *
2083
 * Returns the last value for 0 for no substitution, 1 for substitution.
2084
 */
2085
2086
int
2087
0
xmlKeepBlanksDefault(int val) {
2088
0
    int old = xmlKeepBlanksDefaultValue;
2089
2090
0
    xmlKeepBlanksDefaultValue = val;
2091
0
    if (!val) xmlIndentTreeOutput = 1;
2092
0
    return(old);
2093
0
}
2094