Coverage Report

Created: 2026-08-15 06:15

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/libxml2/xinclude.c
Line
Count
Source
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
 * Author: Daniel Veillard
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
26
#ifdef LIBXML_XINCLUDE_ENABLED
27
#include <libxml/xinclude.h>
28
29
#include "private/buf.h"
30
#include "private/error.h"
31
#include "private/memory.h"
32
#include "private/parser.h"
33
#include "private/tree.h"
34
#include "private/xinclude.h"
35
36
21.2k
#define XINCLUDE_MAX_DEPTH 40
37
38
/************************************************************************
39
 *                  *
40
 *      XInclude context handling     *
41
 *                  *
42
 ************************************************************************/
43
44
/*
45
 * An XInclude context
46
 */
47
typedef xmlChar *xmlURL;
48
49
typedef struct _xmlXIncludeRef xmlXIncludeRef;
50
typedef xmlXIncludeRef *xmlXIncludeRefPtr;
51
struct _xmlXIncludeRef {
52
    xmlChar              *URI; /* the fully resolved resource URL */
53
    xmlChar         *fragment; /* the fragment in the URI */
54
    xmlChar             *base; /* base URI of xi:include element */
55
    xmlNodePtr           elem; /* the xi:include element */
56
    xmlNodePtr            inc; /* the included copy */
57
    int                   xml; /* xml or txt */
58
    int              fallback; /* fallback was loaded */
59
    int       expanding; /* flag to detect inclusion loops */
60
    int         replace; /* should the node be replaced? */
61
};
62
63
typedef struct _xmlXIncludeDoc xmlXIncludeDoc;
64
typedef xmlXIncludeDoc *xmlXIncludeDocPtr;
65
struct _xmlXIncludeDoc {
66
    xmlDocPtr             doc; /* the parsed document */
67
    xmlChar              *url; /* the URL */
68
    int             expanding; /* flag to detect inclusion loops */
69
};
70
71
typedef struct _xmlXIncludeTxt xmlXIncludeTxt;
72
typedef xmlXIncludeTxt *xmlXIncludeTxtPtr;
73
struct _xmlXIncludeTxt {
74
    xmlChar   *text; /* text string */
75
    xmlChar              *url; /* the URL */
76
};
77
78
struct _xmlXIncludeCtxt {
79
    xmlDocPtr             doc; /* the source document */
80
    int                 incNr; /* number of includes */
81
    int                incMax; /* size of includes tab */
82
    xmlXIncludeRefPtr *incTab; /* array of included references */
83
84
    int                 txtNr; /* number of unparsed documents */
85
    int                txtMax; /* size of unparsed documents tab */
86
    xmlXIncludeTxt    *txtTab; /* array of unparsed documents */
87
88
    int                 urlNr; /* number of documents stacked */
89
    int                urlMax; /* size of document stack */
90
    xmlXIncludeDoc    *urlTab; /* document stack */
91
92
    int              nbErrors; /* the number of errors detected */
93
    int              fatalErr; /* abort processing */
94
    int                 errNo; /* error code */
95
    int                legacy; /* using XINCLUDE_OLD_NS */
96
    int            parseFlags; /* the flags used for parsing XML documents */
97
98
    void            *_private; /* application data */
99
100
#ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
101
    unsigned long    incTotal; /* total number of processed inclusions */
102
#endif
103
    int     depth; /* recursion depth */
104
    int        isStream; /* streaming mode */
105
106
#ifdef LIBXML_XPTR_ENABLED
107
    xmlXPathContextPtr xpctxt;
108
#endif
109
110
    xmlStructuredErrorFunc errorHandler;
111
    void *errorCtxt;
112
113
    xmlResourceLoader resourceLoader;
114
    void *resourceCtxt;
115
};
116
117
static xmlXIncludeRefPtr
118
xmlXIncludeExpandNode(xmlXIncludeCtxtPtr ctxt, xmlNodePtr node);
119
120
static int
121
xmlXIncludeLoadNode(xmlXIncludeCtxtPtr ctxt, xmlXIncludeRefPtr ref);
122
123
static int
124
xmlXIncludeDoProcess(xmlXIncludeCtxtPtr ctxt, xmlNodePtr tree);
125
126
127
/************************************************************************
128
 *                  *
129
 *      XInclude error handler        *
130
 *                  *
131
 ************************************************************************/
132
133
/**
134
 * Handle an out of memory condition
135
 *
136
 * @param ctxt  an XInclude context
137
 */
138
static void
139
xmlXIncludeErrMemory(xmlXIncludeCtxtPtr ctxt)
140
3.10k
{
141
3.10k
    ctxt->errNo = XML_ERR_NO_MEMORY;
142
3.10k
    ctxt->fatalErr = 1;
143
3.10k
    ctxt->nbErrors++;
144
145
3.10k
    xmlRaiseMemoryError(ctxt->errorHandler, NULL, ctxt->errorCtxt,
146
3.10k
                        XML_FROM_XINCLUDE, NULL);
147
3.10k
}
148
149
/**
150
 * Handle an XInclude error
151
 *
152
 * @param ctxt  the XInclude context
153
 * @param node  the context node
154
 * @param error  the error code
155
 * @param msg  the error message
156
 * @param extra  extra information
157
 */
158
static void LIBXML_ATTR_FORMAT(4,0)
159
xmlXIncludeErr(xmlXIncludeCtxtPtr ctxt, xmlNodePtr node, int error,
160
               const char *msg, const xmlChar *extra)
161
23.1k
{
162
23.1k
    xmlStructuredErrorFunc schannel = NULL;
163
23.1k
    xmlGenericErrorFunc channel = NULL;
164
23.1k
    void *data = NULL;
165
23.1k
    int res;
166
167
23.1k
    if (error == XML_ERR_NO_MEMORY) {
168
141
        xmlXIncludeErrMemory(ctxt);
169
141
        return;
170
141
    }
171
172
23.0k
    if (ctxt->fatalErr != 0)
173
6.42k
        return;
174
16.5k
    ctxt->nbErrors++;
175
176
16.5k
    schannel = ctxt->errorHandler;
177
16.5k
    data = ctxt->errorCtxt;
178
179
16.5k
    if (schannel == NULL) {
180
0
        channel = xmlGenericError;
181
0
        data = xmlGenericErrorContext;
182
0
    }
183
184
16.5k
    res = xmlRaiseError(schannel, channel, data, ctxt, node,
185
16.5k
                        XML_FROM_XINCLUDE, error, XML_ERR_ERROR,
186
16.5k
                        NULL, 0, (const char *) extra, NULL, NULL, 0, 0,
187
16.5k
                        msg, (const char *) extra);
188
16.5k
    if (res < 0) {
189
131
        ctxt->errNo = XML_ERR_NO_MEMORY;
190
131
        ctxt->fatalErr = 1;
191
16.4k
    } else {
192
16.4k
        ctxt->errNo = error;
193
        /*
194
         * Note that we treat IO errors except ENOENT as fatal
195
         * although the XInclude spec could be interpreted in a
196
         * way that at least some IO errors should be handled
197
         * gracefully.
198
         */
199
16.4k
        if (xmlIsCatastrophicError(XML_ERR_FATAL, error))
200
2
            ctxt->fatalErr = 1;
201
16.4k
    }
202
16.5k
}
203
204
/**
205
 * Get an XInclude attribute
206
 *
207
 * @param ctxt  the XInclude context
208
 * @param cur  the node
209
 * @param name  the attribute name
210
 * @returns the value (to be freed) or NULL if not found
211
 */
212
static xmlChar *
213
xmlXIncludeGetProp(xmlXIncludeCtxtPtr ctxt, xmlNodePtr cur,
214
57.2k
                   const xmlChar *name) {
215
57.2k
    xmlChar *ret;
216
217
57.2k
    if (xmlNodeGetAttrValue(cur, name, XINCLUDE_NS, &ret) < 0)
218
3
        xmlXIncludeErrMemory(ctxt);
219
57.2k
    if (ret != NULL)
220
38
        return(ret);
221
222
57.2k
    if (ctxt->legacy != 0) {
223
31.4k
        if (xmlNodeGetAttrValue(cur, name, XINCLUDE_OLD_NS, &ret) < 0)
224
1
            xmlXIncludeErrMemory(ctxt);
225
31.4k
        if (ret != NULL)
226
39
            return(ret);
227
31.4k
    }
228
229
57.1k
    if (xmlNodeGetAttrValue(cur, name, NULL, &ret) < 0)
230
42
        xmlXIncludeErrMemory(ctxt);
231
57.1k
    return(ret);
232
57.2k
}
233
/**
234
 * Free an XInclude reference
235
 *
236
 * @param ref  the XInclude reference
237
 */
238
static void
239
36.9k
xmlXIncludeFreeRef(xmlXIncludeRefPtr ref) {
240
36.9k
    if (ref == NULL)
241
19.1k
  return;
242
17.8k
    if (ref->URI != NULL)
243
17.8k
  xmlFree(ref->URI);
244
17.8k
    if (ref->fragment != NULL)
245
11.0k
  xmlFree(ref->fragment);
246
17.8k
    if (ref->base != NULL)
247
9.66k
  xmlFree(ref->base);
248
17.8k
    xmlFree(ref);
249
17.8k
}
250
251
/**
252
 * Creates a new XInclude context
253
 *
254
 * @param doc  an XML Document
255
 * @returns the new set
256
 */
257
xmlXIncludeCtxt *
258
8.06k
xmlXIncludeNewContext(xmlDoc *doc) {
259
8.06k
    xmlXIncludeCtxtPtr ret;
260
261
8.06k
    if (doc == NULL)
262
0
  return(NULL);
263
8.06k
    ret = (xmlXIncludeCtxtPtr) xmlMalloc(sizeof(xmlXIncludeCtxt));
264
8.06k
    if (ret == NULL)
265
1
  return(NULL);
266
8.06k
    memset(ret, 0, sizeof(xmlXIncludeCtxt));
267
8.06k
    ret->doc = doc;
268
8.06k
    ret->incNr = 0;
269
8.06k
    ret->incMax = 0;
270
8.06k
    ret->incTab = NULL;
271
8.06k
    ret->nbErrors = 0;
272
8.06k
    return(ret);
273
8.06k
}
274
275
/**
276
 * Free an XInclude context
277
 *
278
 * @param ctxt  the XInclude context
279
 */
280
void
281
8.06k
xmlXIncludeFreeContext(xmlXIncludeCtxt *ctxt) {
282
8.06k
    int i;
283
284
8.06k
    if (ctxt == NULL)
285
0
  return;
286
8.06k
    if (ctxt->urlTab != NULL) {
287
16.5k
  for (i = 0; i < ctxt->urlNr; i++) {
288
8.76k
      xmlFreeDoc(ctxt->urlTab[i].doc);
289
8.76k
      xmlFree(ctxt->urlTab[i].url);
290
8.76k
  }
291
7.73k
  xmlFree(ctxt->urlTab);
292
7.73k
    }
293
8.06k
    for (i = 0;i < ctxt->incNr;i++) {
294
0
  if (ctxt->incTab[i] != NULL)
295
0
      xmlXIncludeFreeRef(ctxt->incTab[i]);
296
0
    }
297
8.06k
    if (ctxt->incTab != NULL)
298
7.98k
  xmlFree(ctxt->incTab);
299
8.06k
    if (ctxt->txtTab != NULL) {
300
104
  for (i = 0;i < ctxt->txtNr;i++) {
301
51
      xmlFree(ctxt->txtTab[i].text);
302
51
      xmlFree(ctxt->txtTab[i].url);
303
51
  }
304
53
  xmlFree(ctxt->txtTab);
305
53
    }
306
8.06k
#ifdef LIBXML_XPTR_ENABLED
307
8.06k
    if (ctxt->xpctxt != NULL)
308
6.39k
  xmlXPathFreeContext(ctxt->xpctxt);
309
8.06k
#endif
310
8.06k
    xmlFree(ctxt);
311
8.06k
}
312
313
/**
314
 * parse a document for XInclude
315
 *
316
 * @param ctxt  the XInclude context
317
 * @param URL  the URL or file path
318
 */
