parser.c 327 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14
/*
 * parser.c : an XML 1.0 parser, namespaces and validity support are mostly
 *            implemented on top of the SAX interfaces
 *
 * References:
 *   The XML specification:
 *     http://www.w3.org/TR/REC-xml
 *   Original 1.0 version:
 *     http://www.w3.org/TR/1998/REC-xml-19980210
 *   XML second edition working draft
 *     http://www.w3.org/TR/2000/WD-xml-2e-20000814
 *
 * Okay this is a big file, the parser core is around 7000 lines, then it
 * is followed by the progressive parser top routines, then the various
15
 * high level APIs to call the parser and a few miscellaneous functions.
16 17 18 19 20 21 22 23 24
 * A number of helper functions and deprecated ones have been moved to
 * parserInternals.c to reduce this file size.
 * As much as possible the functions are associated with their relative
 * production in the XML specification. A few productions defining the
 * different ranges of character are actually implanted either in 
 * parserInternals.h or parserInternals.c
 * The DOM tree build is realized from the default SAX callbacks in
 * the module SAX.c.
 * The routines doing the validation checks are in valid.c and called either
25
 * from the SAX callbacks or as standalone functions using a preparsed
26 27 28 29
 * document.
 *
 * See Copyright for the status of this software.
 *
30
 * daniel@veillard.com
31 32
 */

33
#define IN_LIBXML
Bjorn Reese's avatar
Bjorn Reese committed
34 35
#include "libxml.h"

36
#if defined(WIN32) && !defined (__CYGWIN__)
37 38 39 40 41 42 43 44
#define XML_DIR_SEP '\\'
#else
#define XML_DIR_SEP '/'
#endif

#include <stdlib.h>
#include <string.h>
#include <libxml/xmlmemory.h>
45 46
#include <libxml/threads.h>
#include <libxml/globals.h>
47 48 49 50 51 52 53 54 55
#include <libxml/tree.h>
#include <libxml/parser.h>
#include <libxml/parserInternals.h>
#include <libxml/valid.h>
#include <libxml/entities.h>
#include <libxml/xmlerror.h>
#include <libxml/encoding.h>
#include <libxml/xmlIO.h>
#include <libxml/uri.h>
56 57 58
#ifdef LIBXML_CATALOG_ENABLED
#include <libxml/catalog.h>
#endif
59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78

#ifdef HAVE_CTYPE_H
#include <ctype.h>
#endif
#ifdef HAVE_STDLIB_H
#include <stdlib.h>
#endif
#ifdef HAVE_SYS_STAT_H
#include <sys/stat.h>
#endif
#ifdef HAVE_FCNTL_H
#include <fcntl.h>
#endif
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#ifdef HAVE_ZLIB_H
#include <zlib.h>
#endif

79 80 81 82 83 84 85 86
/**
 * MAX_DEPTH:
 *
 * arbitrary depth limit for the XML documents that we allow to 
 * process. This is not a limitation of the parser but a safety 
 * boundary feature.
 */
#define MAX_DEPTH 1024
87

88 89
#define SAX2 1

90
#define XML_PARSER_BIG_BUFFER_SIZE 300
91 92
#define XML_PARSER_BUFFER_SIZE 100

93 94
#define SAX_COMPAT_MODE BAD_CAST "SAX compatibility mode document"

95 96 97 98
/*
 * List of XML prefixed PI allowed by W3C specs
 */

99
static const char *xmlW3CPIs[] = {
100 101 102 103 104 105 106 107
    "xml-stylesheet",
    NULL
};

/* DEPR void xmlParserHandleReference(xmlParserCtxtPtr ctxt); */
xmlEntityPtr xmlParseStringPEReference(xmlParserCtxtPtr ctxt,
                                       const xmlChar **str);

108
static int
109 110
xmlParseExternalEntityPrivate(xmlDocPtr doc, xmlParserCtxtPtr oldctxt,
	              xmlSAXHandlerPtr sax,
111
		      void *user_data, int depth, const xmlChar *URL,
112
		      const xmlChar *ID, xmlNodePtr *list);
113

114 115 116 117
static void
xmlAddEntityReference(xmlEntityPtr ent, xmlNodePtr firstNode,
                      xmlNodePtr lastNode);

118 119 120
static int
xmlParseBalancedChunkMemoryInternal(xmlParserCtxtPtr oldctxt,
		      const xmlChar *string, void *user_data, xmlNodePtr *lst);
121

122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392
/************************************************************************
 *									*
 * 		Some factorized error routines				*
 *									*
 ************************************************************************/

/**
 * xmlErrMemory:
 * @ctxt:  an XML parser context
 * @extra:  extra informations
 *
 * Handle a redefinition of attribute error
 */
static void
xmlErrMemory(xmlParserCtxtPtr ctxt, const char *extra)
{
    if (ctxt != NULL) {
        ctxt->errNo = XML_ERR_NO_MEMORY;
        ctxt->instate = XML_PARSER_EOF;
        ctxt->disableSAX = 1;
    }
    if ((ctxt != NULL) && (ctxt->sax != NULL)
        && (ctxt->sax->error != NULL)) {
        if (extra)
            ctxt->sax->error(ctxt->userData,
                             "Memory allocation failed : %s\n", extra);
        else
            ctxt->sax->error(ctxt->userData,
                             "Memory allocation failed !\n");
    } else {
        if (extra)
            xmlGenericError(xmlGenericErrorContext,
                            "Memory allocation failed : %s\n", extra);
        else
            xmlGenericError(xmlGenericErrorContext,
                            "Memory allocation failed !\n");
    }
}

/**
 * xmlErrAttributeDup:
 * @ctxt:  an XML parser context
 * @prefix:  the attribute prefix
 * @localname:  the attribute localname
 *
 * Handle a redefinition of attribute error
 */
static void
xmlErrAttributeDup(xmlParserCtxtPtr ctxt, const xmlChar * prefix,
                   const xmlChar * localname)
{
    ctxt->errNo = XML_ERR_ATTRIBUTE_REDEFINED;
    if ((ctxt->sax != NULL) && (ctxt->sax->error != NULL)) {
        if (prefix == NULL)
            ctxt->sax->error(ctxt->userData,
                             "Attribute %s redefined\n", localname);
        else
            ctxt->sax->error(ctxt->userData,
                             "Attribute %s:%s redefined\n", prefix,
                             localname);
    }
    ctxt->wellFormed = 0;
    if (ctxt->recovery == 0)
        ctxt->disableSAX = 1;
}

/**
 * xmlFatalErr:
 * @ctxt:  an XML parser context
 * @error:  the error number
 * @extra:  extra information string
 *
 * Handle a fatal parser error, i.e. violating Well-Formedness constraints
 */
