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