319
static xmlDocPtr
320
8.77k
xmlXIncludeParseFile(xmlXIncludeCtxtPtr ctxt, const char *URL) {
321
8.77k
    xmlDocPtr ret = NULL;
322
8.77k
    xmlParserCtxtPtr pctxt;
323
8.77k
    xmlParserInputPtr inputStream;
324
325
8.77k
    xmlInitParser();
326
327
8.77k
    pctxt = xmlNewParserCtxt();
328
8.77k
    if (pctxt == NULL) {
329
14
  xmlXIncludeErrMemory(ctxt);
330
14
  return(NULL);
331
14
    }
332
8.75k
    if (ctxt->errorHandler != NULL)
333
8.75k
        xmlCtxtSetErrorHandler(pctxt, ctxt->errorHandler, ctxt->errorCtxt);
334
8.75k
    if (ctxt->resourceLoader != NULL)
335
8.75k
        xmlCtxtSetResourceLoader(pctxt, ctxt->resourceLoader,
336
8.75k
                                 ctxt->resourceCtxt);
337
338
    /*
339
     * pass in the application data to the parser context.
340
     */
341
8.75k
    pctxt->_private = ctxt->_private;
342
343
    /*
344
     * try to ensure that new documents included are actually
345
     * built with the same dictionary as the including document.
346
     */
347
8.75k
    if ((ctxt->doc != NULL) && (ctxt->doc->dict != NULL)) {
348
4.69k
       if (pctxt->dict != NULL)
349
4.69k
            xmlDictFree(pctxt->dict);
350
4.69k
  pctxt->dict = ctxt->doc->dict;
351
4.69k
  xmlDictReference(pctxt->dict);
352
4.69k
    }
353
354
    /*
355
     * We set DTDLOAD to make sure that ID attributes declared in
356
     * external DTDs are detected.
357
     */
358
8.75k
    xmlCtxtUseOptions(pctxt, ctxt->parseFlags | XML_PARSE_DTDLOAD);
359
360
8.75k
    inputStream = xmlLoadResource(pctxt, URL, NULL, XML_RESOURCE_XINCLUDE);
361
8.75k
    if (inputStream == NULL)
362
801
        goto error;
363
364
7.95k
    if (xmlCtxtPushInput(pctxt, inputStream) < 0) {
365
1
        xmlFreeInputStream(inputStream);
366
1
        goto error;
367
1
    }
368
369
7.95k
    xmlParseDocument(pctxt);
370
371
7.95k
    if (pctxt->wellFormed) {
372
7.07k
        ret = pctxt->myDoc;
373
7.07k
    }
374
883
    else {
375
883
        ret = NULL;
376
883
  if (pctxt->myDoc != NULL)
377
818
      xmlFreeDoc(pctxt->myDoc);
378
883
        pctxt->myDoc = NULL;
379
883
    }
380
381
8.75k
error:
382
8.75k
    if (xmlCtxtIsCatastrophicError(pctxt))
383
142
        xmlXIncludeErr(ctxt, NULL, pctxt->errNo, "parser error", NULL);
384
8.75k
    xmlFreeParserCtxt(pctxt);
385
386
8.75k
    return(ret);
387
7.95k
}
388
389
/**
390
 * Add a new node to process to an XInclude context
391
 *
392
 * @param ctxt  the XInclude context
393
 * @param cur  the new node
394
 */
395
static xmlXIncludeRefPtr
396
19.1k
xmlXIncludeAddNode(xmlXIncludeCtxtPtr ctxt, xmlNodePtr cur) {
397
19.1k
    xmlXIncludeRefPtr ref = NULL;
398
19.1k
    xmlXIncludeRefPtr ret = NULL;
399
19.1k
    xmlURIPtr uri = NULL;
400
19.1k
    xmlChar *href = NULL;
401
19.1k
    xmlChar *parse = NULL;
402
19.1k
    xmlChar *fragment = NULL;
403
19.1k
    xmlChar *base = NULL;
404
19.1k
    xmlChar *tmp;
405
19.1k
    int xml = 1;
406
19.1k
    int local = 0;
407
19.1k
    int res;
408
409
19.1k
    if (ctxt == NULL)
410
0
  return(NULL);
411
19.1k
    if (cur == NULL)
412
0
  return(NULL);
413
414
    /*
415
     * read the attributes
416
     */
417
418
19.1k
    fragment = xmlXIncludeGetProp(ctxt, cur, XINCLUDE_PARSE_XPOINTER);
419
420
19.1k
    href = xmlXIncludeGetProp(ctxt, cur, XINCLUDE_HREF);
421
19.1k
    if (href == NULL) {
422
502
        if (fragment == NULL) {
423
377
      xmlXIncludeErr(ctxt, cur, XML_XINCLUDE_NO_HREF,
424
377
                     "href or xpointer must be present\n", parse);
425
377
      goto error;
426
377
        }
427
428
125
  href = xmlStrdup(BAD_CAST ""); /* @@@@ href is now optional */
429
125
  if (href == NULL) {
430
2
            xmlXIncludeErrMemory(ctxt);
431
2
      goto error;
432
2
        }
433
18.6k
    } else if (xmlStrlen(href) > XML_MAX_URI_LENGTH) {
434
23
        xmlXIncludeErr(ctxt, cur, XML_XINCLUDE_HREF_URI, "URI too long\n",
435
23
                       NULL);
436
23
        goto error;
437
23
    }
438
439
18.7k
    parse = xmlXIncludeGetProp(ctxt, cur, XINCLUDE_PARSE);
440
18.7k
    if (parse != NULL) {
441
409
  if (xmlStrEqual(parse, XINCLUDE_PARSE_XML))
442
174
      xml = 1;
443
235
  else if (xmlStrEqual(parse, XINCLUDE_PARSE_TEXT))
444
197
      xml = 0;
445
38
  else {
446
38
      xmlXIncludeErr(ctxt, cur, XML_XINCLUDE_PARSE_VALUE,
447
38
                     "invalid value %s for 'parse'\n", parse);
448
38
      goto error;
449
38
  }
450
409
    }
451
452
    /*
453
     * Check the URL and remove any fragment identifier
454
     */
455
18.7k
    res = xmlParseURISafe((const char *)href, &uri);
456
18.7k
    if (uri == NULL) {
457
188
        if (res < 0)
458
46
            xmlXIncludeErrMemory(ctxt);
459
142
        else
460
142
            xmlXIncludeErr(ctxt, cur, XML_XINCLUDE_HREF_URI,
461
142
                           "invalid value href %s\n", href);
462
188
        goto error;
463
188
    }
464
465
18.5k
    if (uri->fragment != NULL) {
466
1.43k
        if (ctxt->legacy != 0) {
467
1.39k
      if (fragment == NULL) {
468
1.30k
    fragment = (xmlChar *) uri->fragment;
469
1.30k
      } else {
470
89
    xmlFree(uri->fragment);
471
89
      }
472
1.39k
  } else {
473
47
      xmlXIncludeErr(ctxt, cur, XML_XINCLUDE_FRAGMENT_ID,
474
47
       "Invalid fragment identifier in URI %s use the xpointer attribute\n",
475
47
                           href);
476
47
      goto error;
477
47
  }
478
1.39k
  uri->fragment = NULL;
479
1.39k
    }
480
18.4k
    tmp = xmlSaveUri(uri);
481
18.4k
    if (tmp == NULL) {
482
13
  xmlXIncludeErrMemory(ctxt);
483
13
  goto error;
484
13
    }
485
18.4k
    xmlFree(href);
486
18.4k
    href = tmp;
487
488
    /*
489
     * Resolve URI
490
     */
491
492
18.4k
    if (xmlNodeGetBaseSafe(ctxt->doc, cur, &base) < 0) {
493
16
        xmlXIncludeErrMemory(ctxt);
494
16
        goto error;
495
16
    }
496
497
18.4k
    if (href[0] != 0) {
498
17.7k
        if (xmlBuildURISafe(href, base, &tmp) < 0) {
499
64
            xmlXIncludeErrMemory(ctxt);
500
64
            goto error;
501
64
        }
502
17.6k
        if (tmp == NULL) {
503
1
            xmlXIncludeErr(ctxt, cur, XML_XINCLUDE_HREF_URI,
504
1
                           "failed build URL\n", NULL);
505
1
            goto error;
506
1
        }
507
17.6k
        xmlFree(href);
508
17.6k
        href = tmp;
509
510
17.6k
        if (xmlStrEqual(href, ctxt->doc->URL))
511
3.26k
            local = 1;
512
17.6k
    } else {
513
757
        local = 1;
514
757
    }
515
516
    /*
517
     * If local and xml then we need a fragment
518
     */
519
18.3k
    if ((local == 1) && (xml == 1) &&
520
4.01k
        ((fragment == NULL) || (fragment[0] == 0))) {
521
534
  xmlXIncludeErr(ctxt, cur, XML_XINCLUDE_RECURSION,
522
534
                 "detected a local recursion with no xpointer in %s\n",
523
534
           href);
524
534
  goto error;
525
534
    }
526
527
17.8k
    ref = (xmlXIncludeRefPtr) xmlMalloc(sizeof(xmlXIncludeRef));
528
17.8k
    if (ref == NULL) {
529
12
        xmlXIncludeErrMemory(ctxt);
530
12
        goto error;
531
12
    }
532
17.8k
    memset(ref, 0, sizeof(xmlXIncludeRef));
533
534
17.8k
    ref->elem = cur;
535
17.8k
    ref->xml = xml;
536
17.8k
    ref->URI = href;
537
17.8k
    href = NULL;
538
17.8k
    ref->fragment = fragment;
539
17.8k
    fragment = NULL;
540
541
    /*
542
     * xml:base fixup
543
     */
544
17.8k
    if (((ctxt->parseFlags & XML_PARSE_NOBASEFIX) == 0) &&
545
9.66k
        (cur->doc != NULL) &&
546
9.66k
        ((cur->doc->parseFlags & XML_PARSE_NOBASEFIX) == 0)) {
547
9.66k
        if (base != NULL) {
548
5.22k
            ref->base = base;
549
5.22k
            base = NULL;
550
5.22k
        } else {
551
4.44k
            ref->base = xmlStrdup(BAD_CAST "");
552
4.44k
            if (ref->base == NULL) {
553
2
          xmlXIncludeErrMemory(ctxt);
554
2
                goto error;
555
2
            }
556
4.44k
        }
557
9.66k
    }
558
559
17.8k
    if (ctxt->incNr >= ctxt->incMax) {
560
12.2k
        xmlXIncludeRefPtr *table;
561
12.2k
        int newSize;
562
563
12.2k
        newSize = xmlGrowCapacity(ctxt->incMax, sizeof(table[0]),
564
12.2k
                                  4, XML_MAX_ITEMS);
565
12.2k
        if (newSize < 0) {
566
0
      xmlXIncludeErrMemory(ctxt);
567
0
      goto error;
568
0
  }
569
12.2k
        table = xmlRealloc(ctxt->incTab, newSize * sizeof(table[0]));
570
12.2k
        if (table == NULL) {
571
25
      xmlXIncludeErrMemory(ctxt);
572
25
      goto error;
573
25
  }
574
12.2k
        ctxt->incTab = table;
575
12.2k
        ctxt->incMax = newSize;
576
12.2k
    }
577
17.8k
    ctxt->incTab[ctxt->incNr++] = ref;
578
579
17.8k
    ret = ref;
580
17.8k
    ref = NULL;
581
582
19.1k
error:
583
19.1k
    xmlXIncludeFreeRef(ref);
584
19.1k
    xmlFreeURI(uri);
585
19.1k
    xmlFree(href);
586
19.1k
    xmlFree(parse);
587
19.1k
    xmlFree(fragment);
588
19.1k
    xmlFree(base);
589
19.1k
    return(ret);
590
17.8k
}
591
592
/**
593
 * The XInclude recursive nature is handled at this point.
594
 *
595
 * @param ctxt  the XInclude context
596
 * @param doc  the new document
597
 */
