• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * relaxng.c : implementation of the Relax-NG handling and validity checking
3  *
4  * See Copyright for the status of this software.
5  *
6  * Daniel Veillard <veillard@redhat.com>
7  */
8 
9 /**
10  * TODO:
11  * - add support for DTD compatibility spec
12  *   http://www.oasis-open.org/committees/relax-ng/compatibility-20011203.html
13  * - report better mem allocations pbms at runtime and abort immediately.
14  */
15 
16 #define IN_LIBXML
17 #include "libxml.h"
18 
19 #ifdef LIBXML_SCHEMAS_ENABLED
20 
21 #include <string.h>
22 #include <stdio.h>
23 #include <stddef.h>
24 #include <libxml/xmlmemory.h>
25 #include <libxml/parser.h>
26 #include <libxml/parserInternals.h>
27 #include <libxml/hash.h>
28 #include <libxml/uri.h>
29 
30 #include <libxml/relaxng.h>
31 
32 #include <libxml/xmlschemastypes.h>
33 #include <libxml/xmlautomata.h>
34 #include <libxml/xmlregexp.h>
35 #include <libxml/xmlschemastypes.h>
36 
37 #include "private/error.h"
38 #include "private/parser.h"
39 #include "private/regexp.h"
40 #include "private/string.h"
41 
42 /*
43  * The Relax-NG namespace
44  */
45 static const xmlChar *xmlRelaxNGNs = (const xmlChar *)
46     "http://relaxng.org/ns/structure/1.0";
47 
48 #define IS_RELAXNG(node, typ)						\
49    ((node != NULL) && (node->ns != NULL) &&				\
50     (node->type == XML_ELEMENT_NODE) &&					\
51     (xmlStrEqual(node->name, (const xmlChar *) typ)) &&		\
52     (xmlStrEqual(node->ns->href, xmlRelaxNGNs)))
53 
54 
55 #define MAX_ERROR 5
56 
57 typedef struct _xmlRelaxNGSchema xmlRelaxNGSchema;
58 typedef xmlRelaxNGSchema *xmlRelaxNGSchemaPtr;
59 
60 typedef struct _xmlRelaxNGDefine xmlRelaxNGDefine;
61 typedef xmlRelaxNGDefine *xmlRelaxNGDefinePtr;
62 
63 typedef struct _xmlRelaxNGDocument xmlRelaxNGDocument;
64 typedef xmlRelaxNGDocument *xmlRelaxNGDocumentPtr;
65 
66 typedef struct _xmlRelaxNGInclude xmlRelaxNGInclude;
67 typedef xmlRelaxNGInclude *xmlRelaxNGIncludePtr;
68 
69 typedef enum {
70     XML_RELAXNG_COMBINE_UNDEFINED = 0,  /* undefined */
71     XML_RELAXNG_COMBINE_CHOICE, /* choice */
72     XML_RELAXNG_COMBINE_INTERLEAVE      /* interleave */
73 } xmlRelaxNGCombine;
74 
75 typedef enum {
76     XML_RELAXNG_CONTENT_ERROR = -1,
77     XML_RELAXNG_CONTENT_EMPTY = 0,
78     XML_RELAXNG_CONTENT_SIMPLE,
79     XML_RELAXNG_CONTENT_COMPLEX
80 } xmlRelaxNGContentType;
81 
82 typedef struct _xmlRelaxNGGrammar xmlRelaxNGGrammar;
83 typedef xmlRelaxNGGrammar *xmlRelaxNGGrammarPtr;
84 
85 struct _xmlRelaxNGGrammar {
86     xmlRelaxNGGrammarPtr parent;        /* the parent grammar if any */
87     xmlRelaxNGGrammarPtr children;      /* the children grammar if any */
88     xmlRelaxNGGrammarPtr next;  /* the next grammar if any */
89     xmlRelaxNGDefinePtr start;  /* <start> content */
90     xmlRelaxNGCombine combine;  /* the default combine value */
91     xmlRelaxNGDefinePtr startList;      /* list of <start> definitions */
92     xmlHashTablePtr defs;       /* define* */
93     xmlHashTablePtr refs;       /* references */
94 };
95 
96 
97 typedef enum {
98     XML_RELAXNG_NOOP = -1,      /* a no operation from simplification  */
99     XML_RELAXNG_EMPTY = 0,      /* an empty pattern */
100     XML_RELAXNG_NOT_ALLOWED,    /* not allowed top */
101     XML_RELAXNG_EXCEPT,         /* except present in nameclass defs */
102     XML_RELAXNG_TEXT,           /* textual content */
103     XML_RELAXNG_ELEMENT,        /* an element */
104     XML_RELAXNG_DATATYPE,       /* external data type definition */
105     XML_RELAXNG_PARAM,          /* external data type parameter */
106     XML_RELAXNG_VALUE,          /* value from an external data type definition */
107     XML_RELAXNG_LIST,           /* a list of patterns */
108     XML_RELAXNG_ATTRIBUTE,      /* an attribute following a pattern */
109     XML_RELAXNG_DEF,            /* a definition */
110     XML_RELAXNG_REF,            /* reference to a definition */
111     XML_RELAXNG_EXTERNALREF,    /* reference to an external def */
112     XML_RELAXNG_PARENTREF,      /* reference to a def in the parent grammar */
113     XML_RELAXNG_OPTIONAL,       /* optional patterns */
114     XML_RELAXNG_ZEROORMORE,     /* zero or more non empty patterns */
115     XML_RELAXNG_ONEORMORE,      /* one or more non empty patterns */
116     XML_RELAXNG_CHOICE,         /* a choice between non empty patterns */
117     XML_RELAXNG_GROUP,          /* a pair/group of non empty patterns */
118     XML_RELAXNG_INTERLEAVE,     /* interleaving choice of non-empty patterns */
119     XML_RELAXNG_START           /* Used to keep track of starts on grammars */
120 } xmlRelaxNGType;
121 
122 #define IS_NULLABLE		(1 << 0)
123 #define IS_NOT_NULLABLE		(1 << 1)
124 #define IS_INDETERMINIST	(1 << 2)
125 #define IS_MIXED		(1 << 3)
126 #define IS_TRIABLE		(1 << 4)
127 #define IS_PROCESSED		(1 << 5)
128 #define IS_COMPILABLE		(1 << 6)
129 #define IS_NOT_COMPILABLE	(1 << 7)
130 #define IS_EXTERNAL_REF	        (1 << 8)
131 
132 struct _xmlRelaxNGDefine {
133     xmlRelaxNGType type;        /* the type of definition */
134     xmlNodePtr node;            /* the node in the source */
135     xmlChar *name;              /* the element local name if present */
136     xmlChar *ns;                /* the namespace local name if present */
137     xmlChar *value;             /* value when available */
138     void *data;                 /* data lib or specific pointer */
139     xmlRelaxNGDefinePtr content;        /* the expected content */
140     xmlRelaxNGDefinePtr parent; /* the parent definition, if any */
141     xmlRelaxNGDefinePtr next;   /* list within grouping sequences */
142     xmlRelaxNGDefinePtr attrs;  /* list of attributes for elements */
143     xmlRelaxNGDefinePtr nameClass;      /* the nameClass definition if any */
144     xmlRelaxNGDefinePtr nextHash;       /* next define in defs/refs hash tables */
145     short depth;                /* used for the cycle detection */
146     short dflags;               /* define related flags */
147     xmlRegexpPtr contModel;     /* a compiled content model if available */
148 };
149 
150 /**
151  * _xmlRelaxNG:
152  *
153  * A RelaxNGs definition
154  */
155 struct _xmlRelaxNG {
156     void *_private;             /* unused by the library for users or bindings */
157     xmlRelaxNGGrammarPtr topgrammar;
158     xmlDocPtr doc;
159 
160     int idref;                  /* requires idref checking */
161 
162     xmlHashTablePtr defs;       /* define */
163     xmlHashTablePtr refs;       /* references */
164     xmlRelaxNGDocumentPtr documents;    /* all the documents loaded */
165     xmlRelaxNGIncludePtr includes;      /* all the includes loaded */
166     int defNr;                  /* number of defines used */
167     xmlRelaxNGDefinePtr *defTab;        /* pointer to the allocated definitions */
168 
169 };
170 
171 #define XML_RELAXNG_IN_ATTRIBUTE	(1 << 0)
172 #define XML_RELAXNG_IN_ONEORMORE	(1 << 1)
173 #define XML_RELAXNG_IN_LIST		(1 << 2)
174 #define XML_RELAXNG_IN_DATAEXCEPT	(1 << 3)
175 #define XML_RELAXNG_IN_START		(1 << 4)
176 #define XML_RELAXNG_IN_OOMGROUP		(1 << 5)
177 #define XML_RELAXNG_IN_OOMINTERLEAVE	(1 << 6)
178 #define XML_RELAXNG_IN_EXTERNALREF	(1 << 7)
179 #define XML_RELAXNG_IN_ANYEXCEPT	(1 << 8)
180 #define XML_RELAXNG_IN_NSEXCEPT		(1 << 9)
181 
182 struct _xmlRelaxNGParserCtxt {
183     void *userData;             /* user specific data block */
184     xmlRelaxNGValidityErrorFunc error;  /* the callback in case of errors */
185     xmlRelaxNGValidityWarningFunc warning;      /* the callback in case of warning */
186     xmlStructuredErrorFunc serror;
187     xmlRelaxNGValidErr err;
188 
189     xmlRelaxNGPtr schema;       /* The schema in use */
190     xmlRelaxNGGrammarPtr grammar;       /* the current grammar */
191     xmlRelaxNGGrammarPtr parentgrammar; /* the parent grammar */
192     int flags;                  /* parser flags */
193     int nbErrors;               /* number of errors at parse time */
194     int nbWarnings;             /* number of warnings at parse time */
195     const xmlChar *define;      /* the current define scope */
196     xmlRelaxNGDefinePtr def;    /* the current define */
197 
198     int nbInterleaves;
199     xmlHashTablePtr interleaves;        /* keep track of all the interleaves */
200 
201     xmlRelaxNGDocumentPtr documents;    /* all the documents loaded */
202     xmlRelaxNGIncludePtr includes;      /* all the includes loaded */
203     xmlChar *URL;
204     xmlDocPtr document;
205 
206     int defNr;                  /* number of defines used */
207     int defMax;                 /* number of defines allocated */
208     xmlRelaxNGDefinePtr *defTab;        /* pointer to the allocated definitions */
209 
210     const char *buffer;
211     int size;
212 
213     /* the document stack */
214     xmlRelaxNGDocumentPtr doc;  /* Current parsed external ref */
215     int docNr;                  /* Depth of the parsing stack */
216     int docMax;                 /* Max depth of the parsing stack */
217     xmlRelaxNGDocumentPtr *docTab;      /* array of docs */
218 
219     /* the include stack */
220     xmlRelaxNGIncludePtr inc;   /* Current parsed include */
221     int incNr;                  /* Depth of the include parsing stack */
222     int incMax;                 /* Max depth of the parsing stack */
223     xmlRelaxNGIncludePtr *incTab;       /* array of incs */
224 
225     int idref;                  /* requires idref checking */
226 
227     /* used to compile content models */
228     xmlAutomataPtr am;          /* the automata */
229     xmlAutomataStatePtr state;  /* used to build the automata */
230 
231     int crng;			/* compact syntax and other flags */
232     int freedoc;		/* need to free the document */
233 
234     xmlResourceLoader resourceLoader;
235     void *resourceCtxt;
236 };
237 
238 #define FLAGS_IGNORABLE		1
239 #define FLAGS_NEGATIVE		2
240 #define FLAGS_MIXED_CONTENT	4
241 #define FLAGS_NOERROR		8
242 
243 /**
244  * xmlRelaxNGInterleaveGroup:
245  *
246  * A RelaxNGs partition set associated to lists of definitions
247  */
248 typedef struct _xmlRelaxNGInterleaveGroup xmlRelaxNGInterleaveGroup;
249 typedef xmlRelaxNGInterleaveGroup *xmlRelaxNGInterleaveGroupPtr;
250 struct _xmlRelaxNGInterleaveGroup {
251     xmlRelaxNGDefinePtr rule;   /* the rule to satisfy */
252     xmlRelaxNGDefinePtr *defs;  /* the array of element definitions */
253     xmlRelaxNGDefinePtr *attrs; /* the array of attributes definitions */
254 };
255 
256 #define IS_DETERMINIST		1
257 #define IS_NEEDCHECK		2
258 
259 /**
260  * xmlRelaxNGPartitions:
261  *
262  * A RelaxNGs partition associated to an interleave group
263  */
264 typedef struct _xmlRelaxNGPartition xmlRelaxNGPartition;
265 typedef xmlRelaxNGPartition *xmlRelaxNGPartitionPtr;
266 struct _xmlRelaxNGPartition {
267     int nbgroups;               /* number of groups in the partitions */
268     xmlHashTablePtr triage;     /* hash table used to direct nodes to the
269                                  * right group when possible */
270     int flags;                  /* determinist ? */
271     xmlRelaxNGInterleaveGroupPtr *groups;
272 };
273 
274 /**
275  * xmlRelaxNGValidState:
276  *
277  * A RelaxNGs validation state
278  */
279 #define MAX_ATTR 20
280 typedef struct _xmlRelaxNGValidState xmlRelaxNGValidState;
281 typedef xmlRelaxNGValidState *xmlRelaxNGValidStatePtr;
282 struct _xmlRelaxNGValidState {
283     xmlNodePtr node;            /* the current node */
284     xmlNodePtr seq;             /* the sequence of children left to validate */
285     int nbAttrs;                /* the number of attributes */
286     int maxAttrs;               /* the size of attrs */
287     int nbAttrLeft;             /* the number of attributes left to validate */
288     xmlChar *value;             /* the value when operating on string */
289     xmlChar *endvalue;          /* the end value when operating on string */
290     xmlAttrPtr *attrs;          /* the array of attributes */
291 };
292 
293 /**
294  * xmlRelaxNGStates:
295  *
296  * A RelaxNGs container for validation state
297  */
298 typedef struct _xmlRelaxNGStates xmlRelaxNGStates;
299 typedef xmlRelaxNGStates *xmlRelaxNGStatesPtr;
300 struct _xmlRelaxNGStates {
301     int nbState;                /* the number of states */
302     int maxState;               /* the size of the array */
303     xmlRelaxNGValidStatePtr *tabState;
304 };
305 
306 #define ERROR_IS_DUP	1
307 
308 /**
309  * xmlRelaxNGValidError:
310  *
311  * A RelaxNGs validation error
312  */
313 typedef struct _xmlRelaxNGValidError xmlRelaxNGValidError;
314 typedef xmlRelaxNGValidError *xmlRelaxNGValidErrorPtr;
315 struct _xmlRelaxNGValidError {
316     xmlRelaxNGValidErr err;     /* the error number */
317     int flags;                  /* flags */
318     xmlNodePtr node;            /* the current node */
319     xmlNodePtr seq;             /* the current child */
320     const xmlChar *arg1;        /* first arg */
321     const xmlChar *arg2;        /* second arg */
322 };
323 
324 /**
325  * xmlRelaxNGValidCtxt:
326  *
327  * A RelaxNGs validation context
328  */
329 
330 struct _xmlRelaxNGValidCtxt {
331     void *userData;             /* user specific data block */
332     xmlRelaxNGValidityErrorFunc error;  /* the callback in case of errors */
333     xmlRelaxNGValidityWarningFunc warning;      /* the callback in case of warning */
334     xmlStructuredErrorFunc serror;
335     int nbErrors;               /* number of errors in validation */
336 
337     xmlRelaxNGPtr schema;       /* The schema in use */
338     xmlDocPtr doc;              /* the document being validated */
339     int flags;                  /* validation flags */
340     int depth;                  /* validation depth */
341     int idref;                  /* requires idref checking */
342     int errNo;                  /* the first error found */
343 
344     /*
345      * Errors accumulated in branches may have to be stacked to be
346      * provided back when it's sure they affect validation.
347      */
348     xmlRelaxNGValidErrorPtr err;        /* Last error */
349     int errNr;                  /* Depth of the error stack */
350     int errMax;                 /* Max depth of the error stack */
351     xmlRelaxNGValidErrorPtr errTab;     /* stack of errors */
352 
353     xmlRelaxNGValidStatePtr state;      /* the current validation state */
354     xmlRelaxNGStatesPtr states; /* the accumulated state list */
355 
356     xmlRelaxNGStatesPtr freeState;      /* the pool of free valid states */
357     int freeStatesNr;
358     int freeStatesMax;
359     xmlRelaxNGStatesPtr *freeStates;    /* the pool of free state groups */
360 
361     /*
362      * This is used for "progressive" validation
363      */
364     xmlRegExecCtxtPtr elem;     /* the current element regexp */
365     int elemNr;                 /* the number of element validated */
366     int elemMax;                /* the max depth of elements */
367     xmlRegExecCtxtPtr *elemTab; /* the stack of regexp runtime */
368     int pstate;                 /* progressive state */
369     xmlNodePtr pnode;           /* the current node */
370     xmlRelaxNGDefinePtr pdef;   /* the non-streamable definition */
371     int perr;                   /* signal error in content model
372                                  * outside the regexp */
373 };
374 
375 /**
376  * xmlRelaxNGInclude:
377  *
378  * Structure associated to a RelaxNGs document element
379  */
380 struct _xmlRelaxNGInclude {
381     xmlRelaxNGIncludePtr next;  /* keep a chain of includes */
382     xmlChar *href;              /* the normalized href value */
383     xmlDocPtr doc;              /* the associated XML document */
384     xmlRelaxNGDefinePtr content;        /* the definitions */
385     xmlRelaxNGPtr schema;       /* the schema */
386 };
387 
388 /**
389  * xmlRelaxNGDocument:
390  *
391  * Structure associated to a RelaxNGs document element
392  */
393 struct _xmlRelaxNGDocument {
394     xmlRelaxNGDocumentPtr next; /* keep a chain of documents */
395     xmlChar *href;              /* the normalized href value */
396     xmlDocPtr doc;              /* the associated XML document */
397     xmlRelaxNGDefinePtr content;        /* the definitions */
398     xmlRelaxNGPtr schema;       /* the schema */
399     int externalRef;            /* 1 if an external ref */
400 };
401 
402 
403 /************************************************************************
404  *									*
405  *		Some factorized error routines				*
406  *									*
407  ************************************************************************/
408 
409 /**
410  * xmlRngPErrMemory:
411  * @ctxt:  an Relax-NG parser context
412  * @extra:  extra information
413  *
414  * Handle a redefinition of attribute error
415  */
416 static void
xmlRngPErrMemory(xmlRelaxNGParserCtxtPtr ctxt)417 xmlRngPErrMemory(xmlRelaxNGParserCtxtPtr ctxt)
418 {
419     xmlStructuredErrorFunc schannel = NULL;
420     xmlGenericErrorFunc channel = NULL;
421     void *data = NULL;
422 
423     if (ctxt != NULL) {
424         if (ctxt->serror != NULL)
425 	    schannel = ctxt->serror;
426 	else
427 	    channel = ctxt->error;
428         data = ctxt->userData;
429         ctxt->nbErrors++;
430     }
431 
432     xmlRaiseMemoryError(schannel, channel, data, XML_FROM_RELAXNGP, NULL);
433 }
434 
435 /**
436  * xmlRngVErrMemory:
437  * @ctxt:  a Relax-NG validation context
438  * @extra:  extra information
439  *
440  * Handle a redefinition of attribute error
441  */
442 static void
xmlRngVErrMemory(xmlRelaxNGValidCtxtPtr ctxt)443 xmlRngVErrMemory(xmlRelaxNGValidCtxtPtr ctxt)
444 {
445     xmlStructuredErrorFunc schannel = NULL;
446     xmlGenericErrorFunc channel = NULL;
447     void *data = NULL;
448 
449     if (ctxt != NULL) {
450         if (ctxt->serror != NULL)
451 	    schannel = ctxt->serror;
452 	else
453 	    channel = ctxt->error;
454         data = ctxt->userData;
455         ctxt->nbErrors++;
456     }
457 
458     xmlRaiseMemoryError(schannel, channel, data, XML_FROM_RELAXNGV, NULL);
459 }
460 
461 /**
462  * xmlRngPErr:
463  * @ctxt:  a Relax-NG parser context
464  * @node:  the node raising the error
465  * @error:  the error code
466  * @msg:  message
467  * @str1:  extra info
468  * @str2:  extra info
469  *
470  * Handle a Relax NG Parsing error
471  */
472 static void LIBXML_ATTR_FORMAT(4,0)
xmlRngPErr(xmlRelaxNGParserCtxtPtr ctxt,xmlNodePtr node,int error,const char * msg,const xmlChar * str1,const xmlChar * str2)473 xmlRngPErr(xmlRelaxNGParserCtxtPtr ctxt, xmlNodePtr node, int error,
474            const char *msg, const xmlChar * str1, const xmlChar * str2)
475 {
476     xmlStructuredErrorFunc schannel = NULL;
477     xmlGenericErrorFunc channel = NULL;
478     void *data = NULL;
479     int res;
480 
481     if (ctxt != NULL) {
482         if (ctxt->serror != NULL)
483 	    schannel = ctxt->serror;
484 	else
485 	    channel = ctxt->error;
486         data = ctxt->userData;
487         ctxt->nbErrors++;
488     }
489 
490     if ((channel == NULL) && (schannel == NULL)) {
491         channel = xmlGenericError;
492         data = xmlGenericErrorContext;
493     }
494 
495     res = xmlRaiseError(schannel, channel, data, NULL, node,
496                         XML_FROM_RELAXNGP, error, XML_ERR_ERROR, NULL, 0,
497                         (const char *) str1, (const char *) str2, NULL, 0, 0,
498                         msg, str1, str2);
499     if (res < 0)
500         xmlRngPErrMemory(ctxt);
501 }
502 
503 /**
504  * xmlRngVErr:
505  * @ctxt:  a Relax-NG validation context
506  * @node:  the node raising the error
507  * @error:  the error code
508  * @msg:  message
509  * @str1:  extra info
510  * @str2:  extra info
511  *
512  * Handle a Relax NG Validation error
513  */
514 static void LIBXML_ATTR_FORMAT(4,0)
xmlRngVErr(xmlRelaxNGValidCtxtPtr ctxt,xmlNodePtr node,int error,const char * msg,const xmlChar * str1,const xmlChar * str2)515 xmlRngVErr(xmlRelaxNGValidCtxtPtr ctxt, xmlNodePtr node, int error,
516            const char *msg, const xmlChar * str1, const xmlChar * str2)
517 {
518     xmlStructuredErrorFunc schannel = NULL;
519     xmlGenericErrorFunc channel = NULL;
520     void *data = NULL;
521     int res;
522 
523     if (ctxt != NULL) {
524         if (ctxt->serror != NULL)
525 	    schannel = ctxt->serror;
526 	else
527 	    channel = ctxt->error;
528         data = ctxt->userData;
529         ctxt->nbErrors++;
530     }
531 
532     if ((channel == NULL) && (schannel == NULL)) {
533         channel = xmlGenericError;
534         data = xmlGenericErrorContext;
535     }
536 
537     res = xmlRaiseError(schannel, channel, data, NULL, node,
538                         XML_FROM_RELAXNGV, error, XML_ERR_ERROR, NULL, 0,
539                         (const char *) str1, (const char *) str2, NULL, 0, 0,
540                         msg, str1, str2);
541     if (res < 0)
542         xmlRngVErrMemory(ctxt);
543 }
544 
545 /************************************************************************
546  *									*
547  *		Preliminary type checking interfaces			*
548  *									*
549  ************************************************************************/
550 
551 /**
552  * xmlRelaxNGTypeHave:
553  * @data:  data needed for the library
554  * @type:  the type name
555  * @value:  the value to check
556  *
557  * Function provided by a type library to check if a type is exported
558  *
559  * Returns 1 if yes, 0 if no and -1 in case of error.
560  */
561 typedef int (*xmlRelaxNGTypeHave) (void *data, const xmlChar * type);
562 
563 /**
564  * xmlRelaxNGTypeCheck:
565  * @data:  data needed for the library
566  * @type:  the type name
567  * @value:  the value to check
568  * @result:  place to store the result if needed
569  *
570  * Function provided by a type library to check if a value match a type
571  *
572  * Returns 1 if yes, 0 if no and -1 in case of error.
573  */
574 typedef int (*xmlRelaxNGTypeCheck) (void *data, const xmlChar * type,
575                                     const xmlChar * value, void **result,
576                                     xmlNodePtr node);
577 
578 /**
579  * xmlRelaxNGFacetCheck:
580  * @data:  data needed for the library
581  * @type:  the type name
582  * @facet:  the facet name
583  * @val:  the facet value
584  * @strval:  the string value
585  * @value:  the value to check
586  *
587  * Function provided by a type library to check a value facet
588  *
589  * Returns 1 if yes, 0 if no and -1 in case of error.
590  */
591 typedef int (*xmlRelaxNGFacetCheck) (void *data, const xmlChar * type,
592                                      const xmlChar * facet,
593                                      const xmlChar * val,
594                                      const xmlChar * strval, void *value);
595 
596 /**
597  * xmlRelaxNGTypeFree:
598  * @data:  data needed for the library
599  * @result:  the value to free
600  *
601  * Function provided by a type library to free a returned result
602  */
603 typedef void (*xmlRelaxNGTypeFree) (void *data, void *result);
604 
605 /**
606  * xmlRelaxNGTypeCompare:
607  * @data:  data needed for the library
608  * @type:  the type name
609  * @value1:  the first value
610  * @value2:  the second value
611  *
612  * Function provided by a type library to compare two values accordingly
613  * to a type.
614  *
615  * Returns 1 if yes, 0 if no and -1 in case of error.
616  */
617 typedef int (*xmlRelaxNGTypeCompare) (void *data, const xmlChar * type,
618                                       const xmlChar * value1,
619                                       xmlNodePtr ctxt1,
620                                       void *comp1,
621                                       const xmlChar * value2,
622                                       xmlNodePtr ctxt2);
623 typedef struct _xmlRelaxNGTypeLibrary xmlRelaxNGTypeLibrary;
624 typedef xmlRelaxNGTypeLibrary *xmlRelaxNGTypeLibraryPtr;
625 struct _xmlRelaxNGTypeLibrary {
626     const xmlChar *namespace;   /* the datatypeLibrary value */
627     void *data;                 /* data needed for the library */
628     xmlRelaxNGTypeHave have;    /* the export function */
629     xmlRelaxNGTypeCheck check;  /* the checking function */
630     xmlRelaxNGTypeCompare comp; /* the compare function */
631     xmlRelaxNGFacetCheck facet; /* the facet check function */
632     xmlRelaxNGTypeFree freef;   /* the freeing function */
633 };
634 
635 /************************************************************************
636  *									*
637  *			Allocation functions				*
638  *									*
639  ************************************************************************/
640 static void xmlRelaxNGFreeGrammar(xmlRelaxNGGrammarPtr grammar);
641 static void xmlRelaxNGFreeDefine(xmlRelaxNGDefinePtr define);
642 static void xmlRelaxNGNormExtSpace(xmlChar * value);
643 static void xmlRelaxNGFreeInnerSchema(xmlRelaxNGPtr schema);
644 static int xmlRelaxNGEqualValidState(xmlRelaxNGValidCtxtPtr ctxt
645                                      ATTRIBUTE_UNUSED,
646                                      xmlRelaxNGValidStatePtr state1,
647                                      xmlRelaxNGValidStatePtr state2);
648 static void xmlRelaxNGFreeValidState(xmlRelaxNGValidCtxtPtr ctxt,
649                                      xmlRelaxNGValidStatePtr state);
650 
651 /**
652  * xmlRelaxNGFreeDocument:
653  * @docu:  a document structure
654  *
655  * Deallocate a RelaxNG document structure.
656  */
657 static void
xmlRelaxNGFreeDocument(xmlRelaxNGDocumentPtr docu)658 xmlRelaxNGFreeDocument(xmlRelaxNGDocumentPtr docu)
659 {
660     if (docu == NULL)
661         return;
662 
663     if (docu->href != NULL)
664         xmlFree(docu->href);
665     if (docu->doc != NULL)
666         xmlFreeDoc(docu->doc);
667     if (docu->schema != NULL)
668         xmlRelaxNGFreeInnerSchema(docu->schema);
669     xmlFree(docu);
670 }
671 
672 /**
673  * xmlRelaxNGFreeDocumentList:
674  * @docu:  a list of  document structure
675  *
676  * Deallocate a RelaxNG document structures.
677  */
678 static void
xmlRelaxNGFreeDocumentList(xmlRelaxNGDocumentPtr docu)679 xmlRelaxNGFreeDocumentList(xmlRelaxNGDocumentPtr docu)
680 {
681     xmlRelaxNGDocumentPtr next;
682 
683     while (docu != NULL) {
684         next = docu->next;
685         xmlRelaxNGFreeDocument(docu);
686         docu = next;
687     }
688 }
689 
690 /**
691  * xmlRelaxNGFreeInclude:
692  * @incl:  a include structure
693  *
694  * Deallocate a RelaxNG include structure.
695  */
696 static void
xmlRelaxNGFreeInclude(xmlRelaxNGIncludePtr incl)697 xmlRelaxNGFreeInclude(xmlRelaxNGIncludePtr incl)
698 {
699     if (incl == NULL)
700         return;
701 
702     if (incl->href != NULL)
703         xmlFree(incl->href);
704     if (incl->doc != NULL)
705         xmlFreeDoc(incl->doc);
706     if (incl->schema != NULL)
707         xmlRelaxNGFree(incl->schema);
708     xmlFree(incl);
709 }
710 
711 /**
712  * xmlRelaxNGFreeIncludeList:
713  * @incl:  a include structure list
714  *
715  * Deallocate a RelaxNG include structure.
716  */
717 static void
xmlRelaxNGFreeIncludeList(xmlRelaxNGIncludePtr incl)718 xmlRelaxNGFreeIncludeList(xmlRelaxNGIncludePtr incl)
719 {
720     xmlRelaxNGIncludePtr next;
721 
722     while (incl != NULL) {
723         next = incl->next;
724         xmlRelaxNGFreeInclude(incl);
725         incl = next;
726     }
727 }
728 
729 /**
730  * xmlRelaxNGNewRelaxNG:
731  * @ctxt:  a Relax-NG validation context (optional)
732  *
733  * Allocate a new RelaxNG structure.
734  *
735  * Returns the newly allocated structure or NULL in case or error
736  */
737 static xmlRelaxNGPtr
xmlRelaxNGNewRelaxNG(xmlRelaxNGParserCtxtPtr ctxt)738 xmlRelaxNGNewRelaxNG(xmlRelaxNGParserCtxtPtr ctxt)
739 {
740     xmlRelaxNGPtr ret;
741 
742     ret = (xmlRelaxNGPtr) xmlMalloc(sizeof(xmlRelaxNG));
743     if (ret == NULL) {
744         xmlRngPErrMemory(ctxt);
745         return (NULL);
746     }
747     memset(ret, 0, sizeof(xmlRelaxNG));
748 
749     return (ret);
750 }
751 
752 /**
753  * xmlRelaxNGFreeInnerSchema:
754  * @schema:  a schema structure
755  *
756  * Deallocate a RelaxNG schema structure.
757  */
758 static void
xmlRelaxNGFreeInnerSchema(xmlRelaxNGPtr schema)759 xmlRelaxNGFreeInnerSchema(xmlRelaxNGPtr schema)
760 {
761     if (schema == NULL)
762         return;
763 
764     if (schema->doc != NULL)
765         xmlFreeDoc(schema->doc);
766     if (schema->defTab != NULL) {
767         int i;
768 
769         for (i = 0; i < schema->defNr; i++)
770             xmlRelaxNGFreeDefine(schema->defTab[i]);
771         xmlFree(schema->defTab);
772     }
773 
774     xmlFree(schema);
775 }
776 
777 /**
778  * xmlRelaxNGFree:
779  * @schema:  a schema structure
780  *
781  * Deallocate a RelaxNG structure.
782  */
783 void
xmlRelaxNGFree(xmlRelaxNGPtr schema)784 xmlRelaxNGFree(xmlRelaxNGPtr schema)
785 {
786     if (schema == NULL)
787         return;
788 
789     if (schema->topgrammar != NULL)
790         xmlRelaxNGFreeGrammar(schema->topgrammar);
791     if (schema->doc != NULL)
792         xmlFreeDoc(schema->doc);
793     if (schema->documents != NULL)
794         xmlRelaxNGFreeDocumentList(schema->documents);
795     if (schema->includes != NULL)
796         xmlRelaxNGFreeIncludeList(schema->includes);
797     if (schema->defTab != NULL) {
798         int i;
799 
800         for (i = 0; i < schema->defNr; i++)
801             xmlRelaxNGFreeDefine(schema->defTab[i]);
802         xmlFree(schema->defTab);
803     }
804 
805     xmlFree(schema);
806 }
807 
808 /**
809  * xmlRelaxNGNewGrammar:
810  * @ctxt:  a Relax-NG validation context (optional)
811  *
812  * Allocate a new RelaxNG grammar.
813  *
814  * Returns the newly allocated structure or NULL in case or error
815  */
816 static xmlRelaxNGGrammarPtr
xmlRelaxNGNewGrammar(xmlRelaxNGParserCtxtPtr ctxt)817 xmlRelaxNGNewGrammar(xmlRelaxNGParserCtxtPtr ctxt)
818 {
819     xmlRelaxNGGrammarPtr ret;
820 
821     ret = (xmlRelaxNGGrammarPtr) xmlMalloc(sizeof(xmlRelaxNGGrammar));
822     if (ret == NULL) {
823         xmlRngPErrMemory(ctxt);
824         return (NULL);
825     }
826     memset(ret, 0, sizeof(xmlRelaxNGGrammar));
827 
828     return (ret);
829 }
830 
831 /**
832  * xmlRelaxNGFreeGrammar:
833  * @grammar:  a grammar structure
834  *
835  * Deallocate a RelaxNG grammar structure.
836  */
837 static void
xmlRelaxNGFreeGrammar(xmlRelaxNGGrammarPtr grammar)838 xmlRelaxNGFreeGrammar(xmlRelaxNGGrammarPtr grammar)
839 {
840     if (grammar == NULL)
841         return;
842 
843     if (grammar->children != NULL) {
844         xmlRelaxNGFreeGrammar(grammar->children);
845     }
846     if (grammar->next != NULL) {
847         xmlRelaxNGFreeGrammar(grammar->next);
848     }
849     if (grammar->refs != NULL) {
850         xmlHashFree(grammar->refs, NULL);
851     }
852     if (grammar->defs != NULL) {
853         xmlHashFree(grammar->defs, NULL);
854     }
855 
856     xmlFree(grammar);
857 }
858 
859 /**
860  * xmlRelaxNGNewDefine:
861  * @ctxt:  a Relax-NG validation context
862  * @node:  the node in the input document.
863  *
864  * Allocate a new RelaxNG define.
865  *
866  * Returns the newly allocated structure or NULL in case or error
867  */
868 static xmlRelaxNGDefinePtr
xmlRelaxNGNewDefine(xmlRelaxNGParserCtxtPtr ctxt,xmlNodePtr node)869 xmlRelaxNGNewDefine(xmlRelaxNGParserCtxtPtr ctxt, xmlNodePtr node)
870 {
871     xmlRelaxNGDefinePtr ret;
872 
873     if (ctxt->defMax == 0) {
874         ctxt->defMax = 16;
875         ctxt->defNr = 0;
876         ctxt->defTab = (xmlRelaxNGDefinePtr *)
877             xmlMalloc(ctxt->defMax * sizeof(xmlRelaxNGDefinePtr));
878         if (ctxt->defTab == NULL) {
879             xmlRngPErrMemory(ctxt);
880             return (NULL);
881         }
882     } else if (ctxt->defMax <= ctxt->defNr) {
883         xmlRelaxNGDefinePtr *tmp;
884 
885         ctxt->defMax *= 2;
886         tmp = (xmlRelaxNGDefinePtr *) xmlRealloc(ctxt->defTab,
887                                                  ctxt->defMax *
888                                                  sizeof
889                                                  (xmlRelaxNGDefinePtr));
890         if (tmp == NULL) {
891             xmlRngPErrMemory(ctxt);
892             return (NULL);
893         }
894         ctxt->defTab = tmp;
895     }
896     ret = (xmlRelaxNGDefinePtr) xmlMalloc(sizeof(xmlRelaxNGDefine));
897     if (ret == NULL) {
898         xmlRngPErrMemory(ctxt);
899         return (NULL);
900     }
901     memset(ret, 0, sizeof(xmlRelaxNGDefine));
902     ctxt->defTab[ctxt->defNr++] = ret;
903     ret->node = node;
904     ret->depth = -1;
905     return (ret);
906 }
907 
908 /**
909  * xmlRelaxNGFreePartition:
910  * @partitions:  a partition set structure
911  *
912  * Deallocate RelaxNG partition set structures.
913  */
914 static void
xmlRelaxNGFreePartition(xmlRelaxNGPartitionPtr partitions)915 xmlRelaxNGFreePartition(xmlRelaxNGPartitionPtr partitions)
916 {
917     xmlRelaxNGInterleaveGroupPtr group;
918     int j;
919 
920     if (partitions != NULL) {
921         if (partitions->groups != NULL) {
922             for (j = 0; j < partitions->nbgroups; j++) {
923                 group = partitions->groups[j];
924                 if (group != NULL) {
925                     if (group->defs != NULL)
926                         xmlFree(group->defs);
927                     if (group->attrs != NULL)
928                         xmlFree(group->attrs);
929                     xmlFree(group);
930                 }
931             }
932             xmlFree(partitions->groups);
933         }
934         if (partitions->triage != NULL) {
935             xmlHashFree(partitions->triage, NULL);
936         }
937         xmlFree(partitions);
938     }
939 }
940 
941 /**
942  * xmlRelaxNGFreeDefine:
943  * @define:  a define structure
944  *
945  * Deallocate a RelaxNG define structure.
946  */
947 static void
xmlRelaxNGFreeDefine(xmlRelaxNGDefinePtr define)948 xmlRelaxNGFreeDefine(xmlRelaxNGDefinePtr define)
949 {
950     if (define == NULL)
951         return;
952 
953     if ((define->type == XML_RELAXNG_VALUE) && (define->attrs != NULL)) {
954         xmlRelaxNGTypeLibraryPtr lib;
955 
956         lib = (xmlRelaxNGTypeLibraryPtr) define->data;
957         if ((lib != NULL) && (lib->freef != NULL))
958             lib->freef(lib->data, (void *) define->attrs);
959     }
960     if ((define->data != NULL) && (define->type == XML_RELAXNG_INTERLEAVE))
961         xmlRelaxNGFreePartition((xmlRelaxNGPartitionPtr) define->data);
962     if ((define->data != NULL) && (define->type == XML_RELAXNG_CHOICE))
963         xmlHashFree((xmlHashTablePtr) define->data, NULL);
964     if (define->name != NULL)
965         xmlFree(define->name);
966     if (define->ns != NULL)
967         xmlFree(define->ns);
968     if (define->value != NULL)
969         xmlFree(define->value);
970     if (define->contModel != NULL)
971         xmlRegFreeRegexp(define->contModel);
972     xmlFree(define);
973 }
974 
975 /**
976  * xmlRelaxNGNewStates:
977  * @ctxt:  a Relax-NG validation context
978  * @size:  the default size for the container
979  *
980  * Allocate a new RelaxNG validation state container
981  *
982  * Returns the newly allocated structure or NULL in case or error
983  */
984 static xmlRelaxNGStatesPtr
xmlRelaxNGNewStates(xmlRelaxNGValidCtxtPtr ctxt,int size)985 xmlRelaxNGNewStates(xmlRelaxNGValidCtxtPtr ctxt, int size)
986 {
987     xmlRelaxNGStatesPtr ret;
988 
989     if ((ctxt != NULL) &&
990         (ctxt->freeStates != NULL) && (ctxt->freeStatesNr > 0)) {
991         ctxt->freeStatesNr--;
992         ret = ctxt->freeStates[ctxt->freeStatesNr];
993         ret->nbState = 0;
994         return (ret);
995     }
996     if (size < 16)
997         size = 16;
998 
999     ret = (xmlRelaxNGStatesPtr) xmlMalloc(sizeof(xmlRelaxNGStates) +
1000                                           (size -
1001                                            1) *
1002                                           sizeof(xmlRelaxNGValidStatePtr));
1003     if (ret == NULL) {
1004         xmlRngVErrMemory(ctxt);
1005         return (NULL);
1006     }
1007     ret->nbState = 0;
1008     ret->maxState = size;
1009     ret->tabState = (xmlRelaxNGValidStatePtr *) xmlMalloc((size) *
1010                                                           sizeof
1011                                                           (xmlRelaxNGValidStatePtr));
1012     if (ret->tabState == NULL) {
1013         xmlRngVErrMemory(ctxt);
1014         xmlFree(ret);
1015         return (NULL);
1016     }
1017     return (ret);
1018 }
1019 
1020 /**
1021  * xmlRelaxNGAddStateUniq:
1022  * @ctxt:  a Relax-NG validation context
1023  * @states:  the states container
1024  * @state:  the validation state
1025  *
1026  * Add a RelaxNG validation state to the container without checking
1027  * for unicity.
1028  *
1029  * Return 1 in case of success and 0 if this is a duplicate and -1 on error
1030  */
1031 static int
xmlRelaxNGAddStatesUniq(xmlRelaxNGValidCtxtPtr ctxt,xmlRelaxNGStatesPtr states,xmlRelaxNGValidStatePtr state)1032 xmlRelaxNGAddStatesUniq(xmlRelaxNGValidCtxtPtr ctxt,
1033                         xmlRelaxNGStatesPtr states,
1034                         xmlRelaxNGValidStatePtr state)
1035 {
1036     if (state == NULL) {
1037         return (-1);
1038     }
1039     if (states->nbState >= states->maxState) {
1040         xmlRelaxNGValidStatePtr *tmp;
1041         int size;
1042 
1043         size = states->maxState * 2;
1044         tmp = (xmlRelaxNGValidStatePtr *) xmlRealloc(states->tabState,
1045                                                      (size) *
1046                                                      sizeof
1047                                                      (xmlRelaxNGValidStatePtr));
1048         if (tmp == NULL) {
1049             xmlRngVErrMemory(ctxt);
1050             return (-1);
1051         }
1052         states->tabState = tmp;
1053         states->maxState = size;
1054     }
1055     states->tabState[states->nbState++] = state;
1056     return (1);
1057 }
1058 
1059 /**
1060  * xmlRelaxNGAddState:
1061  * @ctxt:  a Relax-NG validation context
1062  * @states:  the states container
1063  * @state:  the validation state
1064  *
1065  * Add a RelaxNG validation state to the container
1066  *
1067  * Return 1 in case of success and 0 if this is a duplicate and -1 on error
1068  */
1069 static int
xmlRelaxNGAddStates(xmlRelaxNGValidCtxtPtr ctxt,xmlRelaxNGStatesPtr states,xmlRelaxNGValidStatePtr state)1070 xmlRelaxNGAddStates(xmlRelaxNGValidCtxtPtr ctxt,
1071                     xmlRelaxNGStatesPtr states,
1072                     xmlRelaxNGValidStatePtr state)
1073 {
1074     int i;
1075 
1076     if (state == NULL || states == NULL) {
1077         return (-1);
1078     }
1079     if (states->nbState >= states->maxState) {
1080         xmlRelaxNGValidStatePtr *tmp;
1081         int size;
1082 
1083         size = states->maxState * 2;
1084         tmp = (xmlRelaxNGValidStatePtr *) xmlRealloc(states->tabState,
1085                                                      (size) *
1086                                                      sizeof
1087                                                      (xmlRelaxNGValidStatePtr));
1088         if (tmp == NULL) {
1089             xmlRngVErrMemory(ctxt);
1090             return (-1);
1091         }
1092         states->tabState = tmp;
1093         states->maxState = size;
1094     }
1095     for (i = 0; i < states->nbState; i++) {
1096         if (xmlRelaxNGEqualValidState(ctxt, state, states->tabState[i])) {
1097             xmlRelaxNGFreeValidState(ctxt, state);
1098             return (0);
1099         }
1100     }
1101     states->tabState[states->nbState++] = state;
1102     return (1);
1103 }
1104 
1105 /**
1106  * xmlRelaxNGFreeStates:
1107  * @ctxt:  a Relax-NG validation context
1108  * @states:  the container
1109  *
1110  * Free a RelaxNG validation state container
1111  */
1112 static void
xmlRelaxNGFreeStates(xmlRelaxNGValidCtxtPtr ctxt,xmlRelaxNGStatesPtr states)1113 xmlRelaxNGFreeStates(xmlRelaxNGValidCtxtPtr ctxt,
1114                      xmlRelaxNGStatesPtr states)
1115 {
1116     if (states == NULL)
1117         return;
1118     if ((ctxt != NULL) && (ctxt->freeStates == NULL)) {
1119         ctxt->freeStatesMax = 40;
1120         ctxt->freeStatesNr = 0;
1121         ctxt->freeStates = (xmlRelaxNGStatesPtr *)
1122             xmlMalloc(ctxt->freeStatesMax * sizeof(xmlRelaxNGStatesPtr));
1123         if (ctxt->freeStates == NULL) {
1124             xmlRngVErrMemory(ctxt);
1125         }
1126     } else if ((ctxt != NULL)
1127                && (ctxt->freeStatesNr >= ctxt->freeStatesMax)) {
1128         xmlRelaxNGStatesPtr *tmp;
1129 
1130         tmp = (xmlRelaxNGStatesPtr *) xmlRealloc(ctxt->freeStates,
1131                                                  2 * ctxt->freeStatesMax *
1132                                                  sizeof
1133                                                  (xmlRelaxNGStatesPtr));
1134         if (tmp == NULL) {
1135             xmlRngVErrMemory(ctxt);
1136             xmlFree(states->tabState);
1137             xmlFree(states);
1138             return;
1139         }
1140         ctxt->freeStates = tmp;
1141         ctxt->freeStatesMax *= 2;
1142     }
1143     if ((ctxt == NULL) || (ctxt->freeStates == NULL)) {
1144         xmlFree(states->tabState);
1145         xmlFree(states);
1146     } else {
1147         ctxt->freeStates[ctxt->freeStatesNr++] = states;
1148     }
1149 }
1150 
1151 /**
1152  * xmlRelaxNGNewValidState:
1153  * @ctxt:  a Relax-NG validation context
1154  * @node:  the current node or NULL for the document
1155  *
1156  * Allocate a new RelaxNG validation state
1157  *
1158  * Returns the newly allocated structure or NULL in case or error
1159  */
1160 static xmlRelaxNGValidStatePtr
xmlRelaxNGNewValidState(xmlRelaxNGValidCtxtPtr ctxt,xmlNodePtr node)1161 xmlRelaxNGNewValidState(xmlRelaxNGValidCtxtPtr ctxt, xmlNodePtr node)
1162 {
1163     xmlRelaxNGValidStatePtr ret;
1164     xmlAttrPtr attr;
1165     xmlAttrPtr attrs[MAX_ATTR];
1166     int nbAttrs = 0;
1167     xmlNodePtr root = NULL;
1168 
1169     if (node == NULL) {
1170         root = xmlDocGetRootElement(ctxt->doc);
1171         if (root == NULL)
1172             return (NULL);
1173     } else {
1174         attr = node->properties;
1175         while (attr != NULL) {
1176             if (nbAttrs < MAX_ATTR)
1177                 attrs[nbAttrs++] = attr;
1178             else
1179                 nbAttrs++;
1180             attr = attr->next;
1181         }
1182     }
1183     if ((ctxt->freeState != NULL) && (ctxt->freeState->nbState > 0)) {
1184         ctxt->freeState->nbState--;
1185         ret = ctxt->freeState->tabState[ctxt->freeState->nbState];
1186     } else {
1187         ret =
1188             (xmlRelaxNGValidStatePtr)
1189             xmlMalloc(sizeof(xmlRelaxNGValidState));
1190         if (ret == NULL) {
1191             xmlRngVErrMemory(ctxt);
1192             return (NULL);
1193         }
1194         memset(ret, 0, sizeof(xmlRelaxNGValidState));
1195     }
1196     ret->value = NULL;
1197     ret->endvalue = NULL;
1198     if (node == NULL) {
1199         ret->node = (xmlNodePtr) ctxt->doc;
1200         ret->seq = root;
1201     } else {
1202         ret->node = node;
1203         ret->seq = node->children;
1204     }
1205     ret->nbAttrs = 0;
1206     if (nbAttrs > 0) {
1207         if (ret->attrs == NULL) {
1208             if (nbAttrs < 4)
1209                 ret->maxAttrs = 4;
1210             else
1211                 ret->maxAttrs = nbAttrs;
1212             ret->attrs = (xmlAttrPtr *) xmlMalloc(ret->maxAttrs *
1213                                                   sizeof(xmlAttrPtr));
1214             if (ret->attrs == NULL) {
1215                 xmlRngVErrMemory(ctxt);
1216                 return (ret);
1217             }
1218         } else if (ret->maxAttrs < nbAttrs) {
1219             xmlAttrPtr *tmp;
1220 
1221             tmp = (xmlAttrPtr *) xmlRealloc(ret->attrs, nbAttrs *
1222                                             sizeof(xmlAttrPtr));
1223             if (tmp == NULL) {
1224                 xmlRngVErrMemory(ctxt);
1225                 return (ret);
1226             }
1227             ret->attrs = tmp;
1228             ret->maxAttrs = nbAttrs;
1229         }
1230         ret->nbAttrs = nbAttrs;
1231         if (nbAttrs < MAX_ATTR) {
1232             memcpy(ret->attrs, attrs, sizeof(xmlAttrPtr) * nbAttrs);
1233         } else {
1234             attr = node->properties;
1235             nbAttrs = 0;
1236             while (attr != NULL) {
1237                 ret->attrs[nbAttrs++] = attr;
1238                 attr = attr->next;
1239             }
1240         }
1241     }
1242     ret->nbAttrLeft = ret->nbAttrs;
1243     return (ret);
1244 }
1245 
1246 /**
1247  * xmlRelaxNGCopyValidState:
1248  * @ctxt:  a Relax-NG validation context
1249  * @state:  a validation state
1250  *
1251  * Copy the validation state
1252  *
1253  * Returns the newly allocated structure or NULL in case or error
1254  */
1255 static xmlRelaxNGValidStatePtr
xmlRelaxNGCopyValidState(xmlRelaxNGValidCtxtPtr ctxt,xmlRelaxNGValidStatePtr state)1256 xmlRelaxNGCopyValidState(xmlRelaxNGValidCtxtPtr ctxt,
1257                          xmlRelaxNGValidStatePtr state)
1258 {
1259     xmlRelaxNGValidStatePtr ret;
1260     unsigned int maxAttrs;
1261     xmlAttrPtr *attrs;
1262 
1263     if (state == NULL)
1264         return (NULL);
1265     if ((ctxt->freeState != NULL) && (ctxt->freeState->nbState > 0)) {
1266         ctxt->freeState->nbState--;
1267         ret = ctxt->freeState->tabState[ctxt->freeState->nbState];
1268     } else {
1269         ret =
1270             (xmlRelaxNGValidStatePtr)
1271             xmlMalloc(sizeof(xmlRelaxNGValidState));
1272         if (ret == NULL) {
1273             xmlRngVErrMemory(ctxt);
1274             return (NULL);
1275         }
1276         memset(ret, 0, sizeof(xmlRelaxNGValidState));
1277     }
1278     attrs = ret->attrs;
1279     maxAttrs = ret->maxAttrs;
1280     memcpy(ret, state, sizeof(xmlRelaxNGValidState));
1281     ret->attrs = attrs;
1282     ret->maxAttrs = maxAttrs;
1283     if (state->nbAttrs > 0) {
1284         if (ret->attrs == NULL) {
1285             ret->maxAttrs = state->maxAttrs;
1286             ret->attrs = (xmlAttrPtr *) xmlMalloc(ret->maxAttrs *
1287                                                   sizeof(xmlAttrPtr));
1288             if (ret->attrs == NULL) {
1289                 xmlRngVErrMemory(ctxt);
1290                 ret->nbAttrs = 0;
1291                 return (ret);
1292             }
1293         } else if (ret->maxAttrs < state->nbAttrs) {
1294             xmlAttrPtr *tmp;
1295 
1296             tmp = (xmlAttrPtr *) xmlRealloc(ret->attrs, state->maxAttrs *
1297                                             sizeof(xmlAttrPtr));
1298             if (tmp == NULL) {
1299                 xmlRngVErrMemory(ctxt);
1300                 ret->nbAttrs = 0;
1301                 return (ret);
1302             }
1303             ret->maxAttrs = state->maxAttrs;
1304             ret->attrs = tmp;
1305         }
1306         memcpy(ret->attrs, state->attrs,
1307                state->nbAttrs * sizeof(xmlAttrPtr));
1308     }
1309     return (ret);
1310 }
1311 
1312 /**
1313  * xmlRelaxNGEqualValidState:
1314  * @ctxt:  a Relax-NG validation context
1315  * @state1:  a validation state
1316  * @state2:  a validation state
1317  *
1318  * Compare the validation states for equality
1319  *
1320  * Returns 1 if equal, 0 otherwise
1321  */
1322 static int
xmlRelaxNGEqualValidState(xmlRelaxNGValidCtxtPtr ctxt ATTRIBUTE_UNUSED,xmlRelaxNGValidStatePtr state1,xmlRelaxNGValidStatePtr state2)1323 xmlRelaxNGEqualValidState(xmlRelaxNGValidCtxtPtr ctxt ATTRIBUTE_UNUSED,
1324                           xmlRelaxNGValidStatePtr state1,
1325                           xmlRelaxNGValidStatePtr state2)
1326 {
1327     int i;
1328 
1329     if ((state1 == NULL) || (state2 == NULL))
1330         return (0);
1331     if (state1 == state2)
1332         return (1);
1333     if (state1->node != state2->node)
1334         return (0);
1335     if (state1->seq != state2->seq)
1336         return (0);
1337     if (state1->nbAttrLeft != state2->nbAttrLeft)
1338         return (0);
1339     if (state1->nbAttrs != state2->nbAttrs)
1340         return (0);
1341     if (state1->endvalue != state2->endvalue)
1342         return (0);
1343     if ((state1->value != state2->value) &&
1344         (!xmlStrEqual(state1->value, state2->value)))
1345         return (0);
1346     for (i = 0; i < state1->nbAttrs; i++) {
1347         if (state1->attrs[i] != state2->attrs[i])
1348             return (0);
1349     }
1350     return (1);
1351 }
1352 
1353 /**
1354  * xmlRelaxNGFreeValidState:
1355  * @state:  a validation state structure
1356  *
1357  * Deallocate a RelaxNG validation state structure.
1358  */
1359 static void
xmlRelaxNGFreeValidState(xmlRelaxNGValidCtxtPtr ctxt,xmlRelaxNGValidStatePtr state)1360 xmlRelaxNGFreeValidState(xmlRelaxNGValidCtxtPtr ctxt,
1361                          xmlRelaxNGValidStatePtr state)
1362 {
1363     if (state == NULL)
1364         return;
1365 
1366     if ((ctxt != NULL) && (ctxt->freeState == NULL)) {
1367         ctxt->freeState = xmlRelaxNGNewStates(ctxt, 40);
1368     }
1369     if ((ctxt == NULL) || (ctxt->freeState == NULL)) {
1370         if (state->attrs != NULL)
1371             xmlFree(state->attrs);
1372         xmlFree(state);
1373     } else {
1374         xmlRelaxNGAddStatesUniq(ctxt, ctxt->freeState, state);
1375     }
1376 }
1377 
1378 /************************************************************************
1379  *									*
1380  *			Semi internal functions				*
1381  *									*
1382  ************************************************************************/
1383 
1384 /**
1385  * xmlRelaxParserSetFlag:
1386  * @ctxt: a RelaxNG parser context
1387  * @flags: a set of flags values
1388  *
1389  * Semi private function used to pass information to a parser context
1390  * which are a combination of xmlRelaxNGParserFlag .
1391  *
1392  * Returns 0 if success and -1 in case of error
1393  */
1394 int
xmlRelaxParserSetFlag(xmlRelaxNGParserCtxtPtr ctxt,int flags)1395 xmlRelaxParserSetFlag(xmlRelaxNGParserCtxtPtr ctxt, int flags)
1396 {
1397     if (ctxt == NULL) return(-1);
1398     if (flags & XML_RELAXNGP_FREE_DOC) {
1399         ctxt->crng |= XML_RELAXNGP_FREE_DOC;
1400 	flags -= XML_RELAXNGP_FREE_DOC;
1401     }
1402     if (flags & XML_RELAXNGP_CRNG) {
1403         ctxt->crng |= XML_RELAXNGP_CRNG;
1404 	flags -= XML_RELAXNGP_CRNG;
1405     }
1406     if (flags != 0) return(-1);
1407     return(0);
1408 }
1409 
1410 /************************************************************************
1411  *									*
1412  *			Document functions				*
1413  *									*
1414  ************************************************************************/
1415 static xmlDocPtr xmlRelaxNGCleanupDoc(xmlRelaxNGParserCtxtPtr ctxt,
1416                                       xmlDocPtr doc);
1417 
1418 static xmlDoc *
xmlRelaxReadFile(xmlRelaxNGParserCtxtPtr ctxt,const char * filename)1419 xmlRelaxReadFile(xmlRelaxNGParserCtxtPtr ctxt, const char *filename) {
1420     xmlParserCtxtPtr pctxt;
1421     xmlDocPtr doc;
1422 
1423     pctxt = xmlNewParserCtxt();
1424     if (pctxt == NULL) {
1425         xmlRngPErrMemory(ctxt);
1426         return(NULL);
1427     }
1428     if (ctxt->serror != NULL)
1429         xmlCtxtSetErrorHandler(pctxt, ctxt->serror, ctxt->userData);
1430     if (ctxt->resourceLoader != NULL)
1431         xmlCtxtSetResourceLoader(pctxt, ctxt->resourceLoader,
1432                                  ctxt->resourceCtxt);
1433     doc = xmlCtxtReadFile(pctxt, filename, NULL, 0);
1434     xmlFreeParserCtxt(pctxt);
1435 
1436     return(doc);
1437 }
1438 
1439 static xmlDoc *
xmlRelaxReadMemory(xmlRelaxNGParserCtxtPtr ctxt,const char * buf,int size)1440 xmlRelaxReadMemory(xmlRelaxNGParserCtxtPtr ctxt, const char *buf, int size) {
1441     xmlParserCtxtPtr pctxt;
1442     xmlDocPtr doc;
1443 
1444     pctxt = xmlNewParserCtxt();
1445     if (pctxt == NULL) {
1446         xmlRngPErrMemory(ctxt);
1447         return(NULL);
1448     }
1449     if (ctxt->serror != NULL)
1450         xmlCtxtSetErrorHandler(pctxt, ctxt->serror, ctxt->userData);
1451     if (ctxt->resourceLoader != NULL)
1452         xmlCtxtSetResourceLoader(pctxt, ctxt->resourceLoader,
1453                                  ctxt->resourceCtxt);
1454     doc = xmlCtxtReadMemory(pctxt, buf, size, NULL, NULL, 0);
1455     xmlFreeParserCtxt(pctxt);
1456 
1457     return(doc);
1458 }
1459 
1460 /**
1461  * xmlRelaxNGIncludePush:
1462  * @ctxt:  the parser context
1463  * @value:  the element doc
1464  *
1465  * Pushes a new include on top of the include stack
1466  *
1467  * Returns 0 in case of error, the index in the stack otherwise
1468  */
1469 static int
xmlRelaxNGIncludePush(xmlRelaxNGParserCtxtPtr ctxt,xmlRelaxNGIncludePtr value)1470 xmlRelaxNGIncludePush(xmlRelaxNGParserCtxtPtr ctxt,
1471                       xmlRelaxNGIncludePtr value)
1472 {
1473     if (ctxt->incTab == NULL) {
1474         ctxt->incMax = 4;
1475         ctxt->incNr = 0;
1476         ctxt->incTab =
1477             (xmlRelaxNGIncludePtr *) xmlMalloc(ctxt->incMax *
1478                                                sizeof(ctxt->incTab[0]));
1479         if (ctxt->incTab == NULL) {
1480             xmlRngPErrMemory(ctxt);
1481             return (0);
1482         }
1483     }
1484     if (ctxt->incNr >= ctxt->incMax) {
1485         ctxt->incMax *= 2;
1486         ctxt->incTab =
1487             (xmlRelaxNGIncludePtr *) xmlRealloc(ctxt->incTab,
1488                                                 ctxt->incMax *
1489                                                 sizeof(ctxt->incTab[0]));
1490         if (ctxt->incTab == NULL) {
1491             xmlRngPErrMemory(ctxt);
1492             return (0);
1493         }
1494     }
1495     ctxt->incTab[ctxt->incNr] = value;
1496     ctxt->inc = value;
1497     return (ctxt->incNr++);
1498 }
1499 
1500 /**
1501  * xmlRelaxNGIncludePop:
1502  * @ctxt: the parser context
1503  *
1504  * Pops the top include from the include stack
1505  *
1506  * Returns the include just removed
1507  */
1508 static xmlRelaxNGIncludePtr
xmlRelaxNGIncludePop(xmlRelaxNGParserCtxtPtr ctxt)1509 xmlRelaxNGIncludePop(xmlRelaxNGParserCtxtPtr ctxt)
1510 {
1511     xmlRelaxNGIncludePtr ret;
1512 
1513     if (ctxt->incNr <= 0)
1514         return (NULL);
1515     ctxt->incNr--;
1516     if (ctxt->incNr > 0)
1517         ctxt->inc = ctxt->incTab[ctxt->incNr - 1];
1518     else
1519         ctxt->inc = NULL;
1520     ret = ctxt->incTab[ctxt->incNr];
1521     ctxt->incTab[ctxt->incNr] = NULL;
1522     return (ret);
1523 }
1524 
1525 /**
1526  * xmlRelaxNGRemoveRedefine:
1527  * @ctxt: the parser context
1528  * @URL:  the normalized URL
1529  * @target:  the included target
1530  * @name:  the define name to eliminate
1531  *
1532  * Applies the elimination algorithm of 4.7
1533  *
1534  * Returns 0 in case of error, 1 in case of success.
1535  */
1536 static int
xmlRelaxNGRemoveRedefine(xmlRelaxNGParserCtxtPtr ctxt,const xmlChar * URL ATTRIBUTE_UNUSED,xmlNodePtr target,const xmlChar * name)1537 xmlRelaxNGRemoveRedefine(xmlRelaxNGParserCtxtPtr ctxt,
1538                          const xmlChar * URL ATTRIBUTE_UNUSED,
1539                          xmlNodePtr target, const xmlChar * name)
1540 {
1541     int found = 0;
1542     xmlNodePtr tmp, tmp2;
1543     xmlChar *name2;
1544 
1545     tmp = target;
1546     while (tmp != NULL) {
1547         tmp2 = tmp->next;
1548         if ((name == NULL) && (IS_RELAXNG(tmp, "start"))) {
1549             found = 1;
1550             xmlUnlinkNode(tmp);
1551             xmlFreeNode(tmp);
1552         } else if ((name != NULL) && (IS_RELAXNG(tmp, "define"))) {
1553             name2 = xmlGetProp(tmp, BAD_CAST "name");
1554             xmlRelaxNGNormExtSpace(name2);
1555             if (name2 != NULL) {
1556                 if (xmlStrEqual(name, name2)) {
1557                     found = 1;
1558                     xmlUnlinkNode(tmp);
1559                     xmlFreeNode(tmp);
1560                 }
1561                 xmlFree(name2);
1562             }
1563         } else if (IS_RELAXNG(tmp, "include")) {
1564             xmlChar *href = NULL;
1565             xmlRelaxNGDocumentPtr inc = tmp->psvi;
1566 
1567             if ((inc != NULL) && (inc->doc != NULL) &&
1568                 (inc->doc->children != NULL)) {
1569 
1570                 if (xmlStrEqual
1571                     (inc->doc->children->name, BAD_CAST "grammar")) {
1572                     if (xmlRelaxNGRemoveRedefine(ctxt, href,
1573                                                  xmlDocGetRootElement(inc->doc)->children,
1574                                                  name) == 1) {
1575                         found = 1;
1576                     }
1577                 }
1578             }
1579             if (xmlRelaxNGRemoveRedefine(ctxt, URL, tmp->children, name) == 1) {
1580                 found = 1;
1581             }
1582         }
1583         tmp = tmp2;
1584     }
1585     return (found);
1586 }
1587 
1588 /**
1589  * xmlRelaxNGLoadInclude:
1590  * @ctxt: the parser context
1591  * @URL:  the normalized URL
1592  * @node: the include node.
1593  * @ns:  the namespace passed from the context.
1594  *
1595  * First lookup if the document is already loaded into the parser context,
1596  * check against recursion. If not found the resource is loaded and
1597  * the content is preprocessed before being returned back to the caller.
1598  *
1599  * Returns the xmlRelaxNGIncludePtr or NULL in case of error
1600  */
1601 static xmlRelaxNGIncludePtr
xmlRelaxNGLoadInclude(xmlRelaxNGParserCtxtPtr ctxt,const xmlChar * URL,xmlNodePtr node,const xmlChar * ns)1602 xmlRelaxNGLoadInclude(xmlRelaxNGParserCtxtPtr ctxt, const xmlChar * URL,
1603                       xmlNodePtr node, const xmlChar * ns)
1604 {
1605     xmlRelaxNGIncludePtr ret = NULL;
1606     xmlDocPtr doc;
1607     int i;
1608     xmlNodePtr root, cur;
1609 
1610     /*
1611      * check against recursion in the stack
1612      */
1613     for (i = 0; i < ctxt->incNr; i++) {
1614         if (xmlStrEqual(ctxt->incTab[i]->href, URL)) {
1615             xmlRngPErr(ctxt, NULL, XML_RNGP_INCLUDE_RECURSE,
1616                        "Detected an Include recursion for %s\n", URL,
1617                        NULL);
1618             return (NULL);
1619         }
1620     }
1621 
1622     /*
1623      * load the document
1624      */
1625     doc = xmlRelaxReadFile(ctxt, (const char *) URL);
1626     if (doc == NULL) {
1627         xmlRngPErr(ctxt, node, XML_RNGP_PARSE_ERROR,
1628                    "xmlRelaxNG: could not load %s\n", URL, NULL);
1629         return (NULL);
1630     }
1631 
1632     /*
1633      * Allocate the document structures and register it first.
1634      */
1635     ret = (xmlRelaxNGIncludePtr) xmlMalloc(sizeof(xmlRelaxNGInclude));
1636     if (ret == NULL) {
1637         xmlRngPErrMemory(ctxt);
1638         xmlFreeDoc(doc);
1639         return (NULL);
1640     }
1641     memset(ret, 0, sizeof(xmlRelaxNGInclude));
1642     ret->doc = doc;
1643     ret->href = xmlStrdup(URL);
1644     ret->next = ctxt->includes;
1645     ctxt->includes = ret;
1646 
1647     /*
1648      * transmit the ns if needed
1649      */
1650     if (ns != NULL) {
1651         root = xmlDocGetRootElement(doc);
1652         if (root != NULL) {
1653             if (xmlHasProp(root, BAD_CAST "ns") == NULL) {
1654                 xmlSetProp(root, BAD_CAST "ns", ns);
1655             }
1656         }
1657     }
1658 
1659     /*
1660      * push it on the stack
1661      */
1662     xmlRelaxNGIncludePush(ctxt, ret);
1663 
1664     /*
1665      * Some preprocessing of the document content, this include recursing
1666      * in the include stack.
1667      */
1668 
1669     doc = xmlRelaxNGCleanupDoc(ctxt, doc);
1670     if (doc == NULL) {
1671         ctxt->inc = NULL;
1672         return (NULL);
1673     }
1674 
1675     /*
1676      * Pop up the include from the stack
1677      */
1678     xmlRelaxNGIncludePop(ctxt);
1679 
1680     /*
1681      * Check that the top element is a grammar
1682      */
1683     root = xmlDocGetRootElement(doc);
1684     if (root == NULL) {
1685         xmlRngPErr(ctxt, node, XML_RNGP_EMPTY,
1686                    "xmlRelaxNG: included document is empty %s\n", URL,
1687                    NULL);
1688         return (NULL);
1689     }
1690     if (!IS_RELAXNG(root, "grammar")) {
1691         xmlRngPErr(ctxt, node, XML_RNGP_GRAMMAR_MISSING,
1692                    "xmlRelaxNG: included document %s root is not a grammar\n",
1693                    URL, NULL);
1694         return (NULL);
1695     }
1696 
1697     /*
1698      * Elimination of redefined rules in the include.
1699      */
1700     cur = node->children;
1701     while (cur != NULL) {
1702         if (IS_RELAXNG(cur, "start")) {
1703             int found = 0;
1704 
1705             found =
1706                 xmlRelaxNGRemoveRedefine(ctxt, URL, root->children, NULL);
1707             if (!found) {
1708                 xmlRngPErr(ctxt, node, XML_RNGP_START_MISSING,
1709                            "xmlRelaxNG: include %s has a start but not the included grammar\n",
1710                            URL, NULL);
1711             }
1712         } else if (IS_RELAXNG(cur, "define")) {
1713             xmlChar *name;
1714 
1715             name = xmlGetProp(cur, BAD_CAST "name");
1716             if (name == NULL) {
1717                 xmlRngPErr(ctxt, node, XML_RNGP_NAME_MISSING,
1718                            "xmlRelaxNG: include %s has define without name\n",
1719                            URL, NULL);
1720             } else {
1721                 int found;
1722 
1723                 xmlRelaxNGNormExtSpace(name);
1724                 found = xmlRelaxNGRemoveRedefine(ctxt, URL,
1725                                                  root->children, name);
1726                 if (!found) {
1727                     xmlRngPErr(ctxt, node, XML_RNGP_DEFINE_MISSING,
1728                                "xmlRelaxNG: include %s has a define %s but not the included grammar\n",
1729                                URL, name);
1730                 }
1731                 xmlFree(name);
1732             }
1733         }
1734         if (IS_RELAXNG(cur, "div") && cur->children != NULL) {
1735             cur = cur->children;
1736         } else {
1737             if (cur->next != NULL) {
1738                 cur = cur->next;
1739             } else {
1740                 while (cur->parent != node && cur->parent->next == NULL) {
1741                     cur = cur->parent;
1742                 }
1743                 cur = cur->parent != node ? cur->parent->next : NULL;
1744             }
1745         }
1746     }
1747 
1748 
1749     return (ret);
1750 }
1751 
1752 /**
1753  * xmlRelaxNGValidErrorPush:
1754  * @ctxt:  the validation context
1755  * @err:  the error code
1756  * @arg1:  the first string argument
1757  * @arg2:  the second string argument
1758  * @dup:  arg need to be duplicated
1759  *
1760  * Pushes a new error on top of the error stack
1761  *
1762  * Returns 0 in case of error, the index in the stack otherwise
1763  */
1764 static int
xmlRelaxNGValidErrorPush(xmlRelaxNGValidCtxtPtr ctxt,xmlRelaxNGValidErr err,const xmlChar * arg1,const xmlChar * arg2,int dup)1765 xmlRelaxNGValidErrorPush(xmlRelaxNGValidCtxtPtr ctxt,
1766                          xmlRelaxNGValidErr err, const xmlChar * arg1,
1767                          const xmlChar * arg2, int dup)
1768 {
1769     xmlRelaxNGValidErrorPtr cur;
1770 
1771     if (ctxt->errTab == NULL) {
1772         ctxt->errMax = 8;
1773         ctxt->errNr = 0;
1774         ctxt->errTab =
1775             (xmlRelaxNGValidErrorPtr) xmlMalloc(ctxt->errMax *
1776                                                 sizeof
1777                                                 (xmlRelaxNGValidError));
1778         if (ctxt->errTab == NULL) {
1779             xmlRngVErrMemory(ctxt);
1780             return (0);
1781         }
1782         ctxt->err = NULL;
1783     }
1784     if (ctxt->errNr >= ctxt->errMax) {
1785         ctxt->errMax *= 2;
1786         ctxt->errTab =
1787             (xmlRelaxNGValidErrorPtr) xmlRealloc(ctxt->errTab,
1788                                                  ctxt->errMax *
1789                                                  sizeof
1790                                                  (xmlRelaxNGValidError));
1791         if (ctxt->errTab == NULL) {
1792             xmlRngVErrMemory(ctxt);
1793             return (0);
1794         }
1795         ctxt->err = &ctxt->errTab[ctxt->errNr - 1];
1796     }
1797     if ((ctxt->err != NULL) && (ctxt->state != NULL) &&
1798         (ctxt->err->node == ctxt->state->node) && (ctxt->err->err == err))
1799         return (ctxt->errNr);
1800     cur = &ctxt->errTab[ctxt->errNr];
1801     cur->err = err;
1802     if (dup) {
1803         cur->arg1 = xmlStrdup(arg1);
1804         cur->arg2 = xmlStrdup(arg2);
1805         cur->flags = ERROR_IS_DUP;
1806     } else {
1807         cur->arg1 = arg1;
1808         cur->arg2 = arg2;
1809         cur->flags = 0;
1810     }
1811     if (ctxt->state != NULL) {
1812         cur->node = ctxt->state->node;
1813         cur->seq = ctxt->state->seq;
1814     } else {
1815         cur->node = NULL;
1816         cur->seq = NULL;
1817     }
1818     ctxt->err = cur;
1819     return (ctxt->errNr++);
1820 }
1821 
1822 /**
1823  * xmlRelaxNGValidErrorPop:
1824  * @ctxt: the validation context
1825  *
1826  * Pops the top error from the error stack
1827  */
1828 static void
xmlRelaxNGValidErrorPop(xmlRelaxNGValidCtxtPtr ctxt)1829 xmlRelaxNGValidErrorPop(xmlRelaxNGValidCtxtPtr ctxt)
1830 {
1831     xmlRelaxNGValidErrorPtr cur;
1832 
1833     if (ctxt->errNr <= 0) {
1834         ctxt->err = NULL;
1835         return;
1836     }
1837     ctxt->errNr--;
1838     if (ctxt->errNr > 0)
1839         ctxt->err = &ctxt->errTab[ctxt->errNr - 1];
1840     else
1841         ctxt->err = NULL;
1842     cur = &ctxt->errTab[ctxt->errNr];
1843     if (cur->flags & ERROR_IS_DUP) {
1844         if (cur->arg1 != NULL)
1845             xmlFree((xmlChar *) cur->arg1);
1846         cur->arg1 = NULL;
1847         if (cur->arg2 != NULL)
1848             xmlFree((xmlChar *) cur->arg2);
1849         cur->arg2 = NULL;
1850         cur->flags = 0;
1851     }
1852 }
1853 
1854 /**
1855  * xmlRelaxNGDocumentPush:
1856  * @ctxt:  the parser context
1857  * @value:  the element doc
1858  *
1859  * Pushes a new doc on top of the doc stack
1860  *
1861  * Returns 0 in case of error, the index in the stack otherwise
1862  */
1863 static int
xmlRelaxNGDocumentPush(xmlRelaxNGParserCtxtPtr ctxt,xmlRelaxNGDocumentPtr value)1864 xmlRelaxNGDocumentPush(xmlRelaxNGParserCtxtPtr ctxt,
1865                        xmlRelaxNGDocumentPtr value)
1866 {
1867     if (ctxt->docTab == NULL) {
1868         ctxt->docMax = 4;
1869         ctxt->docNr = 0;
1870         ctxt->docTab =
1871             (xmlRelaxNGDocumentPtr *) xmlMalloc(ctxt->docMax *
1872                                                 sizeof(ctxt->docTab[0]));
1873         if (ctxt->docTab == NULL) {
1874             xmlRngPErrMemory(ctxt);
1875             return (0);
1876         }
1877     }
1878     if (ctxt->docNr >= ctxt->docMax) {
1879         ctxt->docMax *= 2;
1880         ctxt->docTab =
1881             (xmlRelaxNGDocumentPtr *) xmlRealloc(ctxt->docTab,
1882                                                  ctxt->docMax *
1883                                                  sizeof(ctxt->docTab[0]));
1884         if (ctxt->docTab == NULL) {
1885             xmlRngPErrMemory(ctxt);
1886             return (0);
1887         }
1888     }
1889     ctxt->docTab[ctxt->docNr] = value;
1890     ctxt->doc = value;
1891     return (ctxt->docNr++);
1892 }
1893 
1894 /**
1895  * xmlRelaxNGDocumentPop:
1896  * @ctxt: the parser context
1897  *
1898  * Pops the top doc from the doc stack
1899  *
1900  * Returns the doc just removed
1901  */
1902 static xmlRelaxNGDocumentPtr
xmlRelaxNGDocumentPop(xmlRelaxNGParserCtxtPtr ctxt)1903 xmlRelaxNGDocumentPop(xmlRelaxNGParserCtxtPtr ctxt)
1904 {
1905     xmlRelaxNGDocumentPtr ret;
1906 
1907     if (ctxt->docNr <= 0)
1908         return (NULL);
1909     ctxt->docNr--;
1910     if (ctxt->docNr > 0)
1911         ctxt->doc = ctxt->docTab[ctxt->docNr - 1];
1912     else
1913         ctxt->doc = NULL;
1914     ret = ctxt->docTab[ctxt->docNr];
1915     ctxt->docTab[ctxt->docNr] = NULL;
1916     return (ret);
1917 }
1918 
1919 /**
1920  * xmlRelaxNGLoadExternalRef:
1921  * @ctxt: the parser context
1922  * @URL:  the normalized URL
1923  * @ns:  the inherited ns if any
1924  *
1925  * First lookup if the document is already loaded into the parser context,
1926  * check against recursion. If not found the resource is loaded and
1927  * the content is preprocessed before being returned back to the caller.
1928  *
1929  * Returns the xmlRelaxNGDocumentPtr or NULL in case of error
1930  */
1931 static xmlRelaxNGDocumentPtr
xmlRelaxNGLoadExternalRef(xmlRelaxNGParserCtxtPtr ctxt,const xmlChar * URL,const xmlChar * ns)1932 xmlRelaxNGLoadExternalRef(xmlRelaxNGParserCtxtPtr ctxt,
1933                           const xmlChar * URL, const xmlChar * ns)
1934 {
1935     xmlRelaxNGDocumentPtr ret = NULL;
1936     xmlDocPtr doc;
1937     xmlNodePtr root;
1938     int i;
1939 
1940     /*
1941      * check against recursion in the stack
1942      */
1943     for (i = 0; i < ctxt->docNr; i++) {
1944         if (xmlStrEqual(ctxt->docTab[i]->href, URL)) {
1945             xmlRngPErr(ctxt, NULL, XML_RNGP_EXTERNALREF_RECURSE,
1946                        "Detected an externalRef recursion for %s\n", URL,
1947                        NULL);
1948             return (NULL);
1949         }
1950     }
1951 
1952     /*
1953      * load the document
1954      */
1955     doc = xmlRelaxReadFile(ctxt, (const char *) URL);
1956     if (doc == NULL) {
1957         xmlRngPErr(ctxt, NULL, XML_RNGP_PARSE_ERROR,
1958                    "xmlRelaxNG: could not load %s\n", URL, NULL);
1959         return (NULL);
1960     }
1961 
1962     /*
1963      * Allocate the document structures and register it first.
1964      */
1965     ret = (xmlRelaxNGDocumentPtr) xmlMalloc(sizeof(xmlRelaxNGDocument));
1966     if (ret == NULL) {
1967         xmlRngPErrMemory(ctxt);
1968         xmlFreeDoc(doc);
1969         return (NULL);
1970     }
1971     memset(ret, 0, sizeof(xmlRelaxNGDocument));
1972     ret->doc = doc;
1973     ret->href = xmlStrdup(URL);
1974     ret->next = ctxt->documents;
1975     ret->externalRef = 1;
1976     ctxt->documents = ret;
1977 
1978     /*
1979      * transmit the ns if needed
1980      */
1981     if (ns != NULL) {
1982         root = xmlDocGetRootElement(doc);
1983         if (root != NULL) {
1984             if (xmlHasProp(root, BAD_CAST "ns") == NULL) {
1985                 xmlSetProp(root, BAD_CAST "ns", ns);
1986             }
1987         }
1988     }
1989 
1990     /*
1991      * push it on the stack and register it in the hash table
1992      */
1993     xmlRelaxNGDocumentPush(ctxt, ret);
1994 
1995     /*
1996      * Some preprocessing of the document content
1997      */
1998     doc = xmlRelaxNGCleanupDoc(ctxt, doc);
1999     if (doc == NULL) {
2000         ctxt->doc = NULL;
2001         return (NULL);
2002     }
2003 
2004     xmlRelaxNGDocumentPop(ctxt);
2005 
2006     return (ret);
2007 }
2008 
2009 /************************************************************************
2010  *									*
2011  *			Error functions					*
2012  *									*
2013  ************************************************************************/
2014 
2015 #define VALID_ERR(a) xmlRelaxNGAddValidError(ctxt, a, NULL, NULL, 0);
2016 #define VALID_ERR2(a, b) xmlRelaxNGAddValidError(ctxt, a, b, NULL, 0);
2017 #define VALID_ERR3(a, b, c) xmlRelaxNGAddValidError(ctxt, a, b, c, 0);
2018 #define VALID_ERR2P(a, b) xmlRelaxNGAddValidError(ctxt, a, b, NULL, 1);
2019 #define VALID_ERR3P(a, b, c) xmlRelaxNGAddValidError(ctxt, a, b, c, 1);
2020 
2021 static const char *
xmlRelaxNGDefName(xmlRelaxNGDefinePtr def)2022 xmlRelaxNGDefName(xmlRelaxNGDefinePtr def)
2023 {
2024     if (def == NULL)
2025         return ("none");
2026     switch (def->type) {
2027         case XML_RELAXNG_EMPTY:
2028             return ("empty");
2029         case XML_RELAXNG_NOT_ALLOWED:
2030             return ("notAllowed");
2031         case XML_RELAXNG_EXCEPT:
2032             return ("except");
2033         case XML_RELAXNG_TEXT:
2034             return ("text");
2035         case XML_RELAXNG_ELEMENT:
2036             return ("element");
2037         case XML_RELAXNG_DATATYPE:
2038             return ("datatype");
2039         case XML_RELAXNG_VALUE:
2040             return ("value");
2041         case XML_RELAXNG_LIST:
2042             return ("list");
2043         case XML_RELAXNG_ATTRIBUTE:
2044             return ("attribute");
2045         case XML_RELAXNG_DEF:
2046             return ("def");
2047         case XML_RELAXNG_REF:
2048             return ("ref");
2049         case XML_RELAXNG_EXTERNALREF:
2050             return ("externalRef");
2051         case XML_RELAXNG_PARENTREF:
2052             return ("parentRef");
2053         case XML_RELAXNG_OPTIONAL:
2054             return ("optional");
2055         case XML_RELAXNG_ZEROORMORE:
2056             return ("zeroOrMore");
2057         case XML_RELAXNG_ONEORMORE:
2058             return ("oneOrMore");
2059         case XML_RELAXNG_CHOICE:
2060             return ("choice");
2061         case XML_RELAXNG_GROUP:
2062             return ("group");
2063         case XML_RELAXNG_INTERLEAVE:
2064             return ("interleave");
2065         case XML_RELAXNG_START:
2066             return ("start");
2067         case XML_RELAXNG_NOOP:
2068             return ("noop");
2069         case XML_RELAXNG_PARAM:
2070             return ("param");
2071     }
2072     return ("unknown");
2073 }
2074 
2075 /**
2076  * xmlRelaxNGGetErrorString:
2077  * @err:  the error code
2078  * @arg1:  the first string argument
2079  * @arg2:  the second string argument
2080  *
2081  * computes a formatted error string for the given error code and args
2082  *
2083  * Returns the error string, it must be deallocated by the caller
2084  */
2085 static xmlChar *
xmlRelaxNGGetErrorString(xmlRelaxNGValidErr err,const xmlChar * arg1,const xmlChar * arg2)2086 xmlRelaxNGGetErrorString(xmlRelaxNGValidErr err, const xmlChar * arg1,
2087                          const xmlChar * arg2)
2088 {
2089     char msg[1000];
2090     xmlChar *result;
2091 
2092     if (arg1 == NULL)
2093         arg1 = BAD_CAST "";
2094     if (arg2 == NULL)
2095         arg2 = BAD_CAST "";
2096 
2097     msg[0] = 0;
2098     switch (err) {
2099         case XML_RELAXNG_OK:
2100             return (NULL);
2101         case XML_RELAXNG_ERR_MEMORY:
2102             return (xmlCharStrdup("out of memory\n"));
2103         case XML_RELAXNG_ERR_TYPE:
2104             snprintf(msg, 1000, "failed to validate type %s\n", arg1);
2105             break;
2106         case XML_RELAXNG_ERR_TYPEVAL:
2107             snprintf(msg, 1000, "Type %s doesn't allow value '%s'\n", arg1,
2108                      arg2);
2109             break;
2110         case XML_RELAXNG_ERR_DUPID:
2111             snprintf(msg, 1000, "ID %s redefined\n", arg1);
2112             break;
2113         case XML_RELAXNG_ERR_TYPECMP:
2114             snprintf(msg, 1000, "failed to compare type %s\n", arg1);
2115             break;
2116         case XML_RELAXNG_ERR_NOSTATE:
2117             return (xmlCharStrdup("Internal error: no state\n"));
2118         case XML_RELAXNG_ERR_NODEFINE:
2119             return (xmlCharStrdup("Internal error: no define\n"));
2120         case XML_RELAXNG_ERR_INTERNAL:
2121             snprintf(msg, 1000, "Internal error: %s\n", arg1);
2122             break;
2123         case XML_RELAXNG_ERR_LISTEXTRA:
2124             snprintf(msg, 1000, "Extra data in list: %s\n", arg1);
2125             break;
2126         case XML_RELAXNG_ERR_INTERNODATA:
2127             return (xmlCharStrdup
2128                     ("Internal: interleave block has no data\n"));
2129         case XML_RELAXNG_ERR_INTERSEQ:
2130             return (xmlCharStrdup("Invalid sequence in interleave\n"));
2131         case XML_RELAXNG_ERR_INTEREXTRA:
2132             snprintf(msg, 1000, "Extra element %s in interleave\n", arg1);
2133             break;
2134         case XML_RELAXNG_ERR_ELEMNAME:
2135             snprintf(msg, 1000, "Expecting element %s, got %s\n", arg1,
2136                      arg2);
2137             break;
2138         case XML_RELAXNG_ERR_ELEMNONS:
2139             snprintf(msg, 1000, "Expecting a namespace for element %s\n",
2140                      arg1);
2141             break;
2142         case XML_RELAXNG_ERR_ELEMWRONGNS:
2143             snprintf(msg, 1000,
2144                      "Element %s has wrong namespace: expecting %s\n", arg1,
2145                      arg2);
2146             break;
2147         case XML_RELAXNG_ERR_ELEMWRONG:
2148             snprintf(msg, 1000, "Did not expect element %s there\n", arg1);
2149             break;
2150         case XML_RELAXNG_ERR_TEXTWRONG:
2151             snprintf(msg, 1000,
2152                      "Did not expect text in element %s content\n", arg1);
2153             break;
2154         case XML_RELAXNG_ERR_ELEMEXTRANS:
2155             snprintf(msg, 1000, "Expecting no namespace for element %s\n",
2156                      arg1);
2157             break;
2158         case XML_RELAXNG_ERR_ELEMNOTEMPTY:
2159             snprintf(msg, 1000, "Expecting element %s to be empty\n", arg1);
2160             break;
2161         case XML_RELAXNG_ERR_NOELEM:
2162             snprintf(msg, 1000, "Expecting an element %s, got nothing\n",
2163                      arg1);
2164             break;
2165         case XML_RELAXNG_ERR_NOTELEM:
2166             return (xmlCharStrdup("Expecting an element got text\n"));
2167         case XML_RELAXNG_ERR_ATTRVALID:
2168             snprintf(msg, 1000, "Element %s failed to validate attributes\n",
2169                      arg1);
2170             break;
2171         case XML_RELAXNG_ERR_CONTENTVALID:
2172             snprintf(msg, 1000, "Element %s failed to validate content\n",
2173                      arg1);
2174             break;
2175         case XML_RELAXNG_ERR_EXTRACONTENT:
2176             snprintf(msg, 1000, "Element %s has extra content: %s\n",
2177                      arg1, arg2);
2178             break;
2179         case XML_RELAXNG_ERR_INVALIDATTR:
2180             snprintf(msg, 1000, "Invalid attribute %s for element %s\n",
2181                      arg1, arg2);
2182             break;
2183         case XML_RELAXNG_ERR_LACKDATA:
2184             snprintf(msg, 1000, "Datatype element %s contains no data\n",
2185                      arg1);
2186             break;
2187         case XML_RELAXNG_ERR_DATAELEM:
2188             snprintf(msg, 1000, "Datatype element %s has child elements\n",
2189                      arg1);
2190             break;
2191         case XML_RELAXNG_ERR_VALELEM:
2192             snprintf(msg, 1000, "Value element %s has child elements\n",
2193                      arg1);
2194             break;
2195         case XML_RELAXNG_ERR_LISTELEM:
2196             snprintf(msg, 1000, "List element %s has child elements\n",
2197                      arg1);
2198             break;
2199         case XML_RELAXNG_ERR_DATATYPE:
2200             snprintf(msg, 1000, "Error validating datatype %s\n", arg1);
2201             break;
2202         case XML_RELAXNG_ERR_VALUE:
2203             snprintf(msg, 1000, "Error validating value %s\n", arg1);
2204             break;
2205         case XML_RELAXNG_ERR_LIST:
2206             return (xmlCharStrdup("Error validating list\n"));
2207         case XML_RELAXNG_ERR_NOGRAMMAR:
2208             return (xmlCharStrdup("No top grammar defined\n"));
2209         case XML_RELAXNG_ERR_EXTRADATA:
2210             return (xmlCharStrdup("Extra data in the document\n"));
2211         default:
2212             return (xmlCharStrdup("Unknown error !\n"));
2213     }
2214     if (msg[0] == 0) {
2215         snprintf(msg, 1000, "Unknown error code %d\n", err);
2216     }
2217     msg[1000 - 1] = 0;
2218     result = xmlCharStrdup(msg);
2219     return (xmlEscapeFormatString(&result));
2220 }
2221 
2222 /**
2223  * xmlRelaxNGShowValidError:
2224  * @ctxt:  the validation context
2225  * @err:  the error number
2226  * @node:  the node
2227  * @child:  the node child generating the problem.
2228  * @arg1:  the first argument
2229  * @arg2:  the second argument
2230  *
2231  * Show a validation error.
2232  */
2233 static void
xmlRelaxNGShowValidError(xmlRelaxNGValidCtxtPtr ctxt,xmlRelaxNGValidErr err,xmlNodePtr node,xmlNodePtr child,const xmlChar * arg1,const xmlChar * arg2)2234 xmlRelaxNGShowValidError(xmlRelaxNGValidCtxtPtr ctxt,
2235                          xmlRelaxNGValidErr err, xmlNodePtr node,
2236                          xmlNodePtr child, const xmlChar * arg1,
2237                          const xmlChar * arg2)
2238 {
2239     xmlChar *msg;
2240 
2241     if (ctxt->flags & FLAGS_NOERROR)
2242         return;
2243 
2244     msg = xmlRelaxNGGetErrorString(err, arg1, arg2);
2245     if (msg == NULL)
2246         return;
2247 
2248     if (ctxt->errNo == XML_RELAXNG_OK)
2249         ctxt->errNo = err;
2250     xmlRngVErr(ctxt, (child == NULL ? node : child), err,
2251                (const char *) msg, arg1, arg2);
2252     xmlFree(msg);
2253 }
2254 
2255 /**
2256  * xmlRelaxNGPopErrors:
2257  * @ctxt:  the validation context
2258  * @level:  the error level in the stack
2259  *
2260  * pop and discard all errors until the given level is reached
2261  */
2262 static void
xmlRelaxNGPopErrors(xmlRelaxNGValidCtxtPtr ctxt,int level)2263 xmlRelaxNGPopErrors(xmlRelaxNGValidCtxtPtr ctxt, int level)
2264 {
2265     int i;
2266     xmlRelaxNGValidErrorPtr err;
2267 
2268     for (i = level; i < ctxt->errNr; i++) {
2269         err = &ctxt->errTab[i];
2270         if (err->flags & ERROR_IS_DUP) {
2271             if (err->arg1 != NULL)
2272                 xmlFree((xmlChar *) err->arg1);
2273             err->arg1 = NULL;
2274             if (err->arg2 != NULL)
2275                 xmlFree((xmlChar *) err->arg2);
2276             err->arg2 = NULL;
2277             err->flags = 0;
2278         }
2279     }
2280     ctxt->errNr = level;
2281     if (ctxt->errNr <= 0)
2282         ctxt->err = NULL;
2283 }
2284 
2285 /**
2286  * xmlRelaxNGDumpValidError:
2287  * @ctxt:  the validation context
2288  *
2289  * Show all validation error over a given index.
2290  */
2291 static void
xmlRelaxNGDumpValidError(xmlRelaxNGValidCtxtPtr ctxt)2292 xmlRelaxNGDumpValidError(xmlRelaxNGValidCtxtPtr ctxt)
2293 {
2294     int i, j, k;
2295     xmlRelaxNGValidErrorPtr err, dup;
2296 
2297     for (i = 0, k = 0; i < ctxt->errNr; i++) {
2298         err = &ctxt->errTab[i];
2299         if (k < MAX_ERROR) {
2300             for (j = 0; j < i; j++) {
2301                 dup = &ctxt->errTab[j];
2302                 if ((err->err == dup->err) && (err->node == dup->node) &&
2303                     (xmlStrEqual(err->arg1, dup->arg1)) &&
2304                     (xmlStrEqual(err->arg2, dup->arg2))) {
2305                     goto skip;
2306                 }
2307             }
2308             xmlRelaxNGShowValidError(ctxt, err->err, err->node, err->seq,
2309                                      err->arg1, err->arg2);
2310             k++;
2311         }
2312       skip:
2313         if (err->flags & ERROR_IS_DUP) {
2314             if (err->arg1 != NULL)
2315                 xmlFree((xmlChar *) err->arg1);
2316             err->arg1 = NULL;
2317             if (err->arg2 != NULL)
2318                 xmlFree((xmlChar *) err->arg2);
2319             err->arg2 = NULL;
2320             err->flags = 0;
2321         }
2322     }
2323     ctxt->errNr = 0;
2324 }
2325 
2326 /**
2327  * xmlRelaxNGAddValidError:
2328  * @ctxt:  the validation context
2329  * @err:  the error number
2330  * @arg1:  the first argument
2331  * @arg2:  the second argument
2332  * @dup:  need to dup the args
2333  *
2334  * Register a validation error, either generating it if it's sure
2335  * or stacking it for later handling if unsure.
2336  */
2337 static void
xmlRelaxNGAddValidError(xmlRelaxNGValidCtxtPtr ctxt,xmlRelaxNGValidErr err,const xmlChar * arg1,const xmlChar * arg2,int dup)2338 xmlRelaxNGAddValidError(xmlRelaxNGValidCtxtPtr ctxt,
2339                         xmlRelaxNGValidErr err, const xmlChar * arg1,
2340                         const xmlChar * arg2, int dup)
2341 {
2342     if (ctxt == NULL)
2343         return;
2344     if (ctxt->flags & FLAGS_NOERROR)
2345         return;
2346 
2347     /*
2348      * generate the error directly
2349      */
2350     if (((ctxt->flags & FLAGS_IGNORABLE) == 0) ||
2351 	 (ctxt->flags & FLAGS_NEGATIVE)) {
2352         xmlNodePtr node, seq;
2353 
2354         /*
2355          * Flush first any stacked error which might be the
2356          * real cause of the problem.
2357          */
2358         if (ctxt->errNr != 0)
2359             xmlRelaxNGDumpValidError(ctxt);
2360         if (ctxt->state != NULL) {
2361             node = ctxt->state->node;
2362             seq = ctxt->state->seq;
2363         } else {
2364             node = seq = NULL;
2365         }
2366         if ((node == NULL) && (seq == NULL)) {
2367             node = ctxt->pnode;
2368         }
2369         xmlRelaxNGShowValidError(ctxt, err, node, seq, arg1, arg2);
2370     }
2371     /*
2372      * Stack the error for later processing if needed
2373      */
2374     else {
2375         xmlRelaxNGValidErrorPush(ctxt, err, arg1, arg2, dup);
2376     }
2377 }
2378 
2379 
2380 /************************************************************************
2381  *									*
2382  *			Type library hooks				*
2383  *									*
2384  ************************************************************************/
2385 static xmlChar *xmlRelaxNGNormalize(xmlRelaxNGValidCtxtPtr ctxt,
2386                                     const xmlChar * str);
2387 
2388 /**
2389  * xmlRelaxNGSchemaTypeHave:
2390  * @data:  data needed for the library
2391  * @type:  the type name
2392  *
2393  * Check if the given type is provided by
2394  * the W3C XMLSchema Datatype library.
2395  *
2396  * Returns 1 if yes, 0 if no and -1 in case of error.
2397  */
2398 static int
xmlRelaxNGSchemaTypeHave(void * data ATTRIBUTE_UNUSED,const xmlChar * type)2399 xmlRelaxNGSchemaTypeHave(void *data ATTRIBUTE_UNUSED, const xmlChar * type)
2400 {
2401     xmlSchemaTypePtr typ;
2402 
2403     if (type == NULL)
2404         return (-1);
2405     typ = xmlSchemaGetPredefinedType(type,
2406                                      BAD_CAST
2407                                      "http://www.w3.org/2001/XMLSchema");
2408     if (typ == NULL)
2409         return (0);
2410     return (1);
2411 }
2412 
2413 /**
2414  * xmlRelaxNGSchemaTypeCheck:
2415  * @data:  data needed for the library
2416  * @type:  the type name
2417  * @value:  the value to check
2418  * @node:  the node
2419  *
2420  * Check if the given type and value are validated by
2421  * the W3C XMLSchema Datatype library.
2422  *
2423  * Returns 1 if yes, 0 if no and -1 in case of error.
2424  */
2425 static int
xmlRelaxNGSchemaTypeCheck(void * data ATTRIBUTE_UNUSED,const xmlChar * type,const xmlChar * value,void ** result,xmlNodePtr node)2426 xmlRelaxNGSchemaTypeCheck(void *data ATTRIBUTE_UNUSED,
2427                           const xmlChar * type,
2428                           const xmlChar * value,
2429                           void **result, xmlNodePtr node)
2430 {
2431     xmlSchemaTypePtr typ;
2432     int ret;
2433 
2434     if ((type == NULL) || (value == NULL))
2435         return (-1);
2436     typ = xmlSchemaGetPredefinedType(type,
2437                                      BAD_CAST
2438                                      "http://www.w3.org/2001/XMLSchema");
2439     if (typ == NULL)
2440         return (-1);
2441     ret = xmlSchemaValPredefTypeNode(typ, value,
2442                                      (xmlSchemaValPtr *) result, node);
2443     if (ret == 2)               /* special ID error code */
2444         return (2);
2445     if (ret == 0)
2446         return (1);
2447     if (ret > 0)
2448         return (0);
2449     return (-1);
2450 }
2451 
2452 /**
2453  * xmlRelaxNGSchemaFacetCheck:
2454  * @data:  data needed for the library
2455  * @type:  the type name
2456  * @facet:  the facet name
2457  * @val:  the facet value
2458  * @strval:  the string value
2459  * @value:  the value to check
2460  *
2461  * Function provided by a type library to check a value facet
2462  *
2463  * Returns 1 if yes, 0 if no and -1 in case of error.
2464  */
2465 static int
xmlRelaxNGSchemaFacetCheck(void * data ATTRIBUTE_UNUSED,const xmlChar * type,const xmlChar * facetname,const xmlChar * val,const xmlChar * strval,void * value)2466 xmlRelaxNGSchemaFacetCheck(void *data ATTRIBUTE_UNUSED,
2467                            const xmlChar * type, const xmlChar * facetname,
2468                            const xmlChar * val, const xmlChar * strval,
2469                            void *value)
2470 {
2471     xmlSchemaFacetPtr facet;
2472     xmlSchemaTypePtr typ;
2473     int ret;
2474 
2475     if ((type == NULL) || (strval == NULL))
2476         return (-1);
2477     typ = xmlSchemaGetPredefinedType(type,
2478                                      BAD_CAST
2479                                      "http://www.w3.org/2001/XMLSchema");
2480     if (typ == NULL)
2481         return (-1);
2482 
2483     facet = xmlSchemaNewFacet();
2484     if (facet == NULL)
2485         return (-1);
2486 
2487     if (xmlStrEqual(facetname, BAD_CAST "minInclusive")) {
2488         facet->type = XML_SCHEMA_FACET_MININCLUSIVE;
2489     } else if (xmlStrEqual(facetname, BAD_CAST "minExclusive")) {
2490         facet->type = XML_SCHEMA_FACET_MINEXCLUSIVE;
2491     } else if (xmlStrEqual(facetname, BAD_CAST "maxInclusive")) {
2492         facet->type = XML_SCHEMA_FACET_MAXINCLUSIVE;
2493     } else if (xmlStrEqual(facetname, BAD_CAST "maxExclusive")) {
2494         facet->type = XML_SCHEMA_FACET_MAXEXCLUSIVE;
2495     } else if (xmlStrEqual(facetname, BAD_CAST "totalDigits")) {
2496         facet->type = XML_SCHEMA_FACET_TOTALDIGITS;
2497     } else if (xmlStrEqual(facetname, BAD_CAST "fractionDigits")) {
2498         facet->type = XML_SCHEMA_FACET_FRACTIONDIGITS;
2499     } else if (xmlStrEqual(facetname, BAD_CAST "pattern")) {
2500         facet->type = XML_SCHEMA_FACET_PATTERN;
2501     } else if (xmlStrEqual(facetname, BAD_CAST "enumeration")) {
2502         facet->type = XML_SCHEMA_FACET_ENUMERATION;
2503     } else if (xmlStrEqual(facetname, BAD_CAST "whiteSpace")) {
2504         facet->type = XML_SCHEMA_FACET_WHITESPACE;
2505     } else if (xmlStrEqual(facetname, BAD_CAST "length")) {
2506         facet->type = XML_SCHEMA_FACET_LENGTH;
2507     } else if (xmlStrEqual(facetname, BAD_CAST "maxLength")) {
2508         facet->type = XML_SCHEMA_FACET_MAXLENGTH;
2509     } else if (xmlStrEqual(facetname, BAD_CAST "minLength")) {
2510         facet->type = XML_SCHEMA_FACET_MINLENGTH;
2511     } else {
2512         xmlSchemaFreeFacet(facet);
2513         return (-1);
2514     }
2515     facet->value = val;
2516     ret = xmlSchemaCheckFacet(facet, typ, NULL, type);
2517     if (ret != 0) {
2518         xmlSchemaFreeFacet(facet);
2519         return (-1);
2520     }
2521     ret = xmlSchemaValidateFacet(typ, facet, strval, value);
2522     xmlSchemaFreeFacet(facet);
2523     if (ret != 0)
2524         return (-1);
2525     return (0);
2526 }
2527 
2528 /**
2529  * xmlRelaxNGSchemaFreeValue:
2530  * @data:  data needed for the library
2531  * @value:  the value to free
2532  *
2533  * Function provided by a type library to free a Schemas value
2534  *
2535  * Returns 1 if yes, 0 if no and -1 in case of error.
2536  */
2537 static void
xmlRelaxNGSchemaFreeValue(void * data ATTRIBUTE_UNUSED,void * value)2538 xmlRelaxNGSchemaFreeValue(void *data ATTRIBUTE_UNUSED, void *value)
2539 {
2540     xmlSchemaFreeValue(value);
2541 }
2542 
2543 /**
2544  * xmlRelaxNGSchemaTypeCompare:
2545  * @data:  data needed for the library
2546  * @type:  the type name
2547  * @value1:  the first value
2548  * @value2:  the second value
2549  *
2550  * Compare two values for equality accordingly a type from the W3C XMLSchema
2551  * Datatype library.
2552  *
2553  * Returns 1 if equal, 0 if no and -1 in case of error.
2554  */
2555 static int
xmlRelaxNGSchemaTypeCompare(void * data ATTRIBUTE_UNUSED,const xmlChar * type,const xmlChar * value1,xmlNodePtr ctxt1,void * comp1,const xmlChar * value2,xmlNodePtr ctxt2)2556 xmlRelaxNGSchemaTypeCompare(void *data ATTRIBUTE_UNUSED,
2557                             const xmlChar * type,
2558                             const xmlChar * value1,
2559                             xmlNodePtr ctxt1,
2560                             void *comp1,
2561                             const xmlChar * value2, xmlNodePtr ctxt2)
2562 {
2563     int ret;
2564     xmlSchemaTypePtr typ;
2565     xmlSchemaValPtr res1 = NULL, res2 = NULL;
2566 
2567     if ((type == NULL) || (value1 == NULL) || (value2 == NULL))
2568         return (-1);
2569     typ = xmlSchemaGetPredefinedType(type,
2570                                      BAD_CAST
2571                                      "http://www.w3.org/2001/XMLSchema");
2572     if (typ == NULL)
2573         return (-1);
2574     if (comp1 == NULL) {
2575         ret = xmlSchemaValPredefTypeNode(typ, value1, &res1, ctxt1);
2576         if (ret != 0)
2577             return (-1);
2578         if (res1 == NULL)
2579             return (-1);
2580     } else {
2581         res1 = (xmlSchemaValPtr) comp1;
2582     }
2583     ret = xmlSchemaValPredefTypeNode(typ, value2, &res2, ctxt2);
2584     if (ret != 0) {
2585 	if (res1 != (xmlSchemaValPtr) comp1)
2586 	    xmlSchemaFreeValue(res1);
2587         return (-1);
2588     }
2589     ret = xmlSchemaCompareValues(res1, res2);
2590     if (res1 != (xmlSchemaValPtr) comp1)
2591         xmlSchemaFreeValue(res1);
2592     xmlSchemaFreeValue(res2);
2593     if (ret == -2)
2594         return (-1);
2595     if (ret == 0)
2596         return (1);
2597     return (0);
2598 }
2599 
2600 /**
2601  * xmlRelaxNGDefaultTypeHave:
2602  * @data:  data needed for the library
2603  * @type:  the type name
2604  *
2605  * Check if the given type is provided by
2606  * the default datatype library.
2607  *
2608  * Returns 1 if yes, 0 if no and -1 in case of error.
2609  */
2610 static int
xmlRelaxNGDefaultTypeHave(void * data ATTRIBUTE_UNUSED,const xmlChar * type)2611 xmlRelaxNGDefaultTypeHave(void *data ATTRIBUTE_UNUSED,
2612                           const xmlChar * type)
2613 {
2614     if (type == NULL)
2615         return (-1);
2616     if (xmlStrEqual(type, BAD_CAST "string"))
2617         return (1);
2618     if (xmlStrEqual(type, BAD_CAST "token"))
2619         return (1);
2620     return (0);
2621 }
2622 
2623 /**
2624  * xmlRelaxNGDefaultTypeCheck:
2625  * @data:  data needed for the library
2626  * @type:  the type name
2627  * @value:  the value to check
2628  * @node:  the node
2629  *
2630  * Check if the given type and value are validated by
2631  * the default datatype library.
2632  *
2633  * Returns 1 if yes, 0 if no and -1 in case of error.
2634  */
2635 static int
xmlRelaxNGDefaultTypeCheck(void * data ATTRIBUTE_UNUSED,const xmlChar * type ATTRIBUTE_UNUSED,const xmlChar * value ATTRIBUTE_UNUSED,void ** result ATTRIBUTE_UNUSED,xmlNodePtr node ATTRIBUTE_UNUSED)2636 xmlRelaxNGDefaultTypeCheck(void *data ATTRIBUTE_UNUSED,
2637                            const xmlChar * type ATTRIBUTE_UNUSED,
2638                            const xmlChar * value ATTRIBUTE_UNUSED,
2639                            void **result ATTRIBUTE_UNUSED,
2640                            xmlNodePtr node ATTRIBUTE_UNUSED)
2641 {
2642     if (value == NULL)
2643         return (-1);
2644     if (xmlStrEqual(type, BAD_CAST "string"))
2645         return (1);
2646     if (xmlStrEqual(type, BAD_CAST "token")) {
2647         return (1);
2648     }
2649 
2650     return (0);
2651 }
2652 
2653 /**
2654  * xmlRelaxNGDefaultTypeCompare:
2655  * @data:  data needed for the library
2656  * @type:  the type name
2657  * @value1:  the first value
2658  * @value2:  the second value
2659  *
2660  * Compare two values accordingly a type from the default
2661  * datatype library.
2662  *
2663  * Returns 1 if yes, 0 if no and -1 in case of error.
2664  */
2665 static int
xmlRelaxNGDefaultTypeCompare(void * data ATTRIBUTE_UNUSED,const xmlChar * type,const xmlChar * value1,xmlNodePtr ctxt1 ATTRIBUTE_UNUSED,void * comp1 ATTRIBUTE_UNUSED,const xmlChar * value2,xmlNodePtr ctxt2 ATTRIBUTE_UNUSED)2666 xmlRelaxNGDefaultTypeCompare(void *data ATTRIBUTE_UNUSED,
2667                              const xmlChar * type,
2668                              const xmlChar * value1,
2669                              xmlNodePtr ctxt1 ATTRIBUTE_UNUSED,
2670                              void *comp1 ATTRIBUTE_UNUSED,
2671                              const xmlChar * value2,
2672                              xmlNodePtr ctxt2 ATTRIBUTE_UNUSED)
2673 {
2674     int ret = -1;
2675 
2676     if (xmlStrEqual(type, BAD_CAST "string")) {
2677         ret = xmlStrEqual(value1, value2);
2678     } else if (xmlStrEqual(type, BAD_CAST "token")) {
2679         if (!xmlStrEqual(value1, value2)) {
2680             xmlChar *nval, *nvalue;
2681 
2682             /*
2683              * TODO: trivial optimizations are possible by
2684              * computing at compile-time
2685              */
2686             nval = xmlRelaxNGNormalize(NULL, value1);
2687             nvalue = xmlRelaxNGNormalize(NULL, value2);
2688 
2689             if ((nval == NULL) || (nvalue == NULL))
2690                 ret = -1;
2691             else if (xmlStrEqual(nval, nvalue))
2692                 ret = 1;
2693             else
2694                 ret = 0;
2695             if (nval != NULL)
2696                 xmlFree(nval);
2697             if (nvalue != NULL)
2698                 xmlFree(nvalue);
2699         } else
2700             ret = 1;
2701     }
2702     return (ret);
2703 }
2704 
2705 static int xmlRelaxNGTypeInitialized = 0;
2706 static xmlHashTablePtr xmlRelaxNGRegisteredTypes = NULL;
2707 
2708 /**
2709  * xmlRelaxNGFreeTypeLibrary:
2710  * @lib:  the type library structure
2711  * @namespace:  the URI bound to the library
2712  *
2713  * Free the structure associated to the type library
2714  */
2715 static void
xmlRelaxNGFreeTypeLibrary(void * payload,const xmlChar * namespace ATTRIBUTE_UNUSED)2716 xmlRelaxNGFreeTypeLibrary(void *payload,
2717                           const xmlChar * namespace ATTRIBUTE_UNUSED)
2718 {
2719     xmlRelaxNGTypeLibraryPtr lib = (xmlRelaxNGTypeLibraryPtr) payload;
2720     if (lib == NULL)
2721         return;
2722     if (lib->namespace != NULL)
2723         xmlFree((xmlChar *) lib->namespace);
2724     xmlFree(lib);
2725 }
2726 
2727 /**
2728  * xmlRelaxNGRegisterTypeLibrary:
2729  * @namespace:  the URI bound to the library
2730  * @data:  data associated to the library
2731  * @have:  the provide function
2732  * @check:  the checking function
2733  * @comp:  the comparison function
2734  *
2735  * Register a new type library
2736  *
2737  * Returns 0 in case of success and -1 in case of error.
2738  */
2739 static int
xmlRelaxNGRegisterTypeLibrary(const xmlChar * namespace,void * data,xmlRelaxNGTypeHave have,xmlRelaxNGTypeCheck check,xmlRelaxNGTypeCompare comp,xmlRelaxNGFacetCheck facet,xmlRelaxNGTypeFree freef)2740 xmlRelaxNGRegisterTypeLibrary(const xmlChar * namespace, void *data,
2741                               xmlRelaxNGTypeHave have,
2742                               xmlRelaxNGTypeCheck check,
2743                               xmlRelaxNGTypeCompare comp,
2744                               xmlRelaxNGFacetCheck facet,
2745                               xmlRelaxNGTypeFree freef)
2746 {
2747     xmlRelaxNGTypeLibraryPtr lib;
2748     int ret;
2749 
2750     if ((xmlRelaxNGRegisteredTypes == NULL) || (namespace == NULL) ||
2751         (check == NULL) || (comp == NULL))
2752         return (-1);
2753     if (xmlHashLookup(xmlRelaxNGRegisteredTypes, namespace) != NULL)
2754         return (-1);
2755     lib =
2756         (xmlRelaxNGTypeLibraryPtr)
2757         xmlMalloc(sizeof(xmlRelaxNGTypeLibrary));
2758     if (lib == NULL) {
2759         xmlRngVErrMemory(NULL);
2760         return (-1);
2761     }
2762     memset(lib, 0, sizeof(xmlRelaxNGTypeLibrary));
2763     lib->namespace = xmlStrdup(namespace);
2764     lib->data = data;
2765     lib->have = have;
2766     lib->comp = comp;
2767     lib->check = check;
2768     lib->facet = facet;
2769     lib->freef = freef;
2770     ret = xmlHashAddEntry(xmlRelaxNGRegisteredTypes, namespace, lib);
2771     if (ret < 0) {
2772         xmlRelaxNGFreeTypeLibrary(lib, namespace);
2773         return (-1);
2774     }
2775     return (0);
2776 }
2777 
2778 /**
2779  * xmlRelaxNGInitTypes:
2780  *
2781  * Initialize the default type libraries.
2782  *
2783  * Returns 0 in case of success and -1 in case of error.
2784  */
2785 int
xmlRelaxNGInitTypes(void)2786 xmlRelaxNGInitTypes(void)
2787 {
2788     if (xmlRelaxNGTypeInitialized != 0)
2789         return (0);
2790     xmlRelaxNGRegisteredTypes = xmlHashCreate(10);
2791     if (xmlRelaxNGRegisteredTypes == NULL)
2792         return (-1);
2793     xmlRelaxNGRegisterTypeLibrary(BAD_CAST
2794                                   "http://www.w3.org/2001/XMLSchema-datatypes",
2795                                   NULL, xmlRelaxNGSchemaTypeHave,
2796                                   xmlRelaxNGSchemaTypeCheck,
2797                                   xmlRelaxNGSchemaTypeCompare,
2798                                   xmlRelaxNGSchemaFacetCheck,
2799                                   xmlRelaxNGSchemaFreeValue);
2800     xmlRelaxNGRegisterTypeLibrary(xmlRelaxNGNs, NULL,
2801                                   xmlRelaxNGDefaultTypeHave,
2802                                   xmlRelaxNGDefaultTypeCheck,
2803                                   xmlRelaxNGDefaultTypeCompare, NULL,
2804                                   NULL);
2805     xmlRelaxNGTypeInitialized = 1;
2806     return (0);
2807 }
2808 
2809 /**
2810  * xmlRelaxNGCleanupTypes:
2811  *
2812  * DEPRECATED: This function will be made private. Call xmlCleanupParser
2813  * to free global state but see the warnings there. xmlCleanupParser
2814  * should be only called once at program exit. In most cases, you don't
2815  * have call cleanup functions at all.
2816  *
2817  * Cleanup the default Schemas type library associated to RelaxNG
2818  */
2819 void
xmlRelaxNGCleanupTypes(void)2820 xmlRelaxNGCleanupTypes(void)
2821 {
2822     xmlSchemaCleanupTypes();
2823     if (xmlRelaxNGTypeInitialized == 0)
2824         return;
2825     xmlHashFree(xmlRelaxNGRegisteredTypes, xmlRelaxNGFreeTypeLibrary);
2826     xmlRelaxNGTypeInitialized = 0;
2827 }
2828 
2829 /************************************************************************
2830  *									*
2831  *		Compiling element content into regexp			*
2832  *									*
2833  * Sometime the element content can be compiled into a pure regexp,	*
2834  * This allows a faster execution and streamability at that level	*
2835  *									*
2836  ************************************************************************/
2837 
2838 static int xmlRelaxNGTryCompile(xmlRelaxNGParserCtxtPtr ctxt,
2839                                 xmlRelaxNGDefinePtr def);
2840 
2841 /**
2842  * xmlRelaxNGIsCompilable:
2843  * @define:  the definition to check
2844  *
2845  * Check if a definition is nullable.
2846  *
2847  * Returns 1 if yes, 0 if no and -1 in case of error
2848  */
2849 static int
xmlRelaxNGIsCompilable(xmlRelaxNGDefinePtr def)2850 xmlRelaxNGIsCompilable(xmlRelaxNGDefinePtr def)
2851 {
2852     int ret = -1;
2853 
2854     if (def == NULL) {
2855         return (-1);
2856     }
2857     if ((def->type != XML_RELAXNG_ELEMENT) &&
2858         (def->dflags & IS_COMPILABLE))
2859         return (1);
2860     if ((def->type != XML_RELAXNG_ELEMENT) &&
2861         (def->dflags & IS_NOT_COMPILABLE))
2862         return (0);
2863     switch (def->type) {
2864         case XML_RELAXNG_NOOP:
2865             ret = xmlRelaxNGIsCompilable(def->content);
2866             break;
2867         case XML_RELAXNG_TEXT:
2868         case XML_RELAXNG_EMPTY:
2869             ret = 1;
2870             break;
2871         case XML_RELAXNG_ELEMENT:
2872             /*
2873              * Check if the element content is compilable
2874              */
2875             if (((def->dflags & IS_NOT_COMPILABLE) == 0) &&
2876                 ((def->dflags & IS_COMPILABLE) == 0)) {
2877                 xmlRelaxNGDefinePtr list;
2878 
2879                 list = def->content;
2880                 while (list != NULL) {
2881                     ret = xmlRelaxNGIsCompilable(list);
2882                     if (ret != 1)
2883                         break;
2884                     list = list->next;
2885                 }
2886 		/*
2887 		 * Because the routine is recursive, we must guard against
2888 		 * discovering both COMPILABLE and NOT_COMPILABLE
2889 		 */
2890                 if (ret == 0) {
2891 		    def->dflags &= ~IS_COMPILABLE;
2892                     def->dflags |= IS_NOT_COMPILABLE;
2893 		}
2894                 if ((ret == 1) && !(def->dflags &= IS_NOT_COMPILABLE))
2895                     def->dflags |= IS_COMPILABLE;
2896             }
2897             /*
2898              * All elements return a compilable status unless they
2899              * are generic like anyName
2900              */
2901             if ((def->nameClass != NULL) || (def->name == NULL))
2902                 ret = 0;
2903             else
2904                 ret = 1;
2905             return (ret);
2906         case XML_RELAXNG_REF:
2907         case XML_RELAXNG_EXTERNALREF:
2908         case XML_RELAXNG_PARENTREF:
2909             if (def->depth == -20) {
2910                 return (1);
2911             } else {
2912                 xmlRelaxNGDefinePtr list;
2913 
2914                 def->depth = -20;
2915                 list = def->content;
2916                 while (list != NULL) {
2917                     ret = xmlRelaxNGIsCompilable(list);
2918                     if (ret != 1)
2919                         break;
2920                     list = list->next;
2921                 }
2922             }
2923             break;
2924         case XML_RELAXNG_START:
2925         case XML_RELAXNG_OPTIONAL:
2926         case XML_RELAXNG_ZEROORMORE:
2927         case XML_RELAXNG_ONEORMORE:
2928         case XML_RELAXNG_CHOICE:
2929         case XML_RELAXNG_GROUP:
2930         case XML_RELAXNG_DEF:{
2931                 xmlRelaxNGDefinePtr list;
2932 
2933                 list = def->content;
2934                 while (list != NULL) {
2935                     ret = xmlRelaxNGIsCompilable(list);
2936                     if (ret != 1)
2937                         break;
2938                     list = list->next;
2939                 }
2940                 break;
2941             }
2942         case XML_RELAXNG_EXCEPT:
2943         case XML_RELAXNG_ATTRIBUTE:
2944         case XML_RELAXNG_INTERLEAVE:
2945         case XML_RELAXNG_DATATYPE:
2946         case XML_RELAXNG_LIST:
2947         case XML_RELAXNG_PARAM:
2948         case XML_RELAXNG_VALUE:
2949         case XML_RELAXNG_NOT_ALLOWED:
2950             ret = 0;
2951             break;
2952     }
2953     if (ret == 0)
2954         def->dflags |= IS_NOT_COMPILABLE;
2955     if (ret == 1)
2956         def->dflags |= IS_COMPILABLE;
2957     return (ret);
2958 }
2959 
2960 /**
2961  * xmlRelaxNGCompile:
2962  * ctxt:  the RelaxNG parser context
2963  * @define:  the definition tree to compile
2964  *
2965  * Compile the set of definitions, it works recursively, till the
2966  * element boundaries, where it tries to compile the content if possible
2967  *
2968  * Returns 0 if success and -1 in case of error
2969  */
2970 static int
xmlRelaxNGCompile(xmlRelaxNGParserCtxtPtr ctxt,xmlRelaxNGDefinePtr def)2971 xmlRelaxNGCompile(xmlRelaxNGParserCtxtPtr ctxt, xmlRelaxNGDefinePtr def)
2972 {
2973     int ret = 0;
2974     xmlRelaxNGDefinePtr list;
2975 
2976     if ((ctxt == NULL) || (def == NULL))
2977         return (-1);
2978 
2979     switch (def->type) {
2980         case XML_RELAXNG_START:
2981             if ((xmlRelaxNGIsCompilable(def) == 1) && (def->depth != -25)) {
2982                 xmlAutomataPtr oldam = ctxt->am;
2983                 xmlAutomataStatePtr oldstate = ctxt->state;
2984 
2985                 def->depth = -25;
2986 
2987                 list = def->content;
2988                 ctxt->am = xmlNewAutomata();
2989                 if (ctxt->am == NULL)
2990                     return (-1);
2991 
2992                 /*
2993                  * assume identical strings but not same pointer are different
2994                  * atoms, needed for non-determinism detection
2995                  * That way if 2 elements with the same name are in a choice
2996                  * branch the automata is found non-deterministic and
2997                  * we fallback to the normal validation which does the right
2998                  * thing of exploring both choices.
2999                  */
3000                 xmlAutomataSetFlags(ctxt->am, 1);
3001 
3002                 ctxt->state = xmlAutomataGetInitState(ctxt->am);
3003                 while (list != NULL) {
3004                     xmlRelaxNGCompile(ctxt, list);
3005                     list = list->next;
3006                 }
3007                 xmlAutomataSetFinalState(ctxt->am, ctxt->state);
3008                 if (xmlAutomataIsDeterminist(ctxt->am))
3009                     def->contModel = xmlAutomataCompile(ctxt->am);
3010 
3011                 xmlFreeAutomata(ctxt->am);
3012                 ctxt->state = oldstate;
3013                 ctxt->am = oldam;
3014             }
3015             break;
3016         case XML_RELAXNG_ELEMENT:
3017             if ((ctxt->am != NULL) && (def->name != NULL)) {
3018                 ctxt->state = xmlAutomataNewTransition2(ctxt->am,
3019                                                         ctxt->state, NULL,
3020                                                         def->name, def->ns,
3021                                                         def);
3022             }
3023             if ((def->dflags & IS_COMPILABLE) && (def->depth != -25)) {
3024                 xmlAutomataPtr oldam = ctxt->am;
3025                 xmlAutomataStatePtr oldstate = ctxt->state;
3026 
3027                 def->depth = -25;
3028 
3029                 list = def->content;
3030                 ctxt->am = xmlNewAutomata();
3031                 if (ctxt->am == NULL)
3032                     return (-1);
3033                 xmlAutomataSetFlags(ctxt->am, 1);
3034                 ctxt->state = xmlAutomataGetInitState(ctxt->am);
3035                 while (list != NULL) {
3036                     xmlRelaxNGCompile(ctxt, list);
3037                     list = list->next;
3038                 }
3039                 xmlAutomataSetFinalState(ctxt->am, ctxt->state);
3040                 def->contModel = xmlAutomataCompile(ctxt->am);
3041                 if (!xmlRegexpIsDeterminist(def->contModel)) {
3042                     /*
3043                      * we can only use the automata if it is determinist
3044                      */
3045                     xmlRegFreeRegexp(def->contModel);
3046                     def->contModel = NULL;
3047                 }
3048                 xmlFreeAutomata(ctxt->am);
3049                 ctxt->state = oldstate;
3050                 ctxt->am = oldam;
3051             } else {
3052                 xmlAutomataPtr oldam = ctxt->am;
3053 
3054                 /*
3055                  * we can't build the content model for this element content
3056                  * but it still might be possible to build it for some of its
3057                  * children, recurse.
3058                  */
3059                 ret = xmlRelaxNGTryCompile(ctxt, def);
3060                 ctxt->am = oldam;
3061             }
3062             break;
3063         case XML_RELAXNG_NOOP:
3064             ret = xmlRelaxNGCompile(ctxt, def->content);
3065             break;
3066         case XML_RELAXNG_OPTIONAL:{
3067                 xmlAutomataStatePtr oldstate = ctxt->state;
3068 
3069                 list = def->content;
3070                 while (list != NULL) {
3071                     xmlRelaxNGCompile(ctxt, list);
3072                     list = list->next;
3073                 }
3074                 xmlAutomataNewEpsilon(ctxt->am, oldstate, ctxt->state);
3075                 break;
3076             }
3077         case XML_RELAXNG_ZEROORMORE:{
3078                 xmlAutomataStatePtr oldstate;
3079 
3080                 ctxt->state =
3081                     xmlAutomataNewEpsilon(ctxt->am, ctxt->state, NULL);
3082                 oldstate = ctxt->state;
3083                 list = def->content;
3084                 while (list != NULL) {
3085                     xmlRelaxNGCompile(ctxt, list);
3086                     list = list->next;
3087                 }
3088                 xmlAutomataNewEpsilon(ctxt->am, ctxt->state, oldstate);
3089                 ctxt->state =
3090                     xmlAutomataNewEpsilon(ctxt->am, oldstate, NULL);
3091                 break;
3092             }
3093         case XML_RELAXNG_ONEORMORE:{
3094                 xmlAutomataStatePtr oldstate;
3095 
3096                 list = def->content;
3097                 while (list != NULL) {
3098                     xmlRelaxNGCompile(ctxt, list);
3099                     list = list->next;
3100                 }
3101                 oldstate = ctxt->state;
3102                 list = def->content;
3103                 while (list != NULL) {
3104                     xmlRelaxNGCompile(ctxt, list);
3105                     list = list->next;
3106                 }
3107                 xmlAutomataNewEpsilon(ctxt->am, ctxt->state, oldstate);
3108                 ctxt->state =
3109                     xmlAutomataNewEpsilon(ctxt->am, oldstate, NULL);
3110                 break;
3111             }
3112         case XML_RELAXNG_CHOICE:{
3113                 xmlAutomataStatePtr target = NULL;
3114                 xmlAutomataStatePtr oldstate = ctxt->state;
3115 
3116                 list = def->content;
3117                 while (list != NULL) {
3118                     ctxt->state = oldstate;
3119                     ret = xmlRelaxNGCompile(ctxt, list);
3120                     if (ret != 0)
3121                         break;
3122                     if (target == NULL)
3123                         target = ctxt->state;
3124                     else {
3125                         xmlAutomataNewEpsilon(ctxt->am, ctxt->state,
3126                                               target);
3127                     }
3128                     list = list->next;
3129                 }
3130                 ctxt->state = target;
3131 
3132                 break;
3133             }
3134         case XML_RELAXNG_REF:
3135         case XML_RELAXNG_EXTERNALREF:
3136         case XML_RELAXNG_PARENTREF:
3137         case XML_RELAXNG_GROUP:
3138         case XML_RELAXNG_DEF:
3139             list = def->content;
3140             while (list != NULL) {
3141                 ret = xmlRelaxNGCompile(ctxt, list);
3142                 if (ret != 0)
3143                     break;
3144                 list = list->next;
3145             }
3146             break;
3147         case XML_RELAXNG_TEXT:{
3148                 xmlAutomataStatePtr oldstate;
3149 
3150                 ctxt->state =
3151                     xmlAutomataNewEpsilon(ctxt->am, ctxt->state, NULL);
3152                 oldstate = ctxt->state;
3153                 xmlRelaxNGCompile(ctxt, def->content);
3154                 xmlAutomataNewTransition(ctxt->am, ctxt->state,
3155                                          ctxt->state, BAD_CAST "#text",
3156                                          NULL);
3157                 ctxt->state =
3158                     xmlAutomataNewEpsilon(ctxt->am, oldstate, NULL);
3159                 break;
3160             }
3161         case XML_RELAXNG_EMPTY:
3162             ctxt->state =
3163                 xmlAutomataNewEpsilon(ctxt->am, ctxt->state, NULL);
3164             break;
3165         case XML_RELAXNG_EXCEPT:
3166         case XML_RELAXNG_ATTRIBUTE:
3167         case XML_RELAXNG_INTERLEAVE:
3168         case XML_RELAXNG_NOT_ALLOWED:
3169         case XML_RELAXNG_DATATYPE:
3170         case XML_RELAXNG_LIST:
3171         case XML_RELAXNG_PARAM:
3172         case XML_RELAXNG_VALUE:
3173             xmlRngPErr(ctxt, NULL, XML_ERR_INTERNAL_ERROR,
3174                        "RNG internal error trying to compile %s\n",
3175                        BAD_CAST xmlRelaxNGDefName(def), NULL);
3176             break;
3177     }
3178     return (ret);
3179 }
3180 
3181 /**
3182  * xmlRelaxNGTryCompile:
3183  * ctxt:  the RelaxNG parser context
3184  * @define:  the definition tree to compile
3185  *
3186  * Try to compile the set of definitions, it works recursively,
3187  * possibly ignoring parts which cannot be compiled.
3188  *
3189  * Returns 0 if success and -1 in case of error
3190  */
3191 static int
xmlRelaxNGTryCompile(xmlRelaxNGParserCtxtPtr ctxt,xmlRelaxNGDefinePtr def)3192 xmlRelaxNGTryCompile(xmlRelaxNGParserCtxtPtr ctxt, xmlRelaxNGDefinePtr def)
3193 {
3194     int ret = 0;
3195     xmlRelaxNGDefinePtr list;
3196 
3197     if ((ctxt == NULL) || (def == NULL))
3198         return (-1);
3199 
3200     if ((def->type == XML_RELAXNG_START) ||
3201         (def->type == XML_RELAXNG_ELEMENT)) {
3202         ret = xmlRelaxNGIsCompilable(def);
3203         if ((def->dflags & IS_COMPILABLE) && (def->depth != -25)) {
3204             ctxt->am = NULL;
3205             ret = xmlRelaxNGCompile(ctxt, def);
3206             return (ret);
3207         }
3208     }
3209     switch (def->type) {
3210         case XML_RELAXNG_NOOP:
3211             ret = xmlRelaxNGTryCompile(ctxt, def->content);
3212             break;
3213         case XML_RELAXNG_TEXT:
3214         case XML_RELAXNG_DATATYPE:
3215         case XML_RELAXNG_LIST:
3216         case XML_RELAXNG_PARAM:
3217         case XML_RELAXNG_VALUE:
3218         case XML_RELAXNG_EMPTY:
3219         case XML_RELAXNG_ELEMENT:
3220             ret = 0;
3221             break;
3222         case XML_RELAXNG_OPTIONAL:
3223         case XML_RELAXNG_ZEROORMORE:
3224         case XML_RELAXNG_ONEORMORE:
3225         case XML_RELAXNG_CHOICE:
3226         case XML_RELAXNG_GROUP:
3227         case XML_RELAXNG_DEF:
3228         case XML_RELAXNG_START:
3229         case XML_RELAXNG_REF:
3230         case XML_RELAXNG_EXTERNALREF:
3231         case XML_RELAXNG_PARENTREF:
3232             list = def->content;
3233             while (list != NULL) {
3234                 ret = xmlRelaxNGTryCompile(ctxt, list);
3235                 if (ret != 0)
3236                     break;
3237                 list = list->next;
3238             }
3239             break;
3240         case XML_RELAXNG_EXCEPT:
3241         case XML_RELAXNG_ATTRIBUTE:
3242         case XML_RELAXNG_INTERLEAVE:
3243         case XML_RELAXNG_NOT_ALLOWED:
3244             ret = 0;
3245             break;
3246     }
3247     return (ret);
3248 }
3249 
3250 /************************************************************************
3251  *									*
3252  *			Parsing functions				*
3253  *									*
3254  ************************************************************************/
3255 
3256 static xmlRelaxNGDefinePtr xmlRelaxNGParseAttribute(xmlRelaxNGParserCtxtPtr
3257                                                     ctxt, xmlNodePtr node);
3258 static xmlRelaxNGDefinePtr xmlRelaxNGParseElement(xmlRelaxNGParserCtxtPtr
3259                                                   ctxt, xmlNodePtr node);
3260 static xmlRelaxNGDefinePtr xmlRelaxNGParsePatterns(xmlRelaxNGParserCtxtPtr
3261                                                    ctxt, xmlNodePtr nodes,
3262                                                    int group);
3263 static xmlRelaxNGDefinePtr xmlRelaxNGParsePattern(xmlRelaxNGParserCtxtPtr
3264                                                   ctxt, xmlNodePtr node);
3265 static xmlRelaxNGPtr xmlRelaxNGParseDocument(xmlRelaxNGParserCtxtPtr ctxt,
3266                                              xmlNodePtr node);
3267 static int xmlRelaxNGParseGrammarContent(xmlRelaxNGParserCtxtPtr ctxt,
3268                                          xmlNodePtr nodes);
3269 static xmlRelaxNGDefinePtr xmlRelaxNGParseNameClass(xmlRelaxNGParserCtxtPtr
3270                                                     ctxt, xmlNodePtr node,
3271                                                     xmlRelaxNGDefinePtr
3272                                                     def);
3273 static xmlRelaxNGGrammarPtr xmlRelaxNGParseGrammar(xmlRelaxNGParserCtxtPtr
3274                                                    ctxt, xmlNodePtr nodes);
3275 static int xmlRelaxNGElementMatch(xmlRelaxNGValidCtxtPtr ctxt,
3276                                   xmlRelaxNGDefinePtr define,
3277                                   xmlNodePtr elem);
3278 
3279 
3280 #define IS_BLANK_NODE(n) (xmlRelaxNGIsBlank((n)->content))
3281 
3282 /**
3283  * xmlRelaxNGIsNullable:
3284  * @define:  the definition to verify
3285  *
3286  * Check if a definition is nullable.
3287  *
3288  * Returns 1 if yes, 0 if no and -1 in case of error
3289  */
3290 static int
xmlRelaxNGIsNullable(xmlRelaxNGDefinePtr define)3291 xmlRelaxNGIsNullable(xmlRelaxNGDefinePtr define)
3292 {
3293     int ret;
3294 
3295     if (define == NULL)
3296         return (-1);
3297 
3298     if (define->dflags & IS_NULLABLE)
3299         return (1);
3300     if (define->dflags & IS_NOT_NULLABLE)
3301         return (0);
3302     switch (define->type) {
3303         case XML_RELAXNG_EMPTY:
3304         case XML_RELAXNG_TEXT:
3305             ret = 1;
3306             break;
3307         case XML_RELAXNG_NOOP:
3308         case XML_RELAXNG_DEF:
3309         case XML_RELAXNG_REF:
3310         case XML_RELAXNG_EXTERNALREF:
3311         case XML_RELAXNG_PARENTREF:
3312         case XML_RELAXNG_ONEORMORE:
3313             ret = xmlRelaxNGIsNullable(define->content);
3314             break;
3315         case XML_RELAXNG_EXCEPT:
3316         case XML_RELAXNG_NOT_ALLOWED:
3317         case XML_RELAXNG_ELEMENT:
3318         case XML_RELAXNG_DATATYPE:
3319         case XML_RELAXNG_PARAM:
3320         case XML_RELAXNG_VALUE:
3321         case XML_RELAXNG_LIST:
3322         case XML_RELAXNG_ATTRIBUTE:
3323             ret = 0;
3324             break;
3325         case XML_RELAXNG_CHOICE:{
3326                 xmlRelaxNGDefinePtr list = define->content;
3327 
3328                 while (list != NULL) {
3329                     ret = xmlRelaxNGIsNullable(list);
3330                     if (ret != 0)
3331                         goto done;
3332                     list = list->next;
3333                 }
3334                 ret = 0;
3335                 break;
3336             }
3337         case XML_RELAXNG_START:
3338         case XML_RELAXNG_INTERLEAVE:
3339         case XML_RELAXNG_GROUP:{
3340                 xmlRelaxNGDefinePtr list = define->content;
3341 
3342                 while (list != NULL) {
3343                     ret = xmlRelaxNGIsNullable(list);
3344                     if (ret != 1)
3345                         goto done;
3346                     list = list->next;
3347                 }
3348                 return (1);
3349             }
3350         default:
3351             return (-1);
3352     }
3353   done:
3354     if (ret == 0)
3355         define->dflags |= IS_NOT_NULLABLE;
3356     if (ret == 1)
3357         define->dflags |= IS_NULLABLE;
3358     return (ret);
3359 }
3360 
3361 /**
3362  * xmlRelaxNGIsBlank:
3363  * @str:  a string
3364  *
3365  * Check if a string is ignorable c.f. 4.2. Whitespace
3366  *
3367  * Returns 1 if the string is NULL or made of blanks chars, 0 otherwise
3368  */
3369 static int
xmlRelaxNGIsBlank(xmlChar * str)3370 xmlRelaxNGIsBlank(xmlChar * str)
3371 {
3372     if (str == NULL)
3373         return (1);
3374     while (*str != 0) {
3375         if (!(IS_BLANK_CH(*str)))
3376             return (0);
3377         str++;
3378     }
3379     return (1);
3380 }
3381 
3382 /**
3383  * xmlRelaxNGGetDataTypeLibrary:
3384  * @ctxt:  a Relax-NG parser context
3385  * @node:  the current data or value element
3386  *
3387  * Applies algorithm from 4.3. datatypeLibrary attribute
3388  *
3389  * Returns the datatypeLibrary value or NULL if not found
3390  */
3391 static xmlChar *
xmlRelaxNGGetDataTypeLibrary(xmlRelaxNGParserCtxtPtr ctxt ATTRIBUTE_UNUSED,xmlNodePtr node)3392 xmlRelaxNGGetDataTypeLibrary(xmlRelaxNGParserCtxtPtr ctxt ATTRIBUTE_UNUSED,
3393                              xmlNodePtr node)
3394 {
3395     xmlChar *ret, *escape;
3396 
3397     if (node == NULL)
3398         return(NULL);
3399 
3400     if ((IS_RELAXNG(node, "data")) || (IS_RELAXNG(node, "value"))) {
3401         ret = xmlGetProp(node, BAD_CAST "datatypeLibrary");
3402         if (ret != NULL) {
3403             if (ret[0] == 0) {
3404                 xmlFree(ret);
3405                 return (NULL);
3406             }
3407             escape = xmlURIEscapeStr(ret, BAD_CAST ":/#?");
3408             if (escape == NULL) {
3409                 return (ret);
3410             }
3411             xmlFree(ret);
3412             return (escape);
3413         }
3414     }
3415     node = node->parent;
3416     while ((node != NULL) && (node->type == XML_ELEMENT_NODE)) {
3417         ret = xmlGetProp(node, BAD_CAST "datatypeLibrary");
3418         if (ret != NULL) {
3419             if (ret[0] == 0) {
3420                 xmlFree(ret);
3421                 return (NULL);
3422             }
3423             escape = xmlURIEscapeStr(ret, BAD_CAST ":/#?");
3424             if (escape == NULL) {
3425                 return (ret);
3426             }
3427             xmlFree(ret);
3428             return (escape);
3429         }
3430         node = node->parent;
3431     }
3432     return (NULL);
3433 }
3434 
3435 /**
3436  * xmlRelaxNGParseValue:
3437  * @ctxt:  a Relax-NG parser context
3438  * @node:  the data node.
3439  *
3440  * parse the content of a RelaxNG value node.
3441  *
3442  * Returns the definition pointer or NULL in case of error
3443  */
3444 static xmlRelaxNGDefinePtr
xmlRelaxNGParseValue(xmlRelaxNGParserCtxtPtr ctxt,xmlNodePtr node)3445 xmlRelaxNGParseValue(xmlRelaxNGParserCtxtPtr ctxt, xmlNodePtr node)
3446 {
3447     xmlRelaxNGDefinePtr def = NULL;
3448     xmlRelaxNGTypeLibraryPtr lib = NULL;
3449     xmlChar *type;
3450     xmlChar *library;
3451     int success = 0;
3452 
3453     def = xmlRelaxNGNewDefine(ctxt, node);
3454     if (def == NULL)
3455         return (NULL);
3456     def->type = XML_RELAXNG_VALUE;
3457 
3458     type = xmlGetProp(node, BAD_CAST "type");
3459     if (type != NULL) {
3460         xmlRelaxNGNormExtSpace(type);
3461         if (xmlValidateNCName(type, 0)) {
3462             xmlRngPErr(ctxt, node, XML_RNGP_TYPE_VALUE,
3463                        "value type '%s' is not an NCName\n", type, NULL);
3464         }
3465         library = xmlRelaxNGGetDataTypeLibrary(ctxt, node);
3466         if (library == NULL)
3467             library =
3468                 xmlStrdup(BAD_CAST "http://relaxng.org/ns/structure/1.0");
3469 
3470         def->name = type;
3471         def->ns = library;
3472 
3473         lib = (xmlRelaxNGTypeLibraryPtr)
3474             xmlHashLookup(xmlRelaxNGRegisteredTypes, library);
3475         if (lib == NULL) {
3476             xmlRngPErr(ctxt, node, XML_RNGP_UNKNOWN_TYPE_LIB,
3477                        "Use of unregistered type library '%s'\n", library,
3478                        NULL);
3479             def->data = NULL;
3480         } else {
3481             def->data = lib;
3482             if (lib->have == NULL) {
3483                 xmlRngPErr(ctxt, node, XML_RNGP_ERROR_TYPE_LIB,
3484                            "Internal error with type library '%s': no 'have'\n",
3485                            library, NULL);
3486             } else {
3487                 success = lib->have(lib->data, def->name);
3488                 if (success != 1) {
3489                     xmlRngPErr(ctxt, node, XML_RNGP_TYPE_NOT_FOUND,
3490                                "Error type '%s' is not exported by type library '%s'\n",
3491                                def->name, library);
3492                 }
3493             }
3494         }
3495     }
3496     if (node->children == NULL) {
3497         def->value = xmlStrdup(BAD_CAST "");
3498     } else if (((node->children->type != XML_TEXT_NODE) &&
3499                 (node->children->type != XML_CDATA_SECTION_NODE)) ||
3500                (node->children->next != NULL)) {
3501         xmlRngPErr(ctxt, node, XML_RNGP_TEXT_EXPECTED,
3502                    "Expecting a single text value for <value>content\n",
3503                    NULL, NULL);
3504     } else if (def != NULL) {
3505         def->value = xmlNodeGetContent(node);
3506         if (def->value == NULL) {
3507             xmlRngPErr(ctxt, node, XML_RNGP_VALUE_NO_CONTENT,
3508                        "Element <value> has no content\n", NULL, NULL);
3509         } else if ((lib != NULL) && (lib->check != NULL) && (success == 1)) {
3510             void *val = NULL;
3511 
3512             success =
3513                 lib->check(lib->data, def->name, def->value, &val, node);
3514             if (success != 1) {
3515                 xmlRngPErr(ctxt, node, XML_RNGP_INVALID_VALUE,
3516                            "Value '%s' is not acceptable for type '%s'\n",
3517                            def->value, def->name);
3518             } else {
3519                 if (val != NULL)
3520                     def->attrs = val;
3521             }
3522         }
3523     }
3524     return (def);
3525 }
3526 
3527 /**
3528  * xmlRelaxNGParseData:
3529  * @ctxt:  a Relax-NG parser context
3530  * @node:  the data node.
3531  *
3532  * parse the content of a RelaxNG data node.
3533  *
3534  * Returns the definition pointer or NULL in case of error
3535  */
3536 static xmlRelaxNGDefinePtr
xmlRelaxNGParseData(xmlRelaxNGParserCtxtPtr ctxt,xmlNodePtr node)3537 xmlRelaxNGParseData(xmlRelaxNGParserCtxtPtr ctxt, xmlNodePtr node)
3538 {
3539     xmlRelaxNGDefinePtr def = NULL, except;
3540     xmlRelaxNGDefinePtr param, lastparam = NULL;
3541     xmlRelaxNGTypeLibraryPtr lib;
3542     xmlChar *type;
3543     xmlChar *library;
3544     xmlNodePtr content;
3545     int tmp;
3546 
3547     type = xmlGetProp(node, BAD_CAST "type");
3548     if (type == NULL) {
3549         xmlRngPErr(ctxt, node, XML_RNGP_TYPE_MISSING, "data has no type\n", NULL,
3550                    NULL);
3551         return (NULL);
3552     }
3553     xmlRelaxNGNormExtSpace(type);
3554     if (xmlValidateNCName(type, 0)) {
3555         xmlRngPErr(ctxt, node, XML_RNGP_TYPE_VALUE,
3556                    "data type '%s' is not an NCName\n", type, NULL);
3557     }
3558     library = xmlRelaxNGGetDataTypeLibrary(ctxt, node);
3559     if (library == NULL)
3560         library =
3561             xmlStrdup(BAD_CAST "http://relaxng.org/ns/structure/1.0");
3562 
3563     def = xmlRelaxNGNewDefine(ctxt, node);
3564     if (def == NULL) {
3565         xmlFree(library);
3566         xmlFree(type);
3567         return (NULL);
3568     }
3569     def->type = XML_RELAXNG_DATATYPE;
3570     def->name = type;
3571     def->ns = library;
3572 
3573     lib = (xmlRelaxNGTypeLibraryPtr)
3574         xmlHashLookup(xmlRelaxNGRegisteredTypes, library);
3575     if (lib == NULL) {
3576         xmlRngPErr(ctxt, node, XML_RNGP_UNKNOWN_TYPE_LIB,
3577                    "Use of unregistered type library '%s'\n", library,
3578                    NULL);
3579         def->data = NULL;
3580     } else {
3581         def->data = lib;
3582         if (lib->have == NULL) {
3583             xmlRngPErr(ctxt, node, XML_RNGP_ERROR_TYPE_LIB,
3584                        "Internal error with type library '%s': no 'have'\n",
3585                        library, NULL);
3586         } else {
3587             tmp = lib->have(lib->data, def->name);
3588             if (tmp != 1) {
3589                 xmlRngPErr(ctxt, node, XML_RNGP_TYPE_NOT_FOUND,
3590                            "Error type '%s' is not exported by type library '%s'\n",
3591                            def->name, library);
3592             } else
3593                 if ((xmlStrEqual
3594                      (library,
3595                       BAD_CAST
3596                       "http://www.w3.org/2001/XMLSchema-datatypes"))
3597                     && ((xmlStrEqual(def->name, BAD_CAST "IDREF"))
3598                         || (xmlStrEqual(def->name, BAD_CAST "IDREFS")))) {
3599                 ctxt->idref = 1;
3600             }
3601         }
3602     }
3603     content = node->children;
3604 
3605     /*
3606      * Handle optional params
3607      */
3608     while (content != NULL) {
3609         if (!xmlStrEqual(content->name, BAD_CAST "param"))
3610             break;
3611         if (xmlStrEqual(library,
3612                         BAD_CAST "http://relaxng.org/ns/structure/1.0")) {
3613             xmlRngPErr(ctxt, node, XML_RNGP_PARAM_FORBIDDEN,
3614                        "Type library '%s' does not allow type parameters\n",
3615                        library, NULL);
3616             content = content->next;
3617             while ((content != NULL) &&
3618                    (xmlStrEqual(content->name, BAD_CAST "param")))
3619                 content = content->next;
3620         } else {
3621             param = xmlRelaxNGNewDefine(ctxt, node);
3622             if (param != NULL) {
3623                 param->type = XML_RELAXNG_PARAM;
3624                 param->name = xmlGetProp(content, BAD_CAST "name");
3625                 if (param->name == NULL) {
3626                     xmlRngPErr(ctxt, node, XML_RNGP_PARAM_NAME_MISSING,
3627                                "param has no name\n", NULL, NULL);
3628                 }
3629                 param->value = xmlNodeGetContent(content);
3630                 if (lastparam == NULL) {
3631                     def->attrs = lastparam = param;
3632                 } else {
3633                     lastparam->next = param;
3634                     lastparam = param;
3635                 }
3636                 if (lib != NULL) {
3637                 }
3638             }
3639             content = content->next;
3640         }
3641     }
3642     /*
3643      * Handle optional except
3644      */
3645     if ((content != NULL)
3646         && (xmlStrEqual(content->name, BAD_CAST "except"))) {
3647         xmlNodePtr child;
3648         xmlRelaxNGDefinePtr tmp2, last = NULL;
3649 
3650         except = xmlRelaxNGNewDefine(ctxt, node);
3651         if (except == NULL) {
3652             return (def);
3653         }
3654         except->type = XML_RELAXNG_EXCEPT;
3655         child = content->children;
3656 	def->content = except;
3657         if (child == NULL) {
3658             xmlRngPErr(ctxt, content, XML_RNGP_EXCEPT_NO_CONTENT,
3659                        "except has no content\n", NULL, NULL);
3660         }
3661         while (child != NULL) {
3662             tmp2 = xmlRelaxNGParsePattern(ctxt, child);
3663             if (tmp2 != NULL) {
3664                 if (last == NULL) {
3665                     except->content = last = tmp2;
3666                 } else {
3667                     last->next = tmp2;
3668                     last = tmp2;
3669                 }
3670             }
3671             child = child->next;
3672         }
3673         content = content->next;
3674     }
3675     /*
3676      * Check there is no unhandled data
3677      */
3678     if (content != NULL) {
3679         xmlRngPErr(ctxt, content, XML_RNGP_DATA_CONTENT,
3680                    "Element data has unexpected content %s\n",
3681                    content->name, NULL);
3682     }
3683 
3684     return (def);
3685 }
3686 
3687 static const xmlChar *invalidName = BAD_CAST "\1";
3688 
3689 /**
3690  * xmlRelaxNGCompareNameClasses:
3691  * @defs1:  the first element/attribute defs
3692  * @defs2:  the second element/attribute defs
3693  * @name:  the restriction on the name
3694  * @ns:  the restriction on the namespace
3695  *
3696  * Compare the 2 lists of element definitions. The comparison is
3697  * that if both lists do not accept the same QNames, it returns 1
3698  * If the 2 lists can accept the same QName the comparison returns 0
3699  *
3700  * Returns 1 distinct, 0 if equal
3701  */
3702 static int
xmlRelaxNGCompareNameClasses(xmlRelaxNGDefinePtr def1,xmlRelaxNGDefinePtr def2)3703 xmlRelaxNGCompareNameClasses(xmlRelaxNGDefinePtr def1,
3704                              xmlRelaxNGDefinePtr def2)
3705 {
3706     int ret = 1;
3707     xmlNode node;
3708     xmlNs ns;
3709     xmlRelaxNGValidCtxt ctxt;
3710 
3711     memset(&ctxt, 0, sizeof(xmlRelaxNGValidCtxt));
3712 
3713     ctxt.flags = FLAGS_IGNORABLE | FLAGS_NOERROR;
3714 
3715     if ((def1->type == XML_RELAXNG_ELEMENT) ||
3716         (def1->type == XML_RELAXNG_ATTRIBUTE)) {
3717         if (def2->type == XML_RELAXNG_TEXT)
3718             return (1);
3719         if (def1->name != NULL) {
3720             node.name = def1->name;
3721         } else {
3722             node.name = invalidName;
3723         }
3724         if (def1->ns != NULL) {
3725             if (def1->ns[0] == 0) {
3726                 node.ns = NULL;
3727             } else {
3728 	        node.ns = &ns;
3729                 ns.href = def1->ns;
3730             }
3731         } else {
3732             node.ns = NULL;
3733         }
3734         if (xmlRelaxNGElementMatch(&ctxt, def2, &node)) {
3735             if (def1->nameClass != NULL) {
3736                 ret = xmlRelaxNGCompareNameClasses(def1->nameClass, def2);
3737             } else {
3738                 ret = 0;
3739             }
3740         } else {
3741             ret = 1;
3742         }
3743     } else if (def1->type == XML_RELAXNG_TEXT) {
3744         if (def2->type == XML_RELAXNG_TEXT)
3745             return (0);
3746         return (1);
3747     } else if (def1->type == XML_RELAXNG_EXCEPT) {
3748         ret = xmlRelaxNGCompareNameClasses(def1->content, def2);
3749 	if (ret == 0)
3750 	    ret = 1;
3751 	else if (ret == 1)
3752 	    ret = 0;
3753     } else {
3754         /* TODO */
3755         ret = 0;
3756     }
3757     if (ret == 0)
3758         return (ret);
3759     if ((def2->type == XML_RELAXNG_ELEMENT) ||
3760         (def2->type == XML_RELAXNG_ATTRIBUTE)) {
3761         if (def2->name != NULL) {
3762             node.name = def2->name;
3763         } else {
3764             node.name = invalidName;
3765         }
3766         node.ns = &ns;
3767         if (def2->ns != NULL) {
3768             if (def2->ns[0] == 0) {
3769                 node.ns = NULL;
3770             } else {
3771                 ns.href = def2->ns;
3772             }
3773         } else {
3774             ns.href = invalidName;
3775         }
3776         if (xmlRelaxNGElementMatch(&ctxt, def1, &node)) {
3777             if (def2->nameClass != NULL) {
3778                 ret = xmlRelaxNGCompareNameClasses(def2->nameClass, def1);
3779             } else {
3780                 ret = 0;
3781             }
3782         } else {
3783             ret = 1;
3784         }
3785     } else {
3786         /* TODO */
3787         ret = 0;
3788     }
3789 
3790     return (ret);
3791 }
3792 
3793 /**
3794  * xmlRelaxNGCompareElemDefLists:
3795  * @ctxt:  a Relax-NG parser context
3796  * @defs1:  the first list of element/attribute defs
3797  * @defs2:  the second list of element/attribute defs
3798  *
3799  * Compare the 2 lists of element or attribute definitions. The comparison
3800  * is that if both lists do not accept the same QNames, it returns 1
3801  * If the 2 lists can accept the same QName the comparison returns 0
3802  *
3803  * Returns 1 distinct, 0 if equal
3804  */
3805 static int
xmlRelaxNGCompareElemDefLists(xmlRelaxNGParserCtxtPtr ctxt ATTRIBUTE_UNUSED,xmlRelaxNGDefinePtr * def1,xmlRelaxNGDefinePtr * def2)3806 xmlRelaxNGCompareElemDefLists(xmlRelaxNGParserCtxtPtr ctxt
3807                               ATTRIBUTE_UNUSED, xmlRelaxNGDefinePtr * def1,
3808                               xmlRelaxNGDefinePtr * def2)
3809 {
3810     xmlRelaxNGDefinePtr *basedef2 = def2;
3811 
3812     if ((def1 == NULL) || (def2 == NULL))
3813         return (1);
3814     if ((*def1 == NULL) || (*def2 == NULL))
3815         return (1);
3816     while (*def1 != NULL) {
3817         while ((*def2) != NULL) {
3818             if (xmlRelaxNGCompareNameClasses(*def1, *def2) == 0)
3819                 return (0);
3820             def2++;
3821         }
3822         def2 = basedef2;
3823         def1++;
3824     }
3825     return (1);
3826 }
3827 
3828 /**
3829  * xmlRelaxNGGenerateAttributes:
3830  * @ctxt:  a Relax-NG parser context
3831  * @def:  the definition definition
3832  *
3833  * Check if the definition can only generate attributes
3834  *
3835  * Returns 1 if yes, 0 if no and -1 in case of error.
3836  */
3837 static int
xmlRelaxNGGenerateAttributes(xmlRelaxNGParserCtxtPtr ctxt,xmlRelaxNGDefinePtr def)3838 xmlRelaxNGGenerateAttributes(xmlRelaxNGParserCtxtPtr ctxt,
3839                              xmlRelaxNGDefinePtr def)
3840 {
3841     xmlRelaxNGDefinePtr parent, cur, tmp;
3842 
3843     /*
3844      * Don't run that check in case of error. Infinite recursion
3845      * becomes possible.
3846      */
3847     if (ctxt->nbErrors != 0)
3848         return (-1);
3849 
3850     parent = NULL;
3851     cur = def;
3852     while (cur != NULL) {
3853         if ((cur->type == XML_RELAXNG_ELEMENT) ||
3854             (cur->type == XML_RELAXNG_TEXT) ||
3855             (cur->type == XML_RELAXNG_DATATYPE) ||
3856             (cur->type == XML_RELAXNG_PARAM) ||
3857             (cur->type == XML_RELAXNG_LIST) ||
3858             (cur->type == XML_RELAXNG_VALUE) ||
3859             (cur->type == XML_RELAXNG_EMPTY))
3860             return (0);
3861         if ((cur->type == XML_RELAXNG_CHOICE) ||
3862             (cur->type == XML_RELAXNG_INTERLEAVE) ||
3863             (cur->type == XML_RELAXNG_GROUP) ||
3864             (cur->type == XML_RELAXNG_ONEORMORE) ||
3865             (cur->type == XML_RELAXNG_ZEROORMORE) ||
3866             (cur->type == XML_RELAXNG_OPTIONAL) ||
3867             (cur->type == XML_RELAXNG_PARENTREF) ||
3868             (cur->type == XML_RELAXNG_EXTERNALREF) ||
3869             (cur->type == XML_RELAXNG_REF) ||
3870             (cur->type == XML_RELAXNG_DEF)) {
3871             if (cur->content != NULL) {
3872                 parent = cur;
3873                 cur = cur->content;
3874                 tmp = cur;
3875                 while (tmp != NULL) {
3876                     tmp->parent = parent;
3877                     tmp = tmp->next;
3878                 }
3879                 continue;
3880             }
3881         }
3882         if (cur == def)
3883             break;
3884         if (cur->next != NULL) {
3885             cur = cur->next;
3886             continue;
3887         }
3888         do {
3889             cur = cur->parent;
3890             if (cur == NULL)
3891                 break;
3892             if (cur == def)
3893                 return (1);
3894             if (cur->next != NULL) {
3895                 cur = cur->next;
3896                 break;
3897             }
3898         } while (cur != NULL);
3899     }
3900     return (1);
3901 }
3902 
3903 /**
3904  * xmlRelaxNGGetElements:
3905  * @ctxt:  a Relax-NG parser context
3906  * @def:  the definition definition
3907  * @eora:  gather elements (0), attributes (1) or elements and text (2)
3908  *
3909  * Compute the list of top elements a definition can generate
3910  *
3911  * Returns a list of elements or NULL if none was found.
3912  */
3913 static xmlRelaxNGDefinePtr *
xmlRelaxNGGetElements(xmlRelaxNGParserCtxtPtr ctxt,xmlRelaxNGDefinePtr def,int eora)3914 xmlRelaxNGGetElements(xmlRelaxNGParserCtxtPtr ctxt,
3915                       xmlRelaxNGDefinePtr def, int eora)
3916 {
3917     xmlRelaxNGDefinePtr *ret = NULL, parent, cur, tmp;
3918     int len = 0;
3919     int max = 0;
3920 
3921     /*
3922      * Don't run that check in case of error. Infinite recursion
3923      * becomes possible.
3924      */
3925     if (ctxt->nbErrors != 0)
3926         return (NULL);
3927 
3928     parent = NULL;
3929     cur = def;
3930     while (cur != NULL) {
3931         if (((eora == 0) && ((cur->type == XML_RELAXNG_ELEMENT) ||
3932                              (cur->type == XML_RELAXNG_TEXT))) ||
3933             ((eora == 1) && (cur->type == XML_RELAXNG_ATTRIBUTE)) ||
3934             ((eora == 2) && ((cur->type == XML_RELAXNG_DATATYPE) ||
3935 	                     (cur->type == XML_RELAXNG_ELEMENT) ||
3936 			     (cur->type == XML_RELAXNG_LIST) ||
3937                              (cur->type == XML_RELAXNG_TEXT) ||
3938 			     (cur->type == XML_RELAXNG_VALUE)))) {
3939             if (ret == NULL) {
3940                 max = 10;
3941                 ret = (xmlRelaxNGDefinePtr *)
3942                     xmlMalloc((max + 1) * sizeof(xmlRelaxNGDefinePtr));
3943                 if (ret == NULL) {
3944                     xmlRngPErrMemory(ctxt);
3945                     return (NULL);
3946                 }
3947             } else if (max <= len) {
3948 	        xmlRelaxNGDefinePtr *temp;
3949 
3950                 max *= 2;
3951                 temp = xmlRealloc(ret,
3952                                (max + 1) * sizeof(xmlRelaxNGDefinePtr));
3953                 if (temp == NULL) {
3954                     xmlRngPErrMemory(ctxt);
3955 		    xmlFree(ret);
3956                     return (NULL);
3957                 }
3958 		ret = temp;
3959             }
3960             ret[len++] = cur;
3961             ret[len] = NULL;
3962         } else if ((cur->type == XML_RELAXNG_CHOICE) ||
3963                    (cur->type == XML_RELAXNG_INTERLEAVE) ||
3964                    (cur->type == XML_RELAXNG_GROUP) ||
3965                    (cur->type == XML_RELAXNG_ONEORMORE) ||
3966                    (cur->type == XML_RELAXNG_ZEROORMORE) ||
3967                    (cur->type == XML_RELAXNG_OPTIONAL) ||
3968                    (cur->type == XML_RELAXNG_PARENTREF) ||
3969                    (cur->type == XML_RELAXNG_REF) ||
3970                    (cur->type == XML_RELAXNG_DEF) ||
3971 		   (cur->type == XML_RELAXNG_EXTERNALREF)) {
3972             /*
3973              * Don't go within elements or attributes or string values.
3974              * Just gather the element top list
3975              */
3976             if (cur->content != NULL) {
3977                 parent = cur;
3978                 cur = cur->content;
3979                 tmp = cur;
3980                 while (tmp != NULL) {
3981                     tmp->parent = parent;
3982                     tmp = tmp->next;
3983                 }
3984                 continue;
3985             }
3986         }
3987         if (cur == def)
3988             break;
3989         if (cur->next != NULL) {
3990             cur = cur->next;
3991             continue;
3992         }
3993         do {
3994             cur = cur->parent;
3995             if (cur == NULL)
3996                 break;
3997             if (cur == def)
3998                 return (ret);
3999             if (cur->next != NULL) {
4000                 cur = cur->next;
4001                 break;
4002             }
4003         } while (cur != NULL);
4004     }
4005     return (ret);
4006 }
4007 
4008 /**
4009  * xmlRelaxNGCheckChoiceDeterminism:
4010  * @ctxt:  a Relax-NG parser context
4011  * @def:  the choice definition
4012  *
4013  * Also used to find indeterministic pattern in choice
4014  */
4015 static void
xmlRelaxNGCheckChoiceDeterminism(xmlRelaxNGParserCtxtPtr ctxt,xmlRelaxNGDefinePtr def)4016 xmlRelaxNGCheckChoiceDeterminism(xmlRelaxNGParserCtxtPtr ctxt,
4017                                  xmlRelaxNGDefinePtr def)
4018 {
4019     xmlRelaxNGDefinePtr **list;
4020     xmlRelaxNGDefinePtr cur;
4021     int nbchild = 0, i, j, ret;
4022     int is_nullable = 0;
4023     int is_indeterminist = 0;
4024     xmlHashTablePtr triage = NULL;
4025     int is_triable = 1;
4026 
4027     if ((def == NULL) || (def->type != XML_RELAXNG_CHOICE))
4028         return;
4029 
4030     if (def->dflags & IS_PROCESSED)
4031         return;
4032 
4033     /*
4034      * Don't run that check in case of error. Infinite recursion
4035      * becomes possible.
4036      */
4037     if (ctxt->nbErrors != 0)
4038         return;
4039 
4040     is_nullable = xmlRelaxNGIsNullable(def);
4041 
4042     cur = def->content;
4043     while (cur != NULL) {
4044         nbchild++;
4045         cur = cur->next;
4046     }
4047 
4048     list = (xmlRelaxNGDefinePtr **) xmlMalloc(nbchild *
4049                                               sizeof(xmlRelaxNGDefinePtr
4050                                                      *));
4051     if (list == NULL) {
4052         xmlRngPErrMemory(ctxt);
4053         return;
4054     }
4055     i = 0;
4056     /*
4057      * a bit strong but safe
4058      */
4059     if (is_nullable == 0) {
4060         triage = xmlHashCreate(10);
4061     } else {
4062         is_triable = 0;
4063     }
4064     cur = def->content;
4065     while (cur != NULL) {
4066         list[i] = xmlRelaxNGGetElements(ctxt, cur, 0);
4067         if ((list[i] == NULL) || (list[i][0] == NULL)) {
4068             is_triable = 0;
4069         } else if (is_triable == 1) {
4070             xmlRelaxNGDefinePtr *tmp;
4071             int res;
4072 
4073             tmp = list[i];
4074             while ((*tmp != NULL) && (is_triable == 1)) {
4075                 if ((*tmp)->type == XML_RELAXNG_TEXT) {
4076                     res = xmlHashAddEntry2(triage,
4077                                            BAD_CAST "#text", NULL,
4078                                            (void *) cur);
4079                     if (res != 0)
4080                         is_triable = -1;
4081                 } else if (((*tmp)->type == XML_RELAXNG_ELEMENT) &&
4082                            ((*tmp)->name != NULL)) {
4083                     if (((*tmp)->ns == NULL) || ((*tmp)->ns[0] == 0))
4084                         res = xmlHashAddEntry2(triage,
4085                                                (*tmp)->name, NULL,
4086                                                (void *) cur);
4087                     else
4088                         res = xmlHashAddEntry2(triage,
4089                                                (*tmp)->name, (*tmp)->ns,
4090                                                (void *) cur);
4091                     if (res != 0)
4092                         is_triable = -1;
4093                 } else if ((*tmp)->type == XML_RELAXNG_ELEMENT) {
4094                     if (((*tmp)->ns == NULL) || ((*tmp)->ns[0] == 0))
4095                         res = xmlHashAddEntry2(triage,
4096                                                BAD_CAST "#any", NULL,
4097                                                (void *) cur);
4098                     else
4099                         res = xmlHashAddEntry2(triage,
4100                                                BAD_CAST "#any", (*tmp)->ns,
4101                                                (void *) cur);
4102                     if (res != 0)
4103                         is_triable = -1;
4104                 } else {
4105                     is_triable = -1;
4106                 }
4107                 tmp++;
4108             }
4109         }
4110         i++;
4111         cur = cur->next;
4112     }
4113 
4114     for (i = 0; i < nbchild; i++) {
4115         if (list[i] == NULL)
4116             continue;
4117         for (j = 0; j < i; j++) {
4118             if (list[j] == NULL)
4119                 continue;
4120             ret = xmlRelaxNGCompareElemDefLists(ctxt, list[i], list[j]);
4121             if (ret == 0) {
4122                 is_indeterminist = 1;
4123             }
4124         }
4125     }
4126     for (i = 0; i < nbchild; i++) {
4127         if (list[i] != NULL)
4128             xmlFree(list[i]);
4129     }
4130 
4131     xmlFree(list);
4132     if (is_indeterminist) {
4133         def->dflags |= IS_INDETERMINIST;
4134     }
4135     if (is_triable == 1) {
4136         def->dflags |= IS_TRIABLE;
4137         def->data = triage;
4138     } else if (triage != NULL) {
4139         xmlHashFree(triage, NULL);
4140     }
4141     def->dflags |= IS_PROCESSED;
4142 }
4143 
4144 /**
4145  * xmlRelaxNGCheckGroupAttrs:
4146  * @ctxt:  a Relax-NG parser context
4147  * @def:  the group definition
4148  *
4149  * Detects violations of rule 7.3
4150  */
4151 static void
xmlRelaxNGCheckGroupAttrs(xmlRelaxNGParserCtxtPtr ctxt,xmlRelaxNGDefinePtr def)4152 xmlRelaxNGCheckGroupAttrs(xmlRelaxNGParserCtxtPtr ctxt,
4153                           xmlRelaxNGDefinePtr def)
4154 {
4155     xmlRelaxNGDefinePtr **list;
4156     xmlRelaxNGDefinePtr cur;
4157     int nbchild = 0, i, j, ret;
4158 
4159     if ((def == NULL) ||
4160         ((def->type != XML_RELAXNG_GROUP) &&
4161          (def->type != XML_RELAXNG_ELEMENT)))
4162         return;
4163 
4164     if (def->dflags & IS_PROCESSED)
4165         return;
4166 
4167     /*
4168      * Don't run that check in case of error. Infinite recursion
4169      * becomes possible.
4170      */
4171     if (ctxt->nbErrors != 0)
4172         return;
4173 
4174     cur = def->attrs;
4175     while (cur != NULL) {
4176         nbchild++;
4177         cur = cur->next;
4178     }
4179     cur = def->content;
4180     while (cur != NULL) {
4181         nbchild++;
4182         cur = cur->next;
4183     }
4184 
4185     list = (xmlRelaxNGDefinePtr **) xmlMalloc(nbchild *
4186                                               sizeof(xmlRelaxNGDefinePtr
4187                                                      *));
4188     if (list == NULL) {
4189         xmlRngPErrMemory(ctxt);
4190         return;
4191     }
4192     i = 0;
4193     cur = def->attrs;
4194     while (cur != NULL) {
4195         list[i] = xmlRelaxNGGetElements(ctxt, cur, 1);
4196         i++;
4197         cur = cur->next;
4198     }
4199     cur = def->content;
4200     while (cur != NULL) {
4201         list[i] = xmlRelaxNGGetElements(ctxt, cur, 1);
4202         i++;
4203         cur = cur->next;
4204     }
4205 
4206     for (i = 0; i < nbchild; i++) {
4207         if (list[i] == NULL)
4208             continue;
4209         for (j = 0; j < i; j++) {
4210             if (list[j] == NULL)
4211                 continue;
4212             ret = xmlRelaxNGCompareElemDefLists(ctxt, list[i], list[j]);
4213             if (ret == 0) {
4214                 xmlRngPErr(ctxt, def->node, XML_RNGP_GROUP_ATTR_CONFLICT,
4215                            "Attributes conflicts in group\n", NULL, NULL);
4216             }
4217         }
4218     }
4219     for (i = 0; i < nbchild; i++) {
4220         if (list[i] != NULL)
4221             xmlFree(list[i]);
4222     }
4223 
4224     xmlFree(list);
4225     def->dflags |= IS_PROCESSED;
4226 }
4227 
4228 /**
4229  * xmlRelaxNGComputeInterleaves:
4230  * @def:  the interleave definition
4231  * @ctxt:  a Relax-NG parser context
4232  * @name:  the definition name
4233  *
4234  * A lot of work for preprocessing interleave definitions
4235  * is potentially needed to get a decent execution speed at runtime
4236  *   - trying to get a total order on the element nodes generated
4237  *     by the interleaves, order the list of interleave definitions
4238  *     following that order.
4239  *   - if <text/> is used to handle mixed content, it is better to
4240  *     flag this in the define and simplify the runtime checking
4241  *     algorithm
4242  */
4243 static void
xmlRelaxNGComputeInterleaves(void * payload,void * data,const xmlChar * name ATTRIBUTE_UNUSED)4244 xmlRelaxNGComputeInterleaves(void *payload, void *data,
4245                              const xmlChar * name ATTRIBUTE_UNUSED)
4246 {
4247     xmlRelaxNGDefinePtr def = (xmlRelaxNGDefinePtr) payload;
4248     xmlRelaxNGParserCtxtPtr ctxt = (xmlRelaxNGParserCtxtPtr) data;
4249     xmlRelaxNGDefinePtr cur, *tmp;
4250 
4251     xmlRelaxNGPartitionPtr partitions = NULL;
4252     xmlRelaxNGInterleaveGroupPtr *groups = NULL;
4253     xmlRelaxNGInterleaveGroupPtr group;
4254     int i, j, ret, res;
4255     int nbgroups = 0;
4256     int nbchild = 0;
4257     int is_mixed = 0;
4258     int is_determinist = 1;
4259 
4260     /*
4261      * Don't run that check in case of error. Infinite recursion
4262      * becomes possible.
4263      */
4264     if (ctxt->nbErrors != 0)
4265         return;
4266 
4267     cur = def->content;
4268     while (cur != NULL) {
4269         nbchild++;
4270         cur = cur->next;
4271     }
4272 
4273     groups = (xmlRelaxNGInterleaveGroupPtr *)
4274         xmlMalloc(nbchild * sizeof(xmlRelaxNGInterleaveGroupPtr));
4275     if (groups == NULL)
4276         goto error;
4277     cur = def->content;
4278     while (cur != NULL) {
4279         groups[nbgroups] = (xmlRelaxNGInterleaveGroupPtr)
4280             xmlMalloc(sizeof(xmlRelaxNGInterleaveGroup));
4281         if (groups[nbgroups] == NULL)
4282             goto error;
4283         if (cur->type == XML_RELAXNG_TEXT)
4284             is_mixed++;
4285         groups[nbgroups]->rule = cur;
4286         groups[nbgroups]->defs = xmlRelaxNGGetElements(ctxt, cur, 2);
4287         groups[nbgroups]->attrs = xmlRelaxNGGetElements(ctxt, cur, 1);
4288         nbgroups++;
4289         cur = cur->next;
4290     }
4291 
4292     /*
4293      * Let's check that all rules makes a partitions according to 7.4
4294      */
4295     partitions = (xmlRelaxNGPartitionPtr)
4296         xmlMalloc(sizeof(xmlRelaxNGPartition));
4297     if (partitions == NULL)
4298         goto error;
4299     memset(partitions, 0, sizeof(xmlRelaxNGPartition));
4300     partitions->nbgroups = nbgroups;
4301     partitions->triage = xmlHashCreate(nbgroups);
4302     for (i = 0; i < nbgroups; i++) {
4303         group = groups[i];
4304         for (j = i + 1; j < nbgroups; j++) {
4305             if (groups[j] == NULL)
4306                 continue;
4307 
4308             ret = xmlRelaxNGCompareElemDefLists(ctxt, group->defs,
4309                                                 groups[j]->defs);
4310             if (ret == 0) {
4311                 xmlRngPErr(ctxt, def->node, XML_RNGP_ELEM_TEXT_CONFLICT,
4312                            "Element or text conflicts in interleave\n",
4313                            NULL, NULL);
4314             }
4315             ret = xmlRelaxNGCompareElemDefLists(ctxt, group->attrs,
4316                                                 groups[j]->attrs);
4317             if (ret == 0) {
4318                 xmlRngPErr(ctxt, def->node, XML_RNGP_ATTR_CONFLICT,
4319                            "Attributes conflicts in interleave\n", NULL,
4320                            NULL);
4321             }
4322         }
4323         tmp = group->defs;
4324         if ((tmp != NULL) && (*tmp != NULL)) {
4325             while (*tmp != NULL) {
4326                 if ((*tmp)->type == XML_RELAXNG_TEXT) {
4327                     res = xmlHashAddEntry2(partitions->triage,
4328                                            BAD_CAST "#text", NULL,
4329                                            XML_INT_TO_PTR(i + 1));
4330                     if (res != 0)
4331                         is_determinist = -1;
4332                 } else if (((*tmp)->type == XML_RELAXNG_ELEMENT) &&
4333                            ((*tmp)->name != NULL)) {
4334                     if (((*tmp)->ns == NULL) || ((*tmp)->ns[0] == 0))
4335                         res = xmlHashAddEntry2(partitions->triage,
4336                                                (*tmp)->name, NULL,
4337                                                XML_INT_TO_PTR(i + 1));
4338                     else
4339                         res = xmlHashAddEntry2(partitions->triage,
4340                                                (*tmp)->name, (*tmp)->ns,
4341                                                XML_INT_TO_PTR(i + 1));
4342                     if (res != 0)
4343                         is_determinist = -1;
4344                 } else if ((*tmp)->type == XML_RELAXNG_ELEMENT) {
4345                     if (((*tmp)->ns == NULL) || ((*tmp)->ns[0] == 0))
4346                         res = xmlHashAddEntry2(partitions->triage,
4347                                                BAD_CAST "#any", NULL,
4348                                                XML_INT_TO_PTR(i + 1));
4349                     else
4350                         res = xmlHashAddEntry2(partitions->triage,
4351                                                BAD_CAST "#any", (*tmp)->ns,
4352                                                XML_INT_TO_PTR(i + 1));
4353                     if ((*tmp)->nameClass != NULL)
4354                         is_determinist = 2;
4355                     if (res != 0)
4356                         is_determinist = -1;
4357                 } else {
4358                     is_determinist = -1;
4359                 }
4360                 tmp++;
4361             }
4362         } else {
4363             is_determinist = 0;
4364         }
4365     }
4366     partitions->groups = groups;
4367 
4368     /*
4369      * and save the partition list back in the def
4370      */
4371     def->data = partitions;
4372     if (is_mixed != 0)
4373         def->dflags |= IS_MIXED;
4374     if (is_determinist == 1)
4375         partitions->flags = IS_DETERMINIST;
4376     if (is_determinist == 2)
4377         partitions->flags = IS_DETERMINIST | IS_NEEDCHECK;
4378     return;
4379 
4380   error:
4381     xmlRngPErrMemory(ctxt);
4382     if (groups != NULL) {
4383         for (i = 0; i < nbgroups; i++)
4384             if (groups[i] != NULL) {
4385                 if (groups[i]->defs != NULL)
4386                     xmlFree(groups[i]->defs);
4387                 xmlFree(groups[i]);
4388             }
4389         xmlFree(groups);
4390     }
4391     xmlRelaxNGFreePartition(partitions);
4392 }
4393 
4394 /**
4395  * xmlRelaxNGParseInterleave:
4396  * @ctxt:  a Relax-NG parser context
4397  * @node:  the data node.
4398  *
4399  * parse the content of a RelaxNG interleave node.
4400  *
4401  * Returns the definition pointer or NULL in case of error
4402  */
4403 static xmlRelaxNGDefinePtr
xmlRelaxNGParseInterleave(xmlRelaxNGParserCtxtPtr ctxt,xmlNodePtr node)4404 xmlRelaxNGParseInterleave(xmlRelaxNGParserCtxtPtr ctxt, xmlNodePtr node)
4405 {
4406     xmlRelaxNGDefinePtr def = NULL;
4407     xmlRelaxNGDefinePtr last = NULL, cur;
4408     xmlNodePtr child;
4409 
4410     def = xmlRelaxNGNewDefine(ctxt, node);
4411     if (def == NULL) {
4412         return (NULL);
4413     }
4414     def->type = XML_RELAXNG_INTERLEAVE;
4415 
4416     if (ctxt->interleaves == NULL)
4417         ctxt->interleaves = xmlHashCreate(10);
4418     if (ctxt->interleaves == NULL) {
4419         xmlRngPErrMemory(ctxt);
4420     } else {
4421         char name[32];
4422 
4423         snprintf(name, 32, "interleave%d", ctxt->nbInterleaves++);
4424         if (xmlHashAddEntry(ctxt->interleaves, BAD_CAST name, def) < 0) {
4425             xmlRngPErr(ctxt, node, XML_RNGP_INTERLEAVE_ADD,
4426                        "Failed to add %s to hash table\n",
4427 		       (const xmlChar *) name, NULL);
4428         }
4429     }
4430     child = node->children;
4431     if (child == NULL) {
4432         xmlRngPErr(ctxt, node, XML_RNGP_INTERLEAVE_NO_CONTENT,
4433                    "Element interleave is empty\n", NULL, NULL);
4434     }
4435     while (child != NULL) {
4436         if (IS_RELAXNG(child, "element")) {
4437             cur = xmlRelaxNGParseElement(ctxt, child);
4438         } else {
4439             cur = xmlRelaxNGParsePattern(ctxt, child);
4440         }
4441         if (cur != NULL) {
4442             cur->parent = def;
4443             if (last == NULL) {
4444                 def->content = last = cur;
4445             } else {
4446                 last->next = cur;
4447                 last = cur;
4448             }
4449         }
4450         child = child->next;
4451     }
4452 
4453     return (def);
4454 }
4455 
4456 /**
4457  * xmlRelaxNGParseInclude:
4458  * @ctxt:  a Relax-NG parser context
4459  * @node:  the include node
4460  *
4461  * Integrate the content of an include node in the current grammar
4462  *
4463  * Returns 0 in case of success or -1 in case of error
4464  */
4465 static int
xmlRelaxNGParseInclude(xmlRelaxNGParserCtxtPtr ctxt,xmlNodePtr node)4466 xmlRelaxNGParseInclude(xmlRelaxNGParserCtxtPtr ctxt, xmlNodePtr node)
4467 {
4468     xmlRelaxNGIncludePtr incl;
4469     xmlNodePtr root;
4470     int ret = 0, tmp;
4471 
4472     incl = node->psvi;
4473     if (incl == NULL) {
4474         xmlRngPErr(ctxt, node, XML_RNGP_INCLUDE_EMPTY,
4475                    "Include node has no data\n", NULL, NULL);
4476         return (-1);
4477     }
4478     root = xmlDocGetRootElement(incl->doc);
4479     if (root == NULL) {
4480         xmlRngPErr(ctxt, node, XML_RNGP_EMPTY, "Include document is empty\n",
4481                    NULL, NULL);
4482         return (-1);
4483     }
4484     if (!xmlStrEqual(root->name, BAD_CAST "grammar")) {
4485         xmlRngPErr(ctxt, node, XML_RNGP_GRAMMAR_MISSING,
4486                    "Include document root is not a grammar\n", NULL, NULL);
4487         return (-1);
4488     }
4489 
4490     /*
4491      * Merge the definition from both the include and the internal list
4492      */
4493     if (root->children != NULL) {
4494         tmp = xmlRelaxNGParseGrammarContent(ctxt, root->children);
4495         if (tmp != 0)
4496             ret = -1;
4497     }
4498     if (node->children != NULL) {
4499         tmp = xmlRelaxNGParseGrammarContent(ctxt, node->children);
4500         if (tmp != 0)
4501             ret = -1;
4502     }
4503     return (ret);
4504 }
4505 
4506 /**
4507  * xmlRelaxNGParseDefine:
4508  * @ctxt:  a Relax-NG parser context
4509  * @node:  the define node
4510  *
4511  * parse the content of a RelaxNG define element node.
4512  *
4513  * Returns 0 in case of success or -1 in case of error
4514  */
4515 static int
xmlRelaxNGParseDefine(xmlRelaxNGParserCtxtPtr ctxt,xmlNodePtr node)4516 xmlRelaxNGParseDefine(xmlRelaxNGParserCtxtPtr ctxt, xmlNodePtr node)
4517 {
4518     xmlChar *name;
4519     int ret = 0, tmp;
4520     xmlRelaxNGDefinePtr def;
4521     const xmlChar *olddefine;
4522 
4523     name = xmlGetProp(node, BAD_CAST "name");
4524     if (name == NULL) {
4525         xmlRngPErr(ctxt, node, XML_RNGP_DEFINE_NAME_MISSING,
4526                    "define has no name\n", NULL, NULL);
4527     } else {
4528         xmlRelaxNGNormExtSpace(name);
4529         if (xmlValidateNCName(name, 0)) {
4530             xmlRngPErr(ctxt, node, XML_RNGP_INVALID_DEFINE_NAME,
4531                        "define name '%s' is not an NCName\n", name, NULL);
4532         }
4533         def = xmlRelaxNGNewDefine(ctxt, node);
4534         if (def == NULL) {
4535             xmlFree(name);
4536             return (-1);
4537         }
4538         def->type = XML_RELAXNG_DEF;
4539         def->name = name;
4540         if (node->children == NULL) {
4541             xmlRngPErr(ctxt, node, XML_RNGP_DEFINE_EMPTY,
4542                        "define has no children\n", NULL, NULL);
4543         } else {
4544             olddefine = ctxt->define;
4545             ctxt->define = name;
4546             def->content =
4547                 xmlRelaxNGParsePatterns(ctxt, node->children, 0);
4548             ctxt->define = olddefine;
4549         }
4550         if (ctxt->grammar->defs == NULL)
4551             ctxt->grammar->defs = xmlHashCreate(10);
4552         if (ctxt->grammar->defs == NULL) {
4553             xmlRngPErr(ctxt, node, XML_RNGP_DEFINE_CREATE_FAILED,
4554                        "Could not create definition hash\n", NULL, NULL);
4555             ret = -1;
4556         } else {
4557             tmp = xmlHashAddEntry(ctxt->grammar->defs, name, def);
4558             if (tmp < 0) {
4559                 xmlRelaxNGDefinePtr prev;
4560 
4561                 prev = xmlHashLookup(ctxt->grammar->defs, name);
4562                 if (prev == NULL) {
4563                     xmlRngPErr(ctxt, node, XML_RNGP_DEFINE_CREATE_FAILED,
4564                                "Internal error on define aggregation of %s\n",
4565                                name, NULL);
4566                     ret = -1;
4567                 } else {
4568                     while (prev->nextHash != NULL)
4569                         prev = prev->nextHash;
4570                     prev->nextHash = def;
4571                 }
4572             }
4573         }
4574     }
4575     return (ret);
4576 }
4577 
4578 /**
4579  * xmlRelaxNGParseImportRef:
4580  * @payload: the parser context
4581  * @data: the current grammar
4582  * @name: the reference name
4583  *
4584  * Import import one references into the current grammar
4585  */
4586 static void
xmlRelaxNGParseImportRef(void * payload,void * data,const xmlChar * name)4587 xmlRelaxNGParseImportRef(void *payload, void *data, const xmlChar *name) {
4588     xmlRelaxNGParserCtxtPtr ctxt = (xmlRelaxNGParserCtxtPtr) data;
4589     xmlRelaxNGDefinePtr def = (xmlRelaxNGDefinePtr) payload;
4590     int tmp;
4591 
4592     def->dflags |= IS_EXTERNAL_REF;
4593 
4594     tmp = xmlHashAddEntry(ctxt->grammar->refs, name, def);
4595     if (tmp < 0) {
4596         xmlRelaxNGDefinePtr prev;
4597 
4598         prev = (xmlRelaxNGDefinePtr)
4599             xmlHashLookup(ctxt->grammar->refs, def->name);
4600         if (prev == NULL) {
4601             if (def->name != NULL) {
4602                 xmlRngPErr(ctxt, NULL, XML_RNGP_REF_CREATE_FAILED,
4603                            "Error refs definitions '%s'\n",
4604                            def->name, NULL);
4605             } else {
4606                 xmlRngPErr(ctxt, NULL, XML_RNGP_REF_CREATE_FAILED,
4607                            "Error refs definitions\n",
4608                            NULL, NULL);
4609             }
4610         } else {
4611             def->nextHash = prev->nextHash;
4612             prev->nextHash = def;
4613         }
4614     }
4615 }
4616 
4617 /**
4618  * xmlRelaxNGParseImportRefs:
4619  * @ctxt: the parser context
4620  * @grammar: the sub grammar
4621  *
4622  * Import references from the subgrammar into the current grammar
4623  *
4624  * Returns 0 in case of success, -1 in case of failure
4625  */
4626 static int
xmlRelaxNGParseImportRefs(xmlRelaxNGParserCtxtPtr ctxt,xmlRelaxNGGrammarPtr grammar)4627 xmlRelaxNGParseImportRefs(xmlRelaxNGParserCtxtPtr ctxt,
4628                           xmlRelaxNGGrammarPtr grammar) {
4629     if ((ctxt == NULL) || (grammar == NULL) || (ctxt->grammar == NULL))
4630         return(-1);
4631     if (grammar->refs == NULL)
4632         return(0);
4633     if (ctxt->grammar->refs == NULL)
4634         ctxt->grammar->refs = xmlHashCreate(10);
4635     if (ctxt->grammar->refs == NULL) {
4636         xmlRngPErr(ctxt, NULL, XML_RNGP_REF_CREATE_FAILED,
4637                    "Could not create references hash\n", NULL, NULL);
4638         return(-1);
4639     }
4640     xmlHashScan(grammar->refs, xmlRelaxNGParseImportRef, ctxt);
4641     return(0);
4642 }
4643 
4644 /**
4645  * xmlRelaxNGProcessExternalRef:
4646  * @ctxt: the parser context
4647  * @node:  the externalRef node
4648  *
4649  * Process and compile an externalRef node
4650  *
4651  * Returns the xmlRelaxNGDefinePtr or NULL in case of error
4652  */
4653 static xmlRelaxNGDefinePtr
xmlRelaxNGProcessExternalRef(xmlRelaxNGParserCtxtPtr ctxt,xmlNodePtr node)4654 xmlRelaxNGProcessExternalRef(xmlRelaxNGParserCtxtPtr ctxt, xmlNodePtr node)
4655 {
4656     xmlRelaxNGDocumentPtr docu;
4657     xmlNodePtr root, tmp;
4658     xmlChar *ns;
4659     int newNs = 0, oldflags;
4660     xmlRelaxNGDefinePtr def;
4661 
4662     docu = node->psvi;
4663     if (docu != NULL) {
4664         def = xmlRelaxNGNewDefine(ctxt, node);
4665         if (def == NULL)
4666             return (NULL);
4667         def->type = XML_RELAXNG_EXTERNALREF;
4668 
4669         if (docu->content == NULL) {
4670             /*
4671              * Then do the parsing for good
4672              */
4673             root = xmlDocGetRootElement(docu->doc);
4674             if (root == NULL) {
4675                 xmlRngPErr(ctxt, node, XML_RNGP_EXTERNALREF_EMTPY,
4676                            "xmlRelaxNGParse: %s is empty\n", ctxt->URL,
4677                            NULL);
4678                 return (NULL);
4679             }
4680             /*
4681              * ns transmission rules
4682              */
4683             ns = xmlGetProp(root, BAD_CAST "ns");
4684             if (ns == NULL) {
4685                 tmp = node;
4686                 while ((tmp != NULL) && (tmp->type == XML_ELEMENT_NODE)) {
4687                     ns = xmlGetProp(tmp, BAD_CAST "ns");
4688                     if (ns != NULL) {
4689                         break;
4690                     }
4691                     tmp = tmp->parent;
4692                 }
4693                 if (ns != NULL) {
4694                     xmlSetProp(root, BAD_CAST "ns", ns);
4695                     newNs = 1;
4696                     xmlFree(ns);
4697                 }
4698             } else {
4699                 xmlFree(ns);
4700             }
4701 
4702             /*
4703              * Parsing to get a precompiled schemas.
4704              */
4705             oldflags = ctxt->flags;
4706             ctxt->flags |= XML_RELAXNG_IN_EXTERNALREF;
4707             docu->schema = xmlRelaxNGParseDocument(ctxt, root);
4708             ctxt->flags = oldflags;
4709             if ((docu->schema != NULL) &&
4710                 (docu->schema->topgrammar != NULL)) {
4711                 docu->content = docu->schema->topgrammar->start;
4712                 if (docu->schema->topgrammar->refs)
4713                     xmlRelaxNGParseImportRefs(ctxt, docu->schema->topgrammar);
4714             }
4715 
4716             /*
4717              * the externalRef may be reused in a different ns context
4718              */
4719             if (newNs == 1) {
4720                 xmlUnsetProp(root, BAD_CAST "ns");
4721             }
4722         }
4723         def->content = docu->content;
4724     } else {
4725         def = NULL;
4726     }
4727     return (def);
4728 }
4729 
4730 /**
4731  * xmlRelaxNGParsePattern:
4732  * @ctxt:  a Relax-NG parser context
4733  * @node:  the pattern node.
4734  *
4735  * parse the content of a RelaxNG pattern node.
4736  *
4737  * Returns the definition pointer or NULL in case of error or if no
4738  *     pattern is generated.
4739  */
4740 static xmlRelaxNGDefinePtr
xmlRelaxNGParsePattern(xmlRelaxNGParserCtxtPtr ctxt,xmlNodePtr node)4741 xmlRelaxNGParsePattern(xmlRelaxNGParserCtxtPtr ctxt, xmlNodePtr node)
4742 {
4743     xmlRelaxNGDefinePtr def = NULL;
4744 
4745     if (node == NULL) {
4746         return (NULL);
4747     }
4748     if (IS_RELAXNG(node, "element")) {
4749         def = xmlRelaxNGParseElement(ctxt, node);
4750     } else if (IS_RELAXNG(node, "attribute")) {
4751         def = xmlRelaxNGParseAttribute(ctxt, node);
4752     } else if (IS_RELAXNG(node, "empty")) {
4753         def = xmlRelaxNGNewDefine(ctxt, node);
4754         if (def == NULL)
4755             return (NULL);
4756         def->type = XML_RELAXNG_EMPTY;
4757         if (node->children != NULL) {
4758             xmlRngPErr(ctxt, node, XML_RNGP_EMPTY_NOT_EMPTY,
4759                        "empty: had a child node\n", NULL, NULL);
4760         }
4761     } else if (IS_RELAXNG(node, "text")) {
4762         def = xmlRelaxNGNewDefine(ctxt, node);
4763         if (def == NULL)
4764             return (NULL);
4765         def->type = XML_RELAXNG_TEXT;
4766         if (node->children != NULL) {
4767             xmlRngPErr(ctxt, node, XML_RNGP_TEXT_HAS_CHILD,
4768                        "text: had a child node\n", NULL, NULL);
4769         }
4770     } else if (IS_RELAXNG(node, "zeroOrMore")) {
4771         def = xmlRelaxNGNewDefine(ctxt, node);
4772         if (def == NULL)
4773             return (NULL);
4774         def->type = XML_RELAXNG_ZEROORMORE;
4775         if (node->children == NULL) {
4776             xmlRngPErr(ctxt, node, XML_RNGP_EMPTY_CONSTRUCT,
4777                        "Element %s is empty\n", node->name, NULL);
4778         } else {
4779             def->content =
4780                 xmlRelaxNGParsePatterns(ctxt, node->children, 1);
4781         }
4782     } else if (IS_RELAXNG(node, "oneOrMore")) {
4783         def = xmlRelaxNGNewDefine(ctxt, node);
4784         if (def == NULL)
4785             return (NULL);
4786         def->type = XML_RELAXNG_ONEORMORE;
4787         if (node->children == NULL) {
4788             xmlRngPErr(ctxt, node, XML_RNGP_EMPTY_CONSTRUCT,
4789                        "Element %s is empty\n", node->name, NULL);
4790         } else {
4791             def->content =
4792                 xmlRelaxNGParsePatterns(ctxt, node->children, 1);
4793         }
4794     } else if (IS_RELAXNG(node, "optional")) {
4795         def = xmlRelaxNGNewDefine(ctxt, node);
4796         if (def == NULL)
4797             return (NULL);
4798         def->type = XML_RELAXNG_OPTIONAL;
4799         if (node->children == NULL) {
4800             xmlRngPErr(ctxt, node, XML_RNGP_EMPTY_CONSTRUCT,
4801                        "Element %s is empty\n", node->name, NULL);
4802         } else {
4803             def->content =
4804                 xmlRelaxNGParsePatterns(ctxt, node->children, 1);
4805         }
4806     } else if (IS_RELAXNG(node, "choice")) {
4807         def = xmlRelaxNGNewDefine(ctxt, node);
4808         if (def == NULL)
4809             return (NULL);
4810         def->type = XML_RELAXNG_CHOICE;
4811         if (node->children == NULL) {
4812             xmlRngPErr(ctxt, node, XML_RNGP_EMPTY_CONSTRUCT,
4813                        "Element %s is empty\n", node->name, NULL);
4814         } else {
4815             def->content =
4816                 xmlRelaxNGParsePatterns(ctxt, node->children, 0);
4817         }
4818     } else if (IS_RELAXNG(node, "group")) {
4819         def = xmlRelaxNGNewDefine(ctxt, node);
4820         if (def == NULL)
4821             return (NULL);
4822         def->type = XML_RELAXNG_GROUP;
4823         if (node->children == NULL) {
4824             xmlRngPErr(ctxt, node, XML_RNGP_EMPTY_CONSTRUCT,
4825                        "Element %s is empty\n", node->name, NULL);
4826         } else {
4827             def->content =
4828                 xmlRelaxNGParsePatterns(ctxt, node->children, 0);
4829         }
4830     } else if (IS_RELAXNG(node, "ref")) {
4831         def = xmlRelaxNGNewDefine(ctxt, node);
4832         if (def == NULL)
4833             return (NULL);
4834         def->type = XML_RELAXNG_REF;
4835         def->name = xmlGetProp(node, BAD_CAST "name");
4836         if (def->name == NULL) {
4837             xmlRngPErr(ctxt, node, XML_RNGP_REF_NO_NAME, "ref has no name\n",
4838                        NULL, NULL);
4839         } else {
4840             xmlRelaxNGNormExtSpace(def->name);
4841             if (xmlValidateNCName(def->name, 0)) {
4842                 xmlRngPErr(ctxt, node, XML_RNGP_REF_NAME_INVALID,
4843                            "ref name '%s' is not an NCName\n", def->name,
4844                            NULL);
4845             }
4846         }
4847         if (node->children != NULL) {
4848             xmlRngPErr(ctxt, node, XML_RNGP_REF_NOT_EMPTY, "ref is not empty\n",
4849                        NULL, NULL);
4850         }
4851         if (ctxt->grammar->refs == NULL)
4852             ctxt->grammar->refs = xmlHashCreate(10);
4853         if (ctxt->grammar->refs == NULL) {
4854             xmlRngPErr(ctxt, node, XML_RNGP_REF_CREATE_FAILED,
4855                        "Could not create references hash\n", NULL, NULL);
4856             def = NULL;
4857         } else {
4858             int tmp;
4859 
4860             tmp = xmlHashAddEntry(ctxt->grammar->refs, def->name, def);
4861             if (tmp < 0) {
4862                 xmlRelaxNGDefinePtr prev;
4863 
4864                 prev = (xmlRelaxNGDefinePtr)
4865                     xmlHashLookup(ctxt->grammar->refs, def->name);
4866                 if (prev == NULL) {
4867                     if (def->name != NULL) {
4868 		        xmlRngPErr(ctxt, node, XML_RNGP_REF_CREATE_FAILED,
4869 				   "Error refs definitions '%s'\n",
4870 				   def->name, NULL);
4871                     } else {
4872 		        xmlRngPErr(ctxt, node, XML_RNGP_REF_CREATE_FAILED,
4873 				   "Error refs definitions\n",
4874 				   NULL, NULL);
4875                     }
4876                     def = NULL;
4877                 } else {
4878                     def->nextHash = prev->nextHash;
4879                     prev->nextHash = def;
4880                 }
4881             }
4882         }
4883     } else if (IS_RELAXNG(node, "data")) {
4884         def = xmlRelaxNGParseData(ctxt, node);
4885     } else if (IS_RELAXNG(node, "value")) {
4886         def = xmlRelaxNGParseValue(ctxt, node);
4887     } else if (IS_RELAXNG(node, "list")) {
4888         def = xmlRelaxNGNewDefine(ctxt, node);
4889         if (def == NULL)
4890             return (NULL);
4891         def->type = XML_RELAXNG_LIST;
4892         if (node->children == NULL) {
4893             xmlRngPErr(ctxt, node, XML_RNGP_EMPTY_CONSTRUCT,
4894                        "Element %s is empty\n", node->name, NULL);
4895         } else {
4896             def->content =
4897                 xmlRelaxNGParsePatterns(ctxt, node->children, 0);
4898         }
4899     } else if (IS_RELAXNG(node, "interleave")) {
4900         def = xmlRelaxNGParseInterleave(ctxt, node);
4901     } else if (IS_RELAXNG(node, "externalRef")) {
4902         def = xmlRelaxNGProcessExternalRef(ctxt, node);
4903     } else if (IS_RELAXNG(node, "notAllowed")) {
4904         def = xmlRelaxNGNewDefine(ctxt, node);
4905         if (def == NULL)
4906             return (NULL);
4907         def->type = XML_RELAXNG_NOT_ALLOWED;
4908         if (node->children != NULL) {
4909             xmlRngPErr(ctxt, node, XML_RNGP_NOTALLOWED_NOT_EMPTY,
4910                        "xmlRelaxNGParse: notAllowed element is not empty\n",
4911                        NULL, NULL);
4912         }
4913     } else if (IS_RELAXNG(node, "grammar")) {
4914         xmlRelaxNGGrammarPtr grammar, old;
4915         xmlRelaxNGGrammarPtr oldparent;
4916 
4917         oldparent = ctxt->parentgrammar;
4918         old = ctxt->grammar;
4919         ctxt->parentgrammar = old;
4920         grammar = xmlRelaxNGParseGrammar(ctxt, node->children);
4921         if (old != NULL) {
4922             ctxt->grammar = old;
4923             ctxt->parentgrammar = oldparent;
4924 #if 0
4925             if (grammar != NULL) {
4926                 grammar->next = old->next;
4927                 old->next = grammar;
4928             }
4929 #endif
4930         }
4931         if (grammar != NULL)
4932             def = grammar->start;
4933         else
4934             def = NULL;
4935     } else if (IS_RELAXNG(node, "parentRef")) {
4936         if (ctxt->parentgrammar == NULL) {
4937             xmlRngPErr(ctxt, node, XML_RNGP_PARENTREF_NO_PARENT,
4938                        "Use of parentRef without a parent grammar\n", NULL,
4939                        NULL);
4940             return (NULL);
4941         }
4942         def = xmlRelaxNGNewDefine(ctxt, node);
4943         if (def == NULL)
4944             return (NULL);
4945         def->type = XML_RELAXNG_PARENTREF;
4946         def->name = xmlGetProp(node, BAD_CAST "name");
4947         if (def->name == NULL) {
4948             xmlRngPErr(ctxt, node, XML_RNGP_PARENTREF_NO_NAME,
4949                        "parentRef has no name\n", NULL, NULL);
4950         } else {
4951             xmlRelaxNGNormExtSpace(def->name);
4952             if (xmlValidateNCName(def->name, 0)) {
4953                 xmlRngPErr(ctxt, node, XML_RNGP_PARENTREF_NAME_INVALID,
4954                            "parentRef name '%s' is not an NCName\n",
4955                            def->name, NULL);
4956             }
4957         }
4958         if (node->children != NULL) {
4959             xmlRngPErr(ctxt, node, XML_RNGP_PARENTREF_NOT_EMPTY,
4960                        "parentRef is not empty\n", NULL, NULL);
4961         }
4962         if (ctxt->parentgrammar->refs == NULL)
4963             ctxt->parentgrammar->refs = xmlHashCreate(10);
4964         if (ctxt->parentgrammar->refs == NULL) {
4965             xmlRngPErr(ctxt, node, XML_RNGP_PARENTREF_CREATE_FAILED,
4966                        "Could not create references hash\n", NULL, NULL);
4967             def = NULL;
4968         } else if (def->name != NULL) {
4969             int tmp;
4970 
4971             tmp =
4972                 xmlHashAddEntry(ctxt->parentgrammar->refs, def->name, def);
4973             if (tmp < 0) {
4974                 xmlRelaxNGDefinePtr prev;
4975 
4976                 prev = (xmlRelaxNGDefinePtr)
4977                     xmlHashLookup(ctxt->parentgrammar->refs, def->name);
4978                 if (prev == NULL) {
4979                     xmlRngPErr(ctxt, node, XML_RNGP_PARENTREF_CREATE_FAILED,
4980                                "Internal error parentRef definitions '%s'\n",
4981                                def->name, NULL);
4982                     def = NULL;
4983                 } else {
4984                     def->nextHash = prev->nextHash;
4985                     prev->nextHash = def;
4986                 }
4987             }
4988         }
4989     } else if (IS_RELAXNG(node, "mixed")) {
4990         if (node->children == NULL) {
4991             xmlRngPErr(ctxt, node, XML_RNGP_EMPTY_CONSTRUCT, "Mixed is empty\n",
4992                        NULL, NULL);
4993             def = NULL;
4994         } else {
4995             def = xmlRelaxNGParseInterleave(ctxt, node);
4996             if (def != NULL) {
4997                 xmlRelaxNGDefinePtr tmp;
4998 
4999                 if ((def->content != NULL) && (def->content->next != NULL)) {
5000                     tmp = xmlRelaxNGNewDefine(ctxt, node);
5001                     if (tmp != NULL) {
5002                         tmp->type = XML_RELAXNG_GROUP;
5003                         tmp->content = def->content;
5004                         def->content = tmp;
5005                     }
5006                 }
5007 
5008                 tmp = xmlRelaxNGNewDefine(ctxt, node);
5009                 if (tmp == NULL)
5010                     return (def);
5011                 tmp->type = XML_RELAXNG_TEXT;
5012                 tmp->next = def->content;
5013                 def->content = tmp;
5014             }
5015         }
5016     } else {
5017         xmlRngPErr(ctxt, node, XML_RNGP_UNKNOWN_CONSTRUCT,
5018                    "Unexpected node %s is not a pattern\n", node->name,
5019                    NULL);
5020         def = NULL;
5021     }
5022     return (def);
5023 }
5024 
5025 /**
5026  * xmlRelaxNGParseAttribute:
5027  * @ctxt:  a Relax-NG parser context
5028  * @node:  the element node
5029  *
5030  * parse the content of a RelaxNG attribute node.
5031  *
5032  * Returns the definition pointer or NULL in case of error.
5033  */
5034 static xmlRelaxNGDefinePtr
xmlRelaxNGParseAttribute(xmlRelaxNGParserCtxtPtr ctxt,xmlNodePtr node)5035 xmlRelaxNGParseAttribute(xmlRelaxNGParserCtxtPtr ctxt, xmlNodePtr node)
5036 {
5037     xmlRelaxNGDefinePtr ret, cur;
5038     xmlNodePtr child;
5039     int old_flags;
5040 
5041     ret = xmlRelaxNGNewDefine(ctxt, node);
5042     if (ret == NULL)
5043         return (NULL);
5044     ret->type = XML_RELAXNG_ATTRIBUTE;
5045     ret->parent = ctxt->def;
5046     child = node->children;
5047     if (child == NULL) {
5048         xmlRngPErr(ctxt, node, XML_RNGP_ATTRIBUTE_EMPTY,
5049                    "xmlRelaxNGParseattribute: attribute has no children\n",
5050                    NULL, NULL);
5051         return (ret);
5052     }
5053     old_flags = ctxt->flags;
5054     ctxt->flags |= XML_RELAXNG_IN_ATTRIBUTE;
5055     cur = xmlRelaxNGParseNameClass(ctxt, child, ret);
5056     if (cur != NULL)
5057         child = child->next;
5058 
5059     if (child != NULL) {
5060         cur = xmlRelaxNGParsePattern(ctxt, child);
5061         if (cur != NULL) {
5062             switch (cur->type) {
5063                 case XML_RELAXNG_EMPTY:
5064                 case XML_RELAXNG_NOT_ALLOWED:
5065                 case XML_RELAXNG_TEXT:
5066                 case XML_RELAXNG_ELEMENT:
5067                 case XML_RELAXNG_DATATYPE:
5068                 case XML_RELAXNG_VALUE:
5069                 case XML_RELAXNG_LIST:
5070                 case XML_RELAXNG_REF:
5071                 case XML_RELAXNG_PARENTREF:
5072                 case XML_RELAXNG_EXTERNALREF:
5073                 case XML_RELAXNG_DEF:
5074                 case XML_RELAXNG_ONEORMORE:
5075                 case XML_RELAXNG_ZEROORMORE:
5076                 case XML_RELAXNG_OPTIONAL:
5077                 case XML_RELAXNG_CHOICE:
5078                 case XML_RELAXNG_GROUP:
5079                 case XML_RELAXNG_INTERLEAVE:
5080                 case XML_RELAXNG_ATTRIBUTE:
5081                     ret->content = cur;
5082                     cur->parent = ret;
5083                     break;
5084                 case XML_RELAXNG_START:
5085                 case XML_RELAXNG_PARAM:
5086                 case XML_RELAXNG_EXCEPT:
5087                     xmlRngPErr(ctxt, node, XML_RNGP_ATTRIBUTE_CONTENT,
5088                                "attribute has invalid content\n", NULL,
5089                                NULL);
5090                     break;
5091                 case XML_RELAXNG_NOOP:
5092                     xmlRngPErr(ctxt, node, XML_RNGP_ATTRIBUTE_NOOP,
5093                                "RNG Internal error, noop found in attribute\n",
5094                                NULL, NULL);
5095                     break;
5096             }
5097         }
5098         child = child->next;
5099     }
5100     if (child != NULL) {
5101         xmlRngPErr(ctxt, node, XML_RNGP_ATTRIBUTE_CHILDREN,
5102                    "attribute has multiple children\n", NULL, NULL);
5103     }
5104     ctxt->flags = old_flags;
5105     return (ret);
5106 }
5107 
5108 /**
5109  * xmlRelaxNGParseExceptNameClass:
5110  * @ctxt:  a Relax-NG parser context
5111  * @node:  the except node
5112  * @attr:  1 if within an attribute, 0 if within an element
5113  *
5114  * parse the content of a RelaxNG nameClass node.
5115  *
5116  * Returns the definition pointer or NULL in case of error.
5117  */
5118 static xmlRelaxNGDefinePtr
xmlRelaxNGParseExceptNameClass(xmlRelaxNGParserCtxtPtr ctxt,xmlNodePtr node,int attr)5119 xmlRelaxNGParseExceptNameClass(xmlRelaxNGParserCtxtPtr ctxt,
5120                                xmlNodePtr node, int attr)
5121 {
5122     xmlRelaxNGDefinePtr ret, cur, last = NULL;
5123     xmlNodePtr child;
5124 
5125     if (!IS_RELAXNG(node, "except")) {
5126         xmlRngPErr(ctxt, node, XML_RNGP_EXCEPT_MISSING,
5127                    "Expecting an except node\n", NULL, NULL);
5128         return (NULL);
5129     }
5130     if (node->next != NULL) {
5131         xmlRngPErr(ctxt, node, XML_RNGP_EXCEPT_MULTIPLE,
5132                    "exceptNameClass allows only a single except node\n",
5133                    NULL, NULL);
5134     }
5135     if (node->children == NULL) {
5136         xmlRngPErr(ctxt, node, XML_RNGP_EXCEPT_EMPTY, "except has no content\n",
5137                    NULL, NULL);
5138         return (NULL);
5139     }
5140 
5141     ret = xmlRelaxNGNewDefine(ctxt, node);
5142     if (ret == NULL)
5143         return (NULL);
5144     ret->type = XML_RELAXNG_EXCEPT;
5145     child = node->children;
5146     while (child != NULL) {
5147         cur = xmlRelaxNGNewDefine(ctxt, child);
5148         if (cur == NULL)
5149             break;
5150         if (attr)
5151             cur->type = XML_RELAXNG_ATTRIBUTE;
5152         else
5153             cur->type = XML_RELAXNG_ELEMENT;
5154 
5155         if (xmlRelaxNGParseNameClass(ctxt, child, cur) != NULL) {
5156             if (last == NULL) {
5157                 ret->content = cur;
5158             } else {
5159                 last->next = cur;
5160             }
5161             last = cur;
5162         }
5163         child = child->next;
5164     }
5165 
5166     return (ret);
5167 }
5168 
5169 /**
5170  * xmlRelaxNGParseNameClass:
5171  * @ctxt:  a Relax-NG parser context
5172  * @node:  the nameClass node
5173  * @def:  the current definition
5174  *
5175  * parse the content of a RelaxNG nameClass node.
5176  *
5177  * Returns the definition pointer or NULL in case of error.
5178  */
5179 static xmlRelaxNGDefinePtr
xmlRelaxNGParseNameClass(xmlRelaxNGParserCtxtPtr ctxt,xmlNodePtr node,xmlRelaxNGDefinePtr def)5180 xmlRelaxNGParseNameClass(xmlRelaxNGParserCtxtPtr ctxt, xmlNodePtr node,
5181                          xmlRelaxNGDefinePtr def)
5182 {
5183     xmlRelaxNGDefinePtr ret, tmp;
5184     xmlChar *val;
5185 
5186     ret = def;
5187     if ((IS_RELAXNG(node, "name")) || (IS_RELAXNG(node, "anyName")) ||
5188         (IS_RELAXNG(node, "nsName"))) {
5189         if ((def->type != XML_RELAXNG_ELEMENT) &&
5190             (def->type != XML_RELAXNG_ATTRIBUTE)) {
5191             ret = xmlRelaxNGNewDefine(ctxt, node);
5192             if (ret == NULL)
5193                 return (NULL);
5194             ret->parent = def;
5195             if (ctxt->flags & XML_RELAXNG_IN_ATTRIBUTE)
5196                 ret->type = XML_RELAXNG_ATTRIBUTE;
5197             else
5198                 ret->type = XML_RELAXNG_ELEMENT;
5199         }
5200     }
5201     if (IS_RELAXNG(node, "name")) {
5202         val = xmlNodeGetContent(node);
5203         xmlRelaxNGNormExtSpace(val);
5204         if (xmlValidateNCName(val, 0)) {
5205 	    if (node->parent != NULL)
5206 		xmlRngPErr(ctxt, node, XML_RNGP_ELEMENT_NAME,
5207 			   "Element %s name '%s' is not an NCName\n",
5208 			   node->parent->name, val);
5209 	    else
5210 		xmlRngPErr(ctxt, node, XML_RNGP_ELEMENT_NAME,
5211 			   "name '%s' is not an NCName\n",
5212 			   val, NULL);
5213         }
5214         ret->name = val;
5215         val = xmlGetProp(node, BAD_CAST "ns");
5216         ret->ns = val;
5217         if ((ctxt->flags & XML_RELAXNG_IN_ATTRIBUTE) &&
5218             (val != NULL) &&
5219             (xmlStrEqual(val, BAD_CAST "http://www.w3.org/2000/xmlns"))) {
5220 	    xmlRngPErr(ctxt, node, XML_RNGP_XML_NS,
5221                         "Attribute with namespace '%s' is not allowed\n",
5222                         val, NULL);
5223         }
5224         if ((ctxt->flags & XML_RELAXNG_IN_ATTRIBUTE) &&
5225             (val != NULL) &&
5226             (val[0] == 0) && (xmlStrEqual(ret->name, BAD_CAST "xmlns"))) {
5227 	    xmlRngPErr(ctxt, node, XML_RNGP_XMLNS_NAME,
5228                        "Attribute with QName 'xmlns' is not allowed\n",
5229                        val, NULL);
5230         }
5231     } else if (IS_RELAXNG(node, "anyName")) {
5232         ret->name = NULL;
5233         ret->ns = NULL;
5234         if (node->children != NULL) {
5235             ret->nameClass =
5236                 xmlRelaxNGParseExceptNameClass(ctxt, node->children,
5237                                                (def->type ==
5238                                                 XML_RELAXNG_ATTRIBUTE));
5239         }
5240     } else if (IS_RELAXNG(node, "nsName")) {
5241         ret->name = NULL;
5242         ret->ns = xmlGetProp(node, BAD_CAST "ns");
5243         if (ret->ns == NULL) {
5244             xmlRngPErr(ctxt, node, XML_RNGP_NSNAME_NO_NS,
5245                        "nsName has no ns attribute\n", NULL, NULL);
5246         }
5247         if ((ctxt->flags & XML_RELAXNG_IN_ATTRIBUTE) &&
5248             (ret->ns != NULL) &&
5249             (xmlStrEqual
5250              (ret->ns, BAD_CAST "http://www.w3.org/2000/xmlns"))) {
5251             xmlRngPErr(ctxt, node, XML_RNGP_XML_NS,
5252                        "Attribute with namespace '%s' is not allowed\n",
5253                        ret->ns, NULL);
5254         }
5255         if (node->children != NULL) {
5256             ret->nameClass =
5257                 xmlRelaxNGParseExceptNameClass(ctxt, node->children,
5258                                                (def->type ==
5259                                                 XML_RELAXNG_ATTRIBUTE));
5260         }
5261     } else if (IS_RELAXNG(node, "choice")) {
5262         xmlNodePtr child;
5263         xmlRelaxNGDefinePtr last = NULL;
5264 
5265         if (def->type == XML_RELAXNG_CHOICE) {
5266             ret = def;
5267         } else {
5268             ret = xmlRelaxNGNewDefine(ctxt, node);
5269             if (ret == NULL)
5270                 return (NULL);
5271             ret->parent = def;
5272             ret->type = XML_RELAXNG_CHOICE;
5273         }
5274 
5275         if (node->children == NULL) {
5276             xmlRngPErr(ctxt, node, XML_RNGP_CHOICE_EMPTY,
5277                        "Element choice is empty\n", NULL, NULL);
5278         } else {
5279 
5280             child = node->children;
5281             while (child != NULL) {
5282                 tmp = xmlRelaxNGParseNameClass(ctxt, child, ret);
5283                 if (tmp != NULL) {
5284                     if (last == NULL) {
5285                         last = tmp;
5286                     } else if (tmp != ret) {
5287                         last->next = tmp;
5288                         last = tmp;
5289                     }
5290                 }
5291                 child = child->next;
5292             }
5293         }
5294     } else {
5295         xmlRngPErr(ctxt, node, XML_RNGP_CHOICE_CONTENT,
5296                    "expecting name, anyName, nsName or choice : got %s\n",
5297                    (node == NULL ? (const xmlChar *) "nothing" : node->name),
5298 		   NULL);
5299         return (NULL);
5300     }
5301     if (ret != def) {
5302         if (def->nameClass == NULL) {
5303             def->nameClass = ret;
5304         } else {
5305             tmp = def->nameClass;
5306             while (tmp->next != NULL) {
5307                 tmp = tmp->next;
5308             }
5309             tmp->next = ret;
5310         }
5311     }
5312     return (ret);
5313 }
5314 
5315 /**
5316  * xmlRelaxNGParseElement:
5317  * @ctxt:  a Relax-NG parser context
5318  * @node:  the element node
5319  *
5320  * parse the content of a RelaxNG element node.
5321  *
5322  * Returns the definition pointer or NULL in case of error.
5323  */
5324 static xmlRelaxNGDefinePtr
xmlRelaxNGParseElement(xmlRelaxNGParserCtxtPtr ctxt,xmlNodePtr node)5325 xmlRelaxNGParseElement(xmlRelaxNGParserCtxtPtr ctxt, xmlNodePtr node)
5326 {
5327     xmlRelaxNGDefinePtr ret, cur, last;
5328     xmlNodePtr child;
5329     const xmlChar *olddefine;
5330 
5331     ret = xmlRelaxNGNewDefine(ctxt, node);
5332     if (ret == NULL)
5333         return (NULL);
5334     ret->type = XML_RELAXNG_ELEMENT;
5335     ret->parent = ctxt->def;
5336     child = node->children;
5337     if (child == NULL) {
5338         xmlRngPErr(ctxt, node, XML_RNGP_ELEMENT_EMPTY,
5339                    "xmlRelaxNGParseElement: element has no children\n",
5340                    NULL, NULL);
5341         return (ret);
5342     }
5343     cur = xmlRelaxNGParseNameClass(ctxt, child, ret);
5344     if (cur != NULL)
5345         child = child->next;
5346 
5347     if (child == NULL) {
5348         xmlRngPErr(ctxt, node, XML_RNGP_ELEMENT_NO_CONTENT,
5349                    "xmlRelaxNGParseElement: element has no content\n",
5350                    NULL, NULL);
5351         return (ret);
5352     }
5353     olddefine = ctxt->define;
5354     ctxt->define = NULL;
5355     last = NULL;
5356     while (child != NULL) {
5357         cur = xmlRelaxNGParsePattern(ctxt, child);
5358         if (cur != NULL) {
5359             cur->parent = ret;
5360             switch (cur->type) {
5361                 case XML_RELAXNG_EMPTY:
5362                 case XML_RELAXNG_NOT_ALLOWED:
5363                 case XML_RELAXNG_TEXT:
5364                 case XML_RELAXNG_ELEMENT:
5365                 case XML_RELAXNG_DATATYPE:
5366                 case XML_RELAXNG_VALUE:
5367                 case XML_RELAXNG_LIST:
5368                 case XML_RELAXNG_REF:
5369                 case XML_RELAXNG_PARENTREF:
5370                 case XML_RELAXNG_EXTERNALREF:
5371                 case XML_RELAXNG_DEF:
5372                 case XML_RELAXNG_ZEROORMORE:
5373                 case XML_RELAXNG_ONEORMORE:
5374                 case XML_RELAXNG_OPTIONAL:
5375                 case XML_RELAXNG_CHOICE:
5376                 case XML_RELAXNG_GROUP:
5377                 case XML_RELAXNG_INTERLEAVE:
5378                     if (last == NULL) {
5379                         ret->content = last = cur;
5380                     } else {
5381                         if ((last->type == XML_RELAXNG_ELEMENT) &&
5382                             (ret->content == last)) {
5383                             ret->content = xmlRelaxNGNewDefine(ctxt, node);
5384                             if (ret->content != NULL) {
5385                                 ret->content->type = XML_RELAXNG_GROUP;
5386                                 ret->content->content = last;
5387                             } else {
5388                                 ret->content = last;
5389                             }
5390                         }
5391                         last->next = cur;
5392                         last = cur;
5393                     }
5394                     break;
5395                 case XML_RELAXNG_ATTRIBUTE:
5396                     cur->next = ret->attrs;
5397                     ret->attrs = cur;
5398                     break;
5399                 case XML_RELAXNG_START:
5400                     xmlRngPErr(ctxt, node, XML_RNGP_ELEMENT_CONTENT,
5401                                "RNG Internal error, start found in element\n",
5402                                NULL, NULL);
5403                     break;
5404                 case XML_RELAXNG_PARAM:
5405                     xmlRngPErr(ctxt, node, XML_RNGP_ELEMENT_CONTENT,
5406                                "RNG Internal error, param found in element\n",
5407                                NULL, NULL);
5408                     break;
5409                 case XML_RELAXNG_EXCEPT:
5410                     xmlRngPErr(ctxt, node, XML_RNGP_ELEMENT_CONTENT,
5411                                "RNG Internal error, except found in element\n",
5412                                NULL, NULL);
5413                     break;
5414                 case XML_RELAXNG_NOOP:
5415                     xmlRngPErr(ctxt, node, XML_RNGP_ELEMENT_CONTENT,
5416                                "RNG Internal error, noop found in element\n",
5417                                NULL, NULL);
5418                     break;
5419             }
5420         }
5421         child = child->next;
5422     }
5423     ctxt->define = olddefine;
5424     return (ret);
5425 }
5426 
5427 /**
5428  * xmlRelaxNGParsePatterns:
5429  * @ctxt:  a Relax-NG parser context
5430  * @nodes:  list of nodes
5431  * @group:  use an implicit <group> for elements
5432  *
5433  * parse the content of a RelaxNG start node.
5434  *
5435  * Returns the definition pointer or NULL in case of error.
5436  */
5437 static xmlRelaxNGDefinePtr
xmlRelaxNGParsePatterns(xmlRelaxNGParserCtxtPtr ctxt,xmlNodePtr nodes,int group)5438 xmlRelaxNGParsePatterns(xmlRelaxNGParserCtxtPtr ctxt, xmlNodePtr nodes,
5439                         int group)
5440 {
5441     xmlRelaxNGDefinePtr def = NULL, last = NULL, cur, parent;
5442 
5443     parent = ctxt->def;
5444     while (nodes != NULL) {
5445         if (IS_RELAXNG(nodes, "element")) {
5446             cur = xmlRelaxNGParseElement(ctxt, nodes);
5447             if (cur == NULL)
5448                 return (NULL);
5449             if (def == NULL) {
5450                 def = last = cur;
5451             } else {
5452                 if ((group == 1) && (def->type == XML_RELAXNG_ELEMENT) &&
5453                     (def == last)) {
5454                     def = xmlRelaxNGNewDefine(ctxt, nodes);
5455                     if (def == NULL)
5456                         return (NULL);
5457                     def->type = XML_RELAXNG_GROUP;
5458                     def->content = last;
5459                 }
5460                 last->next = cur;
5461                 last = cur;
5462             }
5463             cur->parent = parent;
5464         } else {
5465             cur = xmlRelaxNGParsePattern(ctxt, nodes);
5466             if (cur != NULL) {
5467                 if (def == NULL) {
5468                     def = last = cur;
5469                 } else {
5470                     last->next = cur;
5471                     last = cur;
5472                 }
5473             }
5474         }
5475         nodes = nodes->next;
5476     }
5477     return (def);
5478 }
5479 
5480 /**
5481  * xmlRelaxNGParseStart:
5482  * @ctxt:  a Relax-NG parser context
5483  * @nodes:  start children nodes
5484  *
5485  * parse the content of a RelaxNG start node.
5486  *
5487  * Returns 0 in case of success, -1 in case of error
5488  */
5489 static int
xmlRelaxNGParseStart(xmlRelaxNGParserCtxtPtr ctxt,xmlNodePtr nodes)5490 xmlRelaxNGParseStart(xmlRelaxNGParserCtxtPtr ctxt, xmlNodePtr nodes)
5491 {
5492     int ret = 0;
5493     xmlRelaxNGDefinePtr def = NULL, last;
5494 
5495     if (nodes == NULL) {
5496         xmlRngPErr(ctxt, nodes, XML_RNGP_START_EMPTY, "start has no children\n",
5497                    NULL, NULL);
5498         return (-1);
5499     }
5500     if (IS_RELAXNG(nodes, "empty")) {
5501         def = xmlRelaxNGNewDefine(ctxt, nodes);
5502         if (def == NULL)
5503             return (-1);
5504         def->type = XML_RELAXNG_EMPTY;
5505         if (nodes->children != NULL) {
5506             xmlRngPErr(ctxt, nodes, XML_RNGP_EMPTY_CONTENT,
5507                        "element empty is not empty\n", NULL, NULL);
5508         }
5509     } else if (IS_RELAXNG(nodes, "notAllowed")) {
5510         def = xmlRelaxNGNewDefine(ctxt, nodes);
5511         if (def == NULL)
5512             return (-1);
5513         def->type = XML_RELAXNG_NOT_ALLOWED;
5514         if (nodes->children != NULL) {
5515             xmlRngPErr(ctxt, nodes, XML_RNGP_NOTALLOWED_NOT_EMPTY,
5516                        "element notAllowed is not empty\n", NULL, NULL);
5517         }
5518     } else {
5519         def = xmlRelaxNGParsePatterns(ctxt, nodes, 1);
5520     }
5521     if (ctxt->grammar->start != NULL) {
5522         last = ctxt->grammar->start;
5523         while (last->next != NULL)
5524             last = last->next;
5525         last->next = def;
5526     } else {
5527         ctxt->grammar->start = def;
5528     }
5529     nodes = nodes->next;
5530     if (nodes != NULL) {
5531         xmlRngPErr(ctxt, nodes, XML_RNGP_START_CONTENT,
5532                    "start more than one children\n", NULL, NULL);
5533         return (-1);
5534     }
5535     return (ret);
5536 }
5537 
5538 /**
5539  * xmlRelaxNGParseGrammarContent:
5540  * @ctxt:  a Relax-NG parser context
5541  * @nodes:  grammar children nodes
5542  *
5543  * parse the content of a RelaxNG grammar node.
5544  *
5545  * Returns 0 in case of success, -1 in case of error
5546  */
5547 static int
xmlRelaxNGParseGrammarContent(xmlRelaxNGParserCtxtPtr ctxt,xmlNodePtr nodes)5548 xmlRelaxNGParseGrammarContent(xmlRelaxNGParserCtxtPtr ctxt,
5549                               xmlNodePtr nodes)
5550 {
5551     int ret = 0, tmp;
5552 
5553     if (nodes == NULL) {
5554         xmlRngPErr(ctxt, nodes, XML_RNGP_GRAMMAR_EMPTY,
5555                    "grammar has no children\n", NULL, NULL);
5556         return (-1);
5557     }
5558     while (nodes != NULL) {
5559         if (IS_RELAXNG(nodes, "start")) {
5560             if (nodes->children == NULL) {
5561                 xmlRngPErr(ctxt, nodes, XML_RNGP_START_EMPTY,
5562                            "start has no children\n", NULL, NULL);
5563             } else {
5564                 tmp = xmlRelaxNGParseStart(ctxt, nodes->children);
5565                 if (tmp != 0)
5566                     ret = -1;
5567             }
5568         } else if (IS_RELAXNG(nodes, "define")) {
5569             tmp = xmlRelaxNGParseDefine(ctxt, nodes);
5570             if (tmp != 0)
5571                 ret = -1;
5572         } else if (IS_RELAXNG(nodes, "include")) {
5573             tmp = xmlRelaxNGParseInclude(ctxt, nodes);
5574             if (tmp != 0)
5575                 ret = -1;
5576         } else {
5577             xmlRngPErr(ctxt, nodes, XML_RNGP_GRAMMAR_CONTENT,
5578                        "grammar has unexpected child %s\n", nodes->name,
5579                        NULL);
5580             ret = -1;
5581         }
5582         nodes = nodes->next;
5583     }
5584     return (ret);
5585 }
5586 
5587 /**
5588  * xmlRelaxNGCheckReference:
5589  * @ref:  the ref
5590  * @ctxt:  a Relax-NG parser context
5591  * @name:  the name associated to the defines
5592  *
5593  * Applies the 4.17. combine attribute rule for all the define
5594  * element of a given grammar using the same name.
5595  */
5596 static void
xmlRelaxNGCheckReference(void * payload,void * data,const xmlChar * name)5597 xmlRelaxNGCheckReference(void *payload, void *data, const xmlChar * name)
5598 {
5599     xmlRelaxNGDefinePtr ref = (xmlRelaxNGDefinePtr) payload;
5600     xmlRelaxNGParserCtxtPtr ctxt = (xmlRelaxNGParserCtxtPtr) data;
5601     xmlRelaxNGGrammarPtr grammar;
5602     xmlRelaxNGDefinePtr def, cur;
5603 
5604     /*
5605      * Those rules don't apply to imported ref from xmlRelaxNGParseImportRef
5606      */
5607     if (ref->dflags & IS_EXTERNAL_REF)
5608         return;
5609 
5610     grammar = ctxt->grammar;
5611     if (grammar == NULL) {
5612         xmlRngPErr(ctxt, ref->node, XML_ERR_INTERNAL_ERROR,
5613                    "Internal error: no grammar in CheckReference %s\n",
5614                    name, NULL);
5615         return;
5616     }
5617     if (ref->content != NULL) {
5618         xmlRngPErr(ctxt, ref->node, XML_ERR_INTERNAL_ERROR,
5619                    "Internal error: reference has content in CheckReference %s\n",
5620                    name, NULL);
5621         return;
5622     }
5623     if (grammar->defs != NULL) {
5624         def = xmlHashLookup(grammar->defs, name);
5625         if (def != NULL) {
5626             cur = ref;
5627             while (cur != NULL) {
5628                 cur->content = def;
5629                 cur = cur->nextHash;
5630             }
5631         } else {
5632             xmlRngPErr(ctxt, ref->node, XML_RNGP_REF_NO_DEF,
5633                        "Reference %s has no matching definition\n", name,
5634                        NULL);
5635         }
5636     } else {
5637         xmlRngPErr(ctxt, ref->node, XML_RNGP_REF_NO_DEF,
5638                    "Reference %s has no matching definition\n", name,
5639                    NULL);
5640     }
5641 }
5642 
5643 /**
5644  * xmlRelaxNGCheckCombine:
5645  * @define:  the define(s) list
5646  * @ctxt:  a Relax-NG parser context
5647  * @name:  the name associated to the defines
5648  *
5649  * Applies the 4.17. combine attribute rule for all the define
5650  * element of a given grammar using the same name.
5651  */
5652 static void
xmlRelaxNGCheckCombine(void * payload,void * data,const xmlChar * name)5653 xmlRelaxNGCheckCombine(void *payload, void *data, const xmlChar * name)
5654 {
5655     xmlRelaxNGDefinePtr define = (xmlRelaxNGDefinePtr) payload;
5656     xmlRelaxNGParserCtxtPtr ctxt = (xmlRelaxNGParserCtxtPtr) data;
5657     xmlChar *combine;
5658     int choiceOrInterleave = -1;
5659     int missing = 0;
5660     xmlRelaxNGDefinePtr cur, last, tmp, tmp2;
5661 
5662     if (define->nextHash == NULL)
5663         return;
5664     cur = define;
5665     while (cur != NULL) {
5666         combine = xmlGetProp(cur->node, BAD_CAST "combine");
5667         if (combine != NULL) {
5668             if (xmlStrEqual(combine, BAD_CAST "choice")) {
5669                 if (choiceOrInterleave == -1)
5670                     choiceOrInterleave = 1;
5671                 else if (choiceOrInterleave == 0) {
5672                     xmlRngPErr(ctxt, define->node, XML_RNGP_DEF_CHOICE_AND_INTERLEAVE,
5673                                "Defines for %s use both 'choice' and 'interleave'\n",
5674                                name, NULL);
5675                 }
5676             } else if (xmlStrEqual(combine, BAD_CAST "interleave")) {
5677                 if (choiceOrInterleave == -1)
5678                     choiceOrInterleave = 0;
5679                 else if (choiceOrInterleave == 1) {
5680                     xmlRngPErr(ctxt, define->node, XML_RNGP_DEF_CHOICE_AND_INTERLEAVE,
5681                                "Defines for %s use both 'choice' and 'interleave'\n",
5682                                name, NULL);
5683                 }
5684             } else {
5685                 xmlRngPErr(ctxt, define->node, XML_RNGP_UNKNOWN_COMBINE,
5686                            "Defines for %s use unknown combine value '%s''\n",
5687                            name, combine);
5688             }
5689             xmlFree(combine);
5690         } else {
5691             if (missing == 0)
5692                 missing = 1;
5693             else {
5694                 xmlRngPErr(ctxt, define->node, XML_RNGP_NEED_COMBINE,
5695                            "Some defines for %s needs the combine attribute\n",
5696                            name, NULL);
5697             }
5698         }
5699 
5700         cur = cur->nextHash;
5701     }
5702     if (choiceOrInterleave == -1)
5703         choiceOrInterleave = 0;
5704     cur = xmlRelaxNGNewDefine(ctxt, define->node);
5705     if (cur == NULL)
5706         return;
5707     if (choiceOrInterleave == 0)
5708         cur->type = XML_RELAXNG_INTERLEAVE;
5709     else
5710         cur->type = XML_RELAXNG_CHOICE;
5711     tmp = define;
5712     last = NULL;
5713     while (tmp != NULL) {
5714         if (tmp->content != NULL) {
5715             if (tmp->content->next != NULL) {
5716                 /*
5717                  * we need first to create a wrapper.
5718                  */
5719                 tmp2 = xmlRelaxNGNewDefine(ctxt, tmp->content->node);
5720                 if (tmp2 == NULL)
5721                     break;
5722                 tmp2->type = XML_RELAXNG_GROUP;
5723                 tmp2->content = tmp->content;
5724             } else {
5725                 tmp2 = tmp->content;
5726             }
5727             if (last == NULL) {
5728                 cur->content = tmp2;
5729             } else {
5730                 last->next = tmp2;
5731             }
5732             last = tmp2;
5733         }
5734         tmp->content = cur;
5735         tmp = tmp->nextHash;
5736     }
5737     define->content = cur;
5738     if (choiceOrInterleave == 0) {
5739         if (ctxt->interleaves == NULL)
5740             ctxt->interleaves = xmlHashCreate(10);
5741         if (ctxt->interleaves == NULL) {
5742             xmlRngPErr(ctxt, define->node, XML_RNGP_INTERLEAVE_CREATE_FAILED,
5743                        "Failed to create interleaves hash table\n", NULL,
5744                        NULL);
5745         } else {
5746             char tmpname[32];
5747 
5748             snprintf(tmpname, 32, "interleave%d", ctxt->nbInterleaves++);
5749             if (xmlHashAddEntry(ctxt->interleaves, BAD_CAST tmpname, cur) <
5750                 0) {
5751                 xmlRngPErr(ctxt, define->node, XML_RNGP_INTERLEAVE_CREATE_FAILED,
5752                            "Failed to add %s to hash table\n",
5753 			   (const xmlChar *) tmpname, NULL);
5754             }
5755         }
5756     }
5757 }
5758 
5759 /**
5760  * xmlRelaxNGCombineStart:
5761  * @ctxt:  a Relax-NG parser context
5762  * @grammar:  the grammar
5763  *
5764  * Applies the 4.17. combine rule for all the start
5765  * element of a given grammar.
5766  */
5767 static void
xmlRelaxNGCombineStart(xmlRelaxNGParserCtxtPtr ctxt,xmlRelaxNGGrammarPtr grammar)5768 xmlRelaxNGCombineStart(xmlRelaxNGParserCtxtPtr ctxt,
5769                        xmlRelaxNGGrammarPtr grammar)
5770 {
5771     xmlRelaxNGDefinePtr starts;
5772     xmlChar *combine;
5773     int choiceOrInterleave = -1;
5774     int missing = 0;
5775     xmlRelaxNGDefinePtr cur;
5776 
5777     starts = grammar->start;
5778     if ((starts == NULL) || (starts->next == NULL))
5779         return;
5780     cur = starts;
5781     while (cur != NULL) {
5782         if ((cur->node == NULL) || (cur->node->parent == NULL) ||
5783             (!xmlStrEqual(cur->node->parent->name, BAD_CAST "start"))) {
5784             combine = NULL;
5785             xmlRngPErr(ctxt, cur->node, XML_RNGP_START_MISSING,
5786                        "Internal error: start element not found\n", NULL,
5787                        NULL);
5788         } else {
5789             combine = xmlGetProp(cur->node->parent, BAD_CAST "combine");
5790         }
5791 
5792         if (combine != NULL) {
5793             if (xmlStrEqual(combine, BAD_CAST "choice")) {
5794                 if (choiceOrInterleave == -1)
5795                     choiceOrInterleave = 1;
5796                 else if (choiceOrInterleave == 0) {
5797                     xmlRngPErr(ctxt, cur->node, XML_RNGP_START_CHOICE_AND_INTERLEAVE,
5798                                "<start> use both 'choice' and 'interleave'\n",
5799                                NULL, NULL);
5800                 }
5801             } else if (xmlStrEqual(combine, BAD_CAST "interleave")) {
5802                 if (choiceOrInterleave == -1)
5803                     choiceOrInterleave = 0;
5804                 else if (choiceOrInterleave == 1) {
5805                     xmlRngPErr(ctxt, cur->node, XML_RNGP_START_CHOICE_AND_INTERLEAVE,
5806                                "<start> use both 'choice' and 'interleave'\n",
5807                                NULL, NULL);
5808                 }
5809             } else {
5810                 xmlRngPErr(ctxt, cur->node, XML_RNGP_UNKNOWN_COMBINE,
5811                            "<start> uses unknown combine value '%s''\n",
5812                            combine, NULL);
5813             }
5814             xmlFree(combine);
5815         } else {
5816             if (missing == 0)
5817                 missing = 1;
5818             else {
5819                 xmlRngPErr(ctxt, cur->node, XML_RNGP_NEED_COMBINE,
5820                            "Some <start> element miss the combine attribute\n",
5821                            NULL, NULL);
5822             }
5823         }
5824 
5825         cur = cur->next;
5826     }
5827     if (choiceOrInterleave == -1)
5828         choiceOrInterleave = 0;
5829     cur = xmlRelaxNGNewDefine(ctxt, starts->node);
5830     if (cur == NULL)
5831         return;
5832     if (choiceOrInterleave == 0)
5833         cur->type = XML_RELAXNG_INTERLEAVE;
5834     else
5835         cur->type = XML_RELAXNG_CHOICE;
5836     cur->content = grammar->start;
5837     grammar->start = cur;
5838     if (choiceOrInterleave == 0) {
5839         if (ctxt->interleaves == NULL)
5840             ctxt->interleaves = xmlHashCreate(10);
5841         if (ctxt->interleaves == NULL) {
5842             xmlRngPErr(ctxt, cur->node, XML_RNGP_INTERLEAVE_CREATE_FAILED,
5843                        "Failed to create interleaves hash table\n", NULL,
5844                        NULL);
5845         } else {
5846             char tmpname[32];
5847 
5848             snprintf(tmpname, 32, "interleave%d", ctxt->nbInterleaves++);
5849             if (xmlHashAddEntry(ctxt->interleaves, BAD_CAST tmpname, cur) <
5850                 0) {
5851                 xmlRngPErr(ctxt, cur->node, XML_RNGP_INTERLEAVE_CREATE_FAILED,
5852                            "Failed to add %s to hash table\n",
5853 			   (const xmlChar *) tmpname, NULL);
5854             }
5855         }
5856     }
5857 }
5858 
5859 /**
5860  * xmlRelaxNGCheckCycles:
5861  * @ctxt:  a Relax-NG parser context
5862  * @nodes:  grammar children nodes
5863  * @depth:  the counter
5864  *
5865  * Check for cycles.
5866  *
5867  * Returns 0 if check passed, and -1 in case of error
5868  */
5869 static int
xmlRelaxNGCheckCycles(xmlRelaxNGParserCtxtPtr ctxt,xmlRelaxNGDefinePtr cur,int depth)5870 xmlRelaxNGCheckCycles(xmlRelaxNGParserCtxtPtr ctxt,
5871                       xmlRelaxNGDefinePtr cur, int depth)
5872 {
5873     int ret = 0;
5874 
5875     while ((ret == 0) && (cur != NULL)) {
5876         if ((cur->type == XML_RELAXNG_REF) ||
5877             (cur->type == XML_RELAXNG_PARENTREF)) {
5878             if (cur->depth == -1) {
5879                 cur->depth = depth;
5880                 ret = xmlRelaxNGCheckCycles(ctxt, cur->content, depth);
5881                 cur->depth = -2;
5882             } else if (depth == cur->depth) {
5883                 xmlRngPErr(ctxt, cur->node, XML_RNGP_REF_CYCLE,
5884                            "Detected a cycle in %s references\n",
5885                            cur->name, NULL);
5886                 return (-1);
5887             }
5888         } else if (cur->type == XML_RELAXNG_ELEMENT) {
5889             ret = xmlRelaxNGCheckCycles(ctxt, cur->content, depth + 1);
5890         } else {
5891             ret = xmlRelaxNGCheckCycles(ctxt, cur->content, depth);
5892         }
5893         cur = cur->next;
5894     }
5895     return (ret);
5896 }
5897 
5898 /**
5899  * xmlRelaxNGTryUnlink:
5900  * @ctxt:  a Relax-NG parser context
5901  * @cur:  the definition to unlink
5902  * @parent:  the parent definition
5903  * @prev:  the previous sibling definition
5904  *
5905  * Try to unlink a definition. If not possible make it a NOOP
5906  *
5907  * Returns the new prev definition
5908  */
5909 static xmlRelaxNGDefinePtr
xmlRelaxNGTryUnlink(xmlRelaxNGParserCtxtPtr ctxt ATTRIBUTE_UNUSED,xmlRelaxNGDefinePtr cur,xmlRelaxNGDefinePtr parent,xmlRelaxNGDefinePtr prev)5910 xmlRelaxNGTryUnlink(xmlRelaxNGParserCtxtPtr ctxt ATTRIBUTE_UNUSED,
5911                     xmlRelaxNGDefinePtr cur,
5912                     xmlRelaxNGDefinePtr parent, xmlRelaxNGDefinePtr prev)
5913 {
5914     if (prev != NULL) {
5915         prev->next = cur->next;
5916     } else {
5917         if (parent != NULL) {
5918             if (parent->content == cur)
5919                 parent->content = cur->next;
5920             else if (parent->attrs == cur)
5921                 parent->attrs = cur->next;
5922             else if (parent->nameClass == cur)
5923                 parent->nameClass = cur->next;
5924         } else {
5925             cur->type = XML_RELAXNG_NOOP;
5926             prev = cur;
5927         }
5928     }
5929     return (prev);
5930 }
5931 
5932 /**
5933  * xmlRelaxNGSimplify:
5934  * @ctxt:  a Relax-NG parser context
5935  * @nodes:  grammar children nodes
5936  *
5937  * Check for simplification of empty and notAllowed
5938  */
5939 static void
xmlRelaxNGSimplify(xmlRelaxNGParserCtxtPtr ctxt,xmlRelaxNGDefinePtr cur,xmlRelaxNGDefinePtr parent)5940 xmlRelaxNGSimplify(xmlRelaxNGParserCtxtPtr ctxt,
5941                    xmlRelaxNGDefinePtr cur, xmlRelaxNGDefinePtr parent)
5942 {
5943     xmlRelaxNGDefinePtr prev = NULL;
5944 
5945     while (cur != NULL) {
5946         if ((cur->type == XML_RELAXNG_REF) ||
5947             (cur->type == XML_RELAXNG_PARENTREF)) {
5948             if (cur->depth != -3) {
5949                 cur->depth = -3;
5950                 xmlRelaxNGSimplify(ctxt, cur->content, cur);
5951             }
5952         } else if (cur->type == XML_RELAXNG_NOT_ALLOWED) {
5953             cur->parent = parent;
5954             if ((parent != NULL) &&
5955                 ((parent->type == XML_RELAXNG_ATTRIBUTE) ||
5956                  (parent->type == XML_RELAXNG_LIST) ||
5957                  (parent->type == XML_RELAXNG_GROUP) ||
5958                  (parent->type == XML_RELAXNG_INTERLEAVE) ||
5959                  (parent->type == XML_RELAXNG_ONEORMORE) ||
5960                  (parent->type == XML_RELAXNG_ZEROORMORE))) {
5961                 parent->type = XML_RELAXNG_NOT_ALLOWED;
5962                 break;
5963             }
5964             if ((parent != NULL) && (parent->type == XML_RELAXNG_CHOICE)) {
5965                 prev = xmlRelaxNGTryUnlink(ctxt, cur, parent, prev);
5966             } else
5967                 prev = cur;
5968         } else if (cur->type == XML_RELAXNG_EMPTY) {
5969             cur->parent = parent;
5970             if ((parent != NULL) &&
5971                 ((parent->type == XML_RELAXNG_ONEORMORE) ||
5972                  (parent->type == XML_RELAXNG_ZEROORMORE))) {
5973                 parent->type = XML_RELAXNG_EMPTY;
5974                 break;
5975             }
5976             if ((parent != NULL) &&
5977                 ((parent->type == XML_RELAXNG_GROUP) ||
5978                  (parent->type == XML_RELAXNG_INTERLEAVE))) {
5979                 prev = xmlRelaxNGTryUnlink(ctxt, cur, parent, prev);
5980             } else
5981                 prev = cur;
5982         } else {
5983             cur->parent = parent;
5984             if (cur->content != NULL)
5985                 xmlRelaxNGSimplify(ctxt, cur->content, cur);
5986             if ((cur->type != XML_RELAXNG_VALUE) && (cur->attrs != NULL))
5987                 xmlRelaxNGSimplify(ctxt, cur->attrs, cur);
5988             if (cur->nameClass != NULL)
5989                 xmlRelaxNGSimplify(ctxt, cur->nameClass, cur);
5990             /*
5991              * On Elements, try to move attribute only generating rules on
5992              * the attrs rules.
5993              */
5994             if (cur->type == XML_RELAXNG_ELEMENT) {
5995                 int attronly;
5996                 xmlRelaxNGDefinePtr tmp, pre;
5997 
5998                 while (cur->content != NULL) {
5999                     attronly =
6000                         xmlRelaxNGGenerateAttributes(ctxt, cur->content);
6001                     if (attronly == 1) {
6002                         /*
6003                          * migrate cur->content to attrs
6004                          */
6005                         tmp = cur->content;
6006                         cur->content = tmp->next;
6007                         tmp->next = cur->attrs;
6008                         cur->attrs = tmp;
6009                     } else {
6010                         /*
6011                          * cur->content can generate elements or text
6012                          */
6013                         break;
6014                     }
6015                 }
6016                 pre = cur->content;
6017                 while ((pre != NULL) && (pre->next != NULL)) {
6018                     tmp = pre->next;
6019                     attronly = xmlRelaxNGGenerateAttributes(ctxt, tmp);
6020                     if (attronly == 1) {
6021                         /*
6022                          * migrate tmp to attrs
6023                          */
6024                         pre->next = tmp->next;
6025                         tmp->next = cur->attrs;
6026                         cur->attrs = tmp;
6027                     } else {
6028                         pre = tmp;
6029                     }
6030                 }
6031             }
6032             /*
6033              * This may result in a simplification
6034              */
6035             if ((cur->type == XML_RELAXNG_GROUP) ||
6036                 (cur->type == XML_RELAXNG_INTERLEAVE)) {
6037                 if (cur->content == NULL)
6038                     cur->type = XML_RELAXNG_EMPTY;
6039                 else if (cur->content->next == NULL) {
6040                     if ((parent == NULL) && (prev == NULL)) {
6041                         cur->type = XML_RELAXNG_NOOP;
6042                     } else if (prev == NULL) {
6043                         parent->content = cur->content;
6044                         cur->content->next = cur->next;
6045                         cur = cur->content;
6046                     } else {
6047                         cur->content->next = cur->next;
6048                         prev->next = cur->content;
6049                         cur = cur->content;
6050                     }
6051                 }
6052             }
6053             /*
6054              * the current node may have been transformed back
6055              */
6056             if ((cur->type == XML_RELAXNG_EXCEPT) &&
6057                 (cur->content != NULL) &&
6058                 (cur->content->type == XML_RELAXNG_NOT_ALLOWED)) {
6059                 prev = xmlRelaxNGTryUnlink(ctxt, cur, parent, prev);
6060             } else if (cur->type == XML_RELAXNG_NOT_ALLOWED) {
6061                 if ((parent != NULL) &&
6062                     ((parent->type == XML_RELAXNG_ATTRIBUTE) ||
6063                      (parent->type == XML_RELAXNG_LIST) ||
6064                      (parent->type == XML_RELAXNG_GROUP) ||
6065                      (parent->type == XML_RELAXNG_INTERLEAVE) ||
6066                      (parent->type == XML_RELAXNG_ONEORMORE) ||
6067                      (parent->type == XML_RELAXNG_ZEROORMORE))) {
6068                     parent->type = XML_RELAXNG_NOT_ALLOWED;
6069                     break;
6070                 }
6071                 if ((parent != NULL) &&
6072                     (parent->type == XML_RELAXNG_CHOICE)) {
6073                     prev = xmlRelaxNGTryUnlink(ctxt, cur, parent, prev);
6074                 } else
6075                     prev = cur;
6076             } else if (cur->type == XML_RELAXNG_EMPTY) {
6077                 if ((parent != NULL) &&
6078                     ((parent->type == XML_RELAXNG_ONEORMORE) ||
6079                      (parent->type == XML_RELAXNG_ZEROORMORE))) {
6080                     parent->type = XML_RELAXNG_EMPTY;
6081                     break;
6082                 }
6083                 if ((parent != NULL) &&
6084                     ((parent->type == XML_RELAXNG_GROUP) ||
6085                      (parent->type == XML_RELAXNG_INTERLEAVE) ||
6086                      (parent->type == XML_RELAXNG_CHOICE))) {
6087                     prev = xmlRelaxNGTryUnlink(ctxt, cur, parent, prev);
6088                 } else
6089                     prev = cur;
6090             } else {
6091                 prev = cur;
6092             }
6093         }
6094         cur = cur->next;
6095     }
6096 }
6097 
6098 /**
6099  * xmlRelaxNGGroupContentType:
6100  * @ct1:  the first content type
6101  * @ct2:  the second content type
6102  *
6103  * Try to group 2 content types
6104  *
6105  * Returns the content type
6106  */
6107 static xmlRelaxNGContentType
xmlRelaxNGGroupContentType(xmlRelaxNGContentType ct1,xmlRelaxNGContentType ct2)6108 xmlRelaxNGGroupContentType(xmlRelaxNGContentType ct1,
6109                            xmlRelaxNGContentType ct2)
6110 {
6111     if ((ct1 == XML_RELAXNG_CONTENT_ERROR) ||
6112         (ct2 == XML_RELAXNG_CONTENT_ERROR))
6113         return (XML_RELAXNG_CONTENT_ERROR);
6114     if (ct1 == XML_RELAXNG_CONTENT_EMPTY)
6115         return (ct2);
6116     if (ct2 == XML_RELAXNG_CONTENT_EMPTY)
6117         return (ct1);
6118     if ((ct1 == XML_RELAXNG_CONTENT_COMPLEX) &&
6119         (ct2 == XML_RELAXNG_CONTENT_COMPLEX))
6120         return (XML_RELAXNG_CONTENT_COMPLEX);
6121     return (XML_RELAXNG_CONTENT_ERROR);
6122 }
6123 
6124 /**
6125  * xmlRelaxNGMaxContentType:
6126  * @ct1:  the first content type
6127  * @ct2:  the second content type
6128  *
6129  * Compute the max content-type
6130  *
6131  * Returns the content type
6132  */
6133 static xmlRelaxNGContentType
xmlRelaxNGMaxContentType(xmlRelaxNGContentType ct1,xmlRelaxNGContentType ct2)6134 xmlRelaxNGMaxContentType(xmlRelaxNGContentType ct1,
6135                          xmlRelaxNGContentType ct2)
6136 {
6137     if ((ct1 == XML_RELAXNG_CONTENT_ERROR) ||
6138         (ct2 == XML_RELAXNG_CONTENT_ERROR))
6139         return (XML_RELAXNG_CONTENT_ERROR);
6140     if ((ct1 == XML_RELAXNG_CONTENT_SIMPLE) ||
6141         (ct2 == XML_RELAXNG_CONTENT_SIMPLE))
6142         return (XML_RELAXNG_CONTENT_SIMPLE);
6143     if ((ct1 == XML_RELAXNG_CONTENT_COMPLEX) ||
6144         (ct2 == XML_RELAXNG_CONTENT_COMPLEX))
6145         return (XML_RELAXNG_CONTENT_COMPLEX);
6146     return (XML_RELAXNG_CONTENT_EMPTY);
6147 }
6148 
6149 /**
6150  * xmlRelaxNGCheckRules:
6151  * @ctxt:  a Relax-NG parser context
6152  * @cur:  the current definition
6153  * @flags:  some accumulated flags
6154  * @ptype:  the parent type
6155  *
6156  * Check for rules in section 7.1 and 7.2
6157  *
6158  * Returns the content type of @cur
6159  */
6160 static xmlRelaxNGContentType
xmlRelaxNGCheckRules(xmlRelaxNGParserCtxtPtr ctxt,xmlRelaxNGDefinePtr cur,int flags,xmlRelaxNGType ptype)6161 xmlRelaxNGCheckRules(xmlRelaxNGParserCtxtPtr ctxt,
6162                      xmlRelaxNGDefinePtr cur, int flags,
6163                      xmlRelaxNGType ptype)
6164 {
6165     int nflags;
6166     xmlRelaxNGContentType ret, tmp, val = XML_RELAXNG_CONTENT_EMPTY;
6167 
6168     while (cur != NULL) {
6169         ret = XML_RELAXNG_CONTENT_EMPTY;
6170         if ((cur->type == XML_RELAXNG_REF) ||
6171             (cur->type == XML_RELAXNG_PARENTREF)) {
6172            /*
6173             * This should actually be caught by list//element(ref) at the
6174             * element boundaries, c.f. Bug #159968 local refs are dropped
6175             * in step 4.19.
6176             */
6177 #if 0
6178             if (flags & XML_RELAXNG_IN_LIST) {
6179                 xmlRngPErr(ctxt, cur->node, XML_RNGP_PAT_LIST_REF,
6180                            "Found forbidden pattern list//ref\n", NULL,
6181                            NULL);
6182             }
6183 #endif
6184             if (flags & XML_RELAXNG_IN_DATAEXCEPT) {
6185                 xmlRngPErr(ctxt, cur->node, XML_RNGP_PAT_DATA_EXCEPT_REF,
6186                            "Found forbidden pattern data/except//ref\n",
6187                            NULL, NULL);
6188             }
6189             if (cur->content == NULL) {
6190                 if (cur->type == XML_RELAXNG_PARENTREF)
6191                     xmlRngPErr(ctxt, cur->node, XML_RNGP_REF_NO_DEF,
6192                                "Internal found no define for parent refs\n",
6193                                NULL, NULL);
6194                 else
6195                     xmlRngPErr(ctxt, cur->node, XML_RNGP_REF_NO_DEF,
6196                                "Internal found no define for ref %s\n",
6197                                (cur->name ? cur->name: BAD_CAST "null"), NULL);
6198             }
6199             if (cur->depth > -4) {
6200                 cur->depth = -4;
6201                 ret = xmlRelaxNGCheckRules(ctxt, cur->content,
6202                                            flags, cur->type);
6203                 cur->depth = ret - 15;
6204             } else if (cur->depth == -4) {
6205                 ret = XML_RELAXNG_CONTENT_COMPLEX;
6206             } else {
6207                 ret = (xmlRelaxNGContentType) (cur->depth + 15);
6208             }
6209         } else if (cur->type == XML_RELAXNG_ELEMENT) {
6210             /*
6211              * The 7.3 Attribute derivation rule for groups is plugged there
6212              */
6213             xmlRelaxNGCheckGroupAttrs(ctxt, cur);
6214             if (flags & XML_RELAXNG_IN_DATAEXCEPT) {
6215                 xmlRngPErr(ctxt, cur->node, XML_RNGP_PAT_DATA_EXCEPT_ELEM,
6216                            "Found forbidden pattern data/except//element(ref)\n",
6217                            NULL, NULL);
6218             }
6219             if (flags & XML_RELAXNG_IN_LIST) {
6220                 xmlRngPErr(ctxt, cur->node, XML_RNGP_PAT_LIST_ELEM,
6221                            "Found forbidden pattern list//element(ref)\n",
6222                            NULL, NULL);
6223             }
6224             if (flags & XML_RELAXNG_IN_ATTRIBUTE) {
6225                 xmlRngPErr(ctxt, cur->node, XML_RNGP_PAT_ATTR_ELEM,
6226                            "Found forbidden pattern attribute//element(ref)\n",
6227                            NULL, NULL);
6228             }
6229             if (flags & XML_RELAXNG_IN_ATTRIBUTE) {
6230                 xmlRngPErr(ctxt, cur->node, XML_RNGP_PAT_ATTR_ELEM,
6231                            "Found forbidden pattern attribute//element(ref)\n",
6232                            NULL, NULL);
6233             }
6234             /*
6235              * reset since in the simple form elements are only child
6236              * of grammar/define
6237              */
6238             nflags = 0;
6239             ret =
6240                 xmlRelaxNGCheckRules(ctxt, cur->attrs, nflags, cur->type);
6241             if (ret != XML_RELAXNG_CONTENT_EMPTY) {
6242                 xmlRngPErr(ctxt, cur->node, XML_RNGP_ELEM_CONTENT_EMPTY,
6243                            "Element %s attributes have a content type error\n",
6244                            cur->name, NULL);
6245             }
6246             ret =
6247                 xmlRelaxNGCheckRules(ctxt, cur->content, nflags,
6248                                      cur->type);
6249             if (ret == XML_RELAXNG_CONTENT_ERROR) {
6250                 xmlRngPErr(ctxt, cur->node, XML_RNGP_ELEM_CONTENT_ERROR,
6251                            "Element %s has a content type error\n",
6252                            cur->name, NULL);
6253             } else {
6254                 ret = XML_RELAXNG_CONTENT_COMPLEX;
6255             }
6256         } else if (cur->type == XML_RELAXNG_ATTRIBUTE) {
6257             if (flags & XML_RELAXNG_IN_ATTRIBUTE) {
6258                 xmlRngPErr(ctxt, cur->node, XML_RNGP_PAT_ATTR_ATTR,
6259                            "Found forbidden pattern attribute//attribute\n",
6260                            NULL, NULL);
6261             }
6262             if (flags & XML_RELAXNG_IN_LIST) {
6263                 xmlRngPErr(ctxt, cur->node, XML_RNGP_PAT_LIST_ATTR,
6264                            "Found forbidden pattern list//attribute\n",
6265                            NULL, NULL);
6266             }
6267             if (flags & XML_RELAXNG_IN_OOMGROUP) {
6268                 xmlRngPErr(ctxt, cur->node, XML_RNGP_PAT_ONEMORE_GROUP_ATTR,
6269                            "Found forbidden pattern oneOrMore//group//attribute\n",
6270                            NULL, NULL);
6271             }
6272             if (flags & XML_RELAXNG_IN_OOMINTERLEAVE) {
6273                 xmlRngPErr(ctxt, cur->node, XML_RNGP_PAT_ONEMORE_INTERLEAVE_ATTR,
6274                            "Found forbidden pattern oneOrMore//interleave//attribute\n",
6275                            NULL, NULL);
6276             }
6277             if (flags & XML_RELAXNG_IN_DATAEXCEPT) {
6278                 xmlRngPErr(ctxt, cur->node, XML_RNGP_PAT_DATA_EXCEPT_ATTR,
6279                            "Found forbidden pattern data/except//attribute\n",
6280                            NULL, NULL);
6281             }
6282             if (flags & XML_RELAXNG_IN_START) {
6283                 xmlRngPErr(ctxt, cur->node, XML_RNGP_PAT_START_ATTR,
6284                            "Found forbidden pattern start//attribute\n",
6285                            NULL, NULL);
6286             }
6287             if ((!(flags & XML_RELAXNG_IN_ONEORMORE))
6288                 && cur->name == NULL
6289                 /* following is checking alternative name class readiness
6290                    in case it went the "choice" route */
6291                 && cur->nameClass == NULL) {
6292                 if (cur->ns == NULL) {
6293                     xmlRngPErr(ctxt, cur->node, XML_RNGP_ANYNAME_ATTR_ANCESTOR,
6294                                "Found anyName attribute without oneOrMore ancestor\n",
6295                                NULL, NULL);
6296                 } else {
6297                     xmlRngPErr(ctxt, cur->node, XML_RNGP_NSNAME_ATTR_ANCESTOR,
6298                                "Found nsName attribute without oneOrMore ancestor\n",
6299                                NULL, NULL);
6300                 }
6301             }
6302             nflags = flags | XML_RELAXNG_IN_ATTRIBUTE;
6303             xmlRelaxNGCheckRules(ctxt, cur->content, nflags, cur->type);
6304             ret = XML_RELAXNG_CONTENT_EMPTY;
6305         } else if ((cur->type == XML_RELAXNG_ONEORMORE) ||
6306                    (cur->type == XML_RELAXNG_ZEROORMORE)) {
6307             if (flags & XML_RELAXNG_IN_DATAEXCEPT) {
6308                 xmlRngPErr(ctxt, cur->node, XML_RNGP_PAT_DATA_EXCEPT_ONEMORE,
6309                            "Found forbidden pattern data/except//oneOrMore\n",
6310                            NULL, NULL);
6311             }
6312             if (flags & XML_RELAXNG_IN_START) {
6313                 xmlRngPErr(ctxt, cur->node, XML_RNGP_PAT_START_ONEMORE,
6314                            "Found forbidden pattern start//oneOrMore\n",
6315                            NULL, NULL);
6316             }
6317             nflags = flags | XML_RELAXNG_IN_ONEORMORE;
6318             ret =
6319                 xmlRelaxNGCheckRules(ctxt, cur->content, nflags,
6320                                      cur->type);
6321             ret = xmlRelaxNGGroupContentType(ret, ret);
6322         } else if (cur->type == XML_RELAXNG_LIST) {
6323             if (flags & XML_RELAXNG_IN_LIST) {
6324                 xmlRngPErr(ctxt, cur->node, XML_RNGP_PAT_LIST_LIST,
6325                            "Found forbidden pattern list//list\n", NULL,
6326                            NULL);
6327             }
6328             if (flags & XML_RELAXNG_IN_DATAEXCEPT) {
6329                 xmlRngPErr(ctxt, cur->node, XML_RNGP_PAT_DATA_EXCEPT_LIST,
6330                            "Found forbidden pattern data/except//list\n",
6331                            NULL, NULL);
6332             }
6333             if (flags & XML_RELAXNG_IN_START) {
6334                 xmlRngPErr(ctxt, cur->node, XML_RNGP_PAT_START_LIST,
6335                            "Found forbidden pattern start//list\n", NULL,
6336                            NULL);
6337             }
6338             nflags = flags | XML_RELAXNG_IN_LIST;
6339             ret =
6340                 xmlRelaxNGCheckRules(ctxt, cur->content, nflags,
6341                                      cur->type);
6342         } else if (cur->type == XML_RELAXNG_GROUP) {
6343             if (flags & XML_RELAXNG_IN_DATAEXCEPT) {
6344                 xmlRngPErr(ctxt, cur->node, XML_RNGP_PAT_DATA_EXCEPT_GROUP,
6345                            "Found forbidden pattern data/except//group\n",
6346                            NULL, NULL);
6347             }
6348             if (flags & XML_RELAXNG_IN_START) {
6349                 xmlRngPErr(ctxt, cur->node, XML_RNGP_PAT_START_GROUP,
6350                            "Found forbidden pattern start//group\n", NULL,
6351                            NULL);
6352             }
6353             if (flags & XML_RELAXNG_IN_ONEORMORE)
6354                 nflags = flags | XML_RELAXNG_IN_OOMGROUP;
6355             else
6356                 nflags = flags;
6357             ret =
6358                 xmlRelaxNGCheckRules(ctxt, cur->content, nflags,
6359                                      cur->type);
6360             /*
6361              * The 7.3 Attribute derivation rule for groups is plugged there
6362              */
6363             xmlRelaxNGCheckGroupAttrs(ctxt, cur);
6364         } else if (cur->type == XML_RELAXNG_INTERLEAVE) {
6365             if (flags & XML_RELAXNG_IN_LIST) {
6366                 xmlRngPErr(ctxt, cur->node, XML_RNGP_PAT_LIST_INTERLEAVE,
6367                            "Found forbidden pattern list//interleave\n",
6368                            NULL, NULL);
6369             }
6370             if (flags & XML_RELAXNG_IN_DATAEXCEPT) {
6371                 xmlRngPErr(ctxt, cur->node, XML_RNGP_PAT_DATA_EXCEPT_INTERLEAVE,
6372                            "Found forbidden pattern data/except//interleave\n",
6373                            NULL, NULL);
6374             }
6375             if (flags & XML_RELAXNG_IN_START) {
6376                 xmlRngPErr(ctxt, cur->node, XML_RNGP_PAT_DATA_EXCEPT_INTERLEAVE,
6377                            "Found forbidden pattern start//interleave\n",
6378                            NULL, NULL);
6379             }
6380             if (flags & XML_RELAXNG_IN_ONEORMORE)
6381                 nflags = flags | XML_RELAXNG_IN_OOMINTERLEAVE;
6382             else
6383                 nflags = flags;
6384             ret =
6385                 xmlRelaxNGCheckRules(ctxt, cur->content, nflags,
6386                                      cur->type);
6387         } else if (cur->type == XML_RELAXNG_EXCEPT) {
6388             if ((cur->parent != NULL) &&
6389                 (cur->parent->type == XML_RELAXNG_DATATYPE))
6390                 nflags = flags | XML_RELAXNG_IN_DATAEXCEPT;
6391             else
6392                 nflags = flags;
6393             ret =
6394                 xmlRelaxNGCheckRules(ctxt, cur->content, nflags,
6395                                      cur->type);
6396         } else if (cur->type == XML_RELAXNG_DATATYPE) {
6397             if (flags & XML_RELAXNG_IN_START) {
6398                 xmlRngPErr(ctxt, cur->node, XML_RNGP_PAT_START_DATA,
6399                            "Found forbidden pattern start//data\n", NULL,
6400                            NULL);
6401             }
6402             xmlRelaxNGCheckRules(ctxt, cur->content, flags, cur->type);
6403             ret = XML_RELAXNG_CONTENT_SIMPLE;
6404         } else if (cur->type == XML_RELAXNG_VALUE) {
6405             if (flags & XML_RELAXNG_IN_START) {
6406                 xmlRngPErr(ctxt, cur->node, XML_RNGP_PAT_START_VALUE,
6407                            "Found forbidden pattern start//value\n", NULL,
6408                            NULL);
6409             }
6410             xmlRelaxNGCheckRules(ctxt, cur->content, flags, cur->type);
6411             ret = XML_RELAXNG_CONTENT_SIMPLE;
6412         } else if (cur->type == XML_RELAXNG_TEXT) {
6413             if (flags & XML_RELAXNG_IN_LIST) {
6414                 xmlRngPErr(ctxt, cur->node, XML_RNGP_PAT_LIST_TEXT,
6415                            "Found forbidden pattern list//text\n", NULL,
6416                            NULL);
6417             }
6418             if (flags & XML_RELAXNG_IN_DATAEXCEPT) {
6419                 xmlRngPErr(ctxt, cur->node, XML_RNGP_PAT_DATA_EXCEPT_TEXT,
6420                            "Found forbidden pattern data/except//text\n",
6421                            NULL, NULL);
6422             }
6423             if (flags & XML_RELAXNG_IN_START) {
6424                 xmlRngPErr(ctxt, cur->node, XML_RNGP_PAT_START_TEXT,
6425                            "Found forbidden pattern start//text\n", NULL,
6426                            NULL);
6427             }
6428             ret = XML_RELAXNG_CONTENT_COMPLEX;
6429         } else if (cur->type == XML_RELAXNG_EMPTY) {
6430             if (flags & XML_RELAXNG_IN_DATAEXCEPT) {
6431                 xmlRngPErr(ctxt, cur->node, XML_RNGP_PAT_DATA_EXCEPT_EMPTY,
6432                            "Found forbidden pattern data/except//empty\n",
6433                            NULL, NULL);
6434             }
6435             if (flags & XML_RELAXNG_IN_START) {
6436                 xmlRngPErr(ctxt, cur->node, XML_RNGP_PAT_START_EMPTY,
6437                            "Found forbidden pattern start//empty\n", NULL,
6438                            NULL);
6439             }
6440             ret = XML_RELAXNG_CONTENT_EMPTY;
6441         } else if (cur->type == XML_RELAXNG_CHOICE) {
6442             xmlRelaxNGCheckChoiceDeterminism(ctxt, cur);
6443             ret =
6444                 xmlRelaxNGCheckRules(ctxt, cur->content, flags, cur->type);
6445         } else {
6446             ret =
6447                 xmlRelaxNGCheckRules(ctxt, cur->content, flags, cur->type);
6448         }
6449         cur = cur->next;
6450         if (ptype == XML_RELAXNG_GROUP) {
6451             val = xmlRelaxNGGroupContentType(val, ret);
6452         } else if (ptype == XML_RELAXNG_INTERLEAVE) {
6453             /*
6454              * TODO: scan complain that tmp is never used, seems on purpose
6455              *       need double-checking
6456              */
6457             tmp = xmlRelaxNGGroupContentType(val, ret);
6458             if (tmp != XML_RELAXNG_CONTENT_ERROR)
6459                 tmp = xmlRelaxNGMaxContentType(val, ret);
6460         } else if (ptype == XML_RELAXNG_CHOICE) {
6461             val = xmlRelaxNGMaxContentType(val, ret);
6462         } else if (ptype == XML_RELAXNG_LIST) {
6463             val = XML_RELAXNG_CONTENT_SIMPLE;
6464         } else if (ptype == XML_RELAXNG_EXCEPT) {
6465             if (ret == XML_RELAXNG_CONTENT_ERROR)
6466                 val = XML_RELAXNG_CONTENT_ERROR;
6467             else
6468                 val = XML_RELAXNG_CONTENT_SIMPLE;
6469         } else {
6470             val = xmlRelaxNGGroupContentType(val, ret);
6471         }
6472 
6473     }
6474     return (val);
6475 }
6476 
6477 /**
6478  * xmlRelaxNGParseGrammar:
6479  * @ctxt:  a Relax-NG parser context
6480  * @nodes:  grammar children nodes
6481  *
6482  * parse a Relax-NG <grammar> node
6483  *
6484  * Returns the internal xmlRelaxNGGrammarPtr built or
6485  *         NULL in case of error
6486  */
6487 static xmlRelaxNGGrammarPtr
xmlRelaxNGParseGrammar(xmlRelaxNGParserCtxtPtr ctxt,xmlNodePtr nodes)6488 xmlRelaxNGParseGrammar(xmlRelaxNGParserCtxtPtr ctxt, xmlNodePtr nodes)
6489 {
6490     xmlRelaxNGGrammarPtr ret, tmp, old;
6491 
6492     ret = xmlRelaxNGNewGrammar(ctxt);
6493     if (ret == NULL)
6494         return (NULL);
6495 
6496     /*
6497      * Link the new grammar in the tree
6498      */
6499     ret->parent = ctxt->grammar;
6500     if (ctxt->grammar != NULL) {
6501         tmp = ctxt->grammar->children;
6502         if (tmp == NULL) {
6503             ctxt->grammar->children = ret;
6504         } else {
6505             while (tmp->next != NULL)
6506                 tmp = tmp->next;
6507             tmp->next = ret;
6508         }
6509     }
6510 
6511     old = ctxt->grammar;
6512     ctxt->grammar = ret;
6513     xmlRelaxNGParseGrammarContent(ctxt, nodes);
6514     ctxt->grammar = ret;
6515     if (ctxt->grammar == NULL) {
6516         xmlRngPErr(ctxt, nodes, XML_RNGP_GRAMMAR_CONTENT,
6517                    "Failed to parse <grammar> content\n", NULL, NULL);
6518     } else if (ctxt->grammar->start == NULL) {
6519         xmlRngPErr(ctxt, nodes, XML_RNGP_GRAMMAR_NO_START,
6520                    "Element <grammar> has no <start>\n", NULL, NULL);
6521     }
6522 
6523     /*
6524      * Apply 4.17 merging rules to defines and starts
6525      */
6526     xmlRelaxNGCombineStart(ctxt, ret);
6527     if (ret->defs != NULL) {
6528         xmlHashScan(ret->defs, xmlRelaxNGCheckCombine, ctxt);
6529     }
6530 
6531     /*
6532      * link together defines and refs in this grammar
6533      */
6534     if (ret->refs != NULL) {
6535         xmlHashScan(ret->refs, xmlRelaxNGCheckReference, ctxt);
6536     }
6537 
6538 
6539     /* @@@@ */
6540 
6541     ctxt->grammar = old;
6542     return (ret);
6543 }
6544 
6545 /**
6546  * xmlRelaxNGParseDocument:
6547  * @ctxt:  a Relax-NG parser context
6548  * @node:  the root node of the RelaxNG schema
6549  *
6550  * parse a Relax-NG definition resource and build an internal
6551  * xmlRelaxNG structure which can be used to validate instances.
6552  *
6553  * Returns the internal XML RelaxNG structure built or
6554  *         NULL in case of error
6555  */
6556 static xmlRelaxNGPtr
xmlRelaxNGParseDocument(xmlRelaxNGParserCtxtPtr ctxt,xmlNodePtr node)6557 xmlRelaxNGParseDocument(xmlRelaxNGParserCtxtPtr ctxt, xmlNodePtr node)
6558 {
6559     xmlRelaxNGPtr schema = NULL;
6560     const xmlChar *olddefine;
6561     xmlRelaxNGGrammarPtr old;
6562 
6563     if ((ctxt == NULL) || (node == NULL))
6564         return (NULL);
6565 
6566     schema = xmlRelaxNGNewRelaxNG(ctxt);
6567     if (schema == NULL)
6568         return (NULL);
6569 
6570     olddefine = ctxt->define;
6571     ctxt->define = NULL;
6572     if (IS_RELAXNG(node, "grammar")) {
6573         schema->topgrammar = xmlRelaxNGParseGrammar(ctxt, node->children);
6574         if (schema->topgrammar == NULL) {
6575             xmlRelaxNGFree(schema);
6576             return (NULL);
6577         }
6578     } else {
6579         xmlRelaxNGGrammarPtr tmp, ret;
6580 
6581         schema->topgrammar = ret = xmlRelaxNGNewGrammar(ctxt);
6582         if (schema->topgrammar == NULL) {
6583             xmlRelaxNGFree(schema);
6584             return (NULL);
6585         }
6586         /*
6587          * Link the new grammar in the tree
6588          */
6589         ret->parent = ctxt->grammar;
6590         if (ctxt->grammar != NULL) {
6591             tmp = ctxt->grammar->children;
6592             if (tmp == NULL) {
6593                 ctxt->grammar->children = ret;
6594             } else {
6595                 while (tmp->next != NULL)
6596                     tmp = tmp->next;
6597                 tmp->next = ret;
6598             }
6599         }
6600         old = ctxt->grammar;
6601         ctxt->grammar = ret;
6602         xmlRelaxNGParseStart(ctxt, node);
6603         if (old != NULL)
6604             ctxt->grammar = old;
6605     }
6606     ctxt->define = olddefine;
6607     if (schema->topgrammar->start != NULL) {
6608         xmlRelaxNGCheckCycles(ctxt, schema->topgrammar->start, 0);
6609         if ((ctxt->flags & XML_RELAXNG_IN_EXTERNALREF) == 0) {
6610             xmlRelaxNGSimplify(ctxt, schema->topgrammar->start, NULL);
6611             while ((schema->topgrammar->start != NULL) &&
6612                    (schema->topgrammar->start->type == XML_RELAXNG_NOOP) &&
6613                    (schema->topgrammar->start->next != NULL))
6614                 schema->topgrammar->start =
6615                     schema->topgrammar->start->content;
6616             xmlRelaxNGCheckRules(ctxt, schema->topgrammar->start,
6617                                  XML_RELAXNG_IN_START, XML_RELAXNG_NOOP);
6618         }
6619     }
6620 
6621     return (schema);
6622 }
6623 
6624 /************************************************************************
6625  *									*
6626  *			Reading RelaxNGs				*
6627  *									*
6628  ************************************************************************/
6629 
6630 /**
6631  * xmlRelaxNGNewParserCtxt:
6632  * @URL:  the location of the schema
6633  *
6634  * Create an XML RelaxNGs parse context for that file/resource expected
6635  * to contain an XML RelaxNGs file.
6636  *
6637  * Returns the parser context or NULL in case of error
6638  */
6639 xmlRelaxNGParserCtxtPtr
xmlRelaxNGNewParserCtxt(const char * URL)6640 xmlRelaxNGNewParserCtxt(const char *URL)
6641 {
6642     xmlRelaxNGParserCtxtPtr ret;
6643 
6644     if (URL == NULL)
6645         return (NULL);
6646 
6647     ret =
6648         (xmlRelaxNGParserCtxtPtr) xmlMalloc(sizeof(xmlRelaxNGParserCtxt));
6649     if (ret == NULL) {
6650         xmlRngPErrMemory(NULL);
6651         return (NULL);
6652     }
6653     memset(ret, 0, sizeof(xmlRelaxNGParserCtxt));
6654     ret->URL = xmlStrdup((const xmlChar *) URL);
6655     return (ret);
6656 }
6657 
6658 /**
6659  * xmlRelaxNGNewMemParserCtxt:
6660  * @buffer:  a pointer to a char array containing the schemas
6661  * @size:  the size of the array
6662  *
6663  * Create an XML RelaxNGs parse context for that memory buffer expected
6664  * to contain an XML RelaxNGs file.
6665  *
6666  * Returns the parser context or NULL in case of error
6667  */
6668 xmlRelaxNGParserCtxtPtr
xmlRelaxNGNewMemParserCtxt(const char * buffer,int size)6669 xmlRelaxNGNewMemParserCtxt(const char *buffer, int size)
6670 {
6671     xmlRelaxNGParserCtxtPtr ret;
6672 
6673     if ((buffer == NULL) || (size <= 0))
6674         return (NULL);
6675 
6676     ret =
6677         (xmlRelaxNGParserCtxtPtr) xmlMalloc(sizeof(xmlRelaxNGParserCtxt));
6678     if (ret == NULL) {
6679         xmlRngPErrMemory(NULL);
6680         return (NULL);
6681     }
6682     memset(ret, 0, sizeof(xmlRelaxNGParserCtxt));
6683     ret->buffer = buffer;
6684     ret->size = size;
6685     return (ret);
6686 }
6687 
6688 /**
6689  * xmlRelaxNGNewDocParserCtxt:
6690  * @doc:  a preparsed document tree
6691  *
6692  * Create an XML RelaxNGs parser context for that document.
6693  * Note: since the process of compiling a RelaxNG schemas modifies the
6694  *       document, the @doc parameter is duplicated internally.
6695  *
6696  * Returns the parser context or NULL in case of error
6697  */
6698 xmlRelaxNGParserCtxtPtr
xmlRelaxNGNewDocParserCtxt(xmlDocPtr doc)6699 xmlRelaxNGNewDocParserCtxt(xmlDocPtr doc)
6700 {
6701     xmlRelaxNGParserCtxtPtr ret;
6702     xmlDocPtr copy;
6703 
6704     if (doc == NULL)
6705         return (NULL);
6706     copy = xmlCopyDoc(doc, 1);
6707     if (copy == NULL)
6708         return (NULL);
6709 
6710     ret =
6711         (xmlRelaxNGParserCtxtPtr) xmlMalloc(sizeof(xmlRelaxNGParserCtxt));
6712     if (ret == NULL) {
6713         xmlRngPErrMemory(NULL);
6714         xmlFreeDoc(copy);
6715         return (NULL);
6716     }
6717     memset(ret, 0, sizeof(xmlRelaxNGParserCtxt));
6718     ret->document = copy;
6719     ret->freedoc = 1;
6720     ret->userData = xmlGenericErrorContext;
6721     return (ret);
6722 }
6723 
6724 /**
6725  * xmlRelaxNGFreeParserCtxt:
6726  * @ctxt:  the schema parser context
6727  *
6728  * Free the resources associated to the schema parser context
6729  */
6730 void
xmlRelaxNGFreeParserCtxt(xmlRelaxNGParserCtxtPtr ctxt)6731 xmlRelaxNGFreeParserCtxt(xmlRelaxNGParserCtxtPtr ctxt)
6732 {
6733     if (ctxt == NULL)
6734         return;
6735     if (ctxt->URL != NULL)
6736         xmlFree(ctxt->URL);
6737     if (ctxt->doc != NULL)
6738         xmlRelaxNGFreeDocument(ctxt->doc);
6739     if (ctxt->interleaves != NULL)
6740         xmlHashFree(ctxt->interleaves, NULL);
6741     if (ctxt->documents != NULL)
6742         xmlRelaxNGFreeDocumentList(ctxt->documents);
6743     if (ctxt->includes != NULL)
6744         xmlRelaxNGFreeIncludeList(ctxt->includes);
6745     if (ctxt->docTab != NULL)
6746         xmlFree(ctxt->docTab);
6747     if (ctxt->incTab != NULL)
6748         xmlFree(ctxt->incTab);
6749     if (ctxt->defTab != NULL) {
6750         int i;
6751 
6752         for (i = 0; i < ctxt->defNr; i++)
6753             xmlRelaxNGFreeDefine(ctxt->defTab[i]);
6754         xmlFree(ctxt->defTab);
6755     }
6756     if ((ctxt->document != NULL) && (ctxt->freedoc))
6757         xmlFreeDoc(ctxt->document);
6758     xmlFree(ctxt);
6759 }
6760 
6761 /**
6762  * xmlRelaxNGNormExtSpace:
6763  * @value:  a value
6764  *
6765  * Removes the leading and ending spaces of the value
6766  * The string is modified "in situ"
6767  */
6768 static void
xmlRelaxNGNormExtSpace(xmlChar * value)6769 xmlRelaxNGNormExtSpace(xmlChar * value)
6770 {
6771     xmlChar *start = value;
6772     xmlChar *cur = value;
6773 
6774     if (value == NULL)
6775         return;
6776 
6777     while (IS_BLANK_CH(*cur))
6778         cur++;
6779     if (cur == start) {
6780         do {
6781             while ((*cur != 0) && (!IS_BLANK_CH(*cur)))
6782                 cur++;
6783             if (*cur == 0)
6784                 return;
6785             start = cur;
6786             while (IS_BLANK_CH(*cur))
6787                 cur++;
6788             if (*cur == 0) {
6789                 *start = 0;
6790                 return;
6791             }
6792         } while (1);
6793     } else {
6794         do {
6795             while ((*cur != 0) && (!IS_BLANK_CH(*cur)))
6796                 *start++ = *cur++;
6797             if (*cur == 0) {
6798                 *start = 0;
6799                 return;
6800             }
6801             /* don't try to normalize the inner spaces */
6802             while (IS_BLANK_CH(*cur))
6803                 cur++;
6804             if (*cur == 0) {
6805                 *start = 0;
6806                 return;
6807             }
6808             *start++ = *cur++;
6809         } while (1);
6810     }
6811 }
6812 
6813 /**
6814  * xmlRelaxNGCleanupAttributes:
6815  * @ctxt:  a Relax-NG parser context
6816  * @node:  a Relax-NG node
6817  *
6818  * Check all the attributes on the given node
6819  */
6820 static void
xmlRelaxNGCleanupAttributes(xmlRelaxNGParserCtxtPtr ctxt,xmlNodePtr node)6821 xmlRelaxNGCleanupAttributes(xmlRelaxNGParserCtxtPtr ctxt, xmlNodePtr node)
6822 {
6823     xmlAttrPtr cur, next;
6824 
6825     cur = node->properties;
6826     while (cur != NULL) {
6827         next = cur->next;
6828         if ((cur->ns == NULL) ||
6829             (xmlStrEqual(cur->ns->href, xmlRelaxNGNs))) {
6830             if (xmlStrEqual(cur->name, BAD_CAST "name")) {
6831                 if ((!xmlStrEqual(node->name, BAD_CAST "element")) &&
6832                     (!xmlStrEqual(node->name, BAD_CAST "attribute")) &&
6833                     (!xmlStrEqual(node->name, BAD_CAST "ref")) &&
6834                     (!xmlStrEqual(node->name, BAD_CAST "parentRef")) &&
6835                     (!xmlStrEqual(node->name, BAD_CAST "param")) &&
6836                     (!xmlStrEqual(node->name, BAD_CAST "define"))) {
6837                     xmlRngPErr(ctxt, node, XML_RNGP_FORBIDDEN_ATTRIBUTE,
6838                                "Attribute %s is not allowed on %s\n",
6839                                cur->name, node->name);
6840                 }
6841             } else if (xmlStrEqual(cur->name, BAD_CAST "type")) {
6842                 if ((!xmlStrEqual(node->name, BAD_CAST "value")) &&
6843                     (!xmlStrEqual(node->name, BAD_CAST "data"))) {
6844                     xmlRngPErr(ctxt, node, XML_RNGP_FORBIDDEN_ATTRIBUTE,
6845                                "Attribute %s is not allowed on %s\n",
6846                                cur->name, node->name);
6847                 }
6848             } else if (xmlStrEqual(cur->name, BAD_CAST "href")) {
6849                 if ((!xmlStrEqual(node->name, BAD_CAST "externalRef")) &&
6850                     (!xmlStrEqual(node->name, BAD_CAST "include"))) {
6851                     xmlRngPErr(ctxt, node, XML_RNGP_FORBIDDEN_ATTRIBUTE,
6852                                "Attribute %s is not allowed on %s\n",
6853                                cur->name, node->name);
6854                 }
6855             } else if (xmlStrEqual(cur->name, BAD_CAST "combine")) {
6856                 if ((!xmlStrEqual(node->name, BAD_CAST "start")) &&
6857                     (!xmlStrEqual(node->name, BAD_CAST "define"))) {
6858                     xmlRngPErr(ctxt, node, XML_RNGP_FORBIDDEN_ATTRIBUTE,
6859                                "Attribute %s is not allowed on %s\n",
6860                                cur->name, node->name);
6861                 }
6862             } else if (xmlStrEqual(cur->name, BAD_CAST "datatypeLibrary")) {
6863                 xmlChar *val;
6864                 xmlURIPtr uri;
6865 
6866                 val = xmlNodeListGetString(node->doc, cur->children, 1);
6867                 if (val != NULL) {
6868                     if (val[0] != 0) {
6869                         uri = xmlParseURI((const char *) val);
6870                         if (uri == NULL) {
6871                             xmlRngPErr(ctxt, node, XML_RNGP_INVALID_URI,
6872                                        "Attribute %s contains invalid URI %s\n",
6873                                        cur->name, val);
6874                         } else {
6875                             if (uri->scheme == NULL) {
6876                                 xmlRngPErr(ctxt, node, XML_RNGP_URI_NOT_ABSOLUTE,
6877                                            "Attribute %s URI %s is not absolute\n",
6878                                            cur->name, val);
6879                             }
6880                             if (uri->fragment != NULL) {
6881                                 xmlRngPErr(ctxt, node, XML_RNGP_URI_FRAGMENT,
6882                                            "Attribute %s URI %s has a fragment ID\n",
6883                                            cur->name, val);
6884                             }
6885                             xmlFreeURI(uri);
6886                         }
6887                     }
6888                     xmlFree(val);
6889                 }
6890             } else if (!xmlStrEqual(cur->name, BAD_CAST "ns")) {
6891                 xmlRngPErr(ctxt, node, XML_RNGP_UNKNOWN_ATTRIBUTE,
6892                            "Unknown attribute %s on %s\n", cur->name,
6893                            node->name);
6894             }
6895         }
6896         cur = next;
6897     }
6898 }
6899 
6900 /**
6901  * xmlRelaxNGCleanupTree:
6902  * @ctxt:  a Relax-NG parser context
6903  * @root:  an xmlNodePtr subtree
6904  *
6905  * Cleanup the subtree from unwanted nodes for parsing, resolve
6906  * Include and externalRef lookups.
6907  */
6908 static void
xmlRelaxNGCleanupTree(xmlRelaxNGParserCtxtPtr ctxt,xmlNodePtr root)6909 xmlRelaxNGCleanupTree(xmlRelaxNGParserCtxtPtr ctxt, xmlNodePtr root)
6910 {
6911     xmlNodePtr cur, delete;
6912 
6913     delete = NULL;
6914     cur = root;
6915     while (cur != NULL) {
6916         if (delete != NULL) {
6917             xmlUnlinkNode(delete);
6918             xmlFreeNode(delete);
6919             delete = NULL;
6920         }
6921         if (cur->type == XML_ELEMENT_NODE) {
6922             /*
6923              * Simplification 4.1. Annotations
6924              */
6925             if ((cur->ns == NULL) ||
6926                 (!xmlStrEqual(cur->ns->href, xmlRelaxNGNs))) {
6927                 if ((cur->parent != NULL) &&
6928                     (cur->parent->type == XML_ELEMENT_NODE) &&
6929                     ((xmlStrEqual(cur->parent->name, BAD_CAST "name")) ||
6930                      (xmlStrEqual(cur->parent->name, BAD_CAST "value")) ||
6931                      (xmlStrEqual(cur->parent->name, BAD_CAST "param")))) {
6932                     xmlRngPErr(ctxt, cur, XML_RNGP_FOREIGN_ELEMENT,
6933                                "element %s doesn't allow foreign elements\n",
6934                                cur->parent->name, NULL);
6935                 }
6936                 delete = cur;
6937                 goto skip_children;
6938             } else {
6939                 xmlRelaxNGCleanupAttributes(ctxt, cur);
6940                 if (xmlStrEqual(cur->name, BAD_CAST "externalRef")) {
6941                     xmlChar *href, *ns, *base, *URL;
6942                     xmlRelaxNGDocumentPtr docu;
6943                     xmlNodePtr tmp;
6944 		    xmlURIPtr uri;
6945 
6946                     ns = xmlGetProp(cur, BAD_CAST "ns");
6947                     if (ns == NULL) {
6948                         tmp = cur->parent;
6949                         while ((tmp != NULL) &&
6950                                (tmp->type == XML_ELEMENT_NODE)) {
6951                             ns = xmlGetProp(tmp, BAD_CAST "ns");
6952                             if (ns != NULL)
6953                                 break;
6954                             tmp = tmp->parent;
6955                         }
6956                     }
6957                     href = xmlGetProp(cur, BAD_CAST "href");
6958                     if (href == NULL) {
6959                         xmlRngPErr(ctxt, cur, XML_RNGP_MISSING_HREF,
6960                                    "xmlRelaxNGParse: externalRef has no href attribute\n",
6961                                    NULL, NULL);
6962                         if (ns != NULL)
6963                             xmlFree(ns);
6964                         delete = cur;
6965                         goto skip_children;
6966                     }
6967 		    uri = xmlParseURI((const char *) href);
6968 		    if (uri == NULL) {
6969                         xmlRngPErr(ctxt, cur, XML_RNGP_HREF_ERROR,
6970                                    "Incorrect URI for externalRef %s\n",
6971                                    href, NULL);
6972                         if (ns != NULL)
6973                             xmlFree(ns);
6974                         if (href != NULL)
6975                             xmlFree(href);
6976                         delete = cur;
6977                         goto skip_children;
6978 		    }
6979 		    if (uri->fragment != NULL) {
6980                         xmlRngPErr(ctxt, cur, XML_RNGP_HREF_ERROR,
6981 			       "Fragment forbidden in URI for externalRef %s\n",
6982                                    href, NULL);
6983                         if (ns != NULL)
6984                             xmlFree(ns);
6985 		        xmlFreeURI(uri);
6986                         if (href != NULL)
6987                             xmlFree(href);
6988                         delete = cur;
6989                         goto skip_children;
6990 		    }
6991 		    xmlFreeURI(uri);
6992                     base = xmlNodeGetBase(cur->doc, cur);
6993                     URL = xmlBuildURI(href, base);
6994                     if (URL == NULL) {
6995                         xmlRngPErr(ctxt, cur, XML_RNGP_HREF_ERROR,
6996                                    "Failed to compute URL for externalRef %s\n",
6997                                    href, NULL);
6998                         if (ns != NULL)
6999                             xmlFree(ns);
7000                         if (href != NULL)
7001                             xmlFree(href);
7002                         if (base != NULL)
7003                             xmlFree(base);
7004                         delete = cur;
7005                         goto skip_children;
7006                     }
7007                     if (href != NULL)
7008                         xmlFree(href);
7009                     if (base != NULL)
7010                         xmlFree(base);
7011                     docu = xmlRelaxNGLoadExternalRef(ctxt, URL, ns);
7012                     if (docu == NULL) {
7013                         xmlRngPErr(ctxt, cur, XML_RNGP_EXTERNAL_REF_FAILURE,
7014                                    "Failed to load externalRef %s\n", URL,
7015                                    NULL);
7016                         if (ns != NULL)
7017                             xmlFree(ns);
7018                         xmlFree(URL);
7019                         delete = cur;
7020                         goto skip_children;
7021                     }
7022                     if (ns != NULL)
7023                         xmlFree(ns);
7024                     xmlFree(URL);
7025                     cur->psvi = docu;
7026                 } else if (xmlStrEqual(cur->name, BAD_CAST "include")) {
7027                     xmlChar *href, *ns, *base, *URL;
7028                     xmlRelaxNGIncludePtr incl;
7029                     xmlNodePtr tmp;
7030 
7031                     href = xmlGetProp(cur, BAD_CAST "href");
7032                     if (href == NULL) {
7033                         xmlRngPErr(ctxt, cur, XML_RNGP_MISSING_HREF,
7034                                    "xmlRelaxNGParse: include has no href attribute\n",
7035                                    NULL, NULL);
7036                         delete = cur;
7037                         goto skip_children;
7038                     }
7039                     base = xmlNodeGetBase(cur->doc, cur);
7040                     URL = xmlBuildURI(href, base);
7041                     if (URL == NULL) {
7042                         xmlRngPErr(ctxt, cur, XML_RNGP_HREF_ERROR,
7043                                    "Failed to compute URL for include %s\n",
7044                                    href, NULL);
7045                         if (href != NULL)
7046                             xmlFree(href);
7047                         if (base != NULL)
7048                             xmlFree(base);
7049                         delete = cur;
7050                         goto skip_children;
7051                     }
7052                     if (href != NULL)
7053                         xmlFree(href);
7054                     if (base != NULL)
7055                         xmlFree(base);
7056                     ns = xmlGetProp(cur, BAD_CAST "ns");
7057                     if (ns == NULL) {
7058                         tmp = cur->parent;
7059                         while ((tmp != NULL) &&
7060                                (tmp->type == XML_ELEMENT_NODE)) {
7061                             ns = xmlGetProp(tmp, BAD_CAST "ns");
7062                             if (ns != NULL)
7063                                 break;
7064                             tmp = tmp->parent;
7065                         }
7066                     }
7067                     incl = xmlRelaxNGLoadInclude(ctxt, URL, cur, ns);
7068                     if (ns != NULL)
7069                         xmlFree(ns);
7070                     if (incl == NULL) {
7071                         xmlRngPErr(ctxt, cur, XML_RNGP_INCLUDE_FAILURE,
7072                                    "Failed to load include %s\n", URL,
7073                                    NULL);
7074                         xmlFree(URL);
7075                         delete = cur;
7076                         goto skip_children;
7077                     }
7078                     xmlFree(URL);
7079                     cur->psvi = incl;
7080                 } else if ((xmlStrEqual(cur->name, BAD_CAST "element")) ||
7081                            (xmlStrEqual(cur->name, BAD_CAST "attribute")))
7082                 {
7083                     xmlChar *name, *ns;
7084                     xmlNodePtr text = NULL;
7085 
7086                     /*
7087                      * Simplification 4.8. name attribute of element
7088                      * and attribute elements
7089                      */
7090                     name = xmlGetProp(cur, BAD_CAST "name");
7091                     if (name != NULL) {
7092                         if (cur->children == NULL) {
7093                             text =
7094                                 xmlNewChild(cur, cur->ns, BAD_CAST "name",
7095                                             name);
7096                         } else {
7097                             xmlNodePtr node;
7098 
7099                             node = xmlNewDocNode(cur->doc, cur->ns,
7100 			                         BAD_CAST "name", NULL);
7101                             if (node != NULL) {
7102                                 xmlAddPrevSibling(cur->children, node);
7103                                 text = xmlNewDocText(node->doc, name);
7104                                 xmlAddChild(node, text);
7105                                 text = node;
7106                             }
7107                         }
7108                         if (text == NULL) {
7109                             xmlRngPErr(ctxt, cur, XML_RNGP_CREATE_FAILURE,
7110                                        "Failed to create a name %s element\n",
7111                                        name, NULL);
7112                         }
7113                         xmlUnsetProp(cur, BAD_CAST "name");
7114                         xmlFree(name);
7115                         ns = xmlGetProp(cur, BAD_CAST "ns");
7116                         if (ns != NULL) {
7117                             if (text != NULL) {
7118                                 xmlSetProp(text, BAD_CAST "ns", ns);
7119                                 /* xmlUnsetProp(cur, BAD_CAST "ns"); */
7120                             }
7121                             xmlFree(ns);
7122                         } else if (xmlStrEqual(cur->name,
7123                                                BAD_CAST "attribute")) {
7124                             xmlSetProp(text, BAD_CAST "ns", BAD_CAST "");
7125                         }
7126                     }
7127                 } else if ((xmlStrEqual(cur->name, BAD_CAST "name")) ||
7128                            (xmlStrEqual(cur->name, BAD_CAST "nsName")) ||
7129                            (xmlStrEqual(cur->name, BAD_CAST "value"))) {
7130                     /*
7131                      * Simplification 4.8. name attribute of element
7132                      * and attribute elements
7133                      */
7134                     if (xmlHasProp(cur, BAD_CAST "ns") == NULL) {
7135                         xmlNodePtr node;
7136                         xmlChar *ns = NULL;
7137 
7138                         node = cur->parent;
7139                         while ((node != NULL) &&
7140                                (node->type == XML_ELEMENT_NODE)) {
7141                             ns = xmlGetProp(node, BAD_CAST "ns");
7142                             if (ns != NULL) {
7143                                 break;
7144                             }
7145                             node = node->parent;
7146                         }
7147                         if (ns == NULL) {
7148                             xmlSetProp(cur, BAD_CAST "ns", BAD_CAST "");
7149                         } else {
7150                             xmlSetProp(cur, BAD_CAST "ns", ns);
7151                             xmlFree(ns);
7152                         }
7153                     }
7154                     if (xmlStrEqual(cur->name, BAD_CAST "name")) {
7155                         xmlChar *name, *local, *prefix;
7156 
7157                         /*
7158                          * Simplification: 4.10. QNames
7159                          */
7160                         name = xmlNodeGetContent(cur);
7161                         if (name != NULL) {
7162                             local = xmlSplitQName2(name, &prefix);
7163                             if (local != NULL) {
7164                                 xmlNsPtr ns;
7165 
7166                                 ns = xmlSearchNs(cur->doc, cur, prefix);
7167                                 if (ns == NULL) {
7168                                     xmlRngPErr(ctxt, cur,
7169                                                XML_RNGP_PREFIX_UNDEFINED,
7170                                                "xmlRelaxNGParse: no namespace for prefix %s\n",
7171                                                prefix, NULL);
7172                                 } else {
7173                                     xmlSetProp(cur, BAD_CAST "ns",
7174                                                ns->href);
7175                                     xmlNodeSetContent(cur, local);
7176                                 }
7177                                 xmlFree(local);
7178                                 xmlFree(prefix);
7179                             }
7180                             xmlFree(name);
7181                         }
7182                     }
7183                     /*
7184                      * 4.16
7185                      */
7186                     if (xmlStrEqual(cur->name, BAD_CAST "nsName")) {
7187                         if (ctxt->flags & XML_RELAXNG_IN_NSEXCEPT) {
7188                             xmlRngPErr(ctxt, cur,
7189                                        XML_RNGP_PAT_NSNAME_EXCEPT_NSNAME,
7190                                        "Found nsName/except//nsName forbidden construct\n",
7191                                        NULL, NULL);
7192                         }
7193                     }
7194                 } else if ((xmlStrEqual(cur->name, BAD_CAST "except")) &&
7195                            (cur != root)) {
7196                     int oldflags = ctxt->flags;
7197 
7198                     /*
7199                      * 4.16
7200                      */
7201                     if ((cur->parent != NULL) &&
7202                         (xmlStrEqual
7203                          (cur->parent->name, BAD_CAST "anyName"))) {
7204                         ctxt->flags |= XML_RELAXNG_IN_ANYEXCEPT;
7205                         xmlRelaxNGCleanupTree(ctxt, cur);
7206                         ctxt->flags = oldflags;
7207                         goto skip_children;
7208                     } else if ((cur->parent != NULL) &&
7209                                (xmlStrEqual
7210                                 (cur->parent->name, BAD_CAST "nsName"))) {
7211                         ctxt->flags |= XML_RELAXNG_IN_NSEXCEPT;
7212                         xmlRelaxNGCleanupTree(ctxt, cur);
7213                         ctxt->flags = oldflags;
7214                         goto skip_children;
7215                     }
7216                 } else if (xmlStrEqual(cur->name, BAD_CAST "anyName")) {
7217                     /*
7218                      * 4.16
7219                      */
7220                     if (ctxt->flags & XML_RELAXNG_IN_ANYEXCEPT) {
7221                         xmlRngPErr(ctxt, cur,
7222                                    XML_RNGP_PAT_ANYNAME_EXCEPT_ANYNAME,
7223                                    "Found anyName/except//anyName forbidden construct\n",
7224                                    NULL, NULL);
7225                     } else if (ctxt->flags & XML_RELAXNG_IN_NSEXCEPT) {
7226                         xmlRngPErr(ctxt, cur,
7227                                    XML_RNGP_PAT_NSNAME_EXCEPT_ANYNAME,
7228                                    "Found nsName/except//anyName forbidden construct\n",
7229                                    NULL, NULL);
7230                     }
7231                 }
7232                 /*
7233                  * This is not an else since "include" is transformed
7234                  * into a div
7235                  */
7236                 if (xmlStrEqual(cur->name, BAD_CAST "div")) {
7237                     xmlChar *ns;
7238                     xmlNodePtr child, ins, tmp;
7239 
7240                     /*
7241                      * implements rule 4.11
7242                      */
7243 
7244                     ns = xmlGetProp(cur, BAD_CAST "ns");
7245 
7246                     child = cur->children;
7247                     ins = cur;
7248                     while (child != NULL) {
7249                         if (ns != NULL) {
7250                             if (!xmlHasProp(child, BAD_CAST "ns")) {
7251                                 xmlSetProp(child, BAD_CAST "ns", ns);
7252                             }
7253                         }
7254                         tmp = child->next;
7255                         xmlUnlinkNode(child);
7256                         ins = xmlAddNextSibling(ins, child);
7257                         child = tmp;
7258                     }
7259                     if (ns != NULL)
7260                         xmlFree(ns);
7261 		    /*
7262 		     * Since we are about to delete cur, if its nsDef is non-NULL we
7263 		     * need to preserve it (it contains the ns definitions for the
7264 		     * children we just moved).  We'll just stick it on to the end
7265 		     * of cur->parent's list, since it's never going to be re-serialized
7266 		     * (bug 143738).
7267 		     */
7268 		    if ((cur->nsDef != NULL) && (cur->parent != NULL)) {
7269 			xmlNsPtr parDef = (xmlNsPtr)&cur->parent->nsDef;
7270 			while (parDef->next != NULL)
7271 			    parDef = parDef->next;
7272 			parDef->next = cur->nsDef;
7273 			cur->nsDef = NULL;
7274 		    }
7275                     delete = cur;
7276                     goto skip_children;
7277                 }
7278             }
7279         }
7280         /*
7281          * Simplification 4.2 whitespaces
7282          */
7283         else if ((cur->type == XML_TEXT_NODE) ||
7284                  (cur->type == XML_CDATA_SECTION_NODE)) {
7285             if (IS_BLANK_NODE(cur)) {
7286                 if ((cur->parent != NULL) &&
7287 		    (cur->parent->type == XML_ELEMENT_NODE)) {
7288                     if ((!xmlStrEqual(cur->parent->name, BAD_CAST "value"))
7289                         &&
7290                         (!xmlStrEqual
7291                          (cur->parent->name, BAD_CAST "param")))
7292                         delete = cur;
7293                 } else {
7294                     delete = cur;
7295                     goto skip_children;
7296                 }
7297             }
7298         } else {
7299             delete = cur;
7300             goto skip_children;
7301         }
7302 
7303         /*
7304          * Skip to next node
7305          */
7306         if (cur->children != NULL) {
7307             if ((cur->children->type != XML_ENTITY_DECL) &&
7308                 (cur->children->type != XML_ENTITY_REF_NODE) &&
7309                 (cur->children->type != XML_ENTITY_NODE)) {
7310                 cur = cur->children;
7311                 continue;
7312             }
7313         }
7314       skip_children:
7315         if (cur->next != NULL) {
7316             cur = cur->next;
7317             continue;
7318         }
7319 
7320         do {
7321             cur = cur->parent;
7322             if (cur == NULL)
7323                 break;
7324             if (cur == root) {
7325                 cur = NULL;
7326                 break;
7327             }
7328             if (cur->next != NULL) {
7329                 cur = cur->next;
7330                 break;
7331             }
7332         } while (cur != NULL);
7333     }
7334     if (delete != NULL) {
7335         xmlUnlinkNode(delete);
7336         xmlFreeNode(delete);
7337         delete = NULL;
7338     }
7339 }
7340 
7341 /**
7342  * xmlRelaxNGCleanupDoc:
7343  * @ctxt:  a Relax-NG parser context
7344  * @doc:  an xmldocPtr document pointer
7345  *
7346  * Cleanup the document from unwanted nodes for parsing, resolve
7347  * Include and externalRef lookups.
7348  *
7349  * Returns the cleaned up document or NULL in case of error
7350  */
7351 static xmlDocPtr
xmlRelaxNGCleanupDoc(xmlRelaxNGParserCtxtPtr ctxt,xmlDocPtr doc)7352 xmlRelaxNGCleanupDoc(xmlRelaxNGParserCtxtPtr ctxt, xmlDocPtr doc)
7353 {
7354     xmlNodePtr root;
7355 
7356     /*
7357      * Extract the root
7358      */
7359     root = xmlDocGetRootElement(doc);
7360     if (root == NULL) {
7361         xmlRngPErr(ctxt, (xmlNodePtr) doc, XML_RNGP_EMPTY, "xmlRelaxNGParse: %s is empty\n",
7362                    ctxt->URL, NULL);
7363         return (NULL);
7364     }
7365     xmlRelaxNGCleanupTree(ctxt, root);
7366     return (doc);
7367 }
7368 
7369 /**
7370  * xmlRelaxNGParse:
7371  * @ctxt:  a Relax-NG parser context
7372  *
7373  * parse a schema definition resource and build an internal
7374  * XML Schema structure which can be used to validate instances.
7375  *
7376  * Returns the internal XML RelaxNG structure built from the resource or
7377  *         NULL in case of error
7378  */
7379 xmlRelaxNGPtr
xmlRelaxNGParse(xmlRelaxNGParserCtxtPtr ctxt)7380 xmlRelaxNGParse(xmlRelaxNGParserCtxtPtr ctxt)
7381 {
7382     xmlRelaxNGPtr ret = NULL;
7383     xmlDocPtr doc;
7384     xmlNodePtr root;
7385 
7386     xmlRelaxNGInitTypes();
7387 
7388     if (ctxt == NULL)
7389         return (NULL);
7390 
7391     /*
7392      * First step is to parse the input document into an DOM/Infoset
7393      */
7394     if (ctxt->URL != NULL) {
7395         doc = xmlRelaxReadFile(ctxt, (const char *) ctxt->URL);
7396         if (doc == NULL) {
7397             xmlRngPErr(ctxt, NULL, XML_RNGP_PARSE_ERROR,
7398                        "xmlRelaxNGParse: could not load %s\n", ctxt->URL,
7399                        NULL);
7400             return (NULL);
7401         }
7402     } else if (ctxt->buffer != NULL) {
7403         doc = xmlRelaxReadMemory(ctxt, ctxt->buffer, ctxt->size);
7404         if (doc == NULL) {
7405             xmlRngPErr(ctxt, NULL, XML_RNGP_PARSE_ERROR,
7406                        "xmlRelaxNGParse: could not parse schemas\n", NULL,
7407                        NULL);
7408             return (NULL);
7409         }
7410         doc->URL = xmlStrdup(BAD_CAST "in_memory_buffer");
7411         ctxt->URL = xmlStrdup(BAD_CAST "in_memory_buffer");
7412     } else if (ctxt->document != NULL) {
7413         doc = ctxt->document;
7414     } else {
7415         xmlRngPErr(ctxt, NULL, XML_RNGP_EMPTY,
7416                    "xmlRelaxNGParse: nothing to parse\n", NULL, NULL);
7417         return (NULL);
7418     }
7419     ctxt->document = doc;
7420 
7421     /*
7422      * Some preprocessing of the document content
7423      */
7424     doc = xmlRelaxNGCleanupDoc(ctxt, doc);
7425     if (doc == NULL) {
7426         xmlFreeDoc(ctxt->document);
7427         ctxt->document = NULL;
7428         return (NULL);
7429     }
7430 
7431     /*
7432      * Then do the parsing for good
7433      */
7434     root = xmlDocGetRootElement(doc);
7435     if (root == NULL) {
7436         xmlRngPErr(ctxt, (xmlNodePtr) doc,
7437 	           XML_RNGP_EMPTY, "xmlRelaxNGParse: %s is empty\n",
7438                    (ctxt->URL ? ctxt->URL : BAD_CAST "schemas"), NULL);
7439 
7440         xmlFreeDoc(ctxt->document);
7441         ctxt->document = NULL;
7442         return (NULL);
7443     }
7444     ret = xmlRelaxNGParseDocument(ctxt, root);
7445     if (ret == NULL) {
7446         xmlFreeDoc(ctxt->document);
7447         ctxt->document = NULL;
7448         return (NULL);
7449     }
7450 
7451     /*
7452      * Check the ref/defines links
7453      */
7454     /*
7455      * try to preprocess interleaves
7456      */
7457     if (ctxt->interleaves != NULL) {
7458         xmlHashScan(ctxt->interleaves, xmlRelaxNGComputeInterleaves, ctxt);
7459     }
7460 
7461     /*
7462      * if there was a parsing error return NULL
7463      */
7464     if (ctxt->nbErrors > 0) {
7465         xmlRelaxNGFree(ret);
7466         ctxt->document = NULL;
7467         xmlFreeDoc(doc);
7468         return (NULL);
7469     }
7470 
7471     /*
7472      * try to compile (parts of) the schemas
7473      */
7474     if ((ret->topgrammar != NULL) && (ret->topgrammar->start != NULL)) {
7475         if (ret->topgrammar->start->type != XML_RELAXNG_START) {
7476             xmlRelaxNGDefinePtr def;
7477 
7478             def = xmlRelaxNGNewDefine(ctxt, NULL);
7479             if (def != NULL) {
7480                 def->type = XML_RELAXNG_START;
7481                 def->content = ret->topgrammar->start;
7482                 ret->topgrammar->start = def;
7483             }
7484         }
7485         xmlRelaxNGTryCompile(ctxt, ret->topgrammar->start);
7486     }
7487 
7488     /*
7489      * Transfer the pointer for cleanup at the schema level.
7490      */
7491     ret->doc = doc;
7492     ctxt->document = NULL;
7493     ret->documents = ctxt->documents;
7494     ctxt->documents = NULL;
7495 
7496     ret->includes = ctxt->includes;
7497     ctxt->includes = NULL;
7498     ret->defNr = ctxt->defNr;
7499     ret->defTab = ctxt->defTab;
7500     ctxt->defTab = NULL;
7501     if (ctxt->idref == 1)
7502         ret->idref = 1;
7503 
7504     return (ret);
7505 }
7506 
7507 /**
7508  * xmlRelaxNGSetParserErrors:
7509  * @ctxt:  a Relax-NG validation context
7510  * @err:  the error callback
7511  * @warn:  the warning callback
7512  * @ctx:  contextual data for the callbacks
7513  *
7514  * DEPRECATED: Use xmlRelaxNGSetParserStructuredErrors.
7515  *
7516  * Set the callback functions used to handle errors for a validation context
7517  */
7518 void
xmlRelaxNGSetParserErrors(xmlRelaxNGParserCtxtPtr ctxt,xmlRelaxNGValidityErrorFunc err,xmlRelaxNGValidityWarningFunc warn,void * ctx)7519 xmlRelaxNGSetParserErrors(xmlRelaxNGParserCtxtPtr ctxt,
7520                           xmlRelaxNGValidityErrorFunc err,
7521                           xmlRelaxNGValidityWarningFunc warn, void *ctx)
7522 {
7523     if (ctxt == NULL)
7524         return;
7525     ctxt->error = err;
7526     ctxt->warning = warn;
7527     ctxt->serror = NULL;
7528     ctxt->userData = ctx;
7529 }
7530 
7531 /**
7532  * xmlRelaxNGGetParserErrors:
7533  * @ctxt:  a Relax-NG validation context
7534  * @err:  the error callback result
7535  * @warn:  the warning callback result
7536  * @ctx:  contextual data for the callbacks result
7537  *
7538  * Get the callback information used to handle errors for a validation context
7539  *
7540  * Returns -1 in case of failure, 0 otherwise.
7541  */
7542 int
xmlRelaxNGGetParserErrors(xmlRelaxNGParserCtxtPtr ctxt,xmlRelaxNGValidityErrorFunc * err,xmlRelaxNGValidityWarningFunc * warn,void ** ctx)7543 xmlRelaxNGGetParserErrors(xmlRelaxNGParserCtxtPtr ctxt,
7544                           xmlRelaxNGValidityErrorFunc * err,
7545                           xmlRelaxNGValidityWarningFunc * warn, void **ctx)
7546 {
7547     if (ctxt == NULL)
7548         return (-1);
7549     if (err != NULL)
7550         *err = ctxt->error;
7551     if (warn != NULL)
7552         *warn = ctxt->warning;
7553     if (ctx != NULL)
7554         *ctx = ctxt->userData;
7555     return (0);
7556 }
7557 
7558 /**
7559  * xmlRelaxNGSetParserStructuredErrors:
7560  * @ctxt:  a Relax-NG parser context
7561  * @serror:  the error callback
7562  * @ctx:  contextual data for the callbacks
7563  *
7564  * Set the callback functions used to handle errors for a parsing context
7565  */
7566 void
xmlRelaxNGSetParserStructuredErrors(xmlRelaxNGParserCtxtPtr ctxt,xmlStructuredErrorFunc serror,void * ctx)7567 xmlRelaxNGSetParserStructuredErrors(xmlRelaxNGParserCtxtPtr ctxt,
7568 				    xmlStructuredErrorFunc serror,
7569 				    void *ctx)
7570 {
7571     if (ctxt == NULL)
7572         return;
7573     ctxt->serror = serror;
7574     ctxt->error = NULL;
7575     ctxt->warning = NULL;
7576     ctxt->userData = ctx;
7577 }
7578 
7579 /**
7580  * xmlRelaxNGSetResourceLoader:
7581  * @ctxt:  a Relax-NG parser context
7582  * @loader:  the callback
7583  * @vctxt:  contextual data for the callbacks
7584  *
7585  * Set the callback function used to load external resources.
7586  */
7587 void
xmlRelaxNGSetResourceLoader(xmlRelaxNGParserCtxtPtr ctxt,xmlResourceLoader loader,void * vctxt)7588 xmlRelaxNGSetResourceLoader(xmlRelaxNGParserCtxtPtr ctxt,
7589                             xmlResourceLoader loader, void *vctxt) {
7590     if (ctxt == NULL)
7591         return;
7592     ctxt->resourceLoader = loader;
7593     ctxt->resourceCtxt = vctxt;
7594 }
7595 
7596 #ifdef LIBXML_OUTPUT_ENABLED
7597 
7598 /************************************************************************
7599  *									*
7600  *			Dump back a compiled form			*
7601  *									*
7602  ************************************************************************/
7603 static void xmlRelaxNGDumpDefine(FILE * output,
7604                                  xmlRelaxNGDefinePtr define);
7605 
7606 /**
7607  * xmlRelaxNGDumpDefines:
7608  * @output:  the file output
7609  * @defines:  a list of define structures
7610  *
7611  * Dump a RelaxNG structure back
7612  */
7613 static void
xmlRelaxNGDumpDefines(FILE * output,xmlRelaxNGDefinePtr defines)7614 xmlRelaxNGDumpDefines(FILE * output, xmlRelaxNGDefinePtr defines)
7615 {
7616     while (defines != NULL) {
7617         xmlRelaxNGDumpDefine(output, defines);
7618         defines = defines->next;
7619     }
7620 }
7621 
7622 /**
7623  * xmlRelaxNGDumpDefine:
7624  * @output:  the file output
7625  * @define:  a define structure
7626  *
7627  * Dump a RelaxNG structure back
7628  */
7629 static void
xmlRelaxNGDumpDefine(FILE * output,xmlRelaxNGDefinePtr define)7630 xmlRelaxNGDumpDefine(FILE * output, xmlRelaxNGDefinePtr define)
7631 {
7632     if (define == NULL)
7633         return;
7634     switch (define->type) {
7635         case XML_RELAXNG_EMPTY:
7636             fprintf(output, "<empty/>\n");
7637             break;
7638         case XML_RELAXNG_NOT_ALLOWED:
7639             fprintf(output, "<notAllowed/>\n");
7640             break;
7641         case XML_RELAXNG_TEXT:
7642             fprintf(output, "<text/>\n");
7643             break;
7644         case XML_RELAXNG_ELEMENT:
7645             fprintf(output, "<element>\n");
7646             if (define->name != NULL) {
7647                 fprintf(output, "<name");
7648                 if (define->ns != NULL)
7649                     fprintf(output, " ns=\"%s\"", define->ns);
7650                 fprintf(output, ">%s</name>\n", define->name);
7651             }
7652             xmlRelaxNGDumpDefines(output, define->attrs);
7653             xmlRelaxNGDumpDefines(output, define->content);
7654             fprintf(output, "</element>\n");
7655             break;
7656         case XML_RELAXNG_LIST:
7657             fprintf(output, "<list>\n");
7658             xmlRelaxNGDumpDefines(output, define->content);
7659             fprintf(output, "</list>\n");
7660             break;
7661         case XML_RELAXNG_ONEORMORE:
7662             fprintf(output, "<oneOrMore>\n");
7663             xmlRelaxNGDumpDefines(output, define->content);
7664             fprintf(output, "</oneOrMore>\n");
7665             break;
7666         case XML_RELAXNG_ZEROORMORE:
7667             fprintf(output, "<zeroOrMore>\n");
7668             xmlRelaxNGDumpDefines(output, define->content);
7669             fprintf(output, "</zeroOrMore>\n");
7670             break;
7671         case XML_RELAXNG_CHOICE:
7672             fprintf(output, "<choice>\n");
7673             xmlRelaxNGDumpDefines(output, define->content);
7674             fprintf(output, "</choice>\n");
7675             break;
7676         case XML_RELAXNG_GROUP:
7677             fprintf(output, "<group>\n");
7678             xmlRelaxNGDumpDefines(output, define->content);
7679             fprintf(output, "</group>\n");
7680             break;
7681         case XML_RELAXNG_INTERLEAVE:
7682             fprintf(output, "<interleave>\n");
7683             xmlRelaxNGDumpDefines(output, define->content);
7684             fprintf(output, "</interleave>\n");
7685             break;
7686         case XML_RELAXNG_OPTIONAL:
7687             fprintf(output, "<optional>\n");
7688             xmlRelaxNGDumpDefines(output, define->content);
7689             fprintf(output, "</optional>\n");
7690             break;
7691         case XML_RELAXNG_ATTRIBUTE:
7692             fprintf(output, "<attribute>\n");
7693             xmlRelaxNGDumpDefines(output, define->content);
7694             fprintf(output, "</attribute>\n");
7695             break;
7696         case XML_RELAXNG_DEF:
7697             fprintf(output, "<define");
7698             if (define->name != NULL)
7699                 fprintf(output, " name=\"%s\"", define->name);
7700             fprintf(output, ">\n");
7701             xmlRelaxNGDumpDefines(output, define->content);
7702             fprintf(output, "</define>\n");
7703             break;
7704         case XML_RELAXNG_REF:
7705             fprintf(output, "<ref");
7706             if (define->name != NULL)
7707                 fprintf(output, " name=\"%s\"", define->name);
7708             fprintf(output, ">\n");
7709             xmlRelaxNGDumpDefines(output, define->content);
7710             fprintf(output, "</ref>\n");
7711             break;
7712         case XML_RELAXNG_PARENTREF:
7713             fprintf(output, "<parentRef");
7714             if (define->name != NULL)
7715                 fprintf(output, " name=\"%s\"", define->name);
7716             fprintf(output, ">\n");
7717             xmlRelaxNGDumpDefines(output, define->content);
7718             fprintf(output, "</parentRef>\n");
7719             break;
7720         case XML_RELAXNG_EXTERNALREF:
7721             fprintf(output, "<externalRef>");
7722             xmlRelaxNGDumpDefines(output, define->content);
7723             fprintf(output, "</externalRef>\n");
7724             break;
7725         case XML_RELAXNG_DATATYPE:
7726         case XML_RELAXNG_VALUE:
7727             /* TODO */
7728             break;
7729         case XML_RELAXNG_START:
7730         case XML_RELAXNG_EXCEPT:
7731         case XML_RELAXNG_PARAM:
7732             /* TODO */
7733             break;
7734         case XML_RELAXNG_NOOP:
7735             xmlRelaxNGDumpDefines(output, define->content);
7736             break;
7737     }
7738 }
7739 
7740 /**
7741  * xmlRelaxNGDumpGrammar:
7742  * @output:  the file output
7743  * @grammar:  a grammar structure
7744  * @top:  is this a top grammar
7745  *
7746  * Dump a RelaxNG structure back
7747  */
7748 static void
xmlRelaxNGDumpGrammar(FILE * output,xmlRelaxNGGrammarPtr grammar,int top)7749 xmlRelaxNGDumpGrammar(FILE * output, xmlRelaxNGGrammarPtr grammar, int top)
7750 {
7751     if (grammar == NULL)
7752         return;
7753 
7754     fprintf(output, "<grammar");
7755     if (top)
7756         fprintf(output, " xmlns=\"http://relaxng.org/ns/structure/1.0\"");
7757     switch (grammar->combine) {
7758         case XML_RELAXNG_COMBINE_UNDEFINED:
7759             break;
7760         case XML_RELAXNG_COMBINE_CHOICE:
7761             fprintf(output, " combine=\"choice\"");
7762             break;
7763         case XML_RELAXNG_COMBINE_INTERLEAVE:
7764             fprintf(output, " combine=\"interleave\"");
7765             break;
7766         default:
7767             fprintf(output, " <!-- invalid combine value -->");
7768     }
7769     fprintf(output, ">\n");
7770     if (grammar->start == NULL) {
7771         fprintf(output, " <!-- grammar had no start -->");
7772     } else {
7773         fprintf(output, "<start>\n");
7774         xmlRelaxNGDumpDefine(output, grammar->start);
7775         fprintf(output, "</start>\n");
7776     }
7777     /* TODO ? Dump the defines ? */
7778     fprintf(output, "</grammar>\n");
7779 }
7780 
7781 /**
7782  * xmlRelaxNGDump:
7783  * @output:  the file output
7784  * @schema:  a schema structure
7785  *
7786  * Dump a RelaxNG structure back
7787  */
7788 void
xmlRelaxNGDump(FILE * output,xmlRelaxNGPtr schema)7789 xmlRelaxNGDump(FILE * output, xmlRelaxNGPtr schema)
7790 {
7791     if (output == NULL)
7792         return;
7793     if (schema == NULL) {
7794         fprintf(output, "RelaxNG empty or failed to compile\n");
7795         return;
7796     }
7797     fprintf(output, "RelaxNG: ");
7798     if (schema->doc == NULL) {
7799         fprintf(output, "no document\n");
7800     } else if (schema->doc->URL != NULL) {
7801         fprintf(output, "%s\n", schema->doc->URL);
7802     } else {
7803         fprintf(output, "\n");
7804     }
7805     if (schema->topgrammar == NULL) {
7806         fprintf(output, "RelaxNG has no top grammar\n");
7807         return;
7808     }
7809     xmlRelaxNGDumpGrammar(output, schema->topgrammar, 1);
7810 }
7811 
7812 /**
7813  * xmlRelaxNGDumpTree:
7814  * @output:  the file output
7815  * @schema:  a schema structure
7816  *
7817  * Dump the transformed RelaxNG tree.
7818  */
7819 void
xmlRelaxNGDumpTree(FILE * output,xmlRelaxNGPtr schema)7820 xmlRelaxNGDumpTree(FILE * output, xmlRelaxNGPtr schema)
7821 {
7822     if (output == NULL)
7823         return;
7824     if (schema == NULL) {
7825         fprintf(output, "RelaxNG empty or failed to compile\n");
7826         return;
7827     }
7828     if (schema->doc == NULL) {
7829         fprintf(output, "no document\n");
7830     } else {
7831         xmlDocDump(output, schema->doc);
7832     }
7833 }
7834 #endif /* LIBXML_OUTPUT_ENABLED */
7835 
7836 /************************************************************************
7837  *									*
7838  *		Validation of compiled content				*
7839  *									*
7840  ************************************************************************/
7841 static int xmlRelaxNGValidateDefinition(xmlRelaxNGValidCtxtPtr ctxt,
7842                                         xmlRelaxNGDefinePtr define);
7843 
7844 /**
7845  * xmlRelaxNGValidateCompiledCallback:
7846  * @exec:  the regular expression instance
7847  * @token:  the token which matched
7848  * @transdata:  callback data, the define for the subelement if available
7849  @ @inputdata:  callback data, the Relax NG validation context
7850  *
7851  * Handle the callback and if needed validate the element children.
7852  */
7853 static void
xmlRelaxNGValidateCompiledCallback(xmlRegExecCtxtPtr exec ATTRIBUTE_UNUSED,const xmlChar * token,void * transdata,void * inputdata)7854 xmlRelaxNGValidateCompiledCallback(xmlRegExecCtxtPtr exec ATTRIBUTE_UNUSED,
7855                                    const xmlChar * token,
7856                                    void *transdata, void *inputdata)
7857 {
7858     xmlRelaxNGValidCtxtPtr ctxt = (xmlRelaxNGValidCtxtPtr) inputdata;
7859     xmlRelaxNGDefinePtr define = (xmlRelaxNGDefinePtr) transdata;
7860     int ret;
7861 
7862     if (ctxt == NULL) {
7863         xmlRngVErr(ctxt, NULL, XML_ERR_INTERNAL_ERROR,
7864                    "callback on %s missing context\n", token, NULL);
7865         return;
7866     }
7867     if (define == NULL) {
7868         if (token[0] == '#')
7869             return;
7870         xmlRngVErr(ctxt, NULL, XML_ERR_INTERNAL_ERROR,
7871                    "callback on %s missing define\n", token, NULL);
7872         if ((ctxt != NULL) && (ctxt->errNo == XML_RELAXNG_OK))
7873             ctxt->errNo = XML_RELAXNG_ERR_INTERNAL;
7874         return;
7875     }
7876     if (define->type != XML_RELAXNG_ELEMENT) {
7877         xmlRngVErr(ctxt, NULL, XML_ERR_INTERNAL_ERROR,
7878                    "callback on %s define is not element\n", token, NULL);
7879         if (ctxt->errNo == XML_RELAXNG_OK)
7880             ctxt->errNo = XML_RELAXNG_ERR_INTERNAL;
7881         return;
7882     }
7883     ret = xmlRelaxNGValidateDefinition(ctxt, define);
7884     if (ret != 0)
7885         ctxt->perr = ret;
7886 }
7887 
7888 /**
7889  * xmlRelaxNGValidateCompiledContent:
7890  * @ctxt:  the RelaxNG validation context
7891  * @regexp:  the regular expression as compiled
7892  * @content:  list of children to test against the regexp
7893  *
7894  * Validate the content model of an element or start using the regexp
7895  *
7896  * Returns 0 in case of success, -1 in case of error.
7897  */
7898 static int
xmlRelaxNGValidateCompiledContent(xmlRelaxNGValidCtxtPtr ctxt,xmlRegexpPtr regexp,xmlNodePtr content)7899 xmlRelaxNGValidateCompiledContent(xmlRelaxNGValidCtxtPtr ctxt,
7900                                   xmlRegexpPtr regexp, xmlNodePtr content)
7901 {
7902     xmlRegExecCtxtPtr exec;
7903     xmlNodePtr cur;
7904     int ret = 0;
7905     int oldperr;
7906 
7907     if ((ctxt == NULL) || (regexp == NULL))
7908         return (-1);
7909     oldperr = ctxt->perr;
7910     exec = xmlRegNewExecCtxt(regexp,
7911                              xmlRelaxNGValidateCompiledCallback, ctxt);
7912     ctxt->perr = 0;
7913     cur = content;
7914     while (cur != NULL) {
7915         ctxt->state->seq = cur;
7916         switch (cur->type) {
7917             case XML_TEXT_NODE:
7918             case XML_CDATA_SECTION_NODE:
7919                 if (xmlIsBlankNode(cur))
7920                     break;
7921                 ret = xmlRegExecPushString(exec, BAD_CAST "#text", ctxt);
7922                 if (ret < 0) {
7923                     VALID_ERR2(XML_RELAXNG_ERR_TEXTWRONG,
7924                                cur->parent->name);
7925                 }
7926                 break;
7927             case XML_ELEMENT_NODE:
7928                 if (cur->ns != NULL) {
7929                     ret = xmlRegExecPushString2(exec, cur->name,
7930                                                 cur->ns->href, ctxt);
7931                 } else {
7932                     ret = xmlRegExecPushString(exec, cur->name, ctxt);
7933                 }
7934                 if (ret < 0) {
7935                     VALID_ERR2(XML_RELAXNG_ERR_ELEMWRONG, cur->name);
7936                 }
7937                 break;
7938             default:
7939                 break;
7940         }
7941         if (ret < 0)
7942             break;
7943         /*
7944          * Switch to next element
7945          */
7946         cur = cur->next;
7947     }
7948     ret = xmlRegExecPushString(exec, NULL, NULL);
7949     if (ret == 1) {
7950         ret = 0;
7951         ctxt->state->seq = NULL;
7952     } else if (ret == 0) {
7953         /*
7954          * TODO: get some of the names needed to exit the current state of exec
7955          */
7956         VALID_ERR2(XML_RELAXNG_ERR_NOELEM, BAD_CAST "");
7957         ret = -1;
7958         if ((ctxt->flags & FLAGS_IGNORABLE) == 0)
7959             xmlRelaxNGDumpValidError(ctxt);
7960     } else {
7961         ret = -1;
7962     }
7963     xmlRegFreeExecCtxt(exec);
7964     /*
7965      * There might be content model errors outside of the pure
7966      * regexp validation, e.g. for attribute values.
7967      */
7968     if ((ret == 0) && (ctxt->perr != 0)) {
7969         ret = ctxt->perr;
7970     }
7971     ctxt->perr = oldperr;
7972     return (ret);
7973 }
7974 
7975 /************************************************************************
7976  *									*
7977  *		Progressive validation of when possible			*
7978  *									*
7979  ************************************************************************/
7980 static int xmlRelaxNGValidateAttributeList(xmlRelaxNGValidCtxtPtr ctxt,
7981                                            xmlRelaxNGDefinePtr defines);
7982 static int xmlRelaxNGValidateElementEnd(xmlRelaxNGValidCtxtPtr ctxt,
7983                                         int dolog);
7984 static void xmlRelaxNGLogBestError(xmlRelaxNGValidCtxtPtr ctxt);
7985 
7986 /**
7987  * xmlRelaxNGElemPush:
7988  * @ctxt:  the validation context
7989  * @exec:  the regexp runtime for the new content model
7990  *
7991  * Push a new regexp for the current node content model on the stack
7992  *
7993  * Returns 0 in case of success and -1 in case of error.
7994  */
7995 static int
xmlRelaxNGElemPush(xmlRelaxNGValidCtxtPtr ctxt,xmlRegExecCtxtPtr exec)7996 xmlRelaxNGElemPush(xmlRelaxNGValidCtxtPtr ctxt, xmlRegExecCtxtPtr exec)
7997 {
7998     if (ctxt->elemTab == NULL) {
7999         ctxt->elemMax = 10;
8000         ctxt->elemTab = (xmlRegExecCtxtPtr *) xmlMalloc(ctxt->elemMax *
8001                                                         sizeof
8002                                                         (xmlRegExecCtxtPtr));
8003         if (ctxt->elemTab == NULL) {
8004             xmlRngVErrMemory(ctxt);
8005             return (-1);
8006         }
8007     }
8008     if (ctxt->elemNr >= ctxt->elemMax) {
8009         ctxt->elemMax *= 2;
8010         ctxt->elemTab = (xmlRegExecCtxtPtr *) xmlRealloc(ctxt->elemTab,
8011                                                          ctxt->elemMax *
8012                                                          sizeof
8013                                                          (xmlRegExecCtxtPtr));
8014         if (ctxt->elemTab == NULL) {
8015             xmlRngVErrMemory(ctxt);
8016             return (-1);
8017         }
8018     }
8019     ctxt->elemTab[ctxt->elemNr++] = exec;
8020     ctxt->elem = exec;
8021     return (0);
8022 }
8023 
8024 /**
8025  * xmlRelaxNGElemPop:
8026  * @ctxt:  the validation context
8027  *
8028  * Pop the regexp of the current node content model from the stack
8029  *
8030  * Returns the exec or NULL if empty
8031  */
8032 static xmlRegExecCtxtPtr
xmlRelaxNGElemPop(xmlRelaxNGValidCtxtPtr ctxt)8033 xmlRelaxNGElemPop(xmlRelaxNGValidCtxtPtr ctxt)
8034 {
8035     xmlRegExecCtxtPtr ret;
8036 
8037     if (ctxt->elemNr <= 0)
8038         return (NULL);
8039     ctxt->elemNr--;
8040     ret = ctxt->elemTab[ctxt->elemNr];
8041     ctxt->elemTab[ctxt->elemNr] = NULL;
8042     if (ctxt->elemNr > 0)
8043         ctxt->elem = ctxt->elemTab[ctxt->elemNr - 1];
8044     else
8045         ctxt->elem = NULL;
8046     return (ret);
8047 }
8048 
8049 /**
8050  * xmlRelaxNGValidateProgressiveCallback:
8051  * @exec:  the regular expression instance
8052  * @token:  the token which matched
8053  * @transdata:  callback data, the define for the subelement if available
8054  @ @inputdata:  callback data, the Relax NG validation context
8055  *
8056  * Handle the callback and if needed validate the element children.
8057  * some of the in/out information are passed via the context in @inputdata.
8058  */
8059 static void
xmlRelaxNGValidateProgressiveCallback(xmlRegExecCtxtPtr exec ATTRIBUTE_UNUSED,const xmlChar * token,void * transdata,void * inputdata)8060 xmlRelaxNGValidateProgressiveCallback(xmlRegExecCtxtPtr exec
8061                                       ATTRIBUTE_UNUSED,
8062                                       const xmlChar * token,
8063                                       void *transdata, void *inputdata)
8064 {
8065     xmlRelaxNGValidCtxtPtr ctxt = (xmlRelaxNGValidCtxtPtr) inputdata;
8066     xmlRelaxNGDefinePtr define = (xmlRelaxNGDefinePtr) transdata;
8067     xmlRelaxNGValidStatePtr state, oldstate;
8068     xmlNodePtr node;
8069     int ret = 0, oldflags;
8070 
8071     if (ctxt == NULL) {
8072         xmlRngVErr(ctxt, NULL, XML_ERR_INTERNAL_ERROR,
8073                    "callback on %s missing context\n", token, NULL);
8074         return;
8075     }
8076     node = ctxt->pnode;
8077     ctxt->pstate = 1;
8078     if (define == NULL) {
8079         if (token[0] == '#')
8080             return;
8081         xmlRngVErr(ctxt, NULL, XML_ERR_INTERNAL_ERROR,
8082                    "callback on %s missing define\n", token, NULL);
8083         if ((ctxt != NULL) && (ctxt->errNo == XML_RELAXNG_OK))
8084             ctxt->errNo = XML_RELAXNG_ERR_INTERNAL;
8085         ctxt->pstate = -1;
8086         return;
8087     }
8088     if (define->type != XML_RELAXNG_ELEMENT) {
8089         xmlRngVErr(ctxt, NULL, XML_ERR_INTERNAL_ERROR,
8090                    "callback on %s define is not element\n", token, NULL);
8091         if (ctxt->errNo == XML_RELAXNG_OK)
8092             ctxt->errNo = XML_RELAXNG_ERR_INTERNAL;
8093         ctxt->pstate = -1;
8094         return;
8095     }
8096     if (node->type != XML_ELEMENT_NODE) {
8097         VALID_ERR(XML_RELAXNG_ERR_NOTELEM);
8098         if ((ctxt->flags & FLAGS_IGNORABLE) == 0)
8099             xmlRelaxNGDumpValidError(ctxt);
8100         ctxt->pstate = -1;
8101         return;
8102     }
8103     if (define->contModel == NULL) {
8104         /*
8105          * this node cannot be validated in a streamable fashion
8106          */
8107         ctxt->pstate = 0;
8108         ctxt->pdef = define;
8109         return;
8110     }
8111     exec = xmlRegNewExecCtxt(define->contModel,
8112                              xmlRelaxNGValidateProgressiveCallback, ctxt);
8113     if (exec == NULL) {
8114         ctxt->pstate = -1;
8115         return;
8116     }
8117     xmlRelaxNGElemPush(ctxt, exec);
8118 
8119     /*
8120      * Validate the attributes part of the content.
8121      */
8122     state = xmlRelaxNGNewValidState(ctxt, node);
8123     if (state == NULL) {
8124         ctxt->pstate = -1;
8125         return;
8126     }
8127     oldstate = ctxt->state;
8128     ctxt->state = state;
8129     if (define->attrs != NULL) {
8130         ret = xmlRelaxNGValidateAttributeList(ctxt, define->attrs);
8131         if (ret != 0) {
8132             ctxt->pstate = -1;
8133             VALID_ERR2(XML_RELAXNG_ERR_ATTRVALID, node->name);
8134         }
8135     }
8136     if (ctxt->state != NULL) {
8137         ctxt->state->seq = NULL;
8138         ret = xmlRelaxNGValidateElementEnd(ctxt, 1);
8139         if (ret != 0) {
8140             ctxt->pstate = -1;
8141         }
8142         xmlRelaxNGFreeValidState(ctxt, ctxt->state);
8143     } else if (ctxt->states != NULL) {
8144         int tmp = -1, i;
8145 
8146         oldflags = ctxt->flags;
8147 
8148         for (i = 0; i < ctxt->states->nbState; i++) {
8149             state = ctxt->states->tabState[i];
8150             ctxt->state = state;
8151             ctxt->state->seq = NULL;
8152 
8153             if (xmlRelaxNGValidateElementEnd(ctxt, 0) == 0) {
8154                 tmp = 0;
8155                 break;
8156             }
8157         }
8158         if (tmp != 0) {
8159             /*
8160              * validation error, log the message for the "best" one
8161              */
8162             ctxt->flags |= FLAGS_IGNORABLE;
8163             xmlRelaxNGLogBestError(ctxt);
8164         }
8165         for (i = 0; i < ctxt->states->nbState; i++) {
8166             xmlRelaxNGFreeValidState(ctxt, ctxt->states->tabState[i]);
8167         }
8168         xmlRelaxNGFreeStates(ctxt, ctxt->states);
8169         ctxt->states = NULL;
8170         if ((ret == 0) && (tmp == -1))
8171             ctxt->pstate = -1;
8172         ctxt->flags = oldflags;
8173     }
8174     if (ctxt->pstate == -1) {
8175         if ((ctxt->flags & FLAGS_IGNORABLE) == 0) {
8176             xmlRelaxNGDumpValidError(ctxt);
8177         }
8178     }
8179     ctxt->state = oldstate;
8180 }
8181 
8182 /**
8183  * xmlRelaxNGValidatePushElement:
8184  * @ctxt:  the validation context
8185  * @doc:  a document instance
8186  * @elem:  an element instance
8187  *
8188  * Push a new element start on the RelaxNG validation stack.
8189  *
8190  * returns 1 if no validation problem was found or 0 if validating the
8191  *         element requires a full node, and -1 in case of error.
8192  */
8193 int
xmlRelaxNGValidatePushElement(xmlRelaxNGValidCtxtPtr ctxt,xmlDocPtr doc ATTRIBUTE_UNUSED,xmlNodePtr elem)8194 xmlRelaxNGValidatePushElement(xmlRelaxNGValidCtxtPtr ctxt,
8195                               xmlDocPtr doc ATTRIBUTE_UNUSED,
8196                               xmlNodePtr elem)
8197 {
8198     int ret = 1;
8199 
8200     if ((ctxt == NULL) || (elem == NULL))
8201         return (-1);
8202 
8203     if (ctxt->elem == 0) {
8204         xmlRelaxNGPtr schema;
8205         xmlRelaxNGGrammarPtr grammar;
8206         xmlRegExecCtxtPtr exec;
8207         xmlRelaxNGDefinePtr define;
8208 
8209         schema = ctxt->schema;
8210         if (schema == NULL) {
8211             VALID_ERR(XML_RELAXNG_ERR_NOGRAMMAR);
8212             return (-1);
8213         }
8214         grammar = schema->topgrammar;
8215         if ((grammar == NULL) || (grammar->start == NULL)) {
8216             VALID_ERR(XML_RELAXNG_ERR_NOGRAMMAR);
8217             return (-1);
8218         }
8219         define = grammar->start;
8220         if (define->contModel == NULL) {
8221             ctxt->pdef = define;
8222             return (0);
8223         }
8224         exec = xmlRegNewExecCtxt(define->contModel,
8225                                  xmlRelaxNGValidateProgressiveCallback,
8226                                  ctxt);
8227         if (exec == NULL) {
8228             return (-1);
8229         }
8230         xmlRelaxNGElemPush(ctxt, exec);
8231     }
8232     ctxt->pnode = elem;
8233     ctxt->pstate = 0;
8234     if (elem->ns != NULL) {
8235         ret =
8236             xmlRegExecPushString2(ctxt->elem, elem->name, elem->ns->href,
8237                                   ctxt);
8238     } else {
8239         ret = xmlRegExecPushString(ctxt->elem, elem->name, ctxt);
8240     }
8241     if (ret < 0) {
8242         VALID_ERR2(XML_RELAXNG_ERR_ELEMWRONG, elem->name);
8243     } else {
8244         if (ctxt->pstate == 0)
8245             ret = 0;
8246         else if (ctxt->pstate < 0)
8247             ret = -1;
8248         else
8249             ret = 1;
8250     }
8251     return (ret);
8252 }
8253 
8254 /**
8255  * xmlRelaxNGValidatePushCData:
8256  * @ctxt:  the RelaxNG validation context
8257  * @data:  some character data read
8258  * @len:  the length of the data
8259  *
8260  * check the CData parsed for validation in the current stack
8261  *
8262  * returns 1 if no validation problem was found or -1 otherwise
8263  */
8264 int
xmlRelaxNGValidatePushCData(xmlRelaxNGValidCtxtPtr ctxt,const xmlChar * data,int len ATTRIBUTE_UNUSED)8265 xmlRelaxNGValidatePushCData(xmlRelaxNGValidCtxtPtr ctxt,
8266                             const xmlChar * data, int len ATTRIBUTE_UNUSED)
8267 {
8268     int ret = 1;
8269 
8270     if ((ctxt == NULL) || (ctxt->elem == NULL) || (data == NULL))
8271         return (-1);
8272 
8273     while (*data != 0) {
8274         if (!IS_BLANK_CH(*data))
8275             break;
8276         data++;
8277     }
8278     if (*data == 0)
8279         return (1);
8280 
8281     ret = xmlRegExecPushString(ctxt->elem, BAD_CAST "#text", ctxt);
8282     if (ret < 0) {
8283         VALID_ERR2(XML_RELAXNG_ERR_TEXTWRONG, BAD_CAST " TODO ");
8284 
8285         return (-1);
8286     }
8287     return (1);
8288 }
8289 
8290 /**
8291  * xmlRelaxNGValidatePopElement:
8292  * @ctxt:  the RelaxNG validation context
8293  * @doc:  a document instance
8294  * @elem:  an element instance
8295  *
8296  * Pop the element end from the RelaxNG validation stack.
8297  *
8298  * returns 1 if no validation problem was found or 0 otherwise
8299  */
8300 int
xmlRelaxNGValidatePopElement(xmlRelaxNGValidCtxtPtr ctxt,xmlDocPtr doc ATTRIBUTE_UNUSED,xmlNodePtr elem)8301 xmlRelaxNGValidatePopElement(xmlRelaxNGValidCtxtPtr ctxt,
8302                              xmlDocPtr doc ATTRIBUTE_UNUSED,
8303                              xmlNodePtr elem)
8304 {
8305     int ret;
8306     xmlRegExecCtxtPtr exec;
8307 
8308     if ((ctxt == NULL) || (ctxt->elem == NULL) || (elem == NULL))
8309         return (-1);
8310     /*
8311      * verify that we reached a terminal state of the content model.
8312      */
8313     exec = xmlRelaxNGElemPop(ctxt);
8314     ret = xmlRegExecPushString(exec, NULL, NULL);
8315     if (ret == 0) {
8316         /*
8317          * TODO: get some of the names needed to exit the current state of exec
8318          */
8319         VALID_ERR2(XML_RELAXNG_ERR_NOELEM, BAD_CAST "");
8320         ret = -1;
8321     } else if (ret < 0) {
8322         ret = -1;
8323     } else {
8324         ret = 1;
8325     }
8326     xmlRegFreeExecCtxt(exec);
8327     return (ret);
8328 }
8329 
8330 /**
8331  * xmlRelaxNGValidateFullElement:
8332  * @ctxt:  the validation context
8333  * @doc:  a document instance
8334  * @elem:  an element instance
8335  *
8336  * Validate a full subtree when xmlRelaxNGValidatePushElement() returned
8337  * 0 and the content of the node has been expanded.
8338  *
8339  * returns 1 if no validation problem was found or -1 in case of error.
8340  */
8341 int
xmlRelaxNGValidateFullElement(xmlRelaxNGValidCtxtPtr ctxt,xmlDocPtr doc ATTRIBUTE_UNUSED,xmlNodePtr elem)8342 xmlRelaxNGValidateFullElement(xmlRelaxNGValidCtxtPtr ctxt,
8343                               xmlDocPtr doc ATTRIBUTE_UNUSED,
8344                               xmlNodePtr elem)
8345 {
8346     int ret;
8347     xmlRelaxNGValidStatePtr state;
8348 
8349     if ((ctxt == NULL) || (ctxt->pdef == NULL) || (elem == NULL))
8350         return (-1);
8351     state = xmlRelaxNGNewValidState(ctxt, elem->parent);
8352     if (state == NULL) {
8353         return (-1);
8354     }
8355     state->seq = elem;
8356     ctxt->state = state;
8357     ctxt->errNo = XML_RELAXNG_OK;
8358     ret = xmlRelaxNGValidateDefinition(ctxt, ctxt->pdef);
8359     if ((ret != 0) || (ctxt->errNo != XML_RELAXNG_OK))
8360         ret = -1;
8361     else
8362         ret = 1;
8363     xmlRelaxNGFreeValidState(ctxt, ctxt->state);
8364     ctxt->state = NULL;
8365     return (ret);
8366 }
8367 
8368 /************************************************************************
8369  *									*
8370  *		Generic interpreted validation implementation		*
8371  *									*
8372  ************************************************************************/
8373 static int xmlRelaxNGValidateValue(xmlRelaxNGValidCtxtPtr ctxt,
8374                                    xmlRelaxNGDefinePtr define);
8375 
8376 /**
8377  * xmlRelaxNGSkipIgnored:
8378  * @ctxt:  a schema validation context
8379  * @node:  the top node.
8380  *
8381  * Skip ignorable nodes in that context
8382  *
8383  * Returns the new sibling or NULL in case of error.
8384  */
8385 static xmlNodePtr
xmlRelaxNGSkipIgnored(xmlRelaxNGValidCtxtPtr ctxt ATTRIBUTE_UNUSED,xmlNodePtr node)8386 xmlRelaxNGSkipIgnored(xmlRelaxNGValidCtxtPtr ctxt ATTRIBUTE_UNUSED,
8387                       xmlNodePtr node)
8388 {
8389     /*
8390      * TODO complete and handle entities
8391      */
8392     while ((node != NULL) &&
8393            ((node->type == XML_COMMENT_NODE) ||
8394             (node->type == XML_PI_NODE) ||
8395 	    (node->type == XML_XINCLUDE_START) ||
8396 	    (node->type == XML_XINCLUDE_END) ||
8397             (((node->type == XML_TEXT_NODE) ||
8398               (node->type == XML_CDATA_SECTION_NODE)) &&
8399              ((ctxt->flags & FLAGS_MIXED_CONTENT) ||
8400               (IS_BLANK_NODE(node)))))) {
8401         node = node->next;
8402     }
8403     return (node);
8404 }
8405 
8406 /**
8407  * xmlRelaxNGNormalize:
8408  * @ctxt:  a schema validation context
8409  * @str:  the string to normalize
8410  *
8411  * Implements the  normalizeWhiteSpace( s ) function from
8412  * section 6.2.9 of the spec
8413  *
8414  * Returns the new string or NULL in case of error.
8415  */
8416 static xmlChar *
xmlRelaxNGNormalize(xmlRelaxNGValidCtxtPtr ctxt,const xmlChar * str)8417 xmlRelaxNGNormalize(xmlRelaxNGValidCtxtPtr ctxt, const xmlChar * str)
8418 {
8419     xmlChar *ret, *p;
8420     const xmlChar *tmp;
8421     int len;
8422 
8423     if (str == NULL)
8424         return (NULL);
8425     tmp = str;
8426     while (*tmp != 0)
8427         tmp++;
8428     len = tmp - str;
8429 
8430     ret = xmlMalloc(len + 1);
8431     if (ret == NULL) {
8432         xmlRngVErrMemory(ctxt);
8433         return (NULL);
8434     }
8435     p = ret;
8436     while (IS_BLANK_CH(*str))
8437         str++;
8438     while (*str != 0) {
8439         if (IS_BLANK_CH(*str)) {
8440             while (IS_BLANK_CH(*str))
8441                 str++;
8442             if (*str == 0)
8443                 break;
8444             *p++ = ' ';
8445         } else
8446             *p++ = *str++;
8447     }
8448     *p = 0;
8449     return (ret);
8450 }
8451 
8452 /**
8453  * xmlRelaxNGValidateDatatype:
8454  * @ctxt:  a Relax-NG validation context
8455  * @value:  the string value
8456  * @type:  the datatype definition
8457  * @node:  the node
8458  *
8459  * Validate the given value against the datatype
8460  *
8461  * Returns 0 if the validation succeeded or an error code.
8462  */
8463 static int
xmlRelaxNGValidateDatatype(xmlRelaxNGValidCtxtPtr ctxt,const xmlChar * value,xmlRelaxNGDefinePtr define,xmlNodePtr node)8464 xmlRelaxNGValidateDatatype(xmlRelaxNGValidCtxtPtr ctxt,
8465                            const xmlChar * value,
8466                            xmlRelaxNGDefinePtr define, xmlNodePtr node)
8467 {
8468     int ret, tmp;
8469     xmlRelaxNGTypeLibraryPtr lib;
8470     void *result = NULL;
8471     xmlRelaxNGDefinePtr cur;
8472 
8473     if ((define == NULL) || (define->data == NULL)) {
8474         return (-1);
8475     }
8476     lib = (xmlRelaxNGTypeLibraryPtr) define->data;
8477     if (lib->check != NULL) {
8478         if ((define->attrs != NULL) &&
8479             (define->attrs->type == XML_RELAXNG_PARAM)) {
8480             ret =
8481                 lib->check(lib->data, define->name, value, &result, node);
8482         } else {
8483             ret = lib->check(lib->data, define->name, value, NULL, node);
8484         }
8485     } else
8486         ret = -1;
8487     if (ret < 0) {
8488         VALID_ERR2(XML_RELAXNG_ERR_TYPE, define->name);
8489         if ((result != NULL) && (lib != NULL) && (lib->freef != NULL))
8490             lib->freef(lib->data, result);
8491         return (-1);
8492     } else if (ret == 1) {
8493         ret = 0;
8494     } else if (ret == 2) {
8495         VALID_ERR2P(XML_RELAXNG_ERR_DUPID, value);
8496     } else {
8497         VALID_ERR3P(XML_RELAXNG_ERR_TYPEVAL, define->name, value);
8498         ret = -1;
8499     }
8500     cur = define->attrs;
8501     while ((ret == 0) && (cur != NULL) && (cur->type == XML_RELAXNG_PARAM)) {
8502         if (lib->facet != NULL) {
8503             tmp = lib->facet(lib->data, define->name, cur->name,
8504                              cur->value, value, result);
8505             if (tmp != 0)
8506                 ret = -1;
8507         }
8508         cur = cur->next;
8509     }
8510     if ((ret == 0) && (define->content != NULL)) {
8511         const xmlChar *oldvalue, *oldendvalue;
8512 
8513         oldvalue = ctxt->state->value;
8514         oldendvalue = ctxt->state->endvalue;
8515         ctxt->state->value = (xmlChar *) value;
8516         ctxt->state->endvalue = NULL;
8517         ret = xmlRelaxNGValidateValue(ctxt, define->content);
8518         ctxt->state->value = (xmlChar *) oldvalue;
8519         ctxt->state->endvalue = (xmlChar *) oldendvalue;
8520     }
8521     if ((result != NULL) && (lib != NULL) && (lib->freef != NULL))
8522         lib->freef(lib->data, result);
8523     return (ret);
8524 }
8525 
8526 /**
8527  * xmlRelaxNGNextValue:
8528  * @ctxt:  a Relax-NG validation context
8529  *
8530  * Skip to the next value when validating within a list
8531  *
8532  * Returns 0 if the operation succeeded or an error code.
8533  */
8534 static int
xmlRelaxNGNextValue(xmlRelaxNGValidCtxtPtr ctxt)8535 xmlRelaxNGNextValue(xmlRelaxNGValidCtxtPtr ctxt)
8536 {
8537     xmlChar *cur;
8538 
8539     cur = ctxt->state->value;
8540     if ((cur == NULL) || (ctxt->state->endvalue == NULL)) {
8541         ctxt->state->value = NULL;
8542         ctxt->state->endvalue = NULL;
8543         return (0);
8544     }
8545     while (*cur != 0)
8546         cur++;
8547     while ((cur != ctxt->state->endvalue) && (*cur == 0))
8548         cur++;
8549     if (cur == ctxt->state->endvalue)
8550         ctxt->state->value = NULL;
8551     else
8552         ctxt->state->value = cur;
8553     return (0);
8554 }
8555 
8556 /**
8557  * xmlRelaxNGValidateValueList:
8558  * @ctxt:  a Relax-NG validation context
8559  * @defines:  the list of definitions to verify
8560  *
8561  * Validate the given set of definitions for the current value
8562  *
8563  * Returns 0 if the validation succeeded or an error code.
8564  */
8565 static int
xmlRelaxNGValidateValueList(xmlRelaxNGValidCtxtPtr ctxt,xmlRelaxNGDefinePtr defines)8566 xmlRelaxNGValidateValueList(xmlRelaxNGValidCtxtPtr ctxt,
8567                             xmlRelaxNGDefinePtr defines)
8568 {
8569     int ret = 0;
8570 
8571     while (defines != NULL) {
8572         ret = xmlRelaxNGValidateValue(ctxt, defines);
8573         if (ret != 0)
8574             break;
8575         defines = defines->next;
8576     }
8577     return (ret);
8578 }
8579 
8580 /**
8581  * xmlRelaxNGValidateValue:
8582  * @ctxt:  a Relax-NG validation context
8583  * @define:  the definition to verify
8584  *
8585  * Validate the given definition for the current value
8586  *
8587  * Returns 0 if the validation succeeded or an error code.
8588  */
8589 static int
xmlRelaxNGValidateValue(xmlRelaxNGValidCtxtPtr ctxt,xmlRelaxNGDefinePtr define)8590 xmlRelaxNGValidateValue(xmlRelaxNGValidCtxtPtr ctxt,
8591                         xmlRelaxNGDefinePtr define)
8592 {
8593     int ret = 0, oldflags;
8594     xmlChar *value;
8595 
8596     value = ctxt->state->value;
8597     switch (define->type) {
8598         case XML_RELAXNG_EMPTY:{
8599                 if ((value != NULL) && (value[0] != 0)) {
8600                     int idx = 0;
8601 
8602                     while (IS_BLANK_CH(value[idx]))
8603                         idx++;
8604                     if (value[idx] != 0)
8605                         ret = -1;
8606                 }
8607                 break;
8608             }
8609         case XML_RELAXNG_TEXT:
8610             break;
8611         case XML_RELAXNG_VALUE:{
8612                 if (!xmlStrEqual(value, define->value)) {
8613                     if (define->name != NULL) {
8614                         xmlRelaxNGTypeLibraryPtr lib;
8615 
8616                         lib = (xmlRelaxNGTypeLibraryPtr) define->data;
8617                         if ((lib != NULL) && (lib->comp != NULL)) {
8618                             ret = lib->comp(lib->data, define->name,
8619                                             define->value, define->node,
8620                                             (void *) define->attrs,
8621                                             value, ctxt->state->node);
8622                         } else
8623                             ret = -1;
8624                         if (ret < 0) {
8625                             VALID_ERR2(XML_RELAXNG_ERR_TYPECMP,
8626                                        define->name);
8627                             return (-1);
8628                         } else if (ret == 1) {
8629                             ret = 0;
8630                         } else {
8631                             ret = -1;
8632                         }
8633                     } else {
8634                         xmlChar *nval, *nvalue;
8635 
8636                         /*
8637                          * TODO: trivial optimizations are possible by
8638                          * computing at compile-time
8639                          */
8640                         nval = xmlRelaxNGNormalize(ctxt, define->value);
8641                         nvalue = xmlRelaxNGNormalize(ctxt, value);
8642 
8643                         if ((nval == NULL) || (nvalue == NULL) ||
8644                             (!xmlStrEqual(nval, nvalue)))
8645                             ret = -1;
8646                         if (nval != NULL)
8647                             xmlFree(nval);
8648                         if (nvalue != NULL)
8649                             xmlFree(nvalue);
8650                     }
8651                 }
8652                 if (ret == 0)
8653                     xmlRelaxNGNextValue(ctxt);
8654                 break;
8655             }
8656         case XML_RELAXNG_DATATYPE:{
8657                 ret = xmlRelaxNGValidateDatatype(ctxt, value, define,
8658                                                  ctxt->state->seq);
8659                 if (ret == 0)
8660                     xmlRelaxNGNextValue(ctxt);
8661 
8662                 break;
8663             }
8664         case XML_RELAXNG_CHOICE:{
8665                 xmlRelaxNGDefinePtr list = define->content;
8666                 xmlChar *oldvalue;
8667 
8668                 oldflags = ctxt->flags;
8669                 ctxt->flags |= FLAGS_IGNORABLE;
8670 
8671                 oldvalue = ctxt->state->value;
8672                 while (list != NULL) {
8673                     ret = xmlRelaxNGValidateValue(ctxt, list);
8674                     if (ret == 0) {
8675                         break;
8676                     }
8677                     ctxt->state->value = oldvalue;
8678                     list = list->next;
8679                 }
8680                 ctxt->flags = oldflags;
8681                 if (ret != 0) {
8682                     if ((ctxt->flags & FLAGS_IGNORABLE) == 0)
8683                         xmlRelaxNGDumpValidError(ctxt);
8684                 } else {
8685                     if (ctxt->errNr > 0)
8686                         xmlRelaxNGPopErrors(ctxt, 0);
8687                 }
8688                 break;
8689             }
8690         case XML_RELAXNG_LIST:{
8691                 xmlRelaxNGDefinePtr list = define->content;
8692                 xmlChar *oldvalue, *oldend, *val, *cur;
8693 
8694                 oldvalue = ctxt->state->value;
8695                 oldend = ctxt->state->endvalue;
8696 
8697                 val = xmlStrdup(oldvalue);
8698                 if (val == NULL) {
8699                     val = xmlStrdup(BAD_CAST "");
8700                 }
8701                 if (val == NULL) {
8702                     VALID_ERR(XML_RELAXNG_ERR_NOSTATE);
8703                     return (-1);
8704                 }
8705                 cur = val;
8706                 while (*cur != 0) {
8707                     if (IS_BLANK_CH(*cur)) {
8708                         *cur = 0;
8709                         cur++;
8710                         while (IS_BLANK_CH(*cur))
8711                             *cur++ = 0;
8712                     } else
8713                         cur++;
8714                 }
8715                 ctxt->state->endvalue = cur;
8716                 cur = val;
8717                 while ((*cur == 0) && (cur != ctxt->state->endvalue))
8718                     cur++;
8719 
8720                 ctxt->state->value = cur;
8721 
8722                 while (list != NULL) {
8723                     if (ctxt->state->value == ctxt->state->endvalue)
8724                         ctxt->state->value = NULL;
8725                     ret = xmlRelaxNGValidateValue(ctxt, list);
8726                     if (ret != 0) {
8727                         break;
8728                     }
8729                     list = list->next;
8730                 }
8731 
8732                 if ((ret == 0) && (ctxt->state->value != NULL) &&
8733                     (ctxt->state->value != ctxt->state->endvalue)) {
8734                     VALID_ERR2(XML_RELAXNG_ERR_LISTEXTRA,
8735                                ctxt->state->value);
8736                     ret = -1;
8737                 }
8738                 xmlFree(val);
8739                 ctxt->state->value = oldvalue;
8740                 ctxt->state->endvalue = oldend;
8741                 break;
8742             }
8743         case XML_RELAXNG_ONEORMORE:
8744             ret = xmlRelaxNGValidateValueList(ctxt, define->content);
8745             if (ret != 0) {
8746                 break;
8747             }
8748             /* Falls through. */
8749         case XML_RELAXNG_ZEROORMORE:{
8750                 xmlChar *cur, *temp;
8751 
8752                 if ((ctxt->state->value == NULL) ||
8753                     (*ctxt->state->value == 0)) {
8754                     ret = 0;
8755                     break;
8756                 }
8757                 oldflags = ctxt->flags;
8758                 ctxt->flags |= FLAGS_IGNORABLE;
8759                 cur = ctxt->state->value;
8760                 temp = NULL;
8761                 while ((cur != NULL) && (cur != ctxt->state->endvalue) &&
8762                        (temp != cur)) {
8763                     temp = cur;
8764                     ret =
8765                         xmlRelaxNGValidateValueList(ctxt, define->content);
8766                     if (ret != 0) {
8767                         ctxt->state->value = temp;
8768                         ret = 0;
8769                         break;
8770                     }
8771                     cur = ctxt->state->value;
8772                 }
8773                 ctxt->flags = oldflags;
8774 		if (ctxt->errNr > 0)
8775 		    xmlRelaxNGPopErrors(ctxt, 0);
8776                 break;
8777             }
8778         case XML_RELAXNG_OPTIONAL:{
8779                 xmlChar *temp;
8780 
8781                 if ((ctxt->state->value == NULL) ||
8782                     (*ctxt->state->value == 0)) {
8783                     ret = 0;
8784                     break;
8785                 }
8786                 oldflags = ctxt->flags;
8787                 ctxt->flags |= FLAGS_IGNORABLE;
8788                 temp = ctxt->state->value;
8789                 ret = xmlRelaxNGValidateValue(ctxt, define->content);
8790                 ctxt->flags = oldflags;
8791                 if (ret != 0) {
8792                     ctxt->state->value = temp;
8793                     if (ctxt->errNr > 0)
8794                         xmlRelaxNGPopErrors(ctxt, 0);
8795                     ret = 0;
8796                     break;
8797                 }
8798 		if (ctxt->errNr > 0)
8799 		    xmlRelaxNGPopErrors(ctxt, 0);
8800                 break;
8801             }
8802         case XML_RELAXNG_EXCEPT:{
8803                 xmlRelaxNGDefinePtr list;
8804 
8805                 list = define->content;
8806                 while (list != NULL) {
8807                     ret = xmlRelaxNGValidateValue(ctxt, list);
8808                     if (ret == 0) {
8809                         ret = -1;
8810                         break;
8811                     } else
8812                         ret = 0;
8813                     list = list->next;
8814                 }
8815                 break;
8816             }
8817         case XML_RELAXNG_DEF:
8818         case XML_RELAXNG_GROUP:{
8819                 xmlRelaxNGDefinePtr list;
8820 
8821                 list = define->content;
8822                 while (list != NULL) {
8823                     ret = xmlRelaxNGValidateValue(ctxt, list);
8824                     if (ret != 0) {
8825                         ret = -1;
8826                         break;
8827                     } else
8828                         ret = 0;
8829                     list = list->next;
8830                 }
8831                 break;
8832             }
8833         case XML_RELAXNG_REF:
8834         case XML_RELAXNG_PARENTREF:
8835 	    if (define->content == NULL) {
8836                 VALID_ERR(XML_RELAXNG_ERR_NODEFINE);
8837                 ret = -1;
8838 	    } else {
8839                 ret = xmlRelaxNGValidateValue(ctxt, define->content);
8840             }
8841             break;
8842         default:
8843             /* TODO */
8844             ret = -1;
8845     }
8846     return (ret);
8847 }
8848 
8849 /**
8850  * xmlRelaxNGValidateValueContent:
8851  * @ctxt:  a Relax-NG validation context
8852  * @defines:  the list of definitions to verify
8853  *
8854  * Validate the given definitions for the current value
8855  *
8856  * Returns 0 if the validation succeeded or an error code.
8857  */
8858 static int
xmlRelaxNGValidateValueContent(xmlRelaxNGValidCtxtPtr ctxt,xmlRelaxNGDefinePtr defines)8859 xmlRelaxNGValidateValueContent(xmlRelaxNGValidCtxtPtr ctxt,
8860                                xmlRelaxNGDefinePtr defines)
8861 {
8862     int ret = 0;
8863 
8864     while (defines != NULL) {
8865         ret = xmlRelaxNGValidateValue(ctxt, defines);
8866         if (ret != 0)
8867             break;
8868         defines = defines->next;
8869     }
8870     return (ret);
8871 }
8872 
8873 /**
8874  * xmlRelaxNGAttributeMatch:
8875  * @ctxt:  a Relax-NG validation context
8876  * @define:  the definition to check
8877  * @prop:  the attribute
8878  *
8879  * Check if the attribute matches the definition nameClass
8880  *
8881  * Returns 1 if the attribute matches, 0 if no, or -1 in case of error
8882  */
8883 static int
xmlRelaxNGAttributeMatch(xmlRelaxNGValidCtxtPtr ctxt,xmlRelaxNGDefinePtr define,xmlAttrPtr prop)8884 xmlRelaxNGAttributeMatch(xmlRelaxNGValidCtxtPtr ctxt,
8885                          xmlRelaxNGDefinePtr define, xmlAttrPtr prop)
8886 {
8887     int ret;
8888 
8889     if (define->name != NULL) {
8890         if (!xmlStrEqual(define->name, prop->name))
8891             return (0);
8892     }
8893     if (define->ns != NULL) {
8894         if (define->ns[0] == 0) {
8895             if (prop->ns != NULL)
8896                 return (0);
8897         } else {
8898             if ((prop->ns == NULL) ||
8899                 (!xmlStrEqual(define->ns, prop->ns->href)))
8900                 return (0);
8901         }
8902     }
8903     if (define->nameClass == NULL)
8904         return (1);
8905     define = define->nameClass;
8906     if (define->type == XML_RELAXNG_EXCEPT) {
8907         xmlRelaxNGDefinePtr list;
8908 
8909         list = define->content;
8910         while (list != NULL) {
8911             ret = xmlRelaxNGAttributeMatch(ctxt, list, prop);
8912             if (ret == 1)
8913                 return (0);
8914             if (ret < 0)
8915                 return (ret);
8916             list = list->next;
8917         }
8918     } else if (define->type == XML_RELAXNG_CHOICE) {
8919         xmlRelaxNGDefinePtr list;
8920 
8921         list = define->nameClass;
8922         while (list != NULL) {
8923             ret = xmlRelaxNGAttributeMatch(ctxt, list, prop);
8924             if (ret == 1)
8925                 return (1);
8926             if (ret < 0)
8927                 return (ret);
8928             list = list->next;
8929         }
8930         return (0);
8931     } else {
8932         /* TODO */
8933         return (0);
8934     }
8935     return (1);
8936 }
8937 
8938 /**
8939  * xmlRelaxNGValidateAttribute:
8940  * @ctxt:  a Relax-NG validation context
8941  * @define:  the definition to verify
8942  *
8943  * Validate the given attribute definition for that node
8944  *
8945  * Returns 0 if the validation succeeded or an error code.
8946  */
8947 static int
xmlRelaxNGValidateAttribute(xmlRelaxNGValidCtxtPtr ctxt,xmlRelaxNGDefinePtr define)8948 xmlRelaxNGValidateAttribute(xmlRelaxNGValidCtxtPtr ctxt,
8949                             xmlRelaxNGDefinePtr define)
8950 {
8951     int ret = 0, i;
8952     xmlChar *value, *oldvalue;
8953     xmlAttrPtr prop = NULL, tmp;
8954     xmlNodePtr oldseq;
8955 
8956     if (ctxt->state->nbAttrLeft <= 0)
8957         return (-1);
8958     if (define->name != NULL) {
8959         for (i = 0; i < ctxt->state->nbAttrs; i++) {
8960             tmp = ctxt->state->attrs[i];
8961             if ((tmp != NULL) && (xmlStrEqual(define->name, tmp->name))) {
8962                 if ((((define->ns == NULL) || (define->ns[0] == 0)) &&
8963                      (tmp->ns == NULL)) ||
8964                     ((tmp->ns != NULL) &&
8965                      (xmlStrEqual(define->ns, tmp->ns->href)))) {
8966                     prop = tmp;
8967                     break;
8968                 }
8969             }
8970         }
8971         if (prop != NULL) {
8972             value = xmlNodeListGetString(prop->doc, prop->children, 1);
8973             oldvalue = ctxt->state->value;
8974             oldseq = ctxt->state->seq;
8975             ctxt->state->seq = (xmlNodePtr) prop;
8976             ctxt->state->value = value;
8977             ctxt->state->endvalue = NULL;
8978             ret = xmlRelaxNGValidateValueContent(ctxt, define->content);
8979             if (ctxt->state->value != NULL)
8980                 value = ctxt->state->value;
8981             if (value != NULL)
8982                 xmlFree(value);
8983             ctxt->state->value = oldvalue;
8984             ctxt->state->seq = oldseq;
8985             if (ret == 0) {
8986                 /*
8987                  * flag the attribute as processed
8988                  */
8989                 ctxt->state->attrs[i] = NULL;
8990                 ctxt->state->nbAttrLeft--;
8991             }
8992         } else {
8993             ret = -1;
8994         }
8995     } else {
8996         for (i = 0; i < ctxt->state->nbAttrs; i++) {
8997             tmp = ctxt->state->attrs[i];
8998             if ((tmp != NULL) &&
8999                 (xmlRelaxNGAttributeMatch(ctxt, define, tmp) == 1)) {
9000                 prop = tmp;
9001                 break;
9002             }
9003         }
9004         if (prop != NULL) {
9005             value = xmlNodeListGetString(prop->doc, prop->children, 1);
9006             oldvalue = ctxt->state->value;
9007             oldseq = ctxt->state->seq;
9008             ctxt->state->seq = (xmlNodePtr) prop;
9009             ctxt->state->value = value;
9010             ret = xmlRelaxNGValidateValueContent(ctxt, define->content);
9011             if (ctxt->state->value != NULL)
9012                 value = ctxt->state->value;
9013             if (value != NULL)
9014                 xmlFree(value);
9015             ctxt->state->value = oldvalue;
9016             ctxt->state->seq = oldseq;
9017             if (ret == 0) {
9018                 /*
9019                  * flag the attribute as processed
9020                  */
9021                 ctxt->state->attrs[i] = NULL;
9022                 ctxt->state->nbAttrLeft--;
9023             }
9024         } else {
9025             ret = -1;
9026         }
9027     }
9028 
9029     return (ret);
9030 }
9031 
9032 /**
9033  * xmlRelaxNGValidateAttributeList:
9034  * @ctxt:  a Relax-NG validation context
9035  * @define:  the list of definition to verify
9036  *
9037  * Validate the given node against the list of attribute definitions
9038  *
9039  * Returns 0 if the validation succeeded or an error code.
9040  */
9041 static int
xmlRelaxNGValidateAttributeList(xmlRelaxNGValidCtxtPtr ctxt,xmlRelaxNGDefinePtr defines)9042 xmlRelaxNGValidateAttributeList(xmlRelaxNGValidCtxtPtr ctxt,
9043                                 xmlRelaxNGDefinePtr defines)
9044 {
9045     int ret = 0, res;
9046     int needmore = 0;
9047     xmlRelaxNGDefinePtr cur;
9048 
9049     cur = defines;
9050     while (cur != NULL) {
9051         if (cur->type == XML_RELAXNG_ATTRIBUTE) {
9052             if (xmlRelaxNGValidateAttribute(ctxt, cur) != 0)
9053                 ret = -1;
9054         } else
9055             needmore = 1;
9056         cur = cur->next;
9057     }
9058     if (!needmore)
9059         return (ret);
9060     cur = defines;
9061     while (cur != NULL) {
9062         if (cur->type != XML_RELAXNG_ATTRIBUTE) {
9063             if ((ctxt->state != NULL) || (ctxt->states != NULL)) {
9064                 res = xmlRelaxNGValidateDefinition(ctxt, cur);
9065                 if (res < 0)
9066                     ret = -1;
9067             } else {
9068                 VALID_ERR(XML_RELAXNG_ERR_NOSTATE);
9069                 return (-1);
9070             }
9071             if (res == -1)      /* continues on -2 */
9072                 break;
9073         }
9074         cur = cur->next;
9075     }
9076 
9077     return (ret);
9078 }
9079 
9080 /**
9081  * xmlRelaxNGNodeMatchesList:
9082  * @node:  the node
9083  * @list:  a NULL terminated array of definitions
9084  *
9085  * Check if a node can be matched by one of the definitions
9086  *
9087  * Returns 1 if matches 0 otherwise
9088  */
9089 static int
xmlRelaxNGNodeMatchesList(xmlNodePtr node,xmlRelaxNGDefinePtr * list)9090 xmlRelaxNGNodeMatchesList(xmlNodePtr node, xmlRelaxNGDefinePtr * list)
9091 {
9092     xmlRelaxNGDefinePtr cur;
9093     int i = 0, tmp;
9094 
9095     if ((node == NULL) || (list == NULL))
9096         return (0);
9097 
9098     cur = list[i++];
9099     while (cur != NULL) {
9100         if ((node->type == XML_ELEMENT_NODE) &&
9101             (cur->type == XML_RELAXNG_ELEMENT)) {
9102             tmp = xmlRelaxNGElementMatch(NULL, cur, node);
9103             if (tmp == 1)
9104                 return (1);
9105         } else if (((node->type == XML_TEXT_NODE) ||
9106                     (node->type == XML_CDATA_SECTION_NODE)) &&
9107                    ((cur->type == XML_RELAXNG_DATATYPE) ||
9108 		    (cur->type == XML_RELAXNG_LIST) ||
9109                     (cur->type == XML_RELAXNG_TEXT) ||
9110                     (cur->type == XML_RELAXNG_VALUE))) {
9111             return (1);
9112         }
9113         cur = list[i++];
9114     }
9115     return (0);
9116 }
9117 
9118 /**
9119  * xmlRelaxNGValidateInterleave:
9120  * @ctxt:  a Relax-NG validation context
9121  * @define:  the definition to verify
9122  *
9123  * Validate an interleave definition for a node.
9124  *
9125  * Returns 0 if the validation succeeded or an error code.
9126  */
9127 static int
xmlRelaxNGValidateInterleave(xmlRelaxNGValidCtxtPtr ctxt,xmlRelaxNGDefinePtr define)9128 xmlRelaxNGValidateInterleave(xmlRelaxNGValidCtxtPtr ctxt,
9129                              xmlRelaxNGDefinePtr define)
9130 {
9131     int ret = 0, i, nbgroups;
9132     int errNr = ctxt->errNr;
9133     int oldflags;
9134 
9135     xmlRelaxNGValidStatePtr oldstate;
9136     xmlRelaxNGPartitionPtr partitions;
9137     xmlRelaxNGInterleaveGroupPtr group = NULL;
9138     xmlNodePtr cur, start, last = NULL, lastchg = NULL, lastelem;
9139     xmlNodePtr *list = NULL, *lasts = NULL;
9140 
9141     if (define->data != NULL) {
9142         partitions = (xmlRelaxNGPartitionPtr) define->data;
9143         nbgroups = partitions->nbgroups;
9144     } else {
9145         VALID_ERR(XML_RELAXNG_ERR_INTERNODATA);
9146         return (-1);
9147     }
9148     /*
9149      * Optimizations for MIXED
9150      */
9151     oldflags = ctxt->flags;
9152     if (define->dflags & IS_MIXED) {
9153         ctxt->flags |= FLAGS_MIXED_CONTENT;
9154         if (nbgroups == 2) {
9155             /*
9156              * this is a pure <mixed> case
9157              */
9158             if (ctxt->state != NULL)
9159                 ctxt->state->seq = xmlRelaxNGSkipIgnored(ctxt,
9160                                                          ctxt->state->seq);
9161             if (partitions->groups[0]->rule->type == XML_RELAXNG_TEXT)
9162                 ret = xmlRelaxNGValidateDefinition(ctxt,
9163                                                    partitions->groups[1]->
9164                                                    rule);
9165             else
9166                 ret = xmlRelaxNGValidateDefinition(ctxt,
9167                                                    partitions->groups[0]->
9168                                                    rule);
9169             if (ret == 0) {
9170                 if (ctxt->state != NULL)
9171                     ctxt->state->seq = xmlRelaxNGSkipIgnored(ctxt,
9172                                                              ctxt->state->
9173                                                              seq);
9174             }
9175             ctxt->flags = oldflags;
9176             return (ret);
9177         }
9178     }
9179 
9180     /*
9181      * Build arrays to store the first and last node of the chain
9182      * pertaining to each group
9183      */
9184     list = (xmlNodePtr *) xmlMalloc(nbgroups * sizeof(xmlNodePtr));
9185     if (list == NULL) {
9186         xmlRngVErrMemory(ctxt);
9187         return (-1);
9188     }
9189     memset(list, 0, nbgroups * sizeof(xmlNodePtr));
9190     lasts = (xmlNodePtr *) xmlMalloc(nbgroups * sizeof(xmlNodePtr));
9191     if (lasts == NULL) {
9192         xmlRngVErrMemory(ctxt);
9193         return (-1);
9194     }
9195     memset(lasts, 0, nbgroups * sizeof(xmlNodePtr));
9196 
9197     /*
9198      * Walk the sequence of children finding the right group and
9199      * sorting them in sequences.
9200      */
9201     cur = ctxt->state->seq;
9202     cur = xmlRelaxNGSkipIgnored(ctxt, cur);
9203     start = cur;
9204     while (cur != NULL) {
9205         ctxt->state->seq = cur;
9206         if ((partitions->triage != NULL) &&
9207             (partitions->flags & IS_DETERMINIST)) {
9208             void *tmp = NULL;
9209 
9210             if ((cur->type == XML_TEXT_NODE) ||
9211                 (cur->type == XML_CDATA_SECTION_NODE)) {
9212                 tmp = xmlHashLookup2(partitions->triage, BAD_CAST "#text",
9213                                      NULL);
9214             } else if (cur->type == XML_ELEMENT_NODE) {
9215                 if (cur->ns != NULL) {
9216                     tmp = xmlHashLookup2(partitions->triage, cur->name,
9217                                          cur->ns->href);
9218                     if (tmp == NULL)
9219                         tmp = xmlHashLookup2(partitions->triage,
9220                                              BAD_CAST "#any",
9221                                              cur->ns->href);
9222                 } else
9223                     tmp =
9224                         xmlHashLookup2(partitions->triage, cur->name,
9225                                        NULL);
9226                 if (tmp == NULL)
9227                     tmp =
9228                         xmlHashLookup2(partitions->triage, BAD_CAST "#any",
9229                                        NULL);
9230             }
9231 
9232             if (tmp == NULL) {
9233                 i = nbgroups;
9234             } else {
9235                 i = XML_PTR_TO_INT(tmp) - 1;
9236                 if (partitions->flags & IS_NEEDCHECK) {
9237                     group = partitions->groups[i];
9238                     if (!xmlRelaxNGNodeMatchesList(cur, group->defs))
9239                         i = nbgroups;
9240                 }
9241             }
9242         } else {
9243             for (i = 0; i < nbgroups; i++) {
9244                 group = partitions->groups[i];
9245                 if (group == NULL)
9246                     continue;
9247                 if (xmlRelaxNGNodeMatchesList(cur, group->defs))
9248                     break;
9249             }
9250         }
9251         /*
9252          * We break as soon as an element not matched is found
9253          */
9254         if (i >= nbgroups) {
9255             break;
9256         }
9257         if (lasts[i] != NULL) {
9258             lasts[i]->next = cur;
9259             lasts[i] = cur;
9260         } else {
9261             list[i] = cur;
9262             lasts[i] = cur;
9263         }
9264         if (cur->next != NULL)
9265             lastchg = cur->next;
9266         else
9267             lastchg = cur;
9268         cur = xmlRelaxNGSkipIgnored(ctxt, cur->next);
9269     }
9270     if (ret != 0) {
9271         VALID_ERR(XML_RELAXNG_ERR_INTERSEQ);
9272         ret = -1;
9273         goto done;
9274     }
9275     lastelem = cur;
9276     oldstate = ctxt->state;
9277     for (i = 0; i < nbgroups; i++) {
9278         ctxt->state = xmlRelaxNGCopyValidState(ctxt, oldstate);
9279 	if (ctxt->state == NULL) {
9280 	    ret = -1;
9281 	    break;
9282 	}
9283         group = partitions->groups[i];
9284         if (lasts[i] != NULL) {
9285             last = lasts[i]->next;
9286             lasts[i]->next = NULL;
9287         }
9288         ctxt->state->seq = list[i];
9289         ret = xmlRelaxNGValidateDefinition(ctxt, group->rule);
9290         if (ret != 0)
9291             break;
9292         if (ctxt->state != NULL) {
9293             cur = ctxt->state->seq;
9294             cur = xmlRelaxNGSkipIgnored(ctxt, cur);
9295             xmlRelaxNGFreeValidState(ctxt, oldstate);
9296             oldstate = ctxt->state;
9297             ctxt->state = NULL;
9298             if (cur != NULL
9299                     /* there's a nasty violation of context-free unambiguities,
9300                        since in open-name-class context, interleave in the
9301                        production shall finish without caring about anything
9302                        else that is OK to follow in that case -- it would
9303                        otherwise get marked as "extra content" and would
9304                        hence fail the validation, hence this perhaps
9305                        dirty attempt to rectify such a situation */
9306                     && (define->parent->type != XML_RELAXNG_DEF
9307                         || !xmlStrEqual(define->parent->name,
9308                                         (const xmlChar *) "open-name-class"))) {
9309                 VALID_ERR2(XML_RELAXNG_ERR_INTEREXTRA, cur->name);
9310                 ret = -1;
9311                 ctxt->state = oldstate;
9312                 goto done;
9313             }
9314         } else if (ctxt->states != NULL) {
9315             int j;
9316             int found = 0;
9317 	    int best = -1;
9318 	    int lowattr = -1;
9319 
9320 	    /*
9321 	     * PBM: what happen if there is attributes checks in the interleaves
9322 	     */
9323 
9324             for (j = 0; j < ctxt->states->nbState; j++) {
9325                 cur = ctxt->states->tabState[j]->seq;
9326                 cur = xmlRelaxNGSkipIgnored(ctxt, cur);
9327                 if (cur == NULL) {
9328 		    if (found == 0) {
9329 		        lowattr = ctxt->states->tabState[j]->nbAttrLeft;
9330 			best = j;
9331 		    }
9332                     found = 1;
9333 		    if (ctxt->states->tabState[j]->nbAttrLeft <= lowattr) {
9334 		        /* try  to keep the latest one to mach old heuristic */
9335 		        lowattr = ctxt->states->tabState[j]->nbAttrLeft;
9336 			best = j;
9337 		    }
9338                     if (lowattr == 0)
9339 		        break;
9340                 } else if (found == 0) {
9341                     if (lowattr == -1) {
9342 		        lowattr = ctxt->states->tabState[j]->nbAttrLeft;
9343 			best = j;
9344 		    } else
9345 		    if (ctxt->states->tabState[j]->nbAttrLeft <= lowattr)  {
9346 		        /* try  to keep the latest one to mach old heuristic */
9347 		        lowattr = ctxt->states->tabState[j]->nbAttrLeft;
9348 			best = j;
9349 		    }
9350 		}
9351             }
9352 	    /*
9353 	     * BIG PBM: here we pick only one restarting point :-(
9354 	     */
9355             if (ctxt->states->nbState > 0) {
9356                 xmlRelaxNGFreeValidState(ctxt, oldstate);
9357 		if (best != -1) {
9358 		    oldstate = ctxt->states->tabState[best];
9359 		    ctxt->states->tabState[best] = NULL;
9360 		} else {
9361 		    oldstate =
9362 			ctxt->states->tabState[ctxt->states->nbState - 1];
9363                     ctxt->states->tabState[ctxt->states->nbState - 1] = NULL;
9364                     ctxt->states->nbState--;
9365 		}
9366             }
9367             for (j = 0; j < ctxt->states->nbState ; j++) {
9368                 xmlRelaxNGFreeValidState(ctxt, ctxt->states->tabState[j]);
9369             }
9370             xmlRelaxNGFreeStates(ctxt, ctxt->states);
9371             ctxt->states = NULL;
9372             if (found == 0) {
9373                 if (cur == NULL) {
9374 		    VALID_ERR2(XML_RELAXNG_ERR_INTEREXTRA,
9375 			       (const xmlChar *) "noname");
9376                 } else {
9377                     VALID_ERR2(XML_RELAXNG_ERR_INTEREXTRA, cur->name);
9378                 }
9379                 ret = -1;
9380                 ctxt->state = oldstate;
9381                 goto done;
9382             }
9383         } else {
9384             ret = -1;
9385             break;
9386         }
9387         if (lasts[i] != NULL) {
9388             lasts[i]->next = last;
9389         }
9390     }
9391     if (ctxt->state != NULL)
9392         xmlRelaxNGFreeValidState(ctxt, ctxt->state);
9393     ctxt->state = oldstate;
9394     ctxt->state->seq = lastelem;
9395     if (ret != 0) {
9396         VALID_ERR(XML_RELAXNG_ERR_INTERSEQ);
9397         ret = -1;
9398         goto done;
9399     }
9400 
9401   done:
9402     ctxt->flags = oldflags;
9403     /*
9404      * builds the next links chain from the prev one
9405      */
9406     cur = lastchg;
9407     while (cur != NULL) {
9408         if ((cur == start) || (cur->prev == NULL))
9409             break;
9410         cur->prev->next = cur;
9411         cur = cur->prev;
9412     }
9413     if (ret == 0) {
9414         if (ctxt->errNr > errNr)
9415             xmlRelaxNGPopErrors(ctxt, errNr);
9416     }
9417 
9418     xmlFree(list);
9419     xmlFree(lasts);
9420     return (ret);
9421 }
9422 
9423 /**
9424  * xmlRelaxNGValidateDefinitionList:
9425  * @ctxt:  a Relax-NG validation context
9426  * @define:  the list of definition to verify
9427  *
9428  * Validate the given node content against the (list) of definitions
9429  *
9430  * Returns 0 if the validation succeeded or an error code.
9431  */
9432 static int
xmlRelaxNGValidateDefinitionList(xmlRelaxNGValidCtxtPtr ctxt,xmlRelaxNGDefinePtr defines)9433 xmlRelaxNGValidateDefinitionList(xmlRelaxNGValidCtxtPtr ctxt,
9434                                  xmlRelaxNGDefinePtr defines)
9435 {
9436     int ret = 0, res;
9437 
9438 
9439     if (defines == NULL) {
9440         VALID_ERR2(XML_RELAXNG_ERR_INTERNAL,
9441                    BAD_CAST "NULL definition list");
9442         return (-1);
9443     }
9444     while (defines != NULL) {
9445         if ((ctxt->state != NULL) || (ctxt->states != NULL)) {
9446             res = xmlRelaxNGValidateDefinition(ctxt, defines);
9447             if (res < 0)
9448                 ret = -1;
9449         } else {
9450             VALID_ERR(XML_RELAXNG_ERR_NOSTATE);
9451             return (-1);
9452         }
9453         if (res == -1)          /* continues on -2 */
9454             break;
9455         defines = defines->next;
9456     }
9457 
9458     return (ret);
9459 }
9460 
9461 /**
9462  * xmlRelaxNGElementMatch:
9463  * @ctxt:  a Relax-NG validation context
9464  * @define:  the definition to check
9465  * @elem:  the element
9466  *
9467  * Check if the element matches the definition nameClass
9468  *
9469  * Returns 1 if the element matches, 0 if no, or -1 in case of error
9470  */
9471 static int
xmlRelaxNGElementMatch(xmlRelaxNGValidCtxtPtr ctxt,xmlRelaxNGDefinePtr define,xmlNodePtr elem)9472 xmlRelaxNGElementMatch(xmlRelaxNGValidCtxtPtr ctxt,
9473                        xmlRelaxNGDefinePtr define, xmlNodePtr elem)
9474 {
9475     int ret = 0, oldflags = 0;
9476 
9477     if (define->name != NULL) {
9478         if (!xmlStrEqual(elem->name, define->name)) {
9479             VALID_ERR3(XML_RELAXNG_ERR_ELEMNAME, define->name, elem->name);
9480             return (0);
9481         }
9482     }
9483     if ((define->ns != NULL) && (define->ns[0] != 0)) {
9484         if (elem->ns == NULL) {
9485             VALID_ERR2(XML_RELAXNG_ERR_ELEMNONS, elem->name);
9486             return (0);
9487         } else if (!xmlStrEqual(elem->ns->href, define->ns)) {
9488             VALID_ERR3(XML_RELAXNG_ERR_ELEMWRONGNS,
9489                        elem->name, define->ns);
9490             return (0);
9491         }
9492     } else if ((elem->ns != NULL) && (define->ns != NULL) &&
9493                (define->name == NULL)) {
9494         VALID_ERR2(XML_RELAXNG_ERR_ELEMEXTRANS, elem->name);
9495         return (0);
9496     } else if ((elem->ns != NULL) && (define->name != NULL)) {
9497         VALID_ERR2(XML_RELAXNG_ERR_ELEMEXTRANS, define->name);
9498         return (0);
9499     }
9500 
9501     if (define->nameClass == NULL)
9502         return (1);
9503 
9504     define = define->nameClass;
9505     if (define->type == XML_RELAXNG_EXCEPT) {
9506         xmlRelaxNGDefinePtr list;
9507 
9508         if (ctxt != NULL) {
9509             oldflags = ctxt->flags;
9510             ctxt->flags |= FLAGS_IGNORABLE;
9511         }
9512 
9513         list = define->content;
9514         while (list != NULL) {
9515             ret = xmlRelaxNGElementMatch(ctxt, list, elem);
9516             if (ret == 1) {
9517                 if (ctxt != NULL)
9518                     ctxt->flags = oldflags;
9519                 return (0);
9520             }
9521             if (ret < 0) {
9522                 if (ctxt != NULL)
9523                     ctxt->flags = oldflags;
9524                 return (ret);
9525             }
9526             list = list->next;
9527         }
9528         ret = 1;
9529         if (ctxt != NULL) {
9530             ctxt->flags = oldflags;
9531         }
9532     } else if (define->type == XML_RELAXNG_CHOICE) {
9533         xmlRelaxNGDefinePtr list;
9534 
9535         if (ctxt != NULL) {
9536             oldflags = ctxt->flags;
9537             ctxt->flags |= FLAGS_IGNORABLE;
9538         }
9539 
9540         list = define->nameClass;
9541         while (list != NULL) {
9542             ret = xmlRelaxNGElementMatch(ctxt, list, elem);
9543             if (ret == 1) {
9544                 if (ctxt != NULL)
9545                     ctxt->flags = oldflags;
9546                 return (1);
9547             }
9548             if (ret < 0) {
9549                 if (ctxt != NULL)
9550                     ctxt->flags = oldflags;
9551                 return (ret);
9552             }
9553             list = list->next;
9554         }
9555         if (ctxt != NULL) {
9556             if (ret != 0) {
9557                 if ((ctxt->flags & FLAGS_IGNORABLE) == 0)
9558                     xmlRelaxNGDumpValidError(ctxt);
9559             } else {
9560                 if (ctxt->errNr > 0)
9561                     xmlRelaxNGPopErrors(ctxt, 0);
9562             }
9563         }
9564         ret = 0;
9565         if (ctxt != NULL) {
9566             ctxt->flags = oldflags;
9567         }
9568     } else {
9569         /* TODO */
9570         ret = -1;
9571     }
9572     return (ret);
9573 }
9574 
9575 /**
9576  * xmlRelaxNGBestState:
9577  * @ctxt:  a Relax-NG validation context
9578  *
9579  * Find the "best" state in the ctxt->states list of states to report
9580  * errors about. I.e. a state with no element left in the child list
9581  * or the one with the less attributes left.
9582  * This is called only if a validation error was detected
9583  *
9584  * Returns the index of the "best" state or -1 in case of error
9585  */
9586 static int
xmlRelaxNGBestState(xmlRelaxNGValidCtxtPtr ctxt)9587 xmlRelaxNGBestState(xmlRelaxNGValidCtxtPtr ctxt)
9588 {
9589     xmlRelaxNGValidStatePtr state;
9590     int i, tmp;
9591     int best = -1;
9592     int value = 1000000;
9593 
9594     if ((ctxt == NULL) || (ctxt->states == NULL) ||
9595         (ctxt->states->nbState <= 0))
9596         return (-1);
9597 
9598     for (i = 0; i < ctxt->states->nbState; i++) {
9599         state = ctxt->states->tabState[i];
9600         if (state == NULL)
9601             continue;
9602         if (state->seq != NULL) {
9603             if ((best == -1) || (value > 100000)) {
9604                 value = 100000;
9605                 best = i;
9606             }
9607         } else {
9608             tmp = state->nbAttrLeft;
9609             if ((best == -1) || (value > tmp)) {
9610                 value = tmp;
9611                 best = i;
9612             }
9613         }
9614     }
9615     return (best);
9616 }
9617 
9618 /**
9619  * xmlRelaxNGLogBestError:
9620  * @ctxt:  a Relax-NG validation context
9621  *
9622  * Find the "best" state in the ctxt->states list of states to report
9623  * errors about and log it.
9624  */
9625 static void
xmlRelaxNGLogBestError(xmlRelaxNGValidCtxtPtr ctxt)9626 xmlRelaxNGLogBestError(xmlRelaxNGValidCtxtPtr ctxt)
9627 {
9628     int best;
9629 
9630     if ((ctxt == NULL) || (ctxt->states == NULL) ||
9631         (ctxt->states->nbState <= 0))
9632         return;
9633 
9634     best = xmlRelaxNGBestState(ctxt);
9635     if ((best >= 0) && (best < ctxt->states->nbState)) {
9636         ctxt->state = ctxt->states->tabState[best];
9637 
9638         xmlRelaxNGValidateElementEnd(ctxt, 1);
9639     }
9640 }
9641 
9642 /**
9643  * xmlRelaxNGValidateElementEnd:
9644  * @ctxt:  a Relax-NG validation context
9645  * @dolog:  indicate that error logging should be done
9646  *
9647  * Validate the end of the element, implements check that
9648  * there is nothing left not consumed in the element content
9649  * or in the attribute list.
9650  *
9651  * Returns 0 if the validation succeeded or an error code.
9652  */
9653 static int
xmlRelaxNGValidateElementEnd(xmlRelaxNGValidCtxtPtr ctxt,int dolog)9654 xmlRelaxNGValidateElementEnd(xmlRelaxNGValidCtxtPtr ctxt, int dolog)
9655 {
9656     int i;
9657     xmlRelaxNGValidStatePtr state;
9658 
9659     state = ctxt->state;
9660     if (state->seq != NULL) {
9661         state->seq = xmlRelaxNGSkipIgnored(ctxt, state->seq);
9662         if (state->seq != NULL) {
9663             if (dolog) {
9664                 VALID_ERR3(XML_RELAXNG_ERR_EXTRACONTENT,
9665                            state->node->name, state->seq->name);
9666             }
9667             return (-1);
9668         }
9669     }
9670     for (i = 0; i < state->nbAttrs; i++) {
9671         if (state->attrs[i] != NULL) {
9672             if (dolog) {
9673                 VALID_ERR3(XML_RELAXNG_ERR_INVALIDATTR,
9674                            state->attrs[i]->name, state->node->name);
9675             }
9676             return (-1 - i);
9677         }
9678     }
9679     return (0);
9680 }
9681 
9682 /**
9683  * xmlRelaxNGValidateState:
9684  * @ctxt:  a Relax-NG validation context
9685  * @define:  the definition to verify
9686  *
9687  * Validate the current state against the definition
9688  *
9689  * Returns 0 if the validation succeeded or an error code.
9690  */
9691 static int
xmlRelaxNGValidateState(xmlRelaxNGValidCtxtPtr ctxt,xmlRelaxNGDefinePtr define)9692 xmlRelaxNGValidateState(xmlRelaxNGValidCtxtPtr ctxt,
9693                         xmlRelaxNGDefinePtr define)
9694 {
9695     xmlNodePtr node;
9696     int ret = 0, i, tmp, oldflags, errNr;
9697     xmlRelaxNGValidStatePtr oldstate = NULL, state;
9698 
9699     if (define == NULL) {
9700         VALID_ERR(XML_RELAXNG_ERR_NODEFINE);
9701         return (-1);
9702     }
9703 
9704     if (ctxt->state != NULL) {
9705         node = ctxt->state->seq;
9706     } else {
9707         node = NULL;
9708     }
9709     ctxt->depth++;
9710     switch (define->type) {
9711         case XML_RELAXNG_EMPTY:
9712             ret = 0;
9713             break;
9714         case XML_RELAXNG_NOT_ALLOWED:
9715             ret = -1;
9716             break;
9717         case XML_RELAXNG_TEXT:
9718             while ((node != NULL) &&
9719                    ((node->type == XML_TEXT_NODE) ||
9720                     (node->type == XML_COMMENT_NODE) ||
9721                     (node->type == XML_PI_NODE) ||
9722                     (node->type == XML_CDATA_SECTION_NODE)))
9723                 node = node->next;
9724             ctxt->state->seq = node;
9725             break;
9726         case XML_RELAXNG_ELEMENT:
9727             errNr = ctxt->errNr;
9728             node = xmlRelaxNGSkipIgnored(ctxt, node);
9729             if (node == NULL) {
9730                 VALID_ERR2(XML_RELAXNG_ERR_NOELEM, define->name);
9731                 ret = -1;
9732                 if ((ctxt->flags & FLAGS_IGNORABLE) == 0)
9733                     xmlRelaxNGDumpValidError(ctxt);
9734                 break;
9735             }
9736             if (node->type != XML_ELEMENT_NODE) {
9737                 VALID_ERR(XML_RELAXNG_ERR_NOTELEM);
9738                 ret = -1;
9739                 if ((ctxt->flags & FLAGS_IGNORABLE) == 0)
9740                     xmlRelaxNGDumpValidError(ctxt);
9741                 break;
9742             }
9743             /*
9744              * This node was already validated successfully against
9745              * this definition.
9746              */
9747             if (node->psvi == define) {
9748                 ctxt->state->seq = xmlRelaxNGSkipIgnored(ctxt, node->next);
9749                 if (ctxt->errNr > errNr)
9750                     xmlRelaxNGPopErrors(ctxt, errNr);
9751                 if (ctxt->errNr != 0) {
9752                     while ((ctxt->err != NULL) &&
9753                            (((ctxt->err->err == XML_RELAXNG_ERR_ELEMNAME)
9754                              && (xmlStrEqual(ctxt->err->arg2, node->name)))
9755                             ||
9756                             ((ctxt->err->err ==
9757                               XML_RELAXNG_ERR_ELEMEXTRANS)
9758                              && (xmlStrEqual(ctxt->err->arg1, node->name)))
9759                             || (ctxt->err->err == XML_RELAXNG_ERR_NOELEM)
9760                             || (ctxt->err->err ==
9761                                 XML_RELAXNG_ERR_NOTELEM)))
9762                         xmlRelaxNGValidErrorPop(ctxt);
9763                 }
9764                 break;
9765             }
9766 
9767             ret = xmlRelaxNGElementMatch(ctxt, define, node);
9768             if (ret <= 0) {
9769                 ret = -1;
9770                 if ((ctxt->flags & FLAGS_IGNORABLE) == 0)
9771                     xmlRelaxNGDumpValidError(ctxt);
9772                 break;
9773             }
9774             ret = 0;
9775             if (ctxt->errNr != 0) {
9776                 if (ctxt->errNr > errNr)
9777                     xmlRelaxNGPopErrors(ctxt, errNr);
9778                 while ((ctxt->err != NULL) &&
9779                        (((ctxt->err->err == XML_RELAXNG_ERR_ELEMNAME) &&
9780                          (xmlStrEqual(ctxt->err->arg2, node->name))) ||
9781                         ((ctxt->err->err == XML_RELAXNG_ERR_ELEMEXTRANS) &&
9782                          (xmlStrEqual(ctxt->err->arg1, node->name))) ||
9783                         (ctxt->err->err == XML_RELAXNG_ERR_NOELEM) ||
9784                         (ctxt->err->err == XML_RELAXNG_ERR_NOTELEM)))
9785                     xmlRelaxNGValidErrorPop(ctxt);
9786             }
9787             errNr = ctxt->errNr;
9788 
9789             oldflags = ctxt->flags;
9790             if (ctxt->flags & FLAGS_MIXED_CONTENT) {
9791                 ctxt->flags -= FLAGS_MIXED_CONTENT;
9792             }
9793             state = xmlRelaxNGNewValidState(ctxt, node);
9794             if (state == NULL) {
9795                 ret = -1;
9796                 if ((ctxt->flags & FLAGS_IGNORABLE) == 0)
9797                     xmlRelaxNGDumpValidError(ctxt);
9798                 break;
9799             }
9800 
9801             oldstate = ctxt->state;
9802             ctxt->state = state;
9803             if (define->attrs != NULL) {
9804                 tmp = xmlRelaxNGValidateAttributeList(ctxt, define->attrs);
9805                 if (tmp != 0) {
9806                     ret = -1;
9807                     VALID_ERR2(XML_RELAXNG_ERR_ATTRVALID, node->name);
9808                 }
9809             }
9810             if (define->contModel != NULL) {
9811                 xmlRelaxNGValidStatePtr nstate, tmpstate = ctxt->state;
9812                 xmlRelaxNGStatesPtr tmpstates = ctxt->states;
9813                 xmlNodePtr nseq;
9814 
9815                 nstate = xmlRelaxNGNewValidState(ctxt, node);
9816                 ctxt->state = nstate;
9817                 ctxt->states = NULL;
9818 
9819                 tmp = xmlRelaxNGValidateCompiledContent(ctxt,
9820                                                         define->contModel,
9821                                                         ctxt->state->seq);
9822                 nseq = ctxt->state->seq;
9823                 ctxt->state = tmpstate;
9824                 ctxt->states = tmpstates;
9825                 xmlRelaxNGFreeValidState(ctxt, nstate);
9826 
9827                 if (tmp != 0)
9828                     ret = -1;
9829 
9830                 if (ctxt->states != NULL) {
9831                     tmp = -1;
9832 
9833                     for (i = 0; i < ctxt->states->nbState; i++) {
9834                         state = ctxt->states->tabState[i];
9835                         ctxt->state = state;
9836                         ctxt->state->seq = nseq;
9837 
9838                         if (xmlRelaxNGValidateElementEnd(ctxt, 0) == 0) {
9839                             tmp = 0;
9840                             break;
9841                         }
9842                     }
9843                     if (tmp != 0) {
9844                         /*
9845                          * validation error, log the message for the "best" one
9846                          */
9847                         ctxt->flags |= FLAGS_IGNORABLE;
9848                         xmlRelaxNGLogBestError(ctxt);
9849                     }
9850                     for (i = 0; i < ctxt->states->nbState; i++) {
9851                         xmlRelaxNGFreeValidState(ctxt,
9852                                                  ctxt->states->
9853                                                  tabState[i]);
9854                     }
9855                     xmlRelaxNGFreeStates(ctxt, ctxt->states);
9856                     ctxt->flags = oldflags;
9857                     ctxt->states = NULL;
9858                     if ((ret == 0) && (tmp == -1))
9859                         ret = -1;
9860                 } else {
9861                     state = ctxt->state;
9862 		    if (ctxt->state != NULL)
9863 			ctxt->state->seq = nseq;
9864                     if (ret == 0)
9865                         ret = xmlRelaxNGValidateElementEnd(ctxt, 1);
9866                     xmlRelaxNGFreeValidState(ctxt, state);
9867                 }
9868             } else {
9869                 if (define->content != NULL) {
9870                     tmp = xmlRelaxNGValidateDefinitionList(ctxt,
9871                                                            define->
9872                                                            content);
9873                     if (tmp != 0) {
9874                         ret = -1;
9875                         if (ctxt->state == NULL) {
9876                             ctxt->state = oldstate;
9877                             VALID_ERR2(XML_RELAXNG_ERR_CONTENTVALID,
9878                                        node->name);
9879                             ctxt->state = NULL;
9880                         } else {
9881                             VALID_ERR2(XML_RELAXNG_ERR_CONTENTVALID,
9882                                        node->name);
9883                         }
9884 
9885                     }
9886                 }
9887                 if (ctxt->states != NULL) {
9888                     tmp = -1;
9889 
9890                     for (i = 0; i < ctxt->states->nbState; i++) {
9891                         state = ctxt->states->tabState[i];
9892                         ctxt->state = state;
9893 
9894                         if (xmlRelaxNGValidateElementEnd(ctxt, 0) == 0) {
9895                             tmp = 0;
9896                             break;
9897                         }
9898                     }
9899                     if (tmp != 0) {
9900                         /*
9901                          * validation error, log the message for the "best" one
9902                          */
9903                         ctxt->flags |= FLAGS_IGNORABLE;
9904                         xmlRelaxNGLogBestError(ctxt);
9905                     }
9906                     for (i = 0; i < ctxt->states->nbState; i++) {
9907                         xmlRelaxNGFreeValidState(ctxt,
9908                                                  ctxt->states->tabState[i]);
9909                         ctxt->states->tabState[i] = NULL;
9910                     }
9911                     xmlRelaxNGFreeStates(ctxt, ctxt->states);
9912                     ctxt->flags = oldflags;
9913                     ctxt->states = NULL;
9914                     if ((ret == 0) && (tmp == -1))
9915                         ret = -1;
9916                 } else {
9917                     state = ctxt->state;
9918                     if (ret == 0)
9919                         ret = xmlRelaxNGValidateElementEnd(ctxt, 1);
9920                     xmlRelaxNGFreeValidState(ctxt, state);
9921                 }
9922             }
9923             if (ret == 0) {
9924                 node->psvi = define;
9925             }
9926             ctxt->flags = oldflags;
9927             ctxt->state = oldstate;
9928             if (oldstate != NULL)
9929                 oldstate->seq = xmlRelaxNGSkipIgnored(ctxt, node->next);
9930             if (ret != 0) {
9931                 if ((ctxt->flags & FLAGS_IGNORABLE) == 0) {
9932                     xmlRelaxNGDumpValidError(ctxt);
9933                     ret = 0;
9934 #if 0
9935                 } else {
9936                     ret = -2;
9937 #endif
9938                 }
9939             } else {
9940                 if (ctxt->errNr > errNr)
9941                     xmlRelaxNGPopErrors(ctxt, errNr);
9942             }
9943 
9944             break;
9945         case XML_RELAXNG_OPTIONAL:{
9946                 errNr = ctxt->errNr;
9947                 oldflags = ctxt->flags;
9948                 ctxt->flags |= FLAGS_IGNORABLE;
9949                 oldstate = xmlRelaxNGCopyValidState(ctxt, ctxt->state);
9950                 ret =
9951                     xmlRelaxNGValidateDefinitionList(ctxt,
9952                                                      define->content);
9953                 if (ret != 0) {
9954                     if (ctxt->state != NULL)
9955                         xmlRelaxNGFreeValidState(ctxt, ctxt->state);
9956                     ctxt->state = oldstate;
9957                     ctxt->flags = oldflags;
9958                     ret = 0;
9959                     if (ctxt->errNr > errNr)
9960                         xmlRelaxNGPopErrors(ctxt, errNr);
9961                     break;
9962                 }
9963                 if (ctxt->states != NULL) {
9964                     xmlRelaxNGAddStates(ctxt, ctxt->states, oldstate);
9965                 } else {
9966                     ctxt->states = xmlRelaxNGNewStates(ctxt, 1);
9967                     if (ctxt->states == NULL) {
9968                         xmlRelaxNGFreeValidState(ctxt, oldstate);
9969                         ctxt->flags = oldflags;
9970                         ret = -1;
9971                         if (ctxt->errNr > errNr)
9972                             xmlRelaxNGPopErrors(ctxt, errNr);
9973                         break;
9974                     }
9975                     xmlRelaxNGAddStates(ctxt, ctxt->states, oldstate);
9976                     xmlRelaxNGAddStates(ctxt, ctxt->states, ctxt->state);
9977                     ctxt->state = NULL;
9978                 }
9979                 ctxt->flags = oldflags;
9980                 ret = 0;
9981                 if (ctxt->errNr > errNr)
9982                     xmlRelaxNGPopErrors(ctxt, errNr);
9983                 break;
9984             }
9985         case XML_RELAXNG_ONEORMORE:
9986             errNr = ctxt->errNr;
9987             ret = xmlRelaxNGValidateDefinitionList(ctxt, define->content);
9988             if (ret != 0) {
9989                 break;
9990             }
9991             if (ctxt->errNr > errNr)
9992                 xmlRelaxNGPopErrors(ctxt, errNr);
9993             /* Falls through. */
9994         case XML_RELAXNG_ZEROORMORE:{
9995                 int progress;
9996                 xmlRelaxNGStatesPtr states = NULL, res = NULL;
9997                 int base, j;
9998 
9999                 errNr = ctxt->errNr;
10000                 res = xmlRelaxNGNewStates(ctxt, 1);
10001                 if (res == NULL) {
10002                     ret = -1;
10003                     break;
10004                 }
10005                 /*
10006                  * All the input states are also exit states
10007                  */
10008                 if (ctxt->state != NULL) {
10009                     xmlRelaxNGAddStates(ctxt, res,
10010                                         xmlRelaxNGCopyValidState(ctxt,
10011                                                                  ctxt->
10012                                                                  state));
10013                 } else {
10014                     for (j = 0; j < ctxt->states->nbState; j++) {
10015                         xmlRelaxNGAddStates(ctxt, res,
10016                             xmlRelaxNGCopyValidState(ctxt,
10017                                             ctxt->states->tabState[j]));
10018                     }
10019                 }
10020                 oldflags = ctxt->flags;
10021                 ctxt->flags |= FLAGS_IGNORABLE;
10022                 do {
10023                     progress = 0;
10024                     base = res->nbState;
10025 
10026                     if (ctxt->states != NULL) {
10027                         states = ctxt->states;
10028                         for (i = 0; i < states->nbState; i++) {
10029                             ctxt->state = states->tabState[i];
10030                             ctxt->states = NULL;
10031                             ret = xmlRelaxNGValidateDefinitionList(ctxt,
10032                                                                    define->
10033                                                                    content);
10034                             if (ret == 0) {
10035                                 if (ctxt->state != NULL) {
10036                                     tmp = xmlRelaxNGAddStates(ctxt, res,
10037                                                               ctxt->state);
10038                                     ctxt->state = NULL;
10039                                     if (tmp == 1)
10040                                         progress = 1;
10041                                 } else if (ctxt->states != NULL) {
10042                                     for (j = 0; j < ctxt->states->nbState;
10043                                          j++) {
10044                                         tmp =
10045                                             xmlRelaxNGAddStates(ctxt, res,
10046                                                    ctxt->states->tabState[j]);
10047                                         if (tmp == 1)
10048                                             progress = 1;
10049                                     }
10050                                     xmlRelaxNGFreeStates(ctxt,
10051                                                          ctxt->states);
10052                                     ctxt->states = NULL;
10053                                 }
10054                             } else {
10055                                 if (ctxt->state != NULL) {
10056                                     xmlRelaxNGFreeValidState(ctxt,
10057                                                              ctxt->state);
10058                                     ctxt->state = NULL;
10059                                 }
10060                             }
10061                         }
10062                     } else {
10063                         ret = xmlRelaxNGValidateDefinitionList(ctxt,
10064                                                                define->
10065                                                                content);
10066                         if (ret != 0) {
10067                             xmlRelaxNGFreeValidState(ctxt, ctxt->state);
10068                             ctxt->state = NULL;
10069                         } else {
10070                             base = res->nbState;
10071                             if (ctxt->state != NULL) {
10072                                 tmp = xmlRelaxNGAddStates(ctxt, res,
10073                                                           ctxt->state);
10074                                 ctxt->state = NULL;
10075                                 if (tmp == 1)
10076                                     progress = 1;
10077                             } else if (ctxt->states != NULL) {
10078                                 for (j = 0; j < ctxt->states->nbState; j++) {
10079                                     tmp = xmlRelaxNGAddStates(ctxt, res,
10080                                                ctxt->states->tabState[j]);
10081                                     if (tmp == 1)
10082                                         progress = 1;
10083                                 }
10084                                 if (states == NULL) {
10085                                     states = ctxt->states;
10086                                 } else {
10087                                     xmlRelaxNGFreeStates(ctxt,
10088                                                          ctxt->states);
10089                                 }
10090                                 ctxt->states = NULL;
10091                             }
10092                         }
10093                     }
10094                     if (progress) {
10095                         /*
10096                          * Collect all the new nodes added at that step
10097                          * and make them the new node set
10098                          */
10099                         if (res->nbState - base == 1) {
10100                             ctxt->state = xmlRelaxNGCopyValidState(ctxt,
10101                                                                    res->
10102                                                                    tabState
10103                                                                    [base]);
10104                         } else {
10105                             if (states == NULL) {
10106                                 xmlRelaxNGNewStates(ctxt,
10107                                                     res->nbState - base);
10108 			        states = ctxt->states;
10109 				if (states == NULL) {
10110 				    progress = 0;
10111 				    break;
10112 				}
10113                             }
10114                             states->nbState = 0;
10115                             for (i = base; i < res->nbState; i++)
10116                                 xmlRelaxNGAddStates(ctxt, states,
10117                                                     xmlRelaxNGCopyValidState
10118                                                     (ctxt, res->tabState[i]));
10119                             ctxt->states = states;
10120                         }
10121                     }
10122                 } while (progress == 1);
10123                 if (states != NULL) {
10124                     xmlRelaxNGFreeStates(ctxt, states);
10125                 }
10126                 ctxt->states = res;
10127                 ctxt->flags = oldflags;
10128 #if 0
10129                 /*
10130                  * errors may have to be propagated back...
10131                  */
10132                 if (ctxt->errNr > errNr)
10133                     xmlRelaxNGPopErrors(ctxt, errNr);
10134 #endif
10135                 ret = 0;
10136                 break;
10137             }
10138         case XML_RELAXNG_CHOICE:{
10139                 xmlRelaxNGDefinePtr list = NULL;
10140                 xmlRelaxNGStatesPtr states = NULL;
10141 
10142                 node = xmlRelaxNGSkipIgnored(ctxt, node);
10143 
10144                 errNr = ctxt->errNr;
10145                 if ((define->dflags & IS_TRIABLE) && (define->data != NULL) &&
10146 		    (node != NULL)) {
10147 		    /*
10148 		     * node == NULL can't be optimized since IS_TRIABLE
10149 		     * doesn't account for choice which may lead to
10150 		     * only attributes.
10151 		     */
10152                     xmlHashTablePtr triage =
10153                         (xmlHashTablePtr) define->data;
10154 
10155                     /*
10156                      * Something we can optimize cleanly there is only one
10157                      * possible branch out !
10158                      */
10159                     if ((node->type == XML_TEXT_NODE) ||
10160                         (node->type == XML_CDATA_SECTION_NODE)) {
10161                         list =
10162                             xmlHashLookup2(triage, BAD_CAST "#text", NULL);
10163                     } else if (node->type == XML_ELEMENT_NODE) {
10164                         if (node->ns != NULL) {
10165                             list = xmlHashLookup2(triage, node->name,
10166                                                   node->ns->href);
10167                             if (list == NULL)
10168                                 list =
10169                                     xmlHashLookup2(triage, BAD_CAST "#any",
10170                                                    node->ns->href);
10171                         } else
10172                             list =
10173                                 xmlHashLookup2(triage, node->name, NULL);
10174                         if (list == NULL)
10175                             list =
10176                                 xmlHashLookup2(triage, BAD_CAST "#any",
10177                                                NULL);
10178                     }
10179                     if (list == NULL) {
10180                         ret = -1;
10181 			VALID_ERR2(XML_RELAXNG_ERR_ELEMWRONG, node->name);
10182                         break;
10183                     }
10184                     ret = xmlRelaxNGValidateDefinition(ctxt, list);
10185                     if (ret == 0) {
10186                     }
10187                     break;
10188                 }
10189 
10190                 list = define->content;
10191                 oldflags = ctxt->flags;
10192                 ctxt->flags |= FLAGS_IGNORABLE;
10193 
10194                 while (list != NULL) {
10195                     oldstate = xmlRelaxNGCopyValidState(ctxt, ctxt->state);
10196                     ret = xmlRelaxNGValidateDefinition(ctxt, list);
10197                     if (ret == 0) {
10198                         if (states == NULL) {
10199                             states = xmlRelaxNGNewStates(ctxt, 1);
10200                         }
10201                         if (ctxt->state != NULL) {
10202                             xmlRelaxNGAddStates(ctxt, states, ctxt->state);
10203                         } else if (ctxt->states != NULL) {
10204                             for (i = 0; i < ctxt->states->nbState; i++) {
10205                                 xmlRelaxNGAddStates(ctxt, states,
10206                                                     ctxt->states->
10207                                                     tabState[i]);
10208                             }
10209                             xmlRelaxNGFreeStates(ctxt, ctxt->states);
10210                             ctxt->states = NULL;
10211                         }
10212                     } else {
10213                         xmlRelaxNGFreeValidState(ctxt, ctxt->state);
10214                     }
10215                     ctxt->state = oldstate;
10216                     list = list->next;
10217                 }
10218                 if (states != NULL) {
10219                     xmlRelaxNGFreeValidState(ctxt, oldstate);
10220                     ctxt->states = states;
10221                     ctxt->state = NULL;
10222                     ret = 0;
10223                 } else {
10224                     ctxt->states = NULL;
10225                 }
10226                 ctxt->flags = oldflags;
10227                 if (ret != 0) {
10228                     if ((ctxt->flags & FLAGS_IGNORABLE) == 0) {
10229                         xmlRelaxNGDumpValidError(ctxt);
10230                     }
10231                 } else {
10232                     if (ctxt->errNr > errNr)
10233                         xmlRelaxNGPopErrors(ctxt, errNr);
10234                 }
10235                 break;
10236             }
10237         case XML_RELAXNG_DEF:
10238         case XML_RELAXNG_GROUP:
10239             ret = xmlRelaxNGValidateDefinitionList(ctxt, define->content);
10240             break;
10241         case XML_RELAXNG_INTERLEAVE:
10242             ret = xmlRelaxNGValidateInterleave(ctxt, define);
10243             break;
10244         case XML_RELAXNG_ATTRIBUTE:
10245             ret = xmlRelaxNGValidateAttribute(ctxt, define);
10246             break;
10247         case XML_RELAXNG_START:
10248         case XML_RELAXNG_NOOP:
10249         case XML_RELAXNG_REF:
10250         case XML_RELAXNG_EXTERNALREF:
10251         case XML_RELAXNG_PARENTREF:
10252             ret = xmlRelaxNGValidateDefinition(ctxt, define->content);
10253             break;
10254         case XML_RELAXNG_DATATYPE:{
10255                 xmlNodePtr child;
10256                 xmlChar *content = NULL;
10257 
10258                 child = node;
10259                 while (child != NULL) {
10260                     if (child->type == XML_ELEMENT_NODE) {
10261                         VALID_ERR2(XML_RELAXNG_ERR_DATAELEM,
10262                                    node->parent->name);
10263                         ret = -1;
10264                         break;
10265                     } else if ((child->type == XML_TEXT_NODE) ||
10266                                (child->type == XML_CDATA_SECTION_NODE)) {
10267                         content = xmlStrcat(content, child->content);
10268                     }
10269                     /* TODO: handle entities ... */
10270                     child = child->next;
10271                 }
10272                 if (ret == -1) {
10273                     if (content != NULL)
10274                         xmlFree(content);
10275                     break;
10276                 }
10277                 if (content == NULL) {
10278                     content = xmlStrdup(BAD_CAST "");
10279                     if (content == NULL) {
10280                         xmlRngVErrMemory(ctxt);
10281                         ret = -1;
10282                         break;
10283                     }
10284                 }
10285                 ret = xmlRelaxNGValidateDatatype(ctxt, content, define,
10286                                                  ctxt->state->seq);
10287                 if (ret == -1) {
10288                     VALID_ERR2(XML_RELAXNG_ERR_DATATYPE, define->name);
10289                 } else if (ret == 0) {
10290                     ctxt->state->seq = NULL;
10291                 }
10292                 if (content != NULL)
10293                     xmlFree(content);
10294                 break;
10295             }
10296         case XML_RELAXNG_VALUE:{
10297                 xmlChar *content = NULL;
10298                 xmlChar *oldvalue;
10299                 xmlNodePtr child;
10300 
10301                 child = node;
10302                 while (child != NULL) {
10303                     if (child->type == XML_ELEMENT_NODE) {
10304                         VALID_ERR2(XML_RELAXNG_ERR_VALELEM,
10305                                    node->parent->name);
10306                         ret = -1;
10307                         break;
10308                     } else if ((child->type == XML_TEXT_NODE) ||
10309                                (child->type == XML_CDATA_SECTION_NODE)) {
10310                         content = xmlStrcat(content, child->content);
10311                     }
10312                     /* TODO: handle entities ... */
10313                     child = child->next;
10314                 }
10315                 if (ret == -1) {
10316                     if (content != NULL)
10317                         xmlFree(content);
10318                     break;
10319                 }
10320                 if (content == NULL) {
10321                     content = xmlStrdup(BAD_CAST "");
10322                     if (content == NULL) {
10323                         xmlRngVErrMemory(ctxt);
10324                         ret = -1;
10325                         break;
10326                     }
10327                 }
10328                 oldvalue = ctxt->state->value;
10329                 ctxt->state->value = content;
10330                 ret = xmlRelaxNGValidateValue(ctxt, define);
10331                 ctxt->state->value = oldvalue;
10332                 if (ret == -1) {
10333                     VALID_ERR2(XML_RELAXNG_ERR_VALUE, define->name);
10334                 } else if (ret == 0) {
10335                     ctxt->state->seq = NULL;
10336                 }
10337                 if (content != NULL)
10338                     xmlFree(content);
10339                 break;
10340             }
10341         case XML_RELAXNG_LIST:{
10342                 xmlChar *content;
10343                 xmlNodePtr child;
10344                 xmlChar *oldvalue, *oldendvalue;
10345                 int len;
10346 
10347                 /*
10348                  * Make sure it's only text nodes
10349                  */
10350 
10351                 content = NULL;
10352                 child = node;
10353                 while (child != NULL) {
10354                     if (child->type == XML_ELEMENT_NODE) {
10355                         VALID_ERR2(XML_RELAXNG_ERR_LISTELEM,
10356                                    node->parent->name);
10357                         ret = -1;
10358                         break;
10359                     } else if ((child->type == XML_TEXT_NODE) ||
10360                                (child->type == XML_CDATA_SECTION_NODE)) {
10361                         content = xmlStrcat(content, child->content);
10362                     }
10363                     /* TODO: handle entities ... */
10364                     child = child->next;
10365                 }
10366                 if (ret == -1) {
10367                     if (content != NULL)
10368                         xmlFree(content);
10369                     break;
10370                 }
10371                 if (content == NULL) {
10372                     content = xmlStrdup(BAD_CAST "");
10373                     if (content == NULL) {
10374                         xmlRngVErrMemory(ctxt);
10375                         ret = -1;
10376                         break;
10377                     }
10378                 }
10379                 len = xmlStrlen(content);
10380                 oldvalue = ctxt->state->value;
10381                 oldendvalue = ctxt->state->endvalue;
10382                 ctxt->state->value = content;
10383                 ctxt->state->endvalue = content + len;
10384                 ret = xmlRelaxNGValidateValue(ctxt, define);
10385                 ctxt->state->value = oldvalue;
10386                 ctxt->state->endvalue = oldendvalue;
10387                 if (ret == -1) {
10388                     VALID_ERR(XML_RELAXNG_ERR_LIST);
10389                 } else if ((ret == 0) && (node != NULL)) {
10390                     ctxt->state->seq = node->next;
10391                 }
10392                 if (content != NULL)
10393                     xmlFree(content);
10394                 break;
10395             }
10396         case XML_RELAXNG_EXCEPT:
10397         case XML_RELAXNG_PARAM:
10398             /* TODO */
10399             ret = -1;
10400             break;
10401     }
10402     ctxt->depth--;
10403     return (ret);
10404 }
10405 
10406 /**
10407  * xmlRelaxNGValidateDefinition:
10408  * @ctxt:  a Relax-NG validation context
10409  * @define:  the definition to verify
10410  *
10411  * Validate the current node lists against the definition
10412  *
10413  * Returns 0 if the validation succeeded or an error code.
10414  */
10415 static int
xmlRelaxNGValidateDefinition(xmlRelaxNGValidCtxtPtr ctxt,xmlRelaxNGDefinePtr define)10416 xmlRelaxNGValidateDefinition(xmlRelaxNGValidCtxtPtr ctxt,
10417                              xmlRelaxNGDefinePtr define)
10418 {
10419     xmlRelaxNGStatesPtr states, res;
10420     int i, j, k, ret, oldflags;
10421 
10422     /*
10423      * We should NOT have both ctxt->state and ctxt->states
10424      */
10425     if ((ctxt->state != NULL) && (ctxt->states != NULL)) {
10426         /* TODO */
10427         xmlRelaxNGFreeValidState(ctxt, ctxt->state);
10428         ctxt->state = NULL;
10429     }
10430 
10431     if ((ctxt->states == NULL) || (ctxt->states->nbState == 1)) {
10432         if (ctxt->states != NULL) {
10433             ctxt->state = ctxt->states->tabState[0];
10434             xmlRelaxNGFreeStates(ctxt, ctxt->states);
10435             ctxt->states = NULL;
10436         }
10437         ret = xmlRelaxNGValidateState(ctxt, define);
10438         if ((ctxt->state != NULL) && (ctxt->states != NULL)) {
10439             /* TODO */
10440             xmlRelaxNGFreeValidState(ctxt, ctxt->state);
10441             ctxt->state = NULL;
10442         }
10443         if ((ctxt->states != NULL) && (ctxt->states->nbState == 1)) {
10444             ctxt->state = ctxt->states->tabState[0];
10445             xmlRelaxNGFreeStates(ctxt, ctxt->states);
10446             ctxt->states = NULL;
10447         }
10448         return (ret);
10449     }
10450 
10451     states = ctxt->states;
10452     ctxt->states = NULL;
10453     res = NULL;
10454     j = 0;
10455     oldflags = ctxt->flags;
10456     ctxt->flags |= FLAGS_IGNORABLE;
10457     for (i = 0; i < states->nbState; i++) {
10458         ctxt->state = states->tabState[i];
10459         ctxt->states = NULL;
10460         ret = xmlRelaxNGValidateState(ctxt, define);
10461         /*
10462          * We should NOT have both ctxt->state and ctxt->states
10463          */
10464         if ((ctxt->state != NULL) && (ctxt->states != NULL)) {
10465             /* TODO */
10466             xmlRelaxNGFreeValidState(ctxt, ctxt->state);
10467             ctxt->state = NULL;
10468         }
10469         if (ret == 0) {
10470             if (ctxt->states == NULL) {
10471                 if (res != NULL) {
10472                     /* add the state to the container */
10473                     xmlRelaxNGAddStates(ctxt, res, ctxt->state);
10474                     ctxt->state = NULL;
10475                 } else {
10476                     /* add the state directly in states */
10477                     states->tabState[j++] = ctxt->state;
10478                     ctxt->state = NULL;
10479                 }
10480             } else {
10481                 if (res == NULL) {
10482                     /* make it the new container and copy other results */
10483                     res = ctxt->states;
10484                     ctxt->states = NULL;
10485                     for (k = 0; k < j; k++)
10486                         xmlRelaxNGAddStates(ctxt, res,
10487                                             states->tabState[k]);
10488                 } else {
10489                     /* add all the new results to res and reff the container */
10490                     for (k = 0; k < ctxt->states->nbState; k++)
10491                         xmlRelaxNGAddStates(ctxt, res,
10492                                             ctxt->states->tabState[k]);
10493                     xmlRelaxNGFreeStates(ctxt, ctxt->states);
10494                     ctxt->states = NULL;
10495                 }
10496             }
10497         } else {
10498             if (ctxt->state != NULL) {
10499                 xmlRelaxNGFreeValidState(ctxt, ctxt->state);
10500                 ctxt->state = NULL;
10501             } else if (ctxt->states != NULL) {
10502                 for (k = 0; k < ctxt->states->nbState; k++)
10503                     xmlRelaxNGFreeValidState(ctxt,
10504                                              ctxt->states->tabState[k]);
10505                 xmlRelaxNGFreeStates(ctxt, ctxt->states);
10506                 ctxt->states = NULL;
10507             }
10508         }
10509     }
10510     ctxt->flags = oldflags;
10511     if (res != NULL) {
10512         xmlRelaxNGFreeStates(ctxt, states);
10513         ctxt->states = res;
10514         ret = 0;
10515     } else if (j > 1) {
10516         states->nbState = j;
10517         ctxt->states = states;
10518         ret = 0;
10519     } else if (j == 1) {
10520         ctxt->state = states->tabState[0];
10521         xmlRelaxNGFreeStates(ctxt, states);
10522         ret = 0;
10523     } else {
10524         ret = -1;
10525         xmlRelaxNGFreeStates(ctxt, states);
10526         if (ctxt->states != NULL) {
10527             xmlRelaxNGFreeStates(ctxt, ctxt->states);
10528             ctxt->states = NULL;
10529         }
10530     }
10531     if ((ctxt->state != NULL) && (ctxt->states != NULL)) {
10532         /* TODO */
10533         xmlRelaxNGFreeValidState(ctxt, ctxt->state);
10534         ctxt->state = NULL;
10535     }
10536     return (ret);
10537 }
10538 
10539 /**
10540  * xmlRelaxNGValidateDocument:
10541  * @ctxt:  a Relax-NG validation context
10542  * @doc:  the document
10543  *
10544  * Validate the given document
10545  *
10546  * Returns 0 if the validation succeeded or an error code.
10547  */
10548 static int
xmlRelaxNGValidateDocument(xmlRelaxNGValidCtxtPtr ctxt,xmlDocPtr doc)10549 xmlRelaxNGValidateDocument(xmlRelaxNGValidCtxtPtr ctxt, xmlDocPtr doc)
10550 {
10551     int ret;
10552     xmlRelaxNGPtr schema;
10553     xmlRelaxNGGrammarPtr grammar;
10554     xmlRelaxNGValidStatePtr state;
10555     xmlNodePtr node;
10556 
10557     if ((ctxt == NULL) || (ctxt->schema == NULL) || (doc == NULL))
10558         return (-1);
10559 
10560     ctxt->errNo = XML_RELAXNG_OK;
10561     schema = ctxt->schema;
10562     grammar = schema->topgrammar;
10563     if (grammar == NULL) {
10564         VALID_ERR(XML_RELAXNG_ERR_NOGRAMMAR);
10565         return (-1);
10566     }
10567     state = xmlRelaxNGNewValidState(ctxt, NULL);
10568     ctxt->state = state;
10569     ret = xmlRelaxNGValidateDefinition(ctxt, grammar->start);
10570     if ((ctxt->state != NULL) && (state->seq != NULL)) {
10571         state = ctxt->state;
10572         node = state->seq;
10573         node = xmlRelaxNGSkipIgnored(ctxt, node);
10574         if (node != NULL) {
10575             if (ret != -1) {
10576                 VALID_ERR(XML_RELAXNG_ERR_EXTRADATA);
10577                 ret = -1;
10578             }
10579         }
10580     } else if (ctxt->states != NULL) {
10581         int i;
10582         int tmp = -1;
10583 
10584         for (i = 0; i < ctxt->states->nbState; i++) {
10585             state = ctxt->states->tabState[i];
10586             node = state->seq;
10587             node = xmlRelaxNGSkipIgnored(ctxt, node);
10588             if (node == NULL)
10589                 tmp = 0;
10590             xmlRelaxNGFreeValidState(ctxt, state);
10591         }
10592         if (tmp == -1) {
10593             if (ret != -1) {
10594                 VALID_ERR(XML_RELAXNG_ERR_EXTRADATA);
10595                 ret = -1;
10596             }
10597         }
10598     }
10599     if (ctxt->state != NULL) {
10600         xmlRelaxNGFreeValidState(ctxt, ctxt->state);
10601         ctxt->state = NULL;
10602     }
10603     if (ret != 0)
10604         xmlRelaxNGDumpValidError(ctxt);
10605 #ifdef LIBXML_VALID_ENABLED
10606     if (ctxt->idref == 1) {
10607         xmlValidCtxt vctxt;
10608 
10609         memset(&vctxt, 0, sizeof(xmlValidCtxt));
10610         vctxt.valid = 1;
10611 
10612         if (ctxt->error == NULL) {
10613             vctxt.error = xmlGenericError;
10614             vctxt.warning = xmlGenericError;
10615             vctxt.userData = xmlGenericErrorContext;
10616         } else {
10617             vctxt.error = ctxt->error;
10618             vctxt.warning = ctxt->warning;
10619             vctxt.userData = ctxt->userData;
10620         }
10621 
10622         if (xmlValidateDocumentFinal(&vctxt, doc) != 1)
10623             ret = -1;
10624     }
10625 #endif /* LIBXML_VALID_ENABLED */
10626     if ((ret == 0) && (ctxt->errNo != XML_RELAXNG_OK))
10627         ret = -1;
10628 
10629     return (ret);
10630 }
10631 
10632 /**
10633  * xmlRelaxNGCleanPSVI:
10634  * @node:  an input element or document
10635  *
10636  * Call this routine to speed up XPath computation on static documents.
10637  * This stamps all the element nodes with the document order
10638  * Like for line information, the order is kept in the element->content
10639  * field, the value stored is actually - the node number (starting at -1)
10640  * to be able to differentiate from line numbers.
10641  *
10642  * Returns the number of elements found in the document or -1 in case
10643  *    of error.
10644  */
10645 static void
xmlRelaxNGCleanPSVI(xmlNodePtr node)10646 xmlRelaxNGCleanPSVI(xmlNodePtr node) {
10647     xmlNodePtr cur;
10648 
10649     if ((node == NULL) ||
10650         ((node->type != XML_ELEMENT_NODE) &&
10651          (node->type != XML_DOCUMENT_NODE) &&
10652          (node->type != XML_HTML_DOCUMENT_NODE)))
10653 	return;
10654     if (node->type == XML_ELEMENT_NODE)
10655         node->psvi = NULL;
10656 
10657     cur = node->children;
10658     while (cur != NULL) {
10659 	if (cur->type == XML_ELEMENT_NODE) {
10660 	    cur->psvi = NULL;
10661 	    if (cur->children != NULL) {
10662 		cur = cur->children;
10663 		continue;
10664 	    }
10665 	}
10666 	if (cur->next != NULL) {
10667 	    cur = cur->next;
10668 	    continue;
10669 	}
10670 	do {
10671 	    cur = cur->parent;
10672 	    if (cur == NULL)
10673 		break;
10674 	    if (cur == node) {
10675 		cur = NULL;
10676 		break;
10677 	    }
10678 	    if (cur->next != NULL) {
10679 		cur = cur->next;
10680 		break;
10681 	    }
10682 	} while (cur != NULL);
10683     }
10684 }
10685 /************************************************************************
10686  *									*
10687  *			Validation interfaces				*
10688  *									*
10689  ************************************************************************/
10690 
10691 /**
10692  * xmlRelaxNGNewValidCtxt:
10693  * @schema:  a precompiled XML RelaxNGs
10694  *
10695  * Create an XML RelaxNGs validation context based on the given schema
10696  *
10697  * Returns the validation context or NULL in case of error
10698  */
10699 xmlRelaxNGValidCtxtPtr
xmlRelaxNGNewValidCtxt(xmlRelaxNGPtr schema)10700 xmlRelaxNGNewValidCtxt(xmlRelaxNGPtr schema)
10701 {
10702     xmlRelaxNGValidCtxtPtr ret;
10703 
10704     ret = (xmlRelaxNGValidCtxtPtr) xmlMalloc(sizeof(xmlRelaxNGValidCtxt));
10705     if (ret == NULL) {
10706         xmlRngVErrMemory(NULL);
10707         return (NULL);
10708     }
10709     memset(ret, 0, sizeof(xmlRelaxNGValidCtxt));
10710     ret->schema = schema;
10711     ret->errNr = 0;
10712     ret->errMax = 0;
10713     ret->err = NULL;
10714     ret->errTab = NULL;
10715     if (schema != NULL)
10716 	ret->idref = schema->idref;
10717     ret->states = NULL;
10718     ret->freeState = NULL;
10719     ret->freeStates = NULL;
10720     ret->errNo = XML_RELAXNG_OK;
10721     return (ret);
10722 }
10723 
10724 /**
10725  * xmlRelaxNGFreeValidCtxt:
10726  * @ctxt:  the schema validation context
10727  *
10728  * Free the resources associated to the schema validation context
10729  */
10730 void
xmlRelaxNGFreeValidCtxt(xmlRelaxNGValidCtxtPtr ctxt)10731 xmlRelaxNGFreeValidCtxt(xmlRelaxNGValidCtxtPtr ctxt)
10732 {
10733     int k;
10734 
10735     if (ctxt == NULL)
10736         return;
10737     if (ctxt->states != NULL)
10738         xmlRelaxNGFreeStates(NULL, ctxt->states);
10739     if (ctxt->freeState != NULL) {
10740         for (k = 0; k < ctxt->freeState->nbState; k++) {
10741             xmlRelaxNGFreeValidState(NULL, ctxt->freeState->tabState[k]);
10742         }
10743         xmlRelaxNGFreeStates(NULL, ctxt->freeState);
10744     }
10745     if (ctxt->freeStates != NULL) {
10746         for (k = 0; k < ctxt->freeStatesNr; k++) {
10747             xmlRelaxNGFreeStates(NULL, ctxt->freeStates[k]);
10748         }
10749         xmlFree(ctxt->freeStates);
10750     }
10751     if (ctxt->errTab != NULL)
10752         xmlFree(ctxt->errTab);
10753     if (ctxt->elemTab != NULL) {
10754         xmlRegExecCtxtPtr exec;
10755 
10756         exec = xmlRelaxNGElemPop(ctxt);
10757         while (exec != NULL) {
10758             xmlRegFreeExecCtxt(exec);
10759             exec = xmlRelaxNGElemPop(ctxt);
10760         }
10761         xmlFree(ctxt->elemTab);
10762     }
10763     xmlFree(ctxt);
10764 }
10765 
10766 /**
10767  * xmlRelaxNGSetValidErrors:
10768  * @ctxt:  a Relax-NG validation context
10769  * @err:  the error function
10770  * @warn: the warning function
10771  * @ctx: the functions context
10772  *
10773  * DEPRECATED: Use xmlRelaxNGSetValidStructuredErrors.
10774  *
10775  * Set the error and warning callback information
10776  */
10777 void
xmlRelaxNGSetValidErrors(xmlRelaxNGValidCtxtPtr ctxt,xmlRelaxNGValidityErrorFunc err,xmlRelaxNGValidityWarningFunc warn,void * ctx)10778 xmlRelaxNGSetValidErrors(xmlRelaxNGValidCtxtPtr ctxt,
10779                          xmlRelaxNGValidityErrorFunc err,
10780                          xmlRelaxNGValidityWarningFunc warn, void *ctx)
10781 {
10782     if (ctxt == NULL)
10783         return;
10784     ctxt->error = err;
10785     ctxt->warning = warn;
10786     ctxt->userData = ctx;
10787     ctxt->serror = NULL;
10788 }
10789 
10790 /**
10791  * xmlRelaxNGSetValidStructuredErrors:
10792  * @ctxt:  a Relax-NG validation context
10793  * @serror:  the structured error function
10794  * @ctx: the functions context
10795  *
10796  * Set the structured error callback
10797  */
10798 void
xmlRelaxNGSetValidStructuredErrors(xmlRelaxNGValidCtxtPtr ctxt,xmlStructuredErrorFunc serror,void * ctx)10799 xmlRelaxNGSetValidStructuredErrors(xmlRelaxNGValidCtxtPtr ctxt,
10800                                    xmlStructuredErrorFunc serror, void *ctx)
10801 {
10802     if (ctxt == NULL)
10803         return;
10804     ctxt->serror = serror;
10805     ctxt->error = NULL;
10806     ctxt->warning = NULL;
10807     ctxt->userData = ctx;
10808 }
10809 
10810 /**
10811  * xmlRelaxNGGetValidErrors:
10812  * @ctxt:  a Relax-NG validation context
10813  * @err:  the error function result
10814  * @warn: the warning function result
10815  * @ctx: the functions context result
10816  *
10817  * Get the error and warning callback information
10818  *
10819  * Returns -1 in case of error and 0 otherwise
10820  */
10821 int
xmlRelaxNGGetValidErrors(xmlRelaxNGValidCtxtPtr ctxt,xmlRelaxNGValidityErrorFunc * err,xmlRelaxNGValidityWarningFunc * warn,void ** ctx)10822 xmlRelaxNGGetValidErrors(xmlRelaxNGValidCtxtPtr ctxt,
10823                          xmlRelaxNGValidityErrorFunc * err,
10824                          xmlRelaxNGValidityWarningFunc * warn, void **ctx)
10825 {
10826     if (ctxt == NULL)
10827         return (-1);
10828     if (err != NULL)
10829         *err = ctxt->error;
10830     if (warn != NULL)
10831         *warn = ctxt->warning;
10832     if (ctx != NULL)
10833         *ctx = ctxt->userData;
10834     return (0);
10835 }
10836 
10837 /**
10838  * xmlRelaxNGValidateDoc:
10839  * @ctxt:  a Relax-NG validation context
10840  * @doc:  a parsed document tree
10841  *
10842  * Validate a document tree in memory.
10843  *
10844  * Returns 0 if the document is valid, a positive error code
10845  *     number otherwise and -1 in case of internal or API error.
10846  */
10847 int
xmlRelaxNGValidateDoc(xmlRelaxNGValidCtxtPtr ctxt,xmlDocPtr doc)10848 xmlRelaxNGValidateDoc(xmlRelaxNGValidCtxtPtr ctxt, xmlDocPtr doc)
10849 {
10850     int ret;
10851 
10852     if ((ctxt == NULL) || (doc == NULL))
10853         return (-1);
10854 
10855     ctxt->doc = doc;
10856 
10857     ret = xmlRelaxNGValidateDocument(ctxt, doc);
10858     /*
10859      * Remove all left PSVI
10860      */
10861     xmlRelaxNGCleanPSVI((xmlNodePtr) doc);
10862 
10863     /*
10864      * TODO: build error codes
10865      */
10866     if (ret == -1)
10867         return (1);
10868     return (ret);
10869 }
10870 
10871 #endif /* LIBXML_SCHEMAS_ENABLED */
10872