• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * xpointer.c : Code to handle XML Pointer
3  *
4  * Base implementation was made accordingly to
5  * W3C Candidate Recommendation 7 June 2000
6  * http://www.w3.org/TR/2000/CR-xptr-20000607
7  *
8  * Added support for the element() scheme described in:
9  * W3C Proposed Recommendation 13 November 2002
10  * http://www.w3.org/TR/2002/PR-xptr-element-20021113/
11  *
12  * See Copyright for the status of this software.
13  *
14  * daniel@veillard.com
15  */
16 
17 /* To avoid EBCDIC trouble when parsing on zOS */
18 #if defined(__MVS__)
19 #pragma convert("ISO8859-1")
20 #endif
21 
22 #define IN_LIBXML
23 #include "libxml.h"
24 
25 /*
26  * TODO: better handling of error cases, the full expression should
27  *       be parsed beforehand instead of a progressive evaluation
28  * TODO: Access into entities references are not supported now ...
29  *       need a start to be able to pop out of entities refs since
30  *       parent is the entity declaration, not the ref.
31  */
32 
33 #include <string.h>
34 #include <libxml/xpointer.h>
35 #include <libxml/xmlmemory.h>
36 #include <libxml/parserInternals.h>
37 #include <libxml/uri.h>
38 #include <libxml/xpath.h>
39 #include <libxml/xpathInternals.h>
40 #include <libxml/xmlerror.h>
41 #include <libxml/globals.h>
42 
43 #ifdef LIBXML_XPTR_ENABLED
44 
45 /* Add support of the xmlns() xpointer scheme to initialize the namespaces */
46 #define XPTR_XMLNS_SCHEME
47 
48 /* #define DEBUG_RANGES */
49 #ifdef DEBUG_RANGES
50 #ifdef LIBXML_DEBUG_ENABLED
51 #include <libxml/debugXML.h>
52 #endif
53 #endif
54 
55 #define TODO								\
56     xmlGenericError(xmlGenericErrorContext,				\
57 	    "Unimplemented block at %s:%d\n",				\
58             __FILE__, __LINE__);
59 
60 #define STRANGE							\
61     xmlGenericError(xmlGenericErrorContext,				\
62 	    "Internal error at %s:%d\n",				\
63             __FILE__, __LINE__);
64 
65 /************************************************************************
66  *									*
67  *		Some factorized error routines				*
68  *									*
69  ************************************************************************/
70 
71 /**
72  * xmlXPtrErrMemory:
73  * @extra:  extra informations
74  *
75  * Handle a redefinition of attribute error
76  */
77 static void
xmlXPtrErrMemory(const char * extra)78 xmlXPtrErrMemory(const char *extra)
79 {
80     __xmlRaiseError(NULL, NULL, NULL, NULL, NULL, XML_FROM_XPOINTER,
81 		    XML_ERR_NO_MEMORY, XML_ERR_ERROR, NULL, 0, extra,
82 		    NULL, NULL, 0, 0,
83 		    "Memory allocation failed : %s\n", extra);
84 }
85 
86 /**
87  * xmlXPtrErr:
88  * @ctxt:  an XPTR evaluation context
89  * @extra:  extra informations
90  *
91  * Handle a redefinition of attribute error
92  */
93 static void LIBXML_ATTR_FORMAT(3,0)
xmlXPtrErr(xmlXPathParserContextPtr ctxt,int error,const char * msg,const xmlChar * extra)94 xmlXPtrErr(xmlXPathParserContextPtr ctxt, int error,
95            const char * msg, const xmlChar *extra)
96 {
97     if (ctxt != NULL)
98         ctxt->error = error;
99     if ((ctxt == NULL) || (ctxt->context == NULL)) {
100 	__xmlRaiseError(NULL, NULL, NULL,
101 			NULL, NULL, XML_FROM_XPOINTER, error,
102 			XML_ERR_ERROR, NULL, 0,
103 			(const char *) extra, NULL, NULL, 0, 0,
104 			msg, extra);
105 	return;
106     }
107 
108     /* cleanup current last error */
109     xmlResetError(&ctxt->context->lastError);
110 
111     ctxt->context->lastError.domain = XML_FROM_XPOINTER;
112     ctxt->context->lastError.code = error;
113     ctxt->context->lastError.level = XML_ERR_ERROR;
114     ctxt->context->lastError.str1 = (char *) xmlStrdup(ctxt->base);
115     ctxt->context->lastError.int1 = ctxt->cur - ctxt->base;
116     ctxt->context->lastError.node = ctxt->context->debugNode;
117     if (ctxt->context->error != NULL) {
118 	ctxt->context->error(ctxt->context->userData,
119 	                     &ctxt->context->lastError);
120     } else {
121 	__xmlRaiseError(NULL, NULL, NULL,
122 			NULL, ctxt->context->debugNode, XML_FROM_XPOINTER,
123 			error, XML_ERR_ERROR, NULL, 0,
124 			(const char *) extra, (const char *) ctxt->base, NULL,
125 			ctxt->cur - ctxt->base, 0,
126 			msg, extra);
127     }
128 }
129 
130 /************************************************************************
131  *									*
132  *		A few helper functions for child sequences		*
133  *									*
134  ************************************************************************/
135 /* xmlXPtrAdvanceNode is a private function, but used by xinclude.c */
136 xmlNodePtr xmlXPtrAdvanceNode(xmlNodePtr cur, int *level);
137 /**
138  * xmlXPtrGetArity:
139  * @cur:  the node
140  *
141  * Returns the number of child for an element, -1 in case of error
142  */
143 static int
xmlXPtrGetArity(xmlNodePtr cur)144 xmlXPtrGetArity(xmlNodePtr cur) {
145     int i;
146     if ((cur == NULL) || (cur->type == XML_NAMESPACE_DECL))
147 	return(-1);
148     cur = cur->children;
149     for (i = 0;cur != NULL;cur = cur->next) {
150 	if ((cur->type == XML_ELEMENT_NODE) ||
151 	    (cur->type == XML_DOCUMENT_NODE) ||
152 	    (cur->type == XML_HTML_DOCUMENT_NODE)) {
153 	    i++;
154 	}
155     }
156     return(i);
157 }
158 
159 /**
160  * xmlXPtrGetIndex:
161  * @cur:  the node
162  *
163  * Returns the index of the node in its parent children list, -1
164  *         in case of error
165  */
166 static int
xmlXPtrGetIndex(xmlNodePtr cur)167 xmlXPtrGetIndex(xmlNodePtr cur) {
168     int i;
169     if ((cur == NULL) || (cur->type == XML_NAMESPACE_DECL))
170 	return(-1);
171     for (i = 1;cur != NULL;cur = cur->prev) {
172 	if ((cur->type == XML_ELEMENT_NODE) ||
173 	    (cur->type == XML_DOCUMENT_NODE) ||
174 	    (cur->type == XML_HTML_DOCUMENT_NODE)) {
175 	    i++;
176 	}
177     }
178     return(i);
179 }
180 
181 /**
182  * xmlXPtrGetNthChild:
183  * @cur:  the node
184  * @no:  the child number
185  *
186  * Returns the @no'th element child of @cur or NULL
187  */
188 static xmlNodePtr
xmlXPtrGetNthChild(xmlNodePtr cur,int no)189 xmlXPtrGetNthChild(xmlNodePtr cur, int no) {
190     int i;
191     if ((cur == NULL) || (cur->type == XML_NAMESPACE_DECL))
192 	return(cur);
193     cur = cur->children;
194     for (i = 0;i <= no;cur = cur->next) {
195 	if (cur == NULL)
196 	    return(cur);
197 	if ((cur->type == XML_ELEMENT_NODE) ||
198 	    (cur->type == XML_DOCUMENT_NODE) ||
199 	    (cur->type == XML_HTML_DOCUMENT_NODE)) {
200 	    i++;
201 	    if (i == no)
202 		break;
203 	}
204     }
205     return(cur);
206 }
207 
208 /************************************************************************
209  *									*
210  *		Handling of XPointer specific types			*
211  *									*
212  ************************************************************************/
213 
214 /**
215  * xmlXPtrCmpPoints:
216  * @node1:  the first node
217  * @index1:  the first index
218  * @node2:  the second node
219  * @index2:  the second index
220  *
221  * Compare two points w.r.t document order
222  *
223  * Returns -2 in case of error 1 if first point < second point, 0 if
224  *         that's the same point, -1 otherwise
225  */
226 static int
xmlXPtrCmpPoints(xmlNodePtr node1,int index1,xmlNodePtr node2,int index2)227 xmlXPtrCmpPoints(xmlNodePtr node1, int index1, xmlNodePtr node2, int index2) {
228     if ((node1 == NULL) || (node2 == NULL))
229 	return(-2);
230     /*
231      * a couple of optimizations which will avoid computations in most cases
232      */
233     if (node1 == node2) {
234 	if (index1 < index2)
235 	    return(1);
236 	if (index1 > index2)
237 	    return(-1);
238 	return(0);
239     }
240     return(xmlXPathCmpNodes(node1, node2));
241 }
242 
243 /**
244  * xmlXPtrNewPoint:
245  * @node:  the xmlNodePtr
246  * @indx:  the indx within the node
247  *
248  * Create a new xmlXPathObjectPtr of type point
249  *
250  * Returns the newly created object.
251  */
252 static xmlXPathObjectPtr
xmlXPtrNewPoint(xmlNodePtr node,int indx)253 xmlXPtrNewPoint(xmlNodePtr node, int indx) {
254     xmlXPathObjectPtr ret;
255 
256     if (node == NULL)
257 	return(NULL);
258     if (indx < 0)
259 	return(NULL);
260 
261     ret = (xmlXPathObjectPtr) xmlMalloc(sizeof(xmlXPathObject));
262     if (ret == NULL) {
263         xmlXPtrErrMemory("allocating point");
264 	return(NULL);
265     }
266     memset(ret, 0 , (size_t) sizeof(xmlXPathObject));
267     ret->type = XPATH_POINT;
268     ret->user = (void *) node;
269     ret->index = indx;
270     return(ret);
271 }
272 
273 /**
274  * xmlXPtrRangeCheckOrder:
275  * @range:  an object range
276  *
277  * Make sure the points in the range are in the right order
278  */
279 static void
xmlXPtrRangeCheckOrder(xmlXPathObjectPtr range)280 xmlXPtrRangeCheckOrder(xmlXPathObjectPtr range) {
281     int tmp;
282     xmlNodePtr tmp2;
283     if (range == NULL)
284 	return;
285     if (range->type != XPATH_RANGE)
286 	return;
287     if (range->user2 == NULL)
288 	return;
289     tmp = xmlXPtrCmpPoints(range->user, range->index,
290 	                     range->user2, range->index2);
291     if (tmp == -1) {
292 	tmp2 = range->user;
293 	range->user = range->user2;
294 	range->user2 = tmp2;
295 	tmp = range->index;
296 	range->index = range->index2;
297 	range->index2 = tmp;
298     }
299 }
300 
301 /**
302  * xmlXPtrRangesEqual:
303  * @range1:  the first range
304  * @range2:  the second range
305  *
306  * Compare two ranges
307  *
308  * Returns 1 if equal, 0 otherwise
309  */
310 static int
xmlXPtrRangesEqual(xmlXPathObjectPtr range1,xmlXPathObjectPtr range2)311 xmlXPtrRangesEqual(xmlXPathObjectPtr range1, xmlXPathObjectPtr range2) {
312     if (range1 == range2)
313 	return(1);
314     if ((range1 == NULL) || (range2 == NULL))
315 	return(0);
316     if (range1->type != range2->type)
317 	return(0);
318     if (range1->type != XPATH_RANGE)
319 	return(0);
320     if (range1->user != range2->user)
321 	return(0);
322     if (range1->index != range2->index)
323 	return(0);
324     if (range1->user2 != range2->user2)
325 	return(0);
326     if (range1->index2 != range2->index2)
327 	return(0);
328     return(1);
329 }
330 
331 /**
332  * xmlXPtrNewRangeInternal:
333  * @start:  the starting node
334  * @startindex:  the start index
335  * @end:  the ending point
336  * @endindex:  the ending index
337  *
338  * Internal function to create a new xmlXPathObjectPtr of type range
339  *
340  * Returns the newly created object.
341  */
342 static xmlXPathObjectPtr
xmlXPtrNewRangeInternal(xmlNodePtr start,int startindex,xmlNodePtr end,int endindex)343 xmlXPtrNewRangeInternal(xmlNodePtr start, int startindex,
344                         xmlNodePtr end, int endindex) {
345     xmlXPathObjectPtr ret;
346 
347     /*
348      * Namespace nodes must be copied (see xmlXPathNodeSetDupNs).
349      * Disallow them for now.
350      */
351     if ((start != NULL) && (start->type == XML_NAMESPACE_DECL))
352 	return(NULL);
353     if ((end != NULL) && (end->type == XML_NAMESPACE_DECL))
354 	return(NULL);
355 
356     ret = (xmlXPathObjectPtr) xmlMalloc(sizeof(xmlXPathObject));
357     if (ret == NULL) {
358         xmlXPtrErrMemory("allocating range");
359 	return(NULL);
360     }
361     memset(ret, 0, sizeof(xmlXPathObject));
362     ret->type = XPATH_RANGE;
363     ret->user = start;
364     ret->index = startindex;
365     ret->user2 = end;
366     ret->index2 = endindex;
367     return(ret);
368 }
369 
370 /**
371  * xmlXPtrNewRange:
372  * @start:  the starting node
373  * @startindex:  the start index
374  * @end:  the ending point
375  * @endindex:  the ending index
376  *
377  * Create a new xmlXPathObjectPtr of type range
378  *
379  * Returns the newly created object.
380  */
381 xmlXPathObjectPtr
xmlXPtrNewRange(xmlNodePtr start,int startindex,xmlNodePtr end,int endindex)382 xmlXPtrNewRange(xmlNodePtr start, int startindex,
383 	        xmlNodePtr end, int endindex) {
384     xmlXPathObjectPtr ret;
385 
386     if (start == NULL)
387 	return(NULL);
388     if (end == NULL)
389 	return(NULL);
390     if (startindex < 0)
391 	return(NULL);
392     if (endindex < 0)
393 	return(NULL);
394 
395     ret = xmlXPtrNewRangeInternal(start, startindex, end, endindex);
396     xmlXPtrRangeCheckOrder(ret);
397     return(ret);
398 }
399 
400 /**
401  * xmlXPtrNewRangePoints:
402  * @start:  the starting point
403  * @end:  the ending point
404  *
405  * Create a new xmlXPathObjectPtr of type range using 2 Points
406  *
407  * Returns the newly created object.
408  */
409 xmlXPathObjectPtr
xmlXPtrNewRangePoints(xmlXPathObjectPtr start,xmlXPathObjectPtr end)410 xmlXPtrNewRangePoints(xmlXPathObjectPtr start, xmlXPathObjectPtr end) {
411     xmlXPathObjectPtr ret;
412 
413     if (start == NULL)
414 	return(NULL);
415     if (end == NULL)
416 	return(NULL);
417     if (start->type != XPATH_POINT)
418 	return(NULL);
419     if (end->type != XPATH_POINT)
420 	return(NULL);
421 
422     ret = xmlXPtrNewRangeInternal(start->user, start->index, end->user,
423                                   end->index);
424     xmlXPtrRangeCheckOrder(ret);
425     return(ret);
426 }
427 
428 /**
429  * xmlXPtrNewRangePointNode:
430  * @start:  the starting point
431  * @end:  the ending node
432  *
433  * Create a new xmlXPathObjectPtr of type range from a point to a node
434  *
435  * Returns the newly created object.
436  */
437 xmlXPathObjectPtr
xmlXPtrNewRangePointNode(xmlXPathObjectPtr start,xmlNodePtr end)438 xmlXPtrNewRangePointNode(xmlXPathObjectPtr start, xmlNodePtr end) {
439     xmlXPathObjectPtr ret;
440 
441     if (start == NULL)
442 	return(NULL);
443     if (end == NULL)
444 	return(NULL);
445     if (start->type != XPATH_POINT)
446 	return(NULL);
447 
448     ret = xmlXPtrNewRangeInternal(start->user, start->index, end, -1);
449     xmlXPtrRangeCheckOrder(ret);
450     return(ret);
451 }
452 
453 /**
454  * xmlXPtrNewRangeNodePoint:
455  * @start:  the starting node
456  * @end:  the ending point
457  *
458  * Create a new xmlXPathObjectPtr of type range from a node to a point
459  *
460  * Returns the newly created object.
461  */
462 xmlXPathObjectPtr
xmlXPtrNewRangeNodePoint(xmlNodePtr start,xmlXPathObjectPtr end)463 xmlXPtrNewRangeNodePoint(xmlNodePtr start, xmlXPathObjectPtr end) {
464     xmlXPathObjectPtr ret;
465 
466     if (start == NULL)
467 	return(NULL);
468     if (end == NULL)
469 	return(NULL);
470     if (end->type != XPATH_POINT)
471 	return(NULL);
472 
473     ret = xmlXPtrNewRangeInternal(start, -1, end->user, end->index);
474     xmlXPtrRangeCheckOrder(ret);
475     return(ret);
476 }
477 
478 /**
479  * xmlXPtrNewRangeNodes:
480  * @start:  the starting node
481  * @end:  the ending node
482  *
483  * Create a new xmlXPathObjectPtr of type range using 2 nodes
484  *
485  * Returns the newly created object.
486  */
487 xmlXPathObjectPtr
xmlXPtrNewRangeNodes(xmlNodePtr start,xmlNodePtr end)488 xmlXPtrNewRangeNodes(xmlNodePtr start, xmlNodePtr end) {
489     xmlXPathObjectPtr ret;
490 
491     if (start == NULL)
492 	return(NULL);
493     if (end == NULL)
494 	return(NULL);
495 
496     ret = xmlXPtrNewRangeInternal(start, -1, end, -1);
497     xmlXPtrRangeCheckOrder(ret);
498     return(ret);
499 }
500 
501 /**
502  * xmlXPtrNewCollapsedRange:
503  * @start:  the starting and ending node
504  *
505  * Create a new xmlXPathObjectPtr of type range using a single nodes
506  *
507  * Returns the newly created object.
508  */
509 xmlXPathObjectPtr
xmlXPtrNewCollapsedRange(xmlNodePtr start)510 xmlXPtrNewCollapsedRange(xmlNodePtr start) {
511     xmlXPathObjectPtr ret;
512 
513     if (start == NULL)
514 	return(NULL);
515 
516     ret = xmlXPtrNewRangeInternal(start, -1, NULL, -1);
517     return(ret);
518 }
519 
520 /**
521  * xmlXPtrNewRangeNodeObject:
522  * @start:  the starting node
523  * @end:  the ending object
524  *
525  * Create a new xmlXPathObjectPtr of type range from a not to an object
526  *
527  * Returns the newly created object.
528  */
529 xmlXPathObjectPtr
xmlXPtrNewRangeNodeObject(xmlNodePtr start,xmlXPathObjectPtr end)530 xmlXPtrNewRangeNodeObject(xmlNodePtr start, xmlXPathObjectPtr end) {
531     xmlNodePtr endNode;
532     int endIndex;
533     xmlXPathObjectPtr ret;
534 
535     if (start == NULL)
536 	return(NULL);
537     if (end == NULL)
538 	return(NULL);
539     switch (end->type) {
540 	case XPATH_POINT:
541 	    endNode = end->user;
542 	    endIndex = end->index;
543 	    break;
544 	case XPATH_RANGE:
545 	    endNode = end->user2;
546 	    endIndex = end->index2;
547 	    break;
548 	case XPATH_NODESET:
549 	    /*
550 	     * Empty set ...
551 	     */
552 	    if ((end->nodesetval == NULL) || (end->nodesetval->nodeNr <= 0))
553 		return(NULL);
554 	    endNode = end->nodesetval->nodeTab[end->nodesetval->nodeNr - 1];
555 	    endIndex = -1;
556 	    break;
557 	default:
558 	    /* TODO */
559 	    return(NULL);
560     }
561 
562     ret = xmlXPtrNewRangeInternal(start, -1, endNode, endIndex);
563     xmlXPtrRangeCheckOrder(ret);
564     return(ret);
565 }
566 
567 #define XML_RANGESET_DEFAULT	10
568 
569 /**
570  * xmlXPtrLocationSetCreate:
571  * @val:  an initial xmlXPathObjectPtr, or NULL
572  *
573  * Create a new xmlLocationSetPtr of type double and of value @val
574  *
575  * Returns the newly created object.
576  */
577 xmlLocationSetPtr
xmlXPtrLocationSetCreate(xmlXPathObjectPtr val)578 xmlXPtrLocationSetCreate(xmlXPathObjectPtr val) {
579     xmlLocationSetPtr ret;
580 
581     ret = (xmlLocationSetPtr) xmlMalloc(sizeof(xmlLocationSet));
582     if (ret == NULL) {
583         xmlXPtrErrMemory("allocating locationset");
584 	return(NULL);
585     }
586     memset(ret, 0 , (size_t) sizeof(xmlLocationSet));
587     if (val != NULL) {
588         ret->locTab = (xmlXPathObjectPtr *) xmlMalloc(XML_RANGESET_DEFAULT *
589 					     sizeof(xmlXPathObjectPtr));
590 	if (ret->locTab == NULL) {
591 	    xmlXPtrErrMemory("allocating locationset");
592 	    xmlFree(ret);
593 	    return(NULL);
594 	}
595 	memset(ret->locTab, 0 ,
596 	       XML_RANGESET_DEFAULT * (size_t) sizeof(xmlXPathObjectPtr));
597         ret->locMax = XML_RANGESET_DEFAULT;
598 	ret->locTab[ret->locNr++] = val;
599     }
600     return(ret);
601 }
602 
603 /**
604  * xmlXPtrLocationSetAdd:
605  * @cur:  the initial range set
606  * @val:  a new xmlXPathObjectPtr
607  *
608  * add a new xmlXPathObjectPtr to an existing LocationSet
609  * If the location already exist in the set @val is freed.
610  */
611 void
xmlXPtrLocationSetAdd(xmlLocationSetPtr cur,xmlXPathObjectPtr val)612 xmlXPtrLocationSetAdd(xmlLocationSetPtr cur, xmlXPathObjectPtr val) {
613     int i;
614 
615     if ((cur == NULL) || (val == NULL)) return;
616 
617     /*
618      * check against doublons
619      */
620     for (i = 0;i < cur->locNr;i++) {
621 	if (xmlXPtrRangesEqual(cur->locTab[i], val)) {
622 	    xmlXPathFreeObject(val);
623 	    return;
624 	}
625     }
626 
627     /*
628      * grow the locTab if needed
629      */
630     if (cur->locMax == 0) {
631         cur->locTab = (xmlXPathObjectPtr *) xmlMalloc(XML_RANGESET_DEFAULT *
632 					     sizeof(xmlXPathObjectPtr));
633 	if (cur->locTab == NULL) {
634 	    xmlXPtrErrMemory("adding location to set");
635 	    return;
636 	}
637 	memset(cur->locTab, 0 ,
638 	       XML_RANGESET_DEFAULT * (size_t) sizeof(xmlXPathObjectPtr));
639         cur->locMax = XML_RANGESET_DEFAULT;
640     } else if (cur->locNr == cur->locMax) {
641         xmlXPathObjectPtr *temp;
642 
643         cur->locMax *= 2;
644 	temp = (xmlXPathObjectPtr *) xmlRealloc(cur->locTab, cur->locMax *
645 				      sizeof(xmlXPathObjectPtr));
646 	if (temp == NULL) {
647 	    xmlXPtrErrMemory("adding location to set");
648 	    return;
649 	}
650 	cur->locTab = temp;
651     }
652     cur->locTab[cur->locNr++] = val;
653 }
654 
655 /**
656  * xmlXPtrLocationSetMerge:
657  * @val1:  the first LocationSet
658  * @val2:  the second LocationSet
659  *
660  * Merges two rangesets, all ranges from @val2 are added to @val1
661  *
662  * Returns val1 once extended or NULL in case of error.
663  */
664 xmlLocationSetPtr
xmlXPtrLocationSetMerge(xmlLocationSetPtr val1,xmlLocationSetPtr val2)665 xmlXPtrLocationSetMerge(xmlLocationSetPtr val1, xmlLocationSetPtr val2) {
666     int i;
667 
668     if (val1 == NULL) return(NULL);
669     if (val2 == NULL) return(val1);
670 
671     /*
672      * !!!!! this can be optimized a lot, knowing that both
673      *       val1 and val2 already have unicity of their values.
674      */
675 
676     for (i = 0;i < val2->locNr;i++)
677         xmlXPtrLocationSetAdd(val1, val2->locTab[i]);
678 
679     return(val1);
680 }
681 
682 /**
683  * xmlXPtrLocationSetDel:
684  * @cur:  the initial range set
685  * @val:  an xmlXPathObjectPtr
686  *
687  * Removes an xmlXPathObjectPtr from an existing LocationSet
688  */
689 void
xmlXPtrLocationSetDel(xmlLocationSetPtr cur,xmlXPathObjectPtr val)690 xmlXPtrLocationSetDel(xmlLocationSetPtr cur, xmlXPathObjectPtr val) {
691     int i;
692 
693     if (cur == NULL) return;
694     if (val == NULL) return;
695 
696     /*
697      * check against doublons
698      */
699     for (i = 0;i < cur->locNr;i++)
700         if (cur->locTab[i] == val) break;
701 
702     if (i >= cur->locNr) {
703 #ifdef DEBUG
704         xmlGenericError(xmlGenericErrorContext,
705 	        "xmlXPtrLocationSetDel: Range wasn't found in RangeList\n");
706 #endif
707         return;
708     }
709     cur->locNr--;
710     for (;i < cur->locNr;i++)
711         cur->locTab[i] = cur->locTab[i + 1];
712     cur->locTab[cur->locNr] = NULL;
713 }
714 
715 /**
716  * xmlXPtrLocationSetRemove:
717  * @cur:  the initial range set
718  * @val:  the index to remove
719  *
720  * Removes an entry from an existing LocationSet list.
721  */
722 void
xmlXPtrLocationSetRemove(xmlLocationSetPtr cur,int val)723 xmlXPtrLocationSetRemove(xmlLocationSetPtr cur, int val) {
724     if (cur == NULL) return;
725     if (val >= cur->locNr) return;
726     cur->locNr--;
727     for (;val < cur->locNr;val++)
728         cur->locTab[val] = cur->locTab[val + 1];
729     cur->locTab[cur->locNr] = NULL;
730 }
731 
732 /**
733  * xmlXPtrFreeLocationSet:
734  * @obj:  the xmlLocationSetPtr to free
735  *
736  * Free the LocationSet compound (not the actual ranges !).
737  */
738 void
xmlXPtrFreeLocationSet(xmlLocationSetPtr obj)739 xmlXPtrFreeLocationSet(xmlLocationSetPtr obj) {
740     int i;
741 
742     if (obj == NULL) return;
743     if (obj->locTab != NULL) {
744 	for (i = 0;i < obj->locNr; i++) {
745             xmlXPathFreeObject(obj->locTab[i]);
746 	}
747 	xmlFree(obj->locTab);
748     }
749     xmlFree(obj);
750 }
751 
752 /**
753  * xmlXPtrNewLocationSetNodes:
754  * @start:  the start NodePtr value
755  * @end:  the end NodePtr value or NULL
756  *
757  * Create a new xmlXPathObjectPtr of type LocationSet and initialize
758  * it with the single range made of the two nodes @start and @end
759  *
760  * Returns the newly created object.
761  */
762 xmlXPathObjectPtr
xmlXPtrNewLocationSetNodes(xmlNodePtr start,xmlNodePtr end)763 xmlXPtrNewLocationSetNodes(xmlNodePtr start, xmlNodePtr end) {
764     xmlXPathObjectPtr ret;
765 
766     ret = (xmlXPathObjectPtr) xmlMalloc(sizeof(xmlXPathObject));
767     if (ret == NULL) {
768         xmlXPtrErrMemory("allocating locationset");
769 	return(NULL);
770     }
771     memset(ret, 0 , (size_t) sizeof(xmlXPathObject));
772     ret->type = XPATH_LOCATIONSET;
773     if (end == NULL)
774 	ret->user = xmlXPtrLocationSetCreate(xmlXPtrNewCollapsedRange(start));
775     else
776 	ret->user = xmlXPtrLocationSetCreate(xmlXPtrNewRangeNodes(start,end));
777     return(ret);
778 }
779 
780 /**
781  * xmlXPtrNewLocationSetNodeSet:
782  * @set:  a node set
783  *
784  * Create a new xmlXPathObjectPtr of type LocationSet and initialize
785  * it with all the nodes from @set
786  *
787  * Returns the newly created object.
788  */
789 xmlXPathObjectPtr
xmlXPtrNewLocationSetNodeSet(xmlNodeSetPtr set)790 xmlXPtrNewLocationSetNodeSet(xmlNodeSetPtr set) {
791     xmlXPathObjectPtr ret;
792 
793     ret = (xmlXPathObjectPtr) xmlMalloc(sizeof(xmlXPathObject));
794     if (ret == NULL) {
795         xmlXPtrErrMemory("allocating locationset");
796 	return(NULL);
797     }
798     memset(ret, 0 , (size_t) sizeof(xmlXPathObject));
799     ret->type = XPATH_LOCATIONSET;
800     if (set != NULL) {
801 	int i;
802 	xmlLocationSetPtr newset;
803 
804 	newset = xmlXPtrLocationSetCreate(NULL);
805 	if (newset == NULL)
806 	    return(ret);
807 
808 	for (i = 0;i < set->nodeNr;i++)
809 	    xmlXPtrLocationSetAdd(newset,
810 		        xmlXPtrNewCollapsedRange(set->nodeTab[i]));
811 
812 	ret->user = (void *) newset;
813     }
814     return(ret);
815 }
816 
817 /**
818  * xmlXPtrWrapLocationSet:
819  * @val:  the LocationSet value
820  *
821  * Wrap the LocationSet @val in a new xmlXPathObjectPtr
822  *
823  * Returns the newly created object.
824  */
825 xmlXPathObjectPtr
xmlXPtrWrapLocationSet(xmlLocationSetPtr val)826 xmlXPtrWrapLocationSet(xmlLocationSetPtr val) {
827     xmlXPathObjectPtr ret;
828 
829     ret = (xmlXPathObjectPtr) xmlMalloc(sizeof(xmlXPathObject));
830     if (ret == NULL) {
831         xmlXPtrErrMemory("allocating locationset");
832 	return(NULL);
833     }
834     memset(ret, 0 , (size_t) sizeof(xmlXPathObject));
835     ret->type = XPATH_LOCATIONSET;
836     ret->user = (void *) val;
837     return(ret);
838 }
839 
840 /************************************************************************
841  *									*
842  *			The parser					*
843  *									*
844  ************************************************************************/
845 
846 static void xmlXPtrEvalChildSeq(xmlXPathParserContextPtr ctxt, xmlChar *name);
847 
848 /*
849  * Macros for accessing the content. Those should be used only by the parser,
850  * and not exported.
851  *
852  * Dirty macros, i.e. one need to make assumption on the context to use them
853  *
854  *   CUR_PTR return the current pointer to the xmlChar to be parsed.
855  *   CUR     returns the current xmlChar value, i.e. a 8 bit value
856  *           in ISO-Latin or UTF-8.
857  *           This should be used internally by the parser
858  *           only to compare to ASCII values otherwise it would break when
859  *           running with UTF-8 encoding.
860  *   NXT(n)  returns the n'th next xmlChar. Same as CUR is should be used only
861  *           to compare on ASCII based substring.
862  *   SKIP(n) Skip n xmlChar, and must also be used only to skip ASCII defined
863  *           strings within the parser.
864  *   CURRENT Returns the current char value, with the full decoding of
865  *           UTF-8 if we are using this mode. It returns an int.
866  *   NEXT    Skip to the next character, this does the proper decoding
867  *           in UTF-8 mode. It also pop-up unfinished entities on the fly.
868  *           It returns the pointer to the current xmlChar.
869  */
870 
871 #define CUR (*ctxt->cur)
872 #define SKIP(val) ctxt->cur += (val)
873 #define NXT(val) ctxt->cur[(val)]
874 #define CUR_PTR ctxt->cur
875 
876 #define SKIP_BLANKS							\
877     while (IS_BLANK_CH(*(ctxt->cur))) NEXT
878 
879 #define CURRENT (*ctxt->cur)
880 #define NEXT ((*ctxt->cur) ?  ctxt->cur++: ctxt->cur)
881 
882 /*
883  * xmlXPtrGetChildNo:
884  * @ctxt:  the XPointer Parser context
885  * @index:  the child number
886  *
887  * Move the current node of the nodeset on the stack to the
888  * given child if found
889  */
890 static void
xmlXPtrGetChildNo(xmlXPathParserContextPtr ctxt,int indx)891 xmlXPtrGetChildNo(xmlXPathParserContextPtr ctxt, int indx) {
892     xmlNodePtr cur = NULL;
893     xmlXPathObjectPtr obj;
894     xmlNodeSetPtr oldset;
895 
896     CHECK_TYPE(XPATH_NODESET);
897     obj = valuePop(ctxt);
898     oldset = obj->nodesetval;
899     if ((indx <= 0) || (oldset == NULL) || (oldset->nodeNr != 1)) {
900 	xmlXPathFreeObject(obj);
901 	valuePush(ctxt, xmlXPathNewNodeSet(NULL));
902 	return;
903     }
904     cur = xmlXPtrGetNthChild(oldset->nodeTab[0], indx);
905     if (cur == NULL) {
906 	xmlXPathFreeObject(obj);
907 	valuePush(ctxt, xmlXPathNewNodeSet(NULL));
908 	return;
909     }
910     oldset->nodeTab[0] = cur;
911     valuePush(ctxt, obj);
912 }
913 
914 /**
915  * xmlXPtrEvalXPtrPart:
916  * @ctxt:  the XPointer Parser context
917  * @name:  the preparsed Scheme for the XPtrPart
918  *
919  * XPtrPart ::= 'xpointer' '(' XPtrExpr ')'
920  *            | Scheme '(' SchemeSpecificExpr ')'
921  *
922  * Scheme   ::=  NCName - 'xpointer' [VC: Non-XPointer schemes]
923  *
924  * SchemeSpecificExpr ::= StringWithBalancedParens
925  *
926  * StringWithBalancedParens ::=
927  *              [^()]* ('(' StringWithBalancedParens ')' [^()]*)*
928  *              [VC: Parenthesis escaping]
929  *
930  * XPtrExpr ::= Expr [VC: Parenthesis escaping]
931  *
932  * VC: Parenthesis escaping:
933  *   The end of an XPointer part is signaled by the right parenthesis ")"
934  *   character that is balanced with the left parenthesis "(" character
935  *   that began the part. Any unbalanced parenthesis character inside the
936  *   expression, even within literals, must be escaped with a circumflex (^)
937  *   character preceding it. If the expression contains any literal
938  *   occurrences of the circumflex, each must be escaped with an additional
939  *   circumflex (that is, ^^). If the unescaped parentheses in the expression
940  *   are not balanced, a syntax error results.
941  *
942  * Parse and evaluate an XPtrPart. Basically it generates the unescaped
943  * string and if the scheme is 'xpointer' it will call the XPath interpreter.
944  *
945  * TODO: there is no new scheme registration mechanism
946  */
947 
948 static void
xmlXPtrEvalXPtrPart(xmlXPathParserContextPtr ctxt,xmlChar * name)949 xmlXPtrEvalXPtrPart(xmlXPathParserContextPtr ctxt, xmlChar *name) {
950     xmlChar *buffer, *cur;
951     int len;
952     int level;
953 
954     if (name == NULL)
955     name = xmlXPathParseName(ctxt);
956     if (name == NULL)
957 	XP_ERROR(XPATH_EXPR_ERROR);
958 
959     if (CUR != '(') {
960         xmlFree(name);
961 	XP_ERROR(XPATH_EXPR_ERROR);
962     }
963     NEXT;
964     level = 1;
965 
966     len = xmlStrlen(ctxt->cur);
967     len++;
968     buffer = (xmlChar *) xmlMallocAtomic(len * sizeof (xmlChar));
969     if (buffer == NULL) {
970         xmlXPtrErrMemory("allocating buffer");
971         xmlFree(name);
972 	return;
973     }
974 
975     cur = buffer;
976     while (CUR != 0) {
977 	if (CUR == ')') {
978 	    level--;
979 	    if (level == 0) {
980 		NEXT;
981 		break;
982 	    }
983 	} else if (CUR == '(') {
984 	    level++;
985 	} else if (CUR == '^') {
986             if ((NXT(1) == ')') || (NXT(1) == '(') || (NXT(1) == '^')) {
987                 NEXT;
988             }
989 	}
990         *cur++ = CUR;
991 	NEXT;
992     }
993     *cur = 0;
994 
995     if ((level != 0) && (CUR == 0)) {
996         xmlFree(name);
997 	xmlFree(buffer);
998 	XP_ERROR(XPTR_SYNTAX_ERROR);
999     }
1000 
1001     if (xmlStrEqual(name, (xmlChar *) "xpointer")) {
1002 	const xmlChar *left = CUR_PTR;
1003 
1004 	CUR_PTR = buffer;
1005 	/*
1006 	 * To evaluate an xpointer scheme element (4.3) we need:
1007 	 *   context initialized to the root
1008 	 *   context position initalized to 1
1009 	 *   context size initialized to 1
1010 	 */
1011 	ctxt->context->node = (xmlNodePtr)ctxt->context->doc;
1012 	ctxt->context->proximityPosition = 1;
1013 	ctxt->context->contextSize = 1;
1014 	xmlXPathEvalExpr(ctxt);
1015 	CUR_PTR=left;
1016     } else if (xmlStrEqual(name, (xmlChar *) "element")) {
1017 	const xmlChar *left = CUR_PTR;
1018 	xmlChar *name2;
1019 
1020 	CUR_PTR = buffer;
1021 	if (buffer[0] == '/') {
1022 	    xmlXPathRoot(ctxt);
1023 	    xmlXPtrEvalChildSeq(ctxt, NULL);
1024 	} else {
1025 	    name2 = xmlXPathParseName(ctxt);
1026 	    if (name2 == NULL) {
1027 		CUR_PTR = left;
1028 		xmlFree(buffer);
1029                 xmlFree(name);
1030 		XP_ERROR(XPATH_EXPR_ERROR);
1031 	    }
1032 	    xmlXPtrEvalChildSeq(ctxt, name2);
1033 	}
1034 	CUR_PTR = left;
1035 #ifdef XPTR_XMLNS_SCHEME
1036     } else if (xmlStrEqual(name, (xmlChar *) "xmlns")) {
1037 	const xmlChar *left = CUR_PTR;
1038 	xmlChar *prefix;
1039 	xmlChar *URI;
1040 	xmlURIPtr value;
1041 
1042 	CUR_PTR = buffer;
1043         prefix = xmlXPathParseNCName(ctxt);
1044 	if (prefix == NULL) {
1045 	    xmlFree(buffer);
1046 	    xmlFree(name);
1047 	    XP_ERROR(XPTR_SYNTAX_ERROR);
1048 	}
1049 	SKIP_BLANKS;
1050 	if (CUR != '=') {
1051 	    xmlFree(prefix);
1052 	    xmlFree(buffer);
1053 	    xmlFree(name);
1054 	    XP_ERROR(XPTR_SYNTAX_ERROR);
1055 	}
1056 	NEXT;
1057 	SKIP_BLANKS;
1058 	/* @@ check escaping in the XPointer WD */
1059 
1060 	value = xmlParseURI((const char *)ctxt->cur);
1061 	if (value == NULL) {
1062 	    xmlFree(prefix);
1063 	    xmlFree(buffer);
1064 	    xmlFree(name);
1065 	    XP_ERROR(XPTR_SYNTAX_ERROR);
1066 	}
1067 	URI = xmlSaveUri(value);
1068 	xmlFreeURI(value);
1069 	if (URI == NULL) {
1070 	    xmlFree(prefix);
1071 	    xmlFree(buffer);
1072 	    xmlFree(name);
1073 	    XP_ERROR(XPATH_MEMORY_ERROR);
1074 	}
1075 
1076 	xmlXPathRegisterNs(ctxt->context, prefix, URI);
1077 	CUR_PTR = left;
1078 	xmlFree(URI);
1079 	xmlFree(prefix);
1080 #endif /* XPTR_XMLNS_SCHEME */
1081     } else {
1082         xmlXPtrErr(ctxt, XML_XPTR_UNKNOWN_SCHEME,
1083 		   "unsupported scheme '%s'\n", name);
1084     }
1085     xmlFree(buffer);
1086     xmlFree(name);
1087 }
1088 
1089 /**
1090  * xmlXPtrEvalFullXPtr:
1091  * @ctxt:  the XPointer Parser context
1092  * @name:  the preparsed Scheme for the first XPtrPart
1093  *
1094  * FullXPtr ::= XPtrPart (S? XPtrPart)*
1095  *
1096  * As the specs says:
1097  * -----------
1098  * When multiple XPtrParts are provided, they must be evaluated in
1099  * left-to-right order. If evaluation of one part fails, the nexti
1100  * is evaluated. The following conditions cause XPointer part failure:
1101  *
1102  * - An unknown scheme
1103  * - A scheme that does not locate any sub-resource present in the resource
1104  * - A scheme that is not applicable to the media type of the resource
1105  *
1106  * The XPointer application must consume a failed XPointer part and
1107  * attempt to evaluate the next one, if any. The result of the first
1108  * XPointer part whose evaluation succeeds is taken to be the fragment
1109  * located by the XPointer as a whole. If all the parts fail, the result
1110  * for the XPointer as a whole is a sub-resource error.
1111  * -----------
1112  *
1113  * Parse and evaluate a Full XPtr i.e. possibly a cascade of XPath based
1114  * expressions or other schemes.
1115  */
1116 static void
xmlXPtrEvalFullXPtr(xmlXPathParserContextPtr ctxt,xmlChar * name)1117 xmlXPtrEvalFullXPtr(xmlXPathParserContextPtr ctxt, xmlChar *name) {
1118     if (name == NULL)
1119     name = xmlXPathParseName(ctxt);
1120     if (name == NULL)
1121 	XP_ERROR(XPATH_EXPR_ERROR);
1122     while (name != NULL) {
1123 	ctxt->error = XPATH_EXPRESSION_OK;
1124 	xmlXPtrEvalXPtrPart(ctxt, name);
1125 
1126 	/* in case of syntax error, break here */
1127 	if ((ctxt->error != XPATH_EXPRESSION_OK) &&
1128             (ctxt->error != XML_XPTR_UNKNOWN_SCHEME))
1129 	    return;
1130 
1131 	/*
1132 	 * If the returned value is a non-empty nodeset
1133 	 * or location set, return here.
1134 	 */
1135 	if (ctxt->value != NULL) {
1136 	    xmlXPathObjectPtr obj = ctxt->value;
1137 
1138 	    switch (obj->type) {
1139 		case XPATH_LOCATIONSET: {
1140 		    xmlLocationSetPtr loc = ctxt->value->user;
1141 		    if ((loc != NULL) && (loc->locNr > 0))
1142 			return;
1143 		    break;
1144 		}
1145 		case XPATH_NODESET: {
1146 		    xmlNodeSetPtr loc = ctxt->value->nodesetval;
1147 		    if ((loc != NULL) && (loc->nodeNr > 0))
1148 			return;
1149 		    break;
1150 		}
1151 		default:
1152 		    break;
1153 	    }
1154 
1155 	    /*
1156 	     * Evaluating to improper values is equivalent to
1157 	     * a sub-resource error, clean-up the stack
1158 	     */
1159 	    do {
1160 		obj = valuePop(ctxt);
1161 		if (obj != NULL) {
1162 		    xmlXPathFreeObject(obj);
1163 		}
1164 	    } while (obj != NULL);
1165 	}
1166 
1167 	/*
1168 	 * Is there another XPointer part.
1169 	 */
1170 	SKIP_BLANKS;
1171 	name = xmlXPathParseName(ctxt);
1172     }
1173 }
1174 
1175 /**
1176  * xmlXPtrEvalChildSeq:
1177  * @ctxt:  the XPointer Parser context
1178  * @name:  a possible ID name of the child sequence
1179  *
1180  *  ChildSeq ::= '/1' ('/' [0-9]*)*
1181  *             | Name ('/' [0-9]*)+
1182  *
1183  * Parse and evaluate a Child Sequence. This routine also handle the
1184  * case of a Bare Name used to get a document ID.
1185  */
1186 static void
xmlXPtrEvalChildSeq(xmlXPathParserContextPtr ctxt,xmlChar * name)1187 xmlXPtrEvalChildSeq(xmlXPathParserContextPtr ctxt, xmlChar *name) {
1188     /*
1189      * XPointer don't allow by syntax to address in multirooted trees
1190      * this might prove useful in some cases, warn about it.
1191      */
1192     if ((name == NULL) && (CUR == '/') && (NXT(1) != '1')) {
1193         xmlXPtrErr(ctxt, XML_XPTR_CHILDSEQ_START,
1194 		   "warning: ChildSeq not starting by /1\n", NULL);
1195     }
1196 
1197     if (name != NULL) {
1198 	valuePush(ctxt, xmlXPathNewString(name));
1199 	xmlFree(name);
1200 	xmlXPathIdFunction(ctxt, 1);
1201 	CHECK_ERROR;
1202     }
1203 
1204     while (CUR == '/') {
1205 	int child = 0, overflow = 0;
1206 	NEXT;
1207 
1208 	while ((CUR >= '0') && (CUR <= '9')) {
1209             int d = CUR - '0';
1210             if (child > INT_MAX / 10)
1211                 overflow = 1;
1212             else
1213                 child *= 10;
1214             if (child > INT_MAX - d)
1215                 overflow = 1;
1216             else
1217                 child += d;
1218 	    NEXT;
1219 	}
1220         if (overflow)
1221             child = 0;
1222 	xmlXPtrGetChildNo(ctxt, child);
1223     }
1224 }
1225 
1226 
1227 /**
1228  * xmlXPtrEvalXPointer:
1229  * @ctxt:  the XPointer Parser context
1230  *
1231  *  XPointer ::= Name
1232  *             | ChildSeq
1233  *             | FullXPtr
1234  *
1235  * Parse and evaluate an XPointer
1236  */
1237 static void
xmlXPtrEvalXPointer(xmlXPathParserContextPtr ctxt)1238 xmlXPtrEvalXPointer(xmlXPathParserContextPtr ctxt) {
1239     if (ctxt->valueTab == NULL) {
1240 	/* Allocate the value stack */
1241 	ctxt->valueTab = (xmlXPathObjectPtr *)
1242 			 xmlMalloc(10 * sizeof(xmlXPathObjectPtr));
1243 	if (ctxt->valueTab == NULL) {
1244 	    xmlXPtrErrMemory("allocating evaluation context");
1245 	    return;
1246 	}
1247 	ctxt->valueNr = 0;
1248 	ctxt->valueMax = 10;
1249 	ctxt->value = NULL;
1250 	ctxt->valueFrame = 0;
1251     }
1252     SKIP_BLANKS;
1253     if (CUR == '/') {
1254 	xmlXPathRoot(ctxt);
1255         xmlXPtrEvalChildSeq(ctxt, NULL);
1256     } else {
1257 	xmlChar *name;
1258 
1259 	name = xmlXPathParseName(ctxt);
1260 	if (name == NULL)
1261 	    XP_ERROR(XPATH_EXPR_ERROR);
1262 	if (CUR == '(') {
1263 	    xmlXPtrEvalFullXPtr(ctxt, name);
1264 	    /* Short evaluation */
1265 	    return;
1266 	} else {
1267 	    /* this handle both Bare Names and Child Sequences */
1268 	    xmlXPtrEvalChildSeq(ctxt, name);
1269 	}
1270     }
1271     SKIP_BLANKS;
1272     if (CUR != 0)
1273 	XP_ERROR(XPATH_EXPR_ERROR);
1274 }
1275 
1276 
1277 /************************************************************************
1278  *									*
1279  *			General routines				*
1280  *									*
1281  ************************************************************************/
1282 
1283 static
1284 void xmlXPtrStringRangeFunction(xmlXPathParserContextPtr ctxt, int nargs);
1285 static
1286 void xmlXPtrStartPointFunction(xmlXPathParserContextPtr ctxt, int nargs);
1287 static
1288 void xmlXPtrEndPointFunction(xmlXPathParserContextPtr ctxt, int nargs);
1289 static
1290 void xmlXPtrHereFunction(xmlXPathParserContextPtr ctxt, int nargs);
1291 static
1292 void xmlXPtrOriginFunction(xmlXPathParserContextPtr ctxt, int nargs);
1293 static
1294 void xmlXPtrRangeInsideFunction(xmlXPathParserContextPtr ctxt, int nargs);
1295 static
1296 void xmlXPtrRangeFunction(xmlXPathParserContextPtr ctxt, int nargs);
1297 
1298 /**
1299  * xmlXPtrNewContext:
1300  * @doc:  the XML document
1301  * @here:  the node that directly contains the XPointer being evaluated or NULL
1302  * @origin:  the element from which a user or program initiated traversal of
1303  *           the link, or NULL.
1304  *
1305  * Create a new XPointer context
1306  *
1307  * Returns the xmlXPathContext just allocated.
1308  */
1309 xmlXPathContextPtr
xmlXPtrNewContext(xmlDocPtr doc,xmlNodePtr here,xmlNodePtr origin)1310 xmlXPtrNewContext(xmlDocPtr doc, xmlNodePtr here, xmlNodePtr origin) {
1311     xmlXPathContextPtr ret;
1312 
1313     ret = xmlXPathNewContext(doc);
1314     if (ret == NULL)
1315 	return(ret);
1316     ret->xptr = 1;
1317     ret->here = here;
1318     ret->origin = origin;
1319 
1320     xmlXPathRegisterFunc(ret, (xmlChar *)"range",
1321 	                 xmlXPtrRangeFunction);
1322     xmlXPathRegisterFunc(ret, (xmlChar *)"range-inside",
1323 	                 xmlXPtrRangeInsideFunction);
1324     xmlXPathRegisterFunc(ret, (xmlChar *)"string-range",
1325 	                 xmlXPtrStringRangeFunction);
1326     xmlXPathRegisterFunc(ret, (xmlChar *)"start-point",
1327 	                 xmlXPtrStartPointFunction);
1328     xmlXPathRegisterFunc(ret, (xmlChar *)"end-point",
1329 	                 xmlXPtrEndPointFunction);
1330     xmlXPathRegisterFunc(ret, (xmlChar *)"here",
1331 	                 xmlXPtrHereFunction);
1332     xmlXPathRegisterFunc(ret, (xmlChar *)" origin",
1333 	                 xmlXPtrOriginFunction);
1334 
1335     return(ret);
1336 }
1337 
1338 /**
1339  * xmlXPtrEval:
1340  * @str:  the XPointer expression
1341  * @ctx:  the XPointer context
1342  *
1343  * Evaluate the XPath Location Path in the given context.
1344  *
1345  * Returns the xmlXPathObjectPtr resulting from the evaluation or NULL.
1346  *         the caller has to free the object.
1347  */
1348 xmlXPathObjectPtr
xmlXPtrEval(const xmlChar * str,xmlXPathContextPtr ctx)1349 xmlXPtrEval(const xmlChar *str, xmlXPathContextPtr ctx) {
1350     xmlXPathParserContextPtr ctxt;
1351     xmlXPathObjectPtr res = NULL, tmp;
1352     xmlXPathObjectPtr init = NULL;
1353     int stack = 0;
1354 
1355     xmlXPathInit();
1356 
1357     if ((ctx == NULL) || (str == NULL))
1358 	return(NULL);
1359 
1360     ctxt = xmlXPathNewParserContext(str, ctx);
1361     if (ctxt == NULL)
1362 	return(NULL);
1363     ctxt->xptr = 1;
1364     xmlXPtrEvalXPointer(ctxt);
1365 
1366     if ((ctxt->value != NULL) &&
1367 	(ctxt->value->type != XPATH_NODESET) &&
1368 	(ctxt->value->type != XPATH_LOCATIONSET)) {
1369         xmlXPtrErr(ctxt, XML_XPTR_EVAL_FAILED,
1370 		"xmlXPtrEval: evaluation failed to return a node set\n",
1371 		   NULL);
1372     } else {
1373 	res = valuePop(ctxt);
1374     }
1375 
1376     do {
1377         tmp = valuePop(ctxt);
1378 	if (tmp != NULL) {
1379 	    if (tmp != init) {
1380 		if (tmp->type == XPATH_NODESET) {
1381 		    /*
1382 		     * Evaluation may push a root nodeset which is unused
1383 		     */
1384 		    xmlNodeSetPtr set;
1385 		    set = tmp->nodesetval;
1386 		    if ((set == NULL) || (set->nodeNr != 1) ||
1387 			(set->nodeTab[0] != (xmlNodePtr) ctx->doc))
1388 			stack++;
1389 		} else
1390 		    stack++;
1391 	    }
1392 	    xmlXPathFreeObject(tmp);
1393         }
1394     } while (tmp != NULL);
1395     if (stack != 0) {
1396         xmlXPtrErr(ctxt, XML_XPTR_EXTRA_OBJECTS,
1397 		   "xmlXPtrEval: object(s) left on the eval stack\n",
1398 		   NULL);
1399     }
1400     if (ctxt->error != XPATH_EXPRESSION_OK) {
1401 	xmlXPathFreeObject(res);
1402 	res = NULL;
1403     }
1404 
1405     xmlXPathFreeParserContext(ctxt);
1406     return(res);
1407 }
1408 
1409 /**
1410  * xmlXPtrBuildRangeNodeList:
1411  * @range:  a range object
1412  *
1413  * Build a node list tree copy of the range
1414  *
1415  * Returns an xmlNodePtr list or NULL.
1416  *         the caller has to free the node tree.
1417  */
1418 static xmlNodePtr
xmlXPtrBuildRangeNodeList(xmlXPathObjectPtr range)1419 xmlXPtrBuildRangeNodeList(xmlXPathObjectPtr range) {
1420     /* pointers to generated nodes */
1421     xmlNodePtr list = NULL, last = NULL, parent = NULL, tmp;
1422     /* pointers to traversal nodes */
1423     xmlNodePtr start, cur, end;
1424     int index1, index2;
1425 
1426     if (range == NULL)
1427 	return(NULL);
1428     if (range->type != XPATH_RANGE)
1429 	return(NULL);
1430     start = (xmlNodePtr) range->user;
1431 
1432     if ((start == NULL) || (start->type == XML_NAMESPACE_DECL))
1433 	return(NULL);
1434     end = range->user2;
1435     if (end == NULL)
1436 	return(xmlCopyNode(start, 1));
1437     if (end->type == XML_NAMESPACE_DECL)
1438         return(NULL);
1439 
1440     cur = start;
1441     index1 = range->index;
1442     index2 = range->index2;
1443     while (cur != NULL) {
1444 	if (cur == end) {
1445 	    if (cur->type == XML_TEXT_NODE) {
1446 		const xmlChar *content = cur->content;
1447 		int len;
1448 
1449 		if (content == NULL) {
1450 		    tmp = xmlNewTextLen(NULL, 0);
1451 		} else {
1452 		    len = index2;
1453 		    if ((cur == start) && (index1 > 1)) {
1454 			content += (index1 - 1);
1455 			len -= (index1 - 1);
1456 			index1 = 0;
1457 		    } else {
1458 			len = index2;
1459 		    }
1460 		    tmp = xmlNewTextLen(content, len);
1461 		}
1462 		/* single sub text node selection */
1463 		if (list == NULL)
1464 		    return(tmp);
1465 		/* prune and return full set */
1466 		if (last != NULL)
1467 		    xmlAddNextSibling(last, tmp);
1468 		else
1469 		    xmlAddChild(parent, tmp);
1470 		return(list);
1471 	    } else {
1472 		tmp = xmlCopyNode(cur, 0);
1473 		if (list == NULL) {
1474 		    list = tmp;
1475 		    parent = tmp;
1476 		} else {
1477 		    if (last != NULL)
1478 			parent = xmlAddNextSibling(last, tmp);
1479 		    else
1480 			parent = xmlAddChild(parent, tmp);
1481 		}
1482 		last = NULL;
1483 
1484 		if (index2 > 1) {
1485 		    end = xmlXPtrGetNthChild(cur, index2 - 1);
1486 		    index2 = 0;
1487 		}
1488 		if ((cur == start) && (index1 > 1)) {
1489 		    cur = xmlXPtrGetNthChild(cur, index1 - 1);
1490 		    index1 = 0;
1491 		} else {
1492 		    cur = cur->children;
1493 		}
1494 		/*
1495 		 * Now gather the remaining nodes from cur to end
1496 		 */
1497 		continue; /* while */
1498 	    }
1499 	} else if ((cur == start) &&
1500 		   (list == NULL) /* looks superfluous but ... */ ) {
1501 	    if ((cur->type == XML_TEXT_NODE) ||
1502 		(cur->type == XML_CDATA_SECTION_NODE)) {
1503 		const xmlChar *content = cur->content;
1504 
1505 		if (content == NULL) {
1506 		    tmp = xmlNewTextLen(NULL, 0);
1507 		} else {
1508 		    if (index1 > 1) {
1509 			content += (index1 - 1);
1510 		    }
1511 		    tmp = xmlNewText(content);
1512 		}
1513 		last = list = tmp;
1514 	    } else {
1515 		if ((cur == start) && (index1 > 1)) {
1516 		    tmp = xmlCopyNode(cur, 0);
1517 		    list = tmp;
1518 		    parent = tmp;
1519 		    last = NULL;
1520 		    cur = xmlXPtrGetNthChild(cur, index1 - 1);
1521 		    index1 = 0;
1522 		    /*
1523 		     * Now gather the remaining nodes from cur to end
1524 		     */
1525 		    continue; /* while */
1526 		}
1527 		tmp = xmlCopyNode(cur, 1);
1528 		list = tmp;
1529 		parent = NULL;
1530 		last = tmp;
1531 	    }
1532 	} else {
1533 	    tmp = NULL;
1534 	    switch (cur->type) {
1535 		case XML_DTD_NODE:
1536 		case XML_ELEMENT_DECL:
1537 		case XML_ATTRIBUTE_DECL:
1538 		case XML_ENTITY_NODE:
1539 		    /* Do not copy DTD informations */
1540 		    break;
1541 		case XML_ENTITY_DECL:
1542 		    TODO /* handle crossing entities -> stack needed */
1543 		    break;
1544 		case XML_XINCLUDE_START:
1545 		case XML_XINCLUDE_END:
1546 		    /* don't consider it part of the tree content */
1547 		    break;
1548 		case XML_ATTRIBUTE_NODE:
1549 		    /* Humm, should not happen ! */
1550 		    STRANGE
1551 		    break;
1552 		default:
1553 		    tmp = xmlCopyNode(cur, 1);
1554 		    break;
1555 	    }
1556 	    if (tmp != NULL) {
1557 		if ((list == NULL) || ((last == NULL) && (parent == NULL)))  {
1558 		    STRANGE
1559 		    return(NULL);
1560 		}
1561 		if (last != NULL)
1562 		    xmlAddNextSibling(last, tmp);
1563 		else {
1564 		    last = xmlAddChild(parent, tmp);
1565 		}
1566 	    }
1567 	}
1568 	/*
1569 	 * Skip to next node in document order
1570 	 */
1571 	if ((list == NULL) || ((last == NULL) && (parent == NULL)))  {
1572 	    STRANGE
1573 	    return(NULL);
1574 	}
1575 	cur = xmlXPtrAdvanceNode(cur, NULL);
1576     }
1577     return(list);
1578 }
1579 
1580 /**
1581  * xmlXPtrBuildNodeList:
1582  * @obj:  the XPointer result from the evaluation.
1583  *
1584  * Build a node list tree copy of the XPointer result.
1585  * This will drop Attributes and Namespace declarations.
1586  *
1587  * Returns an xmlNodePtr list or NULL.
1588  *         the caller has to free the node tree.
1589  */
1590 xmlNodePtr
xmlXPtrBuildNodeList(xmlXPathObjectPtr obj)1591 xmlXPtrBuildNodeList(xmlXPathObjectPtr obj) {
1592     xmlNodePtr list = NULL, last = NULL;
1593     int i;
1594 
1595     if (obj == NULL)
1596 	return(NULL);
1597     switch (obj->type) {
1598         case XPATH_NODESET: {
1599 	    xmlNodeSetPtr set = obj->nodesetval;
1600 	    if (set == NULL)
1601 		return(NULL);
1602 	    for (i = 0;i < set->nodeNr;i++) {
1603 		if (set->nodeTab[i] == NULL)
1604 		    continue;
1605 		switch (set->nodeTab[i]->type) {
1606 		    case XML_TEXT_NODE:
1607 		    case XML_CDATA_SECTION_NODE:
1608 		    case XML_ELEMENT_NODE:
1609 		    case XML_ENTITY_REF_NODE:
1610 		    case XML_ENTITY_NODE:
1611 		    case XML_PI_NODE:
1612 		    case XML_COMMENT_NODE:
1613 		    case XML_DOCUMENT_NODE:
1614 		    case XML_HTML_DOCUMENT_NODE:
1615 #ifdef LIBXML_DOCB_ENABLED
1616 		    case XML_DOCB_DOCUMENT_NODE:
1617 #endif
1618 		    case XML_XINCLUDE_START:
1619 		    case XML_XINCLUDE_END:
1620 			break;
1621 		    case XML_ATTRIBUTE_NODE:
1622 		    case XML_NAMESPACE_DECL:
1623 		    case XML_DOCUMENT_TYPE_NODE:
1624 		    case XML_DOCUMENT_FRAG_NODE:
1625 		    case XML_NOTATION_NODE:
1626 		    case XML_DTD_NODE:
1627 		    case XML_ELEMENT_DECL:
1628 		    case XML_ATTRIBUTE_DECL:
1629 		    case XML_ENTITY_DECL:
1630 			continue; /* for */
1631 		}
1632 		if (last == NULL)
1633 		    list = last = xmlCopyNode(set->nodeTab[i], 1);
1634 		else {
1635 		    xmlAddNextSibling(last, xmlCopyNode(set->nodeTab[i], 1));
1636 		    if (last->next != NULL)
1637 			last = last->next;
1638 		}
1639 	    }
1640 	    break;
1641 	}
1642 	case XPATH_LOCATIONSET: {
1643 	    xmlLocationSetPtr set = (xmlLocationSetPtr) obj->user;
1644 	    if (set == NULL)
1645 		return(NULL);
1646 	    for (i = 0;i < set->locNr;i++) {
1647 		if (last == NULL)
1648 		    list = last = xmlXPtrBuildNodeList(set->locTab[i]);
1649 		else
1650 		    xmlAddNextSibling(last,
1651 			    xmlXPtrBuildNodeList(set->locTab[i]));
1652 		if (last != NULL) {
1653 		    while (last->next != NULL)
1654 			last = last->next;
1655 		}
1656 	    }
1657 	    break;
1658 	}
1659 	case XPATH_RANGE:
1660 	    return(xmlXPtrBuildRangeNodeList(obj));
1661 	case XPATH_POINT:
1662 	    return(xmlCopyNode(obj->user, 0));
1663 	default:
1664 	    break;
1665     }
1666     return(list);
1667 }
1668 
1669 /************************************************************************
1670  *									*
1671  *			XPointer functions				*
1672  *									*
1673  ************************************************************************/
1674 
1675 /**
1676  * xmlXPtrNbLocChildren:
1677  * @node:  an xmlNodePtr
1678  *
1679  * Count the number of location children of @node or the length of the
1680  * string value in case of text/PI/Comments nodes
1681  *
1682  * Returns the number of location children
1683  */
1684 static int
xmlXPtrNbLocChildren(xmlNodePtr node)1685 xmlXPtrNbLocChildren(xmlNodePtr node) {
1686     int ret = 0;
1687     if (node == NULL)
1688 	return(-1);
1689     switch (node->type) {
1690         case XML_HTML_DOCUMENT_NODE:
1691         case XML_DOCUMENT_NODE:
1692         case XML_ELEMENT_NODE:
1693 	    node = node->children;
1694 	    while (node != NULL) {
1695 		if (node->type == XML_ELEMENT_NODE)
1696 		    ret++;
1697 		node = node->next;
1698 	    }
1699 	    break;
1700         case XML_ATTRIBUTE_NODE:
1701 	    return(-1);
1702 
1703         case XML_PI_NODE:
1704         case XML_COMMENT_NODE:
1705         case XML_TEXT_NODE:
1706         case XML_CDATA_SECTION_NODE:
1707         case XML_ENTITY_REF_NODE:
1708 	    ret = xmlStrlen(node->content);
1709 	    break;
1710 	default:
1711 	    return(-1);
1712     }
1713     return(ret);
1714 }
1715 
1716 /**
1717  * xmlXPtrHereFunction:
1718  * @ctxt:  the XPointer Parser context
1719  * @nargs:  the number of args
1720  *
1721  * Function implementing here() operation
1722  * as described in 5.4.3
1723  */
1724 static void
xmlXPtrHereFunction(xmlXPathParserContextPtr ctxt,int nargs)1725 xmlXPtrHereFunction(xmlXPathParserContextPtr ctxt, int nargs) {
1726     CHECK_ARITY(0);
1727 
1728     if (ctxt->context->here == NULL)
1729 	XP_ERROR(XPTR_SYNTAX_ERROR);
1730 
1731     valuePush(ctxt, xmlXPtrNewLocationSetNodes(ctxt->context->here, NULL));
1732 }
1733 
1734 /**
1735  * xmlXPtrOriginFunction:
1736  * @ctxt:  the XPointer Parser context
1737  * @nargs:  the number of args
1738  *
1739  * Function implementing origin() operation
1740  * as described in 5.4.3
1741  */
1742 static void
xmlXPtrOriginFunction(xmlXPathParserContextPtr ctxt,int nargs)1743 xmlXPtrOriginFunction(xmlXPathParserContextPtr ctxt, int nargs) {
1744     CHECK_ARITY(0);
1745 
1746     if (ctxt->context->origin == NULL)
1747 	XP_ERROR(XPTR_SYNTAX_ERROR);
1748 
1749     valuePush(ctxt, xmlXPtrNewLocationSetNodes(ctxt->context->origin, NULL));
1750 }
1751 
1752 /**
1753  * xmlXPtrStartPointFunction:
1754  * @ctxt:  the XPointer Parser context
1755  * @nargs:  the number of args
1756  *
1757  * Function implementing start-point() operation
1758  * as described in 5.4.3
1759  * ----------------
1760  * location-set start-point(location-set)
1761  *
1762  * For each location x in the argument location-set, start-point adds a
1763  * location of type point to the result location-set. That point represents
1764  * the start point of location x and is determined by the following rules:
1765  *
1766  * - If x is of type point, the start point is x.
1767  * - If x is of type range, the start point is the start point of x.
1768  * - If x is of type root, element, text, comment, or processing instruction,
1769  * - the container node of the start point is x and the index is 0.
1770  * - If x is of type attribute or namespace, the function must signal a
1771  *   syntax error.
1772  * ----------------
1773  *
1774  */
1775 static void
xmlXPtrStartPointFunction(xmlXPathParserContextPtr ctxt,int nargs)1776 xmlXPtrStartPointFunction(xmlXPathParserContextPtr ctxt, int nargs) {
1777     xmlXPathObjectPtr tmp, obj, point;
1778     xmlLocationSetPtr newset = NULL;
1779     xmlLocationSetPtr oldset = NULL;
1780 
1781     CHECK_ARITY(1);
1782     if ((ctxt->value == NULL) ||
1783 	((ctxt->value->type != XPATH_LOCATIONSET) &&
1784 	 (ctxt->value->type != XPATH_NODESET)))
1785         XP_ERROR(XPATH_INVALID_TYPE)
1786 
1787     obj = valuePop(ctxt);
1788     if (obj->type == XPATH_NODESET) {
1789 	/*
1790 	 * First convert to a location set
1791 	 */
1792 	tmp = xmlXPtrNewLocationSetNodeSet(obj->nodesetval);
1793 	xmlXPathFreeObject(obj);
1794 	if (tmp == NULL)
1795             XP_ERROR(XPATH_MEMORY_ERROR)
1796 	obj = tmp;
1797     }
1798 
1799     newset = xmlXPtrLocationSetCreate(NULL);
1800     if (newset == NULL) {
1801 	xmlXPathFreeObject(obj);
1802         XP_ERROR(XPATH_MEMORY_ERROR);
1803     }
1804     oldset = (xmlLocationSetPtr) obj->user;
1805     if (oldset != NULL) {
1806 	int i;
1807 
1808 	for (i = 0; i < oldset->locNr; i++) {
1809 	    tmp = oldset->locTab[i];
1810 	    if (tmp == NULL)
1811 		continue;
1812 	    point = NULL;
1813 	    switch (tmp->type) {
1814 		case XPATH_POINT:
1815 		    point = xmlXPtrNewPoint(tmp->user, tmp->index);
1816 		    break;
1817 		case XPATH_RANGE: {
1818 		    xmlNodePtr node = tmp->user;
1819 		    if (node != NULL) {
1820 			if ((node->type == XML_ATTRIBUTE_NODE) ||
1821                             (node->type == XML_NAMESPACE_DECL)) {
1822 			    xmlXPathFreeObject(obj);
1823 			    xmlXPtrFreeLocationSet(newset);
1824 			    XP_ERROR(XPTR_SYNTAX_ERROR);
1825 			}
1826 			point = xmlXPtrNewPoint(node, tmp->index);
1827 		    }
1828 		    break;
1829 	        }
1830 		default:
1831 		    /*** Should we raise an error ?
1832 		    xmlXPathFreeObject(obj);
1833 		    xmlXPathFreeObject(newset);
1834 		    XP_ERROR(XPATH_INVALID_TYPE)
1835 		    ***/
1836 		    break;
1837 	    }
1838             if (point != NULL)
1839 		xmlXPtrLocationSetAdd(newset, point);
1840 	}
1841     }
1842     xmlXPathFreeObject(obj);
1843     valuePush(ctxt, xmlXPtrWrapLocationSet(newset));
1844 }
1845 
1846 /**
1847  * xmlXPtrEndPointFunction:
1848  * @ctxt:  the XPointer Parser context
1849  * @nargs:  the number of args
1850  *
1851  * Function implementing end-point() operation
1852  * as described in 5.4.3
1853  * ----------------------------
1854  * location-set end-point(location-set)
1855  *
1856  * For each location x in the argument location-set, end-point adds a
1857  * location of type point to the result location-set. That point represents
1858  * the end point of location x and is determined by the following rules:
1859  *
1860  * - If x is of type point, the resulting point is x.
1861  * - If x is of type range, the resulting point is the end point of x.
1862  * - If x is of type root or element, the container node of the resulting
1863  *   point is x and the index is the number of location children of x.
1864  * - If x is of type text, comment, or processing instruction, the container
1865  *   node of the resulting point is x and the index is the length of the
1866  *   string-value of x.
1867  * - If x is of type attribute or namespace, the function must signal a
1868  *   syntax error.
1869  * ----------------------------
1870  */
1871 static void
xmlXPtrEndPointFunction(xmlXPathParserContextPtr ctxt,int nargs)1872 xmlXPtrEndPointFunction(xmlXPathParserContextPtr ctxt, int nargs) {
1873     xmlXPathObjectPtr tmp, obj, point;
1874     xmlLocationSetPtr newset = NULL;
1875     xmlLocationSetPtr oldset = NULL;
1876 
1877     CHECK_ARITY(1);
1878     if ((ctxt->value == NULL) ||
1879 	((ctxt->value->type != XPATH_LOCATIONSET) &&
1880 	 (ctxt->value->type != XPATH_NODESET)))
1881         XP_ERROR(XPATH_INVALID_TYPE)
1882 
1883     obj = valuePop(ctxt);
1884     if (obj->type == XPATH_NODESET) {
1885 	/*
1886 	 * First convert to a location set
1887 	 */
1888 	tmp = xmlXPtrNewLocationSetNodeSet(obj->nodesetval);
1889 	xmlXPathFreeObject(obj);
1890 	if (tmp == NULL)
1891             XP_ERROR(XPATH_MEMORY_ERROR)
1892 	obj = tmp;
1893     }
1894 
1895     newset = xmlXPtrLocationSetCreate(NULL);
1896     if (newset == NULL) {
1897 	xmlXPathFreeObject(obj);
1898         XP_ERROR(XPATH_MEMORY_ERROR);
1899     }
1900     oldset = (xmlLocationSetPtr) obj->user;
1901     if (oldset != NULL) {
1902 	int i;
1903 
1904 	for (i = 0; i < oldset->locNr; i++) {
1905 	    tmp = oldset->locTab[i];
1906 	    if (tmp == NULL)
1907 		continue;
1908 	    point = NULL;
1909 	    switch (tmp->type) {
1910 		case XPATH_POINT:
1911 		    point = xmlXPtrNewPoint(tmp->user, tmp->index);
1912 		    break;
1913 		case XPATH_RANGE: {
1914 		    xmlNodePtr node = tmp->user2;
1915 		    if (node != NULL) {
1916 			if ((node->type == XML_ATTRIBUTE_NODE) ||
1917                             (node->type == XML_NAMESPACE_DECL)) {
1918 			    xmlXPathFreeObject(obj);
1919 			    xmlXPtrFreeLocationSet(newset);
1920 			    XP_ERROR(XPTR_SYNTAX_ERROR);
1921 			}
1922 			point = xmlXPtrNewPoint(node, tmp->index2);
1923 		    } else if (tmp->user == NULL) {
1924 			point = xmlXPtrNewPoint(node,
1925 				       xmlXPtrNbLocChildren(node));
1926 		    }
1927 		    break;
1928 	        }
1929 		default:
1930 		    /*** Should we raise an error ?
1931 		    xmlXPathFreeObject(obj);
1932 		    xmlXPathFreeObject(newset);
1933 		    XP_ERROR(XPATH_INVALID_TYPE)
1934 		    ***/
1935 		    break;
1936 	    }
1937             if (point != NULL)
1938 		xmlXPtrLocationSetAdd(newset, point);
1939 	}
1940     }
1941     xmlXPathFreeObject(obj);
1942     valuePush(ctxt, xmlXPtrWrapLocationSet(newset));
1943 }
1944 
1945 
1946 /**
1947  * xmlXPtrCoveringRange:
1948  * @ctxt:  the XPointer Parser context
1949  * @loc:  the location for which the covering range must be computed
1950  *
1951  * A covering range is a range that wholly encompasses a location
1952  * Section 5.3.3. Covering Ranges for All Location Types
1953  *        http://www.w3.org/TR/xptr#N2267
1954  *
1955  * Returns a new location or NULL in case of error
1956  */
1957 static xmlXPathObjectPtr
xmlXPtrCoveringRange(xmlXPathParserContextPtr ctxt,xmlXPathObjectPtr loc)1958 xmlXPtrCoveringRange(xmlXPathParserContextPtr ctxt, xmlXPathObjectPtr loc) {
1959     if (loc == NULL)
1960 	return(NULL);
1961     if ((ctxt == NULL) || (ctxt->context == NULL) ||
1962 	(ctxt->context->doc == NULL))
1963 	return(NULL);
1964     switch (loc->type) {
1965         case XPATH_POINT:
1966 	    return(xmlXPtrNewRange(loc->user, loc->index,
1967 			           loc->user, loc->index));
1968         case XPATH_RANGE:
1969 	    if (loc->user2 != NULL) {
1970 		return(xmlXPtrNewRange(loc->user, loc->index,
1971 			              loc->user2, loc->index2));
1972 	    } else {
1973 		xmlNodePtr node = (xmlNodePtr) loc->user;
1974 		if (node == (xmlNodePtr) ctxt->context->doc) {
1975 		    return(xmlXPtrNewRange(node, 0, node,
1976 					   xmlXPtrGetArity(node)));
1977 		} else {
1978 		    switch (node->type) {
1979 			case XML_ATTRIBUTE_NODE:
1980 			/* !!! our model is slightly different than XPath */
1981 			    return(xmlXPtrNewRange(node, 0, node,
1982 					           xmlXPtrGetArity(node)));
1983 			case XML_ELEMENT_NODE:
1984 			case XML_TEXT_NODE:
1985 			case XML_CDATA_SECTION_NODE:
1986 			case XML_ENTITY_REF_NODE:
1987 			case XML_PI_NODE:
1988 			case XML_COMMENT_NODE:
1989 			case XML_DOCUMENT_NODE:
1990 			case XML_NOTATION_NODE:
1991 			case XML_HTML_DOCUMENT_NODE: {
1992 			    int indx = xmlXPtrGetIndex(node);
1993 
1994 			    node = node->parent;
1995 			    return(xmlXPtrNewRange(node, indx - 1,
1996 					           node, indx + 1));
1997 			}
1998 			default:
1999 			    return(NULL);
2000 		    }
2001 		}
2002 	    }
2003 	default:
2004 	    TODO /* missed one case ??? */
2005     }
2006     return(NULL);
2007 }
2008 
2009 /**
2010  * xmlXPtrRangeFunction:
2011  * @ctxt:  the XPointer Parser context
2012  * @nargs:  the number of args
2013  *
2014  * Function implementing the range() function 5.4.3
2015  *  location-set range(location-set )
2016  *
2017  *  The range function returns ranges covering the locations in
2018  *  the argument location-set. For each location x in the argument
2019  *  location-set, a range location representing the covering range of
2020  *  x is added to the result location-set.
2021  */
2022 static void
xmlXPtrRangeFunction(xmlXPathParserContextPtr ctxt,int nargs)2023 xmlXPtrRangeFunction(xmlXPathParserContextPtr ctxt, int nargs) {
2024     int i;
2025     xmlXPathObjectPtr set;
2026     xmlLocationSetPtr oldset;
2027     xmlLocationSetPtr newset;
2028 
2029     CHECK_ARITY(1);
2030     if ((ctxt->value == NULL) ||
2031 	((ctxt->value->type != XPATH_LOCATIONSET) &&
2032 	 (ctxt->value->type != XPATH_NODESET)))
2033         XP_ERROR(XPATH_INVALID_TYPE)
2034 
2035     set = valuePop(ctxt);
2036     if (set->type == XPATH_NODESET) {
2037 	xmlXPathObjectPtr tmp;
2038 
2039 	/*
2040 	 * First convert to a location set
2041 	 */
2042 	tmp = xmlXPtrNewLocationSetNodeSet(set->nodesetval);
2043 	xmlXPathFreeObject(set);
2044 	if (tmp == NULL)
2045             XP_ERROR(XPATH_MEMORY_ERROR)
2046 	set = tmp;
2047     }
2048     oldset = (xmlLocationSetPtr) set->user;
2049 
2050     /*
2051      * The loop is to compute the covering range for each item and add it
2052      */
2053     newset = xmlXPtrLocationSetCreate(NULL);
2054     if (newset == NULL) {
2055 	xmlXPathFreeObject(set);
2056         XP_ERROR(XPATH_MEMORY_ERROR);
2057     }
2058     if (oldset != NULL) {
2059         for (i = 0;i < oldset->locNr;i++) {
2060             xmlXPtrLocationSetAdd(newset,
2061                     xmlXPtrCoveringRange(ctxt, oldset->locTab[i]));
2062         }
2063     }
2064 
2065     /*
2066      * Save the new value and cleanup
2067      */
2068     valuePush(ctxt, xmlXPtrWrapLocationSet(newset));
2069     xmlXPathFreeObject(set);
2070 }
2071 
2072 /**
2073  * xmlXPtrInsideRange:
2074  * @ctxt:  the XPointer Parser context
2075  * @loc:  the location for which the inside range must be computed
2076  *
2077  * A inside range is a range described in the range-inside() description
2078  *
2079  * Returns a new location or NULL in case of error
2080  */
2081 static xmlXPathObjectPtr
xmlXPtrInsideRange(xmlXPathParserContextPtr ctxt,xmlXPathObjectPtr loc)2082 xmlXPtrInsideRange(xmlXPathParserContextPtr ctxt, xmlXPathObjectPtr loc) {
2083     if (loc == NULL)
2084 	return(NULL);
2085     if ((ctxt == NULL) || (ctxt->context == NULL) ||
2086 	(ctxt->context->doc == NULL))
2087 	return(NULL);
2088     switch (loc->type) {
2089         case XPATH_POINT: {
2090 	    xmlNodePtr node = (xmlNodePtr) loc->user;
2091 	    switch (node->type) {
2092 		case XML_PI_NODE:
2093 		case XML_COMMENT_NODE:
2094 		case XML_TEXT_NODE:
2095 		case XML_CDATA_SECTION_NODE: {
2096 		    if (node->content == NULL) {
2097 			return(xmlXPtrNewRange(node, 0, node, 0));
2098 		    } else {
2099 			return(xmlXPtrNewRange(node, 0, node,
2100 					       xmlStrlen(node->content)));
2101 		    }
2102 		}
2103 		case XML_ATTRIBUTE_NODE:
2104 		case XML_ELEMENT_NODE:
2105 		case XML_ENTITY_REF_NODE:
2106 		case XML_DOCUMENT_NODE:
2107 		case XML_NOTATION_NODE:
2108 		case XML_HTML_DOCUMENT_NODE: {
2109 		    return(xmlXPtrNewRange(node, 0, node,
2110 					   xmlXPtrGetArity(node)));
2111 		}
2112 		default:
2113 		    break;
2114 	    }
2115 	    return(NULL);
2116 	}
2117         case XPATH_RANGE: {
2118 	    xmlNodePtr node = (xmlNodePtr) loc->user;
2119 	    if (loc->user2 != NULL) {
2120 		return(xmlXPtrNewRange(node, loc->index,
2121 			               loc->user2, loc->index2));
2122 	    } else {
2123 		switch (node->type) {
2124 		    case XML_PI_NODE:
2125 		    case XML_COMMENT_NODE:
2126 		    case XML_TEXT_NODE:
2127 		    case XML_CDATA_SECTION_NODE: {
2128 			if (node->content == NULL) {
2129 			    return(xmlXPtrNewRange(node, 0, node, 0));
2130 			} else {
2131 			    return(xmlXPtrNewRange(node, 0, node,
2132 						   xmlStrlen(node->content)));
2133 			}
2134 		    }
2135 		    case XML_ATTRIBUTE_NODE:
2136 		    case XML_ELEMENT_NODE:
2137 		    case XML_ENTITY_REF_NODE:
2138 		    case XML_DOCUMENT_NODE:
2139 		    case XML_NOTATION_NODE:
2140 		    case XML_HTML_DOCUMENT_NODE: {
2141 			return(xmlXPtrNewRange(node, 0, node,
2142 					       xmlXPtrGetArity(node)));
2143 		    }
2144 		    default:
2145 			break;
2146 		}
2147 		return(NULL);
2148 	    }
2149         }
2150 	default:
2151 	    TODO /* missed one case ??? */
2152     }
2153     return(NULL);
2154 }
2155 
2156 /**
2157  * xmlXPtrRangeInsideFunction:
2158  * @ctxt:  the XPointer Parser context
2159  * @nargs:  the number of args
2160  *
2161  * Function implementing the range-inside() function 5.4.3
2162  *  location-set range-inside(location-set )
2163  *
2164  *  The range-inside function returns ranges covering the contents of
2165  *  the locations in the argument location-set. For each location x in
2166  *  the argument location-set, a range location is added to the result
2167  *  location-set. If x is a range location, then x is added to the
2168  *  result location-set. If x is not a range location, then x is used
2169  *  as the container location of the start and end points of the range
2170  *  location to be added; the index of the start point of the range is
2171  *  zero; if the end point is a character point then its index is the
2172  *  length of the string-value of x, and otherwise is the number of
2173  *  location children of x.
2174  *
2175  */
2176 static void
xmlXPtrRangeInsideFunction(xmlXPathParserContextPtr ctxt,int nargs)2177 xmlXPtrRangeInsideFunction(xmlXPathParserContextPtr ctxt, int nargs) {
2178     int i;
2179     xmlXPathObjectPtr set;
2180     xmlLocationSetPtr oldset;
2181     xmlLocationSetPtr newset;
2182 
2183     CHECK_ARITY(1);
2184     if ((ctxt->value == NULL) ||
2185 	((ctxt->value->type != XPATH_LOCATIONSET) &&
2186 	 (ctxt->value->type != XPATH_NODESET)))
2187         XP_ERROR(XPATH_INVALID_TYPE)
2188 
2189     set = valuePop(ctxt);
2190     if (set->type == XPATH_NODESET) {
2191 	xmlXPathObjectPtr tmp;
2192 
2193 	/*
2194 	 * First convert to a location set
2195 	 */
2196 	tmp = xmlXPtrNewLocationSetNodeSet(set->nodesetval);
2197 	xmlXPathFreeObject(set);
2198 	if (tmp == NULL)
2199 	     XP_ERROR(XPATH_MEMORY_ERROR)
2200 	set = tmp;
2201     }
2202     oldset = (xmlLocationSetPtr) set->user;
2203 
2204     /*
2205      * The loop is to compute the covering range for each item and add it
2206      */
2207     newset = xmlXPtrLocationSetCreate(NULL);
2208     if (newset == NULL) {
2209 	xmlXPathFreeObject(set);
2210         XP_ERROR(XPATH_MEMORY_ERROR);
2211     }
2212     for (i = 0;i < oldset->locNr;i++) {
2213 	xmlXPtrLocationSetAdd(newset,
2214 		xmlXPtrInsideRange(ctxt, oldset->locTab[i]));
2215     }
2216 
2217     /*
2218      * Save the new value and cleanup
2219      */
2220     valuePush(ctxt, xmlXPtrWrapLocationSet(newset));
2221     xmlXPathFreeObject(set);
2222 }
2223 
2224 /**
2225  * xmlXPtrRangeToFunction:
2226  * @ctxt:  the XPointer Parser context
2227  * @nargs:  the number of args
2228  *
2229  * Implement the range-to() XPointer function
2230  *
2231  * Obsolete. range-to is not a real function but a special type of location
2232  * step which is handled in xpath.c.
2233  */
2234 void
xmlXPtrRangeToFunction(xmlXPathParserContextPtr ctxt,int nargs ATTRIBUTE_UNUSED)2235 xmlXPtrRangeToFunction(xmlXPathParserContextPtr ctxt,
2236                        int nargs ATTRIBUTE_UNUSED) {
2237     XP_ERROR(XPATH_EXPR_ERROR);
2238 }
2239 
2240 /**
2241  * xmlXPtrAdvanceNode:
2242  * @cur:  the node
2243  * @level: incremented/decremented to show level in tree
2244  *
2245  * Advance to the next element or text node in document order
2246  * TODO: add a stack for entering/exiting entities
2247  *
2248  * Returns -1 in case of failure, 0 otherwise
2249  */
2250 xmlNodePtr
xmlXPtrAdvanceNode(xmlNodePtr cur,int * level)2251 xmlXPtrAdvanceNode(xmlNodePtr cur, int *level) {
2252 next:
2253     if ((cur == NULL) || (cur->type == XML_NAMESPACE_DECL))
2254 	return(NULL);
2255     if (cur->children != NULL) {
2256         cur = cur->children ;
2257 	if (level != NULL)
2258 	    (*level)++;
2259 	goto found;
2260     }
2261 skip:		/* This label should only be needed if something is wrong! */
2262     if (cur->next != NULL) {
2263 	cur = cur->next;
2264 	goto found;
2265     }
2266     do {
2267         cur = cur->parent;
2268 	if (level != NULL)
2269 	    (*level)--;
2270         if (cur == NULL) return(NULL);
2271         if (cur->next != NULL) {
2272 	    cur = cur->next;
2273 	    goto found;
2274 	}
2275     } while (cur != NULL);
2276 
2277 found:
2278     if ((cur->type != XML_ELEMENT_NODE) &&
2279 	(cur->type != XML_TEXT_NODE) &&
2280 	(cur->type != XML_DOCUMENT_NODE) &&
2281 	(cur->type != XML_HTML_DOCUMENT_NODE) &&
2282 	(cur->type != XML_CDATA_SECTION_NODE)) {
2283 	    if (cur->type == XML_ENTITY_REF_NODE) {	/* Shouldn't happen */
2284 		TODO
2285 		goto skip;
2286 	    }
2287 	    goto next;
2288 	}
2289     return(cur);
2290 }
2291 
2292 /**
2293  * xmlXPtrAdvanceChar:
2294  * @node:  the node
2295  * @indx:  the indx
2296  * @bytes:  the number of bytes
2297  *
2298  * Advance a point of the associated number of bytes (not UTF8 chars)
2299  *
2300  * Returns -1 in case of failure, 0 otherwise
2301  */
2302 static int
xmlXPtrAdvanceChar(xmlNodePtr * node,int * indx,int bytes)2303 xmlXPtrAdvanceChar(xmlNodePtr *node, int *indx, int bytes) {
2304     xmlNodePtr cur;
2305     int pos;
2306     int len;
2307 
2308     if ((node == NULL) || (indx == NULL))
2309 	return(-1);
2310     cur = *node;
2311     if ((cur == NULL) || (cur->type == XML_NAMESPACE_DECL))
2312 	return(-1);
2313     pos = *indx;
2314 
2315     while (bytes >= 0) {
2316 	/*
2317 	 * First position to the beginning of the first text node
2318 	 * corresponding to this point
2319 	 */
2320 	while ((cur != NULL) &&
2321 	       ((cur->type == XML_ELEMENT_NODE) ||
2322 	        (cur->type == XML_DOCUMENT_NODE) ||
2323 	        (cur->type == XML_HTML_DOCUMENT_NODE))) {
2324 	    if (pos > 0) {
2325 		cur = xmlXPtrGetNthChild(cur, pos);
2326 		pos = 0;
2327 	    } else {
2328 		cur = xmlXPtrAdvanceNode(cur, NULL);
2329 		pos = 0;
2330 	    }
2331 	}
2332 
2333 	if (cur == NULL) {
2334 	    *node = NULL;
2335 	    *indx = 0;
2336 	    return(-1);
2337 	}
2338 
2339 	/*
2340 	 * if there is no move needed return the current value.
2341 	 */
2342 	if (pos == 0) pos = 1;
2343 	if (bytes == 0) {
2344 	    *node = cur;
2345 	    *indx = pos;
2346 	    return(0);
2347 	}
2348 	/*
2349 	 * We should have a text (or cdata) node ...
2350 	 */
2351 	len = 0;
2352 	if ((cur->type != XML_ELEMENT_NODE) &&
2353             (cur->content != NULL)) {
2354 	    len = xmlStrlen(cur->content);
2355 	}
2356 	if (pos > len) {
2357 	    /* Strange, the indx in the text node is greater than it's len */
2358 	    STRANGE
2359 	    pos = len;
2360 	}
2361 	if (pos + bytes >= len) {
2362 	    bytes -= (len - pos);
2363 	    cur = xmlXPtrAdvanceNode(cur, NULL);
2364 	    pos = 0;
2365 	} else if (pos + bytes < len) {
2366 	    pos += bytes;
2367 	    *node = cur;
2368 	    *indx = pos;
2369 	    return(0);
2370 	}
2371     }
2372     return(-1);
2373 }
2374 
2375 /**
2376  * xmlXPtrMatchString:
2377  * @string:  the string to search
2378  * @start:  the start textnode
2379  * @startindex:  the start index
2380  * @end:  the end textnode IN/OUT
2381  * @endindex:  the end index IN/OUT
2382  *
2383  * Check whether the document contains @string at the position
2384  * (@start, @startindex) and limited by the (@end, @endindex) point
2385  *
2386  * Returns -1 in case of failure, 0 if not found, 1 if found in which case
2387  *            (@start, @startindex) will indicate the position of the beginning
2388  *            of the range and (@end, @endindex) will indicate the end
2389  *            of the range
2390  */
2391 static int
xmlXPtrMatchString(const xmlChar * string,xmlNodePtr start,int startindex,xmlNodePtr * end,int * endindex)2392 xmlXPtrMatchString(const xmlChar *string, xmlNodePtr start, int startindex,
2393 	            xmlNodePtr *end, int *endindex) {
2394     xmlNodePtr cur;
2395     int pos; /* 0 based */
2396     int len; /* in bytes */
2397     int stringlen; /* in bytes */
2398     int match;
2399 
2400     if (string == NULL)
2401 	return(-1);
2402     if ((start == NULL) || (start->type == XML_NAMESPACE_DECL))
2403 	return(-1);
2404     if ((end == NULL) || (*end == NULL) ||
2405         ((*end)->type == XML_NAMESPACE_DECL) || (endindex == NULL))
2406 	return(-1);
2407     cur = start;
2408     pos = startindex - 1;
2409     stringlen = xmlStrlen(string);
2410 
2411     while (stringlen > 0) {
2412 	if ((cur == *end) && (pos + stringlen > *endindex))
2413 	    return(0);
2414 
2415 	if ((cur->type != XML_ELEMENT_NODE) && (cur->content != NULL)) {
2416 	    len = xmlStrlen(cur->content);
2417 	    if (len >= pos + stringlen) {
2418 		match = (!xmlStrncmp(&cur->content[pos], string, stringlen));
2419 		if (match) {
2420 #ifdef DEBUG_RANGES
2421 		    xmlGenericError(xmlGenericErrorContext,
2422 			    "found range %d bytes at index %d of ->",
2423 			    stringlen, pos + 1);
2424 		    xmlDebugDumpString(stdout, cur->content);
2425 		    xmlGenericError(xmlGenericErrorContext, "\n");
2426 #endif
2427 		    *end = cur;
2428 		    *endindex = pos + stringlen;
2429 		    return(1);
2430 		} else {
2431 		    return(0);
2432 		}
2433 	    } else {
2434                 int sub = len - pos;
2435 		match = (!xmlStrncmp(&cur->content[pos], string, sub));
2436 		if (match) {
2437 #ifdef DEBUG_RANGES
2438 		    xmlGenericError(xmlGenericErrorContext,
2439 			    "found subrange %d bytes at index %d of ->",
2440 			    sub, pos + 1);
2441 		    xmlDebugDumpString(stdout, cur->content);
2442 		    xmlGenericError(xmlGenericErrorContext, "\n");
2443 #endif
2444                     string = &string[sub];
2445 		    stringlen -= sub;
2446 		} else {
2447 		    return(0);
2448 		}
2449 	    }
2450 	}
2451 	cur = xmlXPtrAdvanceNode(cur, NULL);
2452 	if (cur == NULL)
2453 	    return(0);
2454 	pos = 0;
2455     }
2456     return(1);
2457 }
2458 
2459 /**
2460  * xmlXPtrSearchString:
2461  * @string:  the string to search
2462  * @start:  the start textnode IN/OUT
2463  * @startindex:  the start index IN/OUT
2464  * @end:  the end textnode
2465  * @endindex:  the end index
2466  *
2467  * Search the next occurrence of @string within the document content
2468  * until the (@end, @endindex) point is reached
2469  *
2470  * Returns -1 in case of failure, 0 if not found, 1 if found in which case
2471  *            (@start, @startindex) will indicate the position of the beginning
2472  *            of the range and (@end, @endindex) will indicate the end
2473  *            of the range
2474  */
2475 static int
xmlXPtrSearchString(const xmlChar * string,xmlNodePtr * start,int * startindex,xmlNodePtr * end,int * endindex)2476 xmlXPtrSearchString(const xmlChar *string, xmlNodePtr *start, int *startindex,
2477 	            xmlNodePtr *end, int *endindex) {
2478     xmlNodePtr cur;
2479     const xmlChar *str;
2480     int pos; /* 0 based */
2481     int len; /* in bytes */
2482     xmlChar first;
2483 
2484     if (string == NULL)
2485 	return(-1);
2486     if ((start == NULL) || (*start == NULL) ||
2487         ((*start)->type == XML_NAMESPACE_DECL) || (startindex == NULL))
2488 	return(-1);
2489     if ((end == NULL) || (endindex == NULL))
2490 	return(-1);
2491     cur = *start;
2492     pos = *startindex - 1;
2493     first = string[0];
2494 
2495     while (cur != NULL) {
2496 	if ((cur->type != XML_ELEMENT_NODE) && (cur->content != NULL)) {
2497 	    len = xmlStrlen(cur->content);
2498 	    while (pos <= len) {
2499 		if (first != 0) {
2500 		    str = xmlStrchr(&cur->content[pos], first);
2501 		    if (str != NULL) {
2502 			pos = (str - (xmlChar *)(cur->content));
2503 #ifdef DEBUG_RANGES
2504 			xmlGenericError(xmlGenericErrorContext,
2505 				"found '%c' at index %d of ->",
2506 				first, pos + 1);
2507 			xmlDebugDumpString(stdout, cur->content);
2508 			xmlGenericError(xmlGenericErrorContext, "\n");
2509 #endif
2510 			if (xmlXPtrMatchString(string, cur, pos + 1,
2511 					       end, endindex)) {
2512 			    *start = cur;
2513 			    *startindex = pos + 1;
2514 			    return(1);
2515 			}
2516 			pos++;
2517 		    } else {
2518 			pos = len + 1;
2519 		    }
2520 		} else {
2521 		    /*
2522 		     * An empty string is considered to match before each
2523 		     * character of the string-value and after the final
2524 		     * character.
2525 		     */
2526 #ifdef DEBUG_RANGES
2527 		    xmlGenericError(xmlGenericErrorContext,
2528 			    "found '' at index %d of ->",
2529 			    pos + 1);
2530 		    xmlDebugDumpString(stdout, cur->content);
2531 		    xmlGenericError(xmlGenericErrorContext, "\n");
2532 #endif
2533 		    *start = cur;
2534 		    *startindex = pos + 1;
2535 		    *end = cur;
2536 		    *endindex = pos + 1;
2537 		    return(1);
2538 		}
2539 	    }
2540 	}
2541 	if ((cur == *end) && (pos >= *endindex))
2542 	    return(0);
2543 	cur = xmlXPtrAdvanceNode(cur, NULL);
2544 	if (cur == NULL)
2545 	    return(0);
2546 	pos = 1;
2547     }
2548     return(0);
2549 }
2550 
2551 /**
2552  * xmlXPtrGetLastChar:
2553  * @node:  the node
2554  * @index:  the index
2555  *
2556  * Computes the point coordinates of the last char of this point
2557  *
2558  * Returns -1 in case of failure, 0 otherwise
2559  */
2560 static int
xmlXPtrGetLastChar(xmlNodePtr * node,int * indx)2561 xmlXPtrGetLastChar(xmlNodePtr *node, int *indx) {
2562     xmlNodePtr cur;
2563     int pos, len = 0;
2564 
2565     if ((node == NULL) || (*node == NULL) ||
2566         ((*node)->type == XML_NAMESPACE_DECL) || (indx == NULL))
2567 	return(-1);
2568     cur = *node;
2569     pos = *indx;
2570 
2571     if ((cur->type == XML_ELEMENT_NODE) ||
2572 	(cur->type == XML_DOCUMENT_NODE) ||
2573 	(cur->type == XML_HTML_DOCUMENT_NODE)) {
2574 	if (pos > 0) {
2575 	    cur = xmlXPtrGetNthChild(cur, pos);
2576 	}
2577     }
2578     while (cur != NULL) {
2579 	if (cur->last != NULL)
2580 	    cur = cur->last;
2581 	else if ((cur->type != XML_ELEMENT_NODE) &&
2582 	         (cur->content != NULL)) {
2583 	    len = xmlStrlen(cur->content);
2584 	    break;
2585 	} else {
2586 	    return(-1);
2587 	}
2588     }
2589     if (cur == NULL)
2590 	return(-1);
2591     *node = cur;
2592     *indx = len;
2593     return(0);
2594 }
2595 
2596 /**
2597  * xmlXPtrGetStartPoint:
2598  * @obj:  an range
2599  * @node:  the resulting node
2600  * @indx:  the resulting index
2601  *
2602  * read the object and return the start point coordinates.
2603  *
2604  * Returns -1 in case of failure, 0 otherwise
2605  */
2606 static int
xmlXPtrGetStartPoint(xmlXPathObjectPtr obj,xmlNodePtr * node,int * indx)2607 xmlXPtrGetStartPoint(xmlXPathObjectPtr obj, xmlNodePtr *node, int *indx) {
2608     if ((obj == NULL) || (node == NULL) || (indx == NULL))
2609 	return(-1);
2610 
2611     switch (obj->type) {
2612         case XPATH_POINT:
2613 	    *node = obj->user;
2614 	    if (obj->index <= 0)
2615 		*indx = 0;
2616 	    else
2617 		*indx = obj->index;
2618 	    return(0);
2619         case XPATH_RANGE:
2620 	    *node = obj->user;
2621 	    if (obj->index <= 0)
2622 		*indx = 0;
2623 	    else
2624 		*indx = obj->index;
2625 	    return(0);
2626 	default:
2627 	    break;
2628     }
2629     return(-1);
2630 }
2631 
2632 /**
2633  * xmlXPtrGetEndPoint:
2634  * @obj:  an range
2635  * @node:  the resulting node
2636  * @indx:  the resulting indx
2637  *
2638  * read the object and return the end point coordinates.
2639  *
2640  * Returns -1 in case of failure, 0 otherwise
2641  */
2642 static int
xmlXPtrGetEndPoint(xmlXPathObjectPtr obj,xmlNodePtr * node,int * indx)2643 xmlXPtrGetEndPoint(xmlXPathObjectPtr obj, xmlNodePtr *node, int *indx) {
2644     if ((obj == NULL) || (node == NULL) || (indx == NULL))
2645 	return(-1);
2646 
2647     switch (obj->type) {
2648         case XPATH_POINT:
2649 	    *node = obj->user;
2650 	    if (obj->index <= 0)
2651 		*indx = 0;
2652 	    else
2653 		*indx = obj->index;
2654 	    return(0);
2655         case XPATH_RANGE:
2656 	    *node = obj->user;
2657 	    if (obj->index <= 0)
2658 		*indx = 0;
2659 	    else
2660 		*indx = obj->index;
2661 	    return(0);
2662 	default:
2663 	    break;
2664     }
2665     return(-1);
2666 }
2667 
2668 /**
2669  * xmlXPtrStringRangeFunction:
2670  * @ctxt:  the XPointer Parser context
2671  * @nargs:  the number of args
2672  *
2673  * Function implementing the string-range() function
2674  * range as described in 5.4.2
2675  *
2676  * ------------------------------
2677  * [Definition: For each location in the location-set argument,
2678  * string-range returns a set of string ranges, a set of substrings in a
2679  * string. Specifically, the string-value of the location is searched for
2680  * substrings that match the string argument, and the resulting location-set
2681  * will contain a range location for each non-overlapping match.]
2682  * An empty string is considered to match before each character of the
2683  * string-value and after the final character. Whitespace in a string
2684  * is matched literally, with no normalization except that provided by
2685  * XML for line ends. The third argument gives the position of the first
2686  * character to be in the resulting range, relative to the start of the
2687  * match. The default value is 1, which makes the range start immediately
2688  * before the first character of the matched string. The fourth argument
2689  * gives the number of characters in the range; the default is that the
2690  * range extends to the end of the matched string.
2691  *
2692  * Element boundaries, as well as entire embedded nodes such as processing
2693  * instructions and comments, are ignored as defined in [XPath].
2694  *
2695  * If the string in the second argument is not found in the string-value
2696  * of the location, or if a value in the third or fourth argument indicates
2697  * a string that is beyond the beginning or end of the document, the
2698  * expression fails.
2699  *
2700  * The points of the range-locations in the returned location-set will
2701  * all be character points.
2702  * ------------------------------
2703  */
2704 static void
xmlXPtrStringRangeFunction(xmlXPathParserContextPtr ctxt,int nargs)2705 xmlXPtrStringRangeFunction(xmlXPathParserContextPtr ctxt, int nargs) {
2706     int i, startindex, endindex = 0, fendindex;
2707     xmlNodePtr start, end = 0, fend;
2708     xmlXPathObjectPtr set;
2709     xmlLocationSetPtr oldset;
2710     xmlLocationSetPtr newset;
2711     xmlXPathObjectPtr string;
2712     xmlXPathObjectPtr position = NULL;
2713     xmlXPathObjectPtr number = NULL;
2714     int found, pos = 0, num = 0;
2715 
2716     /*
2717      * Grab the arguments
2718      */
2719     if ((nargs < 2) || (nargs > 4))
2720 	XP_ERROR(XPATH_INVALID_ARITY);
2721 
2722     if (nargs >= 4) {
2723 	CHECK_TYPE(XPATH_NUMBER);
2724 	number = valuePop(ctxt);
2725 	if (number != NULL)
2726 	    num = (int) number->floatval;
2727     }
2728     if (nargs >= 3) {
2729 	CHECK_TYPE(XPATH_NUMBER);
2730 	position = valuePop(ctxt);
2731 	if (position != NULL)
2732 	    pos = (int) position->floatval;
2733     }
2734     CHECK_TYPE(XPATH_STRING);
2735     string = valuePop(ctxt);
2736     if ((ctxt->value == NULL) ||
2737 	((ctxt->value->type != XPATH_LOCATIONSET) &&
2738 	 (ctxt->value->type != XPATH_NODESET)))
2739         XP_ERROR(XPATH_INVALID_TYPE)
2740 
2741     set = valuePop(ctxt);
2742     newset = xmlXPtrLocationSetCreate(NULL);
2743     if (newset == NULL) {
2744 	xmlXPathFreeObject(set);
2745         XP_ERROR(XPATH_MEMORY_ERROR);
2746     }
2747     if (set->nodesetval == NULL) {
2748         goto error;
2749     }
2750     if (set->type == XPATH_NODESET) {
2751 	xmlXPathObjectPtr tmp;
2752 
2753 	/*
2754 	 * First convert to a location set
2755 	 */
2756 	tmp = xmlXPtrNewLocationSetNodeSet(set->nodesetval);
2757 	xmlXPathFreeObject(set);
2758 	if (tmp == NULL)
2759 	     XP_ERROR(XPATH_MEMORY_ERROR)
2760 	set = tmp;
2761     }
2762     oldset = (xmlLocationSetPtr) set->user;
2763 
2764     /*
2765      * The loop is to search for each element in the location set
2766      * the list of location set corresponding to that search
2767      */
2768     for (i = 0;i < oldset->locNr;i++) {
2769 #ifdef DEBUG_RANGES
2770 	xmlXPathDebugDumpObject(stdout, oldset->locTab[i], 0);
2771 #endif
2772 
2773 	xmlXPtrGetStartPoint(oldset->locTab[i], &start, &startindex);
2774 	xmlXPtrGetEndPoint(oldset->locTab[i], &end, &endindex);
2775 	xmlXPtrAdvanceChar(&start, &startindex, 0);
2776 	xmlXPtrGetLastChar(&end, &endindex);
2777 
2778 #ifdef DEBUG_RANGES
2779 	xmlGenericError(xmlGenericErrorContext,
2780 		"from index %d of ->", startindex);
2781 	xmlDebugDumpString(stdout, start->content);
2782 	xmlGenericError(xmlGenericErrorContext, "\n");
2783 	xmlGenericError(xmlGenericErrorContext,
2784 		"to index %d of ->", endindex);
2785 	xmlDebugDumpString(stdout, end->content);
2786 	xmlGenericError(xmlGenericErrorContext, "\n");
2787 #endif
2788 	do {
2789             fend = end;
2790             fendindex = endindex;
2791 	    found = xmlXPtrSearchString(string->stringval, &start, &startindex,
2792 		                        &fend, &fendindex);
2793 	    if (found == 1) {
2794 		if (position == NULL) {
2795 		    xmlXPtrLocationSetAdd(newset,
2796 			 xmlXPtrNewRange(start, startindex, fend, fendindex));
2797 		} else if (xmlXPtrAdvanceChar(&start, &startindex,
2798 			                      pos - 1) == 0) {
2799 		    if ((number != NULL) && (num > 0)) {
2800 			int rindx;
2801 			xmlNodePtr rend;
2802 			rend = start;
2803 			rindx = startindex - 1;
2804 			if (xmlXPtrAdvanceChar(&rend, &rindx,
2805 				               num) == 0) {
2806 			    xmlXPtrLocationSetAdd(newset,
2807 					xmlXPtrNewRange(start, startindex,
2808 							rend, rindx));
2809 			}
2810 		    } else if ((number != NULL) && (num <= 0)) {
2811 			xmlXPtrLocationSetAdd(newset,
2812 				    xmlXPtrNewRange(start, startindex,
2813 						    start, startindex));
2814 		    } else {
2815 			xmlXPtrLocationSetAdd(newset,
2816 				    xmlXPtrNewRange(start, startindex,
2817 						    fend, fendindex));
2818 		    }
2819 		}
2820 		start = fend;
2821 		startindex = fendindex;
2822 		if (string->stringval[0] == 0)
2823 		    startindex++;
2824 	    }
2825 	} while (found == 1);
2826     }
2827 
2828     /*
2829      * Save the new value and cleanup
2830      */
2831 error:
2832     valuePush(ctxt, xmlXPtrWrapLocationSet(newset));
2833     xmlXPathFreeObject(set);
2834     xmlXPathFreeObject(string);
2835     if (position) xmlXPathFreeObject(position);
2836     if (number) xmlXPathFreeObject(number);
2837 }
2838 
2839 /**
2840  * xmlXPtrEvalRangePredicate:
2841  * @ctxt:  the XPointer Parser context
2842  *
2843  *  [8]   Predicate ::=   '[' PredicateExpr ']'
2844  *  [9]   PredicateExpr ::=   Expr
2845  *
2846  * Evaluate a predicate as in xmlXPathEvalPredicate() but for
2847  * a Location Set instead of a node set
2848  */
2849 void
xmlXPtrEvalRangePredicate(xmlXPathParserContextPtr ctxt)2850 xmlXPtrEvalRangePredicate(xmlXPathParserContextPtr ctxt) {
2851     const xmlChar *cur;
2852     xmlXPathObjectPtr res;
2853     xmlXPathObjectPtr obj, tmp;
2854     xmlLocationSetPtr newset = NULL;
2855     xmlLocationSetPtr oldset;
2856     int i;
2857 
2858     if (ctxt == NULL) return;
2859 
2860     SKIP_BLANKS;
2861     if (CUR != '[') {
2862 	XP_ERROR(XPATH_INVALID_PREDICATE_ERROR);
2863     }
2864     NEXT;
2865     SKIP_BLANKS;
2866 
2867     /*
2868      * Extract the old set, and then evaluate the result of the
2869      * expression for all the element in the set. use it to grow
2870      * up a new set.
2871      */
2872     CHECK_TYPE(XPATH_LOCATIONSET);
2873     obj = valuePop(ctxt);
2874     oldset = obj->user;
2875     ctxt->context->node = NULL;
2876 
2877     if ((oldset == NULL) || (oldset->locNr == 0)) {
2878 	ctxt->context->contextSize = 0;
2879 	ctxt->context->proximityPosition = 0;
2880 	xmlXPathEvalExpr(ctxt);
2881 	res = valuePop(ctxt);
2882 	if (res != NULL)
2883 	    xmlXPathFreeObject(res);
2884 	valuePush(ctxt, obj);
2885 	CHECK_ERROR;
2886     } else {
2887 	/*
2888 	 * Save the expression pointer since we will have to evaluate
2889 	 * it multiple times. Initialize the new set.
2890 	 */
2891         cur = ctxt->cur;
2892 	newset = xmlXPtrLocationSetCreate(NULL);
2893 
2894         for (i = 0; i < oldset->locNr; i++) {
2895 	    ctxt->cur = cur;
2896 
2897 	    /*
2898 	     * Run the evaluation with a node list made of a single item
2899 	     * in the nodeset.
2900 	     */
2901 	    ctxt->context->node = oldset->locTab[i]->user;
2902 	    tmp = xmlXPathNewNodeSet(ctxt->context->node);
2903 	    valuePush(ctxt, tmp);
2904 	    ctxt->context->contextSize = oldset->locNr;
2905 	    ctxt->context->proximityPosition = i + 1;
2906 
2907 	    xmlXPathEvalExpr(ctxt);
2908 	    CHECK_ERROR;
2909 
2910 	    /*
2911 	     * The result of the evaluation need to be tested to
2912 	     * decided whether the filter succeeded or not
2913 	     */
2914 	    res = valuePop(ctxt);
2915 	    if (xmlXPathEvaluatePredicateResult(ctxt, res)) {
2916 	        xmlXPtrLocationSetAdd(newset,
2917 			xmlXPathObjectCopy(oldset->locTab[i]));
2918 	    }
2919 
2920 	    /*
2921 	     * Cleanup
2922 	     */
2923 	    if (res != NULL)
2924 		xmlXPathFreeObject(res);
2925 	    if (ctxt->value == tmp) {
2926 		res = valuePop(ctxt);
2927 		xmlXPathFreeObject(res);
2928 	    }
2929 
2930 	    ctxt->context->node = NULL;
2931 	}
2932 
2933 	/*
2934 	 * The result is used as the new evaluation set.
2935 	 */
2936 	xmlXPathFreeObject(obj);
2937 	ctxt->context->node = NULL;
2938 	ctxt->context->contextSize = -1;
2939 	ctxt->context->proximityPosition = -1;
2940 	valuePush(ctxt, xmlXPtrWrapLocationSet(newset));
2941     }
2942     if (CUR != ']') {
2943 	XP_ERROR(XPATH_INVALID_PREDICATE_ERROR);
2944     }
2945 
2946     NEXT;
2947     SKIP_BLANKS;
2948 }
2949 
2950 #define bottom_xpointer
2951 #include "elfgcchack.h"
2952 #endif
2953 
2954