598
static void
599
7.07k
xmlXIncludeRecurseDoc(xmlXIncludeCtxtPtr ctxt, xmlDocPtr doc) {
600
7.07k
    xmlDocPtr oldDoc;
601
7.07k
    xmlXIncludeRefPtr *oldIncTab;
602
7.07k
    int oldIncMax, oldIncNr, oldIsStream;
603
7.07k
    int i;
604
605
7.07k
    oldDoc = ctxt->doc;
606
7.07k
    oldIncMax = ctxt->incMax;
607
7.07k
    oldIncNr = ctxt->incNr;
608
7.07k
    oldIncTab = ctxt->incTab;
609
7.07k
    oldIsStream = ctxt->isStream;
610
7.07k
    ctxt->doc = doc;
611
7.07k
    ctxt->incMax = 0;
612
7.07k
    ctxt->incNr = 0;
613
7.07k
    ctxt->incTab = NULL;
614
7.07k
    ctxt->isStream = 0;
615
616
7.07k
    xmlXIncludeDoProcess(ctxt, xmlDocGetRootElement(doc));
617
618
7.07k
    if (ctxt->incTab != NULL) {
619
7.43k
        for (i = 0; i < ctxt->incNr; i++)
620
4.47k
            xmlXIncludeFreeRef(ctxt->incTab[i]);
621
2.96k
        xmlFree(ctxt->incTab);
622
2.96k
    }
623
624
7.07k
    ctxt->doc = oldDoc;
625
7.07k
    ctxt->incMax = oldIncMax;
626
7.07k
    ctxt->incNr = oldIncNr;
627
7.07k
    ctxt->incTab = oldIncTab;
628
7.07k
    ctxt->isStream = oldIsStream;
629
7.07k
}
630
631
/************************************************************************
632
 *                  *
633
 *      Node copy with specific semantic    *
634
 *                  *
635
 ************************************************************************/
636
637
static void
638
xmlXIncludeBaseFixup(xmlXIncludeCtxtPtr ctxt, xmlNodePtr cur, xmlNodePtr copy,
639
98.4k
                     const xmlChar *targetBase) {
640
98.4k
    xmlChar *base = NULL;
641
98.4k
    xmlChar *relBase = NULL;
642
98.4k
    xmlNs ns;
643
98.4k
    int res;
644
645
98.4k
    if (cur->type != XML_ELEMENT_NODE)
646
71.9k
        return;
647
648
26.5k
    if (xmlNodeGetBaseSafe(cur->doc, cur, &base) < 0)
649
26
        xmlXIncludeErrMemory(ctxt);
650
651
26.5k
    if ((base != NULL) && !xmlStrEqual(base, targetBase)) {
652
23.4k
        if ((xmlStrlen(base) > XML_MAX_URI_LENGTH) ||
653
23.2k
            (xmlStrlen(targetBase) > XML_MAX_URI_LENGTH)) {
654
225
            relBase = xmlStrdup(base);
655
225
            if (relBase == NULL) {
656
1
                xmlXIncludeErrMemory(ctxt);
657
1
                goto done;
658
1
            }
659
23.2k
        } else if (xmlBuildRelativeURISafe(base, targetBase, &relBase) < 0) {
660
68
            xmlXIncludeErrMemory(ctxt);
661
68
            goto done;
662
68
        }
663
23.3k
        if (relBase == NULL) {
664
286
            xmlXIncludeErr(ctxt, cur,
665
286
                    XML_XINCLUDE_HREF_URI,
666
286
                    "Building relative URI failed: %s\n",
667
286
                    base);
668
286
            goto done;
669
286
        }
670
671
        /*
672
         * If the new base doesn't contain a slash, it can be omitted.
673
         */
674
23.0k
        if (xmlStrchr(relBase, '/') != NULL) {
675
2.76k
            res = xmlNodeSetBase(copy, relBase);
676
2.76k
            if (res < 0)
677
26
                xmlXIncludeErrMemory(ctxt);
678
2.76k
            goto done;
679
2.76k
        }
680
23.0k
    }
681
682
    /*
683
     * Delete existing xml:base if bases are equal
684
     */
685
23.4k
    memset(&ns, 0, sizeof(ns));
686
23.4k
    ns.href = XML_XML_NAMESPACE;
687
23.4k
    xmlUnsetNsProp(copy, &ns, BAD_CAST "base");
688
689
26.5k
done:
690
26.5k
    xmlFree(base);
691
26.5k
    xmlFree(relBase);
692
26.5k
}
693
694
/**
695
 * Make a copy of the node while expanding nested XIncludes.
696
 *
697
 * @param ctxt  the XInclude context
698
 * @param elem  the element
699
 * @param copyChildren  copy children instead of node if true
700
 * @param targetBase  the xml:base of the target node
701
 * @returns a node list, not a single node.
702
 */
703
static xmlNodePtr
704
xmlXIncludeCopyNode(xmlXIncludeCtxtPtr ctxt, xmlNodePtr elem,
705
230k
                    int copyChildren, const xmlChar *targetBase) {
706
230k
    xmlNodePtr result = NULL;
707
230k
    xmlNodePtr insertParent = NULL;
708
230k
    xmlNodePtr insertLast = NULL;
709
230k
    xmlNodePtr cur;
710
230k
    xmlNodePtr item;
711
230k
    int depth = 0;
712
713
230k
    if (copyChildren) {
714
496
        cur = elem->children;
715
496
        if (cur == NULL)
716
0
            return(NULL);
717
230k
    } else {
718
230k
        cur = elem;
719
230k
    }
720
721
1.26M
    while (1) {
722
1.26M
        xmlNodePtr copy = NULL;
723
1.26M
        int recurse = 0;
724
725
1.26M
        if ((cur->type == XML_DOCUMENT_NODE) ||
726
1.26M
            (cur->type == XML_DTD_NODE)) {
727
0
            ;
728
1.26M
        } else if ((cur->type == XML_ELEMENT_NODE) &&
729
407k
                   (cur->ns != NULL) &&
730
105k
                   (xmlStrEqual(cur->name, XINCLUDE_NODE)) &&
731
697
                   ((xmlStrEqual(cur->ns->href, XINCLUDE_NS)) ||
732
613
                    (xmlStrEqual(cur->ns->href, XINCLUDE_OLD_NS)))) {
733
613
            xmlXIncludeRefPtr ref = xmlXIncludeExpandNode(ctxt, cur);
734
735
613
            if (ref == NULL)
736
178
                goto error;
737
            /*
738
             * TODO: Insert XML_XINCLUDE_START and XML_XINCLUDE_END nodes
739
             */
740
3.49k
            for (item = ref->inc; item != NULL; item = item->next) {
741
3.06k
                copy = xmlStaticCopyNode(item, ctxt->doc, insertParent, 1);
742
3.06k
                if (copy == NULL) {
743
7
                    xmlXIncludeErrMemory(ctxt);
744
7
                    goto error;
745
7
                }
746
747
3.05k
                if (result == NULL)
748
29
                    result = copy;
749
3.05k
                if (insertLast != NULL) {
750
2.96k
                    insertLast->next = copy;
751
2.96k
                    copy->prev = insertLast;
752
2.96k
                } else if (insertParent != NULL) {
753
61
                    insertParent->children = copy;
754
61
                }
755
3.05k
                insertLast = copy;
756
757
3.05k
                if ((depth == 0) && (targetBase != NULL))
758
958
                    xmlXIncludeBaseFixup(ctxt, item, copy, targetBase);
759
3.05k
            }
760
1.26M
        } else {
761
1.26M
            copy = xmlStaticCopyNode(cur, ctxt->doc, insertParent, 2);
762
1.26M
            if (copy == NULL) {
763
146
                xmlXIncludeErrMemory(ctxt);
764
146
                goto error;
765
146
            }
766
767
1.26M
            if (result == NULL)
768
230k
                result = copy;
769
1.26M
            if (insertLast != NULL) {
770
825k
                insertLast->next = copy;
771
825k
                copy->prev = insertLast;
772
825k
            } else if (insertParent != NULL) {
773
210k
                insertParent->children = copy;
774
210k
            }
775
1.26M
            insertLast = copy;
776
777
1.26M
            if ((depth == 0) && (targetBase != NULL))
778
93.6k
                xmlXIncludeBaseFixup(ctxt, cur, copy, targetBase);
779
780
1.26M
            recurse = (cur->type != XML_ENTITY_REF_NODE) &&
781
1.26M
                      (cur->children != NULL);
782
1.26M
        }
783
784
1.26M
        if (recurse) {
785
211k
            cur = cur->children;
786
211k
            insertParent = insertLast;
787
211k
            insertLast = NULL;
788
211k
            depth += 1;
789
211k
            continue;
790
211k
        }
791
792
1.05M
        if (cur == elem)
793
224k
            return(result);
794
795
1.03M
        while (cur->next == NULL) {
796
209k
            if (insertParent != NULL)
797
208k
                insertParent->last = insertLast;
798
209k
            cur = cur->parent;
799
209k
            if (cur == elem)
800
5.65k
                return(result);
801
203k
            insertLast = insertParent;
802
203k
            insertParent = insertParent->parent;
803
203k
            depth -= 1;
804
203k
        }
805
806
825k
        cur = cur->next;
807
825k
    }
808
809
331
error:
810
331
    xmlFreeNodeList(result);
811
331
    return(NULL);
812
230k
}
813
814
#ifdef LIBXML_XPTR_ENABLED
815
/**
816
 * Build a node list tree copy of the XPointer result.
817
 * This will drop Attributes and Namespace declarations.
818
 *
819
 * @param ctxt  the XInclude context
820
 * @param obj  the XPointer result from the evaluation.
821
 * @param targetBase  the xml:base of the target node
822
 * @returns an xmlNode list or NULL.
823
 *         the caller has to free the node tree.
824
 */
825
static xmlNodePtr
826
xmlXIncludeCopyXPointer(xmlXIncludeCtxtPtr ctxt, xmlXPathObjectPtr obj,
827
1.03k
                        const xmlChar *targetBase) {
828
1.03k
    xmlNodePtr list = NULL, last = NULL, copy;
829
1.03k
    int i;
830
831
1.03k
    if ((ctxt == NULL) || (obj == NULL))
832
0
  return(NULL);
833
1.03k
    switch (obj->type) {
834
1.03k
        case XPATH_NODESET: {
835
1.03k
      xmlNodeSetPtr set = obj->nodesetval;
836
1.03k
      if (set == NULL)
837
0
    break;
838
231k
      for (i = 0;i < set->nodeNr;i++) {
839
230k
                xmlNodePtr node;
840
841
230k
    if (set->nodeTab[i] == NULL)
842
0
        continue;
843
230k
    switch (set->nodeTab[i]->type) {
844
306
        case XML_DOCUMENT_NODE:
845
306
        case XML_HTML_DOCUMENT_NODE:
846
306
                        node = xmlDocGetRootElement(
847
306
                                (xmlDocPtr) set->nodeTab[i]);
848
306
                        if (node == NULL) {
849
0
                            xmlXIncludeErr(ctxt, set->nodeTab[i],
850
0
                                           XML_ERR_INTERNAL_ERROR,
851
0
                                          "document without root\n", NULL);
852
0
                            continue;
853
0
                        }
854
306
                        break;
855
109k
                    case XML_TEXT_NODE:
856
136k
        case XML_CDATA_SECTION_NODE:
857
186k
        case XML_ELEMENT_NODE:
858
227k
        case XML_PI_NODE:
859
230k
        case XML_COMMENT_NODE:
860
230k
                        node = set->nodeTab[i];
861
230k
      break;
862
0
                    default:
863
0
                        xmlXIncludeErr(ctxt, set->nodeTab[i],
864
0
                                       XML_XINCLUDE_XPTR_RESULT,
865
0
                                       "invalid node type in XPtr result\n",
866
0
                                       NULL);
867
0
      continue; /* for */
868
230k
    }
869
                /*
870
                 * OPTIMIZE TODO: External documents should already be
871
                 * expanded, so xmlDocCopyNode should work as well.
872
                 * xmlXIncludeCopyNode is only required for the initial
873
                 * document.
874
                 */
875
230k
    copy = xmlXIncludeCopyNode(ctxt, node, 0, targetBase);
876
230k
                if (copy == NULL) {
877
342
                    xmlFreeNodeList(list);
878
342
                    return(NULL);
879
342
                }
880
230k
    if (last == NULL) {
881
568
                    list = copy;
882
229k
                } else {
883
229k
                    while (last->next != NULL)
884
0
                        last = last->next;
885
229k
                    copy->prev = last;
886
229k
                    last->next = copy;
887
229k
    }
888
230k
                last = copy;
889
230k
      }
890
695
      break;
891
1.03k
  }
892
695
  default:
893
0
      break;
894
1.03k
    }
895
695
    return(list);
896
1.03k
}
897
#endif
898
899
/************************************************************************
900
 *                  *
901
 *      XInclude I/O handling       *
902
 *                  *
903
 ************************************************************************/