static void
xmlFatalErr(xmlParserCtxtPtr ctxt, xmlParserErrors error, const char * info)
{
    const char *errmsg;

    if (ctxt == NULL) {
	xmlGenericError(xmlGenericErrorContext,
			"xmlFatalErr: no context !\n");
	return;
    }
    if ((ctxt->sax == NULL) || (ctxt->sax->error == NULL))
        return;
    switch (error) {
        case XML_ERR_INVALID_HEX_CHARREF:
	    errmsg = "CharRef: invalid hexadecimal value\n";
	    break;
        case XML_ERR_INVALID_DEC_CHARREF:
	    errmsg = "CharRef: invalid decimal value\n";
	    break;
        case XML_ERR_INVALID_CHARREF:
	    errmsg = "CharRef: invalid value\n";
	    break;
        case XML_ERR_INTERNAL_ERROR:
	    errmsg = "internal error";
	    break;
        case XML_ERR_PEREF_AT_EOF:
	    errmsg = "PEReference at end of document\n";
	    break;
        case XML_ERR_PEREF_IN_PROLOG:
	    errmsg = "PEReference in prolog\n";
	    break;
        case XML_ERR_PEREF_IN_EPILOG:
	    errmsg = "PEReference in epilog\n";
	    break;
        case XML_ERR_PEREF_NO_NAME:
	    errmsg = "PEReference: no name\n";
	    break;
        case XML_ERR_PEREF_SEMICOL_MISSING:
	    errmsg = "PEReference: expecting ';'\n";
	    break;
        case XML_ERR_ENTITY_LOOP:
	    errmsg = "Detected an entity reference loop\n";
	    break;
        case XML_ERR_ENTITY_NOT_STARTED:
	    errmsg = "EntityValue: \" or ' expected\n";
	    break;
        case XML_ERR_ENTITY_PE_INTERNAL:
	    errmsg = "PEReferences forbidden in internal subset\n";
	    break;
        case XML_ERR_ENTITY_NOT_FINISHED:
	    errmsg = "EntityValue: \" or ' expected\n";
	    break;
        case XML_ERR_ATTRIBUTE_NOT_STARTED:
	    errmsg = "AttValue: \" or ' expected\n";
	    break;
        case XML_ERR_LT_IN_ATTRIBUTE:
	    errmsg = "Unescaped '<' not allowed in attributes values\n";
	    break;
        case XML_ERR_LITERAL_NOT_STARTED:
	    errmsg = "SystemLiteral \" or ' expected\n";
	    break;
        case XML_ERR_LITERAL_NOT_FINISHED:
	    errmsg = "Unfinished System or Public ID \" or ' expected\n";
	    break;
        case XML_ERR_MISPLACED_CDATA_END:
	    errmsg = "Sequence ']]>' not allowed in content\n";
	    break;
        case XML_ERR_URI_REQUIRED:
	    errmsg = "SYSTEM or PUBLIC, the URI is missing\n";
	    break;
        case XML_ERR_PUBID_REQUIRED:
	    errmsg = "PUBLIC, the Public Identifier is missing\n";
	    break;
        case XML_ERR_HYPHEN_IN_COMMENT:
	    errmsg = "Comment must not contain '--' (double-hyphen)\n";
	    break;
        case XML_ERR_PI_NOT_STARTED:
	    errmsg = "xmlParsePI : no target name\n";
	    break;
        case XML_ERR_RESERVED_XML_NAME:
	    errmsg = "Invalid PI name\n";
	    break;
        case XML_ERR_NOTATION_NOT_STARTED:
	    errmsg = "NOTATION: Name expected here\n";
	    break;
        case XML_ERR_NOTATION_NOT_FINISHED:
	    errmsg = "'>' required to close NOTATION declaration\n";
	    break;
        case XML_ERR_VALUE_REQUIRED:
	    errmsg = "Entity value required\n";
	    break;
        case XML_ERR_URI_FRAGMENT:
	    errmsg = "Fragment not allowed";
	    break;
        case XML_ERR_ATTLIST_NOT_STARTED:
	    errmsg = "'(' required to start ATTLIST enumeration\n";
	    break;
        case XML_ERR_NMTOKEN_REQUIRED:
	    errmsg = "NmToken expected in ATTLIST enumeration\n";
	    break;
        case XML_ERR_ATTLIST_NOT_FINISHED:
	    errmsg = "')' required to finish ATTLIST enumeration\n";
	    break;
        case XML_ERR_MIXED_NOT_STARTED:
	    errmsg = "MixedContentDecl : '|' or ')*' expected\n";
	    break;
        case XML_ERR_PCDATA_REQUIRED:
	    errmsg = "MixedContentDecl : '#PCDATA' expected\n";
	    break;
        case XML_ERR_ELEMCONTENT_NOT_STARTED:
	    errmsg = "ContentDecl : Name or '(' expected\n";
	    break;
        case XML_ERR_ELEMCONTENT_NOT_FINISHED:
	    errmsg = "ContentDecl : ',' '|' or ')' expected\n";
	    break;
        case XML_ERR_PEREF_IN_INT_SUBSET:
	    errmsg = "PEReference: forbidden within markup decl in internal subset\n";
	    break;
        case XML_ERR_GT_REQUIRED:
	    errmsg = "expected '>'\n";
	    break;
        case XML_ERR_CONDSEC_INVALID:
	    errmsg = "XML conditional section '[' expected\n";
	    break;
        case XML_ERR_EXT_SUBSET_NOT_FINISHED:
	    errmsg = "Content error in the external subset\n";
	    break;
	case XML_ERR_CONDSEC_INVALID_KEYWORD: 
	    errmsg = "conditional section INCLUDE or IGNORE keyword expected\n";
	    break;
        case XML_ERR_CONDSEC_NOT_FINISHED:
	    errmsg = "XML conditional section not closed\n";
	    break;
        case XML_ERR_XMLDECL_NOT_STARTED:
	    errmsg = "Text declaration '<?xml' required\n";
	    break;
        case XML_ERR_XMLDECL_NOT_FINISHED:
	    errmsg = "parsing XML declaration: '?>' expected\n";
	    break;
        case XML_ERR_EXT_ENTITY_STANDALONE:
	    errmsg = "external parsed entities cannot be standalone\n";
	    break;
        case XML_ERR_ENTITYREF_SEMICOL_MISSING:
	    errmsg = "EntityRef: expecting ';'\n";
	    break;
        case XML_ERR_DOCTYPE_NOT_FINISHED:
	    errmsg = "DOCTYPE improperly terminated\n";
	    break;
        case XML_ERR_LTSLASH_REQUIRED:
	    errmsg = "EndTag: '</' not found\n";
	    break;
        case XML_ERR_EQUAL_REQUIRED:
	    errmsg = "expected '='\n";
	    break;
        case XML_ERR_STRING_NOT_CLOSED:
	    errmsg = "String not closed expecting \" or '\n";
	    break;
        case XML_ERR_STRING_NOT_STARTED:
	    errmsg = "String not started expecting ' or \"\n";
	    break;
        case XML_ERR_ENCODING_NAME:
	    errmsg = "Invalid XML encoding name\n";
	    break;
        case XML_ERR_STANDALONE_VALUE:
	    errmsg = "standalone accepts only 'yes' or 'no'\n";
	    break;
        case XML_ERR_DOCUMENT_EMPTY:
	    errmsg = "Document is empty\n";
	    break;
        case XML_ERR_DOCUMENT_END:
	    errmsg = "Extra content at the end of the document\n";
	    break;
        case XML_ERR_NOT_WELL_BALANCED:
	    errmsg = "chunk is not well balanced\n";
	    break;
        case XML_ERR_EXTRA_CONTENT:
	    errmsg = "extra content at the end of well balanced chunk\n";
	    break;
#if 0
        case :
	    errmsg = "\n";
	    break;
#endif
	default:
	    errmsg = "Unregistered error message\n";
    }
    ctxt->errNo = error;
    if (info == NULL) {
        ctxt->sax->error(ctxt->userData, errmsg);
    } else {
        ctxt->sax->error(ctxt->userData, "%s: %s", errmsg, info);
    }
    ctxt->wellFormed = 0;
    if (ctxt->recovery == 0)
        ctxt->disableSAX = 1;
}

