• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * testrecurse.c: C program to run libxml2 regression tests checking entities
3  *            recursions
4  *
5  * To compile on Unixes:
6  * cc -o testrecurse `xml2-config --cflags` testrecurse.c `xml2-config --libs` -lpthread
7  *
8  * See Copyright for the status of this software.
9  *
10  * daniel@veillard.com
11  */
12 
13 #define XML_DEPRECATED_MEMBER
14 
15 #include "config.h"
16 #include <stdio.h>
17 
18 #include <stdlib.h>
19 #include <string.h>
20 #include <sys/stat.h>
21 
22 #include <libxml/catalog.h>
23 #include <libxml/parser.h>
24 #include <libxml/parserInternals.h>
25 #include <libxml/tree.h>
26 #include <libxml/uri.h>
27 
28 /*
29  * O_BINARY is just for Windows compatibility - if it isn't defined
30  * on this system, avoid any compilation error
31  */
32 #ifdef	O_BINARY
33 #define RD_FLAGS	O_RDONLY | O_BINARY
34 #else
35 #define	RD_FLAGS	O_RDONLY
36 #endif
37 
38 #define OPT_SAX         (1<<0)
39 #define OPT_NO_SUBST    (1<<1)
40 
41 typedef int (*functest) (const char *filename, const char *result,
42                          const char *error, int options);
43 
44 typedef struct testDesc testDesc;
45 typedef testDesc *testDescPtr;
46 struct testDesc {
47     const char *desc; /* description of the test */
48     functest    func; /* function implementing the test */
49     const char *in;   /* glob to path for input files */
50     const char *out;  /* output directory */
51     const char *suffix;/* suffix for output files */
52     const char *err;  /* suffix for error output files */
53     int     options;  /* parser options for the test */
54 };
55 
56 static int checkTestFile(const char *filename);
57 
58 
59 #if defined(_WIN32)
60 
61 #include <windows.h>
62 
63 typedef struct
64 {
65       size_t gl_pathc;    /* Count of paths matched so far  */
66       char **gl_pathv;    /* List of matched pathnames.  */
67       size_t gl_offs;     /* Slots to reserve in 'gl_pathv'.  */
68 } glob_t;
69 
70 #define GLOB_DOOFFS 0
glob(const char * pattern,ATTRIBUTE_UNUSED int flags,ATTRIBUTE_UNUSED int errfunc (const char * epath,int eerrno),glob_t * pglob)71 static int glob(const char *pattern, ATTRIBUTE_UNUSED int flags,
72                 ATTRIBUTE_UNUSED int errfunc(const char *epath, int eerrno),
73                 glob_t *pglob) {
74     glob_t *ret;
75     WIN32_FIND_DATA FindFileData;
76     HANDLE hFind;
77     unsigned int nb_paths = 0;
78     char directory[500];
79     int len;
80 
81     if ((pattern == NULL) || (pglob == NULL)) return(-1);
82 
83     strncpy(directory, pattern, 499);
84     for (len = strlen(directory);len >= 0;len--) {
85         if (directory[len] == '/') {
86 	    len++;
87 	    directory[len] = 0;
88 	    break;
89 	}
90     }
91     if (len <= 0)
92         len = 0;
93 
94 
95     ret = pglob;
96     memset(ret, 0, sizeof(glob_t));
97 
98     hFind = FindFirstFileA(pattern, &FindFileData);
99     if (hFind == INVALID_HANDLE_VALUE)
100         return(0);
101     nb_paths = 20;
102     ret->gl_pathv = (char **) malloc(nb_paths * sizeof(char *));
103     if (ret->gl_pathv == NULL) {
104 	FindClose(hFind);
105         return(-1);
106     }
107     strncpy(directory + len, FindFileData.cFileName, 499 - len);
108     ret->gl_pathv[ret->gl_pathc] = strdup(directory);
109     if (ret->gl_pathv[ret->gl_pathc] == NULL)
110         goto done;
111     ret->gl_pathc++;
112     while(FindNextFileA(hFind, &FindFileData)) {
113         if (FindFileData.cFileName[0] == '.')
114 	    continue;
115         if (ret->gl_pathc + 2 > nb_paths) {
116             char **tmp = realloc(ret->gl_pathv, nb_paths * 2 * sizeof(char *));
117             if (tmp == NULL)
118                 break;
119             ret->gl_pathv = tmp;
120             nb_paths *= 2;
121 	}
122 	strncpy(directory + len, FindFileData.cFileName, 499 - len);
123 	ret->gl_pathv[ret->gl_pathc] = strdup(directory);
124         if (ret->gl_pathv[ret->gl_pathc] == NULL)
125             break;
126         ret->gl_pathc++;
127     }
128     ret->gl_pathv[ret->gl_pathc] = NULL;
129 
130 done:
131     FindClose(hFind);
132     return(0);
133 }
134 
135 
136 
globfree(glob_t * pglob)137 static void globfree(glob_t *pglob) {
138     unsigned int i;
139     if (pglob == NULL)
140         return;
141 
142     for (i = 0;i < pglob->gl_pathc;i++) {
143          if (pglob->gl_pathv[i] != NULL)
144              free(pglob->gl_pathv[i]);
145     }
146 }
147 
148 #else
149 #include <glob.h>
150 #endif
151 
152 /************************************************************************
153  *									*
154  *		Huge document generator					*
155  *									*
156  ************************************************************************/
157 
158 #include <libxml/xmlIO.h>
159 
160 typedef struct {
161     const char *URL;
162     const char *start;
163     const char *segment;
164     const char *finish;
165 } xmlHugeDocParts;
166 
167 static const xmlHugeDocParts hugeDocTable[] = {
168     {
169         "test/recurse/huge.xml",
170 
171         "<!DOCTYPE foo ["
172         "<!ELEMENT foo (bar*)> "
173         "<!ELEMENT bar (#PCDATA)> "
174         "<!ATTLIST bar attr CDATA #IMPLIED> "
175         "<!ENTITY a SYSTEM 'ga.ent'> "
176         "<!ENTITY b SYSTEM 'gb.ent'> "
177         "<!ENTITY c SYSTEM 'gc.ent'> "
178         "<!ENTITY f 'some internal data'> "
179         "<!ENTITY e '&f;&f;'> "
180         "<!ENTITY d '&e;&e;'> "
181         "]> "
182         "<foo>",
183 
184         "  <bar attr='&e; &f; &d;'>&a; &b; &c; &e; &f; &d;</bar>\n"
185         "  <bar>_123456789_123456789_123456789_123456789</bar>\n"
186         "  <bar>_123456789_123456789_123456789_123456789</bar>\n"
187         "  <bar>_123456789_123456789_123456789_123456789</bar>\n"
188         "  <bar>_123456789_123456789_123456789_123456789</bar>\n",
189 
190         "</foo>"
191     },
192     {
193         "test/recurse/huge_dtd.dtd",
194 
195         "<!ELEMENT foo (#PCDATA)>\n"
196         "<!ENTITY ent 'success'>\n"
197         "<!ENTITY % a SYSTEM 'pa.ent'>\n"
198         "<!ENTITY % b SYSTEM 'pb.ent'>\n"
199         "<!ENTITY % c SYSTEM 'pc.ent'>\n"
200         "<!ENTITY % d '<!-- comment -->'>\n"
201         "<!ENTITY % e '%d;%d;'>\n"
202         "<!ENTITY % f '%e;%e;'>\n",
203 
204         "<!ENTITY ent '%a; %b; %c; %d; %e; %f;'>\n"
205         "%a; %b; %c; %d; %e; %f;\n"
206         "<!-- _123456789_123456789_123456789_123456789 -->\n"
207         "<!-- _123456789_123456789_123456789_123456789 -->\n"
208         "<!-- _123456789_123456789_123456789_123456789 -->\n",
209 
210         ""
211     },
212     { NULL, NULL, NULL, NULL }
213 };
214 
215 static const xmlHugeDocParts *hugeDocParts;
216 static int curseg = 0;
217 static const char *current;
218 static int rlen;
219 
220 /**
221  * hugeMatch:
222  * @URI: an URI to test
223  *
224  * Check for a huge query
225  *
226  * Returns 1 if yes and 0 if another Input module should be used
227  */
228 static int
hugeMatch(const char * URI)229 hugeMatch(const char * URI) {
230     int i;
231 
232     if (URI == NULL)
233         return(0);
234 
235     for (i = 0; hugeDocTable[i].URL; i++) {
236         if (strcmp(URI, hugeDocTable[i].URL) == 0)
237             return(1);
238     }
239 
240     return(0);
241 }
242 
243 /**
244  * hugeOpen:
245  * @URI: an URI to test
246  *
247  * Return a pointer to the huge query handler, in this example simply
248  * the current pointer...
249  *
250  * Returns an Input context or NULL in case or error
251  */
252 static void *
hugeOpen(const char * URI)253 hugeOpen(const char * URI) {
254     int i;
255 
256     if (URI == NULL)
257         return(NULL);
258 
259     for (i = 0; hugeDocTable[i].URL; i++) {
260         if (strcmp(URI, hugeDocTable[i].URL) == 0) {
261             hugeDocParts = hugeDocTable + i;
262             curseg = 0;
263             current = hugeDocParts->start;
264             rlen = strlen(current);
265             return((void *) current);
266         }
267     }
268 
269     return(NULL);
270 }
271 
272 /**
273  * hugeClose:
274  * @context: the read context
275  *
276  * Close the huge query handler
277  *
278  * Returns 0 or -1 in case of error
279  */
280 static int
hugeClose(void * context)281 hugeClose(void * context) {
282     if (context == NULL) return(-1);
283     return(0);
284 }
285 
286 #define MAX_NODES 1000
287 
288 /**
289  * hugeRead:
290  * @context: the read context
291  * @buffer: where to store data
292  * @len: number of bytes to read
293  *
294  * Implement an huge query read.
295  *
296  * Returns the number of bytes read or -1 in case of error
297  */
298 static int
hugeRead(void * context,char * buffer,int len)299 hugeRead(void *context, char *buffer, int len)
300 {
301     if ((context == NULL) || (buffer == NULL) || (len < 0))
302         return (-1);
303 
304     if (len >= rlen) {
305         if (curseg >= MAX_NODES + 1) {
306             rlen = 0;
307             return(0);
308         }
309         len = rlen;
310         rlen = 0;
311 	memcpy(buffer, current, len);
312         curseg ++;
313         if (curseg == MAX_NODES) {
314             current = hugeDocParts->finish;
315 	} else {
316             current = hugeDocParts->segment;
317 	}
318         rlen = strlen(current);
319     } else {
320 	memcpy(buffer, current, len);
321 	rlen -= len;
322         current += len;
323     }
324     return (len);
325 }
326 
327 /************************************************************************
328  *									*
329  *		Libxml2 specific routines				*
330  *									*
331  ************************************************************************/
332 
333 static int nb_tests = 0;
334 static int nb_errors = 0;
335 static int nb_leaks = 0;
336 
337 static int
fatalError(void)338 fatalError(void) {
339     fprintf(stderr, "Exitting tests on fatal error\n");
340     exit(1);
341 }
342 
343 static void
initializeLibxml2(void)344 initializeLibxml2(void) {
345     xmlMemSetup(xmlMemFree, xmlMemMalloc, xmlMemRealloc, xmlMemoryStrdup);
346     xmlInitParser();
347 #ifdef LIBXML_CATALOG_ENABLED
348     xmlInitializeCatalog();
349     xmlCatalogSetDefaults(XML_CATA_ALLOW_NONE);
350 #endif
351     /*
352      * register the new I/O handlers
353      */
354     if (xmlRegisterInputCallbacks(hugeMatch, hugeOpen,
355                                   hugeRead, hugeClose) < 0) {
356         fprintf(stderr, "failed to register Huge handler\n");
357 	exit(1);
358     }
359 }
360 
361 static void
initSAX(xmlParserCtxtPtr ctxt)362 initSAX(xmlParserCtxtPtr ctxt) {
363     ctxt->sax->startElementNs = NULL;
364     ctxt->sax->endElementNs = NULL;
365     ctxt->sax->startElement = NULL;
366     ctxt->sax->endElement = NULL;
367     ctxt->sax->characters = NULL;
368     ctxt->sax->cdataBlock = NULL;
369     ctxt->sax->ignorableWhitespace = NULL;
370     ctxt->sax->processingInstruction = NULL;
371     ctxt->sax->comment = NULL;
372 }
373 
374 /************************************************************************
375  *									*
376  *		File name and path utilities				*
377  *									*
378  ************************************************************************/
379 
baseFilename(const char * filename)380 static const char *baseFilename(const char *filename) {
381     const char *cur;
382     if (filename == NULL)
383         return(NULL);
384     cur = &filename[strlen(filename)];
385     while ((cur > filename) && (*cur != '/'))
386         cur--;
387     if (*cur == '/')
388         return(cur + 1);
389     return(cur);
390 }
391 
resultFilename(const char * filename,const char * out,const char * suffix)392 static char *resultFilename(const char *filename, const char *out,
393                             const char *suffix) {
394     const char *base;
395     char res[500];
396     char suffixbuff[500];
397 
398 /*************
399     if ((filename[0] == 't') && (filename[1] == 'e') &&
400         (filename[2] == 's') && (filename[3] == 't') &&
401 	(filename[4] == '/'))
402 	filename = &filename[5];
403  *************/
404 
405     base = baseFilename(filename);
406     if (suffix == NULL)
407         suffix = ".tmp";
408     if (out == NULL)
409         out = "";
410 
411     strncpy(suffixbuff,suffix,499);
412 
413     if (snprintf(res, 499, "%s%s%s", out, base, suffixbuff) >= 499)
414         res[499] = 0;
415     return(strdup(res));
416 }
417 
checkTestFile(const char * filename)418 static int checkTestFile(const char *filename) {
419     struct stat buf;
420 
421     if (stat(filename, &buf) == -1)
422         return(0);
423 
424 #if defined(_WIN32)
425     if (!(buf.st_mode & _S_IFREG))
426         return(0);
427 #else
428     if (!S_ISREG(buf.st_mode))
429         return(0);
430 #endif
431 
432     return(1);
433 }
434 
435 
436 
437 /************************************************************************
438  *									*
439  *		Test to detect or not recursive entities		*
440  *									*
441  ************************************************************************/
442 /**
443  * recursiveDetectTest:
444  * @filename: the file to parse
445  * @result: the file with expected result
446  * @err: the file with error messages: unused
447  *
448  * Parse a file loading DTD and replacing entities check it fails for
449  * lol cases
450  *
451  * Returns 0 in case of success, an error code otherwise
452  */
453 static int
recursiveDetectTest(const char * filename,const char * result ATTRIBUTE_UNUSED,const char * err ATTRIBUTE_UNUSED,int options)454 recursiveDetectTest(const char *filename,
455              const char *result ATTRIBUTE_UNUSED,
456              const char *err ATTRIBUTE_UNUSED,
457 	     int options) {
458     xmlDocPtr doc;
459     xmlParserCtxtPtr ctxt;
460     int res = 0;
461     /*
462      * XML_PARSE_DTDVALID is the only way to load external entities
463      * without XML_PARSE_NOENT. The validation result doesn't matter
464      * anyway.
465      */
466     int parserOptions = XML_PARSE_DTDVALID | XML_PARSE_NOERROR;
467 
468     nb_tests++;
469 
470     ctxt = xmlNewParserCtxt();
471     if (options & OPT_SAX)
472         initSAX(ctxt);
473     if ((options & OPT_NO_SUBST) == 0)
474         parserOptions |= XML_PARSE_NOENT;
475     /*
476      * base of the test, parse with the old API
477      */
478     doc = xmlCtxtReadFile(ctxt, filename, NULL, parserOptions);
479     if ((doc != NULL) || (ctxt->lastError.code != XML_ERR_RESOURCE_LIMIT)) {
480         fprintf(stderr, "Failed to detect recursion in %s\n", filename);
481 	xmlFreeParserCtxt(ctxt);
482 	xmlFreeDoc(doc);
483         return(1);
484     }
485     xmlFreeParserCtxt(ctxt);
486 
487     return(res);
488 }
489 
490 /**
491  * notRecursiveDetectTest:
492  * @filename: the file to parse
493  * @result: the file with expected result
494  * @err: the file with error messages: unused
495  *
496  * Parse a file loading DTD and replacing entities check it works for
497  * good cases
498  *
499  * Returns 0 in case of success, an error code otherwise
500  */
501 static int
notRecursiveDetectTest(const char * filename,const char * result ATTRIBUTE_UNUSED,const char * err ATTRIBUTE_UNUSED,int options)502 notRecursiveDetectTest(const char *filename,
503              const char *result ATTRIBUTE_UNUSED,
504              const char *err ATTRIBUTE_UNUSED,
505 	     int options) {
506     xmlDocPtr doc;
507     xmlParserCtxtPtr ctxt;
508     int res = 0;
509     int parserOptions = XML_PARSE_DTDLOAD;
510 
511     nb_tests++;
512 
513     ctxt = xmlNewParserCtxt();
514     if (options & OPT_SAX)
515         initSAX(ctxt);
516     if ((options & OPT_NO_SUBST) == 0)
517         parserOptions |= XML_PARSE_NOENT;
518     /*
519      * base of the test, parse with the old API
520      */
521     doc = xmlCtxtReadFile(ctxt, filename, NULL, parserOptions);
522     if (doc == NULL) {
523         fprintf(stderr, "Failed to parse correct file %s\n", filename);
524 	xmlFreeParserCtxt(ctxt);
525         return(1);
526     }
527     xmlFreeDoc(doc);
528     xmlFreeParserCtxt(ctxt);
529 
530     return(res);
531 }
532 
533 /**
534  * notRecursiveHugeTest:
535  * @filename: the file to parse
536  * @result: the file with expected result
537  * @err: the file with error messages: unused
538  *
539  * Parse a memory generated file
540  * good cases
541  *
542  * Returns 0 in case of success, an error code otherwise
543  */
544 static int
notRecursiveHugeTest(const char * filename ATTRIBUTE_UNUSED,const char * result ATTRIBUTE_UNUSED,const char * err ATTRIBUTE_UNUSED,int options)545 notRecursiveHugeTest(const char *filename ATTRIBUTE_UNUSED,
546              const char *result ATTRIBUTE_UNUSED,
547              const char *err ATTRIBUTE_UNUSED,
548 	     int options) {
549     xmlParserCtxtPtr ctxt;
550     xmlDocPtr doc;
551     int res = 0;
552     int parserOptions = XML_PARSE_DTDVALID;
553 
554     nb_tests++;
555 
556     ctxt = xmlNewParserCtxt();
557     if (options & OPT_SAX)
558         initSAX(ctxt);
559     if ((options & OPT_NO_SUBST) == 0)
560         parserOptions |= XML_PARSE_NOENT;
561     doc = xmlCtxtReadFile(ctxt, "test/recurse/huge.xml", NULL, parserOptions);
562     if (doc == NULL) {
563         fprintf(stderr, "Failed to parse huge.xml\n");
564 	res = 1;
565     } else {
566         xmlEntityPtr ent;
567         unsigned long fixed_cost = 20;
568         unsigned long allowed_expansion = 1000000;
569         unsigned long f_size = xmlStrlen(BAD_CAST "some internal data");
570         unsigned long e_size;
571         unsigned long d_size;
572         unsigned long total_size;
573 
574         ent = xmlGetDocEntity(doc, BAD_CAST "e");
575         e_size = f_size * 2 +
576                  xmlStrlen(BAD_CAST "&f;") * 2 +
577                  fixed_cost * 2;
578         if (ent->expandedSize != e_size) {
579             fprintf(stderr, "Wrong size for entity e: %lu (expected %lu)\n",
580                     ent->expandedSize, e_size);
581             res = 1;
582         }
583 
584         ent = xmlGetDocEntity(doc, BAD_CAST "b");
585         if (ent->expandedSize != e_size) {
586             fprintf(stderr, "Wrong size for entity b: %lu (expected %lu)\n",
587                     ent->expandedSize, e_size);
588             res = 1;
589         }
590 
591         ent = xmlGetDocEntity(doc, BAD_CAST "d");
592         d_size = e_size * 2 +
593                  xmlStrlen(BAD_CAST "&e;") * 2 +
594                  fixed_cost * 2;
595         if (ent->expandedSize != d_size) {
596             fprintf(stderr, "Wrong size for entity d: %lu (expected %lu)\n",
597                     ent->expandedSize, d_size);
598             res = 1;
599         }
600 
601         ent = xmlGetDocEntity(doc, BAD_CAST "c");
602         if (ent->expandedSize != d_size) {
603             fprintf(stderr, "Wrong size for entity c: %lu (expected %lu)\n",
604                     ent->expandedSize, d_size);
605             res = 1;
606         }
607 
608         if (ctxt->sizeentcopy < allowed_expansion) {
609             fprintf(stderr, "Total entity size too small: %lu\n",
610                     ctxt->sizeentcopy);
611             res = 1;
612         }
613 
614         total_size = (f_size + e_size + d_size + 3 * fixed_cost) *
615                      (MAX_NODES - 1) * 3;
616         if (ctxt->sizeentcopy != total_size) {
617             fprintf(stderr, "Wrong total entity size: %lu (expected %lu)\n",
618                     ctxt->sizeentcopy, total_size);
619             res = 1;
620         }
621 
622         if (ctxt->sizeentities != 30) {
623             fprintf(stderr, "Wrong parsed entity size: %lu (expected %lu)\n",
624                     ctxt->sizeentities, 30lu);
625             res = 1;
626         }
627     }
628 
629     xmlFreeDoc(doc);
630     xmlFreeParserCtxt(ctxt);
631 
632     return(res);
633 }
634 
635 /**
636  * notRecursiveHugeTest:
637  * @filename: the file to parse
638  * @result: the file with expected result
639  * @err: the file with error messages: unused
640  *
641  * Parse a memory generated file
642  * good cases
643  *
644  * Returns 0 in case of success, an error code otherwise
645  */
646 static int
hugeDtdTest(const char * filename ATTRIBUTE_UNUSED,const char * result ATTRIBUTE_UNUSED,const char * err ATTRIBUTE_UNUSED,int options)647 hugeDtdTest(const char *filename ATTRIBUTE_UNUSED,
648             const char *result ATTRIBUTE_UNUSED,
649             const char *err ATTRIBUTE_UNUSED,
650             int options) {
651     xmlParserCtxtPtr ctxt;
652     xmlDocPtr doc;
653     int res = 0;
654     int parserOptions = XML_PARSE_DTDVALID;
655 
656     nb_tests++;
657 
658     ctxt = xmlNewParserCtxt();
659     if (options & OPT_SAX)
660         initSAX(ctxt);
661     if ((options & OPT_NO_SUBST) == 0)
662         parserOptions |= XML_PARSE_NOENT;
663     doc = xmlCtxtReadFile(ctxt, "test/recurse/huge_dtd.xml", NULL,
664                           parserOptions);
665     if (doc == NULL) {
666         fprintf(stderr, "Failed to parse huge_dtd.xml\n");
667 	res = 1;
668     } else {
669         unsigned long fixed_cost = 20;
670         unsigned long allowed_expansion = 1000000;
671         unsigned long a_size = xmlStrlen(BAD_CAST "<!-- comment -->");
672         unsigned long b_size;
673         unsigned long c_size;
674         unsigned long e_size;
675         unsigned long f_size;
676         unsigned long total_size;
677 
678         if (ctxt->sizeentcopy < allowed_expansion) {
679             fprintf(stderr, "Total entity size too small: %lu\n",
680                     ctxt->sizeentcopy);
681             res = 1;
682         }
683 
684         b_size = (a_size + strlen("&a;") + fixed_cost) * 2;
685         c_size = (b_size + strlen("&b;") + fixed_cost) * 2;
686         /*
687          * Internal parameter entites are substitued eagerly and
688          * need different accounting.
689          */
690         e_size = a_size * 2;
691         f_size = e_size * 2;
692         total_size = /* internal */
693                      e_size + f_size + fixed_cost * 4 +
694                      (a_size + e_size + f_size + fixed_cost * 3) *
695                      (MAX_NODES - 1) * 2 +
696                      /* external */
697                      (a_size + b_size + c_size + fixed_cost * 3) *
698                      (MAX_NODES - 1) * 2 +
699                      /* final reference in main doc */
700                      strlen("success") + fixed_cost;
701         if (ctxt->sizeentcopy != total_size) {
702             fprintf(stderr, "Wrong total entity size: %lu (expected %lu)\n",
703                     ctxt->sizeentcopy, total_size);
704             res = 1;
705         }
706 
707         total_size = strlen(hugeDocParts->start) +
708                      strlen(hugeDocParts->segment) * (MAX_NODES - 1) +
709                      strlen(hugeDocParts->finish) +
710                      /*
711                       * Other external entities pa.ent, pb.ent, pc.ent.
712                       * These are currently counted twice because they're
713                       * used both in DTD and EntityValue.
714                       */
715                      (16 + 6 + 6) * 2;
716         if (ctxt->sizeentities != total_size) {
717             fprintf(stderr, "Wrong parsed entity size: %lu (expected %lu)\n",
718                     ctxt->sizeentities, total_size);
719             res = 1;
720         }
721     }
722 
723     xmlFreeDoc(doc);
724     xmlFreeParserCtxt(ctxt);
725 
726     return(res);
727 }
728 
729 /************************************************************************
730  *									*
731  *			Tests Descriptions				*
732  *									*
733  ************************************************************************/
734 
735 static
736 testDesc testDescriptions[] = {
737     { "Parsing recursive test cases" ,
738       recursiveDetectTest, "./test/recurse/lol*.xml", NULL, NULL, NULL,
739       0 },
740     { "Parsing recursive test cases (no substitution)" ,
741       recursiveDetectTest, "./test/recurse/lol*.xml", NULL, NULL, NULL,
742       OPT_NO_SUBST },
743     { "Parsing recursive test cases (SAX)" ,
744       recursiveDetectTest, "./test/recurse/lol*.xml", NULL, NULL, NULL,
745       OPT_SAX },
746     { "Parsing recursive test cases (SAX, no substitution)" ,
747       recursiveDetectTest, "./test/recurse/lol*.xml", NULL, NULL, NULL,
748       OPT_SAX | OPT_NO_SUBST },
749     { "Parsing non-recursive test cases" ,
750       notRecursiveDetectTest, "./test/recurse/good*.xml", NULL, NULL, NULL,
751       0 },
752     { "Parsing non-recursive test cases (SAX)" ,
753       notRecursiveDetectTest, "./test/recurse/good*.xml", NULL, NULL, NULL,
754       OPT_SAX },
755     { "Parsing non-recursive huge case" ,
756       notRecursiveHugeTest, NULL, NULL, NULL, NULL,
757       0 },
758     { "Parsing non-recursive huge case (no substitution)" ,
759       notRecursiveHugeTest, NULL, NULL, NULL, NULL,
760       OPT_NO_SUBST },
761     { "Parsing non-recursive huge case (SAX)" ,
762       notRecursiveHugeTest, NULL, NULL, NULL, NULL,
763       OPT_SAX },
764     { "Parsing non-recursive huge case (SAX, no substitution)" ,
765       notRecursiveHugeTest, NULL, NULL, NULL, NULL,
766       OPT_SAX | OPT_NO_SUBST },
767     { "Parsing non-recursive huge DTD case" ,
768       hugeDtdTest, NULL, NULL, NULL, NULL,
769       0 },
770     {NULL, NULL, NULL, NULL, NULL, NULL, 0}
771 };
772 
773 /************************************************************************
774  *									*
775  *		The main code driving the tests				*
776  *									*
777  ************************************************************************/
778 
779 static int
launchTests(testDescPtr tst)780 launchTests(testDescPtr tst) {
781     int res = 0, err = 0;
782     size_t i;
783     char *result;
784     char *error;
785     int mem;
786 
787     if (tst == NULL) return(-1);
788     if (tst->in != NULL) {
789 	glob_t globbuf;
790 
791 	globbuf.gl_offs = 0;
792 	glob(tst->in, GLOB_DOOFFS, NULL, &globbuf);
793 	for (i = 0;i < globbuf.gl_pathc;i++) {
794 	    if (!checkTestFile(globbuf.gl_pathv[i]))
795 	        continue;
796 	    if (tst->suffix != NULL) {
797 		result = resultFilename(globbuf.gl_pathv[i], tst->out,
798 					tst->suffix);
799 		if (result == NULL) {
800 		    fprintf(stderr, "Out of memory !\n");
801 		    fatalError();
802 		}
803 	    } else {
804 	        result = NULL;
805 	    }
806 	    if (tst->err != NULL) {
807 		error = resultFilename(globbuf.gl_pathv[i], tst->out,
808 		                        tst->err);
809 		if (error == NULL) {
810 		    fprintf(stderr, "Out of memory !\n");
811 		    fatalError();
812 		}
813 	    } else {
814 	        error = NULL;
815 	    }
816 	    if ((result) &&(!checkTestFile(result))) {
817 	        fprintf(stderr, "Missing result file %s\n", result);
818 	    } else if ((error) &&(!checkTestFile(error))) {
819 	        fprintf(stderr, "Missing error file %s\n", error);
820 	    } else {
821 		mem = xmlMemUsed();
822 		res = tst->func(globbuf.gl_pathv[i], result, error,
823 		                tst->options | XML_PARSE_COMPACT);
824 		xmlResetLastError();
825 		if (res != 0) {
826 		    fprintf(stderr, "File %s generated an error\n",
827 		            globbuf.gl_pathv[i]);
828 		    nb_errors++;
829 		    err++;
830 		}
831 		else if (xmlMemUsed() != mem) {
832                     fprintf(stderr, "File %s leaked %d bytes\n",
833                             globbuf.gl_pathv[i], xmlMemUsed() - mem);
834                     nb_leaks++;
835                     err++;
836 		}
837 	    }
838 	    if (result)
839 		free(result);
840 	    if (error)
841 		free(error);
842 	}
843 	globfree(&globbuf);
844     } else {
845         res = tst->func(NULL, NULL, NULL, tst->options);
846 	if (res != 0) {
847 	    nb_errors++;
848 	    err++;
849 	}
850     }
851     return(err);
852 }
853 
854 static int verbose = 0;
855 static int tests_quiet = 0;
856 
857 static int
runtest(int i)858 runtest(int i) {
859     int ret = 0, res;
860     int old_errors, old_tests, old_leaks;
861 
862     old_errors = nb_errors;
863     old_tests = nb_tests;
864     old_leaks = nb_leaks;
865     if ((tests_quiet == 0) && (testDescriptions[i].desc != NULL))
866 	printf("## %s\n", testDescriptions[i].desc);
867     res = launchTests(&testDescriptions[i]);
868     if (res != 0)
869 	ret++;
870     if (verbose) {
871 	if ((nb_errors == old_errors) && (nb_leaks == old_leaks))
872 	    printf("Ran %d tests, no errors\n", nb_tests - old_tests);
873 	else
874 	    printf("Ran %d tests, %d errors, %d leaks\n",
875 		   nb_tests - old_tests,
876 		   nb_errors - old_errors,
877 		   nb_leaks - old_leaks);
878     }
879     return(ret);
880 }
881 
882 int
main(int argc ATTRIBUTE_UNUSED,char ** argv ATTRIBUTE_UNUSED)883 main(int argc ATTRIBUTE_UNUSED, char **argv ATTRIBUTE_UNUSED) {
884     int i, a, ret = 0;
885     int subset = 0;
886 
887     initializeLibxml2();
888 
889     for (a = 1; a < argc;a++) {
890         if (!strcmp(argv[a], "-v"))
891 	    verbose = 1;
892         else if (!strcmp(argv[a], "-quiet"))
893 	    tests_quiet = 1;
894 	else {
895 	    for (i = 0; testDescriptions[i].func != NULL; i++) {
896 	        if (strstr(testDescriptions[i].desc, argv[a])) {
897 		    ret += runtest(i);
898 		    subset++;
899 		}
900 	    }
901 	}
902     }
903     if (subset == 0) {
904 	for (i = 0; testDescriptions[i].func != NULL; i++) {
905 	    ret += runtest(i);
906 	}
907     }
908     if ((nb_errors == 0) && (nb_leaks == 0)) {
909         ret = 0;
910 	printf("Total %d tests, no errors\n",
911 	       nb_tests);
912     } else {
913         ret = 1;
914 	printf("Total %d tests, %d errors, %d leaks\n",
915 	       nb_tests, nb_errors, nb_leaks);
916     }
917     xmlCleanupParser();
918 
919     return(ret);
920 }
921