904
905
typedef struct _xmlXIncludeMergeData xmlXIncludeMergeData;
906
typedef xmlXIncludeMergeData *xmlXIncludeMergeDataPtr;
907
struct _xmlXIncludeMergeData {
908
    xmlDocPtr doc;
909
    xmlXIncludeCtxtPtr ctxt;
910
};
911
912
/**
913
 * Implements the merge of one entity
914
 *
915
 * @param payload  the entity
916
 * @param vdata  the merge data
917
 * @param name  unused
918
 */
919
static void
920
xmlXIncludeMergeEntity(void *payload, void *vdata,
921
288
                 const xmlChar *name ATTRIBUTE_UNUSED) {
922
288
    xmlEntityPtr ent = (xmlEntityPtr) payload;
923
288
    xmlXIncludeMergeDataPtr data = (xmlXIncludeMergeDataPtr) vdata;
924
288
    xmlEntityPtr ret, prev;
925
288
    xmlDocPtr doc;
926
288
    xmlXIncludeCtxtPtr ctxt;
927
928
288
    if ((ent == NULL) || (data == NULL))
929
0
  return;
930
288
    ctxt = data->ctxt;
931
288
    doc = data->doc;
932
288
    if ((ctxt == NULL) || (doc == NULL))
933
0
  return;
934
288
    switch (ent->etype) {
935
0
        case XML_INTERNAL_PARAMETER_ENTITY:
936
0
        case XML_EXTERNAL_PARAMETER_ENTITY:
937
0
        case XML_INTERNAL_PREDEFINED_ENTITY:
938
0
      return;
939
55
        case XML_INTERNAL_GENERAL_ENTITY:
940
285
        case XML_EXTERNAL_GENERAL_PARSED_ENTITY:
941
288
        case XML_EXTERNAL_GENERAL_UNPARSED_ENTITY:
942
288
      break;
943
288
    }
944
288
    prev = xmlGetDocEntity(doc, ent->name);
945
288
    if (prev == NULL) {
946
154
        ret = xmlAddDocEntity(doc, ent->name, ent->etype, ent->ExternalID,
947
154
                              ent->SystemID, ent->content);
948
154
        if (ret == NULL) {
949
5
            xmlXIncludeErrMemory(ctxt);
950
5
            return;
951
5
        }
952
149
  if (ent->URI != NULL) {
953
104
      ret->URI = xmlStrdup(ent->URI);
954
104
            if (ret->URI == 0)
955
2
                xmlXIncludeErrMemory(ctxt);
956
104
        }
957
149
    } else {
958
134
        if (ent->etype != prev->etype)
959
18
            goto error;
960
961
116
        if ((ent->SystemID != NULL) && (prev->SystemID != NULL)) {
962
105
            if (!xmlStrEqual(ent->SystemID, prev->SystemID))
963
6
                goto error;
964
105
        } else if ((ent->ExternalID != NULL) &&
965
0
                   (prev->ExternalID != NULL)) {
966
0
            if (!xmlStrEqual(ent->ExternalID, prev->ExternalID))
967
0
                goto error;
968
11
        } else if ((ent->content != NULL) && (prev->content != NULL)) {
969
11
            if (!xmlStrEqual(ent->content, prev->content))
970
4
                goto error;
971
11
        } else {
972
0
            goto error;
973
0
        }
974
116
    }
975
255
    return;
976
255
error:
977
28
    switch (ent->etype) {
978
0
        case XML_INTERNAL_PARAMETER_ENTITY:
979
0
        case XML_EXTERNAL_PARAMETER_ENTITY:
980
0
        case XML_INTERNAL_PREDEFINED_ENTITY:
981
20
        case XML_INTERNAL_GENERAL_ENTITY:
982
28
        case XML_EXTERNAL_GENERAL_PARSED_ENTITY:
983
28
      return;
984
0
        case XML_EXTERNAL_GENERAL_UNPARSED_ENTITY:
985
0
      break;
986
28
    }
987
0
    xmlXIncludeErr(ctxt, (xmlNodePtr) ent, XML_XINCLUDE_ENTITY_DEF_MISMATCH,
988
0
                   "mismatch in redefinition of entity %s\n",
989
0
       ent->name);
990
0
}
991
992
/**
993
 * Implements the entity merge
994
 *
995
 * @param ctxt  an XInclude context
996
 * @param doc  the including doc
997
 * @param from  the included doc
998
 * @returns 0 if merge succeeded, -1 if some processing failed
999
 */
1000
static int
1001
xmlXIncludeMergeEntities(xmlXIncludeCtxtPtr ctxt, xmlDocPtr doc,
1002
7.07k
                   xmlDocPtr from) {
1003
7.07k
    xmlNodePtr cur;
1004
7.07k
    xmlDtdPtr target, source;
1005
1006
7.07k
    if (ctxt == NULL)
1007
0
  return(-1);
1008
1009
7.07k
    if ((from == NULL) || (from->intSubset == NULL))
1010
5.37k
  return(0);
1011
1012
1.69k
    target = doc->intSubset;
1013
1.69k
    if (target == NULL) {
1014
142
  cur = xmlDocGetRootElement(doc);
1015
142
  if (cur == NULL)
1016
0
      return(-1);
1017
142
        target = xmlCreateIntSubset(doc, cur->name, NULL, NULL);
1018
142
  if (target == NULL) {
1019
3
            xmlXIncludeErrMemory(ctxt);
1020
3
      return(-1);
1021
3
        }
1022
142
    }
1023
1024
1.68k
    source = from->intSubset;
1025
1.68k
    if ((source != NULL) && (source->entities != NULL)) {
1026
102
  xmlXIncludeMergeData data;
1027
1028
102
  data.ctxt = ctxt;
1029
102
  data.doc = doc;
1030
1031
102
  xmlHashScan((xmlHashTablePtr) source->entities,
1032
102
        xmlXIncludeMergeEntity, &data);
1033
102
    }
1034
1.68k
    source = from->extSubset;
1035
1.68k
    if ((source != NULL) && (source->entities != NULL)) {
1036
2
  xmlXIncludeMergeData data;
1037
1038
2
  data.ctxt = ctxt;
1039
2
  data.doc = doc;
1040
1041
  /*
1042
   * don't duplicate existing stuff when external subsets are the same
1043
   */
1044
2
  if ((!xmlStrEqual(target->ExternalID, source->ExternalID)) &&
1045
0
      (!xmlStrEqual(target->SystemID, source->SystemID))) {
1046
0
      xmlHashScan((xmlHashTablePtr) source->entities,
1047
0
      xmlXIncludeMergeEntity, &data);
1048
0
  }
1049
2
    }
1050
1.68k
    return(0);
1051
1.69k
}
1052
1053
/**
1054
 * Load the document, and store the result in the XInclude context
1055
 *
1056
 * @param ctxt  the XInclude context
1057
 * @param ref  an XMLXincludeRefPtr
1058
 * @returns 0 in case of success, -1 in case of failure
1059
 */