393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510
/************************************************************************
 *									*
 * 		SAX2 defaulted attributes handling			*
 *									*
 ************************************************************************/

/**
 * xmlDetectSAX2:
 * @ctxt:  an XML parser context
 *
 * Do the SAX2 detection and specific intialization
 */
static void
xmlDetectSAX2(xmlParserCtxtPtr ctxt) {
    if (ctxt == NULL) return;
    if ((ctxt->sax) &&  (ctxt->sax->initialized == XML_SAX2_MAGIC) &&
        ((ctxt->sax->startElementNs != NULL) ||
         (ctxt->sax->endElementNs != NULL))) ctxt->sax2 = 1;

    ctxt->str_xml = xmlDictLookup(ctxt->dict, BAD_CAST "xml", 3);
    ctxt->str_xmlns = xmlDictLookup(ctxt->dict, BAD_CAST "xmlns", 5);
    ctxt->str_xml_ns = xmlDictLookup(ctxt->dict, XML_XML_NAMESPACE, 36);
}

#ifdef SAX2
typedef struct _xmlDefAttrs xmlDefAttrs;
typedef xmlDefAttrs *xmlDefAttrsPtr;
struct _xmlDefAttrs {
    int nbAttrs;	/* number of defaulted attributes on that element */
    int maxAttrs;       /* the size of the array */
    const xmlChar *values[4]; /* array of localname/prefix/values */
};
#endif

/**
 * xmlAddDefAttrs:
 * @ctxt:  an XML parser context
 * @fullname:  the element fullname
 * @fullattr:  the attribute fullname
 * @value:  the attribute value
 *
 * Add a defaulted attribute for an element
 */
static void
xmlAddDefAttrs(xmlParserCtxtPtr ctxt,
               const xmlChar *fullname,
               const xmlChar *fullattr,
               const xmlChar *value) {
    xmlDefAttrsPtr defaults;
    int len;
    const xmlChar *name;
    const xmlChar *prefix;

    if (ctxt->attsDefault == NULL) {
        ctxt->attsDefault = xmlHashCreate(10);
	if (ctxt->attsDefault == NULL)
	    goto mem_error;
    }

    /*
     * plit the element name into prefix:localname , the string found
     * are within the DTD and hen not associated to namespace names.
     */
    name = xmlSplitQName3(fullname, &len);
    if (name == NULL) {
        name = xmlDictLookup(ctxt->dict, fullname, -1);
	prefix = NULL;
    } else {
        name = xmlDictLookup(ctxt->dict, name, -1);
	prefix = xmlDictLookup(ctxt->dict, fullname, len);
    }

    /*
     * make sure there is some storage
     */
    defaults = xmlHashLookup2(ctxt->attsDefault, name, prefix);
    if (defaults == NULL) {
        defaults = (xmlDefAttrsPtr) xmlMalloc(sizeof(xmlDefAttrs) +
	                               12 * sizeof(const xmlChar *));
	if (defaults == NULL)
	    goto mem_error;
	defaults->maxAttrs = 4;
	defaults->nbAttrs = 0;
	xmlHashUpdateEntry2(ctxt->attsDefault, name, prefix, defaults, NULL);
    } else if (defaults->nbAttrs >= defaults->maxAttrs) {
        defaults = (xmlDefAttrsPtr) xmlRealloc(defaults, sizeof(xmlDefAttrs) +
		       (2 * defaults->maxAttrs * 4) * sizeof(const xmlChar *));
	if (defaults == NULL)
	    goto mem_error;
	defaults->maxAttrs *= 2;
	xmlHashUpdateEntry2(ctxt->attsDefault, name, prefix, defaults, NULL);
    }

    /*
     * plit the element name into prefix:localname , the string found
     * are within the DTD and hen not associated to namespace names.
     */
    name = xmlSplitQName3(fullattr, &len);
    if (name == NULL) {
        name = xmlDictLookup(ctxt->dict, fullattr, -1);
	prefix = NULL;
    } else {
        name = xmlDictLookup(ctxt->dict, name, -1);
	prefix = xmlDictLookup(ctxt->dict, fullattr, len);
    }

    defaults->values[4 * defaults->nbAttrs] = name;
    defaults->values[4 * defaults->nbAttrs + 1] = prefix;
    /* intern the string and precompute the end */
    len = xmlStrlen(value);
    value = xmlDictLookup(ctxt->dict, value, len);
    defaults->values[4 * defaults->nbAttrs + 2] = value;
    defaults->values[4 * defaults->nbAttrs + 3] = value + len;
    defaults->nbAttrs++;

    return;

mem_error:
511
    xmlErrMemory(ctxt, NULL);
512 513 514
    return;
}

515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539
/**
 * xmlAddSpecialAttr:
 * @ctxt:  an XML parser context
 * @fullname:  the element fullname
 * @fullattr:  the attribute fullname
 * @type:  the attribute type
 *
 * Register that this attribute is not CDATA
 */
static void
xmlAddSpecialAttr(xmlParserCtxtPtr ctxt,
		  const xmlChar *fullname,
		  const xmlChar *fullattr,
		  int type)
{
    if (ctxt->attsSpecial == NULL) {
        ctxt->attsSpecial = xmlHashCreate(10);
	if (ctxt->attsSpecial == NULL)
	    goto mem_error;
    }

    xmlHashAddEntry2(ctxt->attsSpecial, fullname, fullattr, (void *) type);
    return;

mem_error:
540
    xmlErrMemory(ctxt, NULL);
541 542 543
    return;
}

544 545 546 547 548 549 550 551 552
/************************************************************************
 *									*
 * 		Parser stacks related functions and macros		*
 *									*
 ************************************************************************/

xmlEntityPtr xmlParseStringEntityRef(xmlParserCtxtPtr ctxt,
                                     const xmlChar ** str);

