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