1060
static int
1061
17.6k
xmlXIncludeLoadDoc(xmlXIncludeCtxtPtr ctxt, xmlXIncludeRefPtr ref) {
1062
17.6k
    xmlXIncludeDocPtr cache;
1063
17.6k
    xmlDocPtr doc;
1064
17.6k
    const xmlChar *url = ref->URI;
1065
17.6k
    const xmlChar *fragment = ref->fragment;
1066
17.6k
    int i = 0;
1067
17.6k
    int ret = -1;
1068
17.6k
    int cacheNr;
1069
17.6k
#ifdef LIBXML_XPTR_ENABLED
1070
17.6k
    int saveFlags;
1071
17.6k
#endif
1072
1073
    /*
1074
     * Handling of references to the local document are done
1075
     * directly through ctxt->doc.
1076
     */
1077
17.6k
    if ((url[0] == 0) || (url[0] == '#') ||
1078
15.7k
  ((ctxt->doc != NULL) && (xmlStrEqual(url, ctxt->doc->URL)))) {
1079
4.61k
  doc = ctxt->doc;
1080
4.61k
        goto loaded;
1081
4.61k
    }
1082
1083
    /*
1084
     * Prevent reloading the document twice.
1085
     */
1086
16.7k
    for (i = 0; i < ctxt->urlNr; i++) {
1087
7.99k
  if (xmlStrEqual(url, ctxt->urlTab[i].url)) {
1088
4.26k
            if (ctxt->urlTab[i].expanding) {
1089
68
                xmlXIncludeErr(ctxt, ref->elem, XML_XINCLUDE_RECURSION,
1090
68
                               "inclusion loop detected\n", NULL);
1091
68
                goto error;
1092
68
            }
1093
4.19k
      doc = ctxt->urlTab[i].doc;
1094
4.19k
            if (doc == NULL)
1095
429
                goto error;
1096
3.76k
      goto loaded;
1097
4.19k
  }
1098
7.99k
    }
1099
1100
    /*
1101
     * Load it.
1102
     */
1103
8.77k
#ifdef LIBXML_XPTR_ENABLED
1104
    /*
1105
     * If this is an XPointer evaluation, we want to assure that
1106
     * all entities have been resolved prior to processing the
1107
     * referenced document
1108
     */
1109
8.77k
    saveFlags = ctxt->parseFlags;
1110
8.77k
    if (fragment != NULL) { /* if this is an XPointer eval */
1111
6.71k
  ctxt->parseFlags |= XML_PARSE_NOENT;
1112
6.71k
    }
1113
8.77k
#endif
1114
1115
8.77k
    doc = xmlXIncludeParseFile(ctxt, (const char *)url);
1116
8.77k
#ifdef LIBXML_XPTR_ENABLED
1117
8.77k
    ctxt->parseFlags = saveFlags;
1118
8.77k
#endif
1119
1120
    /* Also cache NULL docs */
1121
8.77k
    if (ctxt->urlNr >= ctxt->urlMax) {
1122
8.59k
        xmlXIncludeDoc *tmp;
1123
8.59k
        int newSize;
1124
1125
8.59k
        newSize = xmlGrowCapacity(ctxt->urlMax, sizeof(tmp[0]),
1126
8.59k
                                  8, XML_MAX_ITEMS);
1127
8.59k
        if (newSize < 0) {
1128
0
            xmlXIncludeErrMemory(ctxt);
1129
0
            xmlFreeDoc(doc);
1130
0
            goto error;
1131
0
        }
1132
8.59k
        tmp = xmlRealloc(ctxt->urlTab, newSize * sizeof(tmp[0]));
1133
8.59k
        if (tmp == NULL) {
1134
1
            xmlXIncludeErrMemory(ctxt);
1135
1
            xmlFreeDoc(doc);
1136
1
            goto error;
1137
1
        }
1138
8.59k
        ctxt->urlMax = newSize;
1139
8.59k
        ctxt->urlTab = tmp;
1140
8.59k
    }
1141
8.76k
    cache = &ctxt->urlTab[ctxt->urlNr];
1142
8.76k
    cache->doc = doc;
1143
8.76k
    cache->url = xmlStrdup(url);
1144
8.76k
    if (cache->url == NULL) {
1145
4
        xmlXIncludeErrMemory(ctxt);
1146
4
        xmlFreeDoc(doc);
1147
4
        goto error;
1148
4
    }
1149
8.76k
    cache->expanding = 0;
1150
8.76k
    cacheNr = ctxt->urlNr++;
1151
1152
8.76k
    if (doc == NULL)
1153
1.69k
        goto error;
1154
    /*
1155
     * It's possible that the requested URL has been mapped to a
1156
     * completely different location (e.g. through a catalog entry).
1157
     * To check for this, we compare the URL with that of the doc
1158
     * and change it if they disagree (bug 146988).
1159
     */
1160
7.07k
    if ((doc->URL != NULL) && (!xmlStrEqual(url, doc->URL)))
1161
0
        url = doc->URL;
1162
1163
    /*
1164
     * Make sure we have all entities fixed up
1165
     */
1166
7.07k
    xmlXIncludeMergeEntities(ctxt, ctxt->doc, doc);
1167
1168
    /*
1169
     * We don't need the DTD anymore, free up space
1170
    if (doc->intSubset != NULL) {
1171
  xmlUnlinkNode((xmlNodePtr) doc->intSubset);
1172
  xmlFreeNode((xmlNodePtr) doc->intSubset);
1173
  doc->intSubset = NULL;
1174
    }
1175
    if (doc->extSubset != NULL) {
1176
  xmlUnlinkNode((xmlNodePtr) doc->extSubset);
1177
  xmlFreeNode((xmlNodePtr) doc->extSubset);
1178
  doc->extSubset = NULL;
1179
    }
1180
     */
1181
7.07k
    cache->expanding = 1;
1182
7.07k
    xmlXIncludeRecurseDoc(ctxt, doc);
1183
    /* urlTab might be reallocated. */
1184
7.07k
    cache = &ctxt->urlTab[cacheNr];
1185
7.07k
    cache->expanding = 0;
1186
1187
15.4k
loaded:
1188
15.4k
    if (fragment == NULL) {
1189
4.83k
        xmlNodePtr root;
1190
1191
4.83k
        root = xmlDocGetRootElement(doc);
1192
4.83k
        if (root == NULL) {
1193
1
            xmlXIncludeErr(ctxt, ref->elem, XML_ERR_INTERNAL_ERROR,
1194
1
                           "document without root\n", NULL);
1195
1
            goto error;
1196
1
        }
1197
1198
4.83k
        ref->inc = xmlDocCopyNode(root, ctxt->doc, 1);
1199
4.83k
        if (ref->inc == NULL) {
1200
92
            xmlXIncludeErrMemory(ctxt);
1201
92
            goto error;
1202
92
        }
1203
1204
4.74k
        if (ref->base != NULL)
1205
3.92k
            xmlXIncludeBaseFixup(ctxt, root, ref->inc, ref->base);
1206
4.74k
    }
1207
10.6k
#ifdef LIBXML_XPTR_ENABLED
1208
10.6k
    else {
1209
  /*
1210
   * Computes the XPointer expression and make a copy used
1211
   * as the replacement copy.
1212
   */
1213
10.6k
  xmlXPathObjectPtr xptr;
1214
10.6k
  xmlNodeSetPtr set;
1215
1216
10.6k
        if (ctxt->isStream && doc == ctxt->doc) {
1217
101
      xmlXIncludeErr(ctxt, ref->elem, XML_XINCLUDE_XPTR_FAILED,
1218
101
         "XPointer expressions not allowed in streaming"
1219
101
                           " mode\n", NULL);
1220
101
            goto error;
1221
101
        }
1222
1223
10.5k
        if (ctxt->xpctxt == NULL) {
1224
6.42k
            ctxt->xpctxt = xmlXPathNewContext(doc);
1225
6.42k
            if (ctxt->xpctxt == NULL) {
1226
28
                xmlXIncludeErrMemory(ctxt);
1227
28
                goto error;
1228
28
            }
1229
6.39k
            if (ctxt->errorHandler != NULL)
1230
6.39k
                xmlXPathSetErrorHandler(ctxt->xpctxt, ctxt->errorHandler,
1231
6.39k
                                        ctxt->errorCtxt);
1232
6.39k
#ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
1233
6.39k
            ctxt->xpctxt->opLimit = 100000;
1234
6.39k
#endif
1235
6.39k
        } else {
1236
4.08k
            ctxt->xpctxt->doc = doc;
1237
4.08k
        }
1238
10.4k
  xptr = xmlXPtrEval(fragment, ctxt->xpctxt);
1239
10.4k
  if (ctxt->xpctxt->lastError.code != XML_ERR_OK) {
1240
6.99k
            if (ctxt->xpctxt->lastError.code == XML_ERR_NO_MEMORY)
1241
2.27k
                xmlXIncludeErrMemory(ctxt);
1242
4.71k
            else
1243
4.71k
                xmlXIncludeErr(ctxt, ref->elem, XML_XINCLUDE_XPTR_FAILED,
1244
4.71k
                               "XPointer evaluation failed: #%s\n",
1245
4.71k
                               fragment);
1246
6.99k
            goto error;
1247
6.99k
  }
1248
3.49k
        if (xptr == NULL)
1249
2.43k
            goto done;
1250
1.06k
  switch (xptr->type) {
1251
0
      case XPATH_UNDEFINED:
1252
0
      case XPATH_BOOLEAN:
1253
0
      case XPATH_NUMBER:
1254
0
      case XPATH_STRING:
1255
0
      case XPATH_USERS:
1256
0
      case XPATH_XSLT_TREE:
1257
0
    xmlXIncludeErr(ctxt, ref->elem, XML_XINCLUDE_XPTR_RESULT,
1258
0
             "XPointer is not a range: #%s\n",
1259
0
             fragment);
1260
0
                xmlXPathFreeObject(xptr);
1261
0
                goto error;
1262
1.06k
      case XPATH_NODESET:
1263
1.06k
                break;
1264
1265
1.06k
  }
1266
1.06k
  set = xptr->nodesetval;
1267
1.06k
  if (set != NULL) {
1268
495k
      for (i = 0;i < set->nodeNr;i++) {
1269
494k
    if (set->nodeTab[i] == NULL) /* shouldn't happen */
1270
0
        continue;
1271
494k
    switch (set->nodeTab[i]->type) {
1272
187k
        case XML_ELEMENT_NODE:
1273
374k
        case XML_TEXT_NODE:
1274
420k
        case XML_CDATA_SECTION_NODE:
1275
420k
        case XML_ENTITY_REF_NODE:
1276
420k
        case XML_ENTITY_NODE:
1277
491k
        case XML_PI_NODE:
1278
494k
        case XML_COMMENT_NODE:
1279
494k
        case XML_DOCUMENT_NODE:
1280
494k
        case XML_HTML_DOCUMENT_NODE:
1281
494k
      continue;
1282
1283
22
        case XML_ATTRIBUTE_NODE:
1284
22
      xmlXIncludeErr(ctxt, ref->elem,
1285
22
                     XML_XINCLUDE_XPTR_RESULT,
1286
22
               "XPointer selects an attribute: #%s\n",
1287
22
               fragment);
1288
22
      goto xptr_error;
1289
4
        case XML_NAMESPACE_DECL:
1290
4
      xmlXIncludeErr(ctxt, ref->elem,
1291
4
                     XML_XINCLUDE_XPTR_RESULT,
1292
4
               "XPointer selects a namespace: #%s\n",
1293
4
               fragment);
1294
4
      goto xptr_error;
1295
0
        case XML_DOCUMENT_TYPE_NODE:
1296
0
        case XML_DOCUMENT_FRAG_NODE:
1297
0
        case XML_NOTATION_NODE:
1298
0
        case XML_DTD_NODE:
1299
0
        case XML_ELEMENT_DECL:
1300
0
        case XML_ATTRIBUTE_DECL:
1301
0
        case XML_ENTITY_DECL:
1302
0
        case XML_XINCLUDE_START:
1303
0
        case XML_XINCLUDE_END:
1304
                        /* shouldn't happen */
1305
0
      xmlXIncludeErr(ctxt, ref->elem,
1306
0
                     XML_XINCLUDE_XPTR_RESULT,
1307
0
           "XPointer selects unexpected nodes: #%s\n",
1308
0
               fragment);
1309
0
      goto xptr_error;
1310
494k
    }
1311
494k
      }
1312
1.06k
  }
1313
1.03k
        ref->inc = xmlXIncludeCopyXPointer(ctxt, xptr, ref->base);
1314
1.06k
xptr_error:
1315
1.06k
        xmlXPathFreeObject(xptr);
1316
1.06k
    }
1317
1318
8.23k
done:
1319
8.23k
#endif
1320
1321
8.23k
    ret = 0;
1322
1323
17.6k
error:
1324
17.6k
    return(ret);
1325
8.23k
}
1326
1327
/**
1328
 * Load the content, and store the result in the XInclude context
1329
 *
1330
 * @param ctxt  the XInclude context
1331
 * @param ref  an XMLXincludeRefPtr
1332
 * @returns 0 in case of success, -1 in case of failure
1333
 */