553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572
#ifdef SAX2
/**
 * nsPush:
 * @ctxt:  an XML parser context
 * @prefix:  the namespace prefix or NULL
 * @URL:  the namespace name
 *
 * Pushes a new parser namespace on top of the ns stack
 *
 * Returns -1 in case of error, the index in the stack otherwise
 */
static int
nsPush(xmlParserCtxtPtr ctxt, const xmlChar *prefix, const xmlChar *URL)
{
    if ((ctxt->nsMax == 0) || (ctxt->nsTab == NULL)) {
	ctxt->nsMax = 10;
	ctxt->nsNr = 0;
	ctxt->nsTab = (const xmlChar **)
	              xmlMalloc(ctxt->nsMax * sizeof(xmlChar *));
	if (ctxt->nsTab == NULL) {
573
	    xmlErrMemory(ctxt, NULL);
574 575 576 577 578 579 580 581 582
	    ctxt->nsMax = 0;
            return (-1);
	}
    } else if (ctxt->nsNr >= ctxt->nsMax) {
        ctxt->nsMax *= 2;
        ctxt->nsTab = (const xmlChar **)
	              xmlRealloc(ctxt->nsTab,
				 ctxt->nsMax * sizeof(ctxt->nsTab[0]));
        if (ctxt->nsTab == NULL) {
583
            xmlErrMemory(ctxt, NULL);
584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624
	    ctxt->nsMax /= 2;
            return (-1);
        }
    }
    ctxt->nsTab[ctxt->nsNr++] = prefix;
    ctxt->nsTab[ctxt->nsNr++] = URL;
    return (ctxt->nsNr);
}
/**
 * nsPop:
 * @ctxt: an XML parser context
 * @nr:  the number to pop
 *
 * Pops the top @nr parser prefix/namespace from the ns stack
 *
 * Returns the number of namespaces removed
 */
static int
nsPop(xmlParserCtxtPtr ctxt, int nr)
{
    int i;

    if (ctxt->nsTab == NULL) return(0);
    if (ctxt->nsNr < nr) {
        xmlGenericError(xmlGenericErrorContext, "Pbm popping %d NS\n", nr);
        nr = ctxt->nsNr;
    }
    if (ctxt->nsNr <= 0)
        return (0);
    
    for (i = 0;i < nr;i++) {
         ctxt->nsNr--;
	 ctxt->nsTab[ctxt->nsNr] = NULL;
    }
    return(nr);
}
#endif

static int
xmlCtxtGrowAttrs(xmlParserCtxtPtr ctxt, int nr) {
    const xmlChar **atts;
625
    int *attallocs;
626 627 628
    int maxatts;

    if (ctxt->atts == NULL) {
629
	maxatts = 55; /* allow for 10 attrs by default */
630 631
	atts = (const xmlChar **)
	       xmlMalloc(maxatts * sizeof(xmlChar *));
632
	if (atts == NULL) goto mem_error;
633
	ctxt->atts = atts;
634 635 636
	attallocs = (int *) xmlMalloc((maxatts / 5) * sizeof(int));
	if (attallocs == NULL) goto mem_error;
	ctxt->attallocs = attallocs;
637
	ctxt->maxatts = maxatts;
638 639
    } else if (nr + 5 > ctxt->maxatts) {
	maxatts = (nr + 5) * 2;
640 641
	atts = (const xmlChar **) xmlRealloc((void *) ctxt->atts,
				     maxatts * sizeof(const xmlChar *));
642
	if (atts == NULL) goto mem_error;
643
	ctxt->atts = atts;
644 645 646 647
	attallocs = (int *) xmlRealloc((void *) ctxt->attallocs,
	                             (maxatts / 5) * sizeof(int));
	if (attallocs == NULL) goto mem_error;
	ctxt->attallocs = attallocs;
648 649 650
	ctxt->maxatts = maxatts;
    }
    return(ctxt->maxatts);
651
mem_error:
652
    xmlErrMemory(ctxt, NULL);
653
    return(-1);
654 655
}

656 657 658
/**
 * inputPush:
 * @ctxt:  an XML parser context
659
 * @value:  the parser input
660 661
 *
 * Pushes a new parser input on top of the input stack
662 663
 *
 * Returns 0 in case of error, the index in the stack otherwise
664
 */
Daniel Veillard's avatar
Daniel Veillard committed
665 666 667 668 669 670 671 672 673 674
extern int
inputPush(xmlParserCtxtPtr ctxt, xmlParserInputPtr value)
{
    if (ctxt->inputNr >= ctxt->inputMax) {
        ctxt->inputMax *= 2;
        ctxt->inputTab =
            (xmlParserInputPtr *) xmlRealloc(ctxt->inputTab,
                                             ctxt->inputMax *
                                             sizeof(ctxt->inputTab[0]));
        if (ctxt->inputTab == NULL) {
675
            xmlErrMemory(ctxt, NULL);
Daniel Veillard's avatar
Daniel Veillard committed
676 677 678 679 680 681 682
            return (0);
        }
    }
    ctxt->inputTab[ctxt->inputNr] = value;
    ctxt->input = value;
    return (ctxt->inputNr++);
}
683
/**
Daniel Veillard's avatar
Daniel Veillard committed
684
 * inputPop:
685 686
 * @ctxt: an XML parser context
 *
Daniel Veillard's avatar
Daniel Veillard committed
687
 * Pops the top parser input from the input stack
688
 *
Daniel Veillard's avatar
Daniel Veillard committed
689
 * Returns the input just removed
690
 */
Daniel Veillard's avatar
Daniel Veillard committed
691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706
extern xmlParserInputPtr
inputPop(xmlParserCtxtPtr ctxt)
{
    xmlParserInputPtr ret;

    if (ctxt->inputNr <= 0)
        return (0);
    ctxt->inputNr--;
    if (ctxt->inputNr > 0)
        ctxt->input = ctxt->inputTab[ctxt->inputNr - 1];
    else
        ctxt->input = NULL;
    ret = ctxt->inputTab[ctxt->inputNr];
    ctxt->inputTab[ctxt->inputNr] = 0;
    return (ret);
}
707
/**
Daniel Veillard's avatar
Daniel Veillard committed
708
 * nodePush:
709
 * @ctxt:  an XML parser context
Daniel Veillard's avatar
Daniel Veillard committed
710
 * @value:  the element node
711
 *
Daniel Veillard's avatar
Daniel Veillard committed
712
 * Pushes a new element node on top of the node stack
713 714
 *
 * Returns 0 in case of error, the index in the stack otherwise
715
 */
