• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * tree.c : implementation of access function for an XML tree.
3  *
4  * References:
5  *   XHTML 1.0 W3C REC: http://www.w3.org/TR/2002/REC-xhtml1-20020801/
6  *
7  * See Copyright for the status of this software.
8  *
9  * daniel@veillard.com
10  *
11  */
12 
13 /* To avoid EBCDIC trouble when parsing on zOS */
14 #if defined(__MVS__)
15 #pragma convert("ISO8859-1")
16 #endif
17 
18 #define IN_LIBXML
19 #include "libxml.h"
20 
21 #include <string.h> /* for memset() only ! */
22 #include <stddef.h>
23 #include <limits.h>
24 #ifdef HAVE_CTYPE_H
25 #include <ctype.h>
26 #endif
27 #ifdef HAVE_STDLIB_H
28 #include <stdlib.h>
29 #endif
30 #ifdef LIBXML_ZLIB_ENABLED
31 #include <zlib.h>
32 #endif
33 
34 #include <libxml/xmlmemory.h>
35 #include <libxml/tree.h>
36 #include <libxml/parser.h>
37 #include <libxml/uri.h>
38 #include <libxml/entities.h>
39 #include <libxml/valid.h>
40 #include <libxml/xmlerror.h>
41 #include <libxml/parserInternals.h>
42 #include <libxml/globals.h>
43 #ifdef LIBXML_HTML_ENABLED
44 #include <libxml/HTMLtree.h>
45 #endif
46 #ifdef LIBXML_DEBUG_ENABLED
47 #include <libxml/debugXML.h>
48 #endif
49 
50 #include "buf.h"
51 #include "save.h"
52 
53 int __xmlRegisterCallbacks = 0;
54 
55 /************************************************************************
56  *									*
57  *		Forward declarations					*
58  *									*
59  ************************************************************************/
60 
61 static xmlNsPtr
62 xmlNewReconciledNs(xmlDocPtr doc, xmlNodePtr tree, xmlNsPtr ns);
63 
64 static xmlChar* xmlGetPropNodeValueInternal(const xmlAttr *prop);
65 
66 /************************************************************************
67  *									*
68  *		Tree memory error handler				*
69  *									*
70  ************************************************************************/
71 /**
72  * xmlTreeErrMemory:
73  * @extra:  extra information
74  *
75  * Handle an out of memory condition
76  */
77 static void
xmlTreeErrMemory(const char * extra)78 xmlTreeErrMemory(const char *extra)
79 {
80     __xmlSimpleError(XML_FROM_TREE, XML_ERR_NO_MEMORY, NULL, NULL, extra);
81 }
82 
83 /**
84  * xmlTreeErr:
85  * @code:  the error number
86  * @extra:  extra information
87  *
88  * Handle an out of memory condition
89  */
90 static void
xmlTreeErr(int code,xmlNodePtr node,const char * extra)91 xmlTreeErr(int code, xmlNodePtr node, const char *extra)
92 {
93     const char *msg = NULL;
94 
95     switch(code) {
96         case XML_TREE_INVALID_HEX:
97 	    msg = "invalid hexadecimal character value\n";
98 	    break;
99 	case XML_TREE_INVALID_DEC:
100 	    msg = "invalid decimal character value\n";
101 	    break;
102 	case XML_TREE_UNTERMINATED_ENTITY:
103 	    msg = "unterminated entity reference %15s\n";
104 	    break;
105 	case XML_TREE_NOT_UTF8:
106 	    msg = "string is not in UTF-8\n";
107 	    break;
108 	default:
109 	    msg = "unexpected error number\n";
110     }
111     __xmlSimpleError(XML_FROM_TREE, code, node, msg, extra);
112 }
113 
114 /************************************************************************
115  *									*
116  *		A few static variables and macros			*
117  *									*
118  ************************************************************************/
119 /* #undef xmlStringText */
120 const xmlChar xmlStringText[] = { 't', 'e', 'x', 't', 0 };
121 /* #undef xmlStringTextNoenc */
122 const xmlChar xmlStringTextNoenc[] =
123               { 't', 'e', 'x', 't', 'n', 'o', 'e', 'n', 'c', 0 };
124 /* #undef xmlStringComment */
125 const xmlChar xmlStringComment[] = { 'c', 'o', 'm', 'm', 'e', 'n', 't', 0 };
126 
127 static int xmlCompressMode = 0;
128 static int xmlCheckDTD = 1;
129 
130 #define UPDATE_LAST_CHILD_AND_PARENT(n) if ((n) != NULL) {		\
131     xmlNodePtr ulccur = (n)->children;					\
132     if (ulccur == NULL) {						\
133         (n)->last = NULL;						\
134     } else {								\
135         while (ulccur->next != NULL) {					\
136 		ulccur->parent = (n);					\
137 		ulccur = ulccur->next;					\
138 	}								\
139 	ulccur->parent = (n);						\
140 	(n)->last = ulccur;						\
141 }}
142 
143 #define IS_STR_XML(str) ((str != NULL) && (str[0] == 'x') && \
144   (str[1] == 'm') && (str[2] == 'l') && (str[3] == 0))
145 
146 /* #define DEBUG_BUFFER */
147 /* #define DEBUG_TREE */
148 
149 /************************************************************************
150  *									*
151  *		Functions to move to entities.c once the		*
152  *		API freeze is smoothen and they can be made public.	*
153  *									*
154  ************************************************************************/
155 #include <libxml/hash.h>
156 
157 #ifdef LIBXML_TREE_ENABLED
158 /**
159  * xmlGetEntityFromDtd:
160  * @dtd:  A pointer to the DTD to search
161  * @name:  The entity name
162  *
163  * Do an entity lookup in the DTD entity hash table and
164  * return the corresponding entity, if found.
165  *
166  * Returns A pointer to the entity structure or NULL if not found.
167  */
168 static xmlEntityPtr
xmlGetEntityFromDtd(const xmlDtd * dtd,const xmlChar * name)169 xmlGetEntityFromDtd(const xmlDtd *dtd, const xmlChar *name) {
170     xmlEntitiesTablePtr table;
171 
172     if((dtd != NULL) && (dtd->entities != NULL)) {
173 	table = (xmlEntitiesTablePtr) dtd->entities;
174 	return((xmlEntityPtr) xmlHashLookup(table, name));
175 	/* return(xmlGetEntityFromTable(table, name)); */
176     }
177     return(NULL);
178 }
179 /**
180  * xmlGetParameterEntityFromDtd:
181  * @dtd:  A pointer to the DTD to search
182  * @name:  The entity name
183  *
184  * Do an entity lookup in the DTD parameter entity hash table and
185  * return the corresponding entity, if found.
186  *
187  * Returns A pointer to the entity structure or NULL if not found.
188  */
189 static xmlEntityPtr
xmlGetParameterEntityFromDtd(const xmlDtd * dtd,const xmlChar * name)190 xmlGetParameterEntityFromDtd(const xmlDtd *dtd, const xmlChar *name) {
191     xmlEntitiesTablePtr table;
192 
193     if ((dtd != NULL) && (dtd->pentities != NULL)) {
194 	table = (xmlEntitiesTablePtr) dtd->pentities;
195 	return((xmlEntityPtr) xmlHashLookup(table, name));
196 	/* return(xmlGetEntityFromTable(table, name)); */
197     }
198     return(NULL);
199 }
200 #endif /* LIBXML_TREE_ENABLED */
201 
202 /************************************************************************
203  *									*
204  *			QName handling helper				*
205  *									*
206  ************************************************************************/
207 
208 /**
209  * xmlBuildQName:
210  * @ncname:  the Name
211  * @prefix:  the prefix
212  * @memory:  preallocated memory
213  * @len:  preallocated memory length
214  *
215  * Builds the QName @prefix:@ncname in @memory if there is enough space
216  * and prefix is not NULL nor empty, otherwise allocate a new string.
217  * If prefix is NULL or empty it returns ncname.
218  *
219  * Returns the new string which must be freed by the caller if different from
220  *         @memory and @ncname or NULL in case of error
221  */
222 xmlChar *
xmlBuildQName(const xmlChar * ncname,const xmlChar * prefix,xmlChar * memory,int len)223 xmlBuildQName(const xmlChar *ncname, const xmlChar *prefix,
224 	      xmlChar *memory, int len) {
225     int lenn, lenp;
226     xmlChar *ret;
227 
228     if (ncname == NULL) return(NULL);
229     if (prefix == NULL) return((xmlChar *) ncname);
230 
231     lenn = strlen((char *) ncname);
232     lenp = strlen((char *) prefix);
233 
234     if ((memory == NULL) || (len < lenn + lenp + 2)) {
235 	ret = (xmlChar *) xmlMallocAtomic(lenn + lenp + 2);
236 	if (ret == NULL) {
237 	    xmlTreeErrMemory("building QName");
238 	    return(NULL);
239 	}
240     } else {
241 	ret = memory;
242     }
243     memcpy(&ret[0], prefix, lenp);
244     ret[lenp] = ':';
245     memcpy(&ret[lenp + 1], ncname, lenn);
246     ret[lenn + lenp + 1] = 0;
247     return(ret);
248 }
249 
250 /**
251  * xmlSplitQName2:
252  * @name:  the full QName
253  * @prefix:  a xmlChar **
254  *
255  * parse an XML qualified name string
256  *
257  * [NS 5] QName ::= (Prefix ':')? LocalPart
258  *
259  * [NS 6] Prefix ::= NCName
260  *
261  * [NS 7] LocalPart ::= NCName
262  *
263  * Returns NULL if the name doesn't have a prefix. Otherwise, returns the
264  * local part, and prefix is updated to get the Prefix. Both the return value
265  * and the prefix must be freed by the caller.
266  */
267 xmlChar *
xmlSplitQName2(const xmlChar * name,xmlChar ** prefix)268 xmlSplitQName2(const xmlChar *name, xmlChar **prefix) {
269     int len = 0;
270     xmlChar *ret = NULL;
271 
272     if (prefix == NULL) return(NULL);
273     *prefix = NULL;
274     if (name == NULL) return(NULL);
275 
276 #ifndef XML_XML_NAMESPACE
277     /* xml: prefix is not really a namespace */
278     if ((name[0] == 'x') && (name[1] == 'm') &&
279         (name[2] == 'l') && (name[3] == ':'))
280 	return(NULL);
281 #endif
282 
283     /* nasty but valid */
284     if (name[0] == ':')
285 	return(NULL);
286 
287     /*
288      * we are not trying to validate but just to cut, and yes it will
289      * work even if this is as set of UTF-8 encoded chars
290      */
291     while ((name[len] != 0) && (name[len] != ':'))
292 	len++;
293 
294     if (name[len] == 0)
295 	return(NULL);
296 
297     *prefix = xmlStrndup(name, len);
298     if (*prefix == NULL) {
299 	xmlTreeErrMemory("QName split");
300 	return(NULL);
301     }
302     ret = xmlStrdup(&name[len + 1]);
303     if (ret == NULL) {
304 	xmlTreeErrMemory("QName split");
305 	if (*prefix != NULL) {
306 	    xmlFree(*prefix);
307 	    *prefix = NULL;
308 	}
309 	return(NULL);
310     }
311 
312     return(ret);
313 }
314 
315 /**
316  * xmlSplitQName3:
317  * @name:  the full QName
318  * @len: an int *
319  *
320  * parse an XML qualified name string,i
321  *
322  * returns NULL if it is not a Qualified Name, otherwise, update len
323  *         with the length in byte of the prefix and return a pointer
324  *         to the start of the name without the prefix
325  */
326 
327 const xmlChar *
xmlSplitQName3(const xmlChar * name,int * len)328 xmlSplitQName3(const xmlChar *name, int *len) {
329     int l = 0;
330 
331     if (name == NULL) return(NULL);
332     if (len == NULL) return(NULL);
333 
334     /* nasty but valid */
335     if (name[0] == ':')
336 	return(NULL);
337 
338     /*
339      * we are not trying to validate but just to cut, and yes it will
340      * work even if this is as set of UTF-8 encoded chars
341      */
342     while ((name[l] != 0) && (name[l] != ':'))
343 	l++;
344 
345     if (name[l] == 0)
346 	return(NULL);
347 
348     *len = l;
349 
350     return(&name[l+1]);
351 }
352 
353 /************************************************************************
354  *									*
355  *		Check Name, NCName and QName strings			*
356  *									*
357  ************************************************************************/
358 
359 #define CUR_SCHAR(s, l) xmlStringCurrentChar(NULL, s, &l)
360 
361 #if defined(LIBXML_TREE_ENABLED) || defined(LIBXML_XPATH_ENABLED) || defined(LIBXML_SCHEMAS_ENABLED) || defined(LIBXML_DEBUG_ENABLED) || defined (LIBXML_HTML_ENABLED) || defined(LIBXML_SAX1_ENABLED) || defined(LIBXML_HTML_ENABLED) || defined(LIBXML_WRITER_ENABLED) || defined(LIBXML_DOCB_ENABLED) || defined(LIBXML_LEGACY_ENABLED)
362 /**
363  * xmlValidateNCName:
364  * @value: the value to check
365  * @space: allow spaces in front and end of the string
366  *
367  * Check that a value conforms to the lexical space of NCName
368  *
369  * Returns 0 if this validates, a positive error code number otherwise
370  *         and -1 in case of internal or API error.
371  */
372 int
xmlValidateNCName(const xmlChar * value,int space)373 xmlValidateNCName(const xmlChar *value, int space) {
374     const xmlChar *cur = value;
375     int c,l;
376 
377     if (value == NULL)
378         return(-1);
379 
380     /*
381      * First quick algorithm for ASCII range
382      */
383     if (space)
384 	while (IS_BLANK_CH(*cur)) cur++;
385     if (((*cur >= 'a') && (*cur <= 'z')) || ((*cur >= 'A') && (*cur <= 'Z')) ||
386 	(*cur == '_'))
387 	cur++;
388     else
389 	goto try_complex;
390     while (((*cur >= 'a') && (*cur <= 'z')) ||
391 	   ((*cur >= 'A') && (*cur <= 'Z')) ||
392 	   ((*cur >= '0') && (*cur <= '9')) ||
393 	   (*cur == '_') || (*cur == '-') || (*cur == '.'))
394 	cur++;
395     if (space)
396 	while (IS_BLANK_CH(*cur)) cur++;
397     if (*cur == 0)
398 	return(0);
399 
400 try_complex:
401     /*
402      * Second check for chars outside the ASCII range
403      */
404     cur = value;
405     c = CUR_SCHAR(cur, l);
406     if (space) {
407 	while (IS_BLANK(c)) {
408 	    cur += l;
409 	    c = CUR_SCHAR(cur, l);
410 	}
411     }
412     if ((!IS_LETTER(c)) && (c != '_'))
413 	return(1);
414     cur += l;
415     c = CUR_SCHAR(cur, l);
416     while (IS_LETTER(c) || IS_DIGIT(c) || (c == '.') ||
417 	   (c == '-') || (c == '_') || IS_COMBINING(c) ||
418 	   IS_EXTENDER(c)) {
419 	cur += l;
420 	c = CUR_SCHAR(cur, l);
421     }
422     if (space) {
423 	while (IS_BLANK(c)) {
424 	    cur += l;
425 	    c = CUR_SCHAR(cur, l);
426 	}
427     }
428     if (c != 0)
429 	return(1);
430 
431     return(0);
432 }
433 #endif
434 
435 #if defined(LIBXML_TREE_ENABLED) || defined(LIBXML_SCHEMAS_ENABLED)
436 /**
437  * xmlValidateQName:
438  * @value: the value to check
439  * @space: allow spaces in front and end of the string
440  *
441  * Check that a value conforms to the lexical space of QName
442  *
443  * Returns 0 if this validates, a positive error code number otherwise
444  *         and -1 in case of internal or API error.
445  */
446 int
xmlValidateQName(const xmlChar * value,int space)447 xmlValidateQName(const xmlChar *value, int space) {
448     const xmlChar *cur = value;
449     int c,l;
450 
451     if (value == NULL)
452         return(-1);
453     /*
454      * First quick algorithm for ASCII range
455      */
456     if (space)
457 	while (IS_BLANK_CH(*cur)) cur++;
458     if (((*cur >= 'a') && (*cur <= 'z')) || ((*cur >= 'A') && (*cur <= 'Z')) ||
459 	(*cur == '_'))
460 	cur++;
461     else
462 	goto try_complex;
463     while (((*cur >= 'a') && (*cur <= 'z')) ||
464 	   ((*cur >= 'A') && (*cur <= 'Z')) ||
465 	   ((*cur >= '0') && (*cur <= '9')) ||
466 	   (*cur == '_') || (*cur == '-') || (*cur == '.'))
467 	cur++;
468     if (*cur == ':') {
469 	cur++;
470 	if (((*cur >= 'a') && (*cur <= 'z')) ||
471 	    ((*cur >= 'A') && (*cur <= 'Z')) ||
472 	    (*cur == '_'))
473 	    cur++;
474 	else
475 	    goto try_complex;
476 	while (((*cur >= 'a') && (*cur <= 'z')) ||
477 	       ((*cur >= 'A') && (*cur <= 'Z')) ||
478 	       ((*cur >= '0') && (*cur <= '9')) ||
479 	       (*cur == '_') || (*cur == '-') || (*cur == '.'))
480 	    cur++;
481     }
482     if (space)
483 	while (IS_BLANK_CH(*cur)) cur++;
484     if (*cur == 0)
485 	return(0);
486 
487 try_complex:
488     /*
489      * Second check for chars outside the ASCII range
490      */
491     cur = value;
492     c = CUR_SCHAR(cur, l);
493     if (space) {
494 	while (IS_BLANK(c)) {
495 	    cur += l;
496 	    c = CUR_SCHAR(cur, l);
497 	}
498     }
499     if ((!IS_LETTER(c)) && (c != '_'))
500 	return(1);
501     cur += l;
502     c = CUR_SCHAR(cur, l);
503     while (IS_LETTER(c) || IS_DIGIT(c) || (c == '.') ||
504 	   (c == '-') || (c == '_') || IS_COMBINING(c) ||
505 	   IS_EXTENDER(c)) {
506 	cur += l;
507 	c = CUR_SCHAR(cur, l);
508     }
509     if (c == ':') {
510 	cur += l;
511 	c = CUR_SCHAR(cur, l);
512 	if ((!IS_LETTER(c)) && (c != '_'))
513 	    return(1);
514 	cur += l;
515 	c = CUR_SCHAR(cur, l);
516 	while (IS_LETTER(c) || IS_DIGIT(c) || (c == '.') ||
517 	       (c == '-') || (c == '_') || IS_COMBINING(c) ||
518 	       IS_EXTENDER(c)) {
519 	    cur += l;
520 	    c = CUR_SCHAR(cur, l);
521 	}
522     }
523     if (space) {
524 	while (IS_BLANK(c)) {
525 	    cur += l;
526 	    c = CUR_SCHAR(cur, l);
527 	}
528     }
529     if (c != 0)
530 	return(1);
531     return(0);
532 }
533 
534 /**
535  * xmlValidateName:
536  * @value: the value to check
537  * @space: allow spaces in front and end of the string
538  *
539  * Check that a value conforms to the lexical space of Name
540  *
541  * Returns 0 if this validates, a positive error code number otherwise
542  *         and -1 in case of internal or API error.
543  */
544 int
xmlValidateName(const xmlChar * value,int space)545 xmlValidateName(const xmlChar *value, int space) {
546     const xmlChar *cur = value;
547     int c,l;
548 
549     if (value == NULL)
550         return(-1);
551     /*
552      * First quick algorithm for ASCII range
553      */
554     if (space)
555 	while (IS_BLANK_CH(*cur)) cur++;
556     if (((*cur >= 'a') && (*cur <= 'z')) || ((*cur >= 'A') && (*cur <= 'Z')) ||
557 	(*cur == '_') || (*cur == ':'))
558 	cur++;
559     else
560 	goto try_complex;
561     while (((*cur >= 'a') && (*cur <= 'z')) ||
562 	   ((*cur >= 'A') && (*cur <= 'Z')) ||
563 	   ((*cur >= '0') && (*cur <= '9')) ||
564 	   (*cur == '_') || (*cur == '-') || (*cur == '.') || (*cur == ':'))
565 	cur++;
566     if (space)
567 	while (IS_BLANK_CH(*cur)) cur++;
568     if (*cur == 0)
569 	return(0);
570 
571 try_complex:
572     /*
573      * Second check for chars outside the ASCII range
574      */
575     cur = value;
576     c = CUR_SCHAR(cur, l);
577     if (space) {
578 	while (IS_BLANK(c)) {
579 	    cur += l;
580 	    c = CUR_SCHAR(cur, l);
581 	}
582     }
583     if ((!IS_LETTER(c)) && (c != '_') && (c != ':'))
584 	return(1);
585     cur += l;
586     c = CUR_SCHAR(cur, l);
587     while (IS_LETTER(c) || IS_DIGIT(c) || (c == '.') || (c == ':') ||
588 	   (c == '-') || (c == '_') || IS_COMBINING(c) || IS_EXTENDER(c)) {
589 	cur += l;
590 	c = CUR_SCHAR(cur, l);
591     }
592     if (space) {
593 	while (IS_BLANK(c)) {
594 	    cur += l;
595 	    c = CUR_SCHAR(cur, l);
596 	}
597     }
598     if (c != 0)
599 	return(1);
600     return(0);
601 }
602 
603 /**
604  * xmlValidateNMToken:
605  * @value: the value to check
606  * @space: allow spaces in front and end of the string
607  *
608  * Check that a value conforms to the lexical space of NMToken
609  *
610  * Returns 0 if this validates, a positive error code number otherwise
611  *         and -1 in case of internal or API error.
612  */
613 int
xmlValidateNMToken(const xmlChar * value,int space)614 xmlValidateNMToken(const xmlChar *value, int space) {
615     const xmlChar *cur = value;
616     int c,l;
617 
618     if (value == NULL)
619         return(-1);
620     /*
621      * First quick algorithm for ASCII range
622      */
623     if (space)
624 	while (IS_BLANK_CH(*cur)) cur++;
625     if (((*cur >= 'a') && (*cur <= 'z')) ||
626         ((*cur >= 'A') && (*cur <= 'Z')) ||
627         ((*cur >= '0') && (*cur <= '9')) ||
628         (*cur == '_') || (*cur == '-') || (*cur == '.') || (*cur == ':'))
629 	cur++;
630     else
631 	goto try_complex;
632     while (((*cur >= 'a') && (*cur <= 'z')) ||
633 	   ((*cur >= 'A') && (*cur <= 'Z')) ||
634 	   ((*cur >= '0') && (*cur <= '9')) ||
635 	   (*cur == '_') || (*cur == '-') || (*cur == '.') || (*cur == ':'))
636 	cur++;
637     if (space)
638 	while (IS_BLANK_CH(*cur)) cur++;
639     if (*cur == 0)
640 	return(0);
641 
642 try_complex:
643     /*
644      * Second check for chars outside the ASCII range
645      */
646     cur = value;
647     c = CUR_SCHAR(cur, l);
648     if (space) {
649 	while (IS_BLANK(c)) {
650 	    cur += l;
651 	    c = CUR_SCHAR(cur, l);
652 	}
653     }
654     if (!(IS_LETTER(c) || IS_DIGIT(c) || (c == '.') || (c == ':') ||
655         (c == '-') || (c == '_') || IS_COMBINING(c) || IS_EXTENDER(c)))
656 	return(1);
657     cur += l;
658     c = CUR_SCHAR(cur, l);
659     while (IS_LETTER(c) || IS_DIGIT(c) || (c == '.') || (c == ':') ||
660 	   (c == '-') || (c == '_') || IS_COMBINING(c) || IS_EXTENDER(c)) {
661 	cur += l;
662 	c = CUR_SCHAR(cur, l);
663     }
664     if (space) {
665 	while (IS_BLANK(c)) {
666 	    cur += l;
667 	    c = CUR_SCHAR(cur, l);
668 	}
669     }
670     if (c != 0)
671 	return(1);
672     return(0);
673 }
674 #endif /* LIBXML_TREE_ENABLED */
675 
676 /************************************************************************
677  *									*
678  *		Allocation and deallocation of basic structures		*
679  *									*
680  ************************************************************************/
681 
682 /**
683  * xmlSetBufferAllocationScheme:
684  * @scheme:  allocation method to use
685  *
686  * Set the buffer allocation method.  Types are
687  * XML_BUFFER_ALLOC_EXACT - use exact sizes, keeps memory usage down
688  * XML_BUFFER_ALLOC_DOUBLEIT - double buffer when extra needed,
689  *                             improves performance
690  */
691 void
xmlSetBufferAllocationScheme(xmlBufferAllocationScheme scheme)692 xmlSetBufferAllocationScheme(xmlBufferAllocationScheme scheme) {
693     if ((scheme == XML_BUFFER_ALLOC_EXACT) ||
694         (scheme == XML_BUFFER_ALLOC_DOUBLEIT) ||
695         (scheme == XML_BUFFER_ALLOC_HYBRID))
696 	xmlBufferAllocScheme = scheme;
697 }
698 
699 /**
700  * xmlGetBufferAllocationScheme:
701  *
702  * Types are
703  * XML_BUFFER_ALLOC_EXACT - use exact sizes, keeps memory usage down
704  * XML_BUFFER_ALLOC_DOUBLEIT - double buffer when extra needed,
705  *                             improves performance
706  * XML_BUFFER_ALLOC_HYBRID - use exact sizes on small strings to keep memory usage tight
707  *                            in normal usage, and doubleit on large strings to avoid
708  *                            pathological performance.
709  *
710  * Returns the current allocation scheme
711  */
712 xmlBufferAllocationScheme
xmlGetBufferAllocationScheme(void)713 xmlGetBufferAllocationScheme(void) {
714     return(xmlBufferAllocScheme);
715 }
716 
717 /**
718  * xmlNewNs:
719  * @node:  the element carrying the namespace
720  * @href:  the URI associated
721  * @prefix:  the prefix for the namespace
722  *
723  * Creation of a new Namespace. This function will refuse to create
724  * a namespace with a similar prefix than an existing one present on this
725  * node.
726  * Note that for a default namespace, @prefix should be NULL.
727  *
728  * We use href==NULL in the case of an element creation where the namespace
729  * was not defined.
730  *
731  * Returns a new namespace pointer or NULL
732  */
733 xmlNsPtr
xmlNewNs(xmlNodePtr node,const xmlChar * href,const xmlChar * prefix)734 xmlNewNs(xmlNodePtr node, const xmlChar *href, const xmlChar *prefix) {
735     xmlNsPtr cur;
736 
737     if ((node != NULL) && (node->type != XML_ELEMENT_NODE))
738 	return(NULL);
739 
740     if ((prefix != NULL) && (xmlStrEqual(prefix, BAD_CAST "xml"))) {
741         /* xml namespace is predefined, no need to add it */
742         if (xmlStrEqual(href, XML_XML_NAMESPACE))
743             return(NULL);
744 
745         /*
746          * Problem, this is an attempt to bind xml prefix to a wrong
747          * namespace, which breaks
748          * Namespace constraint: Reserved Prefixes and Namespace Names
749          * from XML namespace. But documents authors may not care in
750          * their context so let's proceed.
751          */
752     }
753 
754     /*
755      * Allocate a new Namespace and fill the fields.
756      */
757     cur = (xmlNsPtr) xmlMalloc(sizeof(xmlNs));
758     if (cur == NULL) {
759 	xmlTreeErrMemory("building namespace");
760 	return(NULL);
761     }
762     memset(cur, 0, sizeof(xmlNs));
763     cur->type = XML_LOCAL_NAMESPACE;
764 
765     if (href != NULL)
766 	cur->href = xmlStrdup(href);
767     if (prefix != NULL)
768 	cur->prefix = xmlStrdup(prefix);
769 
770     /*
771      * Add it at the end to preserve parsing order ...
772      * and checks for existing use of the prefix
773      */
774     if (node != NULL) {
775 	if (node->nsDef == NULL) {
776 	    node->nsDef = cur;
777 	} else {
778 	    xmlNsPtr prev = node->nsDef;
779 
780 	    if (((prev->prefix == NULL) && (cur->prefix == NULL)) ||
781 		(xmlStrEqual(prev->prefix, cur->prefix))) {
782 		xmlFreeNs(cur);
783 		return(NULL);
784 	    }
785 	    while (prev->next != NULL) {
786 	        prev = prev->next;
787 		if (((prev->prefix == NULL) && (cur->prefix == NULL)) ||
788 		    (xmlStrEqual(prev->prefix, cur->prefix))) {
789 		    xmlFreeNs(cur);
790 		    return(NULL);
791 		}
792 	    }
793 	    prev->next = cur;
794 	}
795     }
796     return(cur);
797 }
798 
799 /**
800  * xmlSetNs:
801  * @node:  a node in the document
802  * @ns:  a namespace pointer
803  *
804  * Associate a namespace to a node, a posteriori.
805  */
806 void
xmlSetNs(xmlNodePtr node,xmlNsPtr ns)807 xmlSetNs(xmlNodePtr node, xmlNsPtr ns) {
808     if (node == NULL) {
809 #ifdef DEBUG_TREE
810         xmlGenericError(xmlGenericErrorContext,
811 		"xmlSetNs: node == NULL\n");
812 #endif
813 	return;
814     }
815     if ((node->type == XML_ELEMENT_NODE) ||
816         (node->type == XML_ATTRIBUTE_NODE))
817 	node->ns = ns;
818 }
819 
820 /**
821  * xmlFreeNs:
822  * @cur:  the namespace pointer
823  *
824  * Free up the structures associated to a namespace
825  */
826 void
xmlFreeNs(xmlNsPtr cur)827 xmlFreeNs(xmlNsPtr cur) {
828     if (cur == NULL) {
829 #ifdef DEBUG_TREE
830         xmlGenericError(xmlGenericErrorContext,
831 		"xmlFreeNs : ns == NULL\n");
832 #endif
833 	return;
834     }
835     if (cur->href != NULL) xmlFree((char *) cur->href);
836     if (cur->prefix != NULL) xmlFree((char *) cur->prefix);
837     xmlFree(cur);
838 }
839 
840 /**
841  * xmlFreeNsList:
842  * @cur:  the first namespace pointer
843  *
844  * Free up all the structures associated to the chained namespaces.
845  */
846 void
xmlFreeNsList(xmlNsPtr cur)847 xmlFreeNsList(xmlNsPtr cur) {
848     xmlNsPtr next;
849     if (cur == NULL) {
850 #ifdef DEBUG_TREE
851         xmlGenericError(xmlGenericErrorContext,
852 		"xmlFreeNsList : ns == NULL\n");
853 #endif
854 	return;
855     }
856     while (cur != NULL) {
857         next = cur->next;
858         xmlFreeNs(cur);
859 	cur = next;
860     }
861 }
862 
863 /**
864  * xmlNewDtd:
865  * @doc:  the document pointer
866  * @name:  the DTD name
867  * @ExternalID:  the external ID
868  * @SystemID:  the system ID
869  *
870  * Creation of a new DTD for the external subset. To create an
871  * internal subset, use xmlCreateIntSubset().
872  *
873  * Returns a pointer to the new DTD structure
874  */
875 xmlDtdPtr
xmlNewDtd(xmlDocPtr doc,const xmlChar * name,const xmlChar * ExternalID,const xmlChar * SystemID)876 xmlNewDtd(xmlDocPtr doc, const xmlChar *name,
877                     const xmlChar *ExternalID, const xmlChar *SystemID) {
878     xmlDtdPtr cur;
879 
880     if ((doc != NULL) && (doc->extSubset != NULL)) {
881 #ifdef DEBUG_TREE
882         xmlGenericError(xmlGenericErrorContext,
883 		"xmlNewDtd(%s): document %s already have a DTD %s\n",
884 	    /* !!! */ (char *) name, doc->name,
885 	    /* !!! */ (char *)doc->extSubset->name);
886 #endif
887 	return(NULL);
888     }
889 
890     /*
891      * Allocate a new DTD and fill the fields.
892      */
893     cur = (xmlDtdPtr) xmlMalloc(sizeof(xmlDtd));
894     if (cur == NULL) {
895 	xmlTreeErrMemory("building DTD");
896 	return(NULL);
897     }
898     memset(cur, 0 , sizeof(xmlDtd));
899     cur->type = XML_DTD_NODE;
900 
901     if (name != NULL)
902 	cur->name = xmlStrdup(name);
903     if (ExternalID != NULL)
904 	cur->ExternalID = xmlStrdup(ExternalID);
905     if (SystemID != NULL)
906 	cur->SystemID = xmlStrdup(SystemID);
907     if (doc != NULL)
908 	doc->extSubset = cur;
909     cur->doc = doc;
910 
911     if ((__xmlRegisterCallbacks) && (xmlRegisterNodeDefaultValue))
912 	xmlRegisterNodeDefaultValue((xmlNodePtr)cur);
913     return(cur);
914 }
915 
916 /**
917  * xmlGetIntSubset:
918  * @doc:  the document pointer
919  *
920  * Get the internal subset of a document
921  * Returns a pointer to the DTD structure or NULL if not found
922  */
923 
924 xmlDtdPtr
xmlGetIntSubset(const xmlDoc * doc)925 xmlGetIntSubset(const xmlDoc *doc) {
926     xmlNodePtr cur;
927 
928     if (doc == NULL)
929 	return(NULL);
930     cur = doc->children;
931     while (cur != NULL) {
932 	if (cur->type == XML_DTD_NODE)
933 	    return((xmlDtdPtr) cur);
934 	cur = cur->next;
935     }
936     return((xmlDtdPtr) doc->intSubset);
937 }
938 
939 /**
940  * xmlCreateIntSubset:
941  * @doc:  the document pointer
942  * @name:  the DTD name
943  * @ExternalID:  the external (PUBLIC) ID
944  * @SystemID:  the system ID
945  *
946  * Create the internal subset of a document
947  * Returns a pointer to the new DTD structure
948  */
949 xmlDtdPtr
xmlCreateIntSubset(xmlDocPtr doc,const xmlChar * name,const xmlChar * ExternalID,const xmlChar * SystemID)950 xmlCreateIntSubset(xmlDocPtr doc, const xmlChar *name,
951                    const xmlChar *ExternalID, const xmlChar *SystemID) {
952     xmlDtdPtr cur;
953 
954     if ((doc != NULL) && (xmlGetIntSubset(doc) != NULL)) {
955 #ifdef DEBUG_TREE
956         xmlGenericError(xmlGenericErrorContext,
957 
958      "xmlCreateIntSubset(): document %s already have an internal subset\n",
959 	    doc->name);
960 #endif
961 	return(NULL);
962     }
963 
964     /*
965      * Allocate a new DTD and fill the fields.
966      */
967     cur = (xmlDtdPtr) xmlMalloc(sizeof(xmlDtd));
968     if (cur == NULL) {
969 	xmlTreeErrMemory("building internal subset");
970 	return(NULL);
971     }
972     memset(cur, 0, sizeof(xmlDtd));
973     cur->type = XML_DTD_NODE;
974 
975     if (name != NULL) {
976 	cur->name = xmlStrdup(name);
977 	if (cur->name == NULL) {
978 	    xmlTreeErrMemory("building internal subset");
979 	    xmlFree(cur);
980 	    return(NULL);
981 	}
982     }
983     if (ExternalID != NULL) {
984 	cur->ExternalID = xmlStrdup(ExternalID);
985 	if (cur->ExternalID  == NULL) {
986 	    xmlTreeErrMemory("building internal subset");
987 	    if (cur->name != NULL)
988 	        xmlFree((char *)cur->name);
989 	    xmlFree(cur);
990 	    return(NULL);
991 	}
992     }
993     if (SystemID != NULL) {
994 	cur->SystemID = xmlStrdup(SystemID);
995 	if (cur->SystemID == NULL) {
996 	    xmlTreeErrMemory("building internal subset");
997 	    if (cur->name != NULL)
998 	        xmlFree((char *)cur->name);
999 	    if (cur->ExternalID != NULL)
1000 	        xmlFree((char *)cur->ExternalID);
1001 	    xmlFree(cur);
1002 	    return(NULL);
1003 	}
1004     }
1005     if (doc != NULL) {
1006 	doc->intSubset = cur;
1007 	cur->parent = doc;
1008 	cur->doc = doc;
1009 	if (doc->children == NULL) {
1010 	    doc->children = (xmlNodePtr) cur;
1011 	    doc->last = (xmlNodePtr) cur;
1012 	} else {
1013 	    if (doc->type == XML_HTML_DOCUMENT_NODE) {
1014 		xmlNodePtr prev;
1015 
1016 		prev = doc->children;
1017 		prev->prev = (xmlNodePtr) cur;
1018 		cur->next = prev;
1019 		doc->children = (xmlNodePtr) cur;
1020 	    } else {
1021 		xmlNodePtr next;
1022 
1023 		next = doc->children;
1024 		while ((next != NULL) && (next->type != XML_ELEMENT_NODE))
1025 		    next = next->next;
1026 		if (next == NULL) {
1027 		    cur->prev = doc->last;
1028 		    cur->prev->next = (xmlNodePtr) cur;
1029 		    cur->next = NULL;
1030 		    doc->last = (xmlNodePtr) cur;
1031 		} else {
1032 		    cur->next = next;
1033 		    cur->prev = next->prev;
1034 		    if (cur->prev == NULL)
1035 			doc->children = (xmlNodePtr) cur;
1036 		    else
1037 			cur->prev->next = (xmlNodePtr) cur;
1038 		    next->prev = (xmlNodePtr) cur;
1039 		}
1040 	    }
1041 	}
1042     }
1043 
1044     if ((__xmlRegisterCallbacks) && (xmlRegisterNodeDefaultValue))
1045 	xmlRegisterNodeDefaultValue((xmlNodePtr)cur);
1046     return(cur);
1047 }
1048 
1049 /**
1050  * DICT_FREE:
1051  * @str:  a string
1052  *
1053  * Free a string if it is not owned by the "dict" dictionary in the
1054  * current scope
1055  */
1056 #define DICT_FREE(str)						\
1057 	if ((str) && ((!dict) ||				\
1058 	    (xmlDictOwns(dict, (const xmlChar *)(str)) == 0)))	\
1059 	    xmlFree((char *)(str));
1060 
1061 
1062 /**
1063  * DICT_COPY:
1064  * @str:  a string
1065  *
1066  * Copy a string using a "dict" dictionary in the current scope,
1067  * if available.
1068  */
1069 #define DICT_COPY(str, cpy) \
1070     if (str) { \
1071 	if (dict) { \
1072 	    if (xmlDictOwns(dict, (const xmlChar *)(str))) \
1073 		cpy = (xmlChar *) (str); \
1074 	    else \
1075 		cpy = (xmlChar *) xmlDictLookup((dict), (const xmlChar *)(str), -1); \
1076 	} else \
1077 	    cpy = xmlStrdup((const xmlChar *)(str)); }
1078 
1079 /**
1080  * DICT_CONST_COPY:
1081  * @str:  a string
1082  *
1083  * Copy a string using a "dict" dictionary in the current scope,
1084  * if available.
1085  */
1086 #define DICT_CONST_COPY(str, cpy) \
1087     if (str) { \
1088 	if (dict) { \
1089 	    if (xmlDictOwns(dict, (const xmlChar *)(str))) \
1090 		cpy = (const xmlChar *) (str); \
1091 	    else \
1092 		cpy = xmlDictLookup((dict), (const xmlChar *)(str), -1); \
1093 	} else \
1094 	    cpy = (const xmlChar *) xmlStrdup((const xmlChar *)(str)); }
1095 
1096 
1097 /**
1098  * xmlFreeDtd:
1099  * @cur:  the DTD structure to free up
1100  *
1101  * Free a DTD structure.
1102  */
1103 void
xmlFreeDtd(xmlDtdPtr cur)1104 xmlFreeDtd(xmlDtdPtr cur) {
1105     xmlDictPtr dict = NULL;
1106 
1107     if (cur == NULL) {
1108 	return;
1109     }
1110     if (cur->doc != NULL) dict = cur->doc->dict;
1111 
1112     if ((__xmlRegisterCallbacks) && (xmlDeregisterNodeDefaultValue))
1113 	xmlDeregisterNodeDefaultValue((xmlNodePtr)cur);
1114 
1115     if (cur->children != NULL) {
1116 	xmlNodePtr next, c = cur->children;
1117 
1118 	/*
1119 	 * Cleanup all nodes which are not part of the specific lists
1120 	 * of notations, elements, attributes and entities.
1121 	 */
1122         while (c != NULL) {
1123 	    next = c->next;
1124 	    if ((c->type != XML_NOTATION_NODE) &&
1125 	        (c->type != XML_ELEMENT_DECL) &&
1126 		(c->type != XML_ATTRIBUTE_DECL) &&
1127 		(c->type != XML_ENTITY_DECL)) {
1128 		xmlUnlinkNode(c);
1129 		xmlFreeNode(c);
1130 	    }
1131 	    c = next;
1132 	}
1133     }
1134     DICT_FREE(cur->name)
1135     DICT_FREE(cur->SystemID)
1136     DICT_FREE(cur->ExternalID)
1137     /* TODO !!! */
1138     if (cur->notations != NULL)
1139         xmlFreeNotationTable((xmlNotationTablePtr) cur->notations);
1140 
1141     if (cur->elements != NULL)
1142         xmlFreeElementTable((xmlElementTablePtr) cur->elements);
1143     if (cur->attributes != NULL)
1144         xmlFreeAttributeTable((xmlAttributeTablePtr) cur->attributes);
1145     if (cur->entities != NULL)
1146         xmlFreeEntitiesTable((xmlEntitiesTablePtr) cur->entities);
1147     if (cur->pentities != NULL)
1148         xmlFreeEntitiesTable((xmlEntitiesTablePtr) cur->pentities);
1149 
1150     xmlFree(cur);
1151 }
1152 
1153 /**
1154  * xmlNewDoc:
1155  * @version:  xmlChar string giving the version of XML "1.0"
1156  *
1157  * Creates a new XML document
1158  *
1159  * Returns a new document
1160  */
1161 xmlDocPtr
xmlNewDoc(const xmlChar * version)1162 xmlNewDoc(const xmlChar *version) {
1163     xmlDocPtr cur;
1164 
1165     if (version == NULL)
1166 	version = (const xmlChar *) "1.0";
1167 
1168     /*
1169      * Allocate a new document and fill the fields.
1170      */
1171     cur = (xmlDocPtr) xmlMalloc(sizeof(xmlDoc));
1172     if (cur == NULL) {
1173 	xmlTreeErrMemory("building doc");
1174 	return(NULL);
1175     }
1176     memset(cur, 0, sizeof(xmlDoc));
1177     cur->type = XML_DOCUMENT_NODE;
1178 
1179     cur->version = xmlStrdup(version);
1180     if (cur->version == NULL) {
1181 	xmlTreeErrMemory("building doc");
1182 	xmlFree(cur);
1183 	return(NULL);
1184     }
1185     cur->standalone = -1;
1186     cur->compression = -1; /* not initialized */
1187     cur->doc = cur;
1188     cur->parseFlags = 0;
1189     cur->properties = XML_DOC_USERBUILT;
1190     /*
1191      * The in memory encoding is always UTF8
1192      * This field will never change and would
1193      * be obsolete if not for binary compatibility.
1194      */
1195     cur->charset = XML_CHAR_ENCODING_UTF8;
1196 
1197     if ((__xmlRegisterCallbacks) && (xmlRegisterNodeDefaultValue))
1198 	xmlRegisterNodeDefaultValue((xmlNodePtr)cur);
1199     return(cur);
1200 }
1201 
1202 /**
1203  * xmlFreeDoc:
1204  * @cur:  pointer to the document
1205  *
1206  * Free up all the structures used by a document, tree included.
1207  */
1208 void
xmlFreeDoc(xmlDocPtr cur)1209 xmlFreeDoc(xmlDocPtr cur) {
1210     xmlDtdPtr extSubset, intSubset;
1211     xmlDictPtr dict = NULL;
1212 
1213     if (cur == NULL) {
1214 #ifdef DEBUG_TREE
1215         xmlGenericError(xmlGenericErrorContext,
1216 		"xmlFreeDoc : document == NULL\n");
1217 #endif
1218 	return;
1219     }
1220 #ifdef LIBXML_DEBUG_RUNTIME
1221 #ifdef LIBXML_DEBUG_ENABLED
1222     xmlDebugCheckDocument(stderr, cur);
1223 #endif
1224 #endif
1225 
1226     if (cur != NULL) dict = cur->dict;
1227 
1228     if ((__xmlRegisterCallbacks) && (xmlDeregisterNodeDefaultValue))
1229 	xmlDeregisterNodeDefaultValue((xmlNodePtr)cur);
1230 
1231     /*
1232      * Do this before freeing the children list to avoid ID lookups
1233      */
1234     if (cur->ids != NULL) xmlFreeIDTable((xmlIDTablePtr) cur->ids);
1235     cur->ids = NULL;
1236     if (cur->refs != NULL) xmlFreeRefTable((xmlRefTablePtr) cur->refs);
1237     cur->refs = NULL;
1238     extSubset = cur->extSubset;
1239     intSubset = cur->intSubset;
1240     if (intSubset == extSubset)
1241 	extSubset = NULL;
1242     if (extSubset != NULL) {
1243 	xmlUnlinkNode((xmlNodePtr) cur->extSubset);
1244 	cur->extSubset = NULL;
1245 	xmlFreeDtd(extSubset);
1246     }
1247     if (intSubset != NULL) {
1248 	xmlUnlinkNode((xmlNodePtr) cur->intSubset);
1249 	cur->intSubset = NULL;
1250 	xmlFreeDtd(intSubset);
1251     }
1252 
1253     if (cur->children != NULL) xmlFreeNodeList(cur->children);
1254     if (cur->oldNs != NULL) xmlFreeNsList(cur->oldNs);
1255 
1256     DICT_FREE(cur->version)
1257     DICT_FREE(cur->name)
1258     DICT_FREE(cur->encoding)
1259     DICT_FREE(cur->URL)
1260     xmlFree(cur);
1261     if (dict) xmlDictFree(dict);
1262 }
1263 
1264 /**
1265  * xmlStringLenGetNodeList:
1266  * @doc:  the document
1267  * @value:  the value of the text
1268  * @len:  the length of the string value
1269  *
1270  * Parse the value string and build the node list associated. Should
1271  * produce a flat tree with only TEXTs and ENTITY_REFs.
1272  * Returns a pointer to the first child
1273  */
1274 xmlNodePtr
xmlStringLenGetNodeList(const xmlDoc * doc,const xmlChar * value,int len)1275 xmlStringLenGetNodeList(const xmlDoc *doc, const xmlChar *value, int len) {
1276     xmlNodePtr ret = NULL, last = NULL;
1277     xmlNodePtr node;
1278     xmlChar *val;
1279     const xmlChar *cur, *end;
1280     const xmlChar *q;
1281     xmlEntityPtr ent;
1282     xmlBufPtr buf;
1283 
1284     if (value == NULL) return(NULL);
1285     cur = value;
1286     end = cur + len;
1287 
1288     buf = xmlBufCreateSize(0);
1289     if (buf == NULL) return(NULL);
1290     xmlBufSetAllocationScheme(buf, XML_BUFFER_ALLOC_HYBRID);
1291 
1292     q = cur;
1293     while ((cur < end) && (*cur != 0)) {
1294 	if (cur[0] == '&') {
1295 	    int charval = 0;
1296 	    xmlChar tmp;
1297 
1298 	    /*
1299 	     * Save the current text.
1300 	     */
1301             if (cur != q) {
1302 		if (xmlBufAdd(buf, q, cur - q))
1303 		    goto out;
1304 	    }
1305 	    q = cur;
1306 	    if ((cur + 2 < end) && (cur[1] == '#') && (cur[2] == 'x')) {
1307 		cur += 3;
1308 		if (cur < end)
1309 		    tmp = *cur;
1310 		else
1311 		    tmp = 0;
1312 		while (tmp != ';') { /* Non input consuming loop */
1313                     /*
1314                      * If you find an integer overflow here when fuzzing,
1315                      * the bug is probably elsewhere. This function should
1316                      * only receive entities that were already validated by
1317                      * the parser, typically by xmlParseAttValueComplex
1318                      * calling xmlStringDecodeEntities.
1319                      *
1320                      * So it's better *not* to check for overflow to
1321                      * potentially discover new bugs.
1322                      */
1323 		    if ((tmp >= '0') && (tmp <= '9'))
1324 			charval = charval * 16 + (tmp - '0');
1325 		    else if ((tmp >= 'a') && (tmp <= 'f'))
1326 			charval = charval * 16 + (tmp - 'a') + 10;
1327 		    else if ((tmp >= 'A') && (tmp <= 'F'))
1328 			charval = charval * 16 + (tmp - 'A') + 10;
1329 		    else {
1330 			xmlTreeErr(XML_TREE_INVALID_HEX, (xmlNodePtr) doc,
1331 			           NULL);
1332 			charval = 0;
1333 			break;
1334 		    }
1335 		    cur++;
1336 		    if (cur < end)
1337 			tmp = *cur;
1338 		    else
1339 			tmp = 0;
1340 		}
1341 		if (tmp == ';')
1342 		    cur++;
1343 		q = cur;
1344 	    } else if ((cur + 1 < end) && (cur[1] == '#')) {
1345 		cur += 2;
1346 		if (cur < end)
1347 		    tmp = *cur;
1348 		else
1349 		    tmp = 0;
1350 		while (tmp != ';') { /* Non input consuming loops */
1351                     /* Don't check for integer overflow, see above. */
1352 		    if ((tmp >= '0') && (tmp <= '9'))
1353 			charval = charval * 10 + (tmp - '0');
1354 		    else {
1355 			xmlTreeErr(XML_TREE_INVALID_DEC, (xmlNodePtr) doc,
1356 			           NULL);
1357 			charval = 0;
1358 			break;
1359 		    }
1360 		    cur++;
1361 		    if (cur < end)
1362 			tmp = *cur;
1363 		    else
1364 			tmp = 0;
1365 		}
1366 		if (tmp == ';')
1367 		    cur++;
1368 		q = cur;
1369 	    } else {
1370 		/*
1371 		 * Read the entity string
1372 		 */
1373 		cur++;
1374 		q = cur;
1375 		while ((cur < end) && (*cur != 0) && (*cur != ';')) cur++;
1376 		if ((cur >= end) || (*cur == 0)) {
1377 		    xmlTreeErr(XML_TREE_UNTERMINATED_ENTITY, (xmlNodePtr) doc,
1378 		               (const char *) q);
1379 		    goto out;
1380 		}
1381 		if (cur != q) {
1382 		    /*
1383 		     * Predefined entities don't generate nodes
1384 		     */
1385 		    val = xmlStrndup(q, cur - q);
1386 		    ent = xmlGetDocEntity(doc, val);
1387 		    if ((ent != NULL) &&
1388 			(ent->etype == XML_INTERNAL_PREDEFINED_ENTITY)) {
1389 
1390 			if (xmlBufCat(buf, ent->content))
1391 			    goto out;
1392 
1393 		    } else {
1394 			/*
1395 			 * Flush buffer so far
1396 			 */
1397 			if (!xmlBufIsEmpty(buf)) {
1398 			    node = xmlNewDocText(doc, NULL);
1399 			    if (node == NULL) {
1400 				if (val != NULL) xmlFree(val);
1401 				goto out;
1402 			    }
1403 			    node->content = xmlBufDetach(buf);
1404 
1405 			    if (last == NULL) {
1406 				last = ret = node;
1407 			    } else {
1408 				last = xmlAddNextSibling(last, node);
1409 			    }
1410 			}
1411 
1412 			/*
1413 			 * Create a new REFERENCE_REF node
1414 			 */
1415 			node = xmlNewReference(doc, val);
1416 			if (node == NULL) {
1417 			    if (val != NULL) xmlFree(val);
1418 			    goto out;
1419 			}
1420 			else if ((ent != NULL) && (ent->children == NULL)) {
1421 			    xmlNodePtr temp;
1422 
1423                             /* Set to non-NULL value to avoid recursion. */
1424 			    ent->children = (xmlNodePtr) -1;
1425 			    ent->children = xmlStringGetNodeList(doc,
1426 				    (const xmlChar*)node->content);
1427 			    ent->owner = 1;
1428 			    temp = ent->children;
1429 			    while (temp) {
1430 				temp->parent = (xmlNodePtr)ent;
1431 				ent->last = temp;
1432 				temp = temp->next;
1433 			    }
1434 			}
1435 			if (last == NULL) {
1436 			    last = ret = node;
1437 			} else {
1438 			    last = xmlAddNextSibling(last, node);
1439 			}
1440 		    }
1441 		    xmlFree(val);
1442 		}
1443 		cur++;
1444 		q = cur;
1445 	    }
1446 	    if (charval != 0) {
1447 		xmlChar buffer[10];
1448 		int l;
1449 
1450 		l = xmlCopyCharMultiByte(buffer, charval);
1451 		buffer[l] = 0;
1452 
1453 		if (xmlBufCat(buf, buffer))
1454 		    goto out;
1455 		charval = 0;
1456 	    }
1457 	} else
1458 	    cur++;
1459     }
1460 
1461     if (cur != q) {
1462         /*
1463 	 * Handle the last piece of text.
1464 	 */
1465 	if (xmlBufAdd(buf, q, cur - q))
1466 	    goto out;
1467     }
1468 
1469     if (!xmlBufIsEmpty(buf)) {
1470 	node = xmlNewDocText(doc, NULL);
1471 	if (node == NULL) goto out;
1472 	node->content = xmlBufDetach(buf);
1473 
1474 	if (last == NULL) {
1475 	    ret = node;
1476 	} else {
1477 	    xmlAddNextSibling(last, node);
1478 	}
1479     } else if (ret == NULL) {
1480         ret = xmlNewDocText(doc, BAD_CAST "");
1481     }
1482 
1483 out:
1484     xmlBufFree(buf);
1485     return(ret);
1486 }
1487 
1488 /**
1489  * xmlStringGetNodeList:
1490  * @doc:  the document
1491  * @value:  the value of the attribute
1492  *
1493  * Parse the value string and build the node list associated. Should
1494  * produce a flat tree with only TEXTs and ENTITY_REFs.
1495  * Returns a pointer to the first child
1496  */
1497 xmlNodePtr
xmlStringGetNodeList(const xmlDoc * doc,const xmlChar * value)1498 xmlStringGetNodeList(const xmlDoc *doc, const xmlChar *value) {
1499     xmlNodePtr ret = NULL, last = NULL;
1500     xmlNodePtr node;
1501     xmlChar *val;
1502     const xmlChar *cur = value;
1503     const xmlChar *q;
1504     xmlEntityPtr ent;
1505     xmlBufPtr buf;
1506 
1507     if (value == NULL) return(NULL);
1508 
1509     buf = xmlBufCreateSize(0);
1510     if (buf == NULL) return(NULL);
1511     xmlBufSetAllocationScheme(buf, XML_BUFFER_ALLOC_HYBRID);
1512 
1513     q = cur;
1514     while (*cur != 0) {
1515 	if (cur[0] == '&') {
1516 	    int charval = 0;
1517 	    xmlChar tmp;
1518 
1519 	    /*
1520 	     * Save the current text.
1521 	     */
1522             if (cur != q) {
1523 		if (xmlBufAdd(buf, q, cur - q))
1524 		    goto out;
1525 	    }
1526 	    q = cur;
1527 	    if ((cur[1] == '#') && (cur[2] == 'x')) {
1528 		cur += 3;
1529 		tmp = *cur;
1530 		while (tmp != ';') { /* Non input consuming loop */
1531                     /* Don't check for integer overflow, see above. */
1532 		    if ((tmp >= '0') && (tmp <= '9'))
1533 			charval = charval * 16 + (tmp - '0');
1534 		    else if ((tmp >= 'a') && (tmp <= 'f'))
1535 			charval = charval * 16 + (tmp - 'a') + 10;
1536 		    else if ((tmp >= 'A') && (tmp <= 'F'))
1537 			charval = charval * 16 + (tmp - 'A') + 10;
1538 		    else {
1539 			xmlTreeErr(XML_TREE_INVALID_HEX, (xmlNodePtr) doc,
1540 			           NULL);
1541 			charval = 0;
1542 			break;
1543 		    }
1544 		    cur++;
1545 		    tmp = *cur;
1546 		}
1547 		if (tmp == ';')
1548 		    cur++;
1549 		q = cur;
1550 	    } else if  (cur[1] == '#') {
1551 		cur += 2;
1552 		tmp = *cur;
1553 		while (tmp != ';') { /* Non input consuming loops */
1554                     /* Don't check for integer overflow, see above. */
1555 		    if ((tmp >= '0') && (tmp <= '9'))
1556 			charval = charval * 10 + (tmp - '0');
1557 		    else {
1558 			xmlTreeErr(XML_TREE_INVALID_DEC, (xmlNodePtr) doc,
1559 			           NULL);
1560 			charval = 0;
1561 			break;
1562 		    }
1563 		    cur++;
1564 		    tmp = *cur;
1565 		}
1566 		if (tmp == ';')
1567 		    cur++;
1568 		q = cur;
1569 	    } else {
1570 		/*
1571 		 * Read the entity string
1572 		 */
1573 		cur++;
1574 		q = cur;
1575 		while ((*cur != 0) && (*cur != ';')) cur++;
1576 		if (*cur == 0) {
1577 		    xmlTreeErr(XML_TREE_UNTERMINATED_ENTITY,
1578 		               (xmlNodePtr) doc, (const char *) q);
1579 		    goto out;
1580 		}
1581 		if (cur != q) {
1582 		    /*
1583 		     * Predefined entities don't generate nodes
1584 		     */
1585 		    val = xmlStrndup(q, cur - q);
1586 		    ent = xmlGetDocEntity(doc, val);
1587 		    if ((ent != NULL) &&
1588 			(ent->etype == XML_INTERNAL_PREDEFINED_ENTITY)) {
1589 
1590 			if (xmlBufCat(buf, ent->content))
1591 			    goto out;
1592 
1593 		    } else {
1594 			/*
1595 			 * Flush buffer so far
1596 			 */
1597 			if (!xmlBufIsEmpty(buf)) {
1598 			    node = xmlNewDocText(doc, NULL);
1599 			    if (node == NULL) {
1600 				if (val != NULL) xmlFree(val);
1601 				goto out;
1602 			    }
1603 			    node->content = xmlBufDetach(buf);
1604 
1605 			    if (last == NULL) {
1606 				last = ret = node;
1607 			    } else {
1608 				last = xmlAddNextSibling(last, node);
1609 			    }
1610 			}
1611 
1612 			/*
1613 			 * Create a new REFERENCE_REF node
1614 			 */
1615 			node = xmlNewReference(doc, val);
1616 			if (node == NULL) {
1617 			    if (val != NULL) xmlFree(val);
1618 			    goto out;
1619 			}
1620 			else if ((ent != NULL) && (ent->children == NULL)) {
1621 			    xmlNodePtr temp;
1622 
1623                             /* Set to non-NULL value to avoid recursion. */
1624 			    ent->children = (xmlNodePtr) -1;
1625 			    ent->children = xmlStringGetNodeList(doc,
1626 				    (const xmlChar*)node->content);
1627 			    ent->owner = 1;
1628 			    temp = ent->children;
1629 			    while (temp) {
1630 				temp->parent = (xmlNodePtr)ent;
1631 				ent->last = temp;
1632 				temp = temp->next;
1633 			    }
1634 			}
1635 			if (last == NULL) {
1636 			    last = ret = node;
1637 			} else {
1638 			    last = xmlAddNextSibling(last, node);
1639 			}
1640 		    }
1641 		    xmlFree(val);
1642 		}
1643 		cur++;
1644 		q = cur;
1645 	    }
1646 	    if (charval != 0) {
1647 		xmlChar buffer[10];
1648 		int len;
1649 
1650 		len = xmlCopyCharMultiByte(buffer, charval);
1651 		buffer[len] = 0;
1652 
1653 		if (xmlBufCat(buf, buffer))
1654 		    goto out;
1655 		charval = 0;
1656 	    }
1657 	} else
1658 	    cur++;
1659     }
1660     if ((cur != q) || (ret == NULL)) {
1661         /*
1662 	 * Handle the last piece of text.
1663 	 */
1664 	xmlBufAdd(buf, q, cur - q);
1665     }
1666 
1667     if (!xmlBufIsEmpty(buf)) {
1668 	node = xmlNewDocText(doc, NULL);
1669         if (node == NULL) {
1670             xmlBufFree(buf);
1671             return(NULL);
1672         }
1673 	node->content = xmlBufDetach(buf);
1674 
1675 	if (last == NULL) {
1676 	    ret = node;
1677 	} else {
1678 	    xmlAddNextSibling(last, node);
1679 	}
1680     }
1681 
1682 out:
1683     xmlBufFree(buf);
1684     return(ret);
1685 }
1686 
1687 /**
1688  * xmlNodeListGetString:
1689  * @doc:  the document
1690  * @list:  a Node list
1691  * @inLine:  should we replace entity contents or show their external form
1692  *
1693  * Build the string equivalent to the text contained in the Node list
1694  * made of TEXTs and ENTITY_REFs
1695  *
1696  * Returns a pointer to the string copy, the caller must free it with xmlFree().
1697  */
1698 xmlChar *
xmlNodeListGetString(xmlDocPtr doc,const xmlNode * list,int inLine)1699 xmlNodeListGetString(xmlDocPtr doc, const xmlNode *list, int inLine)
1700 {
1701     const xmlNode *node = list;
1702     xmlChar *ret = NULL;
1703     xmlEntityPtr ent;
1704     int attr;
1705 
1706     if (list == NULL)
1707         return (NULL);
1708     if ((list->parent != NULL) && (list->parent->type == XML_ATTRIBUTE_NODE))
1709         attr = 1;
1710     else
1711         attr = 0;
1712 
1713     while (node != NULL) {
1714         if ((node->type == XML_TEXT_NODE) ||
1715             (node->type == XML_CDATA_SECTION_NODE)) {
1716             if (inLine) {
1717                 ret = xmlStrcat(ret, node->content);
1718             } else {
1719                 xmlChar *buffer;
1720 
1721 		if (attr)
1722 		    buffer = xmlEncodeAttributeEntities(doc, node->content);
1723 		else
1724 		    buffer = xmlEncodeEntitiesReentrant(doc, node->content);
1725                 if (buffer != NULL) {
1726                     ret = xmlStrcat(ret, buffer);
1727                     xmlFree(buffer);
1728                 }
1729             }
1730         } else if (node->type == XML_ENTITY_REF_NODE) {
1731             if (inLine) {
1732                 ent = xmlGetDocEntity(doc, node->name);
1733                 if (ent != NULL) {
1734                     xmlChar *buffer;
1735 
1736                     /* an entity content can be any "well balanced chunk",
1737                      * i.e. the result of the content [43] production:
1738                      * http://www.w3.org/TR/REC-xml#NT-content.
1739                      * So it can contain text, CDATA section or nested
1740                      * entity reference nodes (among others).
1741                      * -> we recursive  call xmlNodeListGetString()
1742                      * which handles these types */
1743                     buffer = xmlNodeListGetString(doc, ent->children, 1);
1744                     if (buffer != NULL) {
1745                         ret = xmlStrcat(ret, buffer);
1746                         xmlFree(buffer);
1747                     }
1748                 } else {
1749                     ret = xmlStrcat(ret, node->content);
1750                 }
1751             } else {
1752                 xmlChar buf[2];
1753 
1754                 buf[0] = '&';
1755                 buf[1] = 0;
1756                 ret = xmlStrncat(ret, buf, 1);
1757                 ret = xmlStrcat(ret, node->name);
1758                 buf[0] = ';';
1759                 buf[1] = 0;
1760                 ret = xmlStrncat(ret, buf, 1);
1761             }
1762         }
1763 #if 0
1764         else {
1765             xmlGenericError(xmlGenericErrorContext,
1766                             "xmlGetNodeListString : invalid node type %d\n",
1767                             node->type);
1768         }
1769 #endif
1770         node = node->next;
1771     }
1772     return (ret);
1773 }
1774 
1775 #ifdef LIBXML_TREE_ENABLED
1776 /**
1777  * xmlNodeListGetRawString:
1778  * @doc:  the document
1779  * @list:  a Node list
1780  * @inLine:  should we replace entity contents or show their external form
1781  *
1782  * Builds the string equivalent to the text contained in the Node list
1783  * made of TEXTs and ENTITY_REFs, contrary to xmlNodeListGetString()
1784  * this function doesn't do any character encoding handling.
1785  *
1786  * Returns a pointer to the string copy, the caller must free it with xmlFree().
1787  */
1788 xmlChar *
xmlNodeListGetRawString(const xmlDoc * doc,const xmlNode * list,int inLine)1789 xmlNodeListGetRawString(const xmlDoc *doc, const xmlNode *list, int inLine)
1790 {
1791     const xmlNode *node = list;
1792     xmlChar *ret = NULL;
1793     xmlEntityPtr ent;
1794 
1795     if (list == NULL)
1796         return (NULL);
1797 
1798     while (node != NULL) {
1799         if ((node->type == XML_TEXT_NODE) ||
1800             (node->type == XML_CDATA_SECTION_NODE)) {
1801             if (inLine) {
1802                 ret = xmlStrcat(ret, node->content);
1803             } else {
1804                 xmlChar *buffer;
1805 
1806                 buffer = xmlEncodeSpecialChars(doc, node->content);
1807                 if (buffer != NULL) {
1808                     ret = xmlStrcat(ret, buffer);
1809                     xmlFree(buffer);
1810                 }
1811             }
1812         } else if (node->type == XML_ENTITY_REF_NODE) {
1813             if (inLine) {
1814                 ent = xmlGetDocEntity(doc, node->name);
1815                 if (ent != NULL) {
1816                     xmlChar *buffer;
1817 
1818                     /* an entity content can be any "well balanced chunk",
1819                      * i.e. the result of the content [43] production:
1820                      * http://www.w3.org/TR/REC-xml#NT-content.
1821                      * So it can contain text, CDATA section or nested
1822                      * entity reference nodes (among others).
1823                      * -> we recursive  call xmlNodeListGetRawString()
1824                      * which handles these types */
1825                     buffer =
1826                         xmlNodeListGetRawString(doc, ent->children, 1);
1827                     if (buffer != NULL) {
1828                         ret = xmlStrcat(ret, buffer);
1829                         xmlFree(buffer);
1830                     }
1831                 } else {
1832                     ret = xmlStrcat(ret, node->content);
1833                 }
1834             } else {
1835                 xmlChar buf[2];
1836 
1837                 buf[0] = '&';
1838                 buf[1] = 0;
1839                 ret = xmlStrncat(ret, buf, 1);
1840                 ret = xmlStrcat(ret, node->name);
1841                 buf[0] = ';';
1842                 buf[1] = 0;
1843                 ret = xmlStrncat(ret, buf, 1);
1844             }
1845         }
1846 #if 0
1847         else {
1848             xmlGenericError(xmlGenericErrorContext,
1849                             "xmlGetNodeListString : invalid node type %d\n",
1850                             node->type);
1851         }
1852 #endif
1853         node = node->next;
1854     }
1855     return (ret);
1856 }
1857 #endif /* LIBXML_TREE_ENABLED */
1858 
1859 static xmlAttrPtr
xmlNewPropInternal(xmlNodePtr node,xmlNsPtr ns,const xmlChar * name,const xmlChar * value,int eatname)1860 xmlNewPropInternal(xmlNodePtr node, xmlNsPtr ns,
1861                    const xmlChar * name, const xmlChar * value,
1862                    int eatname)
1863 {
1864     xmlAttrPtr cur;
1865     xmlDocPtr doc = NULL;
1866 
1867     if ((node != NULL) && (node->type != XML_ELEMENT_NODE)) {
1868         if ((eatname == 1) &&
1869 	    ((node->doc == NULL) ||
1870 	     (!(xmlDictOwns(node->doc->dict, name)))))
1871             xmlFree((xmlChar *) name);
1872         return (NULL);
1873     }
1874 
1875     /*
1876      * Allocate a new property and fill the fields.
1877      */
1878     cur = (xmlAttrPtr) xmlMalloc(sizeof(xmlAttr));
1879     if (cur == NULL) {
1880         if ((eatname == 1) &&
1881 	    ((node == NULL) || (node->doc == NULL) ||
1882 	     (!(xmlDictOwns(node->doc->dict, name)))))
1883             xmlFree((xmlChar *) name);
1884         xmlTreeErrMemory("building attribute");
1885         return (NULL);
1886     }
1887     memset(cur, 0, sizeof(xmlAttr));
1888     cur->type = XML_ATTRIBUTE_NODE;
1889 
1890     cur->parent = node;
1891     if (node != NULL) {
1892         doc = node->doc;
1893         cur->doc = doc;
1894     }
1895     cur->ns = ns;
1896 
1897     if (eatname == 0) {
1898         if ((doc != NULL) && (doc->dict != NULL))
1899             cur->name = (xmlChar *) xmlDictLookup(doc->dict, name, -1);
1900         else
1901             cur->name = xmlStrdup(name);
1902     } else
1903         cur->name = name;
1904 
1905     if (value != NULL) {
1906         xmlNodePtr tmp;
1907 
1908         cur->children = xmlNewDocText(doc, value);
1909         cur->last = NULL;
1910         tmp = cur->children;
1911         while (tmp != NULL) {
1912             tmp->parent = (xmlNodePtr) cur;
1913             if (tmp->next == NULL)
1914                 cur->last = tmp;
1915             tmp = tmp->next;
1916         }
1917     }
1918 
1919     /*
1920      * Add it at the end to preserve parsing order ...
1921      */
1922     if (node != NULL) {
1923         if (node->properties == NULL) {
1924             node->properties = cur;
1925         } else {
1926             xmlAttrPtr prev = node->properties;
1927 
1928             while (prev->next != NULL)
1929                 prev = prev->next;
1930             prev->next = cur;
1931             cur->prev = prev;
1932         }
1933     }
1934 
1935     if ((value != NULL) && (node != NULL) &&
1936         (xmlIsID(node->doc, node, cur) == 1))
1937         xmlAddID(NULL, node->doc, value, cur);
1938 
1939     if ((__xmlRegisterCallbacks) && (xmlRegisterNodeDefaultValue))
1940         xmlRegisterNodeDefaultValue((xmlNodePtr) cur);
1941     return (cur);
1942 }
1943 
1944 #if defined(LIBXML_TREE_ENABLED) || defined(LIBXML_HTML_ENABLED) || \
1945     defined(LIBXML_SCHEMAS_ENABLED)
1946 /**
1947  * xmlNewProp:
1948  * @node:  the holding node
1949  * @name:  the name of the attribute
1950  * @value:  the value of the attribute
1951  *
1952  * Create a new property carried by a node.
1953  * Returns a pointer to the attribute
1954  */
1955 xmlAttrPtr
xmlNewProp(xmlNodePtr node,const xmlChar * name,const xmlChar * value)1956 xmlNewProp(xmlNodePtr node, const xmlChar *name, const xmlChar *value) {
1957 
1958     if (name == NULL) {
1959 #ifdef DEBUG_TREE
1960         xmlGenericError(xmlGenericErrorContext,
1961 		"xmlNewProp : name == NULL\n");
1962 #endif
1963 	return(NULL);
1964     }
1965 
1966 	return xmlNewPropInternal(node, NULL, name, value, 0);
1967 }
1968 #endif /* LIBXML_TREE_ENABLED */
1969 
1970 /**
1971  * xmlNewNsProp:
1972  * @node:  the holding node
1973  * @ns:  the namespace
1974  * @name:  the name of the attribute
1975  * @value:  the value of the attribute
1976  *
1977  * Create a new property tagged with a namespace and carried by a node.
1978  * Returns a pointer to the attribute
1979  */
1980 xmlAttrPtr
xmlNewNsProp(xmlNodePtr node,xmlNsPtr ns,const xmlChar * name,const xmlChar * value)1981 xmlNewNsProp(xmlNodePtr node, xmlNsPtr ns, const xmlChar *name,
1982            const xmlChar *value) {
1983 
1984     if (name == NULL) {
1985 #ifdef DEBUG_TREE
1986         xmlGenericError(xmlGenericErrorContext,
1987 		"xmlNewNsProp : name == NULL\n");
1988 #endif
1989 	return(NULL);
1990     }
1991 
1992     return xmlNewPropInternal(node, ns, name, value, 0);
1993 }
1994 
1995 /**
1996  * xmlNewNsPropEatName:
1997  * @node:  the holding node
1998  * @ns:  the namespace
1999  * @name:  the name of the attribute
2000  * @value:  the value of the attribute
2001  *
2002  * Create a new property tagged with a namespace and carried by a node.
2003  * Returns a pointer to the attribute
2004  */
2005 xmlAttrPtr
xmlNewNsPropEatName(xmlNodePtr node,xmlNsPtr ns,xmlChar * name,const xmlChar * value)2006 xmlNewNsPropEatName(xmlNodePtr node, xmlNsPtr ns, xmlChar *name,
2007            const xmlChar *value) {
2008 
2009     if (name == NULL) {
2010 #ifdef DEBUG_TREE
2011         xmlGenericError(xmlGenericErrorContext,
2012 		"xmlNewNsPropEatName : name == NULL\n");
2013 #endif
2014 	return(NULL);
2015     }
2016 
2017     return xmlNewPropInternal(node, ns, name, value, 1);
2018 }
2019 
2020 /**
2021  * xmlNewDocProp:
2022  * @doc:  the document
2023  * @name:  the name of the attribute
2024  * @value:  the value of the attribute
2025  *
2026  * Create a new property carried by a document.
2027  * NOTE: @value is supposed to be a piece of XML CDATA, so it allows entity
2028  *       references, but XML special chars need to be escaped first by using
2029  *       xmlEncodeEntitiesReentrant(). Use xmlNewProp() if you don't need
2030  *       entities support.
2031  *
2032  * Returns a pointer to the attribute
2033  */
2034 xmlAttrPtr
xmlNewDocProp(xmlDocPtr doc,const xmlChar * name,const xmlChar * value)2035 xmlNewDocProp(xmlDocPtr doc, const xmlChar *name, const xmlChar *value) {
2036     xmlAttrPtr cur;
2037 
2038     if (name == NULL) {
2039 #ifdef DEBUG_TREE
2040         xmlGenericError(xmlGenericErrorContext,
2041 		"xmlNewDocProp : name == NULL\n");
2042 #endif
2043 	return(NULL);
2044     }
2045 
2046     /*
2047      * Allocate a new property and fill the fields.
2048      */
2049     cur = (xmlAttrPtr) xmlMalloc(sizeof(xmlAttr));
2050     if (cur == NULL) {
2051 	xmlTreeErrMemory("building attribute");
2052 	return(NULL);
2053     }
2054     memset(cur, 0, sizeof(xmlAttr));
2055     cur->type = XML_ATTRIBUTE_NODE;
2056 
2057     if ((doc != NULL) && (doc->dict != NULL))
2058 	cur->name = xmlDictLookup(doc->dict, name, -1);
2059     else
2060 	cur->name = xmlStrdup(name);
2061     cur->doc = doc;
2062     if (value != NULL) {
2063 	xmlNodePtr tmp;
2064 
2065 	cur->children = xmlStringGetNodeList(doc, value);
2066 	cur->last = NULL;
2067 
2068 	tmp = cur->children;
2069 	while (tmp != NULL) {
2070 	    tmp->parent = (xmlNodePtr) cur;
2071 	    if (tmp->next == NULL)
2072 		cur->last = tmp;
2073 	    tmp = tmp->next;
2074 	}
2075     }
2076 
2077     if ((__xmlRegisterCallbacks) && (xmlRegisterNodeDefaultValue))
2078 	xmlRegisterNodeDefaultValue((xmlNodePtr)cur);
2079     return(cur);
2080 }
2081 
2082 /**
2083  * xmlFreePropList:
2084  * @cur:  the first property in the list
2085  *
2086  * Free a property and all its siblings, all the children are freed too.
2087  */
2088 void
xmlFreePropList(xmlAttrPtr cur)2089 xmlFreePropList(xmlAttrPtr cur) {
2090     xmlAttrPtr next;
2091     if (cur == NULL) return;
2092     while (cur != NULL) {
2093         next = cur->next;
2094         xmlFreeProp(cur);
2095 	cur = next;
2096     }
2097 }
2098 
2099 /**
2100  * xmlFreeProp:
2101  * @cur:  an attribute
2102  *
2103  * Free one attribute, all the content is freed too
2104  */
2105 void
xmlFreeProp(xmlAttrPtr cur)2106 xmlFreeProp(xmlAttrPtr cur) {
2107     xmlDictPtr dict = NULL;
2108     if (cur == NULL) return;
2109 
2110     if (cur->doc != NULL) dict = cur->doc->dict;
2111 
2112     if ((__xmlRegisterCallbacks) && (xmlDeregisterNodeDefaultValue))
2113 	xmlDeregisterNodeDefaultValue((xmlNodePtr)cur);
2114 
2115     /* Check for ID removal -> leading to invalid references ! */
2116     if ((cur->doc != NULL) && (cur->atype == XML_ATTRIBUTE_ID)) {
2117 	    xmlRemoveID(cur->doc, cur);
2118     }
2119     if (cur->children != NULL) xmlFreeNodeList(cur->children);
2120     DICT_FREE(cur->name)
2121     xmlFree(cur);
2122 }
2123 
2124 /**
2125  * xmlRemoveProp:
2126  * @cur:  an attribute
2127  *
2128  * Unlink and free one attribute, all the content is freed too
2129  * Note this doesn't work for namespace definition attributes
2130  *
2131  * Returns 0 if success and -1 in case of error.
2132  */
2133 int
xmlRemoveProp(xmlAttrPtr cur)2134 xmlRemoveProp(xmlAttrPtr cur) {
2135     xmlAttrPtr tmp;
2136     if (cur == NULL) {
2137 #ifdef DEBUG_TREE
2138         xmlGenericError(xmlGenericErrorContext,
2139 		"xmlRemoveProp : cur == NULL\n");
2140 #endif
2141 	return(-1);
2142     }
2143     if (cur->parent == NULL) {
2144 #ifdef DEBUG_TREE
2145         xmlGenericError(xmlGenericErrorContext,
2146 		"xmlRemoveProp : cur->parent == NULL\n");
2147 #endif
2148 	return(-1);
2149     }
2150     tmp = cur->parent->properties;
2151     if (tmp == cur) {
2152         cur->parent->properties = cur->next;
2153 		if (cur->next != NULL)
2154 			cur->next->prev = NULL;
2155 	xmlFreeProp(cur);
2156 	return(0);
2157     }
2158     while (tmp != NULL) {
2159 	if (tmp->next == cur) {
2160 	    tmp->next = cur->next;
2161 	    if (tmp->next != NULL)
2162 		tmp->next->prev = tmp;
2163 	    xmlFreeProp(cur);
2164 	    return(0);
2165 	}
2166         tmp = tmp->next;
2167     }
2168 #ifdef DEBUG_TREE
2169     xmlGenericError(xmlGenericErrorContext,
2170 	    "xmlRemoveProp : attribute not owned by its node\n");
2171 #endif
2172     return(-1);
2173 }
2174 
2175 /**
2176  * xmlNewDocPI:
2177  * @doc:  the target document
2178  * @name:  the processing instruction name
2179  * @content:  the PI content
2180  *
2181  * Creation of a processing instruction element.
2182  * Returns a pointer to the new node object.
2183  */
2184 xmlNodePtr
xmlNewDocPI(xmlDocPtr doc,const xmlChar * name,const xmlChar * content)2185 xmlNewDocPI(xmlDocPtr doc, const xmlChar *name, const xmlChar *content) {
2186     xmlNodePtr cur;
2187 
2188     if (name == NULL) {
2189 #ifdef DEBUG_TREE
2190         xmlGenericError(xmlGenericErrorContext,
2191 		"xmlNewPI : name == NULL\n");
2192 #endif
2193 	return(NULL);
2194     }
2195 
2196     /*
2197      * Allocate a new node and fill the fields.
2198      */
2199     cur = (xmlNodePtr) xmlMalloc(sizeof(xmlNode));
2200     if (cur == NULL) {
2201 	xmlTreeErrMemory("building PI");
2202 	return(NULL);
2203     }
2204     memset(cur, 0, sizeof(xmlNode));
2205     cur->type = XML_PI_NODE;
2206 
2207     if ((doc != NULL) && (doc->dict != NULL))
2208         cur->name = xmlDictLookup(doc->dict, name, -1);
2209     else
2210 	cur->name = xmlStrdup(name);
2211     if (content != NULL) {
2212 	cur->content = xmlStrdup(content);
2213     }
2214     cur->doc = doc;
2215 
2216     if ((__xmlRegisterCallbacks) && (xmlRegisterNodeDefaultValue))
2217 	xmlRegisterNodeDefaultValue((xmlNodePtr)cur);
2218     return(cur);
2219 }
2220 
2221 /**
2222  * xmlNewPI:
2223  * @name:  the processing instruction name
2224  * @content:  the PI content
2225  *
2226  * Creation of a processing instruction element.
2227  * Use xmlDocNewPI preferably to get string interning
2228  *
2229  * Returns a pointer to the new node object.
2230  */
2231 xmlNodePtr
xmlNewPI(const xmlChar * name,const xmlChar * content)2232 xmlNewPI(const xmlChar *name, const xmlChar *content) {
2233     return(xmlNewDocPI(NULL, name, content));
2234 }
2235 
2236 /**
2237  * xmlNewNode:
2238  * @ns:  namespace if any
2239  * @name:  the node name
2240  *
2241  * Creation of a new node element. @ns is optional (NULL).
2242  *
2243  * Returns a pointer to the new node object. Uses xmlStrdup() to make
2244  * copy of @name.
2245  */
2246 xmlNodePtr
xmlNewNode(xmlNsPtr ns,const xmlChar * name)2247 xmlNewNode(xmlNsPtr ns, const xmlChar *name) {
2248     xmlNodePtr cur;
2249 
2250     if (name == NULL) {
2251 #ifdef DEBUG_TREE
2252         xmlGenericError(xmlGenericErrorContext,
2253 		"xmlNewNode : name == NULL\n");
2254 #endif
2255 	return(NULL);
2256     }
2257 
2258     /*
2259      * Allocate a new node and fill the fields.
2260      */
2261     cur = (xmlNodePtr) xmlMalloc(sizeof(xmlNode));
2262     if (cur == NULL) {
2263 	xmlTreeErrMemory("building node");
2264 	return(NULL);
2265     }
2266     memset(cur, 0, sizeof(xmlNode));
2267     cur->type = XML_ELEMENT_NODE;
2268 
2269     cur->name = xmlStrdup(name);
2270     cur->ns = ns;
2271 
2272     if ((__xmlRegisterCallbacks) && (xmlRegisterNodeDefaultValue))
2273 	xmlRegisterNodeDefaultValue(cur);
2274     return(cur);
2275 }
2276 
2277 /**
2278  * xmlNewNodeEatName:
2279  * @ns:  namespace if any
2280  * @name:  the node name
2281  *
2282  * Creation of a new node element. @ns is optional (NULL).
2283  *
2284  * Returns a pointer to the new node object, with pointer @name as
2285  * new node's name. Use xmlNewNode() if a copy of @name string is
2286  * is needed as new node's name.
2287  */
2288 xmlNodePtr
xmlNewNodeEatName(xmlNsPtr ns,xmlChar * name)2289 xmlNewNodeEatName(xmlNsPtr ns, xmlChar *name) {
2290     xmlNodePtr cur;
2291 
2292     if (name == NULL) {
2293 #ifdef DEBUG_TREE
2294         xmlGenericError(xmlGenericErrorContext,
2295 		"xmlNewNode : name == NULL\n");
2296 #endif
2297 	return(NULL);
2298     }
2299 
2300     /*
2301      * Allocate a new node and fill the fields.
2302      */
2303     cur = (xmlNodePtr) xmlMalloc(sizeof(xmlNode));
2304     if (cur == NULL) {
2305 	xmlTreeErrMemory("building node");
2306 	/* we can't check here that name comes from the doc dictionary */
2307 	return(NULL);
2308     }
2309     memset(cur, 0, sizeof(xmlNode));
2310     cur->type = XML_ELEMENT_NODE;
2311 
2312     cur->name = name;
2313     cur->ns = ns;
2314 
2315     if ((__xmlRegisterCallbacks) && (xmlRegisterNodeDefaultValue))
2316 	xmlRegisterNodeDefaultValue((xmlNodePtr)cur);
2317     return(cur);
2318 }
2319 
2320 /**
2321  * xmlNewDocNode:
2322  * @doc:  the document
2323  * @ns:  namespace if any
2324  * @name:  the node name
2325  * @content:  the XML text content if any
2326  *
2327  * Creation of a new node element within a document. @ns and @content
2328  * are optional (NULL).
2329  * NOTE: @content is supposed to be a piece of XML CDATA, so it allow entities
2330  *       references, but XML special chars need to be escaped first by using
2331  *       xmlEncodeEntitiesReentrant(). Use xmlNewDocRawNode() if you don't
2332  *       need entities support.
2333  *
2334  * Returns a pointer to the new node object.
2335  */
2336 xmlNodePtr
xmlNewDocNode(xmlDocPtr doc,xmlNsPtr ns,const xmlChar * name,const xmlChar * content)2337 xmlNewDocNode(xmlDocPtr doc, xmlNsPtr ns,
2338               const xmlChar *name, const xmlChar *content) {
2339     xmlNodePtr cur;
2340 
2341     if ((doc != NULL) && (doc->dict != NULL))
2342         cur = xmlNewNodeEatName(ns, (xmlChar *)
2343 	                        xmlDictLookup(doc->dict, name, -1));
2344     else
2345 	cur = xmlNewNode(ns, name);
2346     if (cur != NULL) {
2347         cur->doc = doc;
2348 	if (content != NULL) {
2349 	    cur->children = xmlStringGetNodeList(doc, content);
2350 	    UPDATE_LAST_CHILD_AND_PARENT(cur)
2351 	}
2352     }
2353 
2354     return(cur);
2355 }
2356 
2357 /**
2358  * xmlNewDocNodeEatName:
2359  * @doc:  the document
2360  * @ns:  namespace if any
2361  * @name:  the node name
2362  * @content:  the XML text content if any
2363  *
2364  * Creation of a new node element within a document. @ns and @content
2365  * are optional (NULL).
2366  * NOTE: @content is supposed to be a piece of XML CDATA, so it allow entities
2367  *       references, but XML special chars need to be escaped first by using
2368  *       xmlEncodeEntitiesReentrant(). Use xmlNewDocRawNode() if you don't
2369  *       need entities support.
2370  *
2371  * Returns a pointer to the new node object.
2372  */
2373 xmlNodePtr
xmlNewDocNodeEatName(xmlDocPtr doc,xmlNsPtr ns,xmlChar * name,const xmlChar * content)2374 xmlNewDocNodeEatName(xmlDocPtr doc, xmlNsPtr ns,
2375               xmlChar *name, const xmlChar *content) {
2376     xmlNodePtr cur;
2377 
2378     cur = xmlNewNodeEatName(ns, name);
2379     if (cur != NULL) {
2380         cur->doc = doc;
2381 	if (content != NULL) {
2382 	    cur->children = xmlStringGetNodeList(doc, content);
2383 	    UPDATE_LAST_CHILD_AND_PARENT(cur)
2384 	}
2385     } else {
2386         /* if name don't come from the doc dictionary free it here */
2387         if ((name != NULL) && (doc != NULL) &&
2388 	    (!(xmlDictOwns(doc->dict, name))))
2389 	    xmlFree(name);
2390     }
2391     return(cur);
2392 }
2393 
2394 #ifdef LIBXML_TREE_ENABLED
2395 /**
2396  * xmlNewDocRawNode:
2397  * @doc:  the document
2398  * @ns:  namespace if any
2399  * @name:  the node name
2400  * @content:  the text content if any
2401  *
2402  * Creation of a new node element within a document. @ns and @content
2403  * are optional (NULL).
2404  *
2405  * Returns a pointer to the new node object.
2406  */
2407 xmlNodePtr
xmlNewDocRawNode(xmlDocPtr doc,xmlNsPtr ns,const xmlChar * name,const xmlChar * content)2408 xmlNewDocRawNode(xmlDocPtr doc, xmlNsPtr ns,
2409                  const xmlChar *name, const xmlChar *content) {
2410     xmlNodePtr cur;
2411 
2412     cur = xmlNewDocNode(doc, ns, name, NULL);
2413     if (cur != NULL) {
2414         cur->doc = doc;
2415 	if (content != NULL) {
2416 	    cur->children = xmlNewDocText(doc, content);
2417 	    UPDATE_LAST_CHILD_AND_PARENT(cur)
2418 	}
2419     }
2420     return(cur);
2421 }
2422 
2423 /**
2424  * xmlNewDocFragment:
2425  * @doc:  the document owning the fragment
2426  *
2427  * Creation of a new Fragment node.
2428  * Returns a pointer to the new node object.
2429  */
2430 xmlNodePtr
xmlNewDocFragment(xmlDocPtr doc)2431 xmlNewDocFragment(xmlDocPtr doc) {
2432     xmlNodePtr cur;
2433 
2434     /*
2435      * Allocate a new DocumentFragment node and fill the fields.
2436      */
2437     cur = (xmlNodePtr) xmlMalloc(sizeof(xmlNode));
2438     if (cur == NULL) {
2439 	xmlTreeErrMemory("building fragment");
2440 	return(NULL);
2441     }
2442     memset(cur, 0, sizeof(xmlNode));
2443     cur->type = XML_DOCUMENT_FRAG_NODE;
2444 
2445     cur->doc = doc;
2446 
2447     if ((__xmlRegisterCallbacks) && (xmlRegisterNodeDefaultValue))
2448 	xmlRegisterNodeDefaultValue(cur);
2449     return(cur);
2450 }
2451 #endif /* LIBXML_TREE_ENABLED */
2452 
2453 /**
2454  * xmlNewText:
2455  * @content:  the text content
2456  *
2457  * Creation of a new text node.
2458  * Returns a pointer to the new node object.
2459  */
2460 xmlNodePtr
xmlNewText(const xmlChar * content)2461 xmlNewText(const xmlChar *content) {
2462     xmlNodePtr cur;
2463 
2464     /*
2465      * Allocate a new node and fill the fields.
2466      */
2467     cur = (xmlNodePtr) xmlMalloc(sizeof(xmlNode));
2468     if (cur == NULL) {
2469 	xmlTreeErrMemory("building text");
2470 	return(NULL);
2471     }
2472     memset(cur, 0, sizeof(xmlNode));
2473     cur->type = XML_TEXT_NODE;
2474 
2475     cur->name = xmlStringText;
2476     if (content != NULL) {
2477 	cur->content = xmlStrdup(content);
2478     }
2479 
2480     if ((__xmlRegisterCallbacks) && (xmlRegisterNodeDefaultValue))
2481 	xmlRegisterNodeDefaultValue(cur);
2482     return(cur);
2483 }
2484 
2485 #ifdef LIBXML_TREE_ENABLED
2486 /**
2487  * xmlNewTextChild:
2488  * @parent:  the parent node
2489  * @ns:  a namespace if any
2490  * @name:  the name of the child
2491  * @content:  the text content of the child if any.
2492  *
2493  * Creation of a new child element, added at the end of @parent children list.
2494  * @ns and @content parameters are optional (NULL). If @ns is NULL, the newly
2495  * created element inherits the namespace of @parent. If @content is non NULL,
2496  * a child TEXT node will be created containing the string @content.
2497  * NOTE: Use xmlNewChild() if @content will contain entities that need to be
2498  * preserved. Use this function, xmlNewTextChild(), if you need to ensure that
2499  * reserved XML chars that might appear in @content, such as the ampersand,
2500  * greater-than or less-than signs, are automatically replaced by their XML
2501  * escaped entity representations.
2502  *
2503  * Returns a pointer to the new node object.
2504  */
2505 xmlNodePtr
xmlNewTextChild(xmlNodePtr parent,xmlNsPtr ns,const xmlChar * name,const xmlChar * content)2506 xmlNewTextChild(xmlNodePtr parent, xmlNsPtr ns,
2507             const xmlChar *name, const xmlChar *content) {
2508     xmlNodePtr cur, prev;
2509 
2510     if (parent == NULL) {
2511 #ifdef DEBUG_TREE
2512         xmlGenericError(xmlGenericErrorContext,
2513 		"xmlNewTextChild : parent == NULL\n");
2514 #endif
2515 	return(NULL);
2516     }
2517 
2518     if (name == NULL) {
2519 #ifdef DEBUG_TREE
2520         xmlGenericError(xmlGenericErrorContext,
2521 		"xmlNewTextChild : name == NULL\n");
2522 #endif
2523 	return(NULL);
2524     }
2525 
2526     /*
2527      * Allocate a new node
2528      */
2529     if (parent->type == XML_ELEMENT_NODE) {
2530 	if (ns == NULL)
2531 	    cur = xmlNewDocRawNode(parent->doc, parent->ns, name, content);
2532 	else
2533 	    cur = xmlNewDocRawNode(parent->doc, ns, name, content);
2534     } else if ((parent->type == XML_DOCUMENT_NODE) ||
2535 	       (parent->type == XML_HTML_DOCUMENT_NODE)) {
2536 	if (ns == NULL)
2537 	    cur = xmlNewDocRawNode((xmlDocPtr) parent, NULL, name, content);
2538 	else
2539 	    cur = xmlNewDocRawNode((xmlDocPtr) parent, ns, name, content);
2540     } else if (parent->type == XML_DOCUMENT_FRAG_NODE) {
2541 	    cur = xmlNewDocRawNode( parent->doc, ns, name, content);
2542     } else {
2543 	return(NULL);
2544     }
2545     if (cur == NULL) return(NULL);
2546 
2547     /*
2548      * add the new element at the end of the children list.
2549      */
2550     cur->type = XML_ELEMENT_NODE;
2551     cur->parent = parent;
2552     cur->doc = parent->doc;
2553     if (parent->children == NULL) {
2554         parent->children = cur;
2555 	parent->last = cur;
2556     } else {
2557         prev = parent->last;
2558 	prev->next = cur;
2559 	cur->prev = prev;
2560 	parent->last = cur;
2561     }
2562 
2563     return(cur);
2564 }
2565 #endif /* LIBXML_TREE_ENABLED */
2566 
2567 /**
2568  * xmlNewCharRef:
2569  * @doc: the document
2570  * @name:  the char ref string, starting with # or "&# ... ;"
2571  *
2572  * Creation of a new character reference node.
2573  * Returns a pointer to the new node object.
2574  */
2575 xmlNodePtr
xmlNewCharRef(xmlDocPtr doc,const xmlChar * name)2576 xmlNewCharRef(xmlDocPtr doc, const xmlChar *name) {
2577     xmlNodePtr cur;
2578 
2579     if (name == NULL)
2580         return(NULL);
2581 
2582     /*
2583      * Allocate a new node and fill the fields.
2584      */
2585     cur = (xmlNodePtr) xmlMalloc(sizeof(xmlNode));
2586     if (cur == NULL) {
2587 	xmlTreeErrMemory("building character reference");
2588 	return(NULL);
2589     }
2590     memset(cur, 0, sizeof(xmlNode));
2591     cur->type = XML_ENTITY_REF_NODE;
2592 
2593     cur->doc = doc;
2594     if (name[0] == '&') {
2595         int len;
2596         name++;
2597 	len = xmlStrlen(name);
2598 	if (name[len - 1] == ';')
2599 	    cur->name = xmlStrndup(name, len - 1);
2600 	else
2601 	    cur->name = xmlStrndup(name, len);
2602     } else
2603 	cur->name = xmlStrdup(name);
2604 
2605     if ((__xmlRegisterCallbacks) && (xmlRegisterNodeDefaultValue))
2606 	xmlRegisterNodeDefaultValue(cur);
2607     return(cur);
2608 }
2609 
2610 /**
2611  * xmlNewReference:
2612  * @doc: the document
2613  * @name:  the reference name, or the reference string with & and ;
2614  *
2615  * Creation of a new reference node.
2616  * Returns a pointer to the new node object.
2617  */
2618 xmlNodePtr
xmlNewReference(const xmlDoc * doc,const xmlChar * name)2619 xmlNewReference(const xmlDoc *doc, const xmlChar *name) {
2620     xmlNodePtr cur;
2621     xmlEntityPtr ent;
2622 
2623     if (name == NULL)
2624         return(NULL);
2625 
2626     /*
2627      * Allocate a new node and fill the fields.
2628      */
2629     cur = (xmlNodePtr) xmlMalloc(sizeof(xmlNode));
2630     if (cur == NULL) {
2631 	xmlTreeErrMemory("building reference");
2632 	return(NULL);
2633     }
2634     memset(cur, 0, sizeof(xmlNode));
2635     cur->type = XML_ENTITY_REF_NODE;
2636 
2637     cur->doc = (xmlDoc *)doc;
2638     if (name[0] == '&') {
2639         int len;
2640         name++;
2641 	len = xmlStrlen(name);
2642 	if (name[len - 1] == ';')
2643 	    cur->name = xmlStrndup(name, len - 1);
2644 	else
2645 	    cur->name = xmlStrndup(name, len);
2646     } else
2647 	cur->name = xmlStrdup(name);
2648 
2649     ent = xmlGetDocEntity(doc, cur->name);
2650     if (ent != NULL) {
2651 	cur->content = ent->content;
2652 	/*
2653 	 * The parent pointer in entity is a DTD pointer and thus is NOT
2654 	 * updated.  Not sure if this is 100% correct.
2655 	 *  -George
2656 	 */
2657 	cur->children = (xmlNodePtr) ent;
2658 	cur->last = (xmlNodePtr) ent;
2659     }
2660 
2661     if ((__xmlRegisterCallbacks) && (xmlRegisterNodeDefaultValue))
2662 	xmlRegisterNodeDefaultValue(cur);
2663     return(cur);
2664 }
2665 
2666 /**
2667  * xmlNewDocText:
2668  * @doc: the document
2669  * @content:  the text content
2670  *
2671  * Creation of a new text node within a document.
2672  * Returns a pointer to the new node object.
2673  */
2674 xmlNodePtr
xmlNewDocText(const xmlDoc * doc,const xmlChar * content)2675 xmlNewDocText(const xmlDoc *doc, const xmlChar *content) {
2676     xmlNodePtr cur;
2677 
2678     cur = xmlNewText(content);
2679     if (cur != NULL) cur->doc = (xmlDoc *)doc;
2680     return(cur);
2681 }
2682 
2683 /**
2684  * xmlNewTextLen:
2685  * @content:  the text content
2686  * @len:  the text len.
2687  *
2688  * Creation of a new text node with an extra parameter for the content's length
2689  * Returns a pointer to the new node object.
2690  */
2691 xmlNodePtr
xmlNewTextLen(const xmlChar * content,int len)2692 xmlNewTextLen(const xmlChar *content, int len) {
2693     xmlNodePtr cur;
2694 
2695     /*
2696      * Allocate a new node and fill the fields.
2697      */
2698     cur = (xmlNodePtr) xmlMalloc(sizeof(xmlNode));
2699     if (cur == NULL) {
2700 	xmlTreeErrMemory("building text");
2701 	return(NULL);
2702     }
2703     memset(cur, 0, sizeof(xmlNode));
2704     cur->type = XML_TEXT_NODE;
2705 
2706     cur->name = xmlStringText;
2707     if (content != NULL) {
2708 	cur->content = xmlStrndup(content, len);
2709     }
2710 
2711     if ((__xmlRegisterCallbacks) && (xmlRegisterNodeDefaultValue))
2712 	xmlRegisterNodeDefaultValue(cur);
2713     return(cur);
2714 }
2715 
2716 /**
2717  * xmlNewDocTextLen:
2718  * @doc: the document
2719  * @content:  the text content
2720  * @len:  the text len.
2721  *
2722  * Creation of a new text node with an extra content length parameter. The
2723  * text node pertain to a given document.
2724  * Returns a pointer to the new node object.
2725  */
2726 xmlNodePtr
xmlNewDocTextLen(xmlDocPtr doc,const xmlChar * content,int len)2727 xmlNewDocTextLen(xmlDocPtr doc, const xmlChar *content, int len) {
2728     xmlNodePtr cur;
2729 
2730     cur = xmlNewTextLen(content, len);
2731     if (cur != NULL) cur->doc = doc;
2732     return(cur);
2733 }
2734 
2735 /**
2736  * xmlNewComment:
2737  * @content:  the comment content
2738  *
2739  * Creation of a new node containing a comment.
2740  * Returns a pointer to the new node object.
2741  */
2742 xmlNodePtr
xmlNewComment(const xmlChar * content)2743 xmlNewComment(const xmlChar *content) {
2744     xmlNodePtr cur;
2745 
2746     /*
2747      * Allocate a new node and fill the fields.
2748      */
2749     cur = (xmlNodePtr) xmlMalloc(sizeof(xmlNode));
2750     if (cur == NULL) {
2751 	xmlTreeErrMemory("building comment");
2752 	return(NULL);
2753     }
2754     memset(cur, 0, sizeof(xmlNode));
2755     cur->type = XML_COMMENT_NODE;
2756 
2757     cur->name = xmlStringComment;
2758     if (content != NULL) {
2759 	cur->content = xmlStrdup(content);
2760     }
2761 
2762     if ((__xmlRegisterCallbacks) && (xmlRegisterNodeDefaultValue))
2763 	xmlRegisterNodeDefaultValue(cur);
2764     return(cur);
2765 }
2766 
2767 /**
2768  * xmlNewCDataBlock:
2769  * @doc:  the document
2770  * @content:  the CDATA block content content
2771  * @len:  the length of the block
2772  *
2773  * Creation of a new node containing a CDATA block.
2774  * Returns a pointer to the new node object.
2775  */
2776 xmlNodePtr
xmlNewCDataBlock(xmlDocPtr doc,const xmlChar * content,int len)2777 xmlNewCDataBlock(xmlDocPtr doc, const xmlChar *content, int len) {
2778     xmlNodePtr cur;
2779 
2780     /*
2781      * Allocate a new node and fill the fields.
2782      */
2783     cur = (xmlNodePtr) xmlMalloc(sizeof(xmlNode));
2784     if (cur == NULL) {
2785 	xmlTreeErrMemory("building CDATA");
2786 	return(NULL);
2787     }
2788     memset(cur, 0, sizeof(xmlNode));
2789     cur->type = XML_CDATA_SECTION_NODE;
2790     cur->doc = doc;
2791 
2792     if (content != NULL) {
2793 	cur->content = xmlStrndup(content, len);
2794     }
2795 
2796     if ((__xmlRegisterCallbacks) && (xmlRegisterNodeDefaultValue))
2797 	xmlRegisterNodeDefaultValue(cur);
2798     return(cur);
2799 }
2800 
2801 /**
2802  * xmlNewDocComment:
2803  * @doc:  the document
2804  * @content:  the comment content
2805  *
2806  * Creation of a new node containing a comment within a document.
2807  * Returns a pointer to the new node object.
2808  */
2809 xmlNodePtr
xmlNewDocComment(xmlDocPtr doc,const xmlChar * content)2810 xmlNewDocComment(xmlDocPtr doc, const xmlChar *content) {
2811     xmlNodePtr cur;
2812 
2813     cur = xmlNewComment(content);
2814     if (cur != NULL) cur->doc = doc;
2815     return(cur);
2816 }
2817 
2818 /**
2819  * xmlSetTreeDoc:
2820  * @tree:  the top element
2821  * @doc:  the document
2822  *
2823  * update all nodes under the tree to point to the right document
2824  */
2825 void
xmlSetTreeDoc(xmlNodePtr tree,xmlDocPtr doc)2826 xmlSetTreeDoc(xmlNodePtr tree, xmlDocPtr doc) {
2827     xmlAttrPtr prop;
2828 
2829     if ((tree == NULL) || (tree->type == XML_NAMESPACE_DECL))
2830 	return;
2831     if (tree->doc != doc) {
2832 	if(tree->type == XML_ELEMENT_NODE) {
2833 	    prop = tree->properties;
2834 	    while (prop != NULL) {
2835                 if (prop->atype == XML_ATTRIBUTE_ID) {
2836                     xmlRemoveID(tree->doc, prop);
2837                 }
2838 
2839 		prop->doc = doc;
2840 		xmlSetListDoc(prop->children, doc);
2841 
2842                 /*
2843                  * TODO: ID attributes should be also added to the new
2844                  * document, but this breaks things like xmlReplaceNode.
2845                  * The underlying problem is that xmlRemoveID is only called
2846                  * if a node is destroyed, not if it's unlinked.
2847                  */
2848 #if 0
2849                 if (xmlIsID(doc, tree, prop)) {
2850                     xmlChar *idVal = xmlNodeListGetString(doc, prop->children,
2851                                                           1);
2852                     xmlAddID(NULL, doc, idVal, prop);
2853                 }
2854 #endif
2855 
2856 		prop = prop->next;
2857 	    }
2858 	}
2859         if (tree->type == XML_ENTITY_REF_NODE) {
2860             /*
2861              * Clear 'children' which points to the entity declaration
2862              * from the original document.
2863              */
2864             tree->children = NULL;
2865         } else if (tree->children != NULL) {
2866 	    xmlSetListDoc(tree->children, doc);
2867         }
2868 	tree->doc = doc;
2869     }
2870 }
2871 
2872 /**
2873  * xmlSetListDoc:
2874  * @list:  the first element
2875  * @doc:  the document
2876  *
2877  * update all nodes in the list to point to the right document
2878  */
2879 void
xmlSetListDoc(xmlNodePtr list,xmlDocPtr doc)2880 xmlSetListDoc(xmlNodePtr list, xmlDocPtr doc) {
2881     xmlNodePtr cur;
2882 
2883     if ((list == NULL) || (list->type == XML_NAMESPACE_DECL))
2884 	return;
2885     cur = list;
2886     while (cur != NULL) {
2887 	if (cur->doc != doc)
2888 	    xmlSetTreeDoc(cur, doc);
2889 	cur = cur->next;
2890     }
2891 }
2892 
2893 #if defined(LIBXML_TREE_ENABLED) || defined(LIBXML_SCHEMAS_ENABLED)
2894 /**
2895  * xmlNewChild:
2896  * @parent:  the parent node
2897  * @ns:  a namespace if any
2898  * @name:  the name of the child
2899  * @content:  the XML content of the child if any.
2900  *
2901  * Creation of a new child element, added at the end of @parent children list.
2902  * @ns and @content parameters are optional (NULL). If @ns is NULL, the newly
2903  * created element inherits the namespace of @parent. If @content is non NULL,
2904  * a child list containing the TEXTs and ENTITY_REFs node will be created.
2905  * NOTE: @content is supposed to be a piece of XML CDATA, so it allows entity
2906  *       references. XML special chars must be escaped first by using
2907  *       xmlEncodeEntitiesReentrant(), or xmlNewTextChild() should be used.
2908  *
2909  * Returns a pointer to the new node object.
2910  */
2911 xmlNodePtr
xmlNewChild(xmlNodePtr parent,xmlNsPtr ns,const xmlChar * name,const xmlChar * content)2912 xmlNewChild(xmlNodePtr parent, xmlNsPtr ns,
2913             const xmlChar *name, const xmlChar *content) {
2914     xmlNodePtr cur, prev;
2915 
2916     if (parent == NULL) {
2917 #ifdef DEBUG_TREE
2918         xmlGenericError(xmlGenericErrorContext,
2919 		"xmlNewChild : parent == NULL\n");
2920 #endif
2921 	return(NULL);
2922     }
2923 
2924     if (name == NULL) {
2925 #ifdef DEBUG_TREE
2926         xmlGenericError(xmlGenericErrorContext,
2927 		"xmlNewChild : name == NULL\n");
2928 #endif
2929 	return(NULL);
2930     }
2931 
2932     /*
2933      * Allocate a new node
2934      */
2935     if (parent->type == XML_ELEMENT_NODE) {
2936 	if (ns == NULL)
2937 	    cur = xmlNewDocNode(parent->doc, parent->ns, name, content);
2938 	else
2939 	    cur = xmlNewDocNode(parent->doc, ns, name, content);
2940     } else if ((parent->type == XML_DOCUMENT_NODE) ||
2941 	       (parent->type == XML_HTML_DOCUMENT_NODE)) {
2942 	if (ns == NULL)
2943 	    cur = xmlNewDocNode((xmlDocPtr) parent, NULL, name, content);
2944 	else
2945 	    cur = xmlNewDocNode((xmlDocPtr) parent, ns, name, content);
2946     } else if (parent->type == XML_DOCUMENT_FRAG_NODE) {
2947 	    cur = xmlNewDocNode( parent->doc, ns, name, content);
2948     } else {
2949 	return(NULL);
2950     }
2951     if (cur == NULL) return(NULL);
2952 
2953     /*
2954      * add the new element at the end of the children list.
2955      */
2956     cur->type = XML_ELEMENT_NODE;
2957     cur->parent = parent;
2958     cur->doc = parent->doc;
2959     if (parent->children == NULL) {
2960         parent->children = cur;
2961 	parent->last = cur;
2962     } else {
2963         prev = parent->last;
2964 	prev->next = cur;
2965 	cur->prev = prev;
2966 	parent->last = cur;
2967     }
2968 
2969     return(cur);
2970 }
2971 #endif /* LIBXML_TREE_ENABLED */
2972 
2973 /**
2974  * xmlAddPropSibling:
2975  * @prev:  the attribute to which @prop is added after
2976  * @cur:   the base attribute passed to calling function
2977  * @prop:  the new attribute
2978  *
2979  * Add a new attribute after @prev using @cur as base attribute.
2980  * When inserting before @cur, @prev is passed as @cur->prev.
2981  * When inserting after @cur, @prev is passed as @cur.
2982  * If an existing attribute is found it is destroyed prior to adding @prop.
2983  *
2984  * Returns the attribute being inserted or NULL in case of error.
2985  */
2986 static xmlNodePtr
xmlAddPropSibling(xmlNodePtr prev,xmlNodePtr cur,xmlNodePtr prop)2987 xmlAddPropSibling(xmlNodePtr prev, xmlNodePtr cur, xmlNodePtr prop) {
2988 	xmlAttrPtr attr;
2989 
2990 	if ((cur == NULL) || (cur->type != XML_ATTRIBUTE_NODE) ||
2991 	    (prop == NULL) || (prop->type != XML_ATTRIBUTE_NODE) ||
2992 	    ((prev != NULL) && (prev->type != XML_ATTRIBUTE_NODE)))
2993 		return(NULL);
2994 
2995 	/* check if an attribute with the same name exists */
2996 	if (prop->ns == NULL)
2997 		attr = xmlHasNsProp(cur->parent, prop->name, NULL);
2998 	else
2999 		attr = xmlHasNsProp(cur->parent, prop->name, prop->ns->href);
3000 
3001 	if (prop->doc != cur->doc) {
3002 		xmlSetTreeDoc(prop, cur->doc);
3003 	}
3004 	prop->parent = cur->parent;
3005 	prop->prev = prev;
3006 	if (prev != NULL) {
3007 		prop->next = prev->next;
3008 		prev->next = prop;
3009 		if (prop->next)
3010 			prop->next->prev = prop;
3011 	} else {
3012 		prop->next = cur;
3013 		cur->prev = prop;
3014 	}
3015 	if (prop->prev == NULL && prop->parent != NULL)
3016 		prop->parent->properties = (xmlAttrPtr) prop;
3017 	if ((attr != NULL) && (attr->type != XML_ATTRIBUTE_DECL)) {
3018 		/* different instance, destroy it (attributes must be unique) */
3019 		xmlRemoveProp((xmlAttrPtr) attr);
3020 	}
3021 	return prop;
3022 }
3023 
3024 /**
3025  * xmlAddNextSibling:
3026  * @cur:  the child node
3027  * @elem:  the new node
3028  *
3029  * Add a new node @elem as the next sibling of @cur
3030  * If the new node was already inserted in a document it is
3031  * first unlinked from its existing context.
3032  * As a result of text merging @elem may be freed.
3033  * If the new node is ATTRIBUTE, it is added into properties instead of children.
3034  * If there is an attribute with equal name, it is first destroyed.
3035  *
3036  * Returns the new node or NULL in case of error.
3037  */
3038 xmlNodePtr
xmlAddNextSibling(xmlNodePtr cur,xmlNodePtr elem)3039 xmlAddNextSibling(xmlNodePtr cur, xmlNodePtr elem) {
3040     if ((cur == NULL) || (cur->type == XML_NAMESPACE_DECL)) {
3041 #ifdef DEBUG_TREE
3042         xmlGenericError(xmlGenericErrorContext,
3043 		"xmlAddNextSibling : cur == NULL\n");
3044 #endif
3045 	return(NULL);
3046     }
3047     if ((elem == NULL) || (elem->type == XML_NAMESPACE_DECL)) {
3048 #ifdef DEBUG_TREE
3049         xmlGenericError(xmlGenericErrorContext,
3050 		"xmlAddNextSibling : elem == NULL\n");
3051 #endif
3052 	return(NULL);
3053     }
3054 
3055     if (cur == elem) {
3056 #ifdef DEBUG_TREE
3057         xmlGenericError(xmlGenericErrorContext,
3058 		"xmlAddNextSibling : cur == elem\n");
3059 #endif
3060 	return(NULL);
3061     }
3062 
3063     xmlUnlinkNode(elem);
3064 
3065     if (elem->type == XML_TEXT_NODE) {
3066 	if (cur->type == XML_TEXT_NODE) {
3067 	    xmlNodeAddContent(cur, elem->content);
3068 	    xmlFreeNode(elem);
3069 	    return(cur);
3070 	}
3071 	if ((cur->next != NULL) && (cur->next->type == XML_TEXT_NODE) &&
3072             (cur->name == cur->next->name)) {
3073 	    xmlChar *tmp;
3074 
3075 	    tmp = xmlStrdup(elem->content);
3076 	    tmp = xmlStrcat(tmp, cur->next->content);
3077 	    xmlNodeSetContent(cur->next, tmp);
3078 	    xmlFree(tmp);
3079 	    xmlFreeNode(elem);
3080 	    return(cur->next);
3081 	}
3082     } else if (elem->type == XML_ATTRIBUTE_NODE) {
3083 		return xmlAddPropSibling(cur, cur, elem);
3084     }
3085 
3086     if (elem->doc != cur->doc) {
3087 	xmlSetTreeDoc(elem, cur->doc);
3088     }
3089     elem->parent = cur->parent;
3090     elem->prev = cur;
3091     elem->next = cur->next;
3092     cur->next = elem;
3093     if (elem->next != NULL)
3094 	elem->next->prev = elem;
3095     if ((elem->parent != NULL) && (elem->parent->last == cur))
3096 	elem->parent->last = elem;
3097     return(elem);
3098 }
3099 
3100 #if defined(LIBXML_TREE_ENABLED) || defined(LIBXML_HTML_ENABLED) || \
3101     defined(LIBXML_SCHEMAS_ENABLED) || defined(LIBXML_XINCLUDE_ENABLED)
3102 /**
3103  * xmlAddPrevSibling:
3104  * @cur:  the child node
3105  * @elem:  the new node
3106  *
3107  * Add a new node @elem as the previous sibling of @cur
3108  * merging adjacent TEXT nodes (@elem may be freed)
3109  * If the new node was already inserted in a document it is
3110  * first unlinked from its existing context.
3111  * If the new node is ATTRIBUTE, it is added into properties instead of children.
3112  * If there is an attribute with equal name, it is first destroyed.
3113  *
3114  * Returns the new node or NULL in case of error.
3115  */
3116 xmlNodePtr
xmlAddPrevSibling(xmlNodePtr cur,xmlNodePtr elem)3117 xmlAddPrevSibling(xmlNodePtr cur, xmlNodePtr elem) {
3118     if ((cur == NULL) || (cur->type == XML_NAMESPACE_DECL)) {
3119 #ifdef DEBUG_TREE
3120         xmlGenericError(xmlGenericErrorContext,
3121 		"xmlAddPrevSibling : cur == NULL\n");
3122 #endif
3123 	return(NULL);
3124     }
3125     if ((elem == NULL) || (elem->type == XML_NAMESPACE_DECL)) {
3126 #ifdef DEBUG_TREE
3127         xmlGenericError(xmlGenericErrorContext,
3128 		"xmlAddPrevSibling : elem == NULL\n");
3129 #endif
3130 	return(NULL);
3131     }
3132 
3133     if (cur == elem) {
3134 #ifdef DEBUG_TREE
3135         xmlGenericError(xmlGenericErrorContext,
3136 		"xmlAddPrevSibling : cur == elem\n");
3137 #endif
3138 	return(NULL);
3139     }
3140 
3141     xmlUnlinkNode(elem);
3142 
3143     if (elem->type == XML_TEXT_NODE) {
3144 	if (cur->type == XML_TEXT_NODE) {
3145 	    xmlChar *tmp;
3146 
3147 	    tmp = xmlStrdup(elem->content);
3148 	    tmp = xmlStrcat(tmp, cur->content);
3149 	    xmlNodeSetContent(cur, tmp);
3150 	    xmlFree(tmp);
3151 	    xmlFreeNode(elem);
3152 	    return(cur);
3153 	}
3154 	if ((cur->prev != NULL) && (cur->prev->type == XML_TEXT_NODE) &&
3155             (cur->name == cur->prev->name)) {
3156 	    xmlNodeAddContent(cur->prev, elem->content);
3157 	    xmlFreeNode(elem);
3158 	    return(cur->prev);
3159 	}
3160     } else if (elem->type == XML_ATTRIBUTE_NODE) {
3161 		return xmlAddPropSibling(cur->prev, cur, elem);
3162     }
3163 
3164     if (elem->doc != cur->doc) {
3165 	xmlSetTreeDoc(elem, cur->doc);
3166     }
3167     elem->parent = cur->parent;
3168     elem->next = cur;
3169     elem->prev = cur->prev;
3170     cur->prev = elem;
3171     if (elem->prev != NULL)
3172 	elem->prev->next = elem;
3173     if ((elem->parent != NULL) && (elem->parent->children == cur)) {
3174 		elem->parent->children = elem;
3175     }
3176     return(elem);
3177 }
3178 #endif /* LIBXML_TREE_ENABLED */
3179 
3180 /**
3181  * xmlAddSibling:
3182  * @cur:  the child node
3183  * @elem:  the new node
3184  *
3185  * Add a new element @elem to the list of siblings of @cur
3186  * merging adjacent TEXT nodes (@elem may be freed)
3187  * If the new element was already inserted in a document it is
3188  * first unlinked from its existing context.
3189  *
3190  * Returns the new element or NULL in case of error.
3191  */
3192 xmlNodePtr
xmlAddSibling(xmlNodePtr cur,xmlNodePtr elem)3193 xmlAddSibling(xmlNodePtr cur, xmlNodePtr elem) {
3194     xmlNodePtr parent;
3195 
3196     if ((cur == NULL) || (cur->type == XML_NAMESPACE_DECL)) {
3197 #ifdef DEBUG_TREE
3198         xmlGenericError(xmlGenericErrorContext,
3199 		"xmlAddSibling : cur == NULL\n");
3200 #endif
3201 	return(NULL);
3202     }
3203 
3204     if ((elem == NULL) || (elem->type == XML_NAMESPACE_DECL)) {
3205 #ifdef DEBUG_TREE
3206         xmlGenericError(xmlGenericErrorContext,
3207 		"xmlAddSibling : elem == NULL\n");
3208 #endif
3209 	return(NULL);
3210     }
3211 
3212     if (cur == elem) {
3213 #ifdef DEBUG_TREE
3214         xmlGenericError(xmlGenericErrorContext,
3215 		"xmlAddSibling : cur == elem\n");
3216 #endif
3217 	return(NULL);
3218     }
3219 
3220     /*
3221      * Constant time is we can rely on the ->parent->last to find
3222      * the last sibling.
3223      */
3224     if ((cur->type != XML_ATTRIBUTE_NODE) && (cur->parent != NULL) &&
3225 	(cur->parent->children != NULL) &&
3226 	(cur->parent->last != NULL) &&
3227 	(cur->parent->last->next == NULL)) {
3228 	cur = cur->parent->last;
3229     } else {
3230 	while (cur->next != NULL) cur = cur->next;
3231     }
3232 
3233     xmlUnlinkNode(elem);
3234 
3235     if ((cur->type == XML_TEXT_NODE) && (elem->type == XML_TEXT_NODE) &&
3236         (cur->name == elem->name)) {
3237 	xmlNodeAddContent(cur, elem->content);
3238 	xmlFreeNode(elem);
3239 	return(cur);
3240     } else if (elem->type == XML_ATTRIBUTE_NODE) {
3241 		return xmlAddPropSibling(cur, cur, elem);
3242     }
3243 
3244     if (elem->doc != cur->doc) {
3245 	xmlSetTreeDoc(elem, cur->doc);
3246     }
3247     parent = cur->parent;
3248     elem->prev = cur;
3249     elem->next = NULL;
3250     elem->parent = parent;
3251     cur->next = elem;
3252     if (parent != NULL)
3253 	parent->last = elem;
3254 
3255     return(elem);
3256 }
3257 
3258 /**
3259  * xmlAddChildList:
3260  * @parent:  the parent node
3261  * @cur:  the first node in the list
3262  *
3263  * Add a list of node at the end of the child list of the parent
3264  * merging adjacent TEXT nodes (@cur may be freed)
3265  *
3266  * Returns the last child or NULL in case of error.
3267  */
3268 xmlNodePtr
xmlAddChildList(xmlNodePtr parent,xmlNodePtr cur)3269 xmlAddChildList(xmlNodePtr parent, xmlNodePtr cur) {
3270     xmlNodePtr prev;
3271 
3272     if ((parent == NULL) || (parent->type == XML_NAMESPACE_DECL)) {
3273 #ifdef DEBUG_TREE
3274         xmlGenericError(xmlGenericErrorContext,
3275 		"xmlAddChildList : parent == NULL\n");
3276 #endif
3277 	return(NULL);
3278     }
3279 
3280     if ((cur == NULL) || (cur->type == XML_NAMESPACE_DECL)) {
3281 #ifdef DEBUG_TREE
3282         xmlGenericError(xmlGenericErrorContext,
3283 		"xmlAddChildList : child == NULL\n");
3284 #endif
3285 	return(NULL);
3286     }
3287 
3288     if ((cur->doc != NULL) && (parent->doc != NULL) &&
3289         (cur->doc != parent->doc)) {
3290 #ifdef DEBUG_TREE
3291 	xmlGenericError(xmlGenericErrorContext,
3292 		"Elements moved to a different document\n");
3293 #endif
3294     }
3295 
3296     /*
3297      * add the first element at the end of the children list.
3298      */
3299 
3300     if (parent->children == NULL) {
3301         parent->children = cur;
3302     } else {
3303 	/*
3304 	 * If cur and parent->last both are TEXT nodes, then merge them.
3305 	 */
3306 	if ((cur->type == XML_TEXT_NODE) &&
3307 	    (parent->last->type == XML_TEXT_NODE) &&
3308 	    (cur->name == parent->last->name)) {
3309 	    xmlNodeAddContent(parent->last, cur->content);
3310 	    /*
3311 	     * if it's the only child, nothing more to be done.
3312 	     */
3313 	    if (cur->next == NULL) {
3314 		xmlFreeNode(cur);
3315 		return(parent->last);
3316 	    }
3317 	    prev = cur;
3318 	    cur = cur->next;
3319 	    xmlFreeNode(prev);
3320 	}
3321         prev = parent->last;
3322 	prev->next = cur;
3323 	cur->prev = prev;
3324     }
3325     while (cur->next != NULL) {
3326 	cur->parent = parent;
3327 	if (cur->doc != parent->doc) {
3328 	    xmlSetTreeDoc(cur, parent->doc);
3329 	}
3330         cur = cur->next;
3331     }
3332     cur->parent = parent;
3333     /* the parent may not be linked to a doc ! */
3334     if (cur->doc != parent->doc) {
3335         xmlSetTreeDoc(cur, parent->doc);
3336     }
3337     parent->last = cur;
3338 
3339     return(cur);
3340 }
3341 
3342 /**
3343  * xmlAddChild:
3344  * @parent:  the parent node
3345  * @cur:  the child node
3346  *
3347  * Add a new node to @parent, at the end of the child (or property) list
3348  * merging adjacent TEXT nodes (in which case @cur is freed)
3349  * If the new node is ATTRIBUTE, it is added into properties instead of children.
3350  * If there is an attribute with equal name, it is first destroyed.
3351  *
3352  * Returns the child or NULL in case of error.
3353  */
3354 xmlNodePtr
xmlAddChild(xmlNodePtr parent,xmlNodePtr cur)3355 xmlAddChild(xmlNodePtr parent, xmlNodePtr cur) {
3356     xmlNodePtr prev;
3357 
3358     if ((parent == NULL) || (parent->type == XML_NAMESPACE_DECL)) {
3359 #ifdef DEBUG_TREE
3360         xmlGenericError(xmlGenericErrorContext,
3361 		"xmlAddChild : parent == NULL\n");
3362 #endif
3363 	return(NULL);
3364     }
3365 
3366     if ((cur == NULL) || (cur->type == XML_NAMESPACE_DECL)) {
3367 #ifdef DEBUG_TREE
3368         xmlGenericError(xmlGenericErrorContext,
3369 		"xmlAddChild : child == NULL\n");
3370 #endif
3371 	return(NULL);
3372     }
3373 
3374     if (parent == cur) {
3375 #ifdef DEBUG_TREE
3376         xmlGenericError(xmlGenericErrorContext,
3377 		"xmlAddChild : parent == cur\n");
3378 #endif
3379 	return(NULL);
3380     }
3381     /*
3382      * If cur is a TEXT node, merge its content with adjacent TEXT nodes
3383      * cur is then freed.
3384      */
3385     if (cur->type == XML_TEXT_NODE) {
3386 	if ((parent->type == XML_TEXT_NODE) &&
3387 	    (parent->content != NULL) &&
3388 	    (parent->name == cur->name)) {
3389 	    xmlNodeAddContent(parent, cur->content);
3390 	    xmlFreeNode(cur);
3391 	    return(parent);
3392 	}
3393 	if ((parent->last != NULL) && (parent->last->type == XML_TEXT_NODE) &&
3394 	    (parent->last->name == cur->name) &&
3395 	    (parent->last != cur)) {
3396 	    xmlNodeAddContent(parent->last, cur->content);
3397 	    xmlFreeNode(cur);
3398 	    return(parent->last);
3399 	}
3400     }
3401 
3402     /*
3403      * add the new element at the end of the children list.
3404      */
3405     prev = cur->parent;
3406     cur->parent = parent;
3407     if (cur->doc != parent->doc) {
3408 	xmlSetTreeDoc(cur, parent->doc);
3409     }
3410     /* this check prevents a loop on tree-traversions if a developer
3411      * tries to add a node to its parent multiple times
3412      */
3413     if (prev == parent)
3414 	return(cur);
3415 
3416     /*
3417      * Coalescing
3418      */
3419     if ((parent->type == XML_TEXT_NODE) &&
3420 	(parent->content != NULL) &&
3421 	(parent != cur)) {
3422 	xmlNodeAddContent(parent, cur->content);
3423 	xmlFreeNode(cur);
3424 	return(parent);
3425     }
3426     if (cur->type == XML_ATTRIBUTE_NODE) {
3427 		if (parent->type != XML_ELEMENT_NODE)
3428 			return(NULL);
3429 	if (parent->properties != NULL) {
3430 	    /* check if an attribute with the same name exists */
3431 	    xmlAttrPtr lastattr;
3432 
3433 	    if (cur->ns == NULL)
3434 		lastattr = xmlHasNsProp(parent, cur->name, NULL);
3435 	    else
3436 		lastattr = xmlHasNsProp(parent, cur->name, cur->ns->href);
3437 	    if ((lastattr != NULL) && (lastattr != (xmlAttrPtr) cur) && (lastattr->type != XML_ATTRIBUTE_DECL)) {
3438 		/* different instance, destroy it (attributes must be unique) */
3439 			xmlUnlinkNode((xmlNodePtr) lastattr);
3440 		xmlFreeProp(lastattr);
3441 	    }
3442 		if (lastattr == (xmlAttrPtr) cur)
3443 			return(cur);
3444 
3445 	}
3446 	if (parent->properties == NULL) {
3447 	    parent->properties = (xmlAttrPtr) cur;
3448 	} else {
3449 	    /* find the end */
3450 	    xmlAttrPtr lastattr = parent->properties;
3451 	    while (lastattr->next != NULL) {
3452 		lastattr = lastattr->next;
3453 	    }
3454 	    lastattr->next = (xmlAttrPtr) cur;
3455 	    ((xmlAttrPtr) cur)->prev = lastattr;
3456 	}
3457     } else {
3458 	if (parent->children == NULL) {
3459 	    parent->children = cur;
3460 	    parent->last = cur;
3461 	} else {
3462 	    prev = parent->last;
3463 	    prev->next = cur;
3464 	    cur->prev = prev;
3465 	    parent->last = cur;
3466 	}
3467     }
3468     return(cur);
3469 }
3470 
3471 /**
3472  * xmlGetLastChild:
3473  * @parent:  the parent node
3474  *
3475  * Search the last child of a node.
3476  * Returns the last child or NULL if none.
3477  */
3478 xmlNodePtr
xmlGetLastChild(const xmlNode * parent)3479 xmlGetLastChild(const xmlNode *parent) {
3480     if ((parent == NULL) || (parent->type == XML_NAMESPACE_DECL)) {
3481 #ifdef DEBUG_TREE
3482         xmlGenericError(xmlGenericErrorContext,
3483 		"xmlGetLastChild : parent == NULL\n");
3484 #endif
3485 	return(NULL);
3486     }
3487     return(parent->last);
3488 }
3489 
3490 #ifdef LIBXML_TREE_ENABLED
3491 /*
3492  * 5 interfaces from DOM ElementTraversal
3493  */
3494 
3495 /**
3496  * xmlChildElementCount:
3497  * @parent: the parent node
3498  *
3499  * Finds the current number of child nodes of that element which are
3500  * element nodes.
3501  * Note the handling of entities references is different than in
3502  * the W3C DOM element traversal spec since we don't have back reference
3503  * from entities content to entities references.
3504  *
3505  * Returns the count of element child or 0 if not available
3506  */
3507 unsigned long
xmlChildElementCount(xmlNodePtr parent)3508 xmlChildElementCount(xmlNodePtr parent) {
3509     unsigned long ret = 0;
3510     xmlNodePtr cur = NULL;
3511 
3512     if (parent == NULL)
3513         return(0);
3514     switch (parent->type) {
3515         case XML_ELEMENT_NODE:
3516         case XML_ENTITY_NODE:
3517         case XML_DOCUMENT_NODE:
3518         case XML_DOCUMENT_FRAG_NODE:
3519         case XML_HTML_DOCUMENT_NODE:
3520             cur = parent->children;
3521             break;
3522         default:
3523             return(0);
3524     }
3525     while (cur != NULL) {
3526         if (cur->type == XML_ELEMENT_NODE)
3527             ret++;
3528         cur = cur->next;
3529     }
3530     return(ret);
3531 }
3532 
3533 /**
3534  * xmlFirstElementChild:
3535  * @parent: the parent node
3536  *
3537  * Finds the first child node of that element which is a Element node
3538  * Note the handling of entities references is different than in
3539  * the W3C DOM element traversal spec since we don't have back reference
3540  * from entities content to entities references.
3541  *
3542  * Returns the first element child or NULL if not available
3543  */
3544 xmlNodePtr
xmlFirstElementChild(xmlNodePtr parent)3545 xmlFirstElementChild(xmlNodePtr parent) {
3546     xmlNodePtr cur = NULL;
3547 
3548     if (parent == NULL)
3549         return(NULL);
3550     switch (parent->type) {
3551         case XML_ELEMENT_NODE:
3552         case XML_ENTITY_NODE:
3553         case XML_DOCUMENT_NODE:
3554         case XML_DOCUMENT_FRAG_NODE:
3555         case XML_HTML_DOCUMENT_NODE:
3556             cur = parent->children;
3557             break;
3558         default:
3559             return(NULL);
3560     }
3561     while (cur != NULL) {
3562         if (cur->type == XML_ELEMENT_NODE)
3563             return(cur);
3564         cur = cur->next;
3565     }
3566     return(NULL);
3567 }
3568 
3569 /**
3570  * xmlLastElementChild:
3571  * @parent: the parent node
3572  *
3573  * Finds the last child node of that element which is a Element node
3574  * Note the handling of entities references is different than in
3575  * the W3C DOM element traversal spec since we don't have back reference
3576  * from entities content to entities references.
3577  *
3578  * Returns the last element child or NULL if not available
3579  */
3580 xmlNodePtr
xmlLastElementChild(xmlNodePtr parent)3581 xmlLastElementChild(xmlNodePtr parent) {
3582     xmlNodePtr cur = NULL;
3583 
3584     if (parent == NULL)
3585         return(NULL);
3586     switch (parent->type) {
3587         case XML_ELEMENT_NODE:
3588         case XML_ENTITY_NODE:
3589         case XML_DOCUMENT_NODE:
3590         case XML_DOCUMENT_FRAG_NODE:
3591         case XML_HTML_DOCUMENT_NODE:
3592             cur = parent->last;
3593             break;
3594         default:
3595             return(NULL);
3596     }
3597     while (cur != NULL) {
3598         if (cur->type == XML_ELEMENT_NODE)
3599             return(cur);
3600         cur = cur->prev;
3601     }
3602     return(NULL);
3603 }
3604 
3605 /**
3606  * xmlPreviousElementSibling:
3607  * @node: the current node
3608  *
3609  * Finds the first closest previous sibling of the node which is an
3610  * element node.
3611  * Note the handling of entities references is different than in
3612  * the W3C DOM element traversal spec since we don't have back reference
3613  * from entities content to entities references.
3614  *
3615  * Returns the previous element sibling or NULL if not available
3616  */
3617 xmlNodePtr
xmlPreviousElementSibling(xmlNodePtr node)3618 xmlPreviousElementSibling(xmlNodePtr node) {
3619     if (node == NULL)
3620         return(NULL);
3621     switch (node->type) {
3622         case XML_ELEMENT_NODE:
3623         case XML_TEXT_NODE:
3624         case XML_CDATA_SECTION_NODE:
3625         case XML_ENTITY_REF_NODE:
3626         case XML_ENTITY_NODE:
3627         case XML_PI_NODE:
3628         case XML_COMMENT_NODE:
3629         case XML_XINCLUDE_START:
3630         case XML_XINCLUDE_END:
3631             node = node->prev;
3632             break;
3633         default:
3634             return(NULL);
3635     }
3636     while (node != NULL) {
3637         if (node->type == XML_ELEMENT_NODE)
3638             return(node);
3639         node = node->prev;
3640     }
3641     return(NULL);
3642 }
3643 
3644 /**
3645  * xmlNextElementSibling:
3646  * @node: the current node
3647  *
3648  * Finds the first closest next sibling of the node which is an
3649  * element node.
3650  * Note the handling of entities references is different than in
3651  * the W3C DOM element traversal spec since we don't have back reference
3652  * from entities content to entities references.
3653  *
3654  * Returns the next element sibling or NULL if not available
3655  */
3656 xmlNodePtr
xmlNextElementSibling(xmlNodePtr node)3657 xmlNextElementSibling(xmlNodePtr node) {
3658     if (node == NULL)
3659         return(NULL);
3660     switch (node->type) {
3661         case XML_ELEMENT_NODE:
3662         case XML_TEXT_NODE:
3663         case XML_CDATA_SECTION_NODE:
3664         case XML_ENTITY_REF_NODE:
3665         case XML_ENTITY_NODE:
3666         case XML_PI_NODE:
3667         case XML_COMMENT_NODE:
3668         case XML_DTD_NODE:
3669         case XML_XINCLUDE_START:
3670         case XML_XINCLUDE_END:
3671             node = node->next;
3672             break;
3673         default:
3674             return(NULL);
3675     }
3676     while (node != NULL) {
3677         if (node->type == XML_ELEMENT_NODE)
3678             return(node);
3679         node = node->next;
3680     }
3681     return(NULL);
3682 }
3683 
3684 #endif /* LIBXML_TREE_ENABLED */
3685 
3686 /**
3687  * xmlFreeNodeList:
3688  * @cur:  the first node in the list
3689  *
3690  * Free a node and all its siblings, this is a recursive behaviour, all
3691  * the children are freed too.
3692  */
3693 void
xmlFreeNodeList(xmlNodePtr cur)3694 xmlFreeNodeList(xmlNodePtr cur) {
3695     xmlNodePtr next;
3696     xmlNodePtr parent;
3697     xmlDictPtr dict = NULL;
3698     size_t depth = 0;
3699 
3700     if (cur == NULL) return;
3701     if (cur->type == XML_NAMESPACE_DECL) {
3702 	xmlFreeNsList((xmlNsPtr) cur);
3703 	return;
3704     }
3705     if ((cur->type == XML_DOCUMENT_NODE) ||
3706 #ifdef LIBXML_DOCB_ENABLED
3707 	(cur->type == XML_DOCB_DOCUMENT_NODE) ||
3708 #endif
3709 	(cur->type == XML_HTML_DOCUMENT_NODE)) {
3710 	xmlFreeDoc((xmlDocPtr) cur);
3711 	return;
3712     }
3713     if (cur->doc != NULL) dict = cur->doc->dict;
3714     while (1) {
3715         while ((cur->children != NULL) &&
3716                (cur->type != XML_DOCUMENT_NODE) &&
3717 #ifdef LIBXML_DOCB_ENABLED
3718                (cur->type != XML_DOCB_DOCUMENT_NODE) &&
3719 #endif
3720                (cur->type != XML_HTML_DOCUMENT_NODE) &&
3721                (cur->type != XML_DTD_NODE) &&
3722                (cur->type != XML_ENTITY_REF_NODE)) {
3723             cur = cur->children;
3724             depth += 1;
3725         }
3726 
3727         next = cur->next;
3728         parent = cur->parent;
3729 	if ((cur->type == XML_DOCUMENT_NODE) ||
3730 #ifdef LIBXML_DOCB_ENABLED
3731             (cur->type == XML_DOCB_DOCUMENT_NODE) ||
3732 #endif
3733             (cur->type == XML_HTML_DOCUMENT_NODE)) {
3734             xmlFreeDoc((xmlDocPtr) cur);
3735         } else if (cur->type != XML_DTD_NODE) {
3736 
3737 	    if ((__xmlRegisterCallbacks) && (xmlDeregisterNodeDefaultValue))
3738 		xmlDeregisterNodeDefaultValue(cur);
3739 
3740 	    if (((cur->type == XML_ELEMENT_NODE) ||
3741 		 (cur->type == XML_XINCLUDE_START) ||
3742 		 (cur->type == XML_XINCLUDE_END)) &&
3743 		(cur->properties != NULL))
3744 		xmlFreePropList(cur->properties);
3745 	    if ((cur->type != XML_ELEMENT_NODE) &&
3746 		(cur->type != XML_XINCLUDE_START) &&
3747 		(cur->type != XML_XINCLUDE_END) &&
3748 		(cur->type != XML_ENTITY_REF_NODE) &&
3749 		(cur->content != (xmlChar *) &(cur->properties))) {
3750 		DICT_FREE(cur->content)
3751 	    }
3752 	    if (((cur->type == XML_ELEMENT_NODE) ||
3753 	         (cur->type == XML_XINCLUDE_START) ||
3754 		 (cur->type == XML_XINCLUDE_END)) &&
3755 		(cur->nsDef != NULL))
3756 		xmlFreeNsList(cur->nsDef);
3757 
3758 	    /*
3759 	     * When a node is a text node or a comment, it uses a global static
3760 	     * variable for the name of the node.
3761 	     * Otherwise the node name might come from the document's
3762 	     * dictionary
3763 	     */
3764 	    if ((cur->name != NULL) &&
3765 		(cur->type != XML_TEXT_NODE) &&
3766 		(cur->type != XML_COMMENT_NODE))
3767 		DICT_FREE(cur->name)
3768 	    xmlFree(cur);
3769 	}
3770 
3771         if (next != NULL) {
3772 	    cur = next;
3773         } else {
3774             if ((depth == 0) || (parent == NULL))
3775                 break;
3776             depth -= 1;
3777             cur = parent;
3778             cur->children = NULL;
3779         }
3780     }
3781 }
3782 
3783 /**
3784  * xmlFreeNode:
3785  * @cur:  the node
3786  *
3787  * Free a node, this is a recursive behaviour, all the children are freed too.
3788  * This doesn't unlink the child from the list, use xmlUnlinkNode() first.
3789  */
3790 void
xmlFreeNode(xmlNodePtr cur)3791 xmlFreeNode(xmlNodePtr cur) {
3792     xmlDictPtr dict = NULL;
3793 
3794     if (cur == NULL) return;
3795 
3796     /* use xmlFreeDtd for DTD nodes */
3797     if (cur->type == XML_DTD_NODE) {
3798 	xmlFreeDtd((xmlDtdPtr) cur);
3799 	return;
3800     }
3801     if (cur->type == XML_NAMESPACE_DECL) {
3802 	xmlFreeNs((xmlNsPtr) cur);
3803         return;
3804     }
3805     if (cur->type == XML_ATTRIBUTE_NODE) {
3806 	xmlFreeProp((xmlAttrPtr) cur);
3807 	return;
3808     }
3809 
3810     if ((__xmlRegisterCallbacks) && (xmlDeregisterNodeDefaultValue))
3811 	xmlDeregisterNodeDefaultValue(cur);
3812 
3813     if (cur->doc != NULL) dict = cur->doc->dict;
3814 
3815     if (cur->type == XML_ENTITY_DECL) {
3816         xmlEntityPtr ent = (xmlEntityPtr) cur;
3817 	DICT_FREE(ent->SystemID);
3818 	DICT_FREE(ent->ExternalID);
3819     }
3820     if ((cur->children != NULL) &&
3821 	(cur->type != XML_ENTITY_REF_NODE))
3822 	xmlFreeNodeList(cur->children);
3823     if (((cur->type == XML_ELEMENT_NODE) ||
3824 	 (cur->type == XML_XINCLUDE_START) ||
3825 	 (cur->type == XML_XINCLUDE_END)) &&
3826 	(cur->properties != NULL))
3827 	xmlFreePropList(cur->properties);
3828     if ((cur->type != XML_ELEMENT_NODE) &&
3829 	(cur->content != NULL) &&
3830 	(cur->type != XML_ENTITY_REF_NODE) &&
3831 	(cur->type != XML_XINCLUDE_END) &&
3832 	(cur->type != XML_XINCLUDE_START) &&
3833 	(cur->content != (xmlChar *) &(cur->properties))) {
3834 	DICT_FREE(cur->content)
3835     }
3836 
3837     /*
3838      * When a node is a text node or a comment, it uses a global static
3839      * variable for the name of the node.
3840      * Otherwise the node name might come from the document's dictionary
3841      */
3842     if ((cur->name != NULL) &&
3843         (cur->type != XML_TEXT_NODE) &&
3844         (cur->type != XML_COMMENT_NODE))
3845 	DICT_FREE(cur->name)
3846 
3847     if (((cur->type == XML_ELEMENT_NODE) ||
3848 	 (cur->type == XML_XINCLUDE_START) ||
3849 	 (cur->type == XML_XINCLUDE_END)) &&
3850 	(cur->nsDef != NULL))
3851 	xmlFreeNsList(cur->nsDef);
3852     xmlFree(cur);
3853 }
3854 
3855 /**
3856  * xmlUnlinkNode:
3857  * @cur:  the node
3858  *
3859  * Unlink a node from it's current context, the node is not freed
3860  * If one need to free the node, use xmlFreeNode() routine after the
3861  * unlink to discard it.
3862  * Note that namespace nodes can't be unlinked as they do not have
3863  * pointer to their parent.
3864  */
3865 void
xmlUnlinkNode(xmlNodePtr cur)3866 xmlUnlinkNode(xmlNodePtr cur) {
3867     if (cur == NULL) {
3868 #ifdef DEBUG_TREE
3869         xmlGenericError(xmlGenericErrorContext,
3870 		"xmlUnlinkNode : node == NULL\n");
3871 #endif
3872 	return;
3873     }
3874     if (cur->type == XML_NAMESPACE_DECL)
3875         return;
3876     if (cur->type == XML_DTD_NODE) {
3877 	xmlDocPtr doc;
3878 	doc = cur->doc;
3879 	if (doc != NULL) {
3880 	    if (doc->intSubset == (xmlDtdPtr) cur)
3881 		doc->intSubset = NULL;
3882 	    if (doc->extSubset == (xmlDtdPtr) cur)
3883 		doc->extSubset = NULL;
3884 	}
3885     }
3886     if (cur->type == XML_ENTITY_DECL) {
3887         xmlDocPtr doc;
3888 	doc = cur->doc;
3889 	if (doc != NULL) {
3890 	    if (doc->intSubset != NULL) {
3891 	        if (xmlHashLookup(doc->intSubset->entities, cur->name) == cur)
3892 		    xmlHashRemoveEntry(doc->intSubset->entities, cur->name,
3893 		                       NULL);
3894 	        if (xmlHashLookup(doc->intSubset->pentities, cur->name) == cur)
3895 		    xmlHashRemoveEntry(doc->intSubset->pentities, cur->name,
3896 		                       NULL);
3897 	    }
3898 	    if (doc->extSubset != NULL) {
3899 	        if (xmlHashLookup(doc->extSubset->entities, cur->name) == cur)
3900 		    xmlHashRemoveEntry(doc->extSubset->entities, cur->name,
3901 		                       NULL);
3902 	        if (xmlHashLookup(doc->extSubset->pentities, cur->name) == cur)
3903 		    xmlHashRemoveEntry(doc->extSubset->pentities, cur->name,
3904 		                       NULL);
3905 	    }
3906 	}
3907     }
3908     if (cur->parent != NULL) {
3909 	xmlNodePtr parent;
3910 	parent = cur->parent;
3911 	if (cur->type == XML_ATTRIBUTE_NODE) {
3912 	    if (parent->properties == (xmlAttrPtr) cur)
3913 		parent->properties = ((xmlAttrPtr) cur)->next;
3914 	} else {
3915 	    if (parent->children == cur)
3916 		parent->children = cur->next;
3917 	    if (parent->last == cur)
3918 		parent->last = cur->prev;
3919 	}
3920 	cur->parent = NULL;
3921     }
3922     if (cur->next != NULL)
3923         cur->next->prev = cur->prev;
3924     if (cur->prev != NULL)
3925         cur->prev->next = cur->next;
3926     cur->next = cur->prev = NULL;
3927 }
3928 
3929 #if defined(LIBXML_TREE_ENABLED) || defined(LIBXML_WRITER_ENABLED)
3930 /**
3931  * xmlReplaceNode:
3932  * @old:  the old node
3933  * @cur:  the node
3934  *
3935  * Unlink the old node from its current context, prune the new one
3936  * at the same place. If @cur was already inserted in a document it is
3937  * first unlinked from its existing context.
3938  *
3939  * Returns the @old node
3940  */
3941 xmlNodePtr
xmlReplaceNode(xmlNodePtr old,xmlNodePtr cur)3942 xmlReplaceNode(xmlNodePtr old, xmlNodePtr cur) {
3943     if (old == cur) return(NULL);
3944     if ((old == NULL) || (old->type == XML_NAMESPACE_DECL) ||
3945         (old->parent == NULL)) {
3946 #ifdef DEBUG_TREE
3947         xmlGenericError(xmlGenericErrorContext,
3948 		"xmlReplaceNode : old == NULL or without parent\n");
3949 #endif
3950 	return(NULL);
3951     }
3952     if ((cur == NULL) || (cur->type == XML_NAMESPACE_DECL)) {
3953 	xmlUnlinkNode(old);
3954 	return(old);
3955     }
3956     if (cur == old) {
3957 	return(old);
3958     }
3959     if ((old->type==XML_ATTRIBUTE_NODE) && (cur->type!=XML_ATTRIBUTE_NODE)) {
3960 #ifdef DEBUG_TREE
3961         xmlGenericError(xmlGenericErrorContext,
3962 		"xmlReplaceNode : Trying to replace attribute node with other node type\n");
3963 #endif
3964 	return(old);
3965     }
3966     if ((cur->type==XML_ATTRIBUTE_NODE) && (old->type!=XML_ATTRIBUTE_NODE)) {
3967 #ifdef DEBUG_TREE
3968         xmlGenericError(xmlGenericErrorContext,
3969 		"xmlReplaceNode : Trying to replace a non-attribute node with attribute node\n");
3970 #endif
3971 	return(old);
3972     }
3973     xmlUnlinkNode(cur);
3974     xmlSetTreeDoc(cur, old->doc);
3975     cur->parent = old->parent;
3976     cur->next = old->next;
3977     if (cur->next != NULL)
3978 	cur->next->prev = cur;
3979     cur->prev = old->prev;
3980     if (cur->prev != NULL)
3981 	cur->prev->next = cur;
3982     if (cur->parent != NULL) {
3983 	if (cur->type == XML_ATTRIBUTE_NODE) {
3984 	    if (cur->parent->properties == (xmlAttrPtr)old)
3985 		cur->parent->properties = ((xmlAttrPtr) cur);
3986 	} else {
3987 	    if (cur->parent->children == old)
3988 		cur->parent->children = cur;
3989 	    if (cur->parent->last == old)
3990 		cur->parent->last = cur;
3991 	}
3992     }
3993     old->next = old->prev = NULL;
3994     old->parent = NULL;
3995     return(old);
3996 }
3997 #endif /* LIBXML_TREE_ENABLED */
3998 
3999 /************************************************************************
4000  *									*
4001  *		Copy operations						*
4002  *									*
4003  ************************************************************************/
4004 
4005 /**
4006  * xmlCopyNamespace:
4007  * @cur:  the namespace
4008  *
4009  * Do a copy of the namespace.
4010  *
4011  * Returns: a new #xmlNsPtr, or NULL in case of error.
4012  */
4013 xmlNsPtr
xmlCopyNamespace(xmlNsPtr cur)4014 xmlCopyNamespace(xmlNsPtr cur) {
4015     xmlNsPtr ret;
4016 
4017     if (cur == NULL) return(NULL);
4018     switch (cur->type) {
4019 	case XML_LOCAL_NAMESPACE:
4020 	    ret = xmlNewNs(NULL, cur->href, cur->prefix);
4021 	    break;
4022 	default:
4023 #ifdef DEBUG_TREE
4024 	    xmlGenericError(xmlGenericErrorContext,
4025 		    "xmlCopyNamespace: invalid type %d\n", cur->type);
4026 #endif
4027 	    return(NULL);
4028     }
4029     return(ret);
4030 }
4031 
4032 /**
4033  * xmlCopyNamespaceList:
4034  * @cur:  the first namespace
4035  *
4036  * Do a copy of an namespace list.
4037  *
4038  * Returns: a new #xmlNsPtr, or NULL in case of error.
4039  */
4040 xmlNsPtr
xmlCopyNamespaceList(xmlNsPtr cur)4041 xmlCopyNamespaceList(xmlNsPtr cur) {
4042     xmlNsPtr ret = NULL;
4043     xmlNsPtr p = NULL,q;
4044 
4045     while (cur != NULL) {
4046         q = xmlCopyNamespace(cur);
4047 	if (p == NULL) {
4048 	    ret = p = q;
4049 	} else {
4050 	    p->next = q;
4051 	    p = q;
4052 	}
4053 	cur = cur->next;
4054     }
4055     return(ret);
4056 }
4057 
4058 static xmlNodePtr
4059 xmlStaticCopyNodeList(xmlNodePtr node, xmlDocPtr doc, xmlNodePtr parent);
4060 
4061 static xmlAttrPtr
xmlCopyPropInternal(xmlDocPtr doc,xmlNodePtr target,xmlAttrPtr cur)4062 xmlCopyPropInternal(xmlDocPtr doc, xmlNodePtr target, xmlAttrPtr cur) {
4063     xmlAttrPtr ret;
4064 
4065     if (cur == NULL) return(NULL);
4066     if ((target != NULL) && (target->type != XML_ELEMENT_NODE))
4067         return(NULL);
4068     if (target != NULL)
4069 	ret = xmlNewDocProp(target->doc, cur->name, NULL);
4070     else if (doc != NULL)
4071 	ret = xmlNewDocProp(doc, cur->name, NULL);
4072     else if (cur->parent != NULL)
4073 	ret = xmlNewDocProp(cur->parent->doc, cur->name, NULL);
4074     else if (cur->children != NULL)
4075 	ret = xmlNewDocProp(cur->children->doc, cur->name, NULL);
4076     else
4077 	ret = xmlNewDocProp(NULL, cur->name, NULL);
4078     if (ret == NULL) return(NULL);
4079     ret->parent = target;
4080 
4081     if ((cur->ns != NULL) && (target != NULL)) {
4082       xmlNsPtr ns;
4083 
4084       ns = xmlSearchNs(target->doc, target, cur->ns->prefix);
4085       if (ns == NULL) {
4086         /*
4087          * Humm, we are copying an element whose namespace is defined
4088          * out of the new tree scope. Search it in the original tree
4089          * and add it at the top of the new tree
4090          */
4091         ns = xmlSearchNs(cur->doc, cur->parent, cur->ns->prefix);
4092         if (ns != NULL) {
4093           xmlNodePtr root = target;
4094           xmlNodePtr pred = NULL;
4095 
4096           while (root->parent != NULL) {
4097             pred = root;
4098             root = root->parent;
4099           }
4100           if (root == (xmlNodePtr) target->doc) {
4101             /* correct possibly cycling above the document elt */
4102             root = pred;
4103           }
4104           ret->ns = xmlNewNs(root, ns->href, ns->prefix);
4105         }
4106       } else {
4107         /*
4108          * we have to find something appropriate here since
4109          * we can't be sure, that the namespace we found is identified
4110          * by the prefix
4111          */
4112         if (xmlStrEqual(ns->href, cur->ns->href)) {
4113           /* this is the nice case */
4114           ret->ns = ns;
4115         } else {
4116           /*
4117            * we are in trouble: we need a new reconciled namespace.
4118            * This is expensive
4119            */
4120           ret->ns = xmlNewReconciledNs(target->doc, target, cur->ns);
4121         }
4122       }
4123 
4124     } else
4125         ret->ns = NULL;
4126 
4127     if (cur->children != NULL) {
4128 	xmlNodePtr tmp;
4129 
4130 	ret->children = xmlStaticCopyNodeList(cur->children, ret->doc, (xmlNodePtr) ret);
4131 	ret->last = NULL;
4132 	tmp = ret->children;
4133 	while (tmp != NULL) {
4134 	    /* tmp->parent = (xmlNodePtr)ret; */
4135 	    if (tmp->next == NULL)
4136 	        ret->last = tmp;
4137 	    tmp = tmp->next;
4138 	}
4139     }
4140     /*
4141      * Try to handle IDs
4142      */
4143     if ((target!= NULL) && (cur!= NULL) &&
4144 	(target->doc != NULL) && (cur->doc != NULL) &&
4145 	(cur->doc->ids != NULL) && (cur->parent != NULL)) {
4146 	if (xmlIsID(cur->doc, cur->parent, cur)) {
4147 	    xmlChar *id;
4148 
4149 	    id = xmlNodeListGetString(cur->doc, cur->children, 1);
4150 	    if (id != NULL) {
4151 		xmlAddID(NULL, target->doc, id, ret);
4152 		xmlFree(id);
4153 	    }
4154 	}
4155     }
4156     return(ret);
4157 }
4158 
4159 /**
4160  * xmlCopyProp:
4161  * @target:  the element where the attribute will be grafted
4162  * @cur:  the attribute
4163  *
4164  * Do a copy of the attribute.
4165  *
4166  * Returns: a new #xmlAttrPtr, or NULL in case of error.
4167  */
4168 xmlAttrPtr
xmlCopyProp(xmlNodePtr target,xmlAttrPtr cur)4169 xmlCopyProp(xmlNodePtr target, xmlAttrPtr cur) {
4170 	return xmlCopyPropInternal(NULL, target, cur);
4171 }
4172 
4173 /**
4174  * xmlCopyPropList:
4175  * @target:  the element where the attributes will be grafted
4176  * @cur:  the first attribute
4177  *
4178  * Do a copy of an attribute list.
4179  *
4180  * Returns: a new #xmlAttrPtr, or NULL in case of error.
4181  */
4182 xmlAttrPtr
xmlCopyPropList(xmlNodePtr target,xmlAttrPtr cur)4183 xmlCopyPropList(xmlNodePtr target, xmlAttrPtr cur) {
4184     xmlAttrPtr ret = NULL;
4185     xmlAttrPtr p = NULL,q;
4186 
4187     if ((target != NULL) && (target->type != XML_ELEMENT_NODE))
4188         return(NULL);
4189     while (cur != NULL) {
4190         q = xmlCopyProp(target, cur);
4191 	if (q == NULL)
4192 	    return(NULL);
4193 	if (p == NULL) {
4194 	    ret = p = q;
4195 	} else {
4196 	    p->next = q;
4197 	    q->prev = p;
4198 	    p = q;
4199 	}
4200 	cur = cur->next;
4201     }
4202     return(ret);
4203 }
4204 
4205 /*
4206  * NOTE about the CopyNode operations !
4207  *
4208  * They are split into external and internal parts for one
4209  * tricky reason: namespaces. Doing a direct copy of a node
4210  * say RPM:Copyright without changing the namespace pointer to
4211  * something else can produce stale links. One way to do it is
4212  * to keep a reference counter but this doesn't work as soon
4213  * as one moves the element or the subtree out of the scope of
4214  * the existing namespace. The actual solution seems to be to add
4215  * a copy of the namespace at the top of the copied tree if
4216  * not available in the subtree.
4217  * Hence two functions, the public front-end call the inner ones
4218  * The argument "recursive" normally indicates a recursive copy
4219  * of the node with values 0 (no) and 1 (yes).  For XInclude,
4220  * however, we allow a value of 2 to indicate copy properties and
4221  * namespace info, but don't recurse on children.
4222  */
4223 
4224 static xmlNodePtr
xmlStaticCopyNode(xmlNodePtr node,xmlDocPtr doc,xmlNodePtr parent,int extended)4225 xmlStaticCopyNode(xmlNodePtr node, xmlDocPtr doc, xmlNodePtr parent,
4226                   int extended) {
4227     xmlNodePtr ret;
4228 
4229     if (node == NULL) return(NULL);
4230     switch (node->type) {
4231         case XML_TEXT_NODE:
4232         case XML_CDATA_SECTION_NODE:
4233         case XML_ELEMENT_NODE:
4234         case XML_DOCUMENT_FRAG_NODE:
4235         case XML_ENTITY_REF_NODE:
4236         case XML_ENTITY_NODE:
4237         case XML_PI_NODE:
4238         case XML_COMMENT_NODE:
4239         case XML_XINCLUDE_START:
4240         case XML_XINCLUDE_END:
4241 	    break;
4242         case XML_ATTRIBUTE_NODE:
4243 		return((xmlNodePtr) xmlCopyPropInternal(doc, parent, (xmlAttrPtr) node));
4244         case XML_NAMESPACE_DECL:
4245 	    return((xmlNodePtr) xmlCopyNamespaceList((xmlNsPtr) node));
4246 
4247         case XML_DOCUMENT_NODE:
4248         case XML_HTML_DOCUMENT_NODE:
4249 #ifdef LIBXML_DOCB_ENABLED
4250         case XML_DOCB_DOCUMENT_NODE:
4251 #endif
4252 #ifdef LIBXML_TREE_ENABLED
4253 	    return((xmlNodePtr) xmlCopyDoc((xmlDocPtr) node, extended));
4254 #endif /* LIBXML_TREE_ENABLED */
4255         case XML_DOCUMENT_TYPE_NODE:
4256         case XML_NOTATION_NODE:
4257         case XML_DTD_NODE:
4258         case XML_ELEMENT_DECL:
4259         case XML_ATTRIBUTE_DECL:
4260         case XML_ENTITY_DECL:
4261             return(NULL);
4262     }
4263 
4264     /*
4265      * Allocate a new node and fill the fields.
4266      */
4267     ret = (xmlNodePtr) xmlMalloc(sizeof(xmlNode));
4268     if (ret == NULL) {
4269 	xmlTreeErrMemory("copying node");
4270 	return(NULL);
4271     }
4272     memset(ret, 0, sizeof(xmlNode));
4273     ret->type = node->type;
4274 
4275     ret->doc = doc;
4276     ret->parent = parent;
4277     if (node->name == xmlStringText)
4278 	ret->name = xmlStringText;
4279     else if (node->name == xmlStringTextNoenc)
4280 	ret->name = xmlStringTextNoenc;
4281     else if (node->name == xmlStringComment)
4282 	ret->name = xmlStringComment;
4283     else if (node->name != NULL) {
4284         if ((doc != NULL) && (doc->dict != NULL))
4285 	    ret->name = xmlDictLookup(doc->dict, node->name, -1);
4286 	else
4287 	    ret->name = xmlStrdup(node->name);
4288     }
4289     if ((node->type != XML_ELEMENT_NODE) &&
4290 	(node->content != NULL) &&
4291 	(node->type != XML_ENTITY_REF_NODE) &&
4292 	(node->type != XML_XINCLUDE_END) &&
4293 	(node->type != XML_XINCLUDE_START)) {
4294 	ret->content = xmlStrdup(node->content);
4295     }else{
4296       if (node->type == XML_ELEMENT_NODE)
4297         ret->line = node->line;
4298     }
4299     if (parent != NULL) {
4300 	xmlNodePtr tmp;
4301 
4302 	/*
4303 	 * this is a tricky part for the node register thing:
4304 	 * in case ret does get coalesced in xmlAddChild
4305 	 * the deregister-node callback is called; so we register ret now already
4306 	 */
4307 	if ((__xmlRegisterCallbacks) && (xmlRegisterNodeDefaultValue))
4308 	    xmlRegisterNodeDefaultValue((xmlNodePtr)ret);
4309 
4310         tmp = xmlAddChild(parent, ret);
4311 	/* node could have coalesced */
4312 	if (tmp != ret)
4313 	    return(tmp);
4314     }
4315 
4316     if (!extended)
4317 	goto out;
4318     if (((node->type == XML_ELEMENT_NODE) ||
4319          (node->type == XML_XINCLUDE_START)) && (node->nsDef != NULL))
4320         ret->nsDef = xmlCopyNamespaceList(node->nsDef);
4321 
4322     if (node->ns != NULL) {
4323         xmlNsPtr ns;
4324 
4325 	ns = xmlSearchNs(doc, ret, node->ns->prefix);
4326 	if (ns == NULL) {
4327 	    /*
4328 	     * Humm, we are copying an element whose namespace is defined
4329 	     * out of the new tree scope. Search it in the original tree
4330 	     * and add it at the top of the new tree
4331 	     */
4332 	    ns = xmlSearchNs(node->doc, node, node->ns->prefix);
4333 	    if (ns != NULL) {
4334 	        xmlNodePtr root = ret;
4335 
4336 		while (root->parent != NULL) root = root->parent;
4337 		ret->ns = xmlNewNs(root, ns->href, ns->prefix);
4338 		} else {
4339 			ret->ns = xmlNewReconciledNs(doc, ret, node->ns);
4340 	    }
4341 	} else {
4342 	    /*
4343 	     * reference the existing namespace definition in our own tree.
4344 	     */
4345 	    ret->ns = ns;
4346 	}
4347     }
4348     if (((node->type == XML_ELEMENT_NODE) ||
4349          (node->type == XML_XINCLUDE_START)) && (node->properties != NULL))
4350         ret->properties = xmlCopyPropList(ret, node->properties);
4351     if (node->type == XML_ENTITY_REF_NODE) {
4352 	if ((doc == NULL) || (node->doc != doc)) {
4353 	    /*
4354 	     * The copied node will go into a separate document, so
4355 	     * to avoid dangling references to the ENTITY_DECL node
4356 	     * we cannot keep the reference. Try to find it in the
4357 	     * target document.
4358 	     */
4359 	    ret->children = (xmlNodePtr) xmlGetDocEntity(doc, ret->name);
4360 	} else {
4361             ret->children = node->children;
4362 	}
4363 	ret->last = ret->children;
4364     } else if ((node->children != NULL) && (extended != 2)) {
4365         ret->children = xmlStaticCopyNodeList(node->children, doc, ret);
4366 	UPDATE_LAST_CHILD_AND_PARENT(ret)
4367     }
4368 
4369 out:
4370     /* if parent != NULL we already registered the node above */
4371     if ((parent == NULL) &&
4372         ((__xmlRegisterCallbacks) && (xmlRegisterNodeDefaultValue)))
4373 	xmlRegisterNodeDefaultValue((xmlNodePtr)ret);
4374     return(ret);
4375 }
4376 
4377 static xmlNodePtr
xmlStaticCopyNodeList(xmlNodePtr node,xmlDocPtr doc,xmlNodePtr parent)4378 xmlStaticCopyNodeList(xmlNodePtr node, xmlDocPtr doc, xmlNodePtr parent) {
4379     xmlNodePtr ret = NULL;
4380     xmlNodePtr p = NULL,q;
4381 
4382     while (node != NULL) {
4383 #ifdef LIBXML_TREE_ENABLED
4384 	if (node->type == XML_DTD_NODE ) {
4385 	    if (doc == NULL) {
4386 		node = node->next;
4387 		continue;
4388 	    }
4389 	    if (doc->intSubset == NULL) {
4390 		q = (xmlNodePtr) xmlCopyDtd( (xmlDtdPtr) node );
4391 		if (q == NULL) return(NULL);
4392 		q->doc = doc;
4393 		q->parent = parent;
4394 		doc->intSubset = (xmlDtdPtr) q;
4395 		xmlAddChild(parent, q);
4396 	    } else {
4397 		q = (xmlNodePtr) doc->intSubset;
4398 		xmlAddChild(parent, q);
4399 	    }
4400 	} else
4401 #endif /* LIBXML_TREE_ENABLED */
4402 	    q = xmlStaticCopyNode(node, doc, parent, 1);
4403 	if (q == NULL) return(NULL);
4404 	if (ret == NULL) {
4405 	    q->prev = NULL;
4406 	    ret = p = q;
4407 	} else if (p != q) {
4408 	/* the test is required if xmlStaticCopyNode coalesced 2 text nodes */
4409 	    p->next = q;
4410 	    q->prev = p;
4411 	    p = q;
4412 	}
4413 	node = node->next;
4414     }
4415     return(ret);
4416 }
4417 
4418 /**
4419  * xmlCopyNode:
4420  * @node:  the node
4421  * @extended:   if 1 do a recursive copy (properties, namespaces and children
4422  *			when applicable)
4423  *		if 2 copy properties and namespaces (when applicable)
4424  *
4425  * Do a copy of the node.
4426  *
4427  * Returns: a new #xmlNodePtr, or NULL in case of error.
4428  */
4429 xmlNodePtr
xmlCopyNode(xmlNodePtr node,int extended)4430 xmlCopyNode(xmlNodePtr node, int extended) {
4431     xmlNodePtr ret;
4432 
4433     ret = xmlStaticCopyNode(node, NULL, NULL, extended);
4434     return(ret);
4435 }
4436 
4437 /**
4438  * xmlDocCopyNode:
4439  * @node:  the node
4440  * @doc:  the document
4441  * @extended:   if 1 do a recursive copy (properties, namespaces and children
4442  *			when applicable)
4443  *		if 2 copy properties and namespaces (when applicable)
4444  *
4445  * Do a copy of the node to a given document.
4446  *
4447  * Returns: a new #xmlNodePtr, or NULL in case of error.
4448  */
4449 xmlNodePtr
xmlDocCopyNode(xmlNodePtr node,xmlDocPtr doc,int extended)4450 xmlDocCopyNode(xmlNodePtr node, xmlDocPtr doc, int extended) {
4451     xmlNodePtr ret;
4452 
4453     ret = xmlStaticCopyNode(node, doc, NULL, extended);
4454     return(ret);
4455 }
4456 
4457 /**
4458  * xmlDocCopyNodeList:
4459  * @doc: the target document
4460  * @node:  the first node in the list.
4461  *
4462  * Do a recursive copy of the node list.
4463  *
4464  * Returns: a new #xmlNodePtr, or NULL in case of error.
4465  */
xmlDocCopyNodeList(xmlDocPtr doc,xmlNodePtr node)4466 xmlNodePtr xmlDocCopyNodeList(xmlDocPtr doc, xmlNodePtr node) {
4467     xmlNodePtr ret = xmlStaticCopyNodeList(node, doc, NULL);
4468     return(ret);
4469 }
4470 
4471 /**
4472  * xmlCopyNodeList:
4473  * @node:  the first node in the list.
4474  *
4475  * Do a recursive copy of the node list.
4476  * Use xmlDocCopyNodeList() if possible to ensure string interning.
4477  *
4478  * Returns: a new #xmlNodePtr, or NULL in case of error.
4479  */
xmlCopyNodeList(xmlNodePtr node)4480 xmlNodePtr xmlCopyNodeList(xmlNodePtr node) {
4481     xmlNodePtr ret = xmlStaticCopyNodeList(node, NULL, NULL);
4482     return(ret);
4483 }
4484 
4485 #if defined(LIBXML_TREE_ENABLED)
4486 /**
4487  * xmlCopyDtd:
4488  * @dtd:  the dtd
4489  *
4490  * Do a copy of the dtd.
4491  *
4492  * Returns: a new #xmlDtdPtr, or NULL in case of error.
4493  */
4494 xmlDtdPtr
xmlCopyDtd(xmlDtdPtr dtd)4495 xmlCopyDtd(xmlDtdPtr dtd) {
4496     xmlDtdPtr ret;
4497     xmlNodePtr cur, p = NULL, q;
4498 
4499     if (dtd == NULL) return(NULL);
4500     ret = xmlNewDtd(NULL, dtd->name, dtd->ExternalID, dtd->SystemID);
4501     if (ret == NULL) return(NULL);
4502     if (dtd->entities != NULL)
4503         ret->entities = (void *) xmlCopyEntitiesTable(
4504 	                    (xmlEntitiesTablePtr) dtd->entities);
4505     if (dtd->notations != NULL)
4506         ret->notations = (void *) xmlCopyNotationTable(
4507 	                    (xmlNotationTablePtr) dtd->notations);
4508     if (dtd->elements != NULL)
4509         ret->elements = (void *) xmlCopyElementTable(
4510 	                    (xmlElementTablePtr) dtd->elements);
4511     if (dtd->attributes != NULL)
4512         ret->attributes = (void *) xmlCopyAttributeTable(
4513 	                    (xmlAttributeTablePtr) dtd->attributes);
4514     if (dtd->pentities != NULL)
4515 	ret->pentities = (void *) xmlCopyEntitiesTable(
4516 			    (xmlEntitiesTablePtr) dtd->pentities);
4517 
4518     cur = dtd->children;
4519     while (cur != NULL) {
4520 	q = NULL;
4521 
4522 	if (cur->type == XML_ENTITY_DECL) {
4523 	    xmlEntityPtr tmp = (xmlEntityPtr) cur;
4524 	    switch (tmp->etype) {
4525 		case XML_INTERNAL_GENERAL_ENTITY:
4526 		case XML_EXTERNAL_GENERAL_PARSED_ENTITY:
4527 		case XML_EXTERNAL_GENERAL_UNPARSED_ENTITY:
4528 		    q = (xmlNodePtr) xmlGetEntityFromDtd(ret, tmp->name);
4529 		    break;
4530 		case XML_INTERNAL_PARAMETER_ENTITY:
4531 		case XML_EXTERNAL_PARAMETER_ENTITY:
4532 		    q = (xmlNodePtr)
4533 			xmlGetParameterEntityFromDtd(ret, tmp->name);
4534 		    break;
4535 		case XML_INTERNAL_PREDEFINED_ENTITY:
4536 		    break;
4537 	    }
4538 	} else if (cur->type == XML_ELEMENT_DECL) {
4539 	    xmlElementPtr tmp = (xmlElementPtr) cur;
4540 	    q = (xmlNodePtr)
4541 		xmlGetDtdQElementDesc(ret, tmp->name, tmp->prefix);
4542 	} else if (cur->type == XML_ATTRIBUTE_DECL) {
4543 	    xmlAttributePtr tmp = (xmlAttributePtr) cur;
4544 	    q = (xmlNodePtr)
4545 		xmlGetDtdQAttrDesc(ret, tmp->elem, tmp->name, tmp->prefix);
4546 	} else if (cur->type == XML_COMMENT_NODE) {
4547 	    q = xmlCopyNode(cur, 0);
4548 	}
4549 
4550 	if (q == NULL) {
4551 	    cur = cur->next;
4552 	    continue;
4553 	}
4554 
4555 	if (p == NULL)
4556 	    ret->children = q;
4557 	else
4558 	    p->next = q;
4559 
4560 	q->prev = p;
4561 	q->parent = (xmlNodePtr) ret;
4562 	q->next = NULL;
4563 	ret->last = q;
4564 	p = q;
4565 	cur = cur->next;
4566     }
4567 
4568     return(ret);
4569 }
4570 #endif
4571 
4572 #if defined(LIBXML_TREE_ENABLED) || defined(LIBXML_SCHEMAS_ENABLED)
4573 /**
4574  * xmlCopyDoc:
4575  * @doc:  the document
4576  * @recursive:  if not zero do a recursive copy.
4577  *
4578  * Do a copy of the document info. If recursive, the content tree will
4579  * be copied too as well as DTD, namespaces and entities.
4580  *
4581  * Returns: a new #xmlDocPtr, or NULL in case of error.
4582  */
4583 xmlDocPtr
xmlCopyDoc(xmlDocPtr doc,int recursive)4584 xmlCopyDoc(xmlDocPtr doc, int recursive) {
4585     xmlDocPtr ret;
4586 
4587     if (doc == NULL) return(NULL);
4588     ret = xmlNewDoc(doc->version);
4589     if (ret == NULL) return(NULL);
4590     ret->type = doc->type;
4591     if (doc->name != NULL)
4592         ret->name = xmlMemStrdup(doc->name);
4593     if (doc->encoding != NULL)
4594         ret->encoding = xmlStrdup(doc->encoding);
4595     if (doc->URL != NULL)
4596         ret->URL = xmlStrdup(doc->URL);
4597     ret->charset = doc->charset;
4598     ret->compression = doc->compression;
4599     ret->standalone = doc->standalone;
4600     if (!recursive) return(ret);
4601 
4602     ret->last = NULL;
4603     ret->children = NULL;
4604 #ifdef LIBXML_TREE_ENABLED
4605     if (doc->intSubset != NULL) {
4606         ret->intSubset = xmlCopyDtd(doc->intSubset);
4607 	if (ret->intSubset == NULL) {
4608 	    xmlFreeDoc(ret);
4609 	    return(NULL);
4610 	}
4611 	xmlSetTreeDoc((xmlNodePtr)ret->intSubset, ret);
4612 	ret->intSubset->parent = ret;
4613     }
4614 #endif
4615     if (doc->oldNs != NULL)
4616         ret->oldNs = xmlCopyNamespaceList(doc->oldNs);
4617     if (doc->children != NULL) {
4618 	xmlNodePtr tmp;
4619 
4620 	ret->children = xmlStaticCopyNodeList(doc->children, ret,
4621 		                               (xmlNodePtr)ret);
4622 	ret->last = NULL;
4623 	tmp = ret->children;
4624 	while (tmp != NULL) {
4625 	    if (tmp->next == NULL)
4626 	        ret->last = tmp;
4627 	    tmp = tmp->next;
4628 	}
4629     }
4630     return(ret);
4631 }
4632 #endif /* LIBXML_TREE_ENABLED */
4633 
4634 /************************************************************************
4635  *									*
4636  *		Content access functions				*
4637  *									*
4638  ************************************************************************/
4639 
4640 /**
4641  * xmlGetLineNoInternal:
4642  * @node: valid node
4643  * @depth: used to limit any risk of recursion
4644  *
4645  * Get line number of @node.
4646  * Try to override the limitation of lines being store in 16 bits ints
4647  *
4648  * Returns the line number if successful, -1 otherwise
4649  */
4650 static long
xmlGetLineNoInternal(const xmlNode * node,int depth)4651 xmlGetLineNoInternal(const xmlNode *node, int depth)
4652 {
4653     long result = -1;
4654 
4655     if (depth >= 5)
4656         return(-1);
4657 
4658     if (!node)
4659         return result;
4660     if ((node->type == XML_ELEMENT_NODE) ||
4661         (node->type == XML_TEXT_NODE) ||
4662 	(node->type == XML_COMMENT_NODE) ||
4663 	(node->type == XML_PI_NODE)) {
4664 	if (node->line == 65535) {
4665 	    if ((node->type == XML_TEXT_NODE) && (node->psvi != NULL))
4666 	        result = (long) (ptrdiff_t) node->psvi;
4667 	    else if ((node->type == XML_ELEMENT_NODE) &&
4668 	             (node->children != NULL))
4669 	        result = xmlGetLineNoInternal(node->children, depth + 1);
4670 	    else if (node->next != NULL)
4671 	        result = xmlGetLineNoInternal(node->next, depth + 1);
4672 	    else if (node->prev != NULL)
4673 	        result = xmlGetLineNoInternal(node->prev, depth + 1);
4674 	}
4675 	if ((result == -1) || (result == 65535))
4676 	    result = (long) node->line;
4677     } else if ((node->prev != NULL) &&
4678              ((node->prev->type == XML_ELEMENT_NODE) ||
4679 	      (node->prev->type == XML_TEXT_NODE) ||
4680 	      (node->prev->type == XML_COMMENT_NODE) ||
4681 	      (node->prev->type == XML_PI_NODE)))
4682         result = xmlGetLineNoInternal(node->prev, depth + 1);
4683     else if ((node->parent != NULL) &&
4684              (node->parent->type == XML_ELEMENT_NODE))
4685         result = xmlGetLineNoInternal(node->parent, depth + 1);
4686 
4687     return result;
4688 }
4689 
4690 /**
4691  * xmlGetLineNo:
4692  * @node: valid node
4693  *
4694  * Get line number of @node.
4695  * Try to override the limitation of lines being store in 16 bits ints
4696  * if XML_PARSE_BIG_LINES parser option was used
4697  *
4698  * Returns the line number if successful, -1 otherwise
4699  */
4700 long
xmlGetLineNo(const xmlNode * node)4701 xmlGetLineNo(const xmlNode *node)
4702 {
4703     return(xmlGetLineNoInternal(node, 0));
4704 }
4705 
4706 #if defined(LIBXML_TREE_ENABLED) || defined(LIBXML_DEBUG_ENABLED)
4707 /**
4708  * xmlGetNodePath:
4709  * @node: a node
4710  *
4711  * Build a structure based Path for the given node
4712  *
4713  * Returns the new path or NULL in case of error. The caller must free
4714  *     the returned string
4715  */
4716 xmlChar *
xmlGetNodePath(const xmlNode * node)4717 xmlGetNodePath(const xmlNode *node)
4718 {
4719     const xmlNode *cur, *tmp, *next;
4720     xmlChar *buffer = NULL, *temp;
4721     size_t buf_len;
4722     xmlChar *buf;
4723     const char *sep;
4724     const char *name;
4725     char nametemp[100];
4726     int occur = 0, generic;
4727 
4728     if ((node == NULL) || (node->type == XML_NAMESPACE_DECL))
4729         return (NULL);
4730 
4731     buf_len = 500;
4732     buffer = (xmlChar *) xmlMallocAtomic(buf_len * sizeof(xmlChar));
4733     if (buffer == NULL) {
4734 	xmlTreeErrMemory("getting node path");
4735         return (NULL);
4736     }
4737     buf = (xmlChar *) xmlMallocAtomic(buf_len * sizeof(xmlChar));
4738     if (buf == NULL) {
4739 	xmlTreeErrMemory("getting node path");
4740         xmlFree(buffer);
4741         return (NULL);
4742     }
4743 
4744     buffer[0] = 0;
4745     cur = node;
4746     do {
4747         name = "";
4748         sep = "?";
4749         occur = 0;
4750         if ((cur->type == XML_DOCUMENT_NODE) ||
4751             (cur->type == XML_HTML_DOCUMENT_NODE)) {
4752             if (buffer[0] == '/')
4753                 break;
4754             sep = "/";
4755             next = NULL;
4756         } else if (cur->type == XML_ELEMENT_NODE) {
4757 	    generic = 0;
4758             sep = "/";
4759             name = (const char *) cur->name;
4760             if (cur->ns) {
4761 		if (cur->ns->prefix != NULL) {
4762                     snprintf(nametemp, sizeof(nametemp) - 1, "%s:%s",
4763 			(char *)cur->ns->prefix, (char *)cur->name);
4764 		    nametemp[sizeof(nametemp) - 1] = 0;
4765 		    name = nametemp;
4766 		} else {
4767 		    /*
4768 		    * We cannot express named elements in the default
4769 		    * namespace, so use "*".
4770 		    */
4771 		    generic = 1;
4772 		    name = "*";
4773 		}
4774             }
4775             next = cur->parent;
4776 
4777             /*
4778              * Thumbler index computation
4779 	     * TODO: the occurrence test seems bogus for namespaced names
4780              */
4781             tmp = cur->prev;
4782             while (tmp != NULL) {
4783                 if ((tmp->type == XML_ELEMENT_NODE) &&
4784 		    (generic ||
4785 		     (xmlStrEqual(cur->name, tmp->name) &&
4786 		     ((tmp->ns == cur->ns) ||
4787 		      ((tmp->ns != NULL) && (cur->ns != NULL) &&
4788 		       (xmlStrEqual(cur->ns->prefix, tmp->ns->prefix)))))))
4789                     occur++;
4790                 tmp = tmp->prev;
4791             }
4792             if (occur == 0) {
4793                 tmp = cur->next;
4794                 while (tmp != NULL && occur == 0) {
4795                     if ((tmp->type == XML_ELEMENT_NODE) &&
4796 			(generic ||
4797 			 (xmlStrEqual(cur->name, tmp->name) &&
4798 			 ((tmp->ns == cur->ns) ||
4799 			  ((tmp->ns != NULL) && (cur->ns != NULL) &&
4800 			   (xmlStrEqual(cur->ns->prefix, tmp->ns->prefix)))))))
4801                         occur++;
4802                     tmp = tmp->next;
4803                 }
4804                 if (occur != 0)
4805                     occur = 1;
4806             } else
4807                 occur++;
4808         } else if (cur->type == XML_COMMENT_NODE) {
4809             sep = "/";
4810 	    name = "comment()";
4811             next = cur->parent;
4812 
4813             /*
4814              * Thumbler index computation
4815              */
4816             tmp = cur->prev;
4817             while (tmp != NULL) {
4818                 if (tmp->type == XML_COMMENT_NODE)
4819 		    occur++;
4820                 tmp = tmp->prev;
4821             }
4822             if (occur == 0) {
4823                 tmp = cur->next;
4824                 while (tmp != NULL && occur == 0) {
4825 		    if (tmp->type == XML_COMMENT_NODE)
4826 		        occur++;
4827                     tmp = tmp->next;
4828                 }
4829                 if (occur != 0)
4830                     occur = 1;
4831             } else
4832                 occur++;
4833         } else if ((cur->type == XML_TEXT_NODE) ||
4834                    (cur->type == XML_CDATA_SECTION_NODE)) {
4835             sep = "/";
4836 	    name = "text()";
4837             next = cur->parent;
4838 
4839             /*
4840              * Thumbler index computation
4841              */
4842             tmp = cur->prev;
4843             while (tmp != NULL) {
4844                 if ((tmp->type == XML_TEXT_NODE) ||
4845 		    (tmp->type == XML_CDATA_SECTION_NODE))
4846 		    occur++;
4847                 tmp = tmp->prev;
4848             }
4849 	    /*
4850 	    * Evaluate if this is the only text- or CDATA-section-node;
4851 	    * if yes, then we'll get "text()", otherwise "text()[1]".
4852 	    */
4853             if (occur == 0) {
4854                 tmp = cur->next;
4855                 while (tmp != NULL) {
4856 		    if ((tmp->type == XML_TEXT_NODE) ||
4857 			(tmp->type == XML_CDATA_SECTION_NODE))
4858 		    {
4859 			occur = 1;
4860 			break;
4861 		    }
4862 		    tmp = tmp->next;
4863 		}
4864             } else
4865                 occur++;
4866         } else if (cur->type == XML_PI_NODE) {
4867             sep = "/";
4868 	    snprintf(nametemp, sizeof(nametemp) - 1,
4869 		     "processing-instruction('%s')", (char *)cur->name);
4870             nametemp[sizeof(nametemp) - 1] = 0;
4871             name = nametemp;
4872 
4873 	    next = cur->parent;
4874 
4875             /*
4876              * Thumbler index computation
4877              */
4878             tmp = cur->prev;
4879             while (tmp != NULL) {
4880                 if ((tmp->type == XML_PI_NODE) &&
4881 		    (xmlStrEqual(cur->name, tmp->name)))
4882                     occur++;
4883                 tmp = tmp->prev;
4884             }
4885             if (occur == 0) {
4886                 tmp = cur->next;
4887                 while (tmp != NULL && occur == 0) {
4888                     if ((tmp->type == XML_PI_NODE) &&
4889 			(xmlStrEqual(cur->name, tmp->name)))
4890                         occur++;
4891                     tmp = tmp->next;
4892                 }
4893                 if (occur != 0)
4894                     occur = 1;
4895             } else
4896                 occur++;
4897 
4898         } else if (cur->type == XML_ATTRIBUTE_NODE) {
4899             sep = "/@";
4900             name = (const char *) (((xmlAttrPtr) cur)->name);
4901             if (cur->ns) {
4902 	        if (cur->ns->prefix != NULL)
4903                     snprintf(nametemp, sizeof(nametemp) - 1, "%s:%s",
4904 			(char *)cur->ns->prefix, (char *)cur->name);
4905 		else
4906 		    snprintf(nametemp, sizeof(nametemp) - 1, "%s",
4907 			(char *)cur->name);
4908                 nametemp[sizeof(nametemp) - 1] = 0;
4909                 name = nametemp;
4910             }
4911             next = ((xmlAttrPtr) cur)->parent;
4912         } else {
4913             xmlFree(buf);
4914             xmlFree(buffer);
4915             return (NULL);
4916         }
4917 
4918         /*
4919          * Make sure there is enough room
4920          */
4921         if (xmlStrlen(buffer) + sizeof(nametemp) + 20 > buf_len) {
4922             buf_len =
4923                 2 * buf_len + xmlStrlen(buffer) + sizeof(nametemp) + 20;
4924             temp = (xmlChar *) xmlRealloc(buffer, buf_len);
4925             if (temp == NULL) {
4926 		xmlTreeErrMemory("getting node path");
4927                 xmlFree(buf);
4928                 xmlFree(buffer);
4929                 return (NULL);
4930             }
4931             buffer = temp;
4932             temp = (xmlChar *) xmlRealloc(buf, buf_len);
4933             if (temp == NULL) {
4934 		xmlTreeErrMemory("getting node path");
4935                 xmlFree(buf);
4936                 xmlFree(buffer);
4937                 return (NULL);
4938             }
4939             buf = temp;
4940         }
4941         if (occur == 0)
4942             snprintf((char *) buf, buf_len, "%s%s%s",
4943                      sep, name, (char *) buffer);
4944         else
4945             snprintf((char *) buf, buf_len, "%s%s[%d]%s",
4946                      sep, name, occur, (char *) buffer);
4947         snprintf((char *) buffer, buf_len, "%s", (char *)buf);
4948         cur = next;
4949     } while (cur != NULL);
4950     xmlFree(buf);
4951     return (buffer);
4952 }
4953 #endif /* LIBXML_TREE_ENABLED */
4954 
4955 /**
4956  * xmlDocGetRootElement:
4957  * @doc:  the document
4958  *
4959  * Get the root element of the document (doc->children is a list
4960  * containing possibly comments, PIs, etc ...).
4961  *
4962  * Returns the #xmlNodePtr for the root or NULL
4963  */
4964 xmlNodePtr
xmlDocGetRootElement(const xmlDoc * doc)4965 xmlDocGetRootElement(const xmlDoc *doc) {
4966     xmlNodePtr ret;
4967 
4968     if (doc == NULL) return(NULL);
4969     ret = doc->children;
4970     while (ret != NULL) {
4971 	if (ret->type == XML_ELEMENT_NODE)
4972 	    return(ret);
4973         ret = ret->next;
4974     }
4975     return(ret);
4976 }
4977 
4978 #if defined(LIBXML_TREE_ENABLED) || defined(LIBXML_WRITER_ENABLED)
4979 /**
4980  * xmlDocSetRootElement:
4981  * @doc:  the document
4982  * @root:  the new document root element, if root is NULL no action is taken,
4983  *         to remove a node from a document use xmlUnlinkNode(root) instead.
4984  *
4985  * Set the root element of the document (doc->children is a list
4986  * containing possibly comments, PIs, etc ...).
4987  *
4988  * Returns the old root element if any was found, NULL if root was NULL
4989  */
4990 xmlNodePtr
xmlDocSetRootElement(xmlDocPtr doc,xmlNodePtr root)4991 xmlDocSetRootElement(xmlDocPtr doc, xmlNodePtr root) {
4992     xmlNodePtr old = NULL;
4993 
4994     if (doc == NULL) return(NULL);
4995     if ((root == NULL) || (root->type == XML_NAMESPACE_DECL))
4996 	return(NULL);
4997     xmlUnlinkNode(root);
4998     xmlSetTreeDoc(root, doc);
4999     root->parent = (xmlNodePtr) doc;
5000     old = doc->children;
5001     while (old != NULL) {
5002 	if (old->type == XML_ELEMENT_NODE)
5003 	    break;
5004         old = old->next;
5005     }
5006     if (old == NULL) {
5007 	if (doc->children == NULL) {
5008 	    doc->children = root;
5009 	    doc->last = root;
5010 	} else {
5011 	    xmlAddSibling(doc->children, root);
5012 	}
5013     } else {
5014 	xmlReplaceNode(old, root);
5015     }
5016     return(old);
5017 }
5018 #endif
5019 
5020 #if defined(LIBXML_TREE_ENABLED)
5021 /**
5022  * xmlNodeSetLang:
5023  * @cur:  the node being changed
5024  * @lang:  the language description
5025  *
5026  * Set the language of a node, i.e. the values of the xml:lang
5027  * attribute.
5028  */
5029 void
xmlNodeSetLang(xmlNodePtr cur,const xmlChar * lang)5030 xmlNodeSetLang(xmlNodePtr cur, const xmlChar *lang) {
5031     xmlNsPtr ns;
5032 
5033     if (cur == NULL) return;
5034     switch(cur->type) {
5035         case XML_TEXT_NODE:
5036         case XML_CDATA_SECTION_NODE:
5037         case XML_COMMENT_NODE:
5038         case XML_DOCUMENT_NODE:
5039         case XML_DOCUMENT_TYPE_NODE:
5040         case XML_DOCUMENT_FRAG_NODE:
5041         case XML_NOTATION_NODE:
5042         case XML_HTML_DOCUMENT_NODE:
5043         case XML_DTD_NODE:
5044         case XML_ELEMENT_DECL:
5045         case XML_ATTRIBUTE_DECL:
5046         case XML_ENTITY_DECL:
5047         case XML_PI_NODE:
5048         case XML_ENTITY_REF_NODE:
5049         case XML_ENTITY_NODE:
5050 	case XML_NAMESPACE_DECL:
5051 #ifdef LIBXML_DOCB_ENABLED
5052 	case XML_DOCB_DOCUMENT_NODE:
5053 #endif
5054 	case XML_XINCLUDE_START:
5055 	case XML_XINCLUDE_END:
5056 	    return;
5057         case XML_ELEMENT_NODE:
5058         case XML_ATTRIBUTE_NODE:
5059 	    break;
5060     }
5061     ns = xmlSearchNsByHref(cur->doc, cur, XML_XML_NAMESPACE);
5062     if (ns == NULL)
5063 	return;
5064     xmlSetNsProp(cur, ns, BAD_CAST "lang", lang);
5065 }
5066 #endif /* LIBXML_TREE_ENABLED */
5067 
5068 /**
5069  * xmlNodeGetLang:
5070  * @cur:  the node being checked
5071  *
5072  * Searches the language of a node, i.e. the values of the xml:lang
5073  * attribute or the one carried by the nearest ancestor.
5074  *
5075  * Returns a pointer to the lang value, or NULL if not found
5076  *     It's up to the caller to free the memory with xmlFree().
5077  */
5078 xmlChar *
xmlNodeGetLang(const xmlNode * cur)5079 xmlNodeGetLang(const xmlNode *cur) {
5080     xmlChar *lang;
5081 
5082     if ((cur == NULL) || (cur->type == XML_NAMESPACE_DECL))
5083         return(NULL);
5084     while (cur != NULL) {
5085         lang = xmlGetNsProp(cur, BAD_CAST "lang", XML_XML_NAMESPACE);
5086 	if (lang != NULL)
5087 	    return(lang);
5088 	cur = cur->parent;
5089     }
5090     return(NULL);
5091 }
5092 
5093 
5094 #ifdef LIBXML_TREE_ENABLED
5095 /**
5096  * xmlNodeSetSpacePreserve:
5097  * @cur:  the node being changed
5098  * @val:  the xml:space value ("0": default, 1: "preserve")
5099  *
5100  * Set (or reset) the space preserving behaviour of a node, i.e. the
5101  * value of the xml:space attribute.
5102  */
5103 void
xmlNodeSetSpacePreserve(xmlNodePtr cur,int val)5104 xmlNodeSetSpacePreserve(xmlNodePtr cur, int val) {
5105     xmlNsPtr ns;
5106 
5107     if (cur == NULL) return;
5108     switch(cur->type) {
5109         case XML_TEXT_NODE:
5110         case XML_CDATA_SECTION_NODE:
5111         case XML_COMMENT_NODE:
5112         case XML_DOCUMENT_NODE:
5113         case XML_DOCUMENT_TYPE_NODE:
5114         case XML_DOCUMENT_FRAG_NODE:
5115         case XML_NOTATION_NODE:
5116         case XML_HTML_DOCUMENT_NODE:
5117         case XML_DTD_NODE:
5118         case XML_ELEMENT_DECL:
5119         case XML_ATTRIBUTE_DECL:
5120         case XML_ENTITY_DECL:
5121         case XML_PI_NODE:
5122         case XML_ENTITY_REF_NODE:
5123         case XML_ENTITY_NODE:
5124 	case XML_NAMESPACE_DECL:
5125 	case XML_XINCLUDE_START:
5126 	case XML_XINCLUDE_END:
5127 #ifdef LIBXML_DOCB_ENABLED
5128 	case XML_DOCB_DOCUMENT_NODE:
5129 #endif
5130 	    return;
5131         case XML_ELEMENT_NODE:
5132         case XML_ATTRIBUTE_NODE:
5133 	    break;
5134     }
5135     ns = xmlSearchNsByHref(cur->doc, cur, XML_XML_NAMESPACE);
5136     if (ns == NULL)
5137 	return;
5138     switch (val) {
5139     case 0:
5140 	xmlSetNsProp(cur, ns, BAD_CAST "space", BAD_CAST "default");
5141 	break;
5142     case 1:
5143 	xmlSetNsProp(cur, ns, BAD_CAST "space", BAD_CAST "preserve");
5144 	break;
5145     }
5146 }
5147 #endif /* LIBXML_TREE_ENABLED */
5148 
5149 /**
5150  * xmlNodeGetSpacePreserve:
5151  * @cur:  the node being checked
5152  *
5153  * Searches the space preserving behaviour of a node, i.e. the values
5154  * of the xml:space attribute or the one carried by the nearest
5155  * ancestor.
5156  *
5157  * Returns -1 if xml:space is not inherited, 0 if "default", 1 if "preserve"
5158  */
5159 int
xmlNodeGetSpacePreserve(const xmlNode * cur)5160 xmlNodeGetSpacePreserve(const xmlNode *cur) {
5161     xmlChar *space;
5162 
5163     if ((cur == NULL) || (cur->type != XML_ELEMENT_NODE))
5164         return(-1);
5165     while (cur != NULL) {
5166 	space = xmlGetNsProp(cur, BAD_CAST "space", XML_XML_NAMESPACE);
5167 	if (space != NULL) {
5168 	    if (xmlStrEqual(space, BAD_CAST "preserve")) {
5169 		xmlFree(space);
5170 		return(1);
5171 	    }
5172 	    if (xmlStrEqual(space, BAD_CAST "default")) {
5173 		xmlFree(space);
5174 		return(0);
5175 	    }
5176 	    xmlFree(space);
5177 	}
5178 	cur = cur->parent;
5179     }
5180     return(-1);
5181 }
5182 
5183 #ifdef LIBXML_TREE_ENABLED
5184 /**
5185  * xmlNodeSetName:
5186  * @cur:  the node being changed
5187  * @name:  the new tag name
5188  *
5189  * Set (or reset) the name of a node.
5190  */
5191 void
xmlNodeSetName(xmlNodePtr cur,const xmlChar * name)5192 xmlNodeSetName(xmlNodePtr cur, const xmlChar *name) {
5193     xmlDocPtr doc;
5194     xmlDictPtr dict;
5195     const xmlChar *freeme = NULL;
5196 
5197     if (cur == NULL) return;
5198     if (name == NULL) return;
5199     switch(cur->type) {
5200         case XML_TEXT_NODE:
5201         case XML_CDATA_SECTION_NODE:
5202         case XML_COMMENT_NODE:
5203         case XML_DOCUMENT_TYPE_NODE:
5204         case XML_DOCUMENT_FRAG_NODE:
5205         case XML_NOTATION_NODE:
5206         case XML_HTML_DOCUMENT_NODE:
5207 	case XML_NAMESPACE_DECL:
5208 	case XML_XINCLUDE_START:
5209 	case XML_XINCLUDE_END:
5210 #ifdef LIBXML_DOCB_ENABLED
5211 	case XML_DOCB_DOCUMENT_NODE:
5212 #endif
5213 	    return;
5214         case XML_ELEMENT_NODE:
5215         case XML_ATTRIBUTE_NODE:
5216         case XML_PI_NODE:
5217         case XML_ENTITY_REF_NODE:
5218         case XML_ENTITY_NODE:
5219         case XML_DTD_NODE:
5220         case XML_DOCUMENT_NODE:
5221         case XML_ELEMENT_DECL:
5222         case XML_ATTRIBUTE_DECL:
5223         case XML_ENTITY_DECL:
5224 	    break;
5225     }
5226     doc = cur->doc;
5227     if (doc != NULL)
5228 	dict = doc->dict;
5229     else
5230         dict = NULL;
5231     if (dict != NULL) {
5232         if ((cur->name != NULL) && (!xmlDictOwns(dict, cur->name)))
5233 	    freeme = cur->name;
5234 	cur->name = xmlDictLookup(dict, name, -1);
5235     } else {
5236 	if (cur->name != NULL)
5237 	    freeme = cur->name;
5238 	cur->name = xmlStrdup(name);
5239     }
5240 
5241     if (freeme)
5242         xmlFree((xmlChar *) freeme);
5243 }
5244 #endif
5245 
5246 #if defined(LIBXML_TREE_ENABLED) || defined(LIBXML_XINCLUDE_ENABLED)
5247 /**
5248  * xmlNodeSetBase:
5249  * @cur:  the node being changed
5250  * @uri:  the new base URI
5251  *
5252  * Set (or reset) the base URI of a node, i.e. the value of the
5253  * xml:base attribute.
5254  */
5255 void
xmlNodeSetBase(xmlNodePtr cur,const xmlChar * uri)5256 xmlNodeSetBase(xmlNodePtr cur, const xmlChar* uri) {
5257     xmlNsPtr ns;
5258     xmlChar* fixed;
5259 
5260     if (cur == NULL) return;
5261     switch(cur->type) {
5262         case XML_TEXT_NODE:
5263         case XML_CDATA_SECTION_NODE:
5264         case XML_COMMENT_NODE:
5265         case XML_DOCUMENT_TYPE_NODE:
5266         case XML_DOCUMENT_FRAG_NODE:
5267         case XML_NOTATION_NODE:
5268         case XML_DTD_NODE:
5269         case XML_ELEMENT_DECL:
5270         case XML_ATTRIBUTE_DECL:
5271         case XML_ENTITY_DECL:
5272         case XML_PI_NODE:
5273         case XML_ENTITY_REF_NODE:
5274         case XML_ENTITY_NODE:
5275 	case XML_NAMESPACE_DECL:
5276 	case XML_XINCLUDE_START:
5277 	case XML_XINCLUDE_END:
5278 	    return;
5279         case XML_ELEMENT_NODE:
5280         case XML_ATTRIBUTE_NODE:
5281 	    break;
5282         case XML_DOCUMENT_NODE:
5283 #ifdef LIBXML_DOCB_ENABLED
5284 	case XML_DOCB_DOCUMENT_NODE:
5285 #endif
5286         case XML_HTML_DOCUMENT_NODE: {
5287 	    xmlDocPtr doc = (xmlDocPtr) cur;
5288 
5289 	    if (doc->URL != NULL)
5290 		xmlFree((xmlChar *) doc->URL);
5291 	    if (uri == NULL)
5292 		doc->URL = NULL;
5293 	    else
5294 		doc->URL = xmlPathToURI(uri);
5295 	    return;
5296 	}
5297     }
5298 
5299     ns = xmlSearchNsByHref(cur->doc, cur, XML_XML_NAMESPACE);
5300     if (ns == NULL)
5301 	return;
5302     fixed = xmlPathToURI(uri);
5303     if (fixed != NULL) {
5304 	xmlSetNsProp(cur, ns, BAD_CAST "base", fixed);
5305 	xmlFree(fixed);
5306     } else {
5307 	xmlSetNsProp(cur, ns, BAD_CAST "base", uri);
5308     }
5309 }
5310 #endif /* LIBXML_TREE_ENABLED */
5311 
5312 /**
5313  * xmlNodeGetBase:
5314  * @doc:  the document the node pertains to
5315  * @cur:  the node being checked
5316  *
5317  * Searches for the BASE URL. The code should work on both XML
5318  * and HTML document even if base mechanisms are completely different.
5319  * It returns the base as defined in RFC 2396 sections
5320  * 5.1.1. Base URI within Document Content
5321  * and
5322  * 5.1.2. Base URI from the Encapsulating Entity
5323  * However it does not return the document base (5.1.3), use
5324  * doc->URL in this case
5325  *
5326  * Returns a pointer to the base URL, or NULL if not found
5327  *     It's up to the caller to free the memory with xmlFree().
5328  */
5329 xmlChar *
xmlNodeGetBase(const xmlDoc * doc,const xmlNode * cur)5330 xmlNodeGetBase(const xmlDoc *doc, const xmlNode *cur) {
5331     xmlChar *oldbase = NULL;
5332     xmlChar *base, *newbase;
5333 
5334     if ((cur == NULL) && (doc == NULL))
5335         return(NULL);
5336     if ((cur != NULL) && (cur->type == XML_NAMESPACE_DECL))
5337         return(NULL);
5338     if (doc == NULL) doc = cur->doc;
5339     if ((doc != NULL) && (doc->type == XML_HTML_DOCUMENT_NODE)) {
5340         cur = doc->children;
5341 	while ((cur != NULL) && (cur->name != NULL)) {
5342 	    if (cur->type != XML_ELEMENT_NODE) {
5343 	        cur = cur->next;
5344 		continue;
5345 	    }
5346 	    if (!xmlStrcasecmp(cur->name, BAD_CAST "html")) {
5347 	        cur = cur->children;
5348 		continue;
5349 	    }
5350 	    if (!xmlStrcasecmp(cur->name, BAD_CAST "head")) {
5351 	        cur = cur->children;
5352 		continue;
5353 	    }
5354 	    if (!xmlStrcasecmp(cur->name, BAD_CAST "base")) {
5355                 return(xmlGetProp(cur, BAD_CAST "href"));
5356 	    }
5357 	    cur = cur->next;
5358 	}
5359 	return(NULL);
5360     }
5361     while (cur != NULL) {
5362 	if (cur->type == XML_ENTITY_DECL) {
5363 	    xmlEntityPtr ent = (xmlEntityPtr) cur;
5364 	    return(xmlStrdup(ent->URI));
5365 	}
5366 	if (cur->type == XML_ELEMENT_NODE) {
5367 	    base = xmlGetNsProp(cur, BAD_CAST "base", XML_XML_NAMESPACE);
5368 	    if (base != NULL) {
5369 		if (oldbase != NULL) {
5370 		    newbase = xmlBuildURI(oldbase, base);
5371 		    if (newbase != NULL) {
5372 			xmlFree(oldbase);
5373 			xmlFree(base);
5374 			oldbase = newbase;
5375 		    } else {
5376 			xmlFree(oldbase);
5377 			xmlFree(base);
5378 			return(NULL);
5379 		    }
5380 		} else {
5381 		    oldbase = base;
5382 		}
5383 		if ((!xmlStrncmp(oldbase, BAD_CAST "http://", 7)) ||
5384 		    (!xmlStrncmp(oldbase, BAD_CAST "ftp://", 6)) ||
5385 		    (!xmlStrncmp(oldbase, BAD_CAST "urn:", 4)))
5386 		    return(oldbase);
5387 	    }
5388 	}
5389 	cur = cur->parent;
5390     }
5391     if ((doc != NULL) && (doc->URL != NULL)) {
5392 	if (oldbase == NULL)
5393 	    return(xmlStrdup(doc->URL));
5394 	newbase = xmlBuildURI(oldbase, doc->URL);
5395 	xmlFree(oldbase);
5396 	return(newbase);
5397     }
5398     return(oldbase);
5399 }
5400 
5401 /**
5402  * xmlNodeBufGetContent:
5403  * @buffer:  a buffer
5404  * @cur:  the node being read
5405  *
5406  * Read the value of a node @cur, this can be either the text carried
5407  * directly by this node if it's a TEXT node or the aggregate string
5408  * of the values carried by this node child's (TEXT and ENTITY_REF).
5409  * Entity references are substituted.
5410  * Fills up the buffer @buffer with this value
5411  *
5412  * Returns 0 in case of success and -1 in case of error.
5413  */
5414 int
xmlNodeBufGetContent(xmlBufferPtr buffer,const xmlNode * cur)5415 xmlNodeBufGetContent(xmlBufferPtr buffer, const xmlNode *cur)
5416 {
5417     xmlBufPtr buf;
5418     int ret;
5419 
5420     if ((cur == NULL) || (buffer == NULL)) return(-1);
5421     buf = xmlBufFromBuffer(buffer);
5422     ret = xmlBufGetNodeContent(buf, cur);
5423     buffer = xmlBufBackToBuffer(buf);
5424     if ((ret < 0) || (buffer == NULL))
5425         return(-1);
5426     return(0);
5427 }
5428 
5429 /**
5430  * xmlBufGetNodeContent:
5431  * @buf:  a buffer xmlBufPtr
5432  * @cur:  the node being read
5433  *
5434  * Read the value of a node @cur, this can be either the text carried
5435  * directly by this node if it's a TEXT node or the aggregate string
5436  * of the values carried by this node child's (TEXT and ENTITY_REF).
5437  * Entity references are substituted.
5438  * Fills up the buffer @buf with this value
5439  *
5440  * Returns 0 in case of success and -1 in case of error.
5441  */
5442 int
xmlBufGetNodeContent(xmlBufPtr buf,const xmlNode * cur)5443 xmlBufGetNodeContent(xmlBufPtr buf, const xmlNode *cur)
5444 {
5445     if ((cur == NULL) || (buf == NULL)) return(-1);
5446     switch (cur->type) {
5447         case XML_CDATA_SECTION_NODE:
5448         case XML_TEXT_NODE:
5449 	    xmlBufCat(buf, cur->content);
5450             break;
5451         case XML_DOCUMENT_FRAG_NODE:
5452         case XML_ELEMENT_NODE:{
5453                 const xmlNode *tmp = cur;
5454 
5455                 while (tmp != NULL) {
5456                     switch (tmp->type) {
5457                         case XML_CDATA_SECTION_NODE:
5458                         case XML_TEXT_NODE:
5459                             if (tmp->content != NULL)
5460                                 xmlBufCat(buf, tmp->content);
5461                             break;
5462                         case XML_ENTITY_REF_NODE:
5463                             xmlBufGetNodeContent(buf, tmp);
5464                             break;
5465                         default:
5466                             break;
5467                     }
5468                     /*
5469                      * Skip to next node
5470                      */
5471                     if (tmp->children != NULL) {
5472                         if (tmp->children->type != XML_ENTITY_DECL) {
5473                             tmp = tmp->children;
5474                             continue;
5475                         }
5476                     }
5477                     if (tmp == cur)
5478                         break;
5479 
5480                     if (tmp->next != NULL) {
5481                         tmp = tmp->next;
5482                         continue;
5483                     }
5484 
5485                     do {
5486                         tmp = tmp->parent;
5487                         if (tmp == NULL)
5488                             break;
5489                         if (tmp == cur) {
5490                             tmp = NULL;
5491                             break;
5492                         }
5493                         if (tmp->next != NULL) {
5494                             tmp = tmp->next;
5495                             break;
5496                         }
5497                     } while (tmp != NULL);
5498                 }
5499 		break;
5500             }
5501         case XML_ATTRIBUTE_NODE:{
5502                 xmlAttrPtr attr = (xmlAttrPtr) cur;
5503 		xmlNodePtr tmp = attr->children;
5504 
5505 		while (tmp != NULL) {
5506 		    if (tmp->type == XML_TEXT_NODE)
5507 		        xmlBufCat(buf, tmp->content);
5508 		    else
5509 		        xmlBufGetNodeContent(buf, tmp);
5510 		    tmp = tmp->next;
5511 		}
5512                 break;
5513             }
5514         case XML_COMMENT_NODE:
5515         case XML_PI_NODE:
5516 	    xmlBufCat(buf, cur->content);
5517             break;
5518         case XML_ENTITY_REF_NODE:{
5519                 xmlEntityPtr ent;
5520                 xmlNodePtr tmp;
5521 
5522                 /* lookup entity declaration */
5523                 ent = xmlGetDocEntity(cur->doc, cur->name);
5524                 if (ent == NULL)
5525                     return(-1);
5526 
5527                 /* an entity content can be any "well balanced chunk",
5528                  * i.e. the result of the content [43] production:
5529                  * http://www.w3.org/TR/REC-xml#NT-content
5530                  * -> we iterate through child nodes and recursive call
5531                  * xmlNodeGetContent() which handles all possible node types */
5532                 tmp = ent->children;
5533                 while (tmp) {
5534 		    xmlBufGetNodeContent(buf, tmp);
5535                     tmp = tmp->next;
5536                 }
5537 		break;
5538             }
5539         case XML_ENTITY_NODE:
5540         case XML_DOCUMENT_TYPE_NODE:
5541         case XML_NOTATION_NODE:
5542         case XML_DTD_NODE:
5543         case XML_XINCLUDE_START:
5544         case XML_XINCLUDE_END:
5545             break;
5546         case XML_DOCUMENT_NODE:
5547 #ifdef LIBXML_DOCB_ENABLED
5548         case XML_DOCB_DOCUMENT_NODE:
5549 #endif
5550         case XML_HTML_DOCUMENT_NODE:
5551 	    cur = cur->children;
5552 	    while (cur!= NULL) {
5553 		if ((cur->type == XML_ELEMENT_NODE) ||
5554 		    (cur->type == XML_TEXT_NODE) ||
5555 		    (cur->type == XML_CDATA_SECTION_NODE)) {
5556 		    xmlBufGetNodeContent(buf, cur);
5557 		}
5558 		cur = cur->next;
5559 	    }
5560 	    break;
5561         case XML_NAMESPACE_DECL:
5562 	    xmlBufCat(buf, ((xmlNsPtr) cur)->href);
5563 	    break;
5564         case XML_ELEMENT_DECL:
5565         case XML_ATTRIBUTE_DECL:
5566         case XML_ENTITY_DECL:
5567             break;
5568     }
5569     return(0);
5570 }
5571 
5572 /**
5573  * xmlNodeGetContent:
5574  * @cur:  the node being read
5575  *
5576  * Read the value of a node, this can be either the text carried
5577  * directly by this node if it's a TEXT node or the aggregate string
5578  * of the values carried by this node child's (TEXT and ENTITY_REF).
5579  * Entity references are substituted.
5580  * Returns a new #xmlChar * or NULL if no content is available.
5581  *     It's up to the caller to free the memory with xmlFree().
5582  */
5583 xmlChar *
xmlNodeGetContent(const xmlNode * cur)5584 xmlNodeGetContent(const xmlNode *cur)
5585 {
5586     if (cur == NULL)
5587         return (NULL);
5588     switch (cur->type) {
5589         case XML_DOCUMENT_FRAG_NODE:
5590         case XML_ELEMENT_NODE:{
5591                 xmlBufPtr buf;
5592                 xmlChar *ret;
5593 
5594                 buf = xmlBufCreateSize(64);
5595                 if (buf == NULL)
5596                     return (NULL);
5597 		xmlBufGetNodeContent(buf, cur);
5598                 ret = xmlBufDetach(buf);
5599                 xmlBufFree(buf);
5600                 return (ret);
5601             }
5602         case XML_ATTRIBUTE_NODE:
5603 	    return(xmlGetPropNodeValueInternal((xmlAttrPtr) cur));
5604         case XML_COMMENT_NODE:
5605         case XML_PI_NODE:
5606             if (cur->content != NULL)
5607                 return (xmlStrdup(cur->content));
5608             return (NULL);
5609         case XML_ENTITY_REF_NODE:{
5610                 xmlEntityPtr ent;
5611                 xmlBufPtr buf;
5612                 xmlChar *ret;
5613 
5614                 /* lookup entity declaration */
5615                 ent = xmlGetDocEntity(cur->doc, cur->name);
5616                 if (ent == NULL)
5617                     return (NULL);
5618 
5619                 buf = xmlBufCreate();
5620                 if (buf == NULL)
5621                     return (NULL);
5622 
5623                 xmlBufGetNodeContent(buf, cur);
5624 
5625                 ret = xmlBufDetach(buf);
5626                 xmlBufFree(buf);
5627                 return (ret);
5628             }
5629         case XML_ENTITY_NODE:
5630         case XML_DOCUMENT_TYPE_NODE:
5631         case XML_NOTATION_NODE:
5632         case XML_DTD_NODE:
5633         case XML_XINCLUDE_START:
5634         case XML_XINCLUDE_END:
5635             return (NULL);
5636         case XML_DOCUMENT_NODE:
5637 #ifdef LIBXML_DOCB_ENABLED
5638         case XML_DOCB_DOCUMENT_NODE:
5639 #endif
5640         case XML_HTML_DOCUMENT_NODE: {
5641 	    xmlBufPtr buf;
5642 	    xmlChar *ret;
5643 
5644 	    buf = xmlBufCreate();
5645 	    if (buf == NULL)
5646 		return (NULL);
5647 
5648 	    xmlBufGetNodeContent(buf, (xmlNodePtr) cur);
5649 
5650 	    ret = xmlBufDetach(buf);
5651 	    xmlBufFree(buf);
5652 	    return (ret);
5653 	}
5654         case XML_NAMESPACE_DECL: {
5655 	    xmlChar *tmp;
5656 
5657 	    tmp = xmlStrdup(((xmlNsPtr) cur)->href);
5658             return (tmp);
5659 	}
5660         case XML_ELEMENT_DECL:
5661             /* TODO !!! */
5662             return (NULL);
5663         case XML_ATTRIBUTE_DECL:
5664             /* TODO !!! */
5665             return (NULL);
5666         case XML_ENTITY_DECL:
5667             /* TODO !!! */
5668             return (NULL);
5669         case XML_CDATA_SECTION_NODE:
5670         case XML_TEXT_NODE:
5671             if (cur->content != NULL)
5672                 return (xmlStrdup(cur->content));
5673             return (NULL);
5674     }
5675     return (NULL);
5676 }
5677 
5678 /**
5679  * xmlNodeSetContent:
5680  * @cur:  the node being modified
5681  * @content:  the new value of the content
5682  *
5683  * Replace the content of a node.
5684  * NOTE: @content is supposed to be a piece of XML CDATA, so it allows entity
5685  *       references, but XML special chars need to be escaped first by using
5686  *       xmlEncodeEntitiesReentrant() resp. xmlEncodeSpecialChars().
5687  */
5688 void
xmlNodeSetContent(xmlNodePtr cur,const xmlChar * content)5689 xmlNodeSetContent(xmlNodePtr cur, const xmlChar *content) {
5690     if (cur == NULL) {
5691 #ifdef DEBUG_TREE
5692         xmlGenericError(xmlGenericErrorContext,
5693 		"xmlNodeSetContent : node == NULL\n");
5694 #endif
5695 	return;
5696     }
5697     switch (cur->type) {
5698         case XML_DOCUMENT_FRAG_NODE:
5699         case XML_ELEMENT_NODE:
5700         case XML_ATTRIBUTE_NODE:
5701 	    if (cur->children != NULL) xmlFreeNodeList(cur->children);
5702 	    cur->children = xmlStringGetNodeList(cur->doc, content);
5703 	    UPDATE_LAST_CHILD_AND_PARENT(cur)
5704 	    break;
5705         case XML_TEXT_NODE:
5706         case XML_CDATA_SECTION_NODE:
5707         case XML_ENTITY_REF_NODE:
5708         case XML_ENTITY_NODE:
5709         case XML_PI_NODE:
5710         case XML_COMMENT_NODE:
5711 	    if ((cur->content != NULL) &&
5712 	        (cur->content != (xmlChar *) &(cur->properties))) {
5713 	        if (!((cur->doc != NULL) && (cur->doc->dict != NULL) &&
5714 		    (xmlDictOwns(cur->doc->dict, cur->content))))
5715 		    xmlFree(cur->content);
5716 	    }
5717 	    if (cur->children != NULL) xmlFreeNodeList(cur->children);
5718 	    cur->last = cur->children = NULL;
5719 	    if (content != NULL) {
5720 		cur->content = xmlStrdup(content);
5721 	    } else
5722 		cur->content = NULL;
5723 	    cur->properties = NULL;
5724 	    cur->nsDef = NULL;
5725 	    break;
5726         case XML_DOCUMENT_NODE:
5727         case XML_HTML_DOCUMENT_NODE:
5728         case XML_DOCUMENT_TYPE_NODE:
5729 	case XML_XINCLUDE_START:
5730 	case XML_XINCLUDE_END:
5731 #ifdef LIBXML_DOCB_ENABLED
5732 	case XML_DOCB_DOCUMENT_NODE:
5733 #endif
5734 	    break;
5735         case XML_NOTATION_NODE:
5736 	    break;
5737         case XML_DTD_NODE:
5738 	    break;
5739 	case XML_NAMESPACE_DECL:
5740 	    break;
5741         case XML_ELEMENT_DECL:
5742 	    /* TODO !!! */
5743 	    break;
5744         case XML_ATTRIBUTE_DECL:
5745 	    /* TODO !!! */
5746 	    break;
5747         case XML_ENTITY_DECL:
5748 	    /* TODO !!! */
5749 	    break;
5750     }
5751 }
5752 
5753 #ifdef LIBXML_TREE_ENABLED
5754 /**
5755  * xmlNodeSetContentLen:
5756  * @cur:  the node being modified
5757  * @content:  the new value of the content
5758  * @len:  the size of @content
5759  *
5760  * Replace the content of a node.
5761  * NOTE: @content is supposed to be a piece of XML CDATA, so it allows entity
5762  *       references, but XML special chars need to be escaped first by using
5763  *       xmlEncodeEntitiesReentrant() resp. xmlEncodeSpecialChars().
5764  */
5765 void
xmlNodeSetContentLen(xmlNodePtr cur,const xmlChar * content,int len)5766 xmlNodeSetContentLen(xmlNodePtr cur, const xmlChar *content, int len) {
5767     if (cur == NULL) {
5768 #ifdef DEBUG_TREE
5769         xmlGenericError(xmlGenericErrorContext,
5770 		"xmlNodeSetContentLen : node == NULL\n");
5771 #endif
5772 	return;
5773     }
5774     switch (cur->type) {
5775         case XML_DOCUMENT_FRAG_NODE:
5776         case XML_ELEMENT_NODE:
5777         case XML_ATTRIBUTE_NODE:
5778 	    if (cur->children != NULL) xmlFreeNodeList(cur->children);
5779 	    cur->children = xmlStringLenGetNodeList(cur->doc, content, len);
5780 	    UPDATE_LAST_CHILD_AND_PARENT(cur)
5781 	    break;
5782         case XML_TEXT_NODE:
5783         case XML_CDATA_SECTION_NODE:
5784         case XML_ENTITY_REF_NODE:
5785         case XML_ENTITY_NODE:
5786         case XML_PI_NODE:
5787         case XML_COMMENT_NODE:
5788         case XML_NOTATION_NODE:
5789 	    if ((cur->content != NULL) &&
5790 	        (cur->content != (xmlChar *) &(cur->properties))) {
5791 	        if (!((cur->doc != NULL) && (cur->doc->dict != NULL) &&
5792 		    (xmlDictOwns(cur->doc->dict, cur->content))))
5793 		    xmlFree(cur->content);
5794 	    }
5795 	    if (cur->children != NULL) xmlFreeNodeList(cur->children);
5796 	    cur->children = cur->last = NULL;
5797 	    if (content != NULL) {
5798 		cur->content = xmlStrndup(content, len);
5799 	    } else
5800 		cur->content = NULL;
5801 	    cur->properties = NULL;
5802 	    cur->nsDef = NULL;
5803 	    break;
5804         case XML_DOCUMENT_NODE:
5805         case XML_DTD_NODE:
5806         case XML_HTML_DOCUMENT_NODE:
5807         case XML_DOCUMENT_TYPE_NODE:
5808 	case XML_NAMESPACE_DECL:
5809 	case XML_XINCLUDE_START:
5810 	case XML_XINCLUDE_END:
5811 #ifdef LIBXML_DOCB_ENABLED
5812 	case XML_DOCB_DOCUMENT_NODE:
5813 #endif
5814 	    break;
5815         case XML_ELEMENT_DECL:
5816 	    /* TODO !!! */
5817 	    break;
5818         case XML_ATTRIBUTE_DECL:
5819 	    /* TODO !!! */
5820 	    break;
5821         case XML_ENTITY_DECL:
5822 	    /* TODO !!! */
5823 	    break;
5824     }
5825 }
5826 #endif /* LIBXML_TREE_ENABLED */
5827 
5828 /**
5829  * xmlNodeAddContentLen:
5830  * @cur:  the node being modified
5831  * @content:  extra content
5832  * @len:  the size of @content
5833  *
5834  * Append the extra substring to the node content.
5835  * NOTE: In contrast to xmlNodeSetContentLen(), @content is supposed to be
5836  *       raw text, so unescaped XML special chars are allowed, entity
5837  *       references are not supported.
5838  */
5839 void
xmlNodeAddContentLen(xmlNodePtr cur,const xmlChar * content,int len)5840 xmlNodeAddContentLen(xmlNodePtr cur, const xmlChar *content, int len) {
5841     if (cur == NULL) {
5842 #ifdef DEBUG_TREE
5843         xmlGenericError(xmlGenericErrorContext,
5844 		"xmlNodeAddContentLen : node == NULL\n");
5845 #endif
5846 	return;
5847     }
5848     if (len <= 0) return;
5849     switch (cur->type) {
5850         case XML_DOCUMENT_FRAG_NODE:
5851         case XML_ELEMENT_NODE: {
5852 	    xmlNodePtr last, newNode, tmp;
5853 
5854 	    last = cur->last;
5855 	    newNode = xmlNewTextLen(content, len);
5856 	    if (newNode != NULL) {
5857 		tmp = xmlAddChild(cur, newNode);
5858 		if (tmp != newNode)
5859 		    return;
5860 	        if ((last != NULL) && (last->next == newNode)) {
5861 		    xmlTextMerge(last, newNode);
5862 		}
5863 	    }
5864 	    break;
5865 	}
5866         case XML_ATTRIBUTE_NODE:
5867 	    break;
5868         case XML_TEXT_NODE:
5869         case XML_CDATA_SECTION_NODE:
5870         case XML_ENTITY_REF_NODE:
5871         case XML_ENTITY_NODE:
5872         case XML_PI_NODE:
5873         case XML_COMMENT_NODE:
5874         case XML_NOTATION_NODE:
5875 	    if (content != NULL) {
5876 	        if ((cur->content == (xmlChar *) &(cur->properties)) ||
5877 		    ((cur->doc != NULL) && (cur->doc->dict != NULL) &&
5878 			    xmlDictOwns(cur->doc->dict, cur->content))) {
5879 		    cur->content = xmlStrncatNew(cur->content, content, len);
5880 		    cur->properties = NULL;
5881 		    cur->nsDef = NULL;
5882 		    break;
5883 		}
5884 		cur->content = xmlStrncat(cur->content, content, len);
5885             }
5886         case XML_DOCUMENT_NODE:
5887         case XML_DTD_NODE:
5888         case XML_HTML_DOCUMENT_NODE:
5889         case XML_DOCUMENT_TYPE_NODE:
5890 	case XML_NAMESPACE_DECL:
5891 	case XML_XINCLUDE_START:
5892 	case XML_XINCLUDE_END:
5893 #ifdef LIBXML_DOCB_ENABLED
5894 	case XML_DOCB_DOCUMENT_NODE:
5895 #endif
5896 	    break;
5897         case XML_ELEMENT_DECL:
5898         case XML_ATTRIBUTE_DECL:
5899         case XML_ENTITY_DECL:
5900 	    break;
5901     }
5902 }
5903 
5904 /**
5905  * xmlNodeAddContent:
5906  * @cur:  the node being modified
5907  * @content:  extra content
5908  *
5909  * Append the extra substring to the node content.
5910  * NOTE: In contrast to xmlNodeSetContent(), @content is supposed to be
5911  *       raw text, so unescaped XML special chars are allowed, entity
5912  *       references are not supported.
5913  */
5914 void
xmlNodeAddContent(xmlNodePtr cur,const xmlChar * content)5915 xmlNodeAddContent(xmlNodePtr cur, const xmlChar *content) {
5916     int len;
5917 
5918     if (cur == NULL) {
5919 #ifdef DEBUG_TREE
5920         xmlGenericError(xmlGenericErrorContext,
5921 		"xmlNodeAddContent : node == NULL\n");
5922 #endif
5923 	return;
5924     }
5925     if (content == NULL) return;
5926     len = xmlStrlen(content);
5927     xmlNodeAddContentLen(cur, content, len);
5928 }
5929 
5930 /**
5931  * xmlTextMerge:
5932  * @first:  the first text node
5933  * @second:  the second text node being merged
5934  *
5935  * Merge two text nodes into one
5936  * Returns the first text node augmented
5937  */
5938 xmlNodePtr
xmlTextMerge(xmlNodePtr first,xmlNodePtr second)5939 xmlTextMerge(xmlNodePtr first, xmlNodePtr second) {
5940     if (first == NULL) return(second);
5941     if (second == NULL) return(first);
5942     if (first->type != XML_TEXT_NODE) return(first);
5943     if (second->type != XML_TEXT_NODE) return(first);
5944     if (second->name != first->name)
5945 	return(first);
5946     xmlNodeAddContent(first, second->content);
5947     xmlUnlinkNode(second);
5948     xmlFreeNode(second);
5949     return(first);
5950 }
5951 
5952 #if defined(LIBXML_TREE_ENABLED) || defined(LIBXML_XPATH_ENABLED) || defined(LIBXML_SCHEMAS_ENABLED)
5953 /**
5954  * xmlGetNsList:
5955  * @doc:  the document
5956  * @node:  the current node
5957  *
5958  * Search all the namespace applying to a given element.
5959  * Returns an NULL terminated array of all the #xmlNsPtr found
5960  *         that need to be freed by the caller or NULL if no
5961  *         namespace if defined
5962  */
5963 xmlNsPtr *
xmlGetNsList(const xmlDoc * doc ATTRIBUTE_UNUSED,const xmlNode * node)5964 xmlGetNsList(const xmlDoc *doc ATTRIBUTE_UNUSED, const xmlNode *node)
5965 {
5966     xmlNsPtr cur;
5967     xmlNsPtr *ret = NULL;
5968     int nbns = 0;
5969     int maxns = 10;
5970     int i;
5971 
5972     if ((node == NULL) || (node->type == XML_NAMESPACE_DECL))
5973         return(NULL);
5974 
5975     while (node != NULL) {
5976         if (node->type == XML_ELEMENT_NODE) {
5977             cur = node->nsDef;
5978             while (cur != NULL) {
5979                 if (ret == NULL) {
5980                     ret =
5981                         (xmlNsPtr *) xmlMalloc((maxns + 1) *
5982                                                sizeof(xmlNsPtr));
5983                     if (ret == NULL) {
5984 			xmlTreeErrMemory("getting namespace list");
5985                         return (NULL);
5986                     }
5987                     ret[nbns] = NULL;
5988                 }
5989                 for (i = 0; i < nbns; i++) {
5990                     if ((cur->prefix == ret[i]->prefix) ||
5991                         (xmlStrEqual(cur->prefix, ret[i]->prefix)))
5992                         break;
5993                 }
5994                 if (i >= nbns) {
5995                     if (nbns >= maxns) {
5996                         maxns *= 2;
5997                         ret = (xmlNsPtr *) xmlRealloc(ret,
5998                                                       (maxns +
5999                                                        1) *
6000                                                       sizeof(xmlNsPtr));
6001                         if (ret == NULL) {
6002 			    xmlTreeErrMemory("getting namespace list");
6003                             return (NULL);
6004                         }
6005                     }
6006                     ret[nbns++] = cur;
6007                     ret[nbns] = NULL;
6008                 }
6009 
6010                 cur = cur->next;
6011             }
6012         }
6013         node = node->parent;
6014     }
6015     return (ret);
6016 }
6017 #endif /* LIBXML_TREE_ENABLED */
6018 
6019 /*
6020 * xmlTreeEnsureXMLDecl:
6021 * @doc: the doc
6022 *
6023 * Ensures that there is an XML namespace declaration on the doc.
6024 *
6025 * Returns the XML ns-struct or NULL on API and internal errors.
6026 */
6027 static xmlNsPtr
xmlTreeEnsureXMLDecl(xmlDocPtr doc)6028 xmlTreeEnsureXMLDecl(xmlDocPtr doc)
6029 {
6030     if (doc == NULL)
6031 	return (NULL);
6032     if (doc->oldNs != NULL)
6033 	return (doc->oldNs);
6034     {
6035 	xmlNsPtr ns;
6036 	ns = (xmlNsPtr) xmlMalloc(sizeof(xmlNs));
6037 	if (ns == NULL) {
6038 	    xmlTreeErrMemory(
6039 		"allocating the XML namespace");
6040 	    return (NULL);
6041 	}
6042 	memset(ns, 0, sizeof(xmlNs));
6043 	ns->type = XML_LOCAL_NAMESPACE;
6044 	ns->href = xmlStrdup(XML_XML_NAMESPACE);
6045 	ns->prefix = xmlStrdup((const xmlChar *)"xml");
6046 	doc->oldNs = ns;
6047 	return (ns);
6048     }
6049 }
6050 
6051 /**
6052  * xmlSearchNs:
6053  * @doc:  the document
6054  * @node:  the current node
6055  * @nameSpace:  the namespace prefix
6056  *
6057  * Search a Ns registered under a given name space for a document.
6058  * recurse on the parents until it finds the defined namespace
6059  * or return NULL otherwise.
6060  * @nameSpace can be NULL, this is a search for the default namespace.
6061  * We don't allow to cross entities boundaries. If you don't declare
6062  * the namespace within those you will be in troubles !!! A warning
6063  * is generated to cover this case.
6064  *
6065  * Returns the namespace pointer or NULL.
6066  */
6067 xmlNsPtr
xmlSearchNs(xmlDocPtr doc,xmlNodePtr node,const xmlChar * nameSpace)6068 xmlSearchNs(xmlDocPtr doc, xmlNodePtr node, const xmlChar *nameSpace) {
6069 
6070     xmlNsPtr cur;
6071     const xmlNode *orig = node;
6072 
6073     if ((node == NULL) || (node->type == XML_NAMESPACE_DECL)) return(NULL);
6074     if ((nameSpace != NULL) &&
6075 	(xmlStrEqual(nameSpace, (const xmlChar *)"xml"))) {
6076 	if ((doc == NULL) && (node->type == XML_ELEMENT_NODE)) {
6077 	    /*
6078 	     * The XML-1.0 namespace is normally held on the root
6079 	     * element. In this case exceptionally create it on the
6080 	     * node element.
6081 	     */
6082 	    cur = (xmlNsPtr) xmlMalloc(sizeof(xmlNs));
6083 	    if (cur == NULL) {
6084 		xmlTreeErrMemory("searching namespace");
6085 		return(NULL);
6086 	    }
6087 	    memset(cur, 0, sizeof(xmlNs));
6088 	    cur->type = XML_LOCAL_NAMESPACE;
6089 	    cur->href = xmlStrdup(XML_XML_NAMESPACE);
6090 	    cur->prefix = xmlStrdup((const xmlChar *)"xml");
6091 	    cur->next = node->nsDef;
6092 	    node->nsDef = cur;
6093 	    return(cur);
6094 	}
6095 	if (doc == NULL) {
6096 	    doc = node->doc;
6097 	    if (doc == NULL)
6098 		return(NULL);
6099 	}
6100 	/*
6101 	* Return the XML namespace declaration held by the doc.
6102 	*/
6103 	if (doc->oldNs == NULL)
6104 	    return(xmlTreeEnsureXMLDecl(doc));
6105 	else
6106 	    return(doc->oldNs);
6107     }
6108     while (node != NULL) {
6109 	if ((node->type == XML_ENTITY_REF_NODE) ||
6110 	    (node->type == XML_ENTITY_NODE) ||
6111 	    (node->type == XML_ENTITY_DECL))
6112 	    return(NULL);
6113 	if (node->type == XML_ELEMENT_NODE) {
6114 	    cur = node->nsDef;
6115 	    while (cur != NULL) {
6116 		if ((cur->prefix == NULL) && (nameSpace == NULL) &&
6117 		    (cur->href != NULL))
6118 		    return(cur);
6119 		if ((cur->prefix != NULL) && (nameSpace != NULL) &&
6120 		    (cur->href != NULL) &&
6121 		    (xmlStrEqual(cur->prefix, nameSpace)))
6122 		    return(cur);
6123 		cur = cur->next;
6124 	    }
6125 	    if (orig != node) {
6126 	        cur = node->ns;
6127 	        if (cur != NULL) {
6128 		    if ((cur->prefix == NULL) && (nameSpace == NULL) &&
6129 		        (cur->href != NULL))
6130 		        return(cur);
6131 		    if ((cur->prefix != NULL) && (nameSpace != NULL) &&
6132 		        (cur->href != NULL) &&
6133 		        (xmlStrEqual(cur->prefix, nameSpace)))
6134 		        return(cur);
6135 	        }
6136 	    }
6137 	}
6138 	node = node->parent;
6139     }
6140     return(NULL);
6141 }
6142 
6143 /**
6144  * xmlNsInScope:
6145  * @doc:  the document
6146  * @node:  the current node
6147  * @ancestor:  the ancestor carrying the namespace
6148  * @prefix:  the namespace prefix
6149  *
6150  * Verify that the given namespace held on @ancestor is still in scope
6151  * on node.
6152  *
6153  * Returns 1 if true, 0 if false and -1 in case of error.
6154  */
6155 static int
xmlNsInScope(xmlDocPtr doc ATTRIBUTE_UNUSED,xmlNodePtr node,xmlNodePtr ancestor,const xmlChar * prefix)6156 xmlNsInScope(xmlDocPtr doc ATTRIBUTE_UNUSED, xmlNodePtr node,
6157              xmlNodePtr ancestor, const xmlChar * prefix)
6158 {
6159     xmlNsPtr tst;
6160 
6161     while ((node != NULL) && (node != ancestor)) {
6162         if ((node->type == XML_ENTITY_REF_NODE) ||
6163             (node->type == XML_ENTITY_NODE) ||
6164             (node->type == XML_ENTITY_DECL))
6165             return (-1);
6166         if (node->type == XML_ELEMENT_NODE) {
6167             tst = node->nsDef;
6168             while (tst != NULL) {
6169                 if ((tst->prefix == NULL)
6170                     && (prefix == NULL))
6171                     return (0);
6172                 if ((tst->prefix != NULL)
6173                     && (prefix != NULL)
6174                     && (xmlStrEqual(tst->prefix, prefix)))
6175                     return (0);
6176                 tst = tst->next;
6177             }
6178         }
6179         node = node->parent;
6180     }
6181     if (node != ancestor)
6182         return (-1);
6183     return (1);
6184 }
6185 
6186 /**
6187  * xmlSearchNsByHref:
6188  * @doc:  the document
6189  * @node:  the current node
6190  * @href:  the namespace value
6191  *
6192  * Search a Ns aliasing a given URI. Recurse on the parents until it finds
6193  * the defined namespace or return NULL otherwise.
6194  * Returns the namespace pointer or NULL.
6195  */
6196 xmlNsPtr
xmlSearchNsByHref(xmlDocPtr doc,xmlNodePtr node,const xmlChar * href)6197 xmlSearchNsByHref(xmlDocPtr doc, xmlNodePtr node, const xmlChar * href)
6198 {
6199     xmlNsPtr cur;
6200     xmlNodePtr orig = node;
6201     int is_attr;
6202 
6203     if ((node == NULL) || (node->type == XML_NAMESPACE_DECL) || (href == NULL))
6204         return (NULL);
6205     if (xmlStrEqual(href, XML_XML_NAMESPACE)) {
6206         /*
6207          * Only the document can hold the XML spec namespace.
6208          */
6209         if ((doc == NULL) && (node->type == XML_ELEMENT_NODE)) {
6210             /*
6211              * The XML-1.0 namespace is normally held on the root
6212              * element. In this case exceptionally create it on the
6213              * node element.
6214              */
6215             cur = (xmlNsPtr) xmlMalloc(sizeof(xmlNs));
6216             if (cur == NULL) {
6217 		xmlTreeErrMemory("searching namespace");
6218                 return (NULL);
6219             }
6220             memset(cur, 0, sizeof(xmlNs));
6221             cur->type = XML_LOCAL_NAMESPACE;
6222             cur->href = xmlStrdup(XML_XML_NAMESPACE);
6223             cur->prefix = xmlStrdup((const xmlChar *) "xml");
6224             cur->next = node->nsDef;
6225             node->nsDef = cur;
6226             return (cur);
6227         }
6228 	if (doc == NULL) {
6229 	    doc = node->doc;
6230 	    if (doc == NULL)
6231 		return(NULL);
6232 	}
6233 	/*
6234 	* Return the XML namespace declaration held by the doc.
6235 	*/
6236 	if (doc->oldNs == NULL)
6237 	    return(xmlTreeEnsureXMLDecl(doc));
6238 	else
6239 	    return(doc->oldNs);
6240     }
6241     is_attr = (node->type == XML_ATTRIBUTE_NODE);
6242     while (node != NULL) {
6243         if ((node->type == XML_ENTITY_REF_NODE) ||
6244             (node->type == XML_ENTITY_NODE) ||
6245             (node->type == XML_ENTITY_DECL))
6246             return (NULL);
6247         if (node->type == XML_ELEMENT_NODE) {
6248             cur = node->nsDef;
6249             while (cur != NULL) {
6250                 if ((cur->href != NULL) && (href != NULL) &&
6251                     (xmlStrEqual(cur->href, href))) {
6252 		    if (((!is_attr) || (cur->prefix != NULL)) &&
6253 		        (xmlNsInScope(doc, orig, node, cur->prefix) == 1))
6254 			return (cur);
6255                 }
6256                 cur = cur->next;
6257             }
6258             if (orig != node) {
6259                 cur = node->ns;
6260                 if (cur != NULL) {
6261                     if ((cur->href != NULL) && (href != NULL) &&
6262                         (xmlStrEqual(cur->href, href))) {
6263 			if (((!is_attr) || (cur->prefix != NULL)) &&
6264 		            (xmlNsInScope(doc, orig, node, cur->prefix) == 1))
6265 			    return (cur);
6266                     }
6267                 }
6268             }
6269         }
6270         node = node->parent;
6271     }
6272     return (NULL);
6273 }
6274 
6275 /**
6276  * xmlNewReconciledNs:
6277  * @doc:  the document
6278  * @tree:  a node expected to hold the new namespace
6279  * @ns:  the original namespace
6280  *
6281  * This function tries to locate a namespace definition in a tree
6282  * ancestors, or create a new namespace definition node similar to
6283  * @ns trying to reuse the same prefix. However if the given prefix is
6284  * null (default namespace) or reused within the subtree defined by
6285  * @tree or on one of its ancestors then a new prefix is generated.
6286  * Returns the (new) namespace definition or NULL in case of error
6287  */
6288 static xmlNsPtr
xmlNewReconciledNs(xmlDocPtr doc,xmlNodePtr tree,xmlNsPtr ns)6289 xmlNewReconciledNs(xmlDocPtr doc, xmlNodePtr tree, xmlNsPtr ns) {
6290     xmlNsPtr def;
6291     xmlChar prefix[50];
6292     int counter = 1;
6293 
6294     if ((tree == NULL) || (tree->type != XML_ELEMENT_NODE)) {
6295 #ifdef DEBUG_TREE
6296         xmlGenericError(xmlGenericErrorContext,
6297 		"xmlNewReconciledNs : tree == NULL\n");
6298 #endif
6299 	return(NULL);
6300     }
6301     if ((ns == NULL) || (ns->type != XML_NAMESPACE_DECL)) {
6302 #ifdef DEBUG_TREE
6303         xmlGenericError(xmlGenericErrorContext,
6304 		"xmlNewReconciledNs : ns == NULL\n");
6305 #endif
6306 	return(NULL);
6307     }
6308     /*
6309      * Search an existing namespace definition inherited.
6310      */
6311     def = xmlSearchNsByHref(doc, tree, ns->href);
6312     if (def != NULL)
6313         return(def);
6314 
6315     /*
6316      * Find a close prefix which is not already in use.
6317      * Let's strip namespace prefixes longer than 20 chars !
6318      */
6319     if (ns->prefix == NULL)
6320 	snprintf((char *) prefix, sizeof(prefix), "default");
6321     else
6322 	snprintf((char *) prefix, sizeof(prefix), "%.20s", (char *)ns->prefix);
6323 
6324     def = xmlSearchNs(doc, tree, prefix);
6325     while (def != NULL) {
6326         if (counter > 1000) return(NULL);
6327 	if (ns->prefix == NULL)
6328 	    snprintf((char *) prefix, sizeof(prefix), "default%d", counter++);
6329 	else
6330 	    snprintf((char *) prefix, sizeof(prefix), "%.20s%d",
6331 		(char *)ns->prefix, counter++);
6332 	def = xmlSearchNs(doc, tree, prefix);
6333     }
6334 
6335     /*
6336      * OK, now we are ready to create a new one.
6337      */
6338     def = xmlNewNs(tree, ns->href, prefix);
6339     return(def);
6340 }
6341 
6342 #ifdef LIBXML_TREE_ENABLED
6343 /**
6344  * xmlReconciliateNs:
6345  * @doc:  the document
6346  * @tree:  a node defining the subtree to reconciliate
6347  *
6348  * This function checks that all the namespaces declared within the given
6349  * tree are properly declared. This is needed for example after Copy or Cut
6350  * and then paste operations. The subtree may still hold pointers to
6351  * namespace declarations outside the subtree or invalid/masked. As much
6352  * as possible the function try to reuse the existing namespaces found in
6353  * the new environment. If not possible the new namespaces are redeclared
6354  * on @tree at the top of the given subtree.
6355  * Returns the number of namespace declarations created or -1 in case of error.
6356  */
6357 int
xmlReconciliateNs(xmlDocPtr doc,xmlNodePtr tree)6358 xmlReconciliateNs(xmlDocPtr doc, xmlNodePtr tree) {
6359     xmlNsPtr *oldNs = NULL;
6360     xmlNsPtr *newNs = NULL;
6361     int sizeCache = 0;
6362     int nbCache = 0;
6363 
6364     xmlNsPtr n;
6365     xmlNodePtr node = tree;
6366     xmlAttrPtr attr;
6367     int ret = 0, i;
6368 
6369     if ((node == NULL) || (node->type != XML_ELEMENT_NODE)) return(-1);
6370     if ((doc == NULL) || (doc->type != XML_DOCUMENT_NODE)) return(-1);
6371     if (node->doc != doc) return(-1);
6372     while (node != NULL) {
6373         /*
6374 	 * Reconciliate the node namespace
6375 	 */
6376 	if (node->ns != NULL) {
6377 	    /*
6378 	     * initialize the cache if needed
6379 	     */
6380 	    if (sizeCache == 0) {
6381 		sizeCache = 10;
6382 		oldNs = (xmlNsPtr *) xmlMalloc(sizeCache *
6383 					       sizeof(xmlNsPtr));
6384 		if (oldNs == NULL) {
6385 		    xmlTreeErrMemory("fixing namespaces");
6386 		    return(-1);
6387 		}
6388 		newNs = (xmlNsPtr *) xmlMalloc(sizeCache *
6389 					       sizeof(xmlNsPtr));
6390 		if (newNs == NULL) {
6391 		    xmlTreeErrMemory("fixing namespaces");
6392 		    xmlFree(oldNs);
6393 		    return(-1);
6394 		}
6395 	    }
6396 	    for (i = 0;i < nbCache;i++) {
6397 	        if (oldNs[i] == node->ns) {
6398 		    node->ns = newNs[i];
6399 		    break;
6400 		}
6401 	    }
6402 	    if (i == nbCache) {
6403 	        /*
6404 		 * OK we need to recreate a new namespace definition
6405 		 */
6406 		n = xmlNewReconciledNs(doc, tree, node->ns);
6407 		if (n != NULL) { /* :-( what if else ??? */
6408 		    /*
6409 		     * check if we need to grow the cache buffers.
6410 		     */
6411 		    if (sizeCache <= nbCache) {
6412 		        sizeCache *= 2;
6413 			oldNs = (xmlNsPtr *) xmlRealloc(oldNs, sizeCache *
6414 			                               sizeof(xmlNsPtr));
6415 		        if (oldNs == NULL) {
6416 			    xmlTreeErrMemory("fixing namespaces");
6417 			    xmlFree(newNs);
6418 			    return(-1);
6419 			}
6420 			newNs = (xmlNsPtr *) xmlRealloc(newNs, sizeCache *
6421 			                               sizeof(xmlNsPtr));
6422 		        if (newNs == NULL) {
6423 			    xmlTreeErrMemory("fixing namespaces");
6424 			    xmlFree(oldNs);
6425 			    return(-1);
6426 			}
6427 		    }
6428 		    newNs[nbCache] = n;
6429 		    oldNs[nbCache++] = node->ns;
6430 		    node->ns = n;
6431                 }
6432 	    }
6433 	}
6434 	/*
6435 	 * now check for namespace held by attributes on the node.
6436 	 */
6437 	if (node->type == XML_ELEMENT_NODE) {
6438 	    attr = node->properties;
6439 	    while (attr != NULL) {
6440 		if (attr->ns != NULL) {
6441 		    /*
6442 		     * initialize the cache if needed
6443 		     */
6444 		    if (sizeCache == 0) {
6445 			sizeCache = 10;
6446 			oldNs = (xmlNsPtr *) xmlMalloc(sizeCache *
6447 						       sizeof(xmlNsPtr));
6448 			if (oldNs == NULL) {
6449 			    xmlTreeErrMemory("fixing namespaces");
6450 			    return(-1);
6451 			}
6452 			newNs = (xmlNsPtr *) xmlMalloc(sizeCache *
6453 						       sizeof(xmlNsPtr));
6454 			if (newNs == NULL) {
6455 			    xmlTreeErrMemory("fixing namespaces");
6456 			    xmlFree(oldNs);
6457 			    return(-1);
6458 			}
6459 		    }
6460 		    for (i = 0;i < nbCache;i++) {
6461 			if (oldNs[i] == attr->ns) {
6462 			    attr->ns = newNs[i];
6463 			    break;
6464 			}
6465 		    }
6466 		    if (i == nbCache) {
6467 			/*
6468 			 * OK we need to recreate a new namespace definition
6469 			 */
6470 			n = xmlNewReconciledNs(doc, tree, attr->ns);
6471 			if (n != NULL) { /* :-( what if else ??? */
6472 			    /*
6473 			     * check if we need to grow the cache buffers.
6474 			     */
6475 			    if (sizeCache <= nbCache) {
6476 				sizeCache *= 2;
6477 				oldNs = (xmlNsPtr *) xmlRealloc(oldNs,
6478 				           sizeCache * sizeof(xmlNsPtr));
6479 				if (oldNs == NULL) {
6480 				    xmlTreeErrMemory("fixing namespaces");
6481 				    xmlFree(newNs);
6482 				    return(-1);
6483 				}
6484 				newNs = (xmlNsPtr *) xmlRealloc(newNs,
6485 				           sizeCache * sizeof(xmlNsPtr));
6486 				if (newNs == NULL) {
6487 				    xmlTreeErrMemory("fixing namespaces");
6488 				    xmlFree(oldNs);
6489 				    return(-1);
6490 				}
6491 			    }
6492 			    newNs[nbCache] = n;
6493 			    oldNs[nbCache++] = attr->ns;
6494 			    attr->ns = n;
6495 			}
6496 		    }
6497 		}
6498 		attr = attr->next;
6499 	    }
6500 	}
6501 
6502 	/*
6503 	 * Browse the full subtree, deep first
6504 	 */
6505         if ((node->children != NULL) && (node->type != XML_ENTITY_REF_NODE)) {
6506 	    /* deep first */
6507 	    node = node->children;
6508 	} else if ((node != tree) && (node->next != NULL)) {
6509 	    /* then siblings */
6510 	    node = node->next;
6511 	} else if (node != tree) {
6512 	    /* go up to parents->next if needed */
6513 	    while (node != tree) {
6514 	        if (node->parent != NULL)
6515 		    node = node->parent;
6516 		if ((node != tree) && (node->next != NULL)) {
6517 		    node = node->next;
6518 		    break;
6519 		}
6520 		if (node->parent == NULL) {
6521 		    node = NULL;
6522 		    break;
6523 		}
6524 	    }
6525 	    /* exit condition */
6526 	    if (node == tree)
6527 	        node = NULL;
6528 	} else
6529 	    break;
6530     }
6531     if (oldNs != NULL)
6532 	xmlFree(oldNs);
6533     if (newNs != NULL)
6534 	xmlFree(newNs);
6535     return(ret);
6536 }
6537 #endif /* LIBXML_TREE_ENABLED */
6538 
6539 static xmlAttrPtr
xmlGetPropNodeInternal(const xmlNode * node,const xmlChar * name,const xmlChar * nsName,int useDTD)6540 xmlGetPropNodeInternal(const xmlNode *node, const xmlChar *name,
6541 		       const xmlChar *nsName, int useDTD)
6542 {
6543     xmlAttrPtr prop;
6544 
6545     if ((node == NULL) || (node->type != XML_ELEMENT_NODE) || (name == NULL))
6546 	return(NULL);
6547 
6548     if (node->properties != NULL) {
6549 	prop = node->properties;
6550 	if (nsName == NULL) {
6551 	    /*
6552 	    * We want the attr to be in no namespace.
6553 	    */
6554 	    do {
6555 		if ((prop->ns == NULL) && xmlStrEqual(prop->name, name)) {
6556 		    return(prop);
6557 		}
6558 		prop = prop->next;
6559 	    } while (prop != NULL);
6560 	} else {
6561 	    /*
6562 	    * We want the attr to be in the specified namespace.
6563 	    */
6564 	    do {
6565 		if ((prop->ns != NULL) && xmlStrEqual(prop->name, name) &&
6566 		    ((prop->ns->href == nsName) ||
6567 		     xmlStrEqual(prop->ns->href, nsName)))
6568 		{
6569 		    return(prop);
6570 		}
6571 		prop = prop->next;
6572 	    } while (prop != NULL);
6573 	}
6574     }
6575 
6576 #ifdef LIBXML_TREE_ENABLED
6577     if (! useDTD)
6578 	return(NULL);
6579     /*
6580      * Check if there is a default/fixed attribute declaration in
6581      * the internal or external subset.
6582      */
6583     if ((node->doc != NULL) && (node->doc->intSubset != NULL)) {
6584 	xmlDocPtr doc = node->doc;
6585 	xmlAttributePtr attrDecl = NULL;
6586 	xmlChar *elemQName, *tmpstr = NULL;
6587 
6588 	/*
6589 	* We need the QName of the element for the DTD-lookup.
6590 	*/
6591 	if ((node->ns != NULL) && (node->ns->prefix != NULL)) {
6592 	    tmpstr = xmlStrdup(node->ns->prefix);
6593 	    tmpstr = xmlStrcat(tmpstr, BAD_CAST ":");
6594 	    tmpstr = xmlStrcat(tmpstr, node->name);
6595 	    if (tmpstr == NULL)
6596 		return(NULL);
6597 	    elemQName = tmpstr;
6598 	} else
6599 	    elemQName = (xmlChar *) node->name;
6600 	if (nsName == NULL) {
6601 	    /*
6602 	    * The common and nice case: Attr in no namespace.
6603 	    */
6604 	    attrDecl = xmlGetDtdQAttrDesc(doc->intSubset,
6605 		elemQName, name, NULL);
6606 	    if ((attrDecl == NULL) && (doc->extSubset != NULL)) {
6607 		attrDecl = xmlGetDtdQAttrDesc(doc->extSubset,
6608 		    elemQName, name, NULL);
6609 	    }
6610         } else if (xmlStrEqual(nsName, XML_XML_NAMESPACE)) {
6611 	    /*
6612 	    * The XML namespace must be bound to prefix 'xml'.
6613 	    */
6614 	    attrDecl = xmlGetDtdQAttrDesc(doc->intSubset,
6615 		elemQName, name, BAD_CAST "xml");
6616 	    if ((attrDecl == NULL) && (doc->extSubset != NULL)) {
6617 		attrDecl = xmlGetDtdQAttrDesc(doc->extSubset,
6618 		    elemQName, name, BAD_CAST "xml");
6619 	    }
6620 	} else {
6621 	    xmlNsPtr *nsList, *cur;
6622 
6623 	    /*
6624 	    * The ugly case: Search using the prefixes of in-scope
6625 	    * ns-decls corresponding to @nsName.
6626 	    */
6627 	    nsList = xmlGetNsList(node->doc, node);
6628 	    if (nsList == NULL) {
6629 		if (tmpstr != NULL)
6630 		    xmlFree(tmpstr);
6631 		return(NULL);
6632 	    }
6633 	    cur = nsList;
6634 	    while (*cur != NULL) {
6635 		if (xmlStrEqual((*cur)->href, nsName)) {
6636 		    attrDecl = xmlGetDtdQAttrDesc(doc->intSubset, elemQName,
6637 			name, (*cur)->prefix);
6638 		    if (attrDecl)
6639 			break;
6640 		    if (doc->extSubset != NULL) {
6641 			attrDecl = xmlGetDtdQAttrDesc(doc->extSubset, elemQName,
6642 			    name, (*cur)->prefix);
6643 			if (attrDecl)
6644 			    break;
6645 		    }
6646 		}
6647 		cur++;
6648 	    }
6649 	    xmlFree(nsList);
6650 	}
6651 	if (tmpstr != NULL)
6652 	    xmlFree(tmpstr);
6653 	/*
6654 	* Only default/fixed attrs are relevant.
6655 	*/
6656 	if ((attrDecl != NULL) && (attrDecl->defaultValue != NULL))
6657 	    return((xmlAttrPtr) attrDecl);
6658     }
6659 #endif /* LIBXML_TREE_ENABLED */
6660     return(NULL);
6661 }
6662 
6663 static xmlChar*
xmlGetPropNodeValueInternal(const xmlAttr * prop)6664 xmlGetPropNodeValueInternal(const xmlAttr *prop)
6665 {
6666     if (prop == NULL)
6667 	return(NULL);
6668     if (prop->type == XML_ATTRIBUTE_NODE) {
6669 	/*
6670 	* Note that we return at least the empty string.
6671 	*   TODO: Do we really always want that?
6672 	*/
6673 	if (prop->children != NULL) {
6674 	    if ((prop->children->next == NULL) &&
6675 		((prop->children->type == XML_TEXT_NODE) ||
6676 		(prop->children->type == XML_CDATA_SECTION_NODE)))
6677 	    {
6678 		/*
6679 		* Optimization for the common case: only 1 text node.
6680 		*/
6681 		return(xmlStrdup(prop->children->content));
6682 	    } else {
6683 		xmlChar *ret;
6684 
6685 		ret = xmlNodeListGetString(prop->doc, prop->children, 1);
6686 		if (ret != NULL)
6687 		    return(ret);
6688 	    }
6689 	}
6690 	return(xmlStrdup((xmlChar *)""));
6691     } else if (prop->type == XML_ATTRIBUTE_DECL) {
6692 	return(xmlStrdup(((xmlAttributePtr)prop)->defaultValue));
6693     }
6694     return(NULL);
6695 }
6696 
6697 /**
6698  * xmlHasProp:
6699  * @node:  the node
6700  * @name:  the attribute name
6701  *
6702  * Search an attribute associated to a node
6703  * This function also looks in DTD attribute declaration for #FIXED or
6704  * default declaration values unless DTD use has been turned off.
6705  *
6706  * Returns the attribute or the attribute declaration or NULL if
6707  *         neither was found.
6708  */
6709 xmlAttrPtr
xmlHasProp(const xmlNode * node,const xmlChar * name)6710 xmlHasProp(const xmlNode *node, const xmlChar *name) {
6711     xmlAttrPtr prop;
6712     xmlDocPtr doc;
6713 
6714     if ((node == NULL) || (node->type != XML_ELEMENT_NODE) || (name == NULL))
6715         return(NULL);
6716     /*
6717      * Check on the properties attached to the node
6718      */
6719     prop = node->properties;
6720     while (prop != NULL) {
6721         if (xmlStrEqual(prop->name, name))  {
6722 	    return(prop);
6723         }
6724 	prop = prop->next;
6725     }
6726     if (!xmlCheckDTD) return(NULL);
6727 
6728     /*
6729      * Check if there is a default declaration in the internal
6730      * or external subsets
6731      */
6732     doc =  node->doc;
6733     if (doc != NULL) {
6734         xmlAttributePtr attrDecl;
6735         if (doc->intSubset != NULL) {
6736 	    attrDecl = xmlGetDtdAttrDesc(doc->intSubset, node->name, name);
6737 	    if ((attrDecl == NULL) && (doc->extSubset != NULL))
6738 		attrDecl = xmlGetDtdAttrDesc(doc->extSubset, node->name, name);
6739             if ((attrDecl != NULL) && (attrDecl->defaultValue != NULL))
6740               /* return attribute declaration only if a default value is given
6741                  (that includes #FIXED declarations) */
6742 		return((xmlAttrPtr) attrDecl);
6743 	}
6744     }
6745     return(NULL);
6746 }
6747 
6748 /**
6749  * xmlHasNsProp:
6750  * @node:  the node
6751  * @name:  the attribute name
6752  * @nameSpace:  the URI of the namespace
6753  *
6754  * Search for an attribute associated to a node
6755  * This attribute has to be anchored in the namespace specified.
6756  * This does the entity substitution.
6757  * This function looks in DTD attribute declaration for #FIXED or
6758  * default declaration values unless DTD use has been turned off.
6759  * Note that a namespace of NULL indicates to use the default namespace.
6760  *
6761  * Returns the attribute or the attribute declaration or NULL
6762  *     if neither was found.
6763  */
6764 xmlAttrPtr
xmlHasNsProp(const xmlNode * node,const xmlChar * name,const xmlChar * nameSpace)6765 xmlHasNsProp(const xmlNode *node, const xmlChar *name, const xmlChar *nameSpace) {
6766 
6767     return(xmlGetPropNodeInternal(node, name, nameSpace, xmlCheckDTD));
6768 }
6769 
6770 /**
6771  * xmlGetProp:
6772  * @node:  the node
6773  * @name:  the attribute name
6774  *
6775  * Search and get the value of an attribute associated to a node
6776  * This does the entity substitution.
6777  * This function looks in DTD attribute declaration for #FIXED or
6778  * default declaration values unless DTD use has been turned off.
6779  * NOTE: this function acts independently of namespaces associated
6780  *       to the attribute. Use xmlGetNsProp() or xmlGetNoNsProp()
6781  *       for namespace aware processing.
6782  *
6783  * Returns the attribute value or NULL if not found.
6784  *     It's up to the caller to free the memory with xmlFree().
6785  */
6786 xmlChar *
xmlGetProp(const xmlNode * node,const xmlChar * name)6787 xmlGetProp(const xmlNode *node, const xmlChar *name) {
6788     xmlAttrPtr prop;
6789 
6790     prop = xmlHasProp(node, name);
6791     if (prop == NULL)
6792 	return(NULL);
6793     return(xmlGetPropNodeValueInternal(prop));
6794 }
6795 
6796 /**
6797  * xmlGetNoNsProp:
6798  * @node:  the node
6799  * @name:  the attribute name
6800  *
6801  * Search and get the value of an attribute associated to a node
6802  * This does the entity substitution.
6803  * This function looks in DTD attribute declaration for #FIXED or
6804  * default declaration values unless DTD use has been turned off.
6805  * This function is similar to xmlGetProp except it will accept only
6806  * an attribute in no namespace.
6807  *
6808  * Returns the attribute value or NULL if not found.
6809  *     It's up to the caller to free the memory with xmlFree().
6810  */
6811 xmlChar *
xmlGetNoNsProp(const xmlNode * node,const xmlChar * name)6812 xmlGetNoNsProp(const xmlNode *node, const xmlChar *name) {
6813     xmlAttrPtr prop;
6814 
6815     prop = xmlGetPropNodeInternal(node, name, NULL, xmlCheckDTD);
6816     if (prop == NULL)
6817 	return(NULL);
6818     return(xmlGetPropNodeValueInternal(prop));
6819 }
6820 
6821 /**
6822  * xmlGetNsProp:
6823  * @node:  the node
6824  * @name:  the attribute name
6825  * @nameSpace:  the URI of the namespace
6826  *
6827  * Search and get the value of an attribute associated to a node
6828  * This attribute has to be anchored in the namespace specified.
6829  * This does the entity substitution.
6830  * This function looks in DTD attribute declaration for #FIXED or
6831  * default declaration values unless DTD use has been turned off.
6832  *
6833  * Returns the attribute value or NULL if not found.
6834  *     It's up to the caller to free the memory with xmlFree().
6835  */
6836 xmlChar *
xmlGetNsProp(const xmlNode * node,const xmlChar * name,const xmlChar * nameSpace)6837 xmlGetNsProp(const xmlNode *node, const xmlChar *name, const xmlChar *nameSpace) {
6838     xmlAttrPtr prop;
6839 
6840     prop = xmlGetPropNodeInternal(node, name, nameSpace, xmlCheckDTD);
6841     if (prop == NULL)
6842 	return(NULL);
6843     return(xmlGetPropNodeValueInternal(prop));
6844 }
6845 
6846 #if defined(LIBXML_TREE_ENABLED) || defined(LIBXML_SCHEMAS_ENABLED)
6847 /**
6848  * xmlUnsetProp:
6849  * @node:  the node
6850  * @name:  the attribute name
6851  *
6852  * Remove an attribute carried by a node.
6853  * This handles only attributes in no namespace.
6854  * Returns 0 if successful, -1 if not found
6855  */
6856 int
xmlUnsetProp(xmlNodePtr node,const xmlChar * name)6857 xmlUnsetProp(xmlNodePtr node, const xmlChar *name) {
6858     xmlAttrPtr prop;
6859 
6860     prop = xmlGetPropNodeInternal(node, name, NULL, 0);
6861     if (prop == NULL)
6862 	return(-1);
6863     xmlUnlinkNode((xmlNodePtr) prop);
6864     xmlFreeProp(prop);
6865     return(0);
6866 }
6867 
6868 /**
6869  * xmlUnsetNsProp:
6870  * @node:  the node
6871  * @ns:  the namespace definition
6872  * @name:  the attribute name
6873  *
6874  * Remove an attribute carried by a node.
6875  * Returns 0 if successful, -1 if not found
6876  */
6877 int
xmlUnsetNsProp(xmlNodePtr node,xmlNsPtr ns,const xmlChar * name)6878 xmlUnsetNsProp(xmlNodePtr node, xmlNsPtr ns, const xmlChar *name) {
6879     xmlAttrPtr prop;
6880 
6881     prop = xmlGetPropNodeInternal(node, name, (ns != NULL) ? ns->href : NULL, 0);
6882     if (prop == NULL)
6883 	return(-1);
6884     xmlUnlinkNode((xmlNodePtr) prop);
6885     xmlFreeProp(prop);
6886     return(0);
6887 }
6888 #endif
6889 
6890 #if defined(LIBXML_TREE_ENABLED) || defined(LIBXML_XINCLUDE_ENABLED) || defined(LIBXML_SCHEMAS_ENABLED) || defined(LIBXML_HTML_ENABLED)
6891 /**
6892  * xmlSetProp:
6893  * @node:  the node
6894  * @name:  the attribute name (a QName)
6895  * @value:  the attribute value
6896  *
6897  * Set (or reset) an attribute carried by a node.
6898  * If @name has a prefix, then the corresponding
6899  * namespace-binding will be used, if in scope; it is an
6900  * error it there's no such ns-binding for the prefix in
6901  * scope.
6902  * Returns the attribute pointer.
6903  *
6904  */
6905 xmlAttrPtr
xmlSetProp(xmlNodePtr node,const xmlChar * name,const xmlChar * value)6906 xmlSetProp(xmlNodePtr node, const xmlChar *name, const xmlChar *value) {
6907     int len;
6908     const xmlChar *nqname;
6909 
6910     if ((node == NULL) || (name == NULL) || (node->type != XML_ELEMENT_NODE))
6911 	return(NULL);
6912 
6913     /*
6914      * handle QNames
6915      */
6916     nqname = xmlSplitQName3(name, &len);
6917     if (nqname != NULL) {
6918         xmlNsPtr ns;
6919 	xmlChar *prefix = xmlStrndup(name, len);
6920 	ns = xmlSearchNs(node->doc, node, prefix);
6921 	if (prefix != NULL)
6922 	    xmlFree(prefix);
6923 	if (ns != NULL)
6924 	    return(xmlSetNsProp(node, ns, nqname, value));
6925     }
6926     return(xmlSetNsProp(node, NULL, name, value));
6927 }
6928 
6929 /**
6930  * xmlSetNsProp:
6931  * @node:  the node
6932  * @ns:  the namespace definition
6933  * @name:  the attribute name
6934  * @value:  the attribute value
6935  *
6936  * Set (or reset) an attribute carried by a node.
6937  * The ns structure must be in scope, this is not checked
6938  *
6939  * Returns the attribute pointer.
6940  */
6941 xmlAttrPtr
xmlSetNsProp(xmlNodePtr node,xmlNsPtr ns,const xmlChar * name,const xmlChar * value)6942 xmlSetNsProp(xmlNodePtr node, xmlNsPtr ns, const xmlChar *name,
6943 	     const xmlChar *value)
6944 {
6945     xmlAttrPtr prop;
6946 
6947     if (ns && (ns->href == NULL))
6948 	return(NULL);
6949     prop = xmlGetPropNodeInternal(node, name, (ns != NULL) ? ns->href : NULL, 0);
6950     if (prop != NULL) {
6951 	/*
6952 	* Modify the attribute's value.
6953 	*/
6954 	if (prop->atype == XML_ATTRIBUTE_ID) {
6955 	    xmlRemoveID(node->doc, prop);
6956 	    prop->atype = XML_ATTRIBUTE_ID;
6957 	}
6958 	if (prop->children != NULL)
6959 	    xmlFreeNodeList(prop->children);
6960 	prop->children = NULL;
6961 	prop->last = NULL;
6962 	prop->ns = ns;
6963 	if (value != NULL) {
6964 	    xmlNodePtr tmp;
6965 
6966 	    prop->children = xmlNewDocText(node->doc, value);
6967 	    prop->last = NULL;
6968 	    tmp = prop->children;
6969 	    while (tmp != NULL) {
6970 		tmp->parent = (xmlNodePtr) prop;
6971 		if (tmp->next == NULL)
6972 		    prop->last = tmp;
6973 		tmp = tmp->next;
6974 	    }
6975 	}
6976 	if (prop->atype == XML_ATTRIBUTE_ID)
6977 	    xmlAddID(NULL, node->doc, value, prop);
6978 	return(prop);
6979     }
6980     /*
6981     * No equal attr found; create a new one.
6982     */
6983     return(xmlNewPropInternal(node, ns, name, value, 0));
6984 }
6985 
6986 #endif /* LIBXML_TREE_ENABLED */
6987 
6988 /**
6989  * xmlNodeIsText:
6990  * @node:  the node
6991  *
6992  * Is this node a Text node ?
6993  * Returns 1 yes, 0 no
6994  */
6995 int
xmlNodeIsText(const xmlNode * node)6996 xmlNodeIsText(const xmlNode *node) {
6997     if (node == NULL) return(0);
6998 
6999     if (node->type == XML_TEXT_NODE) return(1);
7000     return(0);
7001 }
7002 
7003 /**
7004  * xmlIsBlankNode:
7005  * @node:  the node
7006  *
7007  * Checks whether this node is an empty or whitespace only
7008  * (and possibly ignorable) text-node.
7009  *
7010  * Returns 1 yes, 0 no
7011  */
7012 int
xmlIsBlankNode(const xmlNode * node)7013 xmlIsBlankNode(const xmlNode *node) {
7014     const xmlChar *cur;
7015     if (node == NULL) return(0);
7016 
7017     if ((node->type != XML_TEXT_NODE) &&
7018         (node->type != XML_CDATA_SECTION_NODE))
7019 	return(0);
7020     if (node->content == NULL) return(1);
7021     cur = node->content;
7022     while (*cur != 0) {
7023 	if (!IS_BLANK_CH(*cur)) return(0);
7024 	cur++;
7025     }
7026 
7027     return(1);
7028 }
7029 
7030 /**
7031  * xmlTextConcat:
7032  * @node:  the node
7033  * @content:  the content
7034  * @len:  @content length
7035  *
7036  * Concat the given string at the end of the existing node content
7037  *
7038  * Returns -1 in case of error, 0 otherwise
7039  */
7040 
7041 int
xmlTextConcat(xmlNodePtr node,const xmlChar * content,int len)7042 xmlTextConcat(xmlNodePtr node, const xmlChar *content, int len) {
7043     if (node == NULL) return(-1);
7044 
7045     if ((node->type != XML_TEXT_NODE) &&
7046         (node->type != XML_CDATA_SECTION_NODE) &&
7047 	(node->type != XML_COMMENT_NODE) &&
7048 	(node->type != XML_PI_NODE)) {
7049 #ifdef DEBUG_TREE
7050 	xmlGenericError(xmlGenericErrorContext,
7051 		"xmlTextConcat: node is not text nor CDATA\n");
7052 #endif
7053         return(-1);
7054     }
7055     /* need to check if content is currently in the dictionary */
7056     if ((node->content == (xmlChar *) &(node->properties)) ||
7057         ((node->doc != NULL) && (node->doc->dict != NULL) &&
7058 		xmlDictOwns(node->doc->dict, node->content))) {
7059 	node->content = xmlStrncatNew(node->content, content, len);
7060     } else {
7061         node->content = xmlStrncat(node->content, content, len);
7062     }
7063     node->properties = NULL;
7064     if (node->content == NULL)
7065         return(-1);
7066     return(0);
7067 }
7068 
7069 /************************************************************************
7070  *									*
7071  *			Output : to a FILE or in memory			*
7072  *									*
7073  ************************************************************************/
7074 
7075 /**
7076  * xmlBufferCreate:
7077  *
7078  * routine to create an XML buffer.
7079  * returns the new structure.
7080  */
7081 xmlBufferPtr
xmlBufferCreate(void)7082 xmlBufferCreate(void) {
7083     xmlBufferPtr ret;
7084 
7085     ret = (xmlBufferPtr) xmlMalloc(sizeof(xmlBuffer));
7086     if (ret == NULL) {
7087 	xmlTreeErrMemory("creating buffer");
7088         return(NULL);
7089     }
7090     ret->use = 0;
7091     ret->size = xmlDefaultBufferSize;
7092     ret->alloc = xmlBufferAllocScheme;
7093     ret->content = (xmlChar *) xmlMallocAtomic(ret->size * sizeof(xmlChar));
7094     if (ret->content == NULL) {
7095 	xmlTreeErrMemory("creating buffer");
7096 	xmlFree(ret);
7097         return(NULL);
7098     }
7099     ret->content[0] = 0;
7100     ret->contentIO = NULL;
7101     return(ret);
7102 }
7103 
7104 /**
7105  * xmlBufferCreateSize:
7106  * @size: initial size of buffer
7107  *
7108  * routine to create an XML buffer.
7109  * returns the new structure.
7110  */
7111 xmlBufferPtr
xmlBufferCreateSize(size_t size)7112 xmlBufferCreateSize(size_t size) {
7113     xmlBufferPtr ret;
7114 
7115     if (size >= UINT_MAX)
7116         return(NULL);
7117     ret = (xmlBufferPtr) xmlMalloc(sizeof(xmlBuffer));
7118     if (ret == NULL) {
7119 	xmlTreeErrMemory("creating buffer");
7120         return(NULL);
7121     }
7122     ret->use = 0;
7123     ret->alloc = xmlBufferAllocScheme;
7124     ret->size = (size ? size+1 : 0);         /* +1 for ending null */
7125     if (ret->size){
7126         ret->content = (xmlChar *) xmlMallocAtomic(ret->size * sizeof(xmlChar));
7127         if (ret->content == NULL) {
7128 	    xmlTreeErrMemory("creating buffer");
7129             xmlFree(ret);
7130             return(NULL);
7131         }
7132         ret->content[0] = 0;
7133     } else
7134 	ret->content = NULL;
7135     ret->contentIO = NULL;
7136     return(ret);
7137 }
7138 
7139 /**
7140  * xmlBufferDetach:
7141  * @buf:  the buffer
7142  *
7143  * Remove the string contained in a buffer and gie it back to the
7144  * caller. The buffer is reset to an empty content.
7145  * This doesn't work with immutable buffers as they can't be reset.
7146  *
7147  * Returns the previous string contained by the buffer.
7148  */
7149 xmlChar *
xmlBufferDetach(xmlBufferPtr buf)7150 xmlBufferDetach(xmlBufferPtr buf) {
7151     xmlChar *ret;
7152 
7153     if (buf == NULL)
7154         return(NULL);
7155     if (buf->alloc == XML_BUFFER_ALLOC_IMMUTABLE)
7156         return(NULL);
7157 
7158     ret = buf->content;
7159     buf->content = NULL;
7160     buf->size = 0;
7161     buf->use = 0;
7162 
7163     return ret;
7164 }
7165 
7166 
7167 /**
7168  * xmlBufferCreateStatic:
7169  * @mem: the memory area
7170  * @size:  the size in byte
7171  *
7172  * routine to create an XML buffer from an immutable memory area.
7173  * The area won't be modified nor copied, and is expected to be
7174  * present until the end of the buffer lifetime.
7175  *
7176  * returns the new structure.
7177  */
7178 xmlBufferPtr
xmlBufferCreateStatic(void * mem,size_t size)7179 xmlBufferCreateStatic(void *mem, size_t size) {
7180     xmlBufferPtr ret;
7181 
7182     if ((mem == NULL) || (size == 0))
7183         return(NULL);
7184     if (size > UINT_MAX)
7185         return(NULL);
7186 
7187     ret = (xmlBufferPtr) xmlMalloc(sizeof(xmlBuffer));
7188     if (ret == NULL) {
7189 	xmlTreeErrMemory("creating buffer");
7190         return(NULL);
7191     }
7192     ret->use = size;
7193     ret->size = size;
7194     ret->alloc = XML_BUFFER_ALLOC_IMMUTABLE;
7195     ret->content = (xmlChar *) mem;
7196     return(ret);
7197 }
7198 
7199 /**
7200  * xmlBufferSetAllocationScheme:
7201  * @buf:  the buffer to tune
7202  * @scheme:  allocation scheme to use
7203  *
7204  * Sets the allocation scheme for this buffer
7205  */
7206 void
xmlBufferSetAllocationScheme(xmlBufferPtr buf,xmlBufferAllocationScheme scheme)7207 xmlBufferSetAllocationScheme(xmlBufferPtr buf,
7208                              xmlBufferAllocationScheme scheme) {
7209     if (buf == NULL) {
7210 #ifdef DEBUG_BUFFER
7211         xmlGenericError(xmlGenericErrorContext,
7212 		"xmlBufferSetAllocationScheme: buf == NULL\n");
7213 #endif
7214         return;
7215     }
7216     if ((buf->alloc == XML_BUFFER_ALLOC_IMMUTABLE) ||
7217         (buf->alloc == XML_BUFFER_ALLOC_IO)) return;
7218     if ((scheme == XML_BUFFER_ALLOC_DOUBLEIT) ||
7219         (scheme == XML_BUFFER_ALLOC_EXACT) ||
7220         (scheme == XML_BUFFER_ALLOC_HYBRID) ||
7221         (scheme == XML_BUFFER_ALLOC_IMMUTABLE))
7222 	buf->alloc = scheme;
7223 }
7224 
7225 /**
7226  * xmlBufferFree:
7227  * @buf:  the buffer to free
7228  *
7229  * Frees an XML buffer. It frees both the content and the structure which
7230  * encapsulate it.
7231  */
7232 void
xmlBufferFree(xmlBufferPtr buf)7233 xmlBufferFree(xmlBufferPtr buf) {
7234     if (buf == NULL) {
7235 #ifdef DEBUG_BUFFER
7236         xmlGenericError(xmlGenericErrorContext,
7237 		"xmlBufferFree: buf == NULL\n");
7238 #endif
7239 	return;
7240     }
7241 
7242     if ((buf->alloc == XML_BUFFER_ALLOC_IO) &&
7243         (buf->contentIO != NULL)) {
7244         xmlFree(buf->contentIO);
7245     } else if ((buf->content != NULL) &&
7246         (buf->alloc != XML_BUFFER_ALLOC_IMMUTABLE)) {
7247         xmlFree(buf->content);
7248     }
7249     xmlFree(buf);
7250 }
7251 
7252 /**
7253  * xmlBufferEmpty:
7254  * @buf:  the buffer
7255  *
7256  * empty a buffer.
7257  */
7258 void
xmlBufferEmpty(xmlBufferPtr buf)7259 xmlBufferEmpty(xmlBufferPtr buf) {
7260     if (buf == NULL) return;
7261     if (buf->content == NULL) return;
7262     buf->use = 0;
7263     if (buf->alloc == XML_BUFFER_ALLOC_IMMUTABLE) {
7264         buf->content = BAD_CAST "";
7265     } else if ((buf->alloc == XML_BUFFER_ALLOC_IO) &&
7266                (buf->contentIO != NULL)) {
7267         size_t start_buf = buf->content - buf->contentIO;
7268 
7269 	buf->size += start_buf;
7270         buf->content = buf->contentIO;
7271         buf->content[0] = 0;
7272     } else {
7273         buf->content[0] = 0;
7274     }
7275 }
7276 
7277 /**
7278  * xmlBufferShrink:
7279  * @buf:  the buffer to dump
7280  * @len:  the number of xmlChar to remove
7281  *
7282  * Remove the beginning of an XML buffer.
7283  *
7284  * Returns the number of #xmlChar removed, or -1 in case of failure.
7285  */
7286 int
xmlBufferShrink(xmlBufferPtr buf,unsigned int len)7287 xmlBufferShrink(xmlBufferPtr buf, unsigned int len) {
7288     if (buf == NULL) return(-1);
7289     if (len == 0) return(0);
7290     if (len > buf->use) return(-1);
7291 
7292     buf->use -= len;
7293     if ((buf->alloc == XML_BUFFER_ALLOC_IMMUTABLE) ||
7294         ((buf->alloc == XML_BUFFER_ALLOC_IO) && (buf->contentIO != NULL))) {
7295 	/*
7296 	 * we just move the content pointer, but also make sure
7297 	 * the perceived buffer size has shrunk accordingly
7298 	 */
7299         buf->content += len;
7300 	buf->size -= len;
7301 
7302         /*
7303 	 * sometimes though it maybe be better to really shrink
7304 	 * on IO buffers
7305 	 */
7306 	if ((buf->alloc == XML_BUFFER_ALLOC_IO) && (buf->contentIO != NULL)) {
7307 	    size_t start_buf = buf->content - buf->contentIO;
7308 	    if (start_buf >= buf->size) {
7309 		memmove(buf->contentIO, &buf->content[0], buf->use);
7310 		buf->content = buf->contentIO;
7311 		buf->content[buf->use] = 0;
7312 		buf->size += start_buf;
7313 	    }
7314 	}
7315     } else {
7316 	memmove(buf->content, &buf->content[len], buf->use);
7317 	buf->content[buf->use] = 0;
7318     }
7319     return(len);
7320 }
7321 
7322 /**
7323  * xmlBufferGrow:
7324  * @buf:  the buffer
7325  * @len:  the minimum free size to allocate
7326  *
7327  * Grow the available space of an XML buffer.
7328  *
7329  * Returns the new available space or -1 in case of error
7330  */
7331 int
xmlBufferGrow(xmlBufferPtr buf,unsigned int len)7332 xmlBufferGrow(xmlBufferPtr buf, unsigned int len) {
7333     unsigned int size;
7334     xmlChar *newbuf;
7335 
7336     if (buf == NULL) return(-1);
7337 
7338     if (buf->alloc == XML_BUFFER_ALLOC_IMMUTABLE) return(0);
7339     if (len < buf->size - buf->use)
7340         return(0);
7341     if (len > UINT_MAX - buf->use)
7342         return(-1);
7343 
7344     if (buf->size > (size_t) len) {
7345         size = buf->size > UINT_MAX / 2 ? UINT_MAX : buf->size * 2;
7346     } else {
7347         size = buf->use + len;
7348         size = size > UINT_MAX - 100 ? UINT_MAX : size + 100;
7349     }
7350 
7351     if ((buf->alloc == XML_BUFFER_ALLOC_IO) && (buf->contentIO != NULL)) {
7352         size_t start_buf = buf->content - buf->contentIO;
7353 
7354 	newbuf = (xmlChar *) xmlRealloc(buf->contentIO, start_buf + size);
7355 	if (newbuf == NULL) {
7356 	    xmlTreeErrMemory("growing buffer");
7357 	    return(-1);
7358 	}
7359 	buf->contentIO = newbuf;
7360 	buf->content = newbuf + start_buf;
7361     } else {
7362 	newbuf = (xmlChar *) xmlRealloc(buf->content, size);
7363 	if (newbuf == NULL) {
7364 	    xmlTreeErrMemory("growing buffer");
7365 	    return(-1);
7366 	}
7367 	buf->content = newbuf;
7368     }
7369     buf->size = size;
7370     return(buf->size - buf->use);
7371 }
7372 
7373 /**
7374  * xmlBufferDump:
7375  * @file:  the file output
7376  * @buf:  the buffer to dump
7377  *
7378  * Dumps an XML buffer to  a FILE *.
7379  * Returns the number of #xmlChar written
7380  */
7381 int
xmlBufferDump(FILE * file,xmlBufferPtr buf)7382 xmlBufferDump(FILE *file, xmlBufferPtr buf) {
7383     int ret;
7384 
7385     if (buf == NULL) {
7386 #ifdef DEBUG_BUFFER
7387         xmlGenericError(xmlGenericErrorContext,
7388 		"xmlBufferDump: buf == NULL\n");
7389 #endif
7390 	return(0);
7391     }
7392     if (buf->content == NULL) {
7393 #ifdef DEBUG_BUFFER
7394         xmlGenericError(xmlGenericErrorContext,
7395 		"xmlBufferDump: buf->content == NULL\n");
7396 #endif
7397 	return(0);
7398     }
7399     if (file == NULL)
7400 	file = stdout;
7401     ret = fwrite(buf->content, sizeof(xmlChar), buf->use, file);
7402     return(ret);
7403 }
7404 
7405 /**
7406  * xmlBufferContent:
7407  * @buf:  the buffer
7408  *
7409  * Function to extract the content of a buffer
7410  *
7411  * Returns the internal content
7412  */
7413 
7414 const xmlChar *
xmlBufferContent(const xmlBuffer * buf)7415 xmlBufferContent(const xmlBuffer *buf)
7416 {
7417     if(!buf)
7418         return NULL;
7419 
7420     return buf->content;
7421 }
7422 
7423 /**
7424  * xmlBufferLength:
7425  * @buf:  the buffer
7426  *
7427  * Function to get the length of a buffer
7428  *
7429  * Returns the length of data in the internal content
7430  */
7431 
7432 int
xmlBufferLength(const xmlBuffer * buf)7433 xmlBufferLength(const xmlBuffer *buf)
7434 {
7435     if(!buf)
7436         return 0;
7437 
7438     return buf->use;
7439 }
7440 
7441 /**
7442  * xmlBufferResize:
7443  * @buf:  the buffer to resize
7444  * @size:  the desired size
7445  *
7446  * Resize a buffer to accommodate minimum size of @size.
7447  *
7448  * Returns  0 in case of problems, 1 otherwise
7449  */
7450 int
xmlBufferResize(xmlBufferPtr buf,unsigned int size)7451 xmlBufferResize(xmlBufferPtr buf, unsigned int size)
7452 {
7453     unsigned int newSize;
7454     xmlChar* rebuf = NULL;
7455     size_t start_buf;
7456 
7457     if (buf == NULL)
7458         return(0);
7459 
7460     if (buf->alloc == XML_BUFFER_ALLOC_IMMUTABLE) return(0);
7461 
7462     /* Don't resize if we don't have to */
7463     if (size < buf->size)
7464         return 1;
7465 
7466     if (size > UINT_MAX - 10) {
7467         xmlTreeErrMemory("growing buffer");
7468         return 0;
7469     }
7470 
7471     /* figure out new size */
7472     switch (buf->alloc){
7473 	case XML_BUFFER_ALLOC_IO:
7474 	case XML_BUFFER_ALLOC_DOUBLEIT:
7475 	    /*take care of empty case*/
7476             if (buf->size == 0)
7477                 newSize = (size > UINT_MAX - 10 ? UINT_MAX : size + 10);
7478             else
7479                 newSize = buf->size;
7480 	    while (size > newSize) {
7481 	        if (newSize > UINT_MAX / 2) {
7482 	            xmlTreeErrMemory("growing buffer");
7483 	            return 0;
7484 	        }
7485 	        newSize *= 2;
7486 	    }
7487 	    break;
7488 	case XML_BUFFER_ALLOC_EXACT:
7489 	    newSize = (size > UINT_MAX - 10 ? UINT_MAX : size + 10);
7490 	    break;
7491         case XML_BUFFER_ALLOC_HYBRID:
7492             if (buf->use < BASE_BUFFER_SIZE)
7493                 newSize = size;
7494             else {
7495                 newSize = buf->size;
7496                 while (size > newSize) {
7497                     if (newSize > UINT_MAX / 2) {
7498                         xmlTreeErrMemory("growing buffer");
7499                         return 0;
7500                     }
7501                     newSize *= 2;
7502                 }
7503             }
7504             break;
7505 
7506 	default:
7507 	    newSize = (size > UINT_MAX - 10 ? UINT_MAX : size + 10);
7508 	    break;
7509     }
7510 
7511     if ((buf->alloc == XML_BUFFER_ALLOC_IO) && (buf->contentIO != NULL)) {
7512         start_buf = buf->content - buf->contentIO;
7513 
7514         if (start_buf > newSize) {
7515 	    /* move data back to start */
7516 	    memmove(buf->contentIO, buf->content, buf->use);
7517 	    buf->content = buf->contentIO;
7518 	    buf->content[buf->use] = 0;
7519 	    buf->size += start_buf;
7520 	} else {
7521 	    rebuf = (xmlChar *) xmlRealloc(buf->contentIO, start_buf + newSize);
7522 	    if (rebuf == NULL) {
7523 		xmlTreeErrMemory("growing buffer");
7524 		return 0;
7525 	    }
7526 	    buf->contentIO = rebuf;
7527 	    buf->content = rebuf + start_buf;
7528 	}
7529     } else {
7530 	if (buf->content == NULL) {
7531 	    rebuf = (xmlChar *) xmlMallocAtomic(newSize);
7532 	} else if (buf->size - buf->use < 100) {
7533 	    rebuf = (xmlChar *) xmlRealloc(buf->content, newSize);
7534         } else {
7535 	    /*
7536 	     * if we are reallocating a buffer far from being full, it's
7537 	     * better to make a new allocation and copy only the used range
7538 	     * and free the old one.
7539 	     */
7540 	    rebuf = (xmlChar *) xmlMallocAtomic(newSize);
7541 	    if (rebuf != NULL) {
7542 		memcpy(rebuf, buf->content, buf->use);
7543 		xmlFree(buf->content);
7544 		rebuf[buf->use] = 0;
7545 	    }
7546 	}
7547 	if (rebuf == NULL) {
7548 	    xmlTreeErrMemory("growing buffer");
7549 	    return 0;
7550 	}
7551 	buf->content = rebuf;
7552     }
7553     buf->size = newSize;
7554 
7555     return 1;
7556 }
7557 
7558 /**
7559  * xmlBufferAdd:
7560  * @buf:  the buffer to dump
7561  * @str:  the #xmlChar string
7562  * @len:  the number of #xmlChar to add
7563  *
7564  * Add a string range to an XML buffer. if len == -1, the length of
7565  * str is recomputed.
7566  *
7567  * Returns 0 successful, a positive error code number otherwise
7568  *         and -1 in case of internal or API error.
7569  */
7570 int
xmlBufferAdd(xmlBufferPtr buf,const xmlChar * str,int len)7571 xmlBufferAdd(xmlBufferPtr buf, const xmlChar *str, int len) {
7572     unsigned int needSize;
7573 
7574     if ((str == NULL) || (buf == NULL)) {
7575 	return -1;
7576     }
7577     if (buf->alloc == XML_BUFFER_ALLOC_IMMUTABLE) return -1;
7578     if (len < -1) {
7579 #ifdef DEBUG_BUFFER
7580         xmlGenericError(xmlGenericErrorContext,
7581 		"xmlBufferAdd: len < 0\n");
7582 #endif
7583 	return -1;
7584     }
7585     if (len == 0) return 0;
7586 
7587     if (len < 0)
7588         len = xmlStrlen(str);
7589 
7590     if (len < 0) return -1;
7591     if (len == 0) return 0;
7592 
7593     if ((unsigned) len >= buf->size - buf->use) {
7594         if ((unsigned) len >= UINT_MAX - buf->use)
7595             return XML_ERR_NO_MEMORY;
7596         needSize = buf->use + len + 1;
7597         if (!xmlBufferResize(buf, needSize)){
7598 	    xmlTreeErrMemory("growing buffer");
7599             return XML_ERR_NO_MEMORY;
7600         }
7601     }
7602 
7603     memmove(&buf->content[buf->use], str, len*sizeof(xmlChar));
7604     buf->use += len;
7605     buf->content[buf->use] = 0;
7606     return 0;
7607 }
7608 
7609 /**
7610  * xmlBufferAddHead:
7611  * @buf:  the buffer
7612  * @str:  the #xmlChar string
7613  * @len:  the number of #xmlChar to add
7614  *
7615  * Add a string range to the beginning of an XML buffer.
7616  * if len == -1, the length of @str is recomputed.
7617  *
7618  * Returns 0 successful, a positive error code number otherwise
7619  *         and -1 in case of internal or API error.
7620  */
7621 int
xmlBufferAddHead(xmlBufferPtr buf,const xmlChar * str,int len)7622 xmlBufferAddHead(xmlBufferPtr buf, const xmlChar *str, int len) {
7623     unsigned int needSize;
7624 
7625     if (buf == NULL)
7626         return(-1);
7627     if (buf->alloc == XML_BUFFER_ALLOC_IMMUTABLE) return -1;
7628     if (str == NULL) {
7629 #ifdef DEBUG_BUFFER
7630         xmlGenericError(xmlGenericErrorContext,
7631 		"xmlBufferAddHead: str == NULL\n");
7632 #endif
7633 	return -1;
7634     }
7635     if (len < -1) {
7636 #ifdef DEBUG_BUFFER
7637         xmlGenericError(xmlGenericErrorContext,
7638 		"xmlBufferAddHead: len < 0\n");
7639 #endif
7640 	return -1;
7641     }
7642     if (len == 0) return 0;
7643 
7644     if (len < 0)
7645         len = xmlStrlen(str);
7646 
7647     if (len <= 0) return -1;
7648 
7649     if ((buf->alloc == XML_BUFFER_ALLOC_IO) && (buf->contentIO != NULL)) {
7650         size_t start_buf = buf->content - buf->contentIO;
7651 
7652 	if (start_buf > (unsigned int) len) {
7653 	    /*
7654 	     * We can add it in the space previously shrunk
7655 	     */
7656 	    buf->content -= len;
7657             memmove(&buf->content[0], str, len);
7658 	    buf->use += len;
7659 	    buf->size += len;
7660 	    return(0);
7661 	}
7662     }
7663     needSize = buf->use + len + 2;
7664     if (needSize > buf->size){
7665         if (!xmlBufferResize(buf, needSize)){
7666 	    xmlTreeErrMemory("growing buffer");
7667             return XML_ERR_NO_MEMORY;
7668         }
7669     }
7670 
7671     memmove(&buf->content[len], &buf->content[0], buf->use);
7672     memmove(&buf->content[0], str, len);
7673     buf->use += len;
7674     buf->content[buf->use] = 0;
7675     return 0;
7676 }
7677 
7678 /**
7679  * xmlBufferCat:
7680  * @buf:  the buffer to add to
7681  * @str:  the #xmlChar string
7682  *
7683  * Append a zero terminated string to an XML buffer.
7684  *
7685  * Returns 0 successful, a positive error code number otherwise
7686  *         and -1 in case of internal or API error.
7687  */
7688 int
xmlBufferCat(xmlBufferPtr buf,const xmlChar * str)7689 xmlBufferCat(xmlBufferPtr buf, const xmlChar *str) {
7690     if (buf == NULL)
7691         return(-1);
7692     if (buf->alloc == XML_BUFFER_ALLOC_IMMUTABLE) return -1;
7693     if (str == NULL) return -1;
7694     return xmlBufferAdd(buf, str, -1);
7695 }
7696 
7697 /**
7698  * xmlBufferCCat:
7699  * @buf:  the buffer to dump
7700  * @str:  the C char string
7701  *
7702  * Append a zero terminated C string to an XML buffer.
7703  *
7704  * Returns 0 successful, a positive error code number otherwise
7705  *         and -1 in case of internal or API error.
7706  */
7707 int
xmlBufferCCat(xmlBufferPtr buf,const char * str)7708 xmlBufferCCat(xmlBufferPtr buf, const char *str) {
7709     return xmlBufferCat(buf, (const xmlChar *) str);
7710 }
7711 
7712 /**
7713  * xmlBufferWriteCHAR:
7714  * @buf:  the XML buffer
7715  * @string:  the string to add
7716  *
7717  * routine which manages and grows an output buffer. This one adds
7718  * xmlChars at the end of the buffer.
7719  */
7720 void
xmlBufferWriteCHAR(xmlBufferPtr buf,const xmlChar * string)7721 xmlBufferWriteCHAR(xmlBufferPtr buf, const xmlChar *string) {
7722     if (buf == NULL)
7723         return;
7724     if (buf->alloc == XML_BUFFER_ALLOC_IMMUTABLE) return;
7725     xmlBufferCat(buf, string);
7726 }
7727 
7728 /**
7729  * xmlBufferWriteChar:
7730  * @buf:  the XML buffer output
7731  * @string:  the string to add
7732  *
7733  * routine which manage and grows an output buffer. This one add
7734  * C chars at the end of the array.
7735  */
7736 void
xmlBufferWriteChar(xmlBufferPtr buf,const char * string)7737 xmlBufferWriteChar(xmlBufferPtr buf, const char *string) {
7738     if (buf == NULL)
7739         return;
7740     if (buf->alloc == XML_BUFFER_ALLOC_IMMUTABLE) return;
7741     xmlBufferCCat(buf, string);
7742 }
7743 
7744 
7745 /**
7746  * xmlBufferWriteQuotedString:
7747  * @buf:  the XML buffer output
7748  * @string:  the string to add
7749  *
7750  * routine which manage and grows an output buffer. This one writes
7751  * a quoted or double quoted #xmlChar string, checking first if it holds
7752  * quote or double-quotes internally
7753  */
7754 void
xmlBufferWriteQuotedString(xmlBufferPtr buf,const xmlChar * string)7755 xmlBufferWriteQuotedString(xmlBufferPtr buf, const xmlChar *string) {
7756     const xmlChar *cur, *base;
7757     if (buf == NULL)
7758         return;
7759     if (buf->alloc == XML_BUFFER_ALLOC_IMMUTABLE) return;
7760     if (xmlStrchr(string, '\"')) {
7761         if (xmlStrchr(string, '\'')) {
7762 #ifdef DEBUG_BUFFER
7763 	    xmlGenericError(xmlGenericErrorContext,
7764  "xmlBufferWriteQuotedString: string contains quote and double-quotes !\n");
7765 #endif
7766 	    xmlBufferCCat(buf, "\"");
7767             base = cur = string;
7768             while(*cur != 0){
7769                 if(*cur == '"'){
7770                     if (base != cur)
7771                         xmlBufferAdd(buf, base, cur - base);
7772                     xmlBufferAdd(buf, BAD_CAST "&quot;", 6);
7773                     cur++;
7774                     base = cur;
7775                 }
7776                 else {
7777                     cur++;
7778                 }
7779             }
7780             if (base != cur)
7781                 xmlBufferAdd(buf, base, cur - base);
7782 	    xmlBufferCCat(buf, "\"");
7783 	}
7784         else{
7785 	    xmlBufferCCat(buf, "\'");
7786             xmlBufferCat(buf, string);
7787 	    xmlBufferCCat(buf, "\'");
7788         }
7789     } else {
7790         xmlBufferCCat(buf, "\"");
7791         xmlBufferCat(buf, string);
7792         xmlBufferCCat(buf, "\"");
7793     }
7794 }
7795 
7796 
7797 /**
7798  * xmlGetDocCompressMode:
7799  * @doc:  the document
7800  *
7801  * get the compression ratio for a document, ZLIB based
7802  * Returns 0 (uncompressed) to 9 (max compression)
7803  */
7804 int
xmlGetDocCompressMode(const xmlDoc * doc)7805 xmlGetDocCompressMode (const xmlDoc *doc) {
7806     if (doc == NULL) return(-1);
7807     return(doc->compression);
7808 }
7809 
7810 /**
7811  * xmlSetDocCompressMode:
7812  * @doc:  the document
7813  * @mode:  the compression ratio
7814  *
7815  * set the compression ratio for a document, ZLIB based
7816  * Correct values: 0 (uncompressed) to 9 (max compression)
7817  */
7818 void
xmlSetDocCompressMode(xmlDocPtr doc,int mode)7819 xmlSetDocCompressMode (xmlDocPtr doc, int mode) {
7820     if (doc == NULL) return;
7821     if (mode < 0) doc->compression = 0;
7822     else if (mode > 9) doc->compression = 9;
7823     else doc->compression = mode;
7824 }
7825 
7826 /**
7827  * xmlGetCompressMode:
7828  *
7829  * get the default compression mode used, ZLIB based.
7830  * Returns 0 (uncompressed) to 9 (max compression)
7831  */
7832 int
xmlGetCompressMode(void)7833 xmlGetCompressMode(void)
7834 {
7835     return (xmlCompressMode);
7836 }
7837 
7838 /**
7839  * xmlSetCompressMode:
7840  * @mode:  the compression ratio
7841  *
7842  * set the default compression mode used, ZLIB based
7843  * Correct values: 0 (uncompressed) to 9 (max compression)
7844  */
7845 void
xmlSetCompressMode(int mode)7846 xmlSetCompressMode(int mode) {
7847     if (mode < 0) xmlCompressMode = 0;
7848     else if (mode > 9) xmlCompressMode = 9;
7849     else xmlCompressMode = mode;
7850 }
7851 
7852 #define XML_TREE_NSMAP_PARENT -1
7853 #define XML_TREE_NSMAP_XML -2
7854 #define XML_TREE_NSMAP_DOC -3
7855 #define XML_TREE_NSMAP_CUSTOM -4
7856 
7857 typedef struct xmlNsMapItem *xmlNsMapItemPtr;
7858 struct xmlNsMapItem {
7859     xmlNsMapItemPtr next;
7860     xmlNsMapItemPtr prev;
7861     xmlNsPtr oldNs; /* old ns decl reference */
7862     xmlNsPtr newNs; /* new ns decl reference */
7863     int shadowDepth; /* Shadowed at this depth */
7864     /*
7865     * depth:
7866     * >= 0 == @node's ns-decls
7867     * -1   == @parent's ns-decls
7868     * -2   == the doc->oldNs XML ns-decl
7869     * -3   == the doc->oldNs storage ns-decls
7870     * -4   == ns-decls provided via custom ns-handling
7871     */
7872     int depth;
7873 };
7874 
7875 typedef struct xmlNsMap *xmlNsMapPtr;
7876 struct xmlNsMap {
7877     xmlNsMapItemPtr first;
7878     xmlNsMapItemPtr last;
7879     xmlNsMapItemPtr pool;
7880 };
7881 
7882 #define XML_NSMAP_NOTEMPTY(m) (((m) != NULL) && ((m)->first != NULL))
7883 #define XML_NSMAP_FOREACH(m, i) for (i = (m)->first; i != NULL; i = (i)->next)
7884 #define XML_NSMAP_POP(m, i) \
7885     i = (m)->last; \
7886     (m)->last = (i)->prev; \
7887     if ((m)->last == NULL) \
7888 	(m)->first = NULL; \
7889     else \
7890 	(m)->last->next = NULL; \
7891     (i)->next = (m)->pool; \
7892     (m)->pool = i;
7893 
7894 /*
7895 * xmlDOMWrapNsMapFree:
7896 * @map: the ns-map
7897 *
7898 * Frees the ns-map
7899 */
7900 static void
xmlDOMWrapNsMapFree(xmlNsMapPtr nsmap)7901 xmlDOMWrapNsMapFree(xmlNsMapPtr nsmap)
7902 {
7903     xmlNsMapItemPtr cur, tmp;
7904 
7905     if (nsmap == NULL)
7906 	return;
7907     cur = nsmap->pool;
7908     while (cur != NULL) {
7909 	tmp = cur;
7910 	cur = cur->next;
7911 	xmlFree(tmp);
7912     }
7913     cur = nsmap->first;
7914     while (cur != NULL) {
7915 	tmp = cur;
7916 	cur = cur->next;
7917 	xmlFree(tmp);
7918     }
7919     xmlFree(nsmap);
7920 }
7921 
7922 /*
7923 * xmlDOMWrapNsMapAddItem:
7924 * @map: the ns-map
7925 * @oldNs: the old ns-struct
7926 * @newNs: the new ns-struct
7927 * @depth: depth and ns-kind information
7928 *
7929 * Adds an ns-mapping item.
7930 */
7931 static xmlNsMapItemPtr
xmlDOMWrapNsMapAddItem(xmlNsMapPtr * nsmap,int position,xmlNsPtr oldNs,xmlNsPtr newNs,int depth)7932 xmlDOMWrapNsMapAddItem(xmlNsMapPtr *nsmap, int position,
7933 		       xmlNsPtr oldNs, xmlNsPtr newNs, int depth)
7934 {
7935     xmlNsMapItemPtr ret;
7936     xmlNsMapPtr map;
7937 
7938     if (nsmap == NULL)
7939 	return(NULL);
7940     if ((position != -1) && (position != 0))
7941 	return(NULL);
7942     map = *nsmap;
7943 
7944     if (map == NULL) {
7945 	/*
7946 	* Create the ns-map.
7947 	*/
7948 	map = (xmlNsMapPtr) xmlMalloc(sizeof(struct xmlNsMap));
7949 	if (map == NULL) {
7950 	    xmlTreeErrMemory("allocating namespace map");
7951 	    return (NULL);
7952 	}
7953 	memset(map, 0, sizeof(struct xmlNsMap));
7954 	*nsmap = map;
7955     }
7956 
7957     if (map->pool != NULL) {
7958 	/*
7959 	* Reuse an item from the pool.
7960 	*/
7961 	ret = map->pool;
7962 	map->pool = ret->next;
7963 	memset(ret, 0, sizeof(struct xmlNsMapItem));
7964     } else {
7965 	/*
7966 	* Create a new item.
7967 	*/
7968 	ret = (xmlNsMapItemPtr) xmlMalloc(sizeof(struct xmlNsMapItem));
7969 	if (ret == NULL) {
7970 	    xmlTreeErrMemory("allocating namespace map item");
7971 	    return (NULL);
7972 	}
7973 	memset(ret, 0, sizeof(struct xmlNsMapItem));
7974     }
7975 
7976     if (map->first == NULL) {
7977 	/*
7978 	* First ever.
7979 	*/
7980 	map->first = ret;
7981 	map->last = ret;
7982     } else if (position == -1) {
7983 	/*
7984 	* Append.
7985 	*/
7986 	ret->prev = map->last;
7987 	map->last->next = ret;
7988 	map->last = ret;
7989     } else if (position == 0) {
7990 	/*
7991 	* Set on first position.
7992 	*/
7993 	map->first->prev = ret;
7994 	ret->next = map->first;
7995 	map->first = ret;
7996     }
7997 
7998     ret->oldNs = oldNs;
7999     ret->newNs = newNs;
8000     ret->shadowDepth = -1;
8001     ret->depth = depth;
8002     return (ret);
8003 }
8004 
8005 /*
8006 * xmlDOMWrapStoreNs:
8007 * @doc: the doc
8008 * @nsName: the namespace name
8009 * @prefix: the prefix
8010 *
8011 * Creates or reuses an xmlNs struct on doc->oldNs with
8012 * the given prefix and namespace name.
8013 *
8014 * Returns the acquired ns struct or NULL in case of an API
8015 *         or internal error.
8016 */
8017 static xmlNsPtr
xmlDOMWrapStoreNs(xmlDocPtr doc,const xmlChar * nsName,const xmlChar * prefix)8018 xmlDOMWrapStoreNs(xmlDocPtr doc,
8019 		   const xmlChar *nsName,
8020 		   const xmlChar *prefix)
8021 {
8022     xmlNsPtr ns;
8023 
8024     if (doc == NULL)
8025 	return (NULL);
8026     ns = xmlTreeEnsureXMLDecl(doc);
8027     if (ns == NULL)
8028 	return (NULL);
8029     if (ns->next != NULL) {
8030 	/* Reuse. */
8031 	ns = ns->next;
8032 	while (ns != NULL) {
8033 	    if (((ns->prefix == prefix) ||
8034 		xmlStrEqual(ns->prefix, prefix)) &&
8035 		xmlStrEqual(ns->href, nsName)) {
8036 		return (ns);
8037 	    }
8038 	    if (ns->next == NULL)
8039 		break;
8040 	    ns = ns->next;
8041 	}
8042     }
8043     /* Create. */
8044     if (ns != NULL) {
8045         ns->next = xmlNewNs(NULL, nsName, prefix);
8046         return (ns->next);
8047     }
8048     return(NULL);
8049 }
8050 
8051 /*
8052 * xmlDOMWrapNewCtxt:
8053 *
8054 * Allocates and initializes a new DOM-wrapper context.
8055 *
8056 * Returns the xmlDOMWrapCtxtPtr or NULL in case of an internal error.
8057 */
8058 xmlDOMWrapCtxtPtr
xmlDOMWrapNewCtxt(void)8059 xmlDOMWrapNewCtxt(void)
8060 {
8061     xmlDOMWrapCtxtPtr ret;
8062 
8063     ret = xmlMalloc(sizeof(xmlDOMWrapCtxt));
8064     if (ret == NULL) {
8065 	xmlTreeErrMemory("allocating DOM-wrapper context");
8066 	return (NULL);
8067     }
8068     memset(ret, 0, sizeof(xmlDOMWrapCtxt));
8069     return (ret);
8070 }
8071 
8072 /*
8073 * xmlDOMWrapFreeCtxt:
8074 * @ctxt: the DOM-wrapper context
8075 *
8076 * Frees the DOM-wrapper context.
8077 */
8078 void
xmlDOMWrapFreeCtxt(xmlDOMWrapCtxtPtr ctxt)8079 xmlDOMWrapFreeCtxt(xmlDOMWrapCtxtPtr ctxt)
8080 {
8081     if (ctxt == NULL)
8082 	return;
8083     if (ctxt->namespaceMap != NULL)
8084 	xmlDOMWrapNsMapFree((xmlNsMapPtr) ctxt->namespaceMap);
8085     /*
8086     * TODO: Store the namespace map in the context.
8087     */
8088     xmlFree(ctxt);
8089 }
8090 
8091 /*
8092 * xmlTreeLookupNsListByPrefix:
8093 * @nsList: a list of ns-structs
8094 * @prefix: the searched prefix
8095 *
8096 * Searches for a ns-decl with the given prefix in @nsList.
8097 *
8098 * Returns the ns-decl if found, NULL if not found and on
8099 *         API errors.
8100 */
8101 static xmlNsPtr
xmlTreeNSListLookupByPrefix(xmlNsPtr nsList,const xmlChar * prefix)8102 xmlTreeNSListLookupByPrefix(xmlNsPtr nsList, const xmlChar *prefix)
8103 {
8104     if (nsList == NULL)
8105 	return (NULL);
8106     {
8107 	xmlNsPtr ns;
8108 	ns = nsList;
8109 	do {
8110 	    if ((prefix == ns->prefix) ||
8111 		xmlStrEqual(prefix, ns->prefix)) {
8112 		return (ns);
8113 	    }
8114 	    ns = ns->next;
8115 	} while (ns != NULL);
8116     }
8117     return (NULL);
8118 }
8119 
8120 /*
8121 *
8122 * xmlDOMWrapNSNormGatherInScopeNs:
8123 * @map: the namespace map
8124 * @node: the node to start with
8125 *
8126 * Puts in-scope namespaces into the ns-map.
8127 *
8128 * Returns 0 on success, -1 on API or internal errors.
8129 */
8130 static int
xmlDOMWrapNSNormGatherInScopeNs(xmlNsMapPtr * map,xmlNodePtr node)8131 xmlDOMWrapNSNormGatherInScopeNs(xmlNsMapPtr *map,
8132 				xmlNodePtr node)
8133 {
8134     xmlNodePtr cur;
8135     xmlNsPtr ns;
8136     xmlNsMapItemPtr mi;
8137     int shadowed;
8138 
8139     if ((map == NULL) || (*map != NULL))
8140 	return (-1);
8141     if ((node == NULL) || (node->type == XML_NAMESPACE_DECL))
8142         return (-1);
8143     /*
8144     * Get in-scope ns-decls of @parent.
8145     */
8146     cur = node;
8147     while ((cur != NULL) && (cur != (xmlNodePtr) cur->doc)) {
8148 	if (cur->type == XML_ELEMENT_NODE) {
8149 	    if (cur->nsDef != NULL) {
8150 		ns = cur->nsDef;
8151 		do {
8152 		    shadowed = 0;
8153 		    if (XML_NSMAP_NOTEMPTY(*map)) {
8154 			/*
8155 			* Skip shadowed prefixes.
8156 			*/
8157 			XML_NSMAP_FOREACH(*map, mi) {
8158 			    if ((ns->prefix == mi->newNs->prefix) ||
8159 				xmlStrEqual(ns->prefix, mi->newNs->prefix)) {
8160 				shadowed = 1;
8161 				break;
8162 			    }
8163 			}
8164 		    }
8165 		    /*
8166 		    * Insert mapping.
8167 		    */
8168 		    mi = xmlDOMWrapNsMapAddItem(map, 0, NULL,
8169 			ns, XML_TREE_NSMAP_PARENT);
8170 		    if (mi == NULL)
8171 			return (-1);
8172 		    if (shadowed)
8173 			mi->shadowDepth = 0;
8174 		    ns = ns->next;
8175 		} while (ns != NULL);
8176 	    }
8177 	}
8178 	cur = cur->parent;
8179     }
8180     return (0);
8181 }
8182 
8183 /*
8184 * XML_TREE_ADOPT_STR: If we have a dest-dict, put @str in the dict;
8185 * otherwise copy it, when it was in the source-dict.
8186 */
8187 #define XML_TREE_ADOPT_STR(str) \
8188     if (adoptStr && (str != NULL)) { \
8189 	if (destDoc->dict) { \
8190 	    const xmlChar *old = str;	\
8191 	    str = xmlDictLookup(destDoc->dict, str, -1); \
8192 	    if ((sourceDoc == NULL) || (sourceDoc->dict == NULL) || \
8193 	        (!xmlDictOwns(sourceDoc->dict, old))) \
8194 		xmlFree((char *)old); \
8195 	} else if ((sourceDoc) && (sourceDoc->dict) && \
8196 	    xmlDictOwns(sourceDoc->dict, str)) { \
8197 	    str = BAD_CAST xmlStrdup(str); \
8198 	} \
8199     }
8200 
8201 /*
8202 * XML_TREE_ADOPT_STR_2: If @str was in the source-dict, then
8203 * put it in dest-dict or copy it.
8204 */
8205 #define XML_TREE_ADOPT_STR_2(str) \
8206     if (adoptStr && (str != NULL) && (sourceDoc != NULL) && \
8207 	(sourceDoc->dict != NULL) && \
8208 	xmlDictOwns(sourceDoc->dict, cur->content)) { \
8209 	if (destDoc->dict) \
8210 	    cur->content = (xmlChar *) \
8211 		xmlDictLookup(destDoc->dict, cur->content, -1); \
8212 	else \
8213 	    cur->content = xmlStrdup(BAD_CAST cur->content); \
8214     }
8215 
8216 /*
8217 * xmlDOMWrapNSNormAddNsMapItem2:
8218 *
8219 * For internal use. Adds a ns-decl mapping.
8220 *
8221 * Returns 0 on success, -1 on internal errors.
8222 */
8223 static int
xmlDOMWrapNSNormAddNsMapItem2(xmlNsPtr ** list,int * size,int * number,xmlNsPtr oldNs,xmlNsPtr newNs)8224 xmlDOMWrapNSNormAddNsMapItem2(xmlNsPtr **list, int *size, int *number,
8225 			xmlNsPtr oldNs, xmlNsPtr newNs)
8226 {
8227     if (*list == NULL) {
8228 	*list = (xmlNsPtr *) xmlMalloc(6 * sizeof(xmlNsPtr));
8229 	if (*list == NULL) {
8230 	    xmlTreeErrMemory("alloc ns map item");
8231 	    return(-1);
8232 	}
8233 	*size = 3;
8234 	*number = 0;
8235     } else if ((*number) >= (*size)) {
8236 	*size *= 2;
8237 	*list = (xmlNsPtr *) xmlRealloc(*list,
8238 	    (*size) * 2 * sizeof(xmlNsPtr));
8239 	if (*list == NULL) {
8240 	    xmlTreeErrMemory("realloc ns map item");
8241 	    return(-1);
8242 	}
8243     }
8244     (*list)[2 * (*number)] = oldNs;
8245     (*list)[2 * (*number) +1] = newNs;
8246     (*number)++;
8247     return (0);
8248 }
8249 
8250 /*
8251 * xmlDOMWrapRemoveNode:
8252 * @ctxt: a DOM wrapper context
8253 * @doc: the doc
8254 * @node: the node to be removed.
8255 * @options: set of options, unused at the moment
8256 *
8257 * Unlinks the given node from its owner.
8258 * This will substitute ns-references to node->nsDef for
8259 * ns-references to doc->oldNs, thus ensuring the removed
8260 * branch to be autark wrt ns-references.
8261 *
8262 * NOTE: This function was not intensively tested.
8263 *
8264 * Returns 0 on success, 1 if the node is not supported,
8265 *         -1 on API and internal errors.
8266 */
8267 int
xmlDOMWrapRemoveNode(xmlDOMWrapCtxtPtr ctxt,xmlDocPtr doc,xmlNodePtr node,int options ATTRIBUTE_UNUSED)8268 xmlDOMWrapRemoveNode(xmlDOMWrapCtxtPtr ctxt, xmlDocPtr doc,
8269 		     xmlNodePtr node, int options ATTRIBUTE_UNUSED)
8270 {
8271     xmlNsPtr *list = NULL;
8272     int sizeList, nbList, i, j;
8273     xmlNsPtr ns;
8274 
8275     if ((node == NULL) || (doc == NULL) || (node->doc != doc))
8276 	return (-1);
8277 
8278     /* TODO: 0 or -1 ? */
8279     if (node->parent == NULL)
8280 	return (0);
8281 
8282     switch (node->type) {
8283 	case XML_TEXT_NODE:
8284 	case XML_CDATA_SECTION_NODE:
8285 	case XML_ENTITY_REF_NODE:
8286 	case XML_PI_NODE:
8287 	case XML_COMMENT_NODE:
8288 	    xmlUnlinkNode(node);
8289 	    return (0);
8290 	case XML_ELEMENT_NODE:
8291 	case XML_ATTRIBUTE_NODE:
8292 	    break;
8293 	default:
8294 	    return (1);
8295     }
8296     xmlUnlinkNode(node);
8297     /*
8298     * Save out-of-scope ns-references in doc->oldNs.
8299     */
8300     do {
8301 	switch (node->type) {
8302 	    case XML_ELEMENT_NODE:
8303 		if ((ctxt == NULL) && (node->nsDef != NULL)) {
8304 		    ns = node->nsDef;
8305 		    do {
8306 			if (xmlDOMWrapNSNormAddNsMapItem2(&list, &sizeList,
8307 			    &nbList, ns, ns) == -1)
8308 			    goto internal_error;
8309 			ns = ns->next;
8310 		    } while (ns != NULL);
8311 		}
8312                 /* Falls through. */
8313 	    case XML_ATTRIBUTE_NODE:
8314 		if (node->ns != NULL) {
8315 		    /*
8316 		    * Find a mapping.
8317 		    */
8318 		    if (list != NULL) {
8319 			for (i = 0, j = 0; i < nbList; i++, j += 2) {
8320 			    if (node->ns == list[j]) {
8321 				node->ns = list[++j];
8322 				goto next_node;
8323 			    }
8324 			}
8325 		    }
8326 		    ns = NULL;
8327 		    if (ctxt != NULL) {
8328 			/*
8329 			* User defined.
8330 			*/
8331 		    } else {
8332 			/*
8333 			* Add to doc's oldNs.
8334 			*/
8335 			ns = xmlDOMWrapStoreNs(doc, node->ns->href,
8336 			    node->ns->prefix);
8337 			if (ns == NULL)
8338 			    goto internal_error;
8339 		    }
8340 		    if (ns != NULL) {
8341 			/*
8342 			* Add mapping.
8343 			*/
8344 			if (xmlDOMWrapNSNormAddNsMapItem2(&list, &sizeList,
8345 			    &nbList, node->ns, ns) == -1)
8346 			    goto internal_error;
8347 		    }
8348 		    node->ns = ns;
8349 		}
8350 		if ((node->type == XML_ELEMENT_NODE) &&
8351 		    (node->properties != NULL)) {
8352 		    node = (xmlNodePtr) node->properties;
8353 		    continue;
8354 		}
8355 		break;
8356 	    default:
8357 		goto next_sibling;
8358 	}
8359 next_node:
8360 	if ((node->type == XML_ELEMENT_NODE) &&
8361 	    (node->children != NULL)) {
8362 	    node = node->children;
8363 	    continue;
8364 	}
8365 next_sibling:
8366 	if (node == NULL)
8367 	    break;
8368 	if (node->next != NULL)
8369 	    node = node->next;
8370 	else {
8371 	    node = node->parent;
8372 	    goto next_sibling;
8373 	}
8374     } while (node != NULL);
8375 
8376     if (list != NULL)
8377 	xmlFree(list);
8378     return (0);
8379 
8380 internal_error:
8381     if (list != NULL)
8382 	xmlFree(list);
8383     return (-1);
8384 }
8385 
8386 /*
8387 * xmlSearchNsByNamespaceStrict:
8388 * @doc: the document
8389 * @node: the start node
8390 * @nsName: the searched namespace name
8391 * @retNs: the resulting ns-decl
8392 * @prefixed: if the found ns-decl must have a prefix (for attributes)
8393 *
8394 * Dynamically searches for a ns-declaration which matches
8395 * the given @nsName in the ancestor-or-self axis of @node.
8396 *
8397 * Returns 1 if a ns-decl was found, 0 if not and -1 on API
8398 *         and internal errors.
8399 */
8400 static int
xmlSearchNsByNamespaceStrict(xmlDocPtr doc,xmlNodePtr node,const xmlChar * nsName,xmlNsPtr * retNs,int prefixed)8401 xmlSearchNsByNamespaceStrict(xmlDocPtr doc, xmlNodePtr node,
8402 			     const xmlChar* nsName,
8403 			     xmlNsPtr *retNs, int prefixed)
8404 {
8405     xmlNodePtr cur, prev = NULL, out = NULL;
8406     xmlNsPtr ns, prevns;
8407 
8408     if ((doc == NULL) || (nsName == NULL) || (retNs == NULL))
8409 	return (-1);
8410     if ((node == NULL) || (node->type == XML_NAMESPACE_DECL))
8411         return(-1);
8412 
8413     *retNs = NULL;
8414     if (xmlStrEqual(nsName, XML_XML_NAMESPACE)) {
8415 	*retNs = xmlTreeEnsureXMLDecl(doc);
8416 	if (*retNs == NULL)
8417 	    return (-1);
8418 	return (1);
8419     }
8420     cur = node;
8421     do {
8422 	if (cur->type == XML_ELEMENT_NODE) {
8423 	    if (cur->nsDef != NULL) {
8424 		for (ns = cur->nsDef; ns != NULL; ns = ns->next) {
8425 		    if (prefixed && (ns->prefix == NULL))
8426 			continue;
8427 		    if (prev != NULL) {
8428 			/*
8429 			* Check the last level of ns-decls for a
8430 			* shadowing prefix.
8431 			*/
8432 			prevns = prev->nsDef;
8433 			do {
8434 			    if ((prevns->prefix == ns->prefix) ||
8435 				((prevns->prefix != NULL) &&
8436 				(ns->prefix != NULL) &&
8437 				xmlStrEqual(prevns->prefix, ns->prefix))) {
8438 				/*
8439 				* Shadowed.
8440 				*/
8441 				break;
8442 			    }
8443 			    prevns = prevns->next;
8444 			} while (prevns != NULL);
8445 			if (prevns != NULL)
8446 			    continue;
8447 		    }
8448 		    /*
8449 		    * Ns-name comparison.
8450 		    */
8451 		    if ((nsName == ns->href) ||
8452 			xmlStrEqual(nsName, ns->href)) {
8453 			/*
8454 			* At this point the prefix can only be shadowed,
8455 			* if we are the the (at least) 3rd level of
8456 			* ns-decls.
8457 			*/
8458 			if (out) {
8459 			    int ret;
8460 
8461 			    ret = xmlNsInScope(doc, node, prev, ns->prefix);
8462 			    if (ret < 0)
8463 				return (-1);
8464 			    /*
8465 			    * TODO: Should we try to find a matching ns-name
8466 			    * only once? This here keeps on searching.
8467 			    * I think we should try further since, there might
8468 			    * be an other matching ns-decl with an unshadowed
8469 			    * prefix.
8470 			    */
8471 			    if (! ret)
8472 				continue;
8473 			}
8474 			*retNs = ns;
8475 			return (1);
8476 		    }
8477 		}
8478 		out = prev;
8479 		prev = cur;
8480 	    }
8481 	} else if ((cur->type == XML_ENTITY_NODE) ||
8482             (cur->type == XML_ENTITY_DECL))
8483 	    return (0);
8484 	cur = cur->parent;
8485     } while ((cur != NULL) && (cur->doc != (xmlDocPtr) cur));
8486     return (0);
8487 }
8488 
8489 /*
8490 * xmlSearchNsByPrefixStrict:
8491 * @doc: the document
8492 * @node: the start node
8493 * @prefix: the searched namespace prefix
8494 * @retNs: the resulting ns-decl
8495 *
8496 * Dynamically searches for a ns-declaration which matches
8497 * the given @nsName in the ancestor-or-self axis of @node.
8498 *
8499 * Returns 1 if a ns-decl was found, 0 if not and -1 on API
8500 *         and internal errors.
8501 */
8502 static int
xmlSearchNsByPrefixStrict(xmlDocPtr doc,xmlNodePtr node,const xmlChar * prefix,xmlNsPtr * retNs)8503 xmlSearchNsByPrefixStrict(xmlDocPtr doc, xmlNodePtr node,
8504 			  const xmlChar* prefix,
8505 			  xmlNsPtr *retNs)
8506 {
8507     xmlNodePtr cur;
8508     xmlNsPtr ns;
8509 
8510     if ((doc == NULL) || (node == NULL) || (node->type == XML_NAMESPACE_DECL))
8511         return(-1);
8512 
8513     if (retNs)
8514 	*retNs = NULL;
8515     if (IS_STR_XML(prefix)) {
8516 	if (retNs) {
8517 	    *retNs = xmlTreeEnsureXMLDecl(doc);
8518 	    if (*retNs == NULL)
8519 		return (-1);
8520 	}
8521 	return (1);
8522     }
8523     cur = node;
8524     do {
8525 	if (cur->type == XML_ELEMENT_NODE) {
8526 	    if (cur->nsDef != NULL) {
8527 		ns = cur->nsDef;
8528 		do {
8529 		    if ((prefix == ns->prefix) ||
8530 			xmlStrEqual(prefix, ns->prefix))
8531 		    {
8532 			/*
8533 			* Disabled namespaces, e.g. xmlns:abc="".
8534 			*/
8535 			if (ns->href == NULL)
8536 			    return(0);
8537 			if (retNs)
8538 			    *retNs = ns;
8539 			return (1);
8540 		    }
8541 		    ns = ns->next;
8542 		} while (ns != NULL);
8543 	    }
8544 	} else if ((cur->type == XML_ENTITY_NODE) ||
8545             (cur->type == XML_ENTITY_DECL))
8546 	    return (0);
8547 	cur = cur->parent;
8548     } while ((cur != NULL) && (cur->doc != (xmlDocPtr) cur));
8549     return (0);
8550 }
8551 
8552 /*
8553 * xmlDOMWrapNSNormDeclareNsForced:
8554 * @doc: the doc
8555 * @elem: the element-node to declare on
8556 * @nsName: the namespace-name of the ns-decl
8557 * @prefix: the preferred prefix of the ns-decl
8558 * @checkShadow: ensure that the new ns-decl doesn't shadow ancestor ns-decls
8559 *
8560 * Declares a new namespace on @elem. It tries to use the
8561 * given @prefix; if a ns-decl with the given prefix is already existent
8562 * on @elem, it will generate an other prefix.
8563 *
8564 * Returns 1 if a ns-decl was found, 0 if not and -1 on API
8565 *         and internal errors.
8566 */
8567 static xmlNsPtr
xmlDOMWrapNSNormDeclareNsForced(xmlDocPtr doc,xmlNodePtr elem,const xmlChar * nsName,const xmlChar * prefix,int checkShadow)8568 xmlDOMWrapNSNormDeclareNsForced(xmlDocPtr doc,
8569 				xmlNodePtr elem,
8570 				const xmlChar *nsName,
8571 				const xmlChar *prefix,
8572 				int checkShadow)
8573 {
8574 
8575     xmlNsPtr ret;
8576     char buf[50];
8577     const xmlChar *pref;
8578     int counter = 0;
8579 
8580     if ((doc == NULL) || (elem == NULL) || (elem->type != XML_ELEMENT_NODE))
8581         return(NULL);
8582     /*
8583     * Create a ns-decl on @anchor.
8584     */
8585     pref = prefix;
8586     while (1) {
8587 	/*
8588 	* Lookup whether the prefix is unused in elem's ns-decls.
8589 	*/
8590 	if ((elem->nsDef != NULL) &&
8591 	    (xmlTreeNSListLookupByPrefix(elem->nsDef, pref) != NULL))
8592 	    goto ns_next_prefix;
8593 	if (checkShadow && elem->parent &&
8594 	    ((xmlNodePtr) elem->parent->doc != elem->parent)) {
8595 	    /*
8596 	    * Does it shadow ancestor ns-decls?
8597 	    */
8598 	    if (xmlSearchNsByPrefixStrict(doc, elem->parent, pref, NULL) == 1)
8599 		goto ns_next_prefix;
8600 	}
8601 	ret = xmlNewNs(NULL, nsName, pref);
8602 	if (ret == NULL)
8603 	    return (NULL);
8604 	if (elem->nsDef == NULL)
8605 	    elem->nsDef = ret;
8606 	else {
8607 	    xmlNsPtr ns2 = elem->nsDef;
8608 	    while (ns2->next != NULL)
8609 		ns2 = ns2->next;
8610 	    ns2->next = ret;
8611 	}
8612 	return (ret);
8613 ns_next_prefix:
8614 	counter++;
8615 	if (counter > 1000)
8616 	    return (NULL);
8617 	if (prefix == NULL) {
8618 	    snprintf((char *) buf, sizeof(buf),
8619 		"ns_%d", counter);
8620 	} else
8621 	    snprintf((char *) buf, sizeof(buf),
8622 	    "%.30s_%d", (char *)prefix, counter);
8623 	pref = BAD_CAST buf;
8624     }
8625 }
8626 
8627 /*
8628 * xmlDOMWrapNSNormAcquireNormalizedNs:
8629 * @doc: the doc
8630 * @elem: the element-node to declare namespaces on
8631 * @ns: the ns-struct to use for the search
8632 * @retNs: the found/created ns-struct
8633 * @nsMap: the ns-map
8634 * @depth: the current tree depth
8635 * @ancestorsOnly: search in ancestor ns-decls only
8636 * @prefixed: if the searched ns-decl must have a prefix (for attributes)
8637 *
8638 * Searches for a matching ns-name in the ns-decls of @nsMap, if not
8639 * found it will either declare it on @elem, or store it in doc->oldNs.
8640 * If a new ns-decl needs to be declared on @elem, it tries to use the
8641 * @ns->prefix for it, if this prefix is already in use on @elem, it will
8642 * change the prefix or the new ns-decl.
8643 *
8644 * Returns 0 if succeeded, -1 otherwise and on API/internal errors.
8645 */
8646 static int
xmlDOMWrapNSNormAcquireNormalizedNs(xmlDocPtr doc,xmlNodePtr elem,xmlNsPtr ns,xmlNsPtr * retNs,xmlNsMapPtr * nsMap,int depth,int ancestorsOnly,int prefixed)8647 xmlDOMWrapNSNormAcquireNormalizedNs(xmlDocPtr doc,
8648 				   xmlNodePtr elem,
8649 				   xmlNsPtr ns,
8650 				   xmlNsPtr *retNs,
8651 				   xmlNsMapPtr *nsMap,
8652 
8653 				   int depth,
8654 				   int ancestorsOnly,
8655 				   int prefixed)
8656 {
8657     xmlNsMapItemPtr mi;
8658 
8659     if ((doc == NULL) || (ns == NULL) || (retNs == NULL) ||
8660 	(nsMap == NULL))
8661 	return (-1);
8662 
8663     *retNs = NULL;
8664     /*
8665     * Handle XML namespace.
8666     */
8667     if (IS_STR_XML(ns->prefix)) {
8668 	/*
8669 	* Insert XML namespace mapping.
8670 	*/
8671 	*retNs = xmlTreeEnsureXMLDecl(doc);
8672 	if (*retNs == NULL)
8673 	    return (-1);
8674 	return (0);
8675     }
8676     /*
8677     * If the search should be done in ancestors only and no
8678     * @elem (the first ancestor) was specified, then skip the search.
8679     */
8680     if ((XML_NSMAP_NOTEMPTY(*nsMap)) &&
8681 	(! (ancestorsOnly && (elem == NULL))))
8682     {
8683 	/*
8684 	* Try to find an equal ns-name in in-scope ns-decls.
8685 	*/
8686 	XML_NSMAP_FOREACH(*nsMap, mi) {
8687 	    if ((mi->depth >= XML_TREE_NSMAP_PARENT) &&
8688 		/*
8689 		* ancestorsOnly: This should be turned on to gain speed,
8690 		* if one knows that the branch itself was already
8691 		* ns-wellformed and no stale references existed.
8692 		* I.e. it searches in the ancestor axis only.
8693 		*/
8694 		((! ancestorsOnly) || (mi->depth == XML_TREE_NSMAP_PARENT)) &&
8695 		/* Skip shadowed prefixes. */
8696 		(mi->shadowDepth == -1) &&
8697 		/* Skip xmlns="" or xmlns:foo="". */
8698 		((mi->newNs->href != NULL) &&
8699 		(mi->newNs->href[0] != 0)) &&
8700 		/* Ensure a prefix if wanted. */
8701 		((! prefixed) || (mi->newNs->prefix != NULL)) &&
8702 		/* Equal ns name */
8703 		((mi->newNs->href == ns->href) ||
8704 		xmlStrEqual(mi->newNs->href, ns->href))) {
8705 		/* Set the mapping. */
8706 		mi->oldNs = ns;
8707 		*retNs = mi->newNs;
8708 		return (0);
8709 	    }
8710 	}
8711     }
8712     /*
8713     * No luck, the namespace is out of scope or shadowed.
8714     */
8715     if (elem == NULL) {
8716 	xmlNsPtr tmpns;
8717 
8718 	/*
8719 	* Store ns-decls in "oldNs" of the document-node.
8720 	*/
8721 	tmpns = xmlDOMWrapStoreNs(doc, ns->href, ns->prefix);
8722 	if (tmpns == NULL)
8723 	    return (-1);
8724 	/*
8725 	* Insert mapping.
8726 	*/
8727 	if (xmlDOMWrapNsMapAddItem(nsMap, -1, ns,
8728 		tmpns, XML_TREE_NSMAP_DOC) == NULL) {
8729 	    xmlFreeNs(tmpns);
8730 	    return (-1);
8731 	}
8732 	*retNs = tmpns;
8733     } else {
8734 	xmlNsPtr tmpns;
8735 
8736 	tmpns = xmlDOMWrapNSNormDeclareNsForced(doc, elem, ns->href,
8737 	    ns->prefix, 0);
8738 	if (tmpns == NULL)
8739 	    return (-1);
8740 
8741 	if (*nsMap != NULL) {
8742 	    /*
8743 	    * Does it shadow ancestor ns-decls?
8744 	    */
8745 	    XML_NSMAP_FOREACH(*nsMap, mi) {
8746 		if ((mi->depth < depth) &&
8747 		    (mi->shadowDepth == -1) &&
8748 		    ((ns->prefix == mi->newNs->prefix) ||
8749 		    xmlStrEqual(ns->prefix, mi->newNs->prefix))) {
8750 		    /*
8751 		    * Shadows.
8752 		    */
8753 		    mi->shadowDepth = depth;
8754 		    break;
8755 		}
8756 	    }
8757 	}
8758 	if (xmlDOMWrapNsMapAddItem(nsMap, -1, ns, tmpns, depth) == NULL) {
8759 	    xmlFreeNs(tmpns);
8760 	    return (-1);
8761 	}
8762 	*retNs = tmpns;
8763     }
8764     return (0);
8765 }
8766 
8767 typedef enum {
8768     XML_DOM_RECONNS_REMOVEREDUND = 1<<0
8769 } xmlDOMReconcileNSOptions;
8770 
8771 /*
8772 * xmlDOMWrapReconcileNamespaces:
8773 * @ctxt: DOM wrapper context, unused at the moment
8774 * @elem: the element-node
8775 * @options: option flags
8776 *
8777 * Ensures that ns-references point to ns-decls hold on element-nodes.
8778 * Ensures that the tree is namespace wellformed by creating additional
8779 * ns-decls where needed. Note that, since prefixes of already existent
8780 * ns-decls can be shadowed by this process, it could break QNames in
8781 * attribute values or element content.
8782 *
8783 * NOTE: This function was not intensively tested.
8784 *
8785 * Returns 0 if succeeded, -1 otherwise and on API/internal errors.
8786 */
8787 
8788 int
xmlDOMWrapReconcileNamespaces(xmlDOMWrapCtxtPtr ctxt ATTRIBUTE_UNUSED,xmlNodePtr elem,int options)8789 xmlDOMWrapReconcileNamespaces(xmlDOMWrapCtxtPtr ctxt ATTRIBUTE_UNUSED,
8790 			      xmlNodePtr elem,
8791 			      int options)
8792 {
8793     int depth = -1, adoptns = 0, parnsdone = 0;
8794     xmlNsPtr ns, prevns;
8795     xmlDocPtr doc;
8796     xmlNodePtr cur, curElem = NULL;
8797     xmlNsMapPtr nsMap = NULL;
8798     xmlNsMapItemPtr /* topmi = NULL, */ mi;
8799     /* @ancestorsOnly should be set by an option flag. */
8800     int ancestorsOnly = 0;
8801     int optRemoveRedundantNS =
8802 	((xmlDOMReconcileNSOptions) options & XML_DOM_RECONNS_REMOVEREDUND) ? 1 : 0;
8803     xmlNsPtr *listRedund = NULL;
8804     int sizeRedund = 0, nbRedund = 0, ret, i, j;
8805 
8806     if ((elem == NULL) || (elem->doc == NULL) ||
8807 	(elem->type != XML_ELEMENT_NODE))
8808 	return (-1);
8809 
8810     doc = elem->doc;
8811     cur = elem;
8812     do {
8813 	switch (cur->type) {
8814 	    case XML_ELEMENT_NODE:
8815 		adoptns = 1;
8816 		curElem = cur;
8817 		depth++;
8818 		/*
8819 		* Namespace declarations.
8820 		*/
8821 		if (cur->nsDef != NULL) {
8822 		    prevns = NULL;
8823 		    ns = cur->nsDef;
8824 		    while (ns != NULL) {
8825 			if (! parnsdone) {
8826 			    if ((elem->parent) &&
8827 				((xmlNodePtr) elem->parent->doc != elem->parent)) {
8828 				/*
8829 				* Gather ancestor in-scope ns-decls.
8830 				*/
8831 				if (xmlDOMWrapNSNormGatherInScopeNs(&nsMap,
8832 				    elem->parent) == -1)
8833 				    goto internal_error;
8834 			    }
8835 			    parnsdone = 1;
8836 			}
8837 
8838 			/*
8839 			* Lookup the ns ancestor-axis for equal ns-decls in scope.
8840 			*/
8841 			if (optRemoveRedundantNS && XML_NSMAP_NOTEMPTY(nsMap)) {
8842 			    XML_NSMAP_FOREACH(nsMap, mi) {
8843 				if ((mi->depth >= XML_TREE_NSMAP_PARENT) &&
8844 				    (mi->shadowDepth == -1) &&
8845 				    ((ns->prefix == mi->newNs->prefix) ||
8846 				      xmlStrEqual(ns->prefix, mi->newNs->prefix)) &&
8847 				    ((ns->href == mi->newNs->href) ||
8848 				      xmlStrEqual(ns->href, mi->newNs->href)))
8849 				{
8850 				    /*
8851 				    * A redundant ns-decl was found.
8852 				    * Add it to the list of redundant ns-decls.
8853 				    */
8854 				    if (xmlDOMWrapNSNormAddNsMapItem2(&listRedund,
8855 					&sizeRedund, &nbRedund, ns, mi->newNs) == -1)
8856 					goto internal_error;
8857 				    /*
8858 				    * Remove the ns-decl from the element-node.
8859 				    */
8860 				    if (prevns)
8861 					prevns->next = ns->next;
8862 				    else
8863 					cur->nsDef = ns->next;
8864 				    goto next_ns_decl;
8865 				}
8866 			    }
8867 			}
8868 
8869 			/*
8870 			* Skip ns-references handling if the referenced
8871 			* ns-decl is declared on the same element.
8872 			*/
8873 			if ((cur->ns != NULL) && adoptns && (cur->ns == ns))
8874 			    adoptns = 0;
8875 			/*
8876 			* Does it shadow any ns-decl?
8877 			*/
8878 			if (XML_NSMAP_NOTEMPTY(nsMap)) {
8879 			    XML_NSMAP_FOREACH(nsMap, mi) {
8880 				if ((mi->depth >= XML_TREE_NSMAP_PARENT) &&
8881 				    (mi->shadowDepth == -1) &&
8882 				    ((ns->prefix == mi->newNs->prefix) ||
8883 				    xmlStrEqual(ns->prefix, mi->newNs->prefix))) {
8884 
8885 				    mi->shadowDepth = depth;
8886 				}
8887 			    }
8888 			}
8889 			/*
8890 			* Push mapping.
8891 			*/
8892 			if (xmlDOMWrapNsMapAddItem(&nsMap, -1, ns, ns,
8893 			    depth) == NULL)
8894 			    goto internal_error;
8895 
8896 			prevns = ns;
8897 next_ns_decl:
8898 			ns = ns->next;
8899 		    }
8900 		}
8901 		if (! adoptns)
8902 		    goto ns_end;
8903                 /* Falls through. */
8904 	    case XML_ATTRIBUTE_NODE:
8905 		/* No ns, no fun. */
8906 		if (cur->ns == NULL)
8907 		    goto ns_end;
8908 
8909 		if (! parnsdone) {
8910 		    if ((elem->parent) &&
8911 			((xmlNodePtr) elem->parent->doc != elem->parent)) {
8912 			if (xmlDOMWrapNSNormGatherInScopeNs(&nsMap,
8913 				elem->parent) == -1)
8914 			    goto internal_error;
8915 		    }
8916 		    parnsdone = 1;
8917 		}
8918 		/*
8919 		* Adjust the reference if this was a redundant ns-decl.
8920 		*/
8921 		if (listRedund) {
8922 		   for (i = 0, j = 0; i < nbRedund; i++, j += 2) {
8923 		       if (cur->ns == listRedund[j]) {
8924 			   cur->ns = listRedund[++j];
8925 			   break;
8926 		       }
8927 		   }
8928 		}
8929 		/*
8930 		* Adopt ns-references.
8931 		*/
8932 		if (XML_NSMAP_NOTEMPTY(nsMap)) {
8933 		    /*
8934 		    * Search for a mapping.
8935 		    */
8936 		    XML_NSMAP_FOREACH(nsMap, mi) {
8937 			if ((mi->shadowDepth == -1) &&
8938 			    (cur->ns == mi->oldNs)) {
8939 
8940 			    cur->ns = mi->newNs;
8941 			    goto ns_end;
8942 			}
8943 		    }
8944 		}
8945 		/*
8946 		* Acquire a normalized ns-decl and add it to the map.
8947 		*/
8948 		if (xmlDOMWrapNSNormAcquireNormalizedNs(doc, curElem,
8949 			cur->ns, &ns,
8950 			&nsMap, depth,
8951 			ancestorsOnly,
8952 			(cur->type == XML_ATTRIBUTE_NODE) ? 1 : 0) == -1)
8953 		    goto internal_error;
8954 		cur->ns = ns;
8955 
8956 ns_end:
8957 		if ((cur->type == XML_ELEMENT_NODE) &&
8958 		    (cur->properties != NULL)) {
8959 		    /*
8960 		    * Process attributes.
8961 		    */
8962 		    cur = (xmlNodePtr) cur->properties;
8963 		    continue;
8964 		}
8965 		break;
8966 	    default:
8967 		goto next_sibling;
8968 	}
8969 into_content:
8970 	if ((cur->type == XML_ELEMENT_NODE) &&
8971 	    (cur->children != NULL)) {
8972 	    /*
8973 	    * Process content of element-nodes only.
8974 	    */
8975 	    cur = cur->children;
8976 	    continue;
8977 	}
8978 next_sibling:
8979 	if (cur == elem)
8980 	    break;
8981 	if (cur->type == XML_ELEMENT_NODE) {
8982 	    if (XML_NSMAP_NOTEMPTY(nsMap)) {
8983 		/*
8984 		* Pop mappings.
8985 		*/
8986 		while ((nsMap->last != NULL) &&
8987 		    (nsMap->last->depth >= depth))
8988 		{
8989 		    XML_NSMAP_POP(nsMap, mi)
8990 		}
8991 		/*
8992 		* Unshadow.
8993 		*/
8994 		XML_NSMAP_FOREACH(nsMap, mi) {
8995 		    if (mi->shadowDepth >= depth)
8996 			mi->shadowDepth = -1;
8997 		}
8998 	    }
8999 	    depth--;
9000 	}
9001 	if (cur->next != NULL)
9002 	    cur = cur->next;
9003 	else {
9004 	    if (cur->type == XML_ATTRIBUTE_NODE) {
9005 		cur = cur->parent;
9006 		goto into_content;
9007 	    }
9008 	    cur = cur->parent;
9009 	    goto next_sibling;
9010 	}
9011     } while (cur != NULL);
9012 
9013     ret = 0;
9014     goto exit;
9015 internal_error:
9016     ret = -1;
9017 exit:
9018     if (listRedund) {
9019 	for (i = 0, j = 0; i < nbRedund; i++, j += 2) {
9020 	    xmlFreeNs(listRedund[j]);
9021 	}
9022 	xmlFree(listRedund);
9023     }
9024     if (nsMap != NULL)
9025 	xmlDOMWrapNsMapFree(nsMap);
9026     return (ret);
9027 }
9028 
9029 /*
9030 * xmlDOMWrapAdoptBranch:
9031 * @ctxt: the optional context for custom processing
9032 * @sourceDoc: the optional sourceDoc
9033 * @node: the element-node to start with
9034 * @destDoc: the destination doc for adoption
9035 * @destParent: the optional new parent of @node in @destDoc
9036 * @options: option flags
9037 *
9038 * Ensures that ns-references point to @destDoc: either to
9039 * elements->nsDef entries if @destParent is given, or to
9040 * @destDoc->oldNs otherwise.
9041 * If @destParent is given, it ensures that the tree is namespace
9042 * wellformed by creating additional ns-decls where needed.
9043 * Note that, since prefixes of already existent ns-decls can be
9044 * shadowed by this process, it could break QNames in attribute
9045 * values or element content.
9046 *
9047 * NOTE: This function was not intensively tested.
9048 *
9049 * Returns 0 if succeeded, -1 otherwise and on API/internal errors.
9050 */
9051 static int
xmlDOMWrapAdoptBranch(xmlDOMWrapCtxtPtr ctxt,xmlDocPtr sourceDoc,xmlNodePtr node,xmlDocPtr destDoc,xmlNodePtr destParent,int options ATTRIBUTE_UNUSED)9052 xmlDOMWrapAdoptBranch(xmlDOMWrapCtxtPtr ctxt,
9053 		      xmlDocPtr sourceDoc,
9054 		      xmlNodePtr node,
9055 		      xmlDocPtr destDoc,
9056 		      xmlNodePtr destParent,
9057 		      int options ATTRIBUTE_UNUSED)
9058 {
9059     int ret = 0;
9060     xmlNodePtr cur, curElem = NULL;
9061     xmlNsMapPtr nsMap = NULL;
9062     xmlNsMapItemPtr mi;
9063     xmlNsPtr ns = NULL;
9064     int depth = -1, adoptStr = 1;
9065     /* gather @parent's ns-decls. */
9066     int parnsdone;
9067     /* @ancestorsOnly should be set per option. */
9068     int ancestorsOnly = 0;
9069 
9070     /*
9071     * Optimize string adoption for equal or none dicts.
9072     */
9073     if ((sourceDoc != NULL) &&
9074 	(sourceDoc->dict == destDoc->dict))
9075 	adoptStr = 0;
9076     else
9077 	adoptStr = 1;
9078 
9079     /*
9080     * Get the ns-map from the context if available.
9081     */
9082     if (ctxt)
9083 	nsMap = (xmlNsMapPtr) ctxt->namespaceMap;
9084     /*
9085     * Disable search for ns-decls in the parent-axis of the
9086     * destination element, if:
9087     * 1) there's no destination parent
9088     * 2) custom ns-reference handling is used
9089     */
9090     if ((destParent == NULL) ||
9091 	(ctxt && ctxt->getNsForNodeFunc))
9092     {
9093 	parnsdone = 1;
9094     } else
9095 	parnsdone = 0;
9096 
9097     cur = node;
9098     if ((cur != NULL) && (cur->type == XML_NAMESPACE_DECL))
9099 	goto internal_error;
9100 
9101     while (cur != NULL) {
9102 	/*
9103 	* Paranoid source-doc sanity check.
9104 	*/
9105 	if (cur->doc != sourceDoc) {
9106 	    /*
9107 	    * We'll assume XIncluded nodes if the doc differs.
9108 	    * TODO: Do we need to reconciliate XIncluded nodes?
9109 	    * This here skips XIncluded nodes and tries to handle
9110 	    * broken sequences.
9111 	    */
9112 	    if (cur->next == NULL)
9113 		goto leave_node;
9114 	    do {
9115 		cur = cur->next;
9116 		if ((cur->type == XML_XINCLUDE_END) ||
9117 		    (cur->doc == node->doc))
9118 		    break;
9119 	    } while (cur->next != NULL);
9120 
9121 	    if (cur->doc != node->doc)
9122 		goto leave_node;
9123 	}
9124 	cur->doc = destDoc;
9125 	switch (cur->type) {
9126 	    case XML_XINCLUDE_START:
9127 	    case XML_XINCLUDE_END:
9128 		/*
9129 		* TODO
9130 		*/
9131 		return (-1);
9132 	    case XML_ELEMENT_NODE:
9133 		curElem = cur;
9134 		depth++;
9135 		/*
9136 		* Namespace declarations.
9137 		* - ns->href and ns->prefix are never in the dict, so
9138 		*   we need not move the values over to the destination dict.
9139 		* - Note that for custom handling of ns-references,
9140 		*   the ns-decls need not be stored in the ns-map,
9141 		*   since they won't be referenced by node->ns.
9142 		*/
9143 		if ((cur->nsDef) &&
9144 		    ((ctxt == NULL) || (ctxt->getNsForNodeFunc == NULL)))
9145 		{
9146 		    if (! parnsdone) {
9147 			/*
9148 			* Gather @parent's in-scope ns-decls.
9149 			*/
9150 			if (xmlDOMWrapNSNormGatherInScopeNs(&nsMap,
9151 			    destParent) == -1)
9152 			    goto internal_error;
9153 			parnsdone = 1;
9154 		    }
9155 		    for (ns = cur->nsDef; ns != NULL; ns = ns->next) {
9156 			/*
9157 			* NOTE: ns->prefix and ns->href are never in the dict.
9158 			* XML_TREE_ADOPT_STR(ns->prefix)
9159 			* XML_TREE_ADOPT_STR(ns->href)
9160 			*/
9161 			/*
9162 			* Does it shadow any ns-decl?
9163 			*/
9164 			if (XML_NSMAP_NOTEMPTY(nsMap)) {
9165 			    XML_NSMAP_FOREACH(nsMap, mi) {
9166 				if ((mi->depth >= XML_TREE_NSMAP_PARENT) &&
9167 				    (mi->shadowDepth == -1) &&
9168 				    ((ns->prefix == mi->newNs->prefix) ||
9169 				    xmlStrEqual(ns->prefix,
9170 				    mi->newNs->prefix))) {
9171 
9172 				    mi->shadowDepth = depth;
9173 				}
9174 			    }
9175 			}
9176 			/*
9177 			* Push mapping.
9178 			*/
9179 			if (xmlDOMWrapNsMapAddItem(&nsMap, -1,
9180 			    ns, ns, depth) == NULL)
9181 			    goto internal_error;
9182 		    }
9183 		}
9184                 /* Falls through. */
9185 	    case XML_ATTRIBUTE_NODE:
9186 		/* No namespace, no fun. */
9187 		if (cur->ns == NULL)
9188 		    goto ns_end;
9189 
9190 		if (! parnsdone) {
9191 		    if (xmlDOMWrapNSNormGatherInScopeNs(&nsMap,
9192 			destParent) == -1)
9193 			goto internal_error;
9194 		    parnsdone = 1;
9195 		}
9196 		/*
9197 		* Adopt ns-references.
9198 		*/
9199 		if (XML_NSMAP_NOTEMPTY(nsMap)) {
9200 		    /*
9201 		    * Search for a mapping.
9202 		    */
9203 		    XML_NSMAP_FOREACH(nsMap, mi) {
9204 			if ((mi->shadowDepth == -1) &&
9205 			    (cur->ns == mi->oldNs)) {
9206 
9207 			    cur->ns = mi->newNs;
9208 			    goto ns_end;
9209 			}
9210 		    }
9211 		}
9212 		/*
9213 		* No matching namespace in scope. We need a new one.
9214 		*/
9215 		if ((ctxt) && (ctxt->getNsForNodeFunc)) {
9216 		    /*
9217 		    * User-defined behaviour.
9218 		    */
9219 		    ns = ctxt->getNsForNodeFunc(ctxt, cur,
9220 			cur->ns->href, cur->ns->prefix);
9221 		    /*
9222 		    * Insert mapping if ns is available; it's the users fault
9223 		    * if not.
9224 		    */
9225 		    if (xmlDOMWrapNsMapAddItem(&nsMap, -1,
9226 			    cur->ns, ns, XML_TREE_NSMAP_CUSTOM) == NULL)
9227 			goto internal_error;
9228 		    cur->ns = ns;
9229 		} else {
9230 		    /*
9231 		    * Acquire a normalized ns-decl and add it to the map.
9232 		    */
9233 		    if (xmlDOMWrapNSNormAcquireNormalizedNs(destDoc,
9234 			/* ns-decls on curElem or on destDoc->oldNs */
9235 			destParent ? curElem : NULL,
9236 			cur->ns, &ns,
9237 			&nsMap, depth,
9238 			ancestorsOnly,
9239 			/* ns-decls must be prefixed for attributes. */
9240 			(cur->type == XML_ATTRIBUTE_NODE) ? 1 : 0) == -1)
9241 			goto internal_error;
9242 		    cur->ns = ns;
9243 		}
9244 ns_end:
9245 		/*
9246 		* Further node properties.
9247 		* TODO: Is this all?
9248 		*/
9249 		XML_TREE_ADOPT_STR(cur->name)
9250 		if (cur->type == XML_ELEMENT_NODE) {
9251 		    cur->psvi = NULL;
9252 		    cur->line = 0;
9253 		    cur->extra = 0;
9254 		    /*
9255 		    * Walk attributes.
9256 		    */
9257 		    if (cur->properties != NULL) {
9258 			/*
9259 			* Process first attribute node.
9260 			*/
9261 			cur = (xmlNodePtr) cur->properties;
9262 			continue;
9263 		    }
9264 		} else {
9265 		    /*
9266 		    * Attributes.
9267 		    */
9268 		    if ((sourceDoc != NULL) &&
9269 			(((xmlAttrPtr) cur)->atype == XML_ATTRIBUTE_ID))
9270 		    {
9271 			xmlRemoveID(sourceDoc, (xmlAttrPtr) cur);
9272 		    }
9273 		    ((xmlAttrPtr) cur)->atype = 0;
9274 		    ((xmlAttrPtr) cur)->psvi = NULL;
9275 		}
9276 		break;
9277 	    case XML_TEXT_NODE:
9278 	    case XML_CDATA_SECTION_NODE:
9279 		/*
9280 		* This puts the content in the dest dict, only if
9281 		* it was previously in the source dict.
9282 		*/
9283 		XML_TREE_ADOPT_STR_2(cur->content)
9284 		goto leave_node;
9285 	    case XML_ENTITY_REF_NODE:
9286 		/*
9287 		* Remove reference to the entity-node.
9288 		*/
9289 		cur->content = NULL;
9290 		cur->children = NULL;
9291 		cur->last = NULL;
9292 		if ((destDoc->intSubset) || (destDoc->extSubset)) {
9293 		    xmlEntityPtr ent;
9294 		    /*
9295 		    * Assign new entity-node if available.
9296 		    */
9297 		    ent = xmlGetDocEntity(destDoc, cur->name);
9298 		    if (ent != NULL) {
9299 			cur->content = ent->content;
9300 			cur->children = (xmlNodePtr) ent;
9301 			cur->last = (xmlNodePtr) ent;
9302 		    }
9303 		}
9304 		goto leave_node;
9305 	    case XML_PI_NODE:
9306 		XML_TREE_ADOPT_STR(cur->name)
9307 		XML_TREE_ADOPT_STR_2(cur->content)
9308 		break;
9309 	    case XML_COMMENT_NODE:
9310 		break;
9311 	    default:
9312 		goto internal_error;
9313 	}
9314 	/*
9315 	* Walk the tree.
9316 	*/
9317 	if (cur->children != NULL) {
9318 	    cur = cur->children;
9319 	    continue;
9320 	}
9321 
9322 leave_node:
9323 	if (cur == node)
9324 	    break;
9325 	if ((cur->type == XML_ELEMENT_NODE) ||
9326 	    (cur->type == XML_XINCLUDE_START) ||
9327 	    (cur->type == XML_XINCLUDE_END))
9328 	{
9329 	    /*
9330 	    * TODO: Do we expect nsDefs on XML_XINCLUDE_START?
9331 	    */
9332 	    if (XML_NSMAP_NOTEMPTY(nsMap)) {
9333 		/*
9334 		* Pop mappings.
9335 		*/
9336 		while ((nsMap->last != NULL) &&
9337 		    (nsMap->last->depth >= depth))
9338 		{
9339 		    XML_NSMAP_POP(nsMap, mi)
9340 		}
9341 		/*
9342 		* Unshadow.
9343 		*/
9344 		XML_NSMAP_FOREACH(nsMap, mi) {
9345 		    if (mi->shadowDepth >= depth)
9346 			mi->shadowDepth = -1;
9347 		}
9348 	    }
9349 	    depth--;
9350 	}
9351 	if (cur->next != NULL)
9352 	    cur = cur->next;
9353 	else if ((cur->type == XML_ATTRIBUTE_NODE) &&
9354 	    (cur->parent->children != NULL))
9355 	{
9356 	    cur = cur->parent->children;
9357 	} else {
9358 	    cur = cur->parent;
9359 	    goto leave_node;
9360 	}
9361     }
9362 
9363     goto exit;
9364 
9365 internal_error:
9366     ret = -1;
9367 
9368 exit:
9369     /*
9370     * Cleanup.
9371     */
9372     if (nsMap != NULL) {
9373 	if ((ctxt) && (ctxt->namespaceMap == nsMap)) {
9374 	    /*
9375 	    * Just cleanup the map but don't free.
9376 	    */
9377 	    if (nsMap->first) {
9378 		if (nsMap->pool)
9379 		    nsMap->last->next = nsMap->pool;
9380 		nsMap->pool = nsMap->first;
9381 		nsMap->first = NULL;
9382 	    }
9383 	} else
9384 	    xmlDOMWrapNsMapFree(nsMap);
9385     }
9386     return(ret);
9387 }
9388 
9389 /*
9390 * xmlDOMWrapCloneNode:
9391 * @ctxt: the optional context for custom processing
9392 * @sourceDoc: the optional sourceDoc
9393 * @node: the node to start with
9394 * @resNode: the clone of the given @node
9395 * @destDoc: the destination doc
9396 * @destParent: the optional new parent of @node in @destDoc
9397 * @deep: descend into child if set
9398 * @options: option flags
9399 *
9400 * References of out-of scope ns-decls are remapped to point to @destDoc:
9401 * 1) If @destParent is given, then nsDef entries on element-nodes are used
9402 * 2) If *no* @destParent is given, then @destDoc->oldNs entries are used.
9403 *    This is the case when you don't know already where the cloned branch
9404 *    will be added to.
9405 *
9406 * If @destParent is given, it ensures that the tree is namespace
9407 * wellformed by creating additional ns-decls where needed.
9408 * Note that, since prefixes of already existent ns-decls can be
9409 * shadowed by this process, it could break QNames in attribute
9410 * values or element content.
9411 * TODO:
9412 *   1) What to do with XInclude? Currently this returns an error for XInclude.
9413 *
9414 * Returns 0 if the operation succeeded,
9415 *         1 if a node of unsupported (or not yet supported) type was given,
9416 *         -1 on API/internal errors.
9417 */
9418 
9419 int
xmlDOMWrapCloneNode(xmlDOMWrapCtxtPtr ctxt,xmlDocPtr sourceDoc,xmlNodePtr node,xmlNodePtr * resNode,xmlDocPtr destDoc,xmlNodePtr destParent,int deep,int options ATTRIBUTE_UNUSED)9420 xmlDOMWrapCloneNode(xmlDOMWrapCtxtPtr ctxt,
9421 		      xmlDocPtr sourceDoc,
9422 		      xmlNodePtr node,
9423 		      xmlNodePtr *resNode,
9424 		      xmlDocPtr destDoc,
9425 		      xmlNodePtr destParent,
9426 		      int deep,
9427 		      int options ATTRIBUTE_UNUSED)
9428 {
9429     int ret = 0;
9430     xmlNodePtr cur, curElem = NULL;
9431     xmlNsMapPtr nsMap = NULL;
9432     xmlNsMapItemPtr mi;
9433     xmlNsPtr ns;
9434     int depth = -1;
9435     /* int adoptStr = 1; */
9436     /* gather @parent's ns-decls. */
9437     int parnsdone = 0;
9438     /*
9439     * @ancestorsOnly:
9440     * TODO: @ancestorsOnly should be set per option.
9441     *
9442     */
9443     int ancestorsOnly = 0;
9444     xmlNodePtr resultClone = NULL, clone = NULL, parentClone = NULL, prevClone = NULL;
9445     xmlNsPtr cloneNs = NULL, *cloneNsDefSlot = NULL;
9446     xmlDictPtr dict; /* The destination dict */
9447 
9448     if ((node == NULL) || (resNode == NULL) || (destDoc == NULL))
9449 	return(-1);
9450     /*
9451     * TODO: Initially we support only element-nodes.
9452     */
9453     if (node->type != XML_ELEMENT_NODE)
9454 	return(1);
9455     /*
9456     * Check node->doc sanity.
9457     */
9458     if ((node->doc != NULL) && (sourceDoc != NULL) &&
9459 	(node->doc != sourceDoc)) {
9460 	/*
9461 	* Might be an XIncluded node.
9462 	*/
9463 	return (-1);
9464     }
9465     if (sourceDoc == NULL)
9466 	sourceDoc = node->doc;
9467     if (sourceDoc == NULL)
9468         return (-1);
9469 
9470     dict = destDoc->dict;
9471     /*
9472     * Reuse the namespace map of the context.
9473     */
9474     if (ctxt)
9475 	nsMap = (xmlNsMapPtr) ctxt->namespaceMap;
9476 
9477     *resNode = NULL;
9478 
9479     cur = node;
9480     if ((cur != NULL) && (cur->type == XML_NAMESPACE_DECL))
9481         return(-1);
9482 
9483     while (cur != NULL) {
9484 	if (cur->doc != sourceDoc) {
9485 	    /*
9486 	    * We'll assume XIncluded nodes if the doc differs.
9487 	    * TODO: Do we need to reconciliate XIncluded nodes?
9488 	    * TODO: This here returns -1 in this case.
9489 	    */
9490 	    goto internal_error;
9491 	}
9492 	/*
9493 	* Create a new node.
9494 	*/
9495 	switch (cur->type) {
9496 	    case XML_XINCLUDE_START:
9497 	    case XML_XINCLUDE_END:
9498 		/*
9499 		* TODO: What to do with XInclude?
9500 		*/
9501 		goto internal_error;
9502 		break;
9503 	    case XML_ELEMENT_NODE:
9504 	    case XML_TEXT_NODE:
9505 	    case XML_CDATA_SECTION_NODE:
9506 	    case XML_COMMENT_NODE:
9507 	    case XML_PI_NODE:
9508 	    case XML_DOCUMENT_FRAG_NODE:
9509 	    case XML_ENTITY_REF_NODE:
9510 	    case XML_ENTITY_NODE:
9511 		/*
9512 		* Nodes of xmlNode structure.
9513 		*/
9514 		clone = (xmlNodePtr) xmlMalloc(sizeof(xmlNode));
9515 		if (clone == NULL) {
9516 		    xmlTreeErrMemory("xmlDOMWrapCloneNode(): allocating a node");
9517 		    goto internal_error;
9518 		}
9519 		memset(clone, 0, sizeof(xmlNode));
9520 		/*
9521 		* Set hierarchical links.
9522 		*/
9523 		if (resultClone != NULL) {
9524 		    clone->parent = parentClone;
9525 		    if (prevClone) {
9526 			prevClone->next = clone;
9527 			clone->prev = prevClone;
9528 		    } else
9529 			parentClone->children = clone;
9530 		} else
9531 		    resultClone = clone;
9532 
9533 		break;
9534 	    case XML_ATTRIBUTE_NODE:
9535 		/*
9536 		* Attributes (xmlAttr).
9537 		*/
9538 		clone = (xmlNodePtr) xmlMalloc(sizeof(xmlAttr));
9539 		if (clone == NULL) {
9540 		    xmlTreeErrMemory("xmlDOMWrapCloneNode(): allocating an attr-node");
9541 		    goto internal_error;
9542 		}
9543 		memset(clone, 0, sizeof(xmlAttr));
9544 		/*
9545 		* Set hierarchical links.
9546 		* TODO: Change this to add to the end of attributes.
9547 		*/
9548 		if (resultClone != NULL) {
9549 		    clone->parent = parentClone;
9550 		    if (prevClone) {
9551 			prevClone->next = clone;
9552 			clone->prev = prevClone;
9553 		    } else
9554 			parentClone->properties = (xmlAttrPtr) clone;
9555 		} else
9556 		    resultClone = clone;
9557 		break;
9558 	    default:
9559 		/*
9560 		* TODO QUESTION: Any other nodes expected?
9561 		*/
9562 		goto internal_error;
9563 	}
9564 
9565 	clone->type = cur->type;
9566 	clone->doc = destDoc;
9567 
9568 	/*
9569 	* Clone the name of the node if any.
9570 	*/
9571 	if (cur->name == xmlStringText)
9572 	    clone->name = xmlStringText;
9573 	else if (cur->name == xmlStringTextNoenc)
9574 	    /*
9575 	    * NOTE: Although xmlStringTextNoenc is never assigned to a node
9576 	    *   in tree.c, it might be set in Libxslt via
9577 	    *   "xsl:disable-output-escaping".
9578 	    */
9579 	    clone->name = xmlStringTextNoenc;
9580 	else if (cur->name == xmlStringComment)
9581 	    clone->name = xmlStringComment;
9582 	else if (cur->name != NULL) {
9583 	    DICT_CONST_COPY(cur->name, clone->name);
9584 	}
9585 
9586 	switch (cur->type) {
9587 	    case XML_XINCLUDE_START:
9588 	    case XML_XINCLUDE_END:
9589 		/*
9590 		* TODO
9591 		*/
9592 		return (-1);
9593 	    case XML_ELEMENT_NODE:
9594 		curElem = cur;
9595 		depth++;
9596 		/*
9597 		* Namespace declarations.
9598 		*/
9599 		if (cur->nsDef != NULL) {
9600 		    if (! parnsdone) {
9601 			if (destParent && (ctxt == NULL)) {
9602 			    /*
9603 			    * Gather @parent's in-scope ns-decls.
9604 			    */
9605 			    if (xmlDOMWrapNSNormGatherInScopeNs(&nsMap,
9606 				destParent) == -1)
9607 				goto internal_error;
9608 			}
9609 			parnsdone = 1;
9610 		    }
9611 		    /*
9612 		    * Clone namespace declarations.
9613 		    */
9614 		    cloneNsDefSlot = &(clone->nsDef);
9615 		    for (ns = cur->nsDef; ns != NULL; ns = ns->next) {
9616 			/*
9617 			* Create a new xmlNs.
9618 			*/
9619 			cloneNs = (xmlNsPtr) xmlMalloc(sizeof(xmlNs));
9620 			if (cloneNs == NULL) {
9621 			    xmlTreeErrMemory("xmlDOMWrapCloneNode(): "
9622 				"allocating namespace");
9623 			    return(-1);
9624 			}
9625 			memset(cloneNs, 0, sizeof(xmlNs));
9626 			cloneNs->type = XML_LOCAL_NAMESPACE;
9627 
9628 			if (ns->href != NULL)
9629 			    cloneNs->href = xmlStrdup(ns->href);
9630 			if (ns->prefix != NULL)
9631 			    cloneNs->prefix = xmlStrdup(ns->prefix);
9632 
9633 			*cloneNsDefSlot = cloneNs;
9634 			cloneNsDefSlot = &(cloneNs->next);
9635 
9636 			/*
9637 			* Note that for custom handling of ns-references,
9638 			* the ns-decls need not be stored in the ns-map,
9639 			* since they won't be referenced by node->ns.
9640 			*/
9641 			if ((ctxt == NULL) ||
9642 			    (ctxt->getNsForNodeFunc == NULL))
9643 			{
9644 			    /*
9645 			    * Does it shadow any ns-decl?
9646 			    */
9647 			    if (XML_NSMAP_NOTEMPTY(nsMap)) {
9648 				XML_NSMAP_FOREACH(nsMap, mi) {
9649 				    if ((mi->depth >= XML_TREE_NSMAP_PARENT) &&
9650 					(mi->shadowDepth == -1) &&
9651 					((ns->prefix == mi->newNs->prefix) ||
9652 					xmlStrEqual(ns->prefix,
9653 					mi->newNs->prefix))) {
9654 					/*
9655 					* Mark as shadowed at the current
9656 					* depth.
9657 					*/
9658 					mi->shadowDepth = depth;
9659 				    }
9660 				}
9661 			    }
9662 			    /*
9663 			    * Push mapping.
9664 			    */
9665 			    if (xmlDOMWrapNsMapAddItem(&nsMap, -1,
9666 				ns, cloneNs, depth) == NULL)
9667 				goto internal_error;
9668 			}
9669 		    }
9670 		}
9671 		/* cur->ns will be processed further down. */
9672 		break;
9673 	    case XML_ATTRIBUTE_NODE:
9674 		/* IDs will be processed further down. */
9675 		/* cur->ns will be processed further down. */
9676 		break;
9677 	    case XML_TEXT_NODE:
9678 	    case XML_CDATA_SECTION_NODE:
9679 		/*
9680 		* Note that this will also cover the values of attributes.
9681 		*/
9682 		DICT_COPY(cur->content, clone->content);
9683 		goto leave_node;
9684 	    case XML_ENTITY_NODE:
9685 		/* TODO: What to do here? */
9686 		goto leave_node;
9687 	    case XML_ENTITY_REF_NODE:
9688 		if (sourceDoc != destDoc) {
9689 		    if ((destDoc->intSubset) || (destDoc->extSubset)) {
9690 			xmlEntityPtr ent;
9691 			/*
9692 			* Different doc: Assign new entity-node if available.
9693 			*/
9694 			ent = xmlGetDocEntity(destDoc, cur->name);
9695 			if (ent != NULL) {
9696 			    clone->content = ent->content;
9697 			    clone->children = (xmlNodePtr) ent;
9698 			    clone->last = (xmlNodePtr) ent;
9699 			}
9700 		    }
9701 		} else {
9702 		    /*
9703 		    * Same doc: Use the current node's entity declaration
9704 		    * and value.
9705 		    */
9706 		    clone->content = cur->content;
9707 		    clone->children = cur->children;
9708 		    clone->last = cur->last;
9709 		}
9710 		goto leave_node;
9711 	    case XML_PI_NODE:
9712 		DICT_COPY(cur->content, clone->content);
9713 		goto leave_node;
9714 	    case XML_COMMENT_NODE:
9715 		DICT_COPY(cur->content, clone->content);
9716 		goto leave_node;
9717 	    default:
9718 		goto internal_error;
9719 	}
9720 
9721 	if (cur->ns == NULL)
9722 	    goto end_ns_reference;
9723 
9724 /* handle_ns_reference: */
9725 	/*
9726 	** The following will take care of references to ns-decls ********
9727 	** and is intended only for element- and attribute-nodes.
9728 	**
9729 	*/
9730 	if (! parnsdone) {
9731 	    if (destParent && (ctxt == NULL)) {
9732 		if (xmlDOMWrapNSNormGatherInScopeNs(&nsMap, destParent) == -1)
9733 		    goto internal_error;
9734 	    }
9735 	    parnsdone = 1;
9736 	}
9737 	/*
9738 	* Adopt ns-references.
9739 	*/
9740 	if (XML_NSMAP_NOTEMPTY(nsMap)) {
9741 	    /*
9742 	    * Search for a mapping.
9743 	    */
9744 	    XML_NSMAP_FOREACH(nsMap, mi) {
9745 		if ((mi->shadowDepth == -1) &&
9746 		    (cur->ns == mi->oldNs)) {
9747 		    /*
9748 		    * This is the nice case: a mapping was found.
9749 		    */
9750 		    clone->ns = mi->newNs;
9751 		    goto end_ns_reference;
9752 		}
9753 	    }
9754 	}
9755 	/*
9756 	* No matching namespace in scope. We need a new one.
9757 	*/
9758 	if ((ctxt != NULL) && (ctxt->getNsForNodeFunc != NULL)) {
9759 	    /*
9760 	    * User-defined behaviour.
9761 	    */
9762 	    ns = ctxt->getNsForNodeFunc(ctxt, cur,
9763 		cur->ns->href, cur->ns->prefix);
9764 	    /*
9765 	    * Add user's mapping.
9766 	    */
9767 	    if (xmlDOMWrapNsMapAddItem(&nsMap, -1,
9768 		cur->ns, ns, XML_TREE_NSMAP_CUSTOM) == NULL)
9769 		goto internal_error;
9770 	    clone->ns = ns;
9771 	} else {
9772 	    /*
9773 	    * Acquire a normalized ns-decl and add it to the map.
9774 	    */
9775 	    if (xmlDOMWrapNSNormAcquireNormalizedNs(destDoc,
9776 		/* ns-decls on curElem or on destDoc->oldNs */
9777 		destParent ? curElem : NULL,
9778 		cur->ns, &ns,
9779 		&nsMap, depth,
9780 		/* if we need to search only in the ancestor-axis */
9781 		ancestorsOnly,
9782 		/* ns-decls must be prefixed for attributes. */
9783 		(cur->type == XML_ATTRIBUTE_NODE) ? 1 : 0) == -1)
9784 		goto internal_error;
9785 	    clone->ns = ns;
9786 	}
9787 
9788 end_ns_reference:
9789 
9790 	/*
9791 	* Some post-processing.
9792 	*
9793 	* Handle ID attributes.
9794 	*/
9795 	if ((clone->type == XML_ATTRIBUTE_NODE) &&
9796 	    (clone->parent != NULL))
9797 	{
9798 	    if (xmlIsID(destDoc, clone->parent, (xmlAttrPtr) clone)) {
9799 
9800 		xmlChar *idVal;
9801 
9802 		idVal = xmlNodeListGetString(cur->doc, cur->children, 1);
9803 		if (idVal != NULL) {
9804 		    if (xmlAddID(NULL, destDoc, idVal, (xmlAttrPtr) cur) == NULL) {
9805 			/* TODO: error message. */
9806 			xmlFree(idVal);
9807 			goto internal_error;
9808 		    }
9809 		    xmlFree(idVal);
9810 		}
9811 	    }
9812 	}
9813 	/*
9814 	**
9815 	** The following will traverse the tree **************************
9816 	**
9817 	*
9818 	* Walk the element's attributes before descending into child-nodes.
9819 	*/
9820 	if ((cur->type == XML_ELEMENT_NODE) && (cur->properties != NULL)) {
9821 	    prevClone = NULL;
9822 	    parentClone = clone;
9823 	    cur = (xmlNodePtr) cur->properties;
9824 	    continue;
9825 	}
9826 into_content:
9827 	/*
9828 	* Descend into child-nodes.
9829 	*/
9830 	if (cur->children != NULL) {
9831 	    if (deep || (cur->type == XML_ATTRIBUTE_NODE)) {
9832 		prevClone = NULL;
9833 		parentClone = clone;
9834 		cur = cur->children;
9835 		continue;
9836 	    }
9837 	}
9838 
9839 leave_node:
9840 	/*
9841 	* At this point we are done with the node, its content
9842 	* and an element-nodes's attribute-nodes.
9843 	*/
9844 	if (cur == node)
9845 	    break;
9846 	if ((cur->type == XML_ELEMENT_NODE) ||
9847 	    (cur->type == XML_XINCLUDE_START) ||
9848 	    (cur->type == XML_XINCLUDE_END)) {
9849 	    /*
9850 	    * TODO: Do we expect nsDefs on XML_XINCLUDE_START?
9851 	    */
9852 	    if (XML_NSMAP_NOTEMPTY(nsMap)) {
9853 		/*
9854 		* Pop mappings.
9855 		*/
9856 		while ((nsMap->last != NULL) &&
9857 		    (nsMap->last->depth >= depth))
9858 		{
9859 		    XML_NSMAP_POP(nsMap, mi)
9860 		}
9861 		/*
9862 		* Unshadow.
9863 		*/
9864 		XML_NSMAP_FOREACH(nsMap, mi) {
9865 		    if (mi->shadowDepth >= depth)
9866 			mi->shadowDepth = -1;
9867 		}
9868 	    }
9869 	    depth--;
9870 	}
9871 	if (cur->next != NULL) {
9872 	    prevClone = clone;
9873 	    cur = cur->next;
9874 	} else if (cur->type != XML_ATTRIBUTE_NODE) {
9875 	    /*
9876 	    * Set clone->last.
9877 	    */
9878 	    if (clone->parent != NULL)
9879 		clone->parent->last = clone;
9880 	    clone = clone->parent;
9881 	    if (clone != NULL)
9882 		parentClone = clone->parent;
9883 	    /*
9884 	    * Process parent --> next;
9885 	    */
9886 	    cur = cur->parent;
9887 	    goto leave_node;
9888 	} else {
9889 	    /* This is for attributes only. */
9890 	    clone = clone->parent;
9891 	    parentClone = clone->parent;
9892 	    /*
9893 	    * Process parent-element --> children.
9894 	    */
9895 	    cur = cur->parent;
9896 	    goto into_content;
9897 	}
9898     }
9899     goto exit;
9900 
9901 internal_error:
9902     ret = -1;
9903 
9904 exit:
9905     /*
9906     * Cleanup.
9907     */
9908     if (nsMap != NULL) {
9909 	if ((ctxt) && (ctxt->namespaceMap == nsMap)) {
9910 	    /*
9911 	    * Just cleanup the map but don't free.
9912 	    */
9913 	    if (nsMap->first) {
9914 		if (nsMap->pool)
9915 		    nsMap->last->next = nsMap->pool;
9916 		nsMap->pool = nsMap->first;
9917 		nsMap->first = NULL;
9918 	    }
9919 	} else
9920 	    xmlDOMWrapNsMapFree(nsMap);
9921     }
9922     /*
9923     * TODO: Should we try a cleanup of the cloned node in case of a
9924     * fatal error?
9925     */
9926     *resNode = resultClone;
9927     return (ret);
9928 }
9929 
9930 /*
9931 * xmlDOMWrapAdoptAttr:
9932 * @ctxt: the optional context for custom processing
9933 * @sourceDoc: the optional source document of attr
9934 * @attr: the attribute-node to be adopted
9935 * @destDoc: the destination doc for adoption
9936 * @destParent: the optional new parent of @attr in @destDoc
9937 * @options: option flags
9938 *
9939 * @attr is adopted by @destDoc.
9940 * Ensures that ns-references point to @destDoc: either to
9941 * elements->nsDef entries if @destParent is given, or to
9942 * @destDoc->oldNs otherwise.
9943 *
9944 * Returns 0 if succeeded, -1 otherwise and on API/internal errors.
9945 */
9946 static int
xmlDOMWrapAdoptAttr(xmlDOMWrapCtxtPtr ctxt,xmlDocPtr sourceDoc,xmlAttrPtr attr,xmlDocPtr destDoc,xmlNodePtr destParent,int options ATTRIBUTE_UNUSED)9947 xmlDOMWrapAdoptAttr(xmlDOMWrapCtxtPtr ctxt,
9948 		    xmlDocPtr sourceDoc,
9949 		    xmlAttrPtr attr,
9950 		    xmlDocPtr destDoc,
9951 		    xmlNodePtr destParent,
9952 		    int options ATTRIBUTE_UNUSED)
9953 {
9954     xmlNodePtr cur;
9955     int adoptStr = 1;
9956 
9957     if ((attr == NULL) || (destDoc == NULL))
9958 	return (-1);
9959 
9960     attr->doc = destDoc;
9961     if (attr->ns != NULL) {
9962 	xmlNsPtr ns = NULL;
9963 
9964 	if (ctxt != NULL) {
9965 	    /* TODO: User defined. */
9966 	}
9967 	/* XML Namespace. */
9968 	if (IS_STR_XML(attr->ns->prefix)) {
9969 	    ns = xmlTreeEnsureXMLDecl(destDoc);
9970 	} else if (destParent == NULL) {
9971 	    /*
9972 	    * Store in @destDoc->oldNs.
9973 	    */
9974 	    ns = xmlDOMWrapStoreNs(destDoc, attr->ns->href, attr->ns->prefix);
9975 	} else {
9976 	    /*
9977 	    * Declare on @destParent.
9978 	    */
9979 	    if (xmlSearchNsByNamespaceStrict(destDoc, destParent, attr->ns->href,
9980 		&ns, 1) == -1)
9981 		goto internal_error;
9982 	    if (ns == NULL) {
9983 		ns = xmlDOMWrapNSNormDeclareNsForced(destDoc, destParent,
9984 		    attr->ns->href, attr->ns->prefix, 1);
9985 	    }
9986 	}
9987 	if (ns == NULL)
9988 	    goto internal_error;
9989 	attr->ns = ns;
9990     }
9991 
9992     XML_TREE_ADOPT_STR(attr->name);
9993     attr->atype = 0;
9994     attr->psvi = NULL;
9995     /*
9996     * Walk content.
9997     */
9998     if (attr->children == NULL)
9999 	return (0);
10000     cur = attr->children;
10001     if ((cur != NULL) && (cur->type == XML_NAMESPACE_DECL))
10002         goto internal_error;
10003     while (cur != NULL) {
10004 	cur->doc = destDoc;
10005 	switch (cur->type) {
10006 	    case XML_TEXT_NODE:
10007 	    case XML_CDATA_SECTION_NODE:
10008 		XML_TREE_ADOPT_STR_2(cur->content)
10009 		break;
10010 	    case XML_ENTITY_REF_NODE:
10011 		/*
10012 		* Remove reference to the entity-node.
10013 		*/
10014 		cur->content = NULL;
10015 		cur->children = NULL;
10016 		cur->last = NULL;
10017 		if ((destDoc->intSubset) || (destDoc->extSubset)) {
10018 		    xmlEntityPtr ent;
10019 		    /*
10020 		    * Assign new entity-node if available.
10021 		    */
10022 		    ent = xmlGetDocEntity(destDoc, cur->name);
10023 		    if (ent != NULL) {
10024 			cur->content = ent->content;
10025 			cur->children = (xmlNodePtr) ent;
10026 			cur->last = (xmlNodePtr) ent;
10027 		    }
10028 		}
10029 		break;
10030 	    default:
10031 		break;
10032 	}
10033 	if (cur->children != NULL) {
10034 	    cur = cur->children;
10035 	    continue;
10036 	}
10037 next_sibling:
10038 	if (cur == (xmlNodePtr) attr)
10039 	    break;
10040 	if (cur->next != NULL)
10041 	    cur = cur->next;
10042 	else {
10043 	    cur = cur->parent;
10044 	    goto next_sibling;
10045 	}
10046     }
10047     return (0);
10048 internal_error:
10049     return (-1);
10050 }
10051 
10052 /*
10053 * xmlDOMWrapAdoptNode:
10054 * @ctxt: the optional context for custom processing
10055 * @sourceDoc: the optional sourceDoc
10056 * @node: the node to start with
10057 * @destDoc: the destination doc
10058 * @destParent: the optional new parent of @node in @destDoc
10059 * @options: option flags
10060 *
10061 * References of out-of scope ns-decls are remapped to point to @destDoc:
10062 * 1) If @destParent is given, then nsDef entries on element-nodes are used
10063 * 2) If *no* @destParent is given, then @destDoc->oldNs entries are used
10064 *    This is the case when you have an unlinked node and just want to move it
10065 *    to the context of
10066 *
10067 * If @destParent is given, it ensures that the tree is namespace
10068 * wellformed by creating additional ns-decls where needed.
10069 * Note that, since prefixes of already existent ns-decls can be
10070 * shadowed by this process, it could break QNames in attribute
10071 * values or element content.
10072 * NOTE: This function was not intensively tested.
10073 *
10074 * Returns 0 if the operation succeeded,
10075 *         1 if a node of unsupported type was given,
10076 *         2 if a node of not yet supported type was given and
10077 *         -1 on API/internal errors.
10078 */
10079 int
xmlDOMWrapAdoptNode(xmlDOMWrapCtxtPtr ctxt,xmlDocPtr sourceDoc,xmlNodePtr node,xmlDocPtr destDoc,xmlNodePtr destParent,int options)10080 xmlDOMWrapAdoptNode(xmlDOMWrapCtxtPtr ctxt,
10081 		    xmlDocPtr sourceDoc,
10082 		    xmlNodePtr node,
10083 		    xmlDocPtr destDoc,
10084 		    xmlNodePtr destParent,
10085 		    int options)
10086 {
10087     if ((node == NULL) || (node->type == XML_NAMESPACE_DECL) ||
10088         (destDoc == NULL) ||
10089 	((destParent != NULL) && (destParent->doc != destDoc)))
10090 	return(-1);
10091     /*
10092     * Check node->doc sanity.
10093     */
10094     if ((node->doc != NULL) && (sourceDoc != NULL) &&
10095 	(node->doc != sourceDoc)) {
10096 	/*
10097 	* Might be an XIncluded node.
10098 	*/
10099 	return (-1);
10100     }
10101     if (sourceDoc == NULL)
10102 	sourceDoc = node->doc;
10103     if (sourceDoc == destDoc)
10104 	return (-1);
10105     switch (node->type) {
10106 	case XML_ELEMENT_NODE:
10107 	case XML_ATTRIBUTE_NODE:
10108 	case XML_TEXT_NODE:
10109 	case XML_CDATA_SECTION_NODE:
10110 	case XML_ENTITY_REF_NODE:
10111 	case XML_PI_NODE:
10112 	case XML_COMMENT_NODE:
10113 	    break;
10114 	case XML_DOCUMENT_FRAG_NODE:
10115 	    /* TODO: Support document-fragment-nodes. */
10116 	    return (2);
10117 	default:
10118 	    return (1);
10119     }
10120     /*
10121     * Unlink only if @node was not already added to @destParent.
10122     */
10123     if ((node->parent != NULL) && (destParent != node->parent))
10124 	xmlUnlinkNode(node);
10125 
10126     if (node->type == XML_ELEMENT_NODE) {
10127 	    return (xmlDOMWrapAdoptBranch(ctxt, sourceDoc, node,
10128 		    destDoc, destParent, options));
10129     } else if (node->type == XML_ATTRIBUTE_NODE) {
10130 	    return (xmlDOMWrapAdoptAttr(ctxt, sourceDoc,
10131 		(xmlAttrPtr) node, destDoc, destParent, options));
10132     } else {
10133 	xmlNodePtr cur = node;
10134 	int adoptStr = 1;
10135 
10136 	cur->doc = destDoc;
10137 	/*
10138 	* Optimize string adoption.
10139 	*/
10140 	if ((sourceDoc != NULL) &&
10141 	    (sourceDoc->dict == destDoc->dict))
10142 		adoptStr = 0;
10143 	switch (node->type) {
10144 	    case XML_TEXT_NODE:
10145 	    case XML_CDATA_SECTION_NODE:
10146 		XML_TREE_ADOPT_STR_2(node->content)
10147 		    break;
10148 	    case XML_ENTITY_REF_NODE:
10149 		/*
10150 		* Remove reference to the entity-node.
10151 		*/
10152 		node->content = NULL;
10153 		node->children = NULL;
10154 		node->last = NULL;
10155 		if ((destDoc->intSubset) || (destDoc->extSubset)) {
10156 		    xmlEntityPtr ent;
10157 		    /*
10158 		    * Assign new entity-node if available.
10159 		    */
10160 		    ent = xmlGetDocEntity(destDoc, node->name);
10161 		    if (ent != NULL) {
10162 			node->content = ent->content;
10163 			node->children = (xmlNodePtr) ent;
10164 			node->last = (xmlNodePtr) ent;
10165 		    }
10166 		}
10167 		XML_TREE_ADOPT_STR(node->name)
10168 		break;
10169 	    case XML_PI_NODE: {
10170 		XML_TREE_ADOPT_STR(node->name)
10171 		XML_TREE_ADOPT_STR_2(node->content)
10172 		break;
10173 	    }
10174 	    default:
10175 		break;
10176 	}
10177     }
10178     return (0);
10179 }
10180 
10181 #define bottom_tree
10182 #include "elfgcchack.h"
10183