1334
static int
1335
181
xmlXIncludeLoadTxt(xmlXIncludeCtxtPtr ctxt, xmlXIncludeRefPtr ref) {
1336
181
    xmlParserInputBufferPtr buf;
1337
181
    xmlNodePtr node = NULL;
1338
181
    const xmlChar *url = ref->URI;
1339
181
    int i;
1340
181
    int ret = -1;
1341
181
    xmlChar *encoding = NULL;
1342
181
    xmlCharEncodingHandlerPtr handler = NULL;
1343
181
    xmlParserCtxtPtr pctxt = NULL;
1344
181
    xmlParserInputPtr inputStream = NULL;
1345
181
    int len;
1346
181
    int res;
1347
181
    const xmlChar *content;
1348
1349
    /*
1350
     * Handling of references to the local document are done
1351
     * directly through ctxt->doc.
1352
     */
1353
181
    if (url[0] == 0) {
1354
3
  xmlXIncludeErr(ctxt, ref->elem, XML_XINCLUDE_TEXT_DOCUMENT,
1355
3
           "text serialization of document not available\n", NULL);
1356
3
  goto error;
1357
3
    }
1358
1359
    /*
1360
     * Prevent reloading the document twice.
1361
     */
1362
180
    for (i = 0; i < ctxt->txtNr; i++) {
1363
23
  if (xmlStrEqual(url, ctxt->txtTab[i].url)) {
1364
21
            node = xmlNewDocText(ctxt->doc, ctxt->txtTab[i].text);
1365
21
            if (node == NULL)
1366
1
                xmlXIncludeErrMemory(ctxt);
1367
21
      goto loaded;
1368
21
  }
1369
23
    }
1370
1371
    /*
1372
     * Try to get the encoding if available
1373
     */
1374
157
    if (ref->elem != NULL) {
1375
157
  encoding = xmlXIncludeGetProp(ctxt, ref->elem, XINCLUDE_PARSE_ENCODING);
1376
157
    }
1377
157
    if (encoding != NULL) {
1378
22
        xmlParserErrors code;
1379
1380
22
        code = xmlOpenCharEncodingHandler((const char *) encoding,
1381
22
                                          /* output */ 0, &handler);
1382
1383
22
        if (code != XML_ERR_OK) {
1384
13
            if (code == XML_ERR_NO_MEMORY) {
1385
3
                xmlXIncludeErrMemory(ctxt);
1386
10
            } else if (code == XML_ERR_UNSUPPORTED_ENCODING) {
1387
10
                xmlXIncludeErr(ctxt, ref->elem, XML_XINCLUDE_UNKNOWN_ENCODING,
1388
10
                               "encoding %s not supported\n", encoding);
1389
10
                goto error;
1390
10
            } else {
1391
0
                xmlXIncludeErr(ctxt, ref->elem, code,
1392
0
                               "unexpected error from iconv or ICU\n", NULL);
1393
0
                goto error;
1394
0
            }
1395
13
        }
1396
22
    }
1397
1398
    /*
1399
     * Load it.
1400
     */
1401
147
    pctxt = xmlNewParserCtxt();
1402
147
    if (pctxt == NULL) {
1403
4
        xmlXIncludeErrMemory(ctxt);
1404
4
        goto error;
1405
4
    }
1406
143
    if (ctxt->errorHandler != NULL)
1407
143
        xmlCtxtSetErrorHandler(pctxt, ctxt->errorHandler, ctxt->errorCtxt);
1408
143
    if (ctxt->resourceLoader != NULL)
1409
143
        xmlCtxtSetResourceLoader(pctxt, ctxt->resourceLoader,
1410
143
                                 ctxt->resourceCtxt);
1411
1412
143
    xmlCtxtUseOptions(pctxt, ctxt->parseFlags);
1413
1414
143
    inputStream = xmlLoadResource(pctxt, (const char*) url, NULL,
1415
143
                                  XML_RESOURCE_XINCLUDE_TEXT);
1416
143
    if (inputStream == NULL) {
1417
        /*
1418
         * ENOENT only produces a warning which isn't reflected in errNo.
1419
         */
1420
51
        if (pctxt->errNo == XML_ERR_NO_MEMORY)
1421
1
            xmlXIncludeErrMemory(ctxt);
1422
50
        else if ((pctxt->errNo != XML_ERR_OK) &&
1423
23
                 (pctxt->errNo != XML_IO_ENOENT) &&
1424
1
                 (pctxt->errNo != XML_IO_UNKNOWN) &&
1425
1
                 (pctxt->errNo != XML_IO_NETWORK_ATTEMPT))
1426
1
            xmlXIncludeErr(ctxt, NULL, pctxt->errNo, "load error", NULL);
1427
51
  goto error;
1428
51
    }
1429
92
    buf = inputStream->buf;
1430
92
    if (buf == NULL)
1431
0
  goto error;
1432
92
    if (buf->encoder)
1433
0
  xmlCharEncCloseFunc(buf->encoder);
1434
92
    buf->encoder = handler;
1435
92
    handler = NULL;
1436
1437
92
    node = xmlNewDocText(ctxt->doc, NULL);
1438
92
    if (node == NULL) {
1439
1
        xmlXIncludeErrMemory(ctxt);
1440
1
  goto error;
1441
1
    }
1442
1443
    /*
1444
     * Scan all chars from the resource and add the to the node
1445
     */
1446
91
    do {
1447
91
        res = xmlParserInputBufferRead(buf, 4096);
1448
91
    } while (res > 0);
1449
91
    if (res < 0) {
1450
0
        if (buf->error == XML_ERR_NO_MEMORY)
1451
0
            xmlXIncludeErrMemory(ctxt);
1452
0
        else
1453
0
            xmlXIncludeErr(ctxt, NULL, buf->error, "read error", NULL);
1454
0
        goto error;
1455
0
    }
1456
1457
91
    content = xmlBufContent(buf->buffer);
1458
91
    len = xmlBufUse(buf->buffer);
1459
81.4k
    for (i = 0; i < len;) {
1460
81.4k
        int cur;
1461
81.4k
        int l;
1462
1463
81.4k
        l = len - i;
1464
81.4k
        cur = xmlGetUTF8Char(&content[i], &l);
1465
81.4k
        if ((cur < 0) || (!IS_CHAR(cur))) {
1466
37
            xmlXIncludeErr(ctxt, ref->elem, XML_XINCLUDE_INVALID_CHAR,
1467
37
                           "%s contains invalid char\n", url);
1468
37
            goto error;
1469
37
        }
1470
1471
81.4k
        i += l;
1472
81.4k
    }
1473
1474
54
    if (xmlNodeAddContentLen(node, content, len) < 0)
1475
1
        xmlXIncludeErrMemory(ctxt);
1476
1477
54
    if (ctxt->txtNr >= ctxt->txtMax) {
1478
54
        xmlXIncludeTxt *tmp;
1479
54
        int newSize;
1480
1481
54
        newSize = xmlGrowCapacity(ctxt->txtMax, sizeof(tmp[0]),
1482
54
                                  8, XML_MAX_ITEMS);
1483
54
        if (newSize < 0) {
1484
0
            xmlXIncludeErrMemory(ctxt);
1485
0
      goto error;
1486
0
        }
1487
54
        tmp = xmlRealloc(ctxt->txtTab, newSize * sizeof(tmp[0]));
1488
54
        if (tmp == NULL) {
1489
1
            xmlXIncludeErrMemory(ctxt);
1490
1
      goto error;
1491
1
        }
1492
53
        ctxt->txtMax = newSize;
1493
53
        ctxt->txtTab = tmp;
1494
53
    }
1495
53
    ctxt->txtTab[ctxt->txtNr].text = xmlStrdup(node->content);
1496
53
    if ((node->content != NULL) &&
1497
35
        (ctxt->txtTab[ctxt->txtNr].text == NULL)) {
1498
1
        xmlXIncludeErrMemory(ctxt);
1499
1
        goto error;
1500
1
    }
1501
52
    ctxt->txtTab[ctxt->txtNr].url = xmlStrdup(url);
1502
52
    if (ctxt->txtTab[ctxt->txtNr].url == NULL) {
1503
1
        xmlXIncludeErrMemory(ctxt);
1504
1
        xmlFree(ctxt->txtTab[ctxt->txtNr].text);
1505
1
        goto error;
1506
1
    }
1507
51
    ctxt->txtNr++;
1508
1509
72
loaded:
1510
    /*
1511
     * Add the element as the replacement copy.
1512
     */
1513
72
    ref->inc = node;
1514
72
    node = NULL;
1515
72
    ret = 0;
1516
1517
181
error:
1518
181
    xmlFreeNode(node);
1519
181
    xmlFreeInputStream(inputStream);
1520
181
    xmlFreeParserCtxt(pctxt);
1521
181
    xmlCharEncCloseFunc(handler);
1522
181
    xmlFree(encoding);
1523
181
    return(ret);
1524
72
}
1525
1526
/**
1527
 * Load the content of the fallback node, and store the result
1528
 * in the XInclude context
1529
 *
1530
 * @param ctxt  the XInclude context
1531
 * @param fallback  the fallback node
1532
 * @param ref  an XMLXincludeRefPtr
1533
 * @returns 0 in case of success, -1 in case of failure
1534
 */
1535
static int
1536
xmlXIncludeLoadFallback(xmlXIncludeCtxtPtr ctxt, xmlNodePtr fallback,
1537
531
                        xmlXIncludeRefPtr ref) {
1538
531
    int ret = 0;
1539
531
    int oldNbErrors;
1540
1541
531
    if ((fallback == NULL) || (fallback->type == XML_NAMESPACE_DECL) ||
1542
531
        (ctxt == NULL))
1543
0
  return(-1);
1544
531
    if (fallback->children != NULL) {
1545
  /*
1546
   * It's possible that the fallback also has 'includes'
1547
   * (Bug 129969), so we re-process the fallback just in case
1548
   */
1549
496
        oldNbErrors = ctxt->nbErrors;
1550
496
  ref->inc = xmlXIncludeCopyNode(ctxt, fallback, 1, ref->base);
1551
496
  if (ctxt->nbErrors > oldNbErrors)
1552
143
      ret = -1;
1553
496
    } else {
1554
35
        ref->inc = NULL;
1555
35
    }
1556
531
    ref->fallback = 1;
1557
531
    return(ret);
1558
531
}
1559
1560
/************************************************************************
1561
 *                  *
1562
 *      XInclude Processing       *
1563
 *                  *
1564
 ************************************************************************/
1565
1566
/**
1567
 * If the XInclude node wasn't processed yet, create a new RefPtr,
1568
 * add it to ctxt->incTab and load the included items.
1569
 *
1570
 * @param ctxt  an XInclude context
1571
 * @param node  an XInclude node
1572
 * @returns the new or existing xmlXIncludeRef, or NULL in case of error.
1573
 */
1574
static xmlXIncludeRefPtr
1575
21.9k
xmlXIncludeExpandNode(xmlXIncludeCtxtPtr ctxt, xmlNodePtr node) {
1576
21.9k
    xmlXIncludeRefPtr ref;
1577
21.9k
    int i;
1578
1579
21.9k
    if (ctxt->fatalErr)
1580
644
        return(NULL);
1581
21.2k
    if (ctxt->depth >= XINCLUDE_MAX_DEPTH) {
1582
0
        xmlXIncludeErr(ctxt, node, XML_XINCLUDE_RECURSION,
1583
0
                       "maximum recursion depth exceeded\n", NULL);
1584
0
        ctxt->fatalErr = 1;
1585
0
        return(NULL);
1586
0
    }
1587
1588
21.2k
#ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
1589
    /*
1590
     * The XInclude engine offers no protection against exponential
1591
     * expansion attacks similar to "billion laughs". Avoid timeouts by
1592
     * limiting the total number of replacements when fuzzing.
1593
     *
1594
     * Unfortuately, a single XInclude can already result in quadratic
1595
     * behavior:
1596
     *
1597
     *     <doc xmlns:xi="http://www.w3.org/2001/XInclude">
1598
     *       <xi:include xpointer="xpointer(//e)"/>
1599
     *       <e>
1600
     *         <e>
1601
     *           <e>
1602
     *             <!-- more nested elements -->
1603
     *           </e>
1604
     *         </e>
1605
     *       </e>
1606
     *     </doc>
1607
     */
1608
21.2k
    if (ctxt->incTotal >= 20)
1609
1.94k
        return(NULL);
1610
19.3k
    ctxt->incTotal++;
1611
19.3k
#endif
1612
1613
29.6k
    for (i = 0; i < ctxt->incNr; i++) {
1614
10.4k
        if (ctxt->incTab[i]->elem == node) {
1615
184
            if (ctxt->incTab[i]->expanding) {
1616
120
                xmlXIncludeErr(ctxt, node, XML_XINCLUDE_RECURSION,
1617
120
                               "inclusion loop detected\n", NULL);
1618
120
                return(NULL);
1619
120
            }
1620
64
            return(ctxt->incTab[i]);
1621
184
        }
1622
10.4k
    }
1623
1624
19.1k
    ref = xmlXIncludeAddNode(ctxt, node);
1625
19.1k
    if (ref == NULL)
1626
1.34k
        return(NULL);
1627
17.8k
    ref->expanding = 1;
1628
17.8k
    ctxt->depth++;
1629
17.8k
    xmlXIncludeLoadNode(ctxt, ref);
1630
17.8k
    ctxt->depth--;
1631
17.8k
    ref->expanding = 0;
1632
1633
17.8k
    return(ref);
1634
19.1k
}
1635
1636
/**
1637
 * Find and load the infoset replacement for the given node.
1638
 *
1639
 * @param ctxt  an XInclude context
1640
 * @param ref  an xmlXIncludeRef
1641
 * @returns 0 if substitution succeeded, -1 if some processing failed
1642
 */