Daniel Veillard's avatar
Daniel Veillard committed
716 717 718 719 720 721 722 723 724 725
extern int
nodePush(xmlParserCtxtPtr ctxt, xmlNodePtr value)
{
    if (ctxt->nodeNr >= ctxt->nodeMax) {
        ctxt->nodeMax *= 2;
        ctxt->nodeTab =
            (xmlNodePtr *) xmlRealloc(ctxt->nodeTab,
                                      ctxt->nodeMax *
                                      sizeof(ctxt->nodeTab[0]));
        if (ctxt->nodeTab == NULL) {
726
            xmlErrMemory(ctxt, NULL);
Daniel Veillard's avatar
Daniel Veillard committed
727 728 729
            return (0);
        }
    }
730 731 732 733 734 735 736 737 738 739 740 741
#ifdef MAX_DEPTH
    if (ctxt->nodeNr > MAX_DEPTH) {
	if ((ctxt->sax != NULL) && (ctxt->sax->error != NULL))
	    ctxt->sax->error(ctxt->userData, 
		 "Excessive depth in document: change MAX_DEPTH = %d\n",
		             MAX_DEPTH);
	ctxt->wellFormed = 0;
	ctxt->instate = XML_PARSER_EOF;
	if (ctxt->recovery == 0) ctxt->disableSAX = 1;
	return(0);
    }
#endif
Daniel Veillard's avatar
Daniel Veillard committed
742 743 744 745
    ctxt->nodeTab[ctxt->nodeNr] = value;
    ctxt->node = value;
    return (ctxt->nodeNr++);
}
746 747 748 749 750 751 752 753
/**
 * nodePop:
 * @ctxt: an XML parser context
 *
 * Pops the top element node from the node stack
 *
 * Returns the node just removed
 */
Daniel Veillard's avatar
Daniel Veillard committed
754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769
extern xmlNodePtr
nodePop(xmlParserCtxtPtr ctxt)
{
    xmlNodePtr ret;

    if (ctxt->nodeNr <= 0)
        return (0);
    ctxt->nodeNr--;
    if (ctxt->nodeNr > 0)
        ctxt->node = ctxt->nodeTab[ctxt->nodeNr - 1];
    else
        ctxt->node = NULL;
    ret = ctxt->nodeTab[ctxt->nodeNr];
    ctxt->nodeTab[ctxt->nodeNr] = 0;
    return (ret);
}
770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812
/**
 * nameNsPush:
 * @ctxt:  an XML parser context
 * @value:  the element name
 * @prefix:  the element prefix
 * @URI:  the element namespace name
 *
 * Pushes a new element name/prefix/URL on top of the name stack
 *
 * Returns -1 in case of error, the index in the stack otherwise
 */
static int
nameNsPush(xmlParserCtxtPtr ctxt, const xmlChar * value,
           const xmlChar *prefix, const xmlChar *URI, int nsNr)
{
    if (ctxt->nameNr >= ctxt->nameMax) {
        const xmlChar * *tmp;
        void **tmp2;
        ctxt->nameMax *= 2;
        tmp = (const xmlChar * *) xmlRealloc((xmlChar * *)ctxt->nameTab,
                                    ctxt->nameMax *
                                    sizeof(ctxt->nameTab[0]));
        if (tmp == NULL) {
	    ctxt->nameMax /= 2;
	    goto mem_error;
        }
	ctxt->nameTab = tmp;
        tmp2 = (void **) xmlRealloc((void * *)ctxt->pushTab,
                                    ctxt->nameMax * 3 *
                                    sizeof(ctxt->pushTab[0]));
        if (tmp2 == NULL) {
	    ctxt->nameMax /= 2;
	    goto mem_error;
        }
	ctxt->pushTab = tmp2;
    }
    ctxt->nameTab[ctxt->nameNr] = value;
    ctxt->name = value;
    ctxt->pushTab[ctxt->nameNr * 3] = (void *) prefix;
    ctxt->pushTab[ctxt->nameNr * 3 + 1] = (void *) URI;
    ctxt->pushTab[ctxt->nameNr * 3 + 2] = (void *) nsNr;
    return (ctxt->nameNr++);
mem_error:
813
    xmlErrMemory(ctxt, NULL);
814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840
    return (-1);
}
/**
 * nameNsPop:
 * @ctxt: an XML parser context
 *
 * Pops the top element/prefix/URI name from the name stack
 *
 * Returns the name just removed
 */
static const xmlChar *
nameNsPop(xmlParserCtxtPtr ctxt)
{
    const xmlChar *ret;

    if (ctxt->nameNr <= 0)
        return (0);
    ctxt->nameNr--;
    if (ctxt->nameNr > 0)
        ctxt->name = ctxt->nameTab[ctxt->nameNr - 1];
    else
        ctxt->name = NULL;
    ret = ctxt->nameTab[ctxt->nameNr];
    ctxt->nameTab[ctxt->nameNr] = NULL;
    return (ret);
}

841
/**
Daniel Veillard's avatar
Daniel Veillard committed
842
 * namePush:
843
 * @ctxt:  an XML parser context
Daniel Veillard's avatar
Daniel Veillard committed
844
 * @value:  the element name
845
 *
Daniel Veillard's avatar
Daniel Veillard committed
846
 * Pushes a new element name on top of the name stack
847
 *
848
 * Returns -1 in case of error, the index in the stack otherwise
849
 */
Daniel Veillard's avatar
Daniel Veillard committed
850
extern int
851
namePush(xmlParserCtxtPtr ctxt, const xmlChar * value)
Daniel Veillard's avatar
Daniel Veillard committed
852 853
{
    if (ctxt->nameNr >= ctxt->nameMax) {
854
        const xmlChar * *tmp;
Daniel Veillard's avatar
Daniel Veillard committed
855
        ctxt->nameMax *= 2;
856
        tmp = (const xmlChar * *) xmlRealloc((xmlChar * *)ctxt->nameTab,
Daniel Veillard's avatar
Daniel Veillard committed
857 858
                                    ctxt->nameMax *
                                    sizeof(ctxt->nameTab[0]));
859 860 861
        if (tmp == NULL) {
	    ctxt->nameMax /= 2;
	    goto mem_error;
Daniel Veillard's avatar
Daniel Veillard committed
862
        }
863
	ctxt->nameTab = tmp;
Daniel Veillard's avatar
Daniel Veillard committed
864 865 866 867
    }
    ctxt->nameTab[ctxt->nameNr] = value;
    ctxt->name = value;
    return (ctxt->nameNr++);
868
mem_error:
869
    xmlErrMemory(ctxt, NULL);
870
    return (-1);
Daniel Veillard's avatar
Daniel Veillard committed
871 872 873 874 875 876 877 878
}
/**
 * namePop:
 * @ctxt: an XML parser context
 *
 * Pops the top element name from the name stack
 *
 * Returns the name just removed
879
 */
880
extern const xmlChar *
Daniel Veillard's avatar
Daniel Veillard committed
881 882
namePop(xmlParserCtxtPtr ctxt)
{
883
    const xmlChar *ret;
Daniel Veillard's avatar
Daniel Veillard committed
884 885 886 887 888 889 890 891 892 893 894 895

    if (ctxt->nameNr <= 0)
        return (0);
    ctxt->nameNr--;
    if (ctxt->nameNr > 0)
        ctxt->name = ctxt->nameTab[ctxt->nameNr - 1];
    else
        ctxt->name = NULL;
    ret = ctxt->nameTab[ctxt->nameNr];
    ctxt->nameTab[ctxt->nameNr] = 0;
    return (ret);
}
896

