• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * xinclude.c : Code to implement XInclude processing
3  *
4  * World Wide Web Consortium W3C Last Call Working Draft 10 November 2003
5  * http://www.w3.org/TR/2003/WD-xinclude-20031110
6  *
7  * See Copyright for the status of this software.
8  *
9  * daniel@veillard.com
10  */
11 
12 #define IN_LIBXML
13 #include "libxml.h"
14 
15 #include <string.h>
16 #include <libxml/xmlmemory.h>
17 #include <libxml/tree.h>
18 #include <libxml/parser.h>
19 #include <libxml/uri.h>
20 #include <libxml/xpath.h>
21 #include <libxml/xpointer.h>
22 #include <libxml/parserInternals.h>
23 #include <libxml/xmlerror.h>
24 #include <libxml/encoding.h>
25 #include <libxml/globals.h>
26 
27 #ifdef LIBXML_XINCLUDE_ENABLED
28 #include <libxml/xinclude.h>
29 
30 #include "buf.h"
31 
32 #define XINCLUDE_MAX_DEPTH 40
33 
34 /* #define DEBUG_XINCLUDE */
35 #ifdef DEBUG_XINCLUDE
36 #ifdef LIBXML_DEBUG_ENABLED
37 #include <libxml/debugXML.h>
38 #endif
39 #endif
40 
41 /************************************************************************
42  *									*
43  *			XInclude context handling			*
44  *									*
45  ************************************************************************/
46 
47 /*
48  * An XInclude context
49  */
50 typedef xmlChar *xmlURL;
51 
52 typedef struct _xmlXIncludeRef xmlXIncludeRef;
53 typedef xmlXIncludeRef *xmlXIncludeRefPtr;
54 struct _xmlXIncludeRef {
55     xmlChar              *URI; /* the fully resolved resource URL */
56     xmlChar         *fragment; /* the fragment in the URI */
57     xmlDocPtr		  doc; /* the parsed document */
58     xmlNodePtr            ref; /* the node making the reference in the source */
59     xmlNodePtr            inc; /* the included copy */
60     int                   xml; /* xml or txt */
61     int                 count; /* how many refs use that specific doc */
62     xmlXPathObjectPtr    xptr; /* the xpointer if needed */
63     int		      emptyFb; /* flag to show fallback empty */
64 };
65 
66 struct _xmlXIncludeCtxt {
67     xmlDocPtr             doc; /* the source document */
68     int               incBase; /* the first include for this document */
69     int                 incNr; /* number of includes */
70     int                incMax; /* size of includes tab */
71     xmlXIncludeRefPtr *incTab; /* array of included references */
72 
73     int                 txtNr; /* number of unparsed documents */
74     int                txtMax; /* size of unparsed documents tab */
75     xmlNodePtr        *txtTab; /* array of unparsed text nodes */
76     xmlURL         *txturlTab; /* array of unparsed text URLs */
77 
78     xmlChar *             url; /* the current URL processed */
79     int                 urlNr; /* number of URLs stacked */
80     int                urlMax; /* size of URL stack */
81     xmlChar *         *urlTab; /* URL stack */
82 
83     int              nbErrors; /* the number of errors detected */
84     int                legacy; /* using XINCLUDE_OLD_NS */
85     int            parseFlags; /* the flags used for parsing XML documents */
86     xmlChar *		 base; /* the current xml:base */
87 
88     void            *_private; /* application data */
89 };
90 
91 static int
92 xmlXIncludeDoProcess(xmlXIncludeCtxtPtr ctxt, xmlDocPtr doc, xmlNodePtr tree);
93 
94 
95 /************************************************************************
96  *									*
97  *			XInclude error handler				*
98  *									*
99  ************************************************************************/
100 
101 /**
102  * xmlXIncludeErrMemory:
103  * @extra:  extra information
104  *
105  * Handle an out of memory condition
106  */
107 static void
xmlXIncludeErrMemory(xmlXIncludeCtxtPtr ctxt,xmlNodePtr node,const char * extra)108 xmlXIncludeErrMemory(xmlXIncludeCtxtPtr ctxt, xmlNodePtr node,
109                      const char *extra)
110 {
111     if (ctxt != NULL)
112 	ctxt->nbErrors++;
113     __xmlRaiseError(NULL, NULL, NULL, ctxt, node, XML_FROM_XINCLUDE,
114                     XML_ERR_NO_MEMORY, XML_ERR_ERROR, NULL, 0,
115 		    extra, NULL, NULL, 0, 0,
116 		    "Memory allocation failed : %s\n", extra);
117 }
118 
119 /**
120  * xmlXIncludeErr:
121  * @ctxt: the XInclude context
122  * @node: the context node
123  * @msg:  the error message
124  * @extra:  extra information
125  *
126  * Handle an XInclude error
127  */
128 static void LIBXML_ATTR_FORMAT(4,0)
xmlXIncludeErr(xmlXIncludeCtxtPtr ctxt,xmlNodePtr node,int error,const char * msg,const xmlChar * extra)129 xmlXIncludeErr(xmlXIncludeCtxtPtr ctxt, xmlNodePtr node, int error,
130                const char *msg, const xmlChar *extra)
131 {
132     if (ctxt != NULL)
133 	ctxt->nbErrors++;
134     __xmlRaiseError(NULL, NULL, NULL, ctxt, node, XML_FROM_XINCLUDE,
135                     error, XML_ERR_ERROR, NULL, 0,
136 		    (const char *) extra, NULL, NULL, 0, 0,
137 		    msg, (const char *) extra);
138 }
139 
140 #if 0
141 /**
142  * xmlXIncludeWarn:
143  * @ctxt: the XInclude context
144  * @node: the context node
145  * @msg:  the error message
146  * @extra:  extra information
147  *
148  * Emit an XInclude warning.
149  */
150 static void LIBXML_ATTR_FORMAT(4,0)
151 xmlXIncludeWarn(xmlXIncludeCtxtPtr ctxt, xmlNodePtr node, int error,
152                const char *msg, const xmlChar *extra)
153 {
154     __xmlRaiseError(NULL, NULL, NULL, ctxt, node, XML_FROM_XINCLUDE,
155                     error, XML_ERR_WARNING, NULL, 0,
156 		    (const char *) extra, NULL, NULL, 0, 0,
157 		    msg, (const char *) extra);
158 }
159 #endif
160 
161 /**
162  * xmlXIncludeGetProp:
163  * @ctxt:  the XInclude context
164  * @cur:  the node
165  * @name:  the attribute name
166  *
167  * Get an XInclude attribute
168  *
169  * Returns the value (to be freed) or NULL if not found
170  */
171 static xmlChar *
xmlXIncludeGetProp(xmlXIncludeCtxtPtr ctxt,xmlNodePtr cur,const xmlChar * name)172 xmlXIncludeGetProp(xmlXIncludeCtxtPtr ctxt, xmlNodePtr cur,
173                    const xmlChar *name) {
174     xmlChar *ret;
175 
176     ret = xmlGetNsProp(cur, XINCLUDE_NS, name);
177     if (ret != NULL)
178         return(ret);
179     if (ctxt->legacy != 0) {
180 	ret = xmlGetNsProp(cur, XINCLUDE_OLD_NS, name);
181 	if (ret != NULL)
182 	    return(ret);
183     }
184     ret = xmlGetProp(cur, name);
185     return(ret);
186 }
187 /**
188  * xmlXIncludeFreeRef:
189  * @ref: the XInclude reference
190  *
191  * Free an XInclude reference
192  */
193 static void
xmlXIncludeFreeRef(xmlXIncludeRefPtr ref)194 xmlXIncludeFreeRef(xmlXIncludeRefPtr ref) {
195     if (ref == NULL)
196 	return;
197 #ifdef DEBUG_XINCLUDE
198     xmlGenericError(xmlGenericErrorContext, "Freeing ref\n");
199 #endif
200     if (ref->doc != NULL) {
201 #ifdef DEBUG_XINCLUDE
202 	xmlGenericError(xmlGenericErrorContext, "Freeing doc %s\n", ref->URI);
203 #endif
204 	xmlFreeDoc(ref->doc);
205     }
206     if (ref->URI != NULL)
207 	xmlFree(ref->URI);
208     if (ref->fragment != NULL)
209 	xmlFree(ref->fragment);
210     if (ref->xptr != NULL)
211 	xmlXPathFreeObject(ref->xptr);
212     xmlFree(ref);
213 }
214 
215 /**
216  * xmlXIncludeNewRef:
217  * @ctxt: the XInclude context
218  * @URI:  the resource URI
219  *
220  * Creates a new reference within an XInclude context
221  *
222  * Returns the new set
223  */
224 static xmlXIncludeRefPtr
xmlXIncludeNewRef(xmlXIncludeCtxtPtr ctxt,const xmlChar * URI,xmlNodePtr ref)225 xmlXIncludeNewRef(xmlXIncludeCtxtPtr ctxt, const xmlChar *URI,
226 	          xmlNodePtr ref) {
227     xmlXIncludeRefPtr ret;
228 
229 #ifdef DEBUG_XINCLUDE
230     xmlGenericError(xmlGenericErrorContext, "New ref %s\n", URI);
231 #endif
232     ret = (xmlXIncludeRefPtr) xmlMalloc(sizeof(xmlXIncludeRef));
233     if (ret == NULL) {
234         xmlXIncludeErrMemory(ctxt, ref, "growing XInclude context");
235 	return(NULL);
236     }
237     memset(ret, 0, sizeof(xmlXIncludeRef));
238     if (URI == NULL)
239 	ret->URI = NULL;
240     else
241 	ret->URI = xmlStrdup(URI);
242     ret->fragment = NULL;
243     ret->ref = ref;
244     ret->doc = NULL;
245     ret->count = 0;
246     ret->xml = 0;
247     ret->inc = NULL;
248     if (ctxt->incMax == 0) {
249 	ctxt->incMax = 4;
250         ctxt->incTab = (xmlXIncludeRefPtr *) xmlMalloc(ctxt->incMax *
251 					      sizeof(ctxt->incTab[0]));
252         if (ctxt->incTab == NULL) {
253 	    xmlXIncludeErrMemory(ctxt, ref, "growing XInclude context");
254 	    xmlXIncludeFreeRef(ret);
255 	    return(NULL);
256 	}
257     }
258     if (ctxt->incNr >= ctxt->incMax) {
259 	ctxt->incMax *= 2;
260         ctxt->incTab = (xmlXIncludeRefPtr *) xmlRealloc(ctxt->incTab,
261 	             ctxt->incMax * sizeof(ctxt->incTab[0]));
262         if (ctxt->incTab == NULL) {
263 	    xmlXIncludeErrMemory(ctxt, ref, "growing XInclude context");
264 	    xmlXIncludeFreeRef(ret);
265 	    return(NULL);
266 	}
267     }
268     ctxt->incTab[ctxt->incNr++] = ret;
269     return(ret);
270 }
271 
272 /**
273  * xmlXIncludeNewContext:
274  * @doc:  an XML Document
275  *
276  * Creates a new XInclude context
277  *
278  * Returns the new set
279  */
280 xmlXIncludeCtxtPtr
xmlXIncludeNewContext(xmlDocPtr doc)281 xmlXIncludeNewContext(xmlDocPtr doc) {
282     xmlXIncludeCtxtPtr ret;
283 
284 #ifdef DEBUG_XINCLUDE
285     xmlGenericError(xmlGenericErrorContext, "New context\n");
286 #endif
287     if (doc == NULL)
288 	return(NULL);
289     ret = (xmlXIncludeCtxtPtr) xmlMalloc(sizeof(xmlXIncludeCtxt));
290     if (ret == NULL) {
291 	xmlXIncludeErrMemory(NULL, (xmlNodePtr) doc,
292 	                     "creating XInclude context");
293 	return(NULL);
294     }
295     memset(ret, 0, sizeof(xmlXIncludeCtxt));
296     ret->doc = doc;
297     ret->incNr = 0;
298     ret->incBase = 0;
299     ret->incMax = 0;
300     ret->incTab = NULL;
301     ret->nbErrors = 0;
302     return(ret);
303 }
304 
305 /**
306  * xmlXIncludeURLPush:
307  * @ctxt:  the parser context
308  * @value:  the url
309  *
310  * Pushes a new url on top of the url stack
311  *
312  * Returns -1 in case of error, the index in the stack otherwise
313  */
314 static int
xmlXIncludeURLPush(xmlXIncludeCtxtPtr ctxt,const xmlChar * value)315 xmlXIncludeURLPush(xmlXIncludeCtxtPtr ctxt,
316 	           const xmlChar *value)
317 {
318     if (ctxt->urlNr > XINCLUDE_MAX_DEPTH) {
319 	xmlXIncludeErr(ctxt, NULL, XML_XINCLUDE_RECURSION,
320 	               "detected a recursion in %s\n", value);
321 	return(-1);
322     }
323     if (ctxt->urlTab == NULL) {
324 	ctxt->urlMax = 4;
325 	ctxt->urlNr = 0;
326 	ctxt->urlTab = (xmlChar * *) xmlMalloc(
327 		        ctxt->urlMax * sizeof(ctxt->urlTab[0]));
328         if (ctxt->urlTab == NULL) {
329 	    xmlXIncludeErrMemory(ctxt, NULL, "adding URL");
330             return (-1);
331         }
332     }
333     if (ctxt->urlNr >= ctxt->urlMax) {
334         ctxt->urlMax *= 2;
335         ctxt->urlTab =
336             (xmlChar * *) xmlRealloc(ctxt->urlTab,
337                                       ctxt->urlMax *
338                                       sizeof(ctxt->urlTab[0]));
339         if (ctxt->urlTab == NULL) {
340 	    xmlXIncludeErrMemory(ctxt, NULL, "adding URL");
341             return (-1);
342         }
343     }
344     ctxt->url = ctxt->urlTab[ctxt->urlNr] = xmlStrdup(value);
345     return (ctxt->urlNr++);
346 }
347 
348 /**
349  * xmlXIncludeURLPop:
350  * @ctxt: the parser context
351  *
352  * Pops the top URL from the URL stack
353  */
354 static void
xmlXIncludeURLPop(xmlXIncludeCtxtPtr ctxt)355 xmlXIncludeURLPop(xmlXIncludeCtxtPtr ctxt)
356 {
357     xmlChar * ret;
358 
359     if (ctxt->urlNr <= 0)
360         return;
361     ctxt->urlNr--;
362     if (ctxt->urlNr > 0)
363         ctxt->url = ctxt->urlTab[ctxt->urlNr - 1];
364     else
365         ctxt->url = NULL;
366     ret = ctxt->urlTab[ctxt->urlNr];
367     ctxt->urlTab[ctxt->urlNr] = NULL;
368     if (ret != NULL)
369 	xmlFree(ret);
370 }
371 
372 /**
373  * xmlXIncludeFreeContext:
374  * @ctxt: the XInclude context
375  *
376  * Free an XInclude context
377  */
378 void
xmlXIncludeFreeContext(xmlXIncludeCtxtPtr ctxt)379 xmlXIncludeFreeContext(xmlXIncludeCtxtPtr ctxt) {
380     int i;
381 
382 #ifdef DEBUG_XINCLUDE
383     xmlGenericError(xmlGenericErrorContext, "Freeing context\n");
384 #endif
385     if (ctxt == NULL)
386 	return;
387     while (ctxt->urlNr > 0)
388 	xmlXIncludeURLPop(ctxt);
389     if (ctxt->urlTab != NULL)
390 	xmlFree(ctxt->urlTab);
391     for (i = 0;i < ctxt->incNr;i++) {
392 	if (ctxt->incTab[i] != NULL)
393 	    xmlXIncludeFreeRef(ctxt->incTab[i]);
394     }
395     if (ctxt->txturlTab != NULL) {
396 	for (i = 0;i < ctxt->txtNr;i++) {
397 	    if (ctxt->txturlTab[i] != NULL)
398 		xmlFree(ctxt->txturlTab[i]);
399 	}
400     }
401     if (ctxt->incTab != NULL)
402 	xmlFree(ctxt->incTab);
403     if (ctxt->txtTab != NULL)
404 	xmlFree(ctxt->txtTab);
405     if (ctxt->txturlTab != NULL)
406 	xmlFree(ctxt->txturlTab);
407     if (ctxt->base != NULL) {
408         xmlFree(ctxt->base);
409     }
410     xmlFree(ctxt);
411 }
412 
413 /**
414  * xmlXIncludeParseFile:
415  * @ctxt:  the XInclude context
416  * @URL:  the URL or file path
417  *
418  * parse a document for XInclude
419  */
420 static xmlDocPtr
xmlXIncludeParseFile(xmlXIncludeCtxtPtr ctxt,const char * URL)421 xmlXIncludeParseFile(xmlXIncludeCtxtPtr ctxt, const char *URL) {
422     xmlDocPtr ret;
423     xmlParserCtxtPtr pctxt;
424     xmlParserInputPtr inputStream;
425 
426     xmlInitParser();
427 
428     pctxt = xmlNewParserCtxt();
429     if (pctxt == NULL) {
430 	xmlXIncludeErrMemory(ctxt, NULL, "cannot allocate parser context");
431 	return(NULL);
432     }
433 
434     /*
435      * pass in the application data to the parser context.
436      */
437     pctxt->_private = ctxt->_private;
438 
439     /*
440      * try to ensure that new documents included are actually
441      * built with the same dictionary as the including document.
442      */
443     if ((ctxt->doc != NULL) && (ctxt->doc->dict != NULL)) {
444        if (pctxt->dict != NULL)
445             xmlDictFree(pctxt->dict);
446 	pctxt->dict = ctxt->doc->dict;
447 	xmlDictReference(pctxt->dict);
448     }
449 
450     xmlCtxtUseOptions(pctxt, ctxt->parseFlags | XML_PARSE_DTDLOAD);
451 
452     /* Don't read from stdin. */
453     if ((URL != NULL) && (strcmp(URL, "-") == 0))
454         URL = "./-";
455 
456     inputStream = xmlLoadExternalEntity(URL, NULL, pctxt);
457     if (inputStream == NULL) {
458 	xmlFreeParserCtxt(pctxt);
459 	return(NULL);
460     }
461 
462     inputPush(pctxt, inputStream);
463 
464     if (pctxt->directory == NULL)
465         pctxt->directory = xmlParserGetDirectory(URL);
466 
467     pctxt->loadsubset |= XML_DETECT_IDS;
468 
469     xmlParseDocument(pctxt);
470 
471     if (pctxt->wellFormed) {
472         ret = pctxt->myDoc;
473     }
474     else {
475         ret = NULL;
476 	if (pctxt->myDoc != NULL)
477 	    xmlFreeDoc(pctxt->myDoc);
478         pctxt->myDoc = NULL;
479     }
480     xmlFreeParserCtxt(pctxt);
481 
482     return(ret);
483 }
484 
485 /**
486  * xmlXIncludeAddNode:
487  * @ctxt:  the XInclude context
488  * @cur:  the new node
489  *
490  * Add a new node to process to an XInclude context
491  */
492 static int
xmlXIncludeAddNode(xmlXIncludeCtxtPtr ctxt,xmlNodePtr cur)493 xmlXIncludeAddNode(xmlXIncludeCtxtPtr ctxt, xmlNodePtr cur) {
494     xmlXIncludeRefPtr ref;
495     xmlURIPtr uri;
496     xmlChar *URL;
497     xmlChar *fragment = NULL;
498     xmlChar *href;
499     xmlChar *parse;
500     xmlChar *base;
501     xmlChar *URI;
502     int xml = 1, i; /* default Issue 64 */
503     int local = 0;
504 
505 
506     if (ctxt == NULL)
507 	return(-1);
508     if (cur == NULL)
509 	return(-1);
510 
511 #ifdef DEBUG_XINCLUDE
512     xmlGenericError(xmlGenericErrorContext, "Add node\n");
513 #endif
514     /*
515      * read the attributes
516      */
517     href = xmlXIncludeGetProp(ctxt, cur, XINCLUDE_HREF);
518     if (href == NULL) {
519 	href = xmlStrdup(BAD_CAST ""); /* @@@@ href is now optional */
520 	if (href == NULL)
521 	    return(-1);
522     }
523     if ((href[0] == '#') || (href[0] == 0))
524 	local = 1;
525     parse = xmlXIncludeGetProp(ctxt, cur, XINCLUDE_PARSE);
526     if (parse != NULL) {
527 	if (xmlStrEqual(parse, XINCLUDE_PARSE_XML))
528 	    xml = 1;
529 	else if (xmlStrEqual(parse, XINCLUDE_PARSE_TEXT))
530 	    xml = 0;
531 	else {
532 	    xmlXIncludeErr(ctxt, cur, XML_XINCLUDE_PARSE_VALUE,
533 	                   "invalid value %s for 'parse'\n", parse);
534 	    if (href != NULL)
535 		xmlFree(href);
536 	    if (parse != NULL)
537 		xmlFree(parse);
538 	    return(-1);
539 	}
540     }
541 
542     /*
543      * compute the URI
544      */
545     base = xmlNodeGetBase(ctxt->doc, cur);
546     if (base == NULL) {
547 	URI = xmlBuildURI(href, ctxt->doc->URL);
548     } else {
549 	URI = xmlBuildURI(href, base);
550     }
551     if (URI == NULL) {
552 	xmlChar *escbase;
553 	xmlChar *eschref;
554 	/*
555 	 * Some escaping may be needed
556 	 */
557 	escbase = xmlURIEscape(base);
558 	eschref = xmlURIEscape(href);
559 	URI = xmlBuildURI(eschref, escbase);
560 	if (escbase != NULL)
561 	    xmlFree(escbase);
562 	if (eschref != NULL)
563 	    xmlFree(eschref);
564     }
565     if (parse != NULL)
566 	xmlFree(parse);
567     if (href != NULL)
568 	xmlFree(href);
569     if (base != NULL)
570 	xmlFree(base);
571     if (URI == NULL) {
572 	xmlXIncludeErr(ctxt, cur, XML_XINCLUDE_HREF_URI,
573 	               "failed build URL\n", NULL);
574 	return(-1);
575     }
576     fragment = xmlXIncludeGetProp(ctxt, cur, XINCLUDE_PARSE_XPOINTER);
577 
578     /*
579      * Check the URL and remove any fragment identifier
580      */
581     uri = xmlParseURI((const char *)URI);
582     if (uri == NULL) {
583 	xmlXIncludeErr(ctxt, cur, XML_XINCLUDE_HREF_URI,
584 	               "invalid value URI %s\n", URI);
585 	if (fragment != NULL)
586 	    xmlFree(fragment);
587 	xmlFree(URI);
588 	return(-1);
589     }
590 
591     if (uri->fragment != NULL) {
592         if (ctxt->legacy != 0) {
593 	    if (fragment == NULL) {
594 		fragment = (xmlChar *) uri->fragment;
595 	    } else {
596 		xmlFree(uri->fragment);
597 	    }
598 	} else {
599 	    xmlXIncludeErr(ctxt, cur, XML_XINCLUDE_FRAGMENT_ID,
600        "Invalid fragment identifier in URI %s use the xpointer attribute\n",
601                            URI);
602 	    if (fragment != NULL)
603 	        xmlFree(fragment);
604 	    xmlFreeURI(uri);
605 	    xmlFree(URI);
606 	    return(-1);
607 	}
608 	uri->fragment = NULL;
609     }
610     URL = xmlSaveUri(uri);
611     xmlFreeURI(uri);
612     xmlFree(URI);
613     if (URL == NULL) {
614 	xmlXIncludeErr(ctxt, cur, XML_XINCLUDE_HREF_URI,
615 	               "invalid value URI %s\n", URI);
616 	if (fragment != NULL)
617 	    xmlFree(fragment);
618 	return(-1);
619     }
620 
621     /*
622      * If local and xml then we need a fragment
623      */
624     if ((local == 1) && (xml == 1) &&
625         ((fragment == NULL) || (fragment[0] == 0))) {
626 	xmlXIncludeErr(ctxt, cur, XML_XINCLUDE_RECURSION,
627 	               "detected a local recursion with no xpointer in %s\n",
628 		       URL);
629 	if (fragment != NULL)
630 	    xmlFree(fragment);
631 	return(-1);
632     }
633 
634     /*
635      * Check the URL against the stack for recursions
636      */
637     if ((!local) && (xml == 1)) {
638 	for (i = 0;i < ctxt->urlNr;i++) {
639 	    if (xmlStrEqual(URL, ctxt->urlTab[i])) {
640 		xmlXIncludeErr(ctxt, cur, XML_XINCLUDE_RECURSION,
641 		               "detected a recursion in %s\n", URL);
642 		return(-1);
643 	    }
644 	}
645     }
646 
647     ref = xmlXIncludeNewRef(ctxt, URL, cur);
648     if (ref == NULL) {
649 	return(-1);
650     }
651     ref->fragment = fragment;
652     ref->doc = NULL;
653     ref->xml = xml;
654     ref->count = 1;
655     xmlFree(URL);
656     return(0);
657 }
658 
659 /**
660  * xmlXIncludeRecurseDoc:
661  * @ctxt:  the XInclude context
662  * @doc:  the new document
663  * @url:  the associated URL
664  *
665  * The XInclude recursive nature is handled at this point.
666  */
667 static void
xmlXIncludeRecurseDoc(xmlXIncludeCtxtPtr ctxt,xmlDocPtr doc,const xmlURL url ATTRIBUTE_UNUSED)668 xmlXIncludeRecurseDoc(xmlXIncludeCtxtPtr ctxt, xmlDocPtr doc,
669 	              const xmlURL url ATTRIBUTE_UNUSED) {
670     xmlXIncludeCtxtPtr newctxt;
671     int i;
672 
673     /*
674      * Avoid recursion in already substituted resources
675     for (i = 0;i < ctxt->urlNr;i++) {
676 	if (xmlStrEqual(doc->URL, ctxt->urlTab[i]))
677 	    return;
678     }
679      */
680 
681 #ifdef DEBUG_XINCLUDE
682     xmlGenericError(xmlGenericErrorContext, "Recursing in doc %s\n", doc->URL);
683 #endif
684     /*
685      * Handle recursion here.
686      */
687 
688     newctxt = xmlXIncludeNewContext(doc);
689     if (newctxt != NULL) {
690 	/*
691 	 * Copy the private user data
692 	 */
693 	newctxt->_private = ctxt->_private;
694 	/*
695 	 * Copy the existing document set
696 	 */
697 	newctxt->incMax = ctxt->incMax;
698 	newctxt->incNr = ctxt->incNr;
699         newctxt->incTab = (xmlXIncludeRefPtr *) xmlMalloc(newctxt->incMax *
700 		                          sizeof(newctxt->incTab[0]));
701         if (newctxt->incTab == NULL) {
702 	    xmlXIncludeErrMemory(ctxt, (xmlNodePtr) doc, "processing doc");
703 	    xmlFree(newctxt);
704 	    return;
705 	}
706 	/*
707 	 * copy the urlTab
708 	 */
709 	newctxt->urlMax = ctxt->urlMax;
710 	newctxt->urlNr = ctxt->urlNr;
711 	newctxt->urlTab = ctxt->urlTab;
712 
713 	/*
714 	 * Inherit the existing base
715 	 */
716 	newctxt->base = xmlStrdup(ctxt->base);
717 
718 	/*
719 	 * Inherit the documents already in use by other includes
720 	 */
721 	newctxt->incBase = ctxt->incNr;
722 	for (i = 0;i < ctxt->incNr;i++) {
723 	    newctxt->incTab[i] = ctxt->incTab[i];
724 	    newctxt->incTab[i]->count++; /* prevent the recursion from
725 					    freeing it */
726 	}
727 	/*
728 	 * The new context should also inherit the Parse Flags
729 	 * (bug 132597)
730 	 */
731 	newctxt->parseFlags = ctxt->parseFlags;
732 	xmlXIncludeDoProcess(newctxt, doc, xmlDocGetRootElement(doc));
733 	for (i = 0;i < ctxt->incNr;i++) {
734 	    newctxt->incTab[i]->count--;
735 	    newctxt->incTab[i] = NULL;
736 	}
737 
738 	/* urlTab may have been reallocated */
739 	ctxt->urlTab = newctxt->urlTab;
740 	ctxt->urlMax = newctxt->urlMax;
741 
742 	newctxt->urlMax = 0;
743 	newctxt->urlNr = 0;
744 	newctxt->urlTab = NULL;
745 
746 	xmlXIncludeFreeContext(newctxt);
747     }
748 #ifdef DEBUG_XINCLUDE
749     xmlGenericError(xmlGenericErrorContext, "Done recursing in doc %s\n", url);
750 #endif
751 }
752 
753 /**
754  * xmlXIncludeAddTxt:
755  * @ctxt:  the XInclude context
756  * @txt:  the new text node
757  * @url:  the associated URL
758  *
759  * Add a new text node to the list
760  */
761 static void
xmlXIncludeAddTxt(xmlXIncludeCtxtPtr ctxt,xmlNodePtr txt,const xmlURL url)762 xmlXIncludeAddTxt(xmlXIncludeCtxtPtr ctxt, xmlNodePtr txt, const xmlURL url) {
763 #ifdef DEBUG_XINCLUDE
764     xmlGenericError(xmlGenericErrorContext, "Adding text %s\n", url);
765 #endif
766     if (ctxt->txtMax == 0) {
767 	ctxt->txtMax = 4;
768         ctxt->txtTab = (xmlNodePtr *) xmlMalloc(ctxt->txtMax *
769 		                          sizeof(ctxt->txtTab[0]));
770         if (ctxt->txtTab == NULL) {
771 	    xmlXIncludeErrMemory(ctxt, NULL, "processing text");
772 	    return;
773 	}
774         ctxt->txturlTab = (xmlURL *) xmlMalloc(ctxt->txtMax *
775 		                          sizeof(ctxt->txturlTab[0]));
776         if (ctxt->txturlTab == NULL) {
777 	    xmlXIncludeErrMemory(ctxt, NULL, "processing text");
778 	    return;
779 	}
780     }
781     if (ctxt->txtNr >= ctxt->txtMax) {
782 	ctxt->txtMax *= 2;
783         ctxt->txtTab = (xmlNodePtr *) xmlRealloc(ctxt->txtTab,
784 	             ctxt->txtMax * sizeof(ctxt->txtTab[0]));
785         if (ctxt->txtTab == NULL) {
786 	    xmlXIncludeErrMemory(ctxt, NULL, "processing text");
787 	    return;
788 	}
789         ctxt->txturlTab = (xmlURL *) xmlRealloc(ctxt->txturlTab,
790 	             ctxt->txtMax * sizeof(ctxt->txturlTab[0]));
791         if (ctxt->txturlTab == NULL) {
792 	    xmlXIncludeErrMemory(ctxt, NULL, "processing text");
793 	    return;
794 	}
795     }
796     ctxt->txtTab[ctxt->txtNr] = txt;
797     ctxt->txturlTab[ctxt->txtNr] = xmlStrdup(url);
798     ctxt->txtNr++;
799 }
800 
801 /************************************************************************
802  *									*
803  *			Node copy with specific semantic		*
804  *									*
805  ************************************************************************/
806 
807 static xmlNodePtr
808 xmlXIncludeCopyNodeList(xmlXIncludeCtxtPtr ctxt, xmlDocPtr target,
809 	                xmlDocPtr source, xmlNodePtr elem);
810 
811 /**
812  * xmlXIncludeCopyNode:
813  * @ctxt:  the XInclude context
814  * @target:  the document target
815  * @source:  the document source
816  * @elem:  the element
817  *
818  * Make a copy of the node while preserving the XInclude semantic
819  * of the Infoset copy
820  */
821 static xmlNodePtr
xmlXIncludeCopyNode(xmlXIncludeCtxtPtr ctxt,xmlDocPtr target,xmlDocPtr source,xmlNodePtr elem)822 xmlXIncludeCopyNode(xmlXIncludeCtxtPtr ctxt, xmlDocPtr target,
823 	            xmlDocPtr source, xmlNodePtr elem) {
824     xmlNodePtr result = NULL;
825 
826     if ((ctxt == NULL) || (target == NULL) || (source == NULL) ||
827 	(elem == NULL))
828 	return(NULL);
829     if (elem->type == XML_DTD_NODE)
830 	return(NULL);
831     if (elem->type == XML_DOCUMENT_NODE)
832 	result = xmlXIncludeCopyNodeList(ctxt, target, source, elem->children);
833     else
834         result = xmlDocCopyNode(elem, target, 1);
835     return(result);
836 }
837 
838 /**
839  * xmlXIncludeCopyNodeList:
840  * @ctxt:  the XInclude context
841  * @target:  the document target
842  * @source:  the document source
843  * @elem:  the element list
844  *
845  * Make a copy of the node list while preserving the XInclude semantic
846  * of the Infoset copy
847  */
848 static xmlNodePtr
xmlXIncludeCopyNodeList(xmlXIncludeCtxtPtr ctxt,xmlDocPtr target,xmlDocPtr source,xmlNodePtr elem)849 xmlXIncludeCopyNodeList(xmlXIncludeCtxtPtr ctxt, xmlDocPtr target,
850 	                xmlDocPtr source, xmlNodePtr elem) {
851     xmlNodePtr cur, res, result = NULL, last = NULL;
852 
853     if ((ctxt == NULL) || (target == NULL) || (source == NULL) ||
854 	(elem == NULL))
855 	return(NULL);
856     cur = elem;
857     while (cur != NULL) {
858 	res = xmlXIncludeCopyNode(ctxt, target, source, cur);
859 	if (res != NULL) {
860 	    if (result == NULL) {
861 		result = last = res;
862 	    } else {
863 		last->next = res;
864 		res->prev = last;
865 		last = res;
866 	    }
867 	}
868 	cur = cur->next;
869     }
870     return(result);
871 }
872 
873 /**
874  * xmlXIncludeGetNthChild:
875  * @cur:  the node
876  * @no:  the child number
877  *
878  * Returns the @n'th element child of @cur or NULL
879  */
880 static xmlNodePtr
xmlXIncludeGetNthChild(xmlNodePtr cur,int no)881 xmlXIncludeGetNthChild(xmlNodePtr cur, int no) {
882     int i;
883     if ((cur == NULL) || (cur->type == XML_NAMESPACE_DECL))
884         return(NULL);
885     cur = cur->children;
886     for (i = 0;i <= no;cur = cur->next) {
887 	if (cur == NULL)
888 	    return(cur);
889 	if ((cur->type == XML_ELEMENT_NODE) ||
890 	    (cur->type == XML_DOCUMENT_NODE) ||
891 	    (cur->type == XML_HTML_DOCUMENT_NODE)) {
892 	    i++;
893 	    if (i == no)
894 		break;
895 	}
896     }
897     return(cur);
898 }
899 
900 xmlNodePtr xmlXPtrAdvanceNode(xmlNodePtr cur, int *level); /* in xpointer.c */
901 /**
902  * xmlXIncludeCopyRange:
903  * @ctxt:  the XInclude context
904  * @target:  the document target
905  * @source:  the document source
906  * @obj:  the XPointer result from the evaluation.
907  *
908  * Build a node list tree copy of the XPointer result.
909  *
910  * Returns an xmlNodePtr list or NULL.
911  *         The caller has to free the node tree.
912  */
913 static xmlNodePtr
xmlXIncludeCopyRange(xmlXIncludeCtxtPtr ctxt,xmlDocPtr target,xmlDocPtr source,xmlXPathObjectPtr range)914 xmlXIncludeCopyRange(xmlXIncludeCtxtPtr ctxt, xmlDocPtr target,
915 	                xmlDocPtr source, xmlXPathObjectPtr range) {
916     /* pointers to generated nodes */
917     xmlNodePtr list = NULL, last = NULL, listParent = NULL;
918     xmlNodePtr tmp, tmp2;
919     /* pointers to traversal nodes */
920     xmlNodePtr start, cur, end;
921     int index1, index2;
922     int level = 0, lastLevel = 0, endLevel = 0, endFlag = 0;
923 
924     if ((ctxt == NULL) || (target == NULL) || (source == NULL) ||
925 	(range == NULL))
926 	return(NULL);
927     if (range->type != XPATH_RANGE)
928 	return(NULL);
929     start = (xmlNodePtr) range->user;
930 
931     if ((start == NULL) || (start->type == XML_NAMESPACE_DECL))
932 	return(NULL);
933     end = range->user2;
934     if (end == NULL)
935 	return(xmlDocCopyNode(start, target, 1));
936     if (end->type == XML_NAMESPACE_DECL)
937         return(NULL);
938 
939     cur = start;
940     index1 = range->index;
941     index2 = range->index2;
942     /*
943      * level is depth of the current node under consideration
944      * list is the pointer to the root of the output tree
945      * listParent is a pointer to the parent of output tree (within
946        the included file) in case we need to add another level
947      * last is a pointer to the last node added to the output tree
948      * lastLevel is the depth of last (relative to the root)
949      */
950     while (cur != NULL) {
951 	/*
952 	 * Check if our output tree needs a parent
953 	 */
954 	if (level < 0) {
955 	    while (level < 0) {
956 	        /* copy must include namespaces and properties */
957 	        tmp2 = xmlDocCopyNode(listParent, target, 2);
958 	        xmlAddChild(tmp2, list);
959 	        list = tmp2;
960 	        listParent = listParent->parent;
961 	        level++;
962 	    }
963 	    last = list;
964 	    lastLevel = 0;
965 	}
966 	/*
967 	 * Check whether we need to change our insertion point
968 	 */
969 	while (level < lastLevel) {
970 	    last = last->parent;
971 	    lastLevel --;
972 	}
973 	if (cur == end) {	/* Are we at the end of the range? */
974 	    if (cur->type == XML_TEXT_NODE) {
975 		const xmlChar *content = cur->content;
976 		int len;
977 
978 		if (content == NULL) {
979 		    tmp = xmlNewTextLen(NULL, 0);
980 		} else {
981 		    len = index2;
982 		    if ((cur == start) && (index1 > 1)) {
983 			content += (index1 - 1);
984 			len -= (index1 - 1);
985 		    } else {
986 			len = index2;
987 		    }
988 		    tmp = xmlNewTextLen(content, len);
989 		}
990 		/* single sub text node selection */
991 		if (list == NULL)
992 		    return(tmp);
993 		/* prune and return full set */
994 		if (level == lastLevel)
995 		    xmlAddNextSibling(last, tmp);
996 		else
997 		    xmlAddChild(last, tmp);
998 		return(list);
999 	    } else {	/* ending node not a text node */
1000 	        endLevel = level;	/* remember the level of the end node */
1001 		endFlag = 1;
1002 		/* last node - need to take care of properties + namespaces */
1003 		tmp = xmlDocCopyNode(cur, target, 2);
1004 		if (list == NULL) {
1005 		    list = tmp;
1006 		    listParent = cur->parent;
1007 		    last = tmp;
1008 		} else {
1009 		    if (level == lastLevel)
1010 			last = xmlAddNextSibling(last, tmp);
1011 		    else {
1012 			last = xmlAddChild(last, tmp);
1013 			lastLevel = level;
1014 		    }
1015 		}
1016 
1017 		if (index2 > 1) {
1018 		    end = xmlXIncludeGetNthChild(cur, index2 - 1);
1019 		    index2 = 0;
1020 		}
1021 		if ((cur == start) && (index1 > 1)) {
1022 		    cur = xmlXIncludeGetNthChild(cur, index1 - 1);
1023 		    index1 = 0;
1024 		}  else {
1025 		    cur = cur->children;
1026 		}
1027 		level++;	/* increment level to show change */
1028 		/*
1029 		 * Now gather the remaining nodes from cur to end
1030 		 */
1031 		continue;	/* while */
1032 	    }
1033 	} else if (cur == start) {	/* Not at the end, are we at start? */
1034 	    if ((cur->type == XML_TEXT_NODE) ||
1035 		(cur->type == XML_CDATA_SECTION_NODE)) {
1036 		const xmlChar *content = cur->content;
1037 
1038 		if (content == NULL) {
1039 		    tmp = xmlNewTextLen(NULL, 0);
1040 		} else {
1041 		    if (index1 > 1) {
1042 			content += (index1 - 1);
1043 			index1 = 0;
1044 		    }
1045 		    tmp = xmlNewText(content);
1046 		}
1047 		last = list = tmp;
1048 		listParent = cur->parent;
1049 	    } else {		/* Not text node */
1050 	        /*
1051 		 * start of the range - need to take care of
1052 		 * properties and namespaces
1053 		 */
1054 		tmp = xmlDocCopyNode(cur, target, 2);
1055 		list = last = tmp;
1056 		listParent = cur->parent;
1057 		if (index1 > 1) {	/* Do we need to position? */
1058 		    cur = xmlXIncludeGetNthChild(cur, index1 - 1);
1059 		    level = lastLevel = 1;
1060 		    index1 = 0;
1061 		    /*
1062 		     * Now gather the remaining nodes from cur to end
1063 		     */
1064 		    continue; /* while */
1065 		}
1066 	    }
1067 	} else {
1068 	    tmp = NULL;
1069 	    switch (cur->type) {
1070 		case XML_DTD_NODE:
1071 		case XML_ELEMENT_DECL:
1072 		case XML_ATTRIBUTE_DECL:
1073 		case XML_ENTITY_NODE:
1074 		    /* Do not copy DTD informations */
1075 		    break;
1076 		case XML_ENTITY_DECL:
1077 		    /* handle crossing entities -> stack needed */
1078 		    break;
1079 		case XML_XINCLUDE_START:
1080 		case XML_XINCLUDE_END:
1081 		    /* don't consider it part of the tree content */
1082 		    break;
1083 		case XML_ATTRIBUTE_NODE:
1084 		    /* Humm, should not happen ! */
1085 		    break;
1086 		default:
1087 		    /*
1088 		     * Middle of the range - need to take care of
1089 		     * properties and namespaces
1090 		     */
1091 		    tmp = xmlDocCopyNode(cur, target, 2);
1092 		    break;
1093 	    }
1094 	    if (tmp != NULL) {
1095 		if (level == lastLevel)
1096 		    last = xmlAddNextSibling(last, tmp);
1097 		else {
1098 		    last = xmlAddChild(last, tmp);
1099 		    lastLevel = level;
1100 		}
1101 	    }
1102 	}
1103 	/*
1104 	 * Skip to next node in document order
1105 	 */
1106 	cur = xmlXPtrAdvanceNode(cur, &level);
1107 	if (endFlag && (level >= endLevel))
1108 	    break;
1109     }
1110     return(list);
1111 }
1112 
1113 /**
1114  * xmlXIncludeBuildNodeList:
1115  * @ctxt:  the XInclude context
1116  * @target:  the document target
1117  * @source:  the document source
1118  * @obj:  the XPointer result from the evaluation.
1119  *
1120  * Build a node list tree copy of the XPointer result.
1121  * This will drop Attributes and Namespace declarations.
1122  *
1123  * Returns an xmlNodePtr list or NULL.
1124  *         the caller has to free the node tree.
1125  */
1126 static xmlNodePtr
xmlXIncludeCopyXPointer(xmlXIncludeCtxtPtr ctxt,xmlDocPtr target,xmlDocPtr source,xmlXPathObjectPtr obj)1127 xmlXIncludeCopyXPointer(xmlXIncludeCtxtPtr ctxt, xmlDocPtr target,
1128 	                xmlDocPtr source, xmlXPathObjectPtr obj) {
1129     xmlNodePtr list = NULL, last = NULL;
1130     int i;
1131 
1132     if (source == NULL)
1133 	source = ctxt->doc;
1134     if ((ctxt == NULL) || (target == NULL) || (source == NULL) ||
1135 	(obj == NULL))
1136 	return(NULL);
1137     switch (obj->type) {
1138         case XPATH_NODESET: {
1139 	    xmlNodeSetPtr set = obj->nodesetval;
1140 	    if (set == NULL)
1141 		return(NULL);
1142 	    for (i = 0;i < set->nodeNr;i++) {
1143 		if (set->nodeTab[i] == NULL)
1144 		    continue;
1145 		switch (set->nodeTab[i]->type) {
1146 		    case XML_TEXT_NODE:
1147 		    case XML_CDATA_SECTION_NODE:
1148 		    case XML_ELEMENT_NODE:
1149 		    case XML_ENTITY_REF_NODE:
1150 		    case XML_ENTITY_NODE:
1151 		    case XML_PI_NODE:
1152 		    case XML_COMMENT_NODE:
1153 		    case XML_DOCUMENT_NODE:
1154 		    case XML_HTML_DOCUMENT_NODE:
1155 #ifdef LIBXML_DOCB_ENABLED
1156 		    case XML_DOCB_DOCUMENT_NODE:
1157 #endif
1158 		    case XML_XINCLUDE_END:
1159 			break;
1160 		    case XML_XINCLUDE_START: {
1161 	                xmlNodePtr tmp, cur = set->nodeTab[i];
1162 
1163 			cur = cur->next;
1164 			while (cur != NULL) {
1165 			    switch(cur->type) {
1166 				case XML_TEXT_NODE:
1167 				case XML_CDATA_SECTION_NODE:
1168 				case XML_ELEMENT_NODE:
1169 				case XML_ENTITY_REF_NODE:
1170 				case XML_ENTITY_NODE:
1171 				case XML_PI_NODE:
1172 				case XML_COMMENT_NODE:
1173 				    tmp = xmlXIncludeCopyNode(ctxt, target,
1174 							      source, cur);
1175 				    if (last == NULL) {
1176 					list = last = tmp;
1177 				    } else {
1178 					last = xmlAddNextSibling(last, tmp);
1179 				    }
1180 				    cur = cur->next;
1181 				    continue;
1182 				default:
1183 				    break;
1184 			    }
1185 			    break;
1186 			}
1187 			continue;
1188 		    }
1189 		    case XML_ATTRIBUTE_NODE:
1190 		    case XML_NAMESPACE_DECL:
1191 		    case XML_DOCUMENT_TYPE_NODE:
1192 		    case XML_DOCUMENT_FRAG_NODE:
1193 		    case XML_NOTATION_NODE:
1194 		    case XML_DTD_NODE:
1195 		    case XML_ELEMENT_DECL:
1196 		    case XML_ATTRIBUTE_DECL:
1197 		    case XML_ENTITY_DECL:
1198 			continue; /* for */
1199 		}
1200 		if (last == NULL)
1201 		    list = last = xmlXIncludeCopyNode(ctxt, target, source,
1202 			                              set->nodeTab[i]);
1203 		else {
1204 		    xmlAddNextSibling(last,
1205 			    xmlXIncludeCopyNode(ctxt, target, source,
1206 				                set->nodeTab[i]));
1207 		    if (last->next != NULL)
1208 			last = last->next;
1209 		}
1210 	    }
1211 	    break;
1212 	}
1213 #ifdef LIBXML_XPTR_ENABLED
1214 	case XPATH_LOCATIONSET: {
1215 	    xmlLocationSetPtr set = (xmlLocationSetPtr) obj->user;
1216 	    if (set == NULL)
1217 		return(NULL);
1218 	    for (i = 0;i < set->locNr;i++) {
1219 		if (last == NULL)
1220 		    list = last = xmlXIncludeCopyXPointer(ctxt, target, source,
1221 			                                  set->locTab[i]);
1222 		else
1223 		    xmlAddNextSibling(last,
1224 			    xmlXIncludeCopyXPointer(ctxt, target, source,
1225 				                    set->locTab[i]));
1226 		if (last != NULL) {
1227 		    while (last->next != NULL)
1228 			last = last->next;
1229 		}
1230 	    }
1231 	    break;
1232 	}
1233 	case XPATH_RANGE:
1234 	    return(xmlXIncludeCopyRange(ctxt, target, source, obj));
1235 #endif
1236 	case XPATH_POINT:
1237 	    /* points are ignored in XInclude */
1238 	    break;
1239 	default:
1240 	    break;
1241     }
1242     return(list);
1243 }
1244 /************************************************************************
1245  *									*
1246  *			XInclude I/O handling				*
1247  *									*
1248  ************************************************************************/
1249 
1250 typedef struct _xmlXIncludeMergeData xmlXIncludeMergeData;
1251 typedef xmlXIncludeMergeData *xmlXIncludeMergeDataPtr;
1252 struct _xmlXIncludeMergeData {
1253     xmlDocPtr doc;
1254     xmlXIncludeCtxtPtr ctxt;
1255 };
1256 
1257 /**
1258  * xmlXIncludeMergeOneEntity:
1259  * @ent: the entity
1260  * @doc:  the including doc
1261  * @nr: the entity name
1262  *
1263  * Implements the merge of one entity
1264  */
1265 static void
xmlXIncludeMergeEntity(void * payload,void * vdata,const xmlChar * name ATTRIBUTE_UNUSED)1266 xmlXIncludeMergeEntity(void *payload, void *vdata,
1267 	               const xmlChar *name ATTRIBUTE_UNUSED) {
1268     xmlEntityPtr ent = (xmlEntityPtr) payload;
1269     xmlXIncludeMergeDataPtr data = (xmlXIncludeMergeDataPtr) vdata;
1270     xmlEntityPtr ret, prev;
1271     xmlDocPtr doc;
1272     xmlXIncludeCtxtPtr ctxt;
1273 
1274     if ((ent == NULL) || (data == NULL))
1275 	return;
1276     ctxt = data->ctxt;
1277     doc = data->doc;
1278     if ((ctxt == NULL) || (doc == NULL))
1279 	return;
1280     switch (ent->etype) {
1281         case XML_INTERNAL_PARAMETER_ENTITY:
1282         case XML_EXTERNAL_PARAMETER_ENTITY:
1283         case XML_INTERNAL_PREDEFINED_ENTITY:
1284 	    return;
1285         case XML_INTERNAL_GENERAL_ENTITY:
1286         case XML_EXTERNAL_GENERAL_PARSED_ENTITY:
1287         case XML_EXTERNAL_GENERAL_UNPARSED_ENTITY:
1288 	    break;
1289     }
1290     ret = xmlAddDocEntity(doc, ent->name, ent->etype, ent->ExternalID,
1291 			  ent->SystemID, ent->content);
1292     if (ret != NULL) {
1293 	if (ent->URI != NULL)
1294 	    ret->URI = xmlStrdup(ent->URI);
1295     } else {
1296 	prev = xmlGetDocEntity(doc, ent->name);
1297 	if (prev != NULL) {
1298 	    if (ent->etype != prev->etype)
1299 		goto error;
1300 
1301 	    if ((ent->SystemID != NULL) && (prev->SystemID != NULL)) {
1302 		if (!xmlStrEqual(ent->SystemID, prev->SystemID))
1303 		    goto error;
1304 	    } else if ((ent->ExternalID != NULL) &&
1305 		       (prev->ExternalID != NULL)) {
1306 		if (!xmlStrEqual(ent->ExternalID, prev->ExternalID))
1307 		    goto error;
1308 	    } else if ((ent->content != NULL) && (prev->content != NULL)) {
1309 		if (!xmlStrEqual(ent->content, prev->content))
1310 		    goto error;
1311 	    } else {
1312 		goto error;
1313 	    }
1314 
1315 	}
1316     }
1317     return;
1318 error:
1319     switch (ent->etype) {
1320         case XML_INTERNAL_PARAMETER_ENTITY:
1321         case XML_EXTERNAL_PARAMETER_ENTITY:
1322         case XML_INTERNAL_PREDEFINED_ENTITY:
1323         case XML_INTERNAL_GENERAL_ENTITY:
1324         case XML_EXTERNAL_GENERAL_PARSED_ENTITY:
1325 	    return;
1326         case XML_EXTERNAL_GENERAL_UNPARSED_ENTITY:
1327 	    break;
1328     }
1329     xmlXIncludeErr(ctxt, (xmlNodePtr) ent, XML_XINCLUDE_ENTITY_DEF_MISMATCH,
1330                    "mismatch in redefinition of entity %s\n",
1331 		   ent->name);
1332 }
1333 
1334 /**
1335  * xmlXIncludeMergeEntities:
1336  * @ctxt: an XInclude context
1337  * @doc:  the including doc
1338  * @from:  the included doc
1339  *
1340  * Implements the entity merge
1341  *
1342  * Returns 0 if merge succeeded, -1 if some processing failed
1343  */
1344 static int
xmlXIncludeMergeEntities(xmlXIncludeCtxtPtr ctxt,xmlDocPtr doc,xmlDocPtr from)1345 xmlXIncludeMergeEntities(xmlXIncludeCtxtPtr ctxt, xmlDocPtr doc,
1346 	                 xmlDocPtr from) {
1347     xmlNodePtr cur;
1348     xmlDtdPtr target, source;
1349 
1350     if (ctxt == NULL)
1351 	return(-1);
1352 
1353     if ((from == NULL) || (from->intSubset == NULL))
1354 	return(0);
1355 
1356     target = doc->intSubset;
1357     if (target == NULL) {
1358 	cur = xmlDocGetRootElement(doc);
1359 	if (cur == NULL)
1360 	    return(-1);
1361         target = xmlCreateIntSubset(doc, cur->name, NULL, NULL);
1362 	if (target == NULL)
1363 	    return(-1);
1364     }
1365 
1366     source = from->intSubset;
1367     if ((source != NULL) && (source->entities != NULL)) {
1368 	xmlXIncludeMergeData data;
1369 
1370 	data.ctxt = ctxt;
1371 	data.doc = doc;
1372 
1373 	xmlHashScan((xmlHashTablePtr) source->entities,
1374 		    xmlXIncludeMergeEntity, &data);
1375     }
1376     source = from->extSubset;
1377     if ((source != NULL) && (source->entities != NULL)) {
1378 	xmlXIncludeMergeData data;
1379 
1380 	data.ctxt = ctxt;
1381 	data.doc = doc;
1382 
1383 	/*
1384 	 * don't duplicate existing stuff when external subsets are the same
1385 	 */
1386 	if ((!xmlStrEqual(target->ExternalID, source->ExternalID)) &&
1387 	    (!xmlStrEqual(target->SystemID, source->SystemID))) {
1388 	    xmlHashScan((xmlHashTablePtr) source->entities,
1389 			xmlXIncludeMergeEntity, &data);
1390 	}
1391     }
1392     return(0);
1393 }
1394 
1395 /**
1396  * xmlXIncludeLoadDoc:
1397  * @ctxt:  the XInclude context
1398  * @url:  the associated URL
1399  * @nr:  the xinclude node number
1400  *
1401  * Load the document, and store the result in the XInclude context
1402  *
1403  * Returns 0 in case of success, -1 in case of failure
1404  */
1405 static int
xmlXIncludeLoadDoc(xmlXIncludeCtxtPtr ctxt,const xmlChar * url,int nr)1406 xmlXIncludeLoadDoc(xmlXIncludeCtxtPtr ctxt, const xmlChar *url, int nr) {
1407     xmlDocPtr doc;
1408     xmlURIPtr uri;
1409     xmlChar *URL;
1410     xmlChar *fragment = NULL;
1411     int i = 0;
1412 #ifdef LIBXML_XPTR_ENABLED
1413     int saveFlags;
1414 #endif
1415 
1416 #ifdef DEBUG_XINCLUDE
1417     xmlGenericError(xmlGenericErrorContext, "Loading doc %s:%d\n", url, nr);
1418 #endif
1419     /*
1420      * Check the URL and remove any fragment identifier
1421      */
1422     uri = xmlParseURI((const char *)url);
1423     if (uri == NULL) {
1424 	xmlXIncludeErr(ctxt, ctxt->incTab[nr]->ref,
1425 	               XML_XINCLUDE_HREF_URI,
1426 		       "invalid value URI %s\n", url);
1427 	return(-1);
1428     }
1429     if (uri->fragment != NULL) {
1430 	fragment = (xmlChar *) uri->fragment;
1431 	uri->fragment = NULL;
1432     }
1433     if ((ctxt->incTab != NULL) && (ctxt->incTab[nr] != NULL) &&
1434         (ctxt->incTab[nr]->fragment != NULL)) {
1435 	if (fragment != NULL) xmlFree(fragment);
1436 	fragment = xmlStrdup(ctxt->incTab[nr]->fragment);
1437     }
1438     URL = xmlSaveUri(uri);
1439     xmlFreeURI(uri);
1440     if (URL == NULL) {
1441         if (ctxt->incTab != NULL)
1442 	    xmlXIncludeErr(ctxt, ctxt->incTab[nr]->ref,
1443 			   XML_XINCLUDE_HREF_URI,
1444 			   "invalid value URI %s\n", url);
1445 	else
1446 	    xmlXIncludeErr(ctxt, NULL,
1447 			   XML_XINCLUDE_HREF_URI,
1448 			   "invalid value URI %s\n", url);
1449 	if (fragment != NULL)
1450 	    xmlFree(fragment);
1451 	return(-1);
1452     }
1453 
1454     /*
1455      * Handling of references to the local document are done
1456      * directly through ctxt->doc.
1457      */
1458     if ((URL[0] == 0) || (URL[0] == '#') ||
1459 	((ctxt->doc != NULL) && (xmlStrEqual(URL, ctxt->doc->URL)))) {
1460 	doc = NULL;
1461         goto loaded;
1462     }
1463 
1464     /*
1465      * Prevent reloading twice the document.
1466      */
1467     for (i = 0; i < ctxt->incNr; i++) {
1468 	if ((xmlStrEqual(URL, ctxt->incTab[i]->URI)) &&
1469 	    (ctxt->incTab[i]->doc != NULL)) {
1470 	    doc = ctxt->incTab[i]->doc;
1471 #ifdef DEBUG_XINCLUDE
1472 	    printf("Already loaded %s\n", URL);
1473 #endif
1474 	    goto loaded;
1475 	}
1476     }
1477 
1478     /*
1479      * Load it.
1480      */
1481 #ifdef DEBUG_XINCLUDE
1482     printf("loading %s\n", URL);
1483 #endif
1484 #ifdef LIBXML_XPTR_ENABLED
1485     /*
1486      * If this is an XPointer evaluation, we want to assure that
1487      * all entities have been resolved prior to processing the
1488      * referenced document
1489      */
1490     saveFlags = ctxt->parseFlags;
1491     if (fragment != NULL) {	/* if this is an XPointer eval */
1492 	ctxt->parseFlags |= XML_PARSE_NOENT;
1493     }
1494 #endif
1495 
1496     doc = xmlXIncludeParseFile(ctxt, (const char *)URL);
1497 #ifdef LIBXML_XPTR_ENABLED
1498     ctxt->parseFlags = saveFlags;
1499 #endif
1500     if (doc == NULL) {
1501 	xmlFree(URL);
1502 	if (fragment != NULL)
1503 	    xmlFree(fragment);
1504 	return(-1);
1505     }
1506     ctxt->incTab[nr]->doc = doc;
1507     /*
1508      * It's possible that the requested URL has been mapped to a
1509      * completely different location (e.g. through a catalog entry).
1510      * To check for this, we compare the URL with that of the doc
1511      * and change it if they disagree (bug 146988).
1512      */
1513    if (!xmlStrEqual(URL, doc->URL)) {
1514        xmlFree(URL);
1515        URL = xmlStrdup(doc->URL);
1516    }
1517     for (i = nr + 1; i < ctxt->incNr; i++) {
1518 	if (xmlStrEqual(URL, ctxt->incTab[i]->URI)) {
1519 	    ctxt->incTab[nr]->count++;
1520 #ifdef DEBUG_XINCLUDE
1521 	    printf("Increasing %s count since reused\n", URL);
1522 #endif
1523             break;
1524 	}
1525     }
1526 
1527     /*
1528      * Make sure we have all entities fixed up
1529      */
1530     xmlXIncludeMergeEntities(ctxt, ctxt->doc, doc);
1531 
1532     /*
1533      * We don't need the DTD anymore, free up space
1534     if (doc->intSubset != NULL) {
1535 	xmlUnlinkNode((xmlNodePtr) doc->intSubset);
1536 	xmlFreeNode((xmlNodePtr) doc->intSubset);
1537 	doc->intSubset = NULL;
1538     }
1539     if (doc->extSubset != NULL) {
1540 	xmlUnlinkNode((xmlNodePtr) doc->extSubset);
1541 	xmlFreeNode((xmlNodePtr) doc->extSubset);
1542 	doc->extSubset = NULL;
1543     }
1544      */
1545     xmlXIncludeRecurseDoc(ctxt, doc, URL);
1546 
1547 loaded:
1548     if (fragment == NULL) {
1549 	/*
1550 	 * Add the top children list as the replacement copy.
1551 	 */
1552 	if (doc == NULL)
1553 	{
1554 	    /* Hopefully a DTD declaration won't be copied from
1555 	     * the same document */
1556 	    ctxt->incTab[nr]->inc = xmlCopyNodeList(ctxt->doc->children);
1557 	} else {
1558 	    ctxt->incTab[nr]->inc = xmlXIncludeCopyNodeList(ctxt, ctxt->doc,
1559 		                                       doc, doc->children);
1560 	}
1561     }
1562 #ifdef LIBXML_XPTR_ENABLED
1563     else {
1564 	/*
1565 	 * Computes the XPointer expression and make a copy used
1566 	 * as the replacement copy.
1567 	 */
1568 	xmlXPathObjectPtr xptr;
1569 	xmlXPathContextPtr xptrctxt;
1570 	xmlNodeSetPtr set;
1571 
1572 	if (doc == NULL) {
1573 	    xptrctxt = xmlXPtrNewContext(ctxt->doc, ctxt->incTab[nr]->ref,
1574 		                         NULL);
1575 	} else {
1576 	    xptrctxt = xmlXPtrNewContext(doc, NULL, NULL);
1577 	}
1578 	if (xptrctxt == NULL) {
1579 	    xmlXIncludeErr(ctxt, ctxt->incTab[nr]->ref,
1580 	                   XML_XINCLUDE_XPTR_FAILED,
1581 			   "could not create XPointer context\n", NULL);
1582 	    xmlFree(URL);
1583 	    xmlFree(fragment);
1584 	    return(-1);
1585 	}
1586 	xptr = xmlXPtrEval(fragment, xptrctxt);
1587 	if (xptr == NULL) {
1588 	    xmlXIncludeErr(ctxt, ctxt->incTab[nr]->ref,
1589 	                   XML_XINCLUDE_XPTR_FAILED,
1590 			   "XPointer evaluation failed: #%s\n",
1591 			   fragment);
1592 	    xmlXPathFreeContext(xptrctxt);
1593 	    xmlFree(URL);
1594 	    xmlFree(fragment);
1595 	    return(-1);
1596 	}
1597 	switch (xptr->type) {
1598 	    case XPATH_UNDEFINED:
1599 	    case XPATH_BOOLEAN:
1600 	    case XPATH_NUMBER:
1601 	    case XPATH_STRING:
1602 	    case XPATH_POINT:
1603 	    case XPATH_USERS:
1604 	    case XPATH_XSLT_TREE:
1605 		xmlXIncludeErr(ctxt, ctxt->incTab[nr]->ref,
1606 		               XML_XINCLUDE_XPTR_RESULT,
1607 			       "XPointer is not a range: #%s\n",
1608 			       fragment);
1609 		xmlXPathFreeContext(xptrctxt);
1610 		xmlFree(URL);
1611 		xmlFree(fragment);
1612 		return(-1);
1613 	    case XPATH_NODESET:
1614 	        if ((xptr->nodesetval == NULL) ||
1615 		    (xptr->nodesetval->nodeNr <= 0)) {
1616 		    xmlXPathFreeContext(xptrctxt);
1617 		    xmlFree(URL);
1618 		    xmlFree(fragment);
1619 		    return(-1);
1620 		}
1621 
1622 	    case XPATH_RANGE:
1623 	    case XPATH_LOCATIONSET:
1624 		break;
1625 	}
1626 	set = xptr->nodesetval;
1627 	if (set != NULL) {
1628 	    for (i = 0;i < set->nodeNr;i++) {
1629 		if (set->nodeTab[i] == NULL)
1630 		    continue;
1631 		switch (set->nodeTab[i]->type) {
1632 		    case XML_ELEMENT_NODE:
1633 		    case XML_TEXT_NODE:
1634 		    case XML_CDATA_SECTION_NODE:
1635 		    case XML_ENTITY_REF_NODE:
1636 		    case XML_ENTITY_NODE:
1637 		    case XML_PI_NODE:
1638 		    case XML_COMMENT_NODE:
1639 		    case XML_DOCUMENT_NODE:
1640 		    case XML_HTML_DOCUMENT_NODE:
1641 #ifdef LIBXML_DOCB_ENABLED
1642 		    case XML_DOCB_DOCUMENT_NODE:
1643 #endif
1644 			continue;
1645 
1646 		    case XML_ATTRIBUTE_NODE:
1647 			xmlXIncludeErr(ctxt, ctxt->incTab[nr]->ref,
1648 			               XML_XINCLUDE_XPTR_RESULT,
1649 				       "XPointer selects an attribute: #%s\n",
1650 				       fragment);
1651 			set->nodeTab[i] = NULL;
1652 			continue;
1653 		    case XML_NAMESPACE_DECL:
1654 			xmlXIncludeErr(ctxt, ctxt->incTab[nr]->ref,
1655 			               XML_XINCLUDE_XPTR_RESULT,
1656 				       "XPointer selects a namespace: #%s\n",
1657 				       fragment);
1658 			set->nodeTab[i] = NULL;
1659 			continue;
1660 		    case XML_DOCUMENT_TYPE_NODE:
1661 		    case XML_DOCUMENT_FRAG_NODE:
1662 		    case XML_NOTATION_NODE:
1663 		    case XML_DTD_NODE:
1664 		    case XML_ELEMENT_DECL:
1665 		    case XML_ATTRIBUTE_DECL:
1666 		    case XML_ENTITY_DECL:
1667 		    case XML_XINCLUDE_START:
1668 		    case XML_XINCLUDE_END:
1669 			xmlXIncludeErr(ctxt, ctxt->incTab[nr]->ref,
1670 			               XML_XINCLUDE_XPTR_RESULT,
1671 				   "XPointer selects unexpected nodes: #%s\n",
1672 				       fragment);
1673 			set->nodeTab[i] = NULL;
1674 			set->nodeTab[i] = NULL;
1675 			continue; /* for */
1676 		}
1677 	    }
1678 	}
1679 	if (doc == NULL) {
1680 	    ctxt->incTab[nr]->xptr = xptr;
1681 	    ctxt->incTab[nr]->inc = NULL;
1682 	} else {
1683 	    ctxt->incTab[nr]->inc =
1684 		xmlXIncludeCopyXPointer(ctxt, ctxt->doc, doc, xptr);
1685 	    xmlXPathFreeObject(xptr);
1686 	}
1687 	xmlXPathFreeContext(xptrctxt);
1688 	xmlFree(fragment);
1689     }
1690 #endif
1691 
1692     /*
1693      * Do the xml:base fixup if needed
1694      */
1695     if ((doc != NULL) && (URL != NULL) &&
1696         (!(ctxt->parseFlags & XML_PARSE_NOBASEFIX)) &&
1697 	(!(doc->parseFlags & XML_PARSE_NOBASEFIX))) {
1698 	xmlNodePtr node;
1699 	xmlChar *base;
1700 	xmlChar *curBase;
1701 
1702 	/*
1703 	 * The base is only adjusted if "necessary", i.e. if the xinclude node
1704 	 * has a base specified, or the URL is relative
1705 	 */
1706 	base = xmlGetNsProp(ctxt->incTab[nr]->ref, BAD_CAST "base",
1707 			XML_XML_NAMESPACE);
1708 	if (base == NULL) {
1709 	    /*
1710 	     * No xml:base on the xinclude node, so we check whether the
1711 	     * URI base is different than (relative to) the context base
1712 	     */
1713 	    curBase = xmlBuildRelativeURI(URL, ctxt->base);
1714 	    if (curBase == NULL) {	/* Error return */
1715 	        xmlXIncludeErr(ctxt, ctxt->incTab[nr]->ref,
1716 	               XML_XINCLUDE_HREF_URI,
1717 		       "trying to build relative URI from %s\n", URL);
1718 	    } else {
1719 		/* If the URI doesn't contain a slash, it's not relative */
1720 	        if (!xmlStrchr(curBase, (xmlChar) '/'))
1721 		    xmlFree(curBase);
1722 		else
1723 		    base = curBase;
1724 	    }
1725 	}
1726 	if (base != NULL) {	/* Adjustment may be needed */
1727 	    node = ctxt->incTab[nr]->inc;
1728 	    while (node != NULL) {
1729 		/* Only work on element nodes */
1730 		if (node->type == XML_ELEMENT_NODE) {
1731 		    curBase = xmlNodeGetBase(node->doc, node);
1732 		    /* If no current base, set it */
1733 		    if (curBase == NULL) {
1734 			xmlNodeSetBase(node, base);
1735 		    } else {
1736 			/*
1737 			 * If the current base is the same as the
1738 			 * URL of the document, then reset it to be
1739 			 * the specified xml:base or the relative URI
1740 			 */
1741 			if (xmlStrEqual(curBase, node->doc->URL)) {
1742 			    xmlNodeSetBase(node, base);
1743 			} else {
1744 			    /*
1745 			     * If the element already has an xml:base
1746 			     * set, then relativise it if necessary
1747 			     */
1748 			    xmlChar *xmlBase;
1749 			    xmlBase = xmlGetNsProp(node,
1750 					    BAD_CAST "base",
1751 					    XML_XML_NAMESPACE);
1752 			    if (xmlBase != NULL) {
1753 				xmlChar *relBase;
1754 				relBase = xmlBuildURI(xmlBase, base);
1755 				if (relBase == NULL) { /* error */
1756 				    xmlXIncludeErr(ctxt,
1757 						ctxt->incTab[nr]->ref,
1758 						XML_XINCLUDE_HREF_URI,
1759 					"trying to rebuild base from %s\n",
1760 						xmlBase);
1761 				} else {
1762 				    xmlNodeSetBase(node, relBase);
1763 				    xmlFree(relBase);
1764 				}
1765 				xmlFree(xmlBase);
1766 			    }
1767 			}
1768 			xmlFree(curBase);
1769 		    }
1770 		}
1771 	        node = node->next;
1772 	    }
1773 	    xmlFree(base);
1774 	}
1775     }
1776     if ((nr < ctxt->incNr) && (ctxt->incTab[nr]->doc != NULL) &&
1777 	(ctxt->incTab[nr]->count <= 1)) {
1778 #ifdef DEBUG_XINCLUDE
1779         printf("freeing %s\n", ctxt->incTab[nr]->doc->URL);
1780 #endif
1781 	xmlFreeDoc(ctxt->incTab[nr]->doc);
1782 	ctxt->incTab[nr]->doc = NULL;
1783     }
1784     xmlFree(URL);
1785     return(0);
1786 }
1787 
1788 /**
1789  * xmlXIncludeLoadTxt:
1790  * @ctxt:  the XInclude context
1791  * @url:  the associated URL
1792  * @nr:  the xinclude node number
1793  *
1794  * Load the content, and store the result in the XInclude context
1795  *
1796  * Returns 0 in case of success, -1 in case of failure
1797  */
1798 static int
xmlXIncludeLoadTxt(xmlXIncludeCtxtPtr ctxt,const xmlChar * url,int nr)1799 xmlXIncludeLoadTxt(xmlXIncludeCtxtPtr ctxt, const xmlChar *url, int nr) {
1800     xmlParserInputBufferPtr buf;
1801     xmlNodePtr node;
1802     xmlURIPtr uri;
1803     xmlChar *URL;
1804     int i;
1805     xmlChar *encoding = NULL;
1806     xmlCharEncoding enc = (xmlCharEncoding) 0;
1807     xmlParserCtxtPtr pctxt;
1808     xmlParserInputPtr inputStream;
1809     int xinclude_multibyte_fallback_used = 0;
1810 
1811     /* Don't read from stdin. */
1812     if (xmlStrcmp(url, BAD_CAST "-") == 0)
1813         url = BAD_CAST "./-";
1814 
1815     /*
1816      * Check the URL and remove any fragment identifier
1817      */
1818     uri = xmlParseURI((const char *)url);
1819     if (uri == NULL) {
1820 	xmlXIncludeErr(ctxt, ctxt->incTab[nr]->ref, XML_XINCLUDE_HREF_URI,
1821 	               "invalid value URI %s\n", url);
1822 	return(-1);
1823     }
1824     if (uri->fragment != NULL) {
1825 	xmlXIncludeErr(ctxt, ctxt->incTab[nr]->ref, XML_XINCLUDE_TEXT_FRAGMENT,
1826 	               "fragment identifier forbidden for text: %s\n",
1827 		       (const xmlChar *) uri->fragment);
1828 	xmlFreeURI(uri);
1829 	return(-1);
1830     }
1831     URL = xmlSaveUri(uri);
1832     xmlFreeURI(uri);
1833     if (URL == NULL) {
1834 	xmlXIncludeErr(ctxt, ctxt->incTab[nr]->ref, XML_XINCLUDE_HREF_URI,
1835 	               "invalid value URI %s\n", url);
1836 	return(-1);
1837     }
1838 
1839     /*
1840      * Handling of references to the local document are done
1841      * directly through ctxt->doc.
1842      */
1843     if (URL[0] == 0) {
1844 	xmlXIncludeErr(ctxt, ctxt->incTab[nr]->ref,
1845 	               XML_XINCLUDE_TEXT_DOCUMENT,
1846 		       "text serialization of document not available\n", NULL);
1847 	xmlFree(URL);
1848 	return(-1);
1849     }
1850 
1851     /*
1852      * Prevent reloading twice the document.
1853      */
1854     for (i = 0; i < ctxt->txtNr; i++) {
1855 	if (xmlStrEqual(URL, ctxt->txturlTab[i])) {
1856 	    node = xmlCopyNode(ctxt->txtTab[i], 1);
1857 	    goto loaded;
1858 	}
1859     }
1860     /*
1861      * Try to get the encoding if available
1862      */
1863     if ((ctxt->incTab[nr] != NULL) && (ctxt->incTab[nr]->ref != NULL)) {
1864 	encoding = xmlGetProp(ctxt->incTab[nr]->ref, XINCLUDE_PARSE_ENCODING);
1865     }
1866     if (encoding != NULL) {
1867 	/*
1868 	 * TODO: we should not have to remap to the xmlCharEncoding
1869 	 *       predefined set, a better interface than
1870 	 *       xmlParserInputBufferCreateFilename should allow any
1871 	 *       encoding supported by iconv
1872 	 */
1873         enc = xmlParseCharEncoding((const char *) encoding);
1874 	if (enc == XML_CHAR_ENCODING_ERROR) {
1875 	    xmlXIncludeErr(ctxt, ctxt->incTab[nr]->ref,
1876 	                   XML_XINCLUDE_UNKNOWN_ENCODING,
1877 			   "encoding %s not supported\n", encoding);
1878 	    xmlFree(encoding);
1879 	    xmlFree(URL);
1880 	    return(-1);
1881 	}
1882 	xmlFree(encoding);
1883     }
1884 
1885     /*
1886      * Load it.
1887      */
1888     pctxt = xmlNewParserCtxt();
1889     inputStream = xmlLoadExternalEntity((const char*)URL, NULL, pctxt);
1890     if(inputStream == NULL) {
1891 	xmlFreeParserCtxt(pctxt);
1892 	xmlFree(URL);
1893 	return(-1);
1894     }
1895     buf = inputStream->buf;
1896     if (buf == NULL) {
1897 	xmlFreeInputStream (inputStream);
1898 	xmlFreeParserCtxt(pctxt);
1899 	xmlFree(URL);
1900 	return(-1);
1901     }
1902     if (buf->encoder)
1903 	xmlCharEncCloseFunc(buf->encoder);
1904     buf->encoder = xmlGetCharEncodingHandler(enc);
1905     node = xmlNewText(NULL);
1906 
1907     /*
1908      * Scan all chars from the resource and add the to the node
1909      */
1910 xinclude_multibyte_fallback:
1911     while (xmlParserInputBufferRead(buf, 128) > 0) {
1912 	int len;
1913 	const xmlChar *content;
1914 
1915 	content = xmlBufContent(buf->buffer);
1916 	len = xmlBufLength(buf->buffer);
1917 	for (i = 0;i < len;) {
1918 	    int cur;
1919 	    int l;
1920 
1921 	    cur = xmlStringCurrentChar(NULL, &content[i], &l);
1922 	    if (!IS_CHAR(cur)) {
1923 		/* Handle split multibyte char at buffer boundary */
1924 		if (((len - i) < 4) && (!xinclude_multibyte_fallback_used)) {
1925 		    xinclude_multibyte_fallback_used = 1;
1926 		    xmlBufShrink(buf->buffer, i);
1927 		    goto xinclude_multibyte_fallback;
1928 		} else {
1929 		    xmlXIncludeErr(ctxt, ctxt->incTab[nr]->ref,
1930 				   XML_XINCLUDE_INVALID_CHAR,
1931 				   "%s contains invalid char\n", URL);
1932 		    xmlFreeParserCtxt(pctxt);
1933 		    xmlFreeParserInputBuffer(buf);
1934 		    xmlFree(URL);
1935 		    return(-1);
1936 		}
1937 	    } else {
1938 		xinclude_multibyte_fallback_used = 0;
1939 		xmlNodeAddContentLen(node, &content[i], l);
1940 	    }
1941 	    i += l;
1942 	}
1943 	xmlBufShrink(buf->buffer, len);
1944     }
1945     xmlFreeParserCtxt(pctxt);
1946     xmlXIncludeAddTxt(ctxt, node, URL);
1947     xmlFreeInputStream(inputStream);
1948 
1949 loaded:
1950     /*
1951      * Add the element as the replacement copy.
1952      */
1953     ctxt->incTab[nr]->inc = node;
1954     xmlFree(URL);
1955     return(0);
1956 }
1957 
1958 /**
1959  * xmlXIncludeLoadFallback:
1960  * @ctxt:  the XInclude context
1961  * @fallback:  the fallback node
1962  * @nr:  the xinclude node number
1963  *
1964  * Load the content of the fallback node, and store the result
1965  * in the XInclude context
1966  *
1967  * Returns 0 in case of success, -1 in case of failure
1968  */
1969 static int
xmlXIncludeLoadFallback(xmlXIncludeCtxtPtr ctxt,xmlNodePtr fallback,int nr)1970 xmlXIncludeLoadFallback(xmlXIncludeCtxtPtr ctxt, xmlNodePtr fallback, int nr) {
1971     xmlXIncludeCtxtPtr newctxt;
1972     int ret = 0;
1973     int oldNbErrors = ctxt->nbErrors;
1974 
1975     if ((fallback == NULL) || (fallback->type == XML_NAMESPACE_DECL) ||
1976         (ctxt == NULL))
1977 	return(-1);
1978     if (fallback->children != NULL) {
1979 	/*
1980 	 * It's possible that the fallback also has 'includes'
1981 	 * (Bug 129969), so we re-process the fallback just in case
1982 	 */
1983 	newctxt = xmlXIncludeNewContext(ctxt->doc);
1984 	if (newctxt == NULL)
1985 	    return (-1);
1986 	newctxt->_private = ctxt->_private;
1987 	newctxt->base = xmlStrdup(ctxt->base);	/* Inherit the base from the existing context */
1988 	xmlXIncludeSetFlags(newctxt, ctxt->parseFlags);
1989 	ret = xmlXIncludeDoProcess(newctxt, ctxt->doc, fallback->children);
1990 	if (ctxt->nbErrors > oldNbErrors)
1991 	    ret = -1;
1992 	else if (ret > 0)
1993 	    ret = 0;	/* xmlXIncludeDoProcess can return +ve number */
1994 	xmlXIncludeFreeContext(newctxt);
1995 
1996 	ctxt->incTab[nr]->inc = xmlDocCopyNodeList(ctxt->doc,
1997 	                                           fallback->children);
1998     } else {
1999         ctxt->incTab[nr]->inc = NULL;
2000 	ctxt->incTab[nr]->emptyFb = 1;	/* flag empty callback */
2001     }
2002     return(ret);
2003 }
2004 
2005 /************************************************************************
2006  *									*
2007  *			XInclude Processing				*
2008  *									*
2009  ************************************************************************/
2010 
2011 /**
2012  * xmlXIncludePreProcessNode:
2013  * @ctxt: an XInclude context
2014  * @node: an XInclude node
2015  *
2016  * Implement the XInclude preprocessing, currently just adding the element
2017  * for further processing.
2018  *
2019  * Returns the result list or NULL in case of error
2020  */
2021 static xmlNodePtr
xmlXIncludePreProcessNode(xmlXIncludeCtxtPtr ctxt,xmlNodePtr node)2022 xmlXIncludePreProcessNode(xmlXIncludeCtxtPtr ctxt, xmlNodePtr node) {
2023     xmlXIncludeAddNode(ctxt, node);
2024     return(NULL);
2025 }
2026 
2027 /**
2028  * xmlXIncludeLoadNode:
2029  * @ctxt: an XInclude context
2030  * @nr: the node number
2031  *
2032  * Find and load the infoset replacement for the given node.
2033  *
2034  * Returns 0 if substitution succeeded, -1 if some processing failed
2035  */
2036 static int
xmlXIncludeLoadNode(xmlXIncludeCtxtPtr ctxt,int nr)2037 xmlXIncludeLoadNode(xmlXIncludeCtxtPtr ctxt, int nr) {
2038     xmlNodePtr cur;
2039     xmlChar *href;
2040     xmlChar *parse;
2041     xmlChar *base;
2042     xmlChar *oldBase;
2043     xmlChar *URI;
2044     int xml = 1; /* default Issue 64 */
2045     int ret;
2046 
2047     if (ctxt == NULL)
2048 	return(-1);
2049     if ((nr < 0) || (nr >= ctxt->incNr))
2050 	return(-1);
2051     cur = ctxt->incTab[nr]->ref;
2052     if (cur == NULL)
2053 	return(-1);
2054 
2055     /*
2056      * read the attributes
2057      */
2058     href = xmlXIncludeGetProp(ctxt, cur, XINCLUDE_HREF);
2059     if (href == NULL) {
2060 	href = xmlStrdup(BAD_CAST ""); /* @@@@ href is now optional */
2061 	if (href == NULL)
2062 	    return(-1);
2063     }
2064     parse = xmlXIncludeGetProp(ctxt, cur, XINCLUDE_PARSE);
2065     if (parse != NULL) {
2066 	if (xmlStrEqual(parse, XINCLUDE_PARSE_XML))
2067 	    xml = 1;
2068 	else if (xmlStrEqual(parse, XINCLUDE_PARSE_TEXT))
2069 	    xml = 0;
2070 	else {
2071 	    xmlXIncludeErr(ctxt, ctxt->incTab[nr]->ref,
2072 	                   XML_XINCLUDE_PARSE_VALUE,
2073 			   "invalid value %s for 'parse'\n", parse);
2074 	    if (href != NULL)
2075 		xmlFree(href);
2076 	    if (parse != NULL)
2077 		xmlFree(parse);
2078 	    return(-1);
2079 	}
2080     }
2081 
2082     /*
2083      * compute the URI
2084      */
2085     base = xmlNodeGetBase(ctxt->doc, cur);
2086     if (base == NULL) {
2087 	URI = xmlBuildURI(href, ctxt->doc->URL);
2088     } else {
2089 	URI = xmlBuildURI(href, base);
2090     }
2091     if (URI == NULL) {
2092 	xmlChar *escbase;
2093 	xmlChar *eschref;
2094 	/*
2095 	 * Some escaping may be needed
2096 	 */
2097 	escbase = xmlURIEscape(base);
2098 	eschref = xmlURIEscape(href);
2099 	URI = xmlBuildURI(eschref, escbase);
2100 	if (escbase != NULL)
2101 	    xmlFree(escbase);
2102 	if (eschref != NULL)
2103 	    xmlFree(eschref);
2104     }
2105     if (URI == NULL) {
2106 	xmlXIncludeErr(ctxt, ctxt->incTab[nr]->ref,
2107 	               XML_XINCLUDE_HREF_URI, "failed build URL\n", NULL);
2108 	if (parse != NULL)
2109 	    xmlFree(parse);
2110 	if (href != NULL)
2111 	    xmlFree(href);
2112 	if (base != NULL)
2113 	    xmlFree(base);
2114 	return(-1);
2115     }
2116 #ifdef DEBUG_XINCLUDE
2117     xmlGenericError(xmlGenericErrorContext, "parse: %s\n",
2118 	    xml ? "xml": "text");
2119     xmlGenericError(xmlGenericErrorContext, "URI: %s\n", URI);
2120 #endif
2121 
2122     /*
2123      * Save the base for this include (saving the current one)
2124      */
2125     oldBase = ctxt->base;
2126     ctxt->base = base;
2127 
2128     if (xml) {
2129 	ret = xmlXIncludeLoadDoc(ctxt, URI, nr);
2130 	/* xmlXIncludeGetFragment(ctxt, cur, URI); */
2131     } else {
2132 	ret = xmlXIncludeLoadTxt(ctxt, URI, nr);
2133     }
2134 
2135     /*
2136      * Restore the original base before checking for fallback
2137      */
2138     ctxt->base = oldBase;
2139 
2140     if (ret < 0) {
2141 	xmlNodePtr children;
2142 
2143 	/*
2144 	 * Time to try a fallback if available
2145 	 */
2146 #ifdef DEBUG_XINCLUDE
2147 	xmlGenericError(xmlGenericErrorContext, "error looking for fallback\n");
2148 #endif
2149 	children = cur->children;
2150 	while (children != NULL) {
2151 	    if ((children->type == XML_ELEMENT_NODE) &&
2152 		(children->ns != NULL) &&
2153 		(xmlStrEqual(children->name, XINCLUDE_FALLBACK)) &&
2154 		((xmlStrEqual(children->ns->href, XINCLUDE_NS)) ||
2155 		 (xmlStrEqual(children->ns->href, XINCLUDE_OLD_NS)))) {
2156 		ret = xmlXIncludeLoadFallback(ctxt, children, nr);
2157 		if (ret == 0)
2158 		    break;
2159 	    }
2160 	    children = children->next;
2161 	}
2162     }
2163     if (ret < 0) {
2164 	xmlXIncludeErr(ctxt, ctxt->incTab[nr]->ref,
2165 	               XML_XINCLUDE_NO_FALLBACK,
2166 		       "could not load %s, and no fallback was found\n",
2167 		       URI);
2168     }
2169 
2170     /*
2171      * Cleanup
2172      */
2173     if (URI != NULL)
2174 	xmlFree(URI);
2175     if (parse != NULL)
2176 	xmlFree(parse);
2177     if (href != NULL)
2178 	xmlFree(href);
2179     if (base != NULL)
2180 	xmlFree(base);
2181     return(0);
2182 }
2183 
2184 /**
2185  * xmlXIncludeIncludeNode:
2186  * @ctxt: an XInclude context
2187  * @nr: the node number
2188  *
2189  * Implement the infoset replacement for the given node
2190  *
2191  * Returns 0 if substitution succeeded, -1 if some processing failed
2192  */
2193 static int
xmlXIncludeIncludeNode(xmlXIncludeCtxtPtr ctxt,int nr)2194 xmlXIncludeIncludeNode(xmlXIncludeCtxtPtr ctxt, int nr) {
2195     xmlNodePtr cur, end, list, tmp;
2196 
2197     if (ctxt == NULL)
2198 	return(-1);
2199     if ((nr < 0) || (nr >= ctxt->incNr))
2200 	return(-1);
2201     cur = ctxt->incTab[nr]->ref;
2202     if ((cur == NULL) || (cur->type == XML_NAMESPACE_DECL))
2203 	return(-1);
2204 
2205     /*
2206      * If we stored an XPointer a late computation may be needed
2207      */
2208     if ((ctxt->incTab[nr]->inc == NULL) &&
2209 	(ctxt->incTab[nr]->xptr != NULL)) {
2210 	ctxt->incTab[nr]->inc =
2211 	    xmlXIncludeCopyXPointer(ctxt, ctxt->doc, ctxt->doc,
2212 		                    ctxt->incTab[nr]->xptr);
2213 	xmlXPathFreeObject(ctxt->incTab[nr]->xptr);
2214 	ctxt->incTab[nr]->xptr = NULL;
2215     }
2216     list = ctxt->incTab[nr]->inc;
2217     ctxt->incTab[nr]->inc = NULL;
2218 
2219     /*
2220      * Check against the risk of generating a multi-rooted document
2221      */
2222     if ((cur->parent != NULL) &&
2223 	(cur->parent->type != XML_ELEMENT_NODE)) {
2224 	int nb_elem = 0;
2225 
2226 	tmp = list;
2227 	while (tmp != NULL) {
2228 	    if (tmp->type == XML_ELEMENT_NODE)
2229 		nb_elem++;
2230 	    tmp = tmp->next;
2231 	}
2232 	if (nb_elem > 1) {
2233 	    xmlXIncludeErr(ctxt, ctxt->incTab[nr]->ref,
2234 	                   XML_XINCLUDE_MULTIPLE_ROOT,
2235 		       "XInclude error: would result in multiple root nodes\n",
2236 			   NULL);
2237 	    return(-1);
2238 	}
2239     }
2240 
2241     if (ctxt->parseFlags & XML_PARSE_NOXINCNODE) {
2242 	/*
2243 	 * Add the list of nodes
2244 	 */
2245 	while (list != NULL) {
2246 	    end = list;
2247 	    list = list->next;
2248 
2249 	    xmlAddPrevSibling(cur, end);
2250 	}
2251 	xmlUnlinkNode(cur);
2252 	xmlFreeNode(cur);
2253     } else {
2254 	/*
2255 	 * Change the current node as an XInclude start one, and add an
2256 	 * XInclude end one
2257 	 */
2258 	cur->type = XML_XINCLUDE_START;
2259 	end = xmlNewDocNode(cur->doc, cur->ns, cur->name, NULL);
2260 	if (end == NULL) {
2261 	    xmlXIncludeErr(ctxt, ctxt->incTab[nr]->ref,
2262 	                   XML_XINCLUDE_BUILD_FAILED,
2263 			   "failed to build node\n", NULL);
2264 	    return(-1);
2265 	}
2266 	end->type = XML_XINCLUDE_END;
2267 	xmlAddNextSibling(cur, end);
2268 
2269 	/*
2270 	 * Add the list of nodes
2271 	 */
2272 	while (list != NULL) {
2273 	    cur = list;
2274 	    list = list->next;
2275 
2276 	    xmlAddPrevSibling(end, cur);
2277 	}
2278     }
2279 
2280 
2281     return(0);
2282 }
2283 
2284 /**
2285  * xmlXIncludeTestNode:
2286  * @ctxt: the XInclude processing context
2287  * @node: an XInclude node
2288  *
2289  * test if the node is an XInclude node
2290  *
2291  * Returns 1 true, 0 otherwise
2292  */
2293 static int
xmlXIncludeTestNode(xmlXIncludeCtxtPtr ctxt,xmlNodePtr node)2294 xmlXIncludeTestNode(xmlXIncludeCtxtPtr ctxt, xmlNodePtr node) {
2295     if (node == NULL)
2296 	return(0);
2297     if (node->type != XML_ELEMENT_NODE)
2298 	return(0);
2299     if (node->ns == NULL)
2300 	return(0);
2301     if ((xmlStrEqual(node->ns->href, XINCLUDE_NS)) ||
2302         (xmlStrEqual(node->ns->href, XINCLUDE_OLD_NS))) {
2303 	if (xmlStrEqual(node->ns->href, XINCLUDE_OLD_NS)) {
2304 	    if (ctxt->legacy == 0) {
2305 #if 0 /* wait for the XML Core Working Group to get something stable ! */
2306 		xmlXIncludeWarn(ctxt, node, XML_XINCLUDE_DEPRECATED_NS,
2307 	               "Deprecated XInclude namespace found, use %s",
2308 		                XINCLUDE_NS);
2309 #endif
2310 	        ctxt->legacy = 1;
2311 	    }
2312 	}
2313 	if (xmlStrEqual(node->name, XINCLUDE_NODE)) {
2314 	    xmlNodePtr child = node->children;
2315 	    int nb_fallback = 0;
2316 
2317 	    while (child != NULL) {
2318 		if ((child->type == XML_ELEMENT_NODE) &&
2319 		    (child->ns != NULL) &&
2320 		    ((xmlStrEqual(child->ns->href, XINCLUDE_NS)) ||
2321 		     (xmlStrEqual(child->ns->href, XINCLUDE_OLD_NS)))) {
2322 		    if (xmlStrEqual(child->name, XINCLUDE_NODE)) {
2323 			xmlXIncludeErr(ctxt, node,
2324 			               XML_XINCLUDE_INCLUDE_IN_INCLUDE,
2325 				       "%s has an 'include' child\n",
2326 				       XINCLUDE_NODE);
2327 			return(0);
2328 		    }
2329 		    if (xmlStrEqual(child->name, XINCLUDE_FALLBACK)) {
2330 			nb_fallback++;
2331 		    }
2332 		}
2333 		child = child->next;
2334 	    }
2335 	    if (nb_fallback > 1) {
2336 		xmlXIncludeErr(ctxt, node, XML_XINCLUDE_FALLBACKS_IN_INCLUDE,
2337 			       "%s has multiple fallback children\n",
2338 		               XINCLUDE_NODE);
2339 		return(0);
2340 	    }
2341 	    return(1);
2342 	}
2343 	if (xmlStrEqual(node->name, XINCLUDE_FALLBACK)) {
2344 	    if ((node->parent == NULL) ||
2345 		(node->parent->type != XML_ELEMENT_NODE) ||
2346 		(node->parent->ns == NULL) ||
2347 		((!xmlStrEqual(node->parent->ns->href, XINCLUDE_NS)) &&
2348 		 (!xmlStrEqual(node->parent->ns->href, XINCLUDE_OLD_NS))) ||
2349 		(!xmlStrEqual(node->parent->name, XINCLUDE_NODE))) {
2350 		xmlXIncludeErr(ctxt, node,
2351 		               XML_XINCLUDE_FALLBACK_NOT_IN_INCLUDE,
2352 			       "%s is not the child of an 'include'\n",
2353 			       XINCLUDE_FALLBACK);
2354 	    }
2355 	}
2356     }
2357     return(0);
2358 }
2359 
2360 /**
2361  * xmlXIncludeDoProcess:
2362  * @ctxt: the XInclude processing context
2363  * @doc: an XML document
2364  * @tree: the top of the tree to process
2365  *
2366  * Implement the XInclude substitution on the XML document @doc
2367  *
2368  * Returns 0 if no substitution were done, -1 if some processing failed
2369  *    or the number of substitutions done.
2370  */
2371 static int
xmlXIncludeDoProcess(xmlXIncludeCtxtPtr ctxt,xmlDocPtr doc,xmlNodePtr tree)2372 xmlXIncludeDoProcess(xmlXIncludeCtxtPtr ctxt, xmlDocPtr doc, xmlNodePtr tree) {
2373     xmlNodePtr cur;
2374     int ret = 0;
2375     int i, start;
2376 
2377     if ((doc == NULL) || (tree == NULL) || (tree->type == XML_NAMESPACE_DECL))
2378 	return(-1);
2379     if (ctxt == NULL)
2380 	return(-1);
2381 
2382     if (doc->URL != NULL) {
2383 	ret = xmlXIncludeURLPush(ctxt, doc->URL);
2384 	if (ret < 0)
2385 	    return(-1);
2386     }
2387     start = ctxt->incNr;
2388 
2389     /*
2390      * First phase: lookup the elements in the document
2391      */
2392     cur = tree;
2393     if (xmlXIncludeTestNode(ctxt, cur) == 1)
2394 	xmlXIncludePreProcessNode(ctxt, cur);
2395     while ((cur != NULL) && (cur != tree->parent)) {
2396 	/* TODO: need to work on entities -> stack */
2397 	if ((cur->children != NULL) &&
2398 	    ((cur->type == XML_DOCUMENT_NODE) ||
2399 	    (cur->type == XML_ELEMENT_NODE))) {
2400 	    cur = cur->children;
2401 	    if (xmlXIncludeTestNode(ctxt, cur))
2402 		xmlXIncludePreProcessNode(ctxt, cur);
2403 	} else if (cur->next != NULL) {
2404 	    cur = cur->next;
2405 	    if (xmlXIncludeTestNode(ctxt, cur))
2406 		xmlXIncludePreProcessNode(ctxt, cur);
2407 	} else {
2408 	    if (cur == tree)
2409 	        break;
2410 	    do {
2411 		cur = cur->parent;
2412 		if ((cur == NULL) || (cur == tree->parent))
2413 		    break; /* do */
2414 		if (cur->next != NULL) {
2415 		    cur = cur->next;
2416 		    if (xmlXIncludeTestNode(ctxt, cur))
2417 			xmlXIncludePreProcessNode(ctxt, cur);
2418 		    break; /* do */
2419 		}
2420 	    } while (cur != NULL);
2421 	}
2422     }
2423 
2424     /*
2425      * Second Phase : collect the infosets fragments
2426      */
2427     for (i = start;i < ctxt->incNr; i++) {
2428         xmlXIncludeLoadNode(ctxt, i);
2429 	ret++;
2430     }
2431 
2432     /*
2433      * Third phase: extend the original document infoset.
2434      *
2435      * Originally we bypassed the inclusion if there were any errors
2436      * encountered on any of the XIncludes.  A bug was raised (bug
2437      * 132588) requesting that we output the XIncludes without error,
2438      * so the check for inc!=NULL || xptr!=NULL was put in.  This may
2439      * give some other problems in the future, but for now it seems to
2440      * work ok.
2441      *
2442      */
2443     for (i = ctxt->incBase;i < ctxt->incNr; i++) {
2444 	if ((ctxt->incTab[i]->inc != NULL) ||
2445 		(ctxt->incTab[i]->xptr != NULL) ||
2446 		(ctxt->incTab[i]->emptyFb != 0))	/* (empty fallback) */
2447 	    xmlXIncludeIncludeNode(ctxt, i);
2448     }
2449 
2450     if (doc->URL != NULL)
2451 	xmlXIncludeURLPop(ctxt);
2452     return(ret);
2453 }
2454 
2455 /**
2456  * xmlXIncludeSetFlags:
2457  * @ctxt:  an XInclude processing context
2458  * @flags: a set of xmlParserOption used for parsing XML includes
2459  *
2460  * Set the flags used for further processing of XML resources.
2461  *
2462  * Returns 0 in case of success and -1 in case of error.
2463  */
2464 int
xmlXIncludeSetFlags(xmlXIncludeCtxtPtr ctxt,int flags)2465 xmlXIncludeSetFlags(xmlXIncludeCtxtPtr ctxt, int flags) {
2466     if (ctxt == NULL)
2467         return(-1);
2468     ctxt->parseFlags = flags;
2469     return(0);
2470 }
2471 
2472 /**
2473  * xmlXIncludeProcessTreeFlagsData:
2474  * @tree: an XML node
2475  * @flags: a set of xmlParserOption used for parsing XML includes
2476  * @data: application data that will be passed to the parser context
2477  *        in the _private field of the parser context(s)
2478  *
2479  * Implement the XInclude substitution on the XML node @tree
2480  *
2481  * Returns 0 if no substitution were done, -1 if some processing failed
2482  *    or the number of substitutions done.
2483  */
2484 
2485 int
xmlXIncludeProcessTreeFlagsData(xmlNodePtr tree,int flags,void * data)2486 xmlXIncludeProcessTreeFlagsData(xmlNodePtr tree, int flags, void *data) {
2487     xmlXIncludeCtxtPtr ctxt;
2488     int ret = 0;
2489 
2490     if ((tree == NULL) || (tree->type == XML_NAMESPACE_DECL) ||
2491         (tree->doc == NULL))
2492         return(-1);
2493 
2494     ctxt = xmlXIncludeNewContext(tree->doc);
2495     if (ctxt == NULL)
2496         return(-1);
2497     ctxt->_private = data;
2498     ctxt->base = xmlStrdup((xmlChar *)tree->doc->URL);
2499     xmlXIncludeSetFlags(ctxt, flags);
2500     ret = xmlXIncludeDoProcess(ctxt, tree->doc, tree);
2501     if ((ret >= 0) && (ctxt->nbErrors > 0))
2502         ret = -1;
2503 
2504     xmlXIncludeFreeContext(ctxt);
2505     return(ret);
2506 }
2507 
2508 /**
2509  * xmlXIncludeProcessFlagsData:
2510  * @doc: an XML document
2511  * @flags: a set of xmlParserOption used for parsing XML includes
2512  * @data: application data that will be passed to the parser context
2513  *        in the _private field of the parser context(s)
2514  *
2515  * Implement the XInclude substitution on the XML document @doc
2516  *
2517  * Returns 0 if no substitution were done, -1 if some processing failed
2518  *    or the number of substitutions done.
2519  */
2520 int
xmlXIncludeProcessFlagsData(xmlDocPtr doc,int flags,void * data)2521 xmlXIncludeProcessFlagsData(xmlDocPtr doc, int flags, void *data) {
2522     xmlNodePtr tree;
2523 
2524     if (doc == NULL)
2525 	return(-1);
2526     tree = xmlDocGetRootElement(doc);
2527     if (tree == NULL)
2528 	return(-1);
2529     return(xmlXIncludeProcessTreeFlagsData(tree, flags, data));
2530 }
2531 
2532 /**
2533  * xmlXIncludeProcessFlags:
2534  * @doc: an XML document
2535  * @flags: a set of xmlParserOption used for parsing XML includes
2536  *
2537  * Implement the XInclude substitution on the XML document @doc
2538  *
2539  * Returns 0 if no substitution were done, -1 if some processing failed
2540  *    or the number of substitutions done.
2541  */
2542 int
xmlXIncludeProcessFlags(xmlDocPtr doc,int flags)2543 xmlXIncludeProcessFlags(xmlDocPtr doc, int flags) {
2544     return xmlXIncludeProcessFlagsData(doc, flags, NULL);
2545 }
2546 
2547 /**
2548  * xmlXIncludeProcess:
2549  * @doc: an XML document
2550  *
2551  * Implement the XInclude substitution on the XML document @doc
2552  *
2553  * Returns 0 if no substitution were done, -1 if some processing failed
2554  *    or the number of substitutions done.
2555  */
2556 int
xmlXIncludeProcess(xmlDocPtr doc)2557 xmlXIncludeProcess(xmlDocPtr doc) {
2558     return(xmlXIncludeProcessFlags(doc, 0));
2559 }
2560 
2561 /**
2562  * xmlXIncludeProcessTreeFlags:
2563  * @tree: a node in an XML document
2564  * @flags: a set of xmlParserOption used for parsing XML includes
2565  *
2566  * Implement the XInclude substitution for the given subtree
2567  *
2568  * Returns 0 if no substitution were done, -1 if some processing failed
2569  *    or the number of substitutions done.
2570  */
2571 int
xmlXIncludeProcessTreeFlags(xmlNodePtr tree,int flags)2572 xmlXIncludeProcessTreeFlags(xmlNodePtr tree, int flags) {
2573     xmlXIncludeCtxtPtr ctxt;
2574     int ret = 0;
2575 
2576     if ((tree == NULL) || (tree->type == XML_NAMESPACE_DECL) ||
2577         (tree->doc == NULL))
2578 	return(-1);
2579     ctxt = xmlXIncludeNewContext(tree->doc);
2580     if (ctxt == NULL)
2581 	return(-1);
2582     ctxt->base = xmlNodeGetBase(tree->doc, tree);
2583     xmlXIncludeSetFlags(ctxt, flags);
2584     ret = xmlXIncludeDoProcess(ctxt, tree->doc, tree);
2585     if ((ret >= 0) && (ctxt->nbErrors > 0))
2586 	ret = -1;
2587 
2588     xmlXIncludeFreeContext(ctxt);
2589     return(ret);
2590 }
2591 
2592 /**
2593  * xmlXIncludeProcessTree:
2594  * @tree: a node in an XML document
2595  *
2596  * Implement the XInclude substitution for the given subtree
2597  *
2598  * Returns 0 if no substitution were done, -1 if some processing failed
2599  *    or the number of substitutions done.
2600  */
2601 int
xmlXIncludeProcessTree(xmlNodePtr tree)2602 xmlXIncludeProcessTree(xmlNodePtr tree) {
2603     return(xmlXIncludeProcessTreeFlags(tree, 0));
2604 }
2605 
2606 /**
2607  * xmlXIncludeProcessNode:
2608  * @ctxt: an existing XInclude context
2609  * @node: a node in an XML document
2610  *
2611  * Implement the XInclude substitution for the given subtree reusing
2612  * the informations and data coming from the given context.
2613  *
2614  * Returns 0 if no substitution were done, -1 if some processing failed
2615  *    or the number of substitutions done.
2616  */
2617 int
xmlXIncludeProcessNode(xmlXIncludeCtxtPtr ctxt,xmlNodePtr node)2618 xmlXIncludeProcessNode(xmlXIncludeCtxtPtr ctxt, xmlNodePtr node) {
2619     int ret = 0;
2620 
2621     if ((node == NULL) || (node->type == XML_NAMESPACE_DECL) ||
2622         (node->doc == NULL) || (ctxt == NULL))
2623 	return(-1);
2624     ret = xmlXIncludeDoProcess(ctxt, node->doc, node);
2625     if ((ret >= 0) && (ctxt->nbErrors > 0))
2626 	ret = -1;
2627     return(ret);
2628 }
2629 
2630 #else /* !LIBXML_XINCLUDE_ENABLED */
2631 #endif
2632 #define bottom_xinclude
2633 #include "elfgcchack.h"
2634