1643
static int
1644
17.8k
xmlXIncludeLoadNode(xmlXIncludeCtxtPtr ctxt, xmlXIncludeRefPtr ref) {
1645
17.8k
    xmlNodePtr cur;
1646
17.8k
    int ret;
1647
1648
17.8k
    if ((ctxt == NULL) || (ref == NULL))
1649
0
  return(-1);
1650
17.8k
    cur = ref->elem;
1651
17.8k
    if (cur == NULL)
1652
0
  return(-1);
1653
1654
17.8k
    if (ref->xml) {
1655
17.6k
  ret = xmlXIncludeLoadDoc(ctxt, ref);
1656
  /* xmlXIncludeGetFragment(ctxt, cur, URI); */
1657
17.6k
    } else {
1658
181
  ret = xmlXIncludeLoadTxt(ctxt, ref);
1659
181
    }
1660
1661
17.8k
    if (ret < 0) {
1662
9.52k
  xmlNodePtr children;
1663
1664
  /*
1665
   * Time to try a fallback if available
1666
   */
1667
9.52k
  children = cur->children;
1668
12.2k
  while (children != NULL) {
1669
3.24k
      if ((children->type == XML_ELEMENT_NODE) &&
1670
1.35k
    (children->ns != NULL) &&
1671
777
    (xmlStrEqual(children->name, XINCLUDE_FALLBACK)) &&
1672
531
    ((xmlStrEqual(children->ns->href, XINCLUDE_NS)) ||
1673
531
     (xmlStrEqual(children->ns->href, XINCLUDE_OLD_NS)))) {
1674
531
    ret = xmlXIncludeLoadFallback(ctxt, children, ref);
1675
531
    break;
1676
531
      }
1677
2.71k
      children = children->next;
1678
2.71k
  }
1679
9.52k
    }
1680
17.8k
    if (ret < 0) {
1681
9.13k
  xmlXIncludeErr(ctxt, cur, XML_XINCLUDE_NO_FALLBACK,
1682
9.13k
           "could not load %s, and no fallback was found\n",
1683
9.13k
           ref->URI);
1684
9.13k
    }
1685
1686
17.8k
    return(0);
1687
17.8k
}
1688
1689
/**
1690
 * Implement the infoset replacement for the given node
1691
 *
1692
 * @param ctxt  an XInclude context
1693
 * @param ref  an xmlXIncludeRef
1694
 * @returns 0 if substitution succeeded, -1 if some processing failed
1695
 */
1696
static int
1697
17.4k
xmlXIncludeIncludeNode(xmlXIncludeCtxtPtr ctxt, xmlXIncludeRefPtr ref) {
1698
17.4k
    xmlNodePtr cur, end, list, tmp;
1699
1700
17.4k
    if ((ctxt == NULL) || (ref == NULL))
1701
0
  return(-1);
1702
17.4k
    cur = ref->elem;
1703
17.4k
    if ((cur == NULL) || (cur->type == XML_NAMESPACE_DECL))
1704
0
  return(-1);
1705
1706
17.4k
    list = ref->inc;
1707
17.4k
    ref->inc = NULL;
1708
1709
    /*
1710
     * Check against the risk of generating a multi-rooted document
1711
     */
1712
17.4k
    if ((cur->parent != NULL) &&
1713
17.4k
  (cur->parent->type != XML_ELEMENT_NODE)) {
1714
8.46k
  int nb_elem = 0;
1715
1716
8.46k
  tmp = list;
1717
12.4k
  while (tmp != NULL) {
1718
4.02k
      if (tmp->type == XML_ELEMENT_NODE)
1719
3.41k
    nb_elem++;
1720
4.02k
      tmp = tmp->next;
1721
4.02k
  }
1722
8.46k
        if (nb_elem != 1) {
1723
5.44k
            if (nb_elem > 1)
1724
58
                xmlXIncludeErr(ctxt, ref->elem, XML_XINCLUDE_MULTIPLE_ROOT,
1725
58
                               "XInclude error: would result in multiple root "
1726
58
                               "nodes\n", NULL);
1727
5.39k
            else
1728
5.39k
                xmlXIncludeErr(ctxt, ref->elem, XML_XINCLUDE_MULTIPLE_ROOT,
1729
5.39k
                               "XInclude error: would result in no root "
1730
5.39k
                               "node\n", NULL);
1731
5.44k
            xmlFreeNodeList(list);
1732
5.44k
      return(-1);
1733
5.44k
  }
1734
8.46k
    }
1735
1736
12.0k
    if (ctxt->parseFlags & XML_PARSE_NOXINCNODE) {
1737
  /*
1738
   * Add the list of nodes
1739
         *
1740
         * TODO: Coalesce text nodes unless we are streaming mode.
1741
   */
1742
0
  while (list != NULL) {
1743
0
      end = list;
1744
0
      list = list->next;
1745
1746
0
      if (xmlAddPrevSibling(cur, end) == NULL) {
1747
0
                xmlUnlinkNode(end);
1748
0
                xmlFreeNode(end);
1749
0
                goto err_memory;
1750
0
            }
1751
0
  }
1752
0
  xmlUnlinkNode(cur);
1753
0
  xmlFreeNode(cur);
1754
12.0k
    } else {
1755
12.0k
        xmlNodePtr child, next;
1756
1757
  /*
1758
   * Change the current node as an XInclude start one, and add an
1759
   * XInclude end one
1760
   */
1761
12.0k
        if (ref->fallback)
1762
174
            xmlUnsetProp(cur, BAD_CAST "href");
1763
12.0k
  cur->type = XML_XINCLUDE_START;
1764
        /* Remove fallback children */
1765
19.6k
        for (child = cur->children; child != NULL; child = next) {
1766
7.60k
            next = child->next;
1767
7.60k
            xmlUnlinkNode(child);
1768
7.60k
            xmlFreeNode(child);
1769
7.60k
        }
1770
12.0k
  end = xmlNewDocNode(cur->doc, cur->ns, cur->name, NULL);
1771
12.0k
  if (end == NULL)
1772
26
            goto err_memory;
1773
11.9k
  end->type = XML_XINCLUDE_END;
1774
11.9k
  if (xmlAddNextSibling(cur, end) == NULL) {
1775
0
            xmlFreeNode(end);
1776
0
            goto err_memory;
1777
0
        }
1778
1779
  /*
1780
   * Add the list of nodes
1781
   */
1782
176k
  while (list != NULL) {
1783
164k
      cur = list;
1784
164k
      list = list->next;
1785
1786
164k
      if (xmlAddPrevSibling(end, cur) == NULL) {
1787
0
                xmlUnlinkNode(cur);
1788
0
                xmlFreeNode(cur);
1789
0
                goto err_memory;
1790
0
            }
1791
164k
  }
1792
11.9k
    }
1793
1794
1795
11.9k
    return(0);
1796
1797
26
err_memory:
1798
26
    xmlXIncludeErrMemory(ctxt);
1799
26
    xmlFreeNodeList(list);
1800
26
    return(-1);
1801
12.0k
}
1802
1803
/**
1804
 * test if the node is an XInclude node
1805
 *
1806
 * @param ctxt  the XInclude processing context
1807
 * @param node  an XInclude node
1808
 * @returns 1 true, 0 otherwise
1809
 */
1810
static int
1811
848k
xmlXIncludeTestNode(xmlXIncludeCtxtPtr ctxt, xmlNodePtr node) {
1812
848k
    if (node == NULL)
1813
0
  return(0);
1814
848k
    if (node->type != XML_ELEMENT_NODE)
1815
535k
  return(0);
1816
313k
    if (node->ns == NULL)
1817
224k
  return(0);
1818
88.4k
    if ((xmlStrEqual(node->ns->href, XINCLUDE_NS)) ||
1819
79.0k
        (xmlStrEqual(node->ns->href, XINCLUDE_OLD_NS))) {
1820
25.8k
  if (xmlStrEqual(node->ns->href, XINCLUDE_OLD_NS)) {
1821
16.4k
      if (ctxt->legacy == 0) {
1822
5.01k
          ctxt->legacy = 1;
1823
5.01k
      }
1824
16.4k
  }
1825
25.8k
  if (xmlStrEqual(node->name, XINCLUDE_NODE)) {
1826
22.6k
      xmlNodePtr child = node->children;
1827
22.6k
      int nb_fallback = 0;
1828
1829
37.9k
      while (child != NULL) {
1830
16.3k
    if ((child->type == XML_ELEMENT_NODE) &&
1831
7.11k
        (child->ns != NULL) &&
1832
5.55k
        ((xmlStrEqual(child->ns->href, XINCLUDE_NS)) ||
1833
5.40k
         (xmlStrEqual(child->ns->href, XINCLUDE_OLD_NS)))) {
1834
5.40k
        if (xmlStrEqual(child->name, XINCLUDE_NODE)) {
1835
1.03k
      xmlXIncludeErr(ctxt, node,
1836
1.03k
                     XML_XINCLUDE_INCLUDE_IN_INCLUDE,
1837
1.03k
               "%s has an 'include' child\n",
1838
1.03k
               XINCLUDE_NODE);
1839
1.03k
      return(0);
1840
1.03k
        }
1841
4.37k
        if (xmlStrEqual(child->name, XINCLUDE_FALLBACK)) {
1842
841
      nb_fallback++;
1843
841
        }
1844
4.37k
    }
1845
15.3k
    child = child->next;
1846
15.3k
      }
1847
21.5k
      if (nb_fallback > 1) {
1848
239
    xmlXIncludeErr(ctxt, node, XML_XINCLUDE_FALLBACKS_IN_INCLUDE,
1849
239
             "%s has multiple fallback children\n",
1850
239
                   XINCLUDE_NODE);
1851
239
    return(0);
1852
239
      }
1853
21.3k
      return(1);
1854
21.5k
  }
1855
3.24k
  if (xmlStrEqual(node->name, XINCLUDE_FALLBACK)) {
1856
1.28k
      if ((node->parent == NULL) ||
1857
1.28k
    (node->parent->type != XML_ELEMENT_NODE) ||
1858
1.28k
    (node->parent->ns == NULL) ||
1859
1.11k
    ((!xmlStrEqual(node->parent->ns->href, XINCLUDE_NS)) &&
1860
705
     (!xmlStrEqual(node->parent->ns->href, XINCLUDE_OLD_NS))) ||
1861
1.04k
    (!xmlStrEqual(node->parent->name, XINCLUDE_NODE))) {
1862
616
    xmlXIncludeErr(ctxt, node,
1863
616
                   XML_XINCLUDE_FALLBACK_NOT_IN_INCLUDE,
1864
616
             "%s is not the child of an 'include'\n",
1865
616
             XINCLUDE_FALLBACK);
1866
616
      }
1867
1.28k
  }
1868
3.24k
    }
1869
65.8k
    return(0);
1870
88.4k
}
1871
1872
/**
1873
 * Implement the XInclude substitution on the XML document `doc`
1874
 *
1875
 * @param ctxt  the XInclude processing context
1876
 * @param tree  the top of the tree to process
1877
 * @returns 0 if no substitution were done, -1 if some processing failed
1878
 *    or the number of substitutions done.
1879
 */