897
static int spacePush(xmlParserCtxtPtr ctxt, int val) {
898 899 900 901 902
    if (ctxt->spaceNr >= ctxt->spaceMax) {
	ctxt->spaceMax *= 2;
        ctxt->spaceTab = (int *) xmlRealloc(ctxt->spaceTab,
	             ctxt->spaceMax * sizeof(ctxt->spaceTab[0]));
        if (ctxt->spaceTab == NULL) {
903
	    xmlErrMemory(ctxt, NULL);
904 905 906 907 908 909 910 911
	    return(0);
	}
    }
    ctxt->spaceTab[ctxt->spaceNr] = val;
    ctxt->space = &ctxt->spaceTab[ctxt->spaceNr];
    return(ctxt->spaceNr++);
}

912
static int spacePop(xmlParserCtxtPtr ctxt) {
913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943
    int ret;
    if (ctxt->spaceNr <= 0) return(0);
    ctxt->spaceNr--;
    if (ctxt->spaceNr > 0)
	ctxt->space = &ctxt->spaceTab[ctxt->spaceNr - 1];
    else
        ctxt->space = NULL;
    ret = ctxt->spaceTab[ctxt->spaceNr];
    ctxt->spaceTab[ctxt->spaceNr] = -1;
    return(ret);
}

/*
 * Macros for accessing the content. Those should be used only by the parser,
 * and not exported.
 *
 * Dirty macros, i.e. one often need to make assumption on the context to
 * use them
 *
 *   CUR_PTR return the current pointer to the xmlChar to be parsed.
 *           To be used with extreme caution since operations consuming
 *           characters may move the input buffer to a different location !
 *   CUR     returns the current xmlChar value, i.e. a 8 bit value if compiled
 *           This should be used internally by the parser
 *           only to compare to ASCII values otherwise it would break when
 *           running with UTF-8 encoding.
 *   RAW     same as CUR but in the input buffer, bypass any token
 *           extraction that may have been done
 *   NXT(n)  returns the n'th next xmlChar. Same as CUR is should be used only
 *           to compare on ASCII based substring.
 *   SKIP(n) Skip n xmlChar, and must also be used only to skip ASCII defined
944 945 946
 *           strings without newlines within the parser.
 *   NEXT1(l) Skip 1 xmlChar, and must also be used only to skip 1 non-newline ASCII 
 *           defined char within the parser.
947 948 949 950
 * Clean macros, not dependent of an ASCII context, expect UTF-8 encoding
 *
 *   NEXT    Skip to the next character, this does the proper decoding
 *           in UTF-8 mode. It also pop-up unfinished entities on the fly.
951
 *   NEXTL(l) Skip the current unicode character of l xmlChars long.
952 953 954 955 956 957 958 959
 *   CUR_CHAR(l) returns the current unicode character (int), set l
 *           to the number of xmlChars used for the encoding [0-5].
 *   CUR_SCHAR  same but operate on a string instead of the context
 *   COPY_BUF  copy the current unicode char to the target buffer, increment
 *            the index
 *   GROW, SHRINK  handling of input buffers
 */

960 961
#define RAW (*ctxt->input->cur)
#define CUR (*ctxt->input->cur)
962 963 964 965
#define NXT(val) ctxt->input->cur[(val)]
#define CUR_PTR ctxt->input->cur

#define SKIP(val) do {							\
966
    ctxt->nbChars += (val),ctxt->input->cur += (val),ctxt->input->col+=(val);			\
967
    if (*ctxt->input->cur == '%') xmlParserHandlePEReference(ctxt);	\
968
    if ((*ctxt->input->cur == 0) &&					\
969 970 971 972
        (xmlParserInputGrow(ctxt->input, INPUT_CHUNK) <= 0))		\
	    xmlPopInput(ctxt);						\
  } while (0)

973
#define SHRINK if ((ctxt->progressive == 0) &&				\
974 975
		   (ctxt->input->cur - ctxt->input->base > 2 * INPUT_CHUNK) && \
		   (ctxt->input->end - ctxt->input->cur < 2 * INPUT_CHUNK)) \
976 977 978 979 980 981 982
	xmlSHRINK (ctxt);

static void xmlSHRINK (xmlParserCtxtPtr ctxt) {
    xmlParserInputShrink(ctxt->input);
    if ((*ctxt->input->cur == 0) &&
        (xmlParserInputGrow(ctxt->input, INPUT_CHUNK) <= 0))
	    xmlPopInput(ctxt);
983
  }
984

985 986
#define GROW if ((ctxt->progressive == 0) &&				\
		 (ctxt->input->end - ctxt->input->cur < INPUT_CHUNK))	\
987 988 989 990 991 992 993
	xmlGROW (ctxt);

static void xmlGROW (xmlParserCtxtPtr ctxt) {
    xmlParserInputGrow(ctxt->input, INPUT_CHUNK);
    if ((*ctxt->input->cur == 0) &&
        (xmlParserInputGrow(ctxt->input, INPUT_CHUNK) <= 0))
	    xmlPopInput(ctxt);
994
}
995 996 997 998 999

#define SKIP_BLANKS xmlSkipBlankChars(ctxt)

#define NEXT xmlNextChar(ctxt)

1000
#define NEXT1 {								\
1001
	ctxt->input->col++;						\
1002 1003
	ctxt->input->cur++;						\
	ctxt->nbChars++;						\
1004
	if (*ctxt->input->cur == 0)					\
1005 1006 1007
	    xmlParserInputGrow(ctxt->input, INPUT_CHUNK);		\
    }

1008 1009 1010 1011
#define NEXTL(l) do {							\
    if (*(ctxt->input->cur) == '\n') {					\
	ctxt->input->line++; ctxt->input->col = 1;			\
    } else ctxt->input->col++;						\
1012
    ctxt->input->cur += l;				\
1013 1014 1015 1016 1017 1018 1019 1020
    if (*ctxt->input->cur == '%') xmlParserHandlePEReference(ctxt);	\
  } while (0)

#define CUR_CHAR(l) xmlCurrentChar(ctxt, &l)
#define CUR_SCHAR(s, l) xmlStringCurrentChar(ctxt, s, &l)

#define COPY_BUF(l,b,i,v)						\
    if (l == 1) b[i++] = (xmlChar) v;					\
1021
    else i += xmlCopyCharMultiByte(&b[i],v)
1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034

/**
 * xmlSkipBlankChars:
 * @ctxt:  the XML parser context
 *
 * skip all blanks character found at that point in the input streams.
 * It pops up finished entities in the process if allowable at that point.
 *
 * Returns the number of space chars skipped
 */

int
xmlSkipBlankChars(xmlParserCtxtPtr ctxt) {
1035
    int res = 0;
1036 1037 1038 1039 1040

    /*
     * It's Okay to use CUR/NEXT here since all the blanks are on
     * the ASCII range.
     */
1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051
    if ((ctxt->inputNr == 1) && (ctxt->instate != XML_PARSER_DTD)) {
	const xmlChar *cur;
	/*
	 * if we are in the document content, go really fast
	 */
	cur = ctxt->input->cur;
	while (IS_BLANK(*cur)) {
	    if (*cur == '\n') {
		ctxt->input->line++; ctxt->input->col = 1;
	    }
	    cur++;
1052
	    res++;
1053 1054 1055 1056 1057
	    if (*cur == 0) {
		ctxt->input->cur = cur;
		xmlParserInputGrow(ctxt->input, INPUT_CHUNK);
		cur = ctxt->input->cur;
	    }
1058
	}
1059 1060 1061 1062
	ctxt->input->cur = cur;
    } else {
	int cur;
	do {
1063
	    cur = CUR;
1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079
	    while (IS_BLANK(cur)) { /* CHECKED tstblanks.xml */
		NEXT;
		cur = CUR;
		res++;
	    }
	    while ((cur == 0) && (ctxt->inputNr > 1) &&
		   (ctxt->instate != XML_PARSER_COMMENT)) {
		xmlPopInput(ctxt);
		cur = CUR;
	    }
	    /*
	     * Need to handle support of entities branching here
	     */
	    if (*ctxt->input->cur == '%') xmlParserHandlePEReference(ctxt);
	} while (IS_BLANK(cur)); /* CHECKED tstblanks.xml */
    }
1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104
    return(res);
}

/************************************************************************
 *									*
 *		Commodity functions to handle entities			*
 *									*
 ************************************************************************/

/**
 * xmlPopInput:
 * @ctxt:  an XML parser context
 *
 * xmlPopInput: the current input pointed by ctxt->input came to an end
 *          pop it and return the next char.
 *
 * Returns the current xmlChar in the parser context
 */
xmlChar
xmlPopInput(xmlParserCtxtPtr ctxt) {
    if (ctxt->inputNr == 1) return(0); /* End of main Input */
    if (xmlParserDebugEntities)
	xmlGenericError(xmlGenericErrorContext,
		"Popping input %d\n", ctxt->inputNr);
    xmlFreeInputStream(inputPop(ctxt));
1105
    if ((*ctxt->input->cur == 0) &&
1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151
        (xmlParserInputGrow(ctxt->input, INPUT_CHUNK) <= 0))
	    return(xmlPopInput(ctxt));
    return(CUR);
}

/**
 * xmlPushInput:
 * @ctxt:  an XML parser context
 * @input:  an XML parser input fragment (entity, XML fragment ...).
 *
 * xmlPushInput: switch to a new input stream which is stacked on top
 *               of the previous one(s).
 */
void
xmlPushInput(xmlParserCtxtPtr ctxt, xmlParserInputPtr input) {
    if (input == NULL) return;

    if (xmlParserDebugEntities) {
	if ((ctxt->input != NULL) && (ctxt->input->filename))
	    xmlGenericError(xmlGenericErrorContext,
		    "%s(%d): ", ctxt->input->filename,
		    ctxt->input->line);
	xmlGenericError(xmlGenericErrorContext,
		"Pushing input %d : %.30s\n", ctxt->inputNr+1, input->cur);
    }
    inputPush(ctxt, input);
    GROW;
}

/**
 * xmlParseCharRef:
 * @ctxt:  an XML parser context
 *
 * parse Reference declarations
 *
 * [66] CharRef ::= '&#' [0-9]+ ';' |
 *                  '&#x' [0-9a-fA-F]+ ';'
 *
 * [ WFC: Legal Character ]
 * Characters referred to using character references must match the
 * production for Char. 
 *
 * Returns the value parsed (as an int), 0 in case of error
 */
int
xmlParseCharRef(xmlParserCtxtPtr ctxt) {
1152
    unsigned int val = 0;
1153 1154 1155 1156 1157
    int count = 0;

    /*
     * Using RAW/CUR/NEXT is okay since we are working on ASCII range here
     */
1158
    if ((RAW == '&') && (NXT(1) == '#') &&
1159 1160 1161 1162
        (NXT(2) == 'x')) {
	SKIP(3);
	GROW;
	while (RAW != ';') { /* loop blocked by count */
1163 1164 1165 1166 1167
	    if (count++ > 20) {
		count = 0;
		GROW;
	    }
	    if ((RAW >= '0') && (RAW <= '9')) 
1168 1169 1170 1171 1172 1173
	        val = val * 16 + (CUR - '0');
	    else if ((RAW >= 'a') && (RAW <= 'f') && (count < 20))
	        val = val * 16 + (CUR - 'a') + 10;
	    else if ((RAW >= 'A') && (RAW <= 'F') && (count < 20))
	        val = val * 16 + (CUR - 'A') + 10;
	    else {
1174
		xmlFatalErr(ctxt, XML_ERR_INVALID_HEX_CHARREF, NULL);
1175 1176 1177 1178 1179 1180 1181 1182
		val = 0;
		break;
	    }
	    NEXT;
	    count++;
	}
	if (RAW == ';') {
	    /* on purpose to avoid reentrancy problems with NEXT and SKIP */
1183
	    ctxt->input->col++;
1184 1185 1186
	    ctxt->nbChars ++;
	    ctxt->input->cur++;
	}
1187
    } else if  ((RAW == '&') && (NXT(1) == '#')) {
1188 1189 1190
	SKIP(2);
	GROW;
	while (RAW != ';') { /* loop blocked by count */
1191 1192 1193 1194 1195
	    if (count++ > 20) {
		count = 0;
		GROW;
	    }
	    if ((RAW >= '0') && (RAW <= '9')) 
1196 1197
	        val = val * 10 + (CUR - '0');
	    else {
1198
		xmlFatalErr(ctxt, XML_ERR_INVALID_DEC_CHARREF, NULL);
1199 1200 1201 1202 1203 1204 1205 1206
		val = 0;
		break;
	    }
	    NEXT;
	    count++;
	}
	if (RAW == ';') {
	    /* on purpose to avoid reentrancy problems with NEXT and SKIP */
1207
	    ctxt->input->col++;
1208 1209 1210 1211
	    ctxt->nbChars ++;
	    ctxt->input->cur++;
	}
    } else {
1212
        xmlFatalErr(ctxt, XML_ERR_INVALID_CHARREF, NULL);
1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224
    }

    /*
     * [ WFC: Legal Character ]
     * Characters referred to using character references must match the
     * production for Char. 
     */
    if (IS_CHAR(val)) {
        return(val);
    } else {
	ctxt->errNo = XML_ERR_INVALID_CHAR;
	if ((ctxt->sax != NULL) && (ctxt->sax->error != NULL))
1225 1226
	    ctxt->sax->error(ctxt->userData,
                             "xmlParseCharRef: invalid xmlChar value %d\n",
1227 1228
	                     val);
	ctxt->wellFormed = 0;
1229
	if (ctxt->recovery == 0) ctxt->disableSAX = 1;
1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251
    }
    return(0);
}