1880
static int
1881
21.5k
xmlXIncludeDoProcess(xmlXIncludeCtxtPtr ctxt, xmlNodePtr tree) {
1882
21.5k
    xmlXIncludeRefPtr ref;
1883
21.5k
    xmlNodePtr cur;
1884
21.5k
    int ret = 0;
1885
21.5k
    int i, start;
1886
1887
    /*
1888
     * First phase: lookup the elements in the document
1889
     */
1890
21.5k
    start = ctxt->incNr;
1891
21.5k
    cur = tree;
1892
848k
    do {
1893
  /* TODO: need to work on entities -> stack */
1894
848k
        if (xmlXIncludeTestNode(ctxt, cur) == 1) {
1895
21.3k
            ref = xmlXIncludeExpandNode(ctxt, cur);
1896
            /*
1897
             * Mark direct includes.
1898
             */
1899
21.3k
            if (ref != NULL)
1900
17.4k
                ref->replace = 1;
1901
827k
        } else if ((cur->children != NULL) &&
1902
161k
                   ((cur->type == XML_DOCUMENT_NODE) ||
1903
161k
                    (cur->type == XML_ELEMENT_NODE))) {
1904
161k
            cur = cur->children;
1905
161k
            continue;
1906
161k
        }
1907
848k
        do {
1908
848k
            if (cur == tree)
1909
21.5k
                break;
1910
827k
            if (cur->next != NULL) {
1911
665k
                cur = cur->next;
1912
665k
                break;
1913
665k
            }
1914
161k
            cur = cur->parent;
1915
161k
        } while (cur != NULL);
1916
848k
    } while ((cur != NULL) && (cur != tree));
1917
1918
    /*
1919
     * Second phase: extend the original document infoset.
1920
     */
1921
39.3k
    for (i = start; i < ctxt->incNr; i++) {
1922
17.8k
  if (ctxt->incTab[i]->replace != 0) {
1923
17.4k
            xmlXIncludeIncludeNode(ctxt, ctxt->incTab[i]);
1924
17.4k
            ctxt->incTab[i]->replace = 0;
1925
17.4k
        } else {
1926
            /*
1927
             * Ignore includes which were added indirectly, for example
1928
             * inside xi:fallback elements.
1929
             */
1930
371
            if (ctxt->incTab[i]->inc != NULL) {
1931
264
                xmlFreeNodeList(ctxt->incTab[i]->inc);
1932
264
                ctxt->incTab[i]->inc = NULL;
1933
264
            }
1934
371
        }
1935
17.8k
  ret++;
1936
17.8k
    }
1937
1938
21.5k
    if (ctxt->isStream) {
1939
        /*
1940
         * incTab references nodes which will eventually be deleted in
1941
         * streaming mode. The table is only required for XPointer
1942
         * expressions which aren't allowed in streaming mode.
1943
         */
1944
27.8k
        for (i = 0;i < ctxt->incNr;i++) {
1945
13.3k
            xmlXIncludeFreeRef(ctxt->incTab[i]);
1946
13.3k
        }
1947
14.4k
        ctxt->incNr = 0;
1948
14.4k
    }
1949
1950
21.5k
    return(ret);
1951
21.5k
}
1952
1953
/**
1954
 * Implement the XInclude substitution on the XML document `doc`
1955
 *
1956
 * @param ctxt  the XInclude processing context
1957
 * @param tree  the top of the tree to process
1958
 * @returns 0 if no substitution were done, -1 if some processing failed
1959
 *    or the number of substitutions done.
1960
 */
1961
static int
1962
14.4k
xmlXIncludeDoProcessRoot(xmlXIncludeCtxtPtr ctxt, xmlNodePtr tree) {
1963
14.4k
    if ((tree == NULL) || (tree->type == XML_NAMESPACE_DECL))
1964
0
  return(-1);
1965
14.4k
    if (ctxt == NULL)
1966
0
  return(-1);
1967
1968
14.4k
    return(xmlXIncludeDoProcess(ctxt, tree));
1969
14.4k
}
1970
1971
/**
1972
 * @since 2.13.0
1973
 *
1974
 * @param ctxt  an XInclude processing context
1975
 * @returns the last error code.
1976
 */
1977
int
1978
12.2k
xmlXIncludeGetLastError(xmlXIncludeCtxt *ctxt) {
1979
12.2k
    if (ctxt == NULL)
1980
0
        return(XML_ERR_ARGUMENT);
1981
12.2k
    return(ctxt->errNo);
1982
12.2k
}
1983
1984
/**
1985
 * Register a callback function that will be called on errors and
1986
 * warnings. If handler is NULL, the error handler will be deactivated.
1987
 *
1988
 * @since 2.13.0
1989
 * @param ctxt  an XInclude processing context
1990
 * @param handler  error handler
1991
 * @param data  user data which will be passed to the handler
1992
 */
1993
void
1994
xmlXIncludeSetErrorHandler(xmlXIncludeCtxt *ctxt,
1995
8.06k
                           xmlStructuredErrorFunc handler, void *data) {
1996
8.06k
    if (ctxt == NULL)
1997
0
        return;
1998
8.06k
    ctxt->errorHandler = handler;
1999
8.06k
    ctxt->errorCtxt = data;
2000
8.06k
}
2001
2002
/**
2003
 * Register a callback function that will be called to load included
2004
 * documents.
2005
 *
2006
 * @since 2.14.0
2007
 * @param ctxt  an XInclude processing context
2008
 * @param loader  resource loader
2009
 * @param data  user data which will be passed to the loader
2010
 */
2011
void
2012
xmlXIncludeSetResourceLoader(xmlXIncludeCtxt *ctxt,
2013
8.06k
                             xmlResourceLoader loader, void *data) {
2014
8.06k
    if (ctxt == NULL)
2015
0
        return;
2016
8.06k
    ctxt->resourceLoader = loader;
2017
8.06k
    ctxt->resourceCtxt = data;
2018
8.06k
}
2019
2020
/**
2021
 * Set the flags used for further processing of XML resources.
2022
 *
2023
 * @param ctxt  an XInclude processing context
2024
 * @param flags  a set of xmlParserOption used for parsing XML includes
2025
 * @returns 0 in case of success and -1 in case of error.
2026
 */
2027
int
2028
8.06k
xmlXIncludeSetFlags(xmlXIncludeCtxt *ctxt, int flags) {
2029
8.06k
    if (ctxt == NULL)
2030
0
        return(-1);
2031
8.06k
    ctxt->parseFlags = flags;
2032
8.06k
    return(0);
2033
8.06k
}
2034
2035
/**
2036
 * In streaming mode, XPointer expressions aren't allowed.
2037
 *
2038
 * @param ctxt  an XInclude processing context
2039
 * @param mode  whether streaming mode should be enabled
2040
 * @returns 0 in case of success and -1 in case of error.
2041
 */
2042
int
2043
8.06k
xmlXIncludeSetStreamingMode(xmlXIncludeCtxt *ctxt, int mode) {
2044
8.06k
    if (ctxt == NULL)
2045
0
        return(-1);
2046
8.06k
    ctxt->isStream = !!mode;
2047
8.06k
    return(0);
2048
8.06k
}
2049
2050
/**
2051
 * Implement the XInclude substitution on the XML node `tree`
2052
 *
2053
 * @param tree  an XML node
2054
 * @param flags  a set of xmlParserOption used for parsing XML includes
2055
 * @param data  application data that will be passed to the parser context
2056
 *        in the _private field of the parser context(s)
2057
 * @returns 0 if no substitution were done, -1 if some processing failed
2058
 *    or the number of substitutions done.
2059
 */
2060
2061
int
2062
0
xmlXIncludeProcessTreeFlagsData(xmlNode *tree, int flags, void *data) {
2063
0
    xmlXIncludeCtxtPtr ctxt;
2064
0
    int ret = 0;
2065
2066
0
    if ((tree == NULL) || (tree->type == XML_NAMESPACE_DECL) ||
2067
0
        (tree->doc == NULL))
2068
0
        return(-1);
2069
2070
0
    ctxt = xmlXIncludeNewContext(tree->doc);
2071
0
    if (ctxt == NULL)
2072
0
        return(-1);
2073
0
    ctxt->_private = data;
2074
0
    xmlXIncludeSetFlags(ctxt, flags);
2075
0
    ret = xmlXIncludeDoProcessRoot(ctxt, tree);
2076
0
    if ((ret >= 0) && (ctxt->nbErrors > 0))
2077
0
        ret = -1;
2078
2079
0
    xmlXIncludeFreeContext(ctxt);
2080
0
    return(ret);
2081
0
}
2082
2083
/**
2084
 * Implement the XInclude substitution on the XML document `doc`
2085
 *
2086
 * @param doc  an XML document
2087
 * @param flags  a set of xmlParserOption used for parsing XML includes
2088
 * @param data  application data that will be passed to the parser context
2089
 *        in the _private field of the parser context(s)
2090
 * @returns 0 if no substitution were done, -1 if some processing failed
2091
 *    or the number of substitutions done.
2092
 */
2093
int
2094
0
xmlXIncludeProcessFlagsData(xmlDoc *doc, int flags, void *data) {
2095
0
    xmlNodePtr tree;
2096
2097
0
    if (doc == NULL)
2098
0
  return(-1);
2099
0
    tree = xmlDocGetRootElement(doc);
2100
0
    if (tree == NULL)
2101
0
  return(-1);
2102
0
    return(xmlXIncludeProcessTreeFlagsData(tree, flags, data));
2103
0
}
2104
2105
/**
2106
 * Implement the XInclude substitution on the XML document `doc`
2107
 *
2108
 * @param doc  an XML document
2109
 * @param flags  a set of xmlParserOption used for parsing XML includes
2110
 * @returns 0 if no substitution were done, -1 if some processing failed
2111
 *    or the number of substitutions done.
2112
 */
2113
int
2114
0
xmlXIncludeProcessFlags(xmlDoc *doc, int flags) {
2115
0
    return xmlXIncludeProcessFlagsData(doc, flags, NULL);
2116
0
}
2117
2118
/**
2119
 * Implement the XInclude substitution on the XML document `doc`
2120
 *
2121
 * @param doc  an XML document
2122
 * @returns 0 if no substitution were done, -1 if some processing failed
2123
 *    or the number of substitutions done.
2124
 */
2125
int
2126
0
xmlXIncludeProcess(xmlDoc *doc) {
2127
0
    return(xmlXIncludeProcessFlags(doc, doc ? doc->parseFlags : 0));
2128
0
}
2129
2130
/**
2131
 * Implement the XInclude substitution for the given subtree
2132
 *
2133
 * @param tree  a node in an XML document
2134
 * @param flags  a set of xmlParserOption used for parsing XML includes
2135
 * @returns 0 if no substitution were done, -1 if some processing failed
2136
 *    or the number of substitutions done.
2137
 */
2138
int
2139
0
xmlXIncludeProcessTreeFlags(xmlNode *tree, int flags) {
2140
0
    xmlXIncludeCtxtPtr ctxt;
2141
0
    int ret = 0;
2142
2143
0
    if ((tree == NULL) || (tree->type == XML_NAMESPACE_DECL) ||
2144
0
        (tree->doc == NULL))
2145
0
  return(-1);
2146
0
    ctxt = xmlXIncludeNewContext(tree->doc);
2147
0
    if (ctxt == NULL)
2148
0
  return(-1);
2149
0
    xmlXIncludeSetFlags(ctxt, flags);
2150
0
    ret = xmlXIncludeDoProcessRoot(ctxt, tree);
2151
0
    if ((ret >= 0) && (ctxt->nbErrors > 0))
2152
0
  ret = -1;
2153
2154
0
    xmlXIncludeFreeContext(ctxt);
2155
0
    return(ret);
2156
0
}
2157
2158
/**
2159
 * Implement the XInclude substitution for the given subtree
2160
 *
2161
 * @param tree  a node in an XML document
2162
 * @returns 0 if no substitution were done, -1 if some processing failed
2163
 *    or the number of substitutions done.
2164
 */
2165
int
2166
0
xmlXIncludeProcessTree(xmlNode *tree) {
2167
0
    return(xmlXIncludeProcessTreeFlags(tree, (tree && tree->doc) ? tree->doc->parseFlags : 0));
2168
0
}
2169
2170
/**
2171
 * Implement the XInclude substitution for the given subtree reusing
2172
 * the information and data coming from the given context.
2173
 *
2174
 * @param ctxt  an existing XInclude context
2175
 * @param node  a node in an XML document
2176
 * @returns 0 if no substitution were done, -1 if some processing failed
2177
 *    or the number of substitutions done.
2178
 */
2179
int
2180
14.4k
xmlXIncludeProcessNode(xmlXIncludeCtxt *ctxt, xmlNode *node) {
2181
14.4k
    int ret = 0;
2182
2183
14.4k
    if ((node == NULL) || (node->type == XML_NAMESPACE_DECL) ||
2184
14.4k
        (node->doc == NULL) || (ctxt == NULL))
2185
0
  return(-1);
2186
14.4k
    ret = xmlXIncludeDoProcessRoot(ctxt, node);
2187
14.4k
    if ((ret >= 0) && (ctxt->nbErrors > 0))
2188
12.2k
  ret = -1;
2189
14.4k
    return(ret);
2190
14.4k
}
2191
2192
#else /* !LIBXML_XINCLUDE_ENABLED */
2193
#endif