/**
 * xmlParseStringCharRef:
 * @ctxt:  an XML parser context
 * @str:  a pointer to an index in the string
 *
 * parse Reference declarations, variant parsing from a string rather
 * than an an input flow.
 *
 * [66] CharRef ::= '&#' [0-9]+ ';' |
 *                  '&#x' [0-9a-fA-F]+ ';'
 *
 * [ WFC: Legal Character ]
 * Characters referred to using character references must match the
 * production for Char. 
 *
 * Returns the value parsed (as an int), 0 in case of error, str will be
 *         updated to the current value of the index
 */
1252
static int
1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271
xmlParseStringCharRef(xmlParserCtxtPtr ctxt, const xmlChar **str) {
    const xmlChar *ptr;
    xmlChar cur;
    int val = 0;

    if ((str == NULL) || (*str == NULL)) return(0);
    ptr = *str;
    cur = *ptr;
    if ((cur == '&') && (ptr[1] == '#') && (ptr[2] == 'x')) {
	ptr += 3;
	cur = *ptr;
	while (cur != ';') { /* Non input consuming loop */
	    if ((cur >= '0') && (cur <= '9')) 
	        val = val * 16 + (cur - '0');
	    else if ((cur >= 'a') && (cur <= 'f'))
	        val = val * 16 + (cur - 'a') + 10;
	    else if ((cur >= 'A') && (cur <= 'F'))
	        val = val * 16 + (cur - 'A') + 10;
	    else {
1272
		xmlFatalErr(ctxt, XML_ERR_INVALID_HEX_CHARREF, NULL);
1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287
		val = 0;
		break;
	    }
	    ptr++;
	    cur = *ptr;
	}
	if (cur == ';')
	    ptr++;
    } else if  ((cur == '&') && (ptr[1] == '#')){
	ptr += 2;
	cur = *ptr;
	while (cur != ';') { /* Non input consuming loops */
	    if ((cur >= '0') && (cur <= '9')) 
	        val = val * 10 + (cur - '0');
	    else {
1288
		xmlFatalErr(ctxt, XML_ERR_INVALID_DEC_CHARREF, NULL);
1289 1290 1291 1292 1293 1294 1295 1296 1297
		val = 0;
		break;
	    }
	    ptr++;
	    cur = *ptr;
	}
	if (cur == ';')
	    ptr++;
    } else {
1298
	xmlFatalErr(ctxt, XML_ERR_INVALID_CHARREF, NULL);
1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313
	return(0);
    }
    *str = ptr;

    /*
     * [ WFC: Legal Character ]
     * Characters referred to using character references must match the
     * production for Char. 
     */
    if (IS_CHAR(val)) {
        return(val);
    } else {
	ctxt->errNo = XML_ERR_INVALID_CHAR;
	if ((ctxt->sax != NULL) && (ctxt->sax->error != NULL))
	    ctxt->sax->error(ctxt->userData,
1314
		             "xmlParseStringCharRef: invalid xmlChar value %d\n", val);
1315
	ctxt->wellFormed = 0;
1316
	if (ctxt->recovery == 0) ctxt->disableSAX = 1;
1317 1318 1319 1320
    }
    return(0);
}

1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333
/**
 * xmlNewBlanksWrapperInputStream:
 * @ctxt:  an XML parser context
 * @entity:  an Entity pointer
 *
 * Create a new input stream for wrapping
 * blanks around a PEReference
 *
 * Returns the new input stream or NULL
 */
 
static void deallocblankswrapper (xmlChar *str) {xmlFree(str);}
 
1334
static xmlParserInputPtr
1335 1336 1337 1338 1339
xmlNewBlanksWrapperInputStream(xmlParserCtxtPtr ctxt, xmlEntityPtr entity) {
    xmlParserInputPtr input;
    xmlChar *buffer;
    size_t length;
    if (entity == NULL) {
1340 1341
	xmlFatalErr(ctxt, XML_ERR_INTERNAL_ERROR,
	            "xmlNewBlanksWrapperInputStream entity\n");
1342 1343 1344 1345 1346 1347 1348 1349 1350 1351
	return(NULL);
    }
    if (xmlParserDebugEntities)
	xmlGenericError(xmlGenericErrorContext,
		"new blanks wrapper for entity: %s\n", entity->name);
    input = xmlNewInputStream(ctxt);
    if (input == NULL) {
	return(NULL);
    }
    length = xmlStrlen(entity->name) + 5;
1352
    buffer = xmlMallocAtomic(length);
1353
    if (buffer == NULL) {
1354
	xmlErrMemory(ctxt, NULL);
1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370
    	return(NULL);
    }
    buffer [0] = ' ';
    buffer [1] = '%';
    buffer [length-3] = ';';
    buffer [length-2] = ' ';
    buffer [length-1] = 0;
    memcpy(buffer + 2, entity->name, length - 5);
    input->free = deallocblankswrapper;
    input->base = buffer;
    input->cur = buffer;
    input->length = length;
    input->end = &buffer[length];
    return(input);
}

1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400
/**
 * xmlParserHandlePEReference:
 * @ctxt:  the parser context
 * 
 * [69] PEReference ::= '%' Name ';'
 *
 * [ WFC: No Recursion ]
 * A parsed entity must not contain a recursive
 * reference to itself, either directly or indirectly. 
 *
 * [ WFC: Entity Declared ]
 * In a document without any DTD, a document with only an internal DTD
 * subset which contains no parameter entity references, or a document
 * with "standalone='yes'", ...  ... The declaration of a parameter
 * entity must precede any reference to it...
 *
 * [ VC: Entity Declared ]
 * In a document with an external subset or external parameter entities
 * with "standalone='no'", ...  ... The declaration of a parameter entity
 * must precede any reference to it...
 *
 * [ WFC: In DTD ]
 * Parameter-entity references may only appear in the DTD.
 * NOTE: misleading but this is handled.
 *
 * A PEReference may have been detected in the current input stream
 * the handling is done accordingly to 
 *      http://www.w3.org/TR/REC-xml#entproc
 * i.e. 
 *   - Included in literal in entity values
1401
 *   - Included as Parameter Entity reference within DTDs
1402 1403 1404
 */
void
xmlParserHandlePEReference(xmlParserCtxtPtr ctxt) {
1405
    const xmlChar *name;
1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419
    xmlEntityPtr entity = NULL;
    xmlParserInputPtr input;

    if (RAW != '%') return;
    switch(ctxt->instate) {
	case XML_PARSER_CDATA_SECTION:
	    return;
        case XML_PARSER_COMMENT:
	    return;
	case XML_PARSER_START_TAG:
	    return;
	case XML_PARSER_END_TAG:
	    return;
        case XML_PARSER_EOF:
1420
	    xmlFatalErr(ctxt, XML_ERR_PEREF_AT_EOF, NULL);