• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * libxml.c: this modules implements the main part of the glue of the
3  *           libxml2 library and the Python interpreter. It provides the
4  *           entry points where an automatically generated stub is either
5  *           unpractical or would not match cleanly the Python model.
6  *
7  * If compiled with MERGED_MODULES, the entry point will be used to
8  * initialize both the libxml2 and the libxslt wrappers
9  *
10  * See Copyright for the status of this software.
11  *
12  * daniel@veillard.com
13  */
14 #define PY_SSIZE_T_CLEAN
15 #include <Python.h>
16 #include <fileobject.h>
17 /* #include "config.h" */
18 #include <libxml/xmlmemory.h>
19 #include <libxml/parser.h>
20 #include <libxml/tree.h>
21 #include <libxml/xpath.h>
22 #include <libxml/xmlerror.h>
23 #include <libxml/xpathInternals.h>
24 #include <libxml/xmlmemory.h>
25 #include <libxml/xmlIO.h>
26 #include <libxml/c14n.h>
27 #include <libxml/xmlreader.h>
28 #include <libxml/xmlsave.h>
29 #include "libxml_wrap.h"
30 #include "libxml2-py.h"
31 
32 #if defined(WITH_TRIO)
33 #include "trio.h"
34 #define vsnprintf trio_vsnprintf
35 #endif
36 
37 /* #define DEBUG */
38 /* #define DEBUG_SAX */
39 /* #define DEBUG_XPATH */
40 /* #define DEBUG_ERROR */
41 /* #define DEBUG_MEMORY */
42 /* #define DEBUG_FILES */
43 /* #define DEBUG_LOADER */
44 
45 #if PY_MAJOR_VERSION >= 3
46 PyObject *PyInit_libxml2mod(void);
47 
48 #define PY_IMPORT_STRING_SIZE PyUnicode_FromStringAndSize
49 #define PY_IMPORT_STRING PyUnicode_FromString
50 #else
51 void initlibxml2mod(void);
52 #define PY_IMPORT_STRING_SIZE PyString_FromStringAndSize
53 #define PY_IMPORT_STRING PyString_FromString
54 #endif
55 
56 
57 /**
58  * TODO:
59  *
60  * macro to flag unimplemented blocks
61  */
62 #define TODO 								\
63     xmlGenericError(xmlGenericErrorContext,				\
64 	    "Unimplemented block at %s:%d\n",				\
65             __FILE__, __LINE__);
66 /*
67  * the following vars are used for XPath extensions, but
68  * are also referenced within the parser cleanup routine.
69  */
70 static int libxml_xpathCallbacksInitialized = 0;
71 
72 typedef struct libxml_xpathCallback {
73     xmlXPathContextPtr ctx;
74     xmlChar *name;
75     xmlChar *ns_uri;
76     PyObject *function;
77 } libxml_xpathCallback, *libxml_xpathCallbackPtr;
78 typedef libxml_xpathCallback libxml_xpathCallbackArray[];
79 static int libxml_xpathCallbacksAllocd = 10;
80 static libxml_xpathCallbackArray *libxml_xpathCallbacks = NULL;
81 static int libxml_xpathCallbacksNb = 0;
82 
83 /************************************************************************
84  *									*
85  *		Memory debug interface					*
86  *									*
87  ************************************************************************/
88 
89 #if 0
90 extern void xmlMemFree(void *ptr);
91 extern void *xmlMemMalloc(size_t size);
92 extern void *xmlMemRealloc(void *ptr, size_t size);
93 extern char *xmlMemoryStrdup(const char *str);
94 #endif
95 
96 static int libxmlMemoryDebugActivated = 0;
97 static long libxmlMemoryAllocatedBase = 0;
98 
99 static int libxmlMemoryDebug = 0;
100 static xmlFreeFunc freeFunc = NULL;
101 static xmlMallocFunc mallocFunc = NULL;
102 static xmlReallocFunc reallocFunc = NULL;
103 static xmlStrdupFunc strdupFunc = NULL;
104 
105 static void
106 libxml_xmlErrorInitialize(void); /* forward declare */
107 
108 PyObject *
libxml_xmlMemoryUsed(PyObject * self ATTRIBUTE_UNUSED,PyObject * args ATTRIBUTE_UNUSED)109 libxml_xmlMemoryUsed(PyObject * self ATTRIBUTE_UNUSED,
110         PyObject * args ATTRIBUTE_UNUSED)
111 {
112     long ret;
113     PyObject *py_retval;
114 
115     ret = xmlMemUsed();
116 
117     py_retval = libxml_longWrap(ret);
118     return (py_retval);
119 }
120 
121 PyObject *
libxml_xmlDebugMemory(PyObject * self ATTRIBUTE_UNUSED,PyObject * args)122 libxml_xmlDebugMemory(PyObject * self ATTRIBUTE_UNUSED, PyObject * args)
123 {
124     int activate;
125     PyObject *py_retval;
126     long ret;
127 
128     if (!PyArg_ParseTuple(args, (char *) "i:xmlDebugMemory", &activate))
129         return (NULL);
130 
131 #ifdef DEBUG_MEMORY
132     printf("libxml_xmlDebugMemory(%d) called\n", activate);
133 #endif
134 
135     if (activate != 0) {
136         if (libxmlMemoryDebug == 0) {
137             /*
138              * First initialize the library and grab the old memory handlers
139              * and switch the library to memory debugging
140              */
141             xmlMemGet((xmlFreeFunc *) & freeFunc,
142                       (xmlMallocFunc *) & mallocFunc,
143                       (xmlReallocFunc *) & reallocFunc,
144                       (xmlStrdupFunc *) & strdupFunc);
145             if ((freeFunc == xmlMemFree) && (mallocFunc == xmlMemMalloc) &&
146                 (reallocFunc == xmlMemRealloc) &&
147                 (strdupFunc == xmlMemoryStrdup)) {
148                 libxmlMemoryAllocatedBase = xmlMemUsed();
149             } else {
150                 /*
151                  * cleanup first, because some memory has been
152                  * allocated with the non-debug malloc in xmlInitParser
153                  * when the python module was imported
154                  */
155                 xmlCleanupParser();
156                 ret = (long) xmlMemSetup(xmlMemFree, xmlMemMalloc,
157                                          xmlMemRealloc, xmlMemoryStrdup);
158                 if (ret < 0)
159                     goto error;
160                 libxmlMemoryAllocatedBase = xmlMemUsed();
161                 /* reinitialize */
162                 xmlInitParser();
163                 libxml_xmlErrorInitialize();
164             }
165             ret = 0;
166         } else if (libxmlMemoryDebugActivated == 0) {
167             libxmlMemoryAllocatedBase = xmlMemUsed();
168             ret = 0;
169         } else {
170             ret = xmlMemUsed() - libxmlMemoryAllocatedBase;
171         }
172         libxmlMemoryDebug = 1;
173         libxmlMemoryDebugActivated = 1;
174     } else {
175         if (libxmlMemoryDebugActivated == 1)
176             ret = xmlMemUsed() - libxmlMemoryAllocatedBase;
177         else
178             ret = 0;
179         libxmlMemoryDebugActivated = 0;
180     }
181   error:
182     py_retval = libxml_longWrap(ret);
183     return (py_retval);
184 }
185 
186 PyObject *
libxml_xmlPythonCleanupParser(PyObject * self ATTRIBUTE_UNUSED,PyObject * args ATTRIBUTE_UNUSED)187 libxml_xmlPythonCleanupParser(PyObject *self ATTRIBUTE_UNUSED,
188                               PyObject *args ATTRIBUTE_UNUSED) {
189 
190     int ix;
191     long freed = -1;
192 
193     if (libxmlMemoryDebug) {
194         freed = xmlMemUsed();
195     }
196 
197     xmlCleanupParser();
198     /*
199      * Need to confirm whether we really want to do this (required for
200      * memcheck) in all cases...
201      */
202 
203     if (libxml_xpathCallbacks != NULL) {	/* if ext funcs declared */
204 	for (ix=0; ix<libxml_xpathCallbacksNb; ix++) {
205 	    if ((*libxml_xpathCallbacks)[ix].name != NULL)
206 	        xmlFree((*libxml_xpathCallbacks)[ix].name);
207 	    if ((*libxml_xpathCallbacks)[ix].ns_uri != NULL)
208 	        xmlFree((*libxml_xpathCallbacks)[ix].ns_uri);
209 	}
210 	libxml_xpathCallbacksNb = 0;
211         xmlFree(libxml_xpathCallbacks);
212 	libxml_xpathCallbacks = NULL;
213     }
214 
215     if (libxmlMemoryDebug) {
216         freed -= xmlMemUsed();
217 	libxmlMemoryAllocatedBase -= freed;
218 	if (libxmlMemoryAllocatedBase < 0)
219 	    libxmlMemoryAllocatedBase = 0;
220     }
221 
222     Py_INCREF(Py_None);
223     return(Py_None);
224 }
225 
226 PyObject *
libxml_xmlDumpMemory(ATTRIBUTE_UNUSED PyObject * self,ATTRIBUTE_UNUSED PyObject * args)227 libxml_xmlDumpMemory(ATTRIBUTE_UNUSED PyObject * self,
228                      ATTRIBUTE_UNUSED PyObject * args)
229 {
230 
231     if (libxmlMemoryDebug != 0)
232         xmlMemoryDump();
233     Py_INCREF(Py_None);
234     return (Py_None);
235 }
236 
237 /************************************************************************
238  *									*
239  *		Handling Python FILE I/O at the C level			*
240  *	The raw I/O attack directly the File objects, while the		*
241  *	other routines address the ioWrapper instance instead		*
242  *									*
243  ************************************************************************/
244 
245 /**
246  * xmlPythonFileCloseUnref:
247  * @context:  the I/O context
248  *
249  * Close an I/O channel
250  */
251 static int
xmlPythonFileCloseRaw(void * context)252 xmlPythonFileCloseRaw (void * context) {
253     PyObject *file, *ret;
254 
255 #ifdef DEBUG_FILES
256     printf("xmlPythonFileCloseUnref\n");
257 #endif
258     file = (PyObject *) context;
259     if (file == NULL) return(-1);
260     ret = PyEval_CallMethod(file, (char *) "close", (char *) "()");
261     if (ret != NULL) {
262 	Py_DECREF(ret);
263     }
264     Py_DECREF(file);
265     return(0);
266 }
267 
268 /**
269  * xmlPythonFileReadRaw:
270  * @context:  the I/O context
271  * @buffer:  where to drop data
272  * @len:  number of bytes to write
273  *
274  * Read @len bytes to @buffer from the Python file in the I/O channel
275  *
276  * Returns the number of bytes read
277  */
278 static int
xmlPythonFileReadRaw(void * context,char * buffer,int len)279 xmlPythonFileReadRaw (void * context, char * buffer, int len) {
280     PyObject *file;
281     PyObject *ret;
282     int lenread = -1;
283     char *data;
284 
285 #ifdef DEBUG_FILES
286     printf("xmlPythonFileReadRaw: %d\n", len);
287 #endif
288     file = (PyObject *) context;
289     if (file == NULL) return(-1);
290     ret = PyEval_CallMethod(file, (char *) "read", (char *) "(i)", len);
291     if (ret == NULL) {
292 	printf("xmlPythonFileReadRaw: result is NULL\n");
293 	return(-1);
294     } else if (PyBytes_Check(ret)) {
295 	lenread = PyBytes_Size(ret);
296 	data = PyBytes_AsString(ret);
297 #ifdef PyUnicode_Check
298     } else if (PyUnicode_Check (ret)) {
299 #if PY_VERSION_HEX >= 0x03030000
300         Py_ssize_t size;
301 	const char *tmp;
302 
303 	/* tmp doesn't need to be deallocated */
304         tmp = PyUnicode_AsUTF8AndSize(ret, &size);
305 
306 	lenread = (int) size;
307 	data = (char *) tmp;
308 #else
309         PyObject *b;
310 	b = PyUnicode_AsUTF8String(ret);
311 	if (b == NULL) {
312 	    printf("xmlPythonFileReadRaw: failed to convert to UTF-8\n");
313 	    return(-1);
314 	}
315 	lenread = PyBytes_Size(b);
316 	data = PyBytes_AsString(b);
317 	Py_DECREF(b);
318 #endif
319 #endif
320     } else {
321 	printf("xmlPythonFileReadRaw: result is not a String\n");
322 	Py_DECREF(ret);
323 	return(-1);
324     }
325     if (lenread > len)
326 	memcpy(buffer, data, len);
327     else
328 	memcpy(buffer, data, lenread);
329     Py_DECREF(ret);
330     return(lenread);
331 }
332 
333 /**
334  * xmlPythonFileRead:
335  * @context:  the I/O context
336  * @buffer:  where to drop data
337  * @len:  number of bytes to write
338  *
339  * Read @len bytes to @buffer from the I/O channel.
340  *
341  * Returns the number of bytes read
342  */
343 static int
xmlPythonFileRead(void * context,char * buffer,int len)344 xmlPythonFileRead (void * context, char * buffer, int len) {
345     PyObject *file;
346     PyObject *ret;
347     int lenread = -1;
348     char *data;
349 
350 #ifdef DEBUG_FILES
351     printf("xmlPythonFileRead: %d\n", len);
352 #endif
353     file = (PyObject *) context;
354     if (file == NULL) return(-1);
355     ret = PyEval_CallMethod(file, (char *) "io_read", (char *) "(i)", len);
356     if (ret == NULL) {
357 	printf("xmlPythonFileRead: result is NULL\n");
358 	return(-1);
359     } else if (PyBytes_Check(ret)) {
360 	lenread = PyBytes_Size(ret);
361 	data = PyBytes_AsString(ret);
362 #ifdef PyUnicode_Check
363     } else if (PyUnicode_Check (ret)) {
364 #if PY_VERSION_HEX >= 0x03030000
365         Py_ssize_t size;
366 	const char *tmp;
367 
368 	/* tmp doesn't need to be deallocated */
369         tmp = PyUnicode_AsUTF8AndSize(ret, &size);
370 
371 	lenread = (int) size;
372 	data = (char *) tmp;
373 #else
374         PyObject *b;
375 	b = PyUnicode_AsUTF8String(ret);
376 	if (b == NULL) {
377 	    printf("xmlPythonFileRead: failed to convert to UTF-8\n");
378 	    return(-1);
379 	}
380 	lenread = PyBytes_Size(b);
381 	data = PyBytes_AsString(b);
382 	Py_DECREF(b);
383 #endif
384 #endif
385     } else {
386 	printf("xmlPythonFileRead: result is not a String\n");
387 	Py_DECREF(ret);
388 	return(-1);
389     }
390     if (lenread > len)
391 	memcpy(buffer, data, len);
392     else
393 	memcpy(buffer, data, lenread);
394     Py_DECREF(ret);
395     return(lenread);
396 }
397 
398 /**
399  * xmlFileWrite:
400  * @context:  the I/O context
401  * @buffer:  where to drop data
402  * @len:  number of bytes to write
403  *
404  * Write @len bytes from @buffer to the I/O channel.
405  *
406  * Returns the number of bytes written
407  */
408 static int
xmlPythonFileWrite(void * context,const char * buffer,int len)409 xmlPythonFileWrite (void * context, const char * buffer, int len) {
410     PyObject *file;
411     PyObject *string;
412     PyObject *ret = NULL;
413     int written = -1;
414 
415 #ifdef DEBUG_FILES
416     printf("xmlPythonFileWrite: %d\n", len);
417 #endif
418     file = (PyObject *) context;
419     if (file == NULL) return(-1);
420     string = PY_IMPORT_STRING_SIZE(buffer, len);
421     if (string == NULL) return(-1);
422     if (PyObject_HasAttrString(file, (char *) "io_write")) {
423         ret = PyEval_CallMethod(file, (char *) "io_write", (char *) "(O)",
424 	                        string);
425     } else if (PyObject_HasAttrString(file, (char *) "write")) {
426         ret = PyEval_CallMethod(file, (char *) "write", (char *) "(O)",
427 	                        string);
428     }
429     Py_DECREF(string);
430     if (ret == NULL) {
431 	printf("xmlPythonFileWrite: result is NULL\n");
432 	return(-1);
433     } else if (PyLong_Check(ret)) {
434 	written = (int) PyLong_AsLong(ret);
435 	Py_DECREF(ret);
436     } else if (ret == Py_None) {
437 	written = len;
438 	Py_DECREF(ret);
439     } else {
440 	printf("xmlPythonFileWrite: result is not an Int nor None\n");
441 	Py_DECREF(ret);
442     }
443     return(written);
444 }
445 
446 /**
447  * xmlPythonFileClose:
448  * @context:  the I/O context
449  *
450  * Close an I/O channel
451  */
452 static int
xmlPythonFileClose(void * context)453 xmlPythonFileClose (void * context) {
454     PyObject *file, *ret = NULL;
455 
456 #ifdef DEBUG_FILES
457     printf("xmlPythonFileClose\n");
458 #endif
459     file = (PyObject *) context;
460     if (file == NULL) return(-1);
461     if (PyObject_HasAttrString(file, (char *) "io_close")) {
462         ret = PyEval_CallMethod(file, (char *) "io_close", (char *) "()");
463     } else if (PyObject_HasAttrString(file, (char *) "flush")) {
464         ret = PyEval_CallMethod(file, (char *) "flush", (char *) "()");
465     }
466     if (ret != NULL) {
467 	Py_DECREF(ret);
468     }
469     return(0);
470 }
471 
472 #ifdef LIBXML_OUTPUT_ENABLED
473 /**
474  * xmlOutputBufferCreatePythonFile:
475  * @file:  a PyFile_Type
476  * @encoder:  the encoding converter or NULL
477  *
478  * Create a buffered output for the progressive saving to a PyFile_Type
479  * buffered C I/O
480  *
481  * Returns the new parser output or NULL
482  */
483 static xmlOutputBufferPtr
xmlOutputBufferCreatePythonFile(PyObject * file,xmlCharEncodingHandlerPtr encoder)484 xmlOutputBufferCreatePythonFile(PyObject *file,
485 	                        xmlCharEncodingHandlerPtr encoder) {
486     xmlOutputBufferPtr ret;
487 
488     if (file == NULL) return(NULL);
489 
490     ret = xmlAllocOutputBuffer(encoder);
491     if (ret != NULL) {
492         ret->context = file;
493 	/* Py_INCREF(file); */
494 	ret->writecallback = xmlPythonFileWrite;
495 	ret->closecallback = xmlPythonFileClose;
496     }
497 
498     return(ret);
499 }
500 
501 PyObject *
libxml_xmlCreateOutputBuffer(ATTRIBUTE_UNUSED PyObject * self,PyObject * args)502 libxml_xmlCreateOutputBuffer(ATTRIBUTE_UNUSED PyObject *self, PyObject *args) {
503     PyObject *py_retval;
504     PyObject *file;
505     xmlChar  *encoding;
506     xmlCharEncodingHandlerPtr handler = NULL;
507     xmlOutputBufferPtr buffer;
508 
509 
510     if (!PyArg_ParseTuple(args, (char *)"Oz:xmlOutputBufferCreate",
511 		&file, &encoding))
512 	return(NULL);
513     if ((encoding != NULL) && (encoding[0] != 0)) {
514 	handler = xmlFindCharEncodingHandler((const char *) encoding);
515     }
516     buffer = xmlOutputBufferCreatePythonFile(file, handler);
517     if (buffer == NULL)
518 	printf("libxml_xmlCreateOutputBuffer: buffer == NULL\n");
519     py_retval = libxml_xmlOutputBufferPtrWrap(buffer);
520     return(py_retval);
521 }
522 
523 /**
524  * libxml_outputBufferGetPythonFile:
525  * @buffer:  the I/O buffer
526  *
527  * read the Python I/O from the CObject
528  *
529  * Returns the new parser output or NULL
530  */
531 static PyObject *
libxml_outputBufferGetPythonFile(ATTRIBUTE_UNUSED PyObject * self,PyObject * args)532 libxml_outputBufferGetPythonFile(ATTRIBUTE_UNUSED PyObject *self,
533                                     PyObject *args) {
534     PyObject *buffer;
535     PyObject *file;
536     xmlOutputBufferPtr obj;
537 
538     if (!PyArg_ParseTuple(args, (char *)"O:outputBufferGetPythonFile",
539 			  &buffer))
540 	return(NULL);
541 
542     obj = PyoutputBuffer_Get(buffer);
543     if (obj == NULL) {
544 	fprintf(stderr,
545 	        "outputBufferGetPythonFile: obj == NULL\n");
546 	Py_INCREF(Py_None);
547 	return(Py_None);
548     }
549     if (obj->closecallback != xmlPythonFileClose) {
550 	fprintf(stderr,
551 	        "outputBufferGetPythonFile: not a python file wrapper\n");
552 	Py_INCREF(Py_None);
553 	return(Py_None);
554     }
555     file = (PyObject *) obj->context;
556     if (file == NULL) {
557 	Py_INCREF(Py_None);
558 	return(Py_None);
559     }
560     Py_INCREF(file);
561     return(file);
562 }
563 
564 static PyObject *
libxml_xmlOutputBufferClose(PyObject * self ATTRIBUTE_UNUSED,PyObject * args)565 libxml_xmlOutputBufferClose(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) {
566     PyObject *py_retval;
567     int c_retval;
568     xmlOutputBufferPtr out;
569     PyObject *pyobj_out;
570 
571     if (!PyArg_ParseTuple(args, (char *)"O:xmlOutputBufferClose", &pyobj_out))
572         return(NULL);
573     out = (xmlOutputBufferPtr) PyoutputBuffer_Get(pyobj_out);
574     /* Buffer may already have been destroyed elsewhere. This is harmless. */
575     if (out == NULL) {
576 	Py_INCREF(Py_None);
577 	return(Py_None);
578     }
579 
580     c_retval = xmlOutputBufferClose(out);
581     py_retval = libxml_intWrap((int) c_retval);
582     return(py_retval);
583 }
584 
585 static PyObject *
libxml_xmlOutputBufferFlush(PyObject * self ATTRIBUTE_UNUSED,PyObject * args)586 libxml_xmlOutputBufferFlush(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) {
587     PyObject *py_retval;
588     int c_retval;
589     xmlOutputBufferPtr out;
590     PyObject *pyobj_out;
591 
592     if (!PyArg_ParseTuple(args, (char *)"O:xmlOutputBufferFlush", &pyobj_out))
593         return(NULL);
594     out = (xmlOutputBufferPtr) PyoutputBuffer_Get(pyobj_out);
595 
596     c_retval = xmlOutputBufferFlush(out);
597     py_retval = libxml_intWrap((int) c_retval);
598     return(py_retval);
599 }
600 
601 static PyObject *
libxml_xmlSaveFileTo(PyObject * self ATTRIBUTE_UNUSED,PyObject * args)602 libxml_xmlSaveFileTo(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) {
603     PyObject *py_retval;
604     int c_retval;
605     xmlOutputBufferPtr buf;
606     PyObject *pyobj_buf;
607     xmlDocPtr cur;
608     PyObject *pyobj_cur;
609     char * encoding;
610 
611     if (!PyArg_ParseTuple(args, (char *)"OOz:xmlSaveFileTo", &pyobj_buf, &pyobj_cur, &encoding))
612         return(NULL);
613     buf = (xmlOutputBufferPtr) PyoutputBuffer_Get(pyobj_buf);
614     cur = (xmlDocPtr) PyxmlNode_Get(pyobj_cur);
615 
616     c_retval = xmlSaveFileTo(buf, cur, encoding);
617 	/* xmlSaveTo() freed the memory pointed to by buf, so record that in the
618 	 * Python object. */
619     ((PyoutputBuffer_Object *)(pyobj_buf))->obj = NULL;
620     py_retval = libxml_intWrap((int) c_retval);
621     return(py_retval);
622 }
623 
624 static PyObject *
libxml_xmlSaveFormatFileTo(PyObject * self ATTRIBUTE_UNUSED,PyObject * args)625 libxml_xmlSaveFormatFileTo(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) {
626     PyObject *py_retval;
627     int c_retval;
628     xmlOutputBufferPtr buf;
629     PyObject *pyobj_buf;
630     xmlDocPtr cur;
631     PyObject *pyobj_cur;
632     char * encoding;
633     int format;
634 
635     if (!PyArg_ParseTuple(args, (char *)"OOzi:xmlSaveFormatFileTo", &pyobj_buf, &pyobj_cur, &encoding, &format))
636         return(NULL);
637     buf = (xmlOutputBufferPtr) PyoutputBuffer_Get(pyobj_buf);
638     cur = (xmlDocPtr) PyxmlNode_Get(pyobj_cur);
639 
640     c_retval = xmlSaveFormatFileTo(buf, cur, encoding, format);
641 	/* xmlSaveFormatFileTo() freed the memory pointed to by buf, so record that
642 	 * in the Python object */
643 	((PyoutputBuffer_Object *)(pyobj_buf))->obj = NULL;
644     py_retval = libxml_intWrap((int) c_retval);
645     return(py_retval);
646 }
647 #endif /* LIBXML_OUTPUT_ENABLED */
648 
649 
650 /**
651  * xmlParserInputBufferCreatePythonFile:
652  * @file:  a PyFile_Type
653  * @encoder:  the encoding converter or NULL
654  *
655  * Create a buffered output for the progressive saving to a PyFile_Type
656  * buffered C I/O
657  *
658  * Returns the new parser output or NULL
659  */
660 static xmlParserInputBufferPtr
xmlParserInputBufferCreatePythonFile(PyObject * file,xmlCharEncoding encoding)661 xmlParserInputBufferCreatePythonFile(PyObject *file,
662 	                        xmlCharEncoding encoding) {
663     xmlParserInputBufferPtr ret;
664 
665     if (file == NULL) return(NULL);
666 
667     ret = xmlAllocParserInputBuffer(encoding);
668     if (ret != NULL) {
669         ret->context = file;
670 	/* Py_INCREF(file); */
671 	ret->readcallback = xmlPythonFileRead;
672 	ret->closecallback = xmlPythonFileClose;
673     }
674 
675     return(ret);
676 }
677 
678 PyObject *
libxml_xmlCreateInputBuffer(ATTRIBUTE_UNUSED PyObject * self,PyObject * args)679 libxml_xmlCreateInputBuffer(ATTRIBUTE_UNUSED PyObject *self, PyObject *args) {
680     PyObject *py_retval;
681     PyObject *file;
682     xmlChar  *encoding;
683     xmlCharEncoding enc = XML_CHAR_ENCODING_NONE;
684     xmlParserInputBufferPtr buffer;
685 
686 
687     if (!PyArg_ParseTuple(args, (char *)"Oz:xmlParserInputBufferCreate",
688 		&file, &encoding))
689 	return(NULL);
690     if ((encoding != NULL) && (encoding[0] != 0)) {
691 	enc = xmlParseCharEncoding((const char *) encoding);
692     }
693     buffer = xmlParserInputBufferCreatePythonFile(file, enc);
694     if (buffer == NULL)
695 	printf("libxml_xmlParserInputBufferCreate: buffer == NULL\n");
696     py_retval = libxml_xmlParserInputBufferPtrWrap(buffer);
697     return(py_retval);
698 }
699 
700 /************************************************************************
701  *									*
702  *		Providing the resolver at the Python level		*
703  *									*
704  ************************************************************************/
705 
706 static xmlExternalEntityLoader defaultExternalEntityLoader = NULL;
707 static PyObject *pythonExternalEntityLoaderObjext;
708 
709 static xmlParserInputPtr
pythonExternalEntityLoader(const char * URL,const char * ID,xmlParserCtxtPtr ctxt)710 pythonExternalEntityLoader(const char *URL, const char *ID,
711 			   xmlParserCtxtPtr ctxt) {
712     xmlParserInputPtr result = NULL;
713     if (pythonExternalEntityLoaderObjext != NULL) {
714 	PyObject *ret;
715 	PyObject *ctxtobj;
716 
717 	ctxtobj = libxml_xmlParserCtxtPtrWrap(ctxt);
718 #ifdef DEBUG_LOADER
719 	printf("pythonExternalEntityLoader: ready to call\n");
720 #endif
721 
722 	ret = PyObject_CallFunction(pythonExternalEntityLoaderObjext,
723 		      (char *) "(ssO)", URL, ID, ctxtobj);
724 	Py_XDECREF(ctxtobj);
725 #ifdef DEBUG_LOADER
726 	printf("pythonExternalEntityLoader: result ");
727 	PyObject_Print(ret, stdout, 0);
728 	printf("\n");
729 #endif
730 
731 	if (ret != NULL) {
732 	    if (PyObject_HasAttrString(ret, (char *) "read")) {
733 		xmlParserInputBufferPtr buf;
734 
735 		buf = xmlAllocParserInputBuffer(XML_CHAR_ENCODING_NONE);
736 		if (buf != NULL) {
737 		    buf->context = ret;
738 		    buf->readcallback = xmlPythonFileReadRaw;
739 		    buf->closecallback = xmlPythonFileCloseRaw;
740 		    result = xmlNewIOInputStream(ctxt, buf,
741 			                         XML_CHAR_ENCODING_NONE);
742 		}
743 #if 0
744 	    } else {
745 		if (URL != NULL)
746 		    printf("pythonExternalEntityLoader: can't read %s\n",
747 		           URL);
748 #endif
749 	    }
750 	    if (result == NULL) {
751 		Py_DECREF(ret);
752 	    } else if (URL != NULL) {
753 		result->filename = (char *) xmlStrdup((const xmlChar *)URL);
754 		result->directory = xmlParserGetDirectory((const char *) URL);
755 	    }
756 	}
757     }
758     if ((result == NULL) && (defaultExternalEntityLoader != NULL)) {
759 	result = defaultExternalEntityLoader(URL, ID, ctxt);
760     }
761     return(result);
762 }
763 
764 PyObject *
libxml_xmlSetEntityLoader(ATTRIBUTE_UNUSED PyObject * self,PyObject * args)765 libxml_xmlSetEntityLoader(ATTRIBUTE_UNUSED PyObject *self, PyObject *args) {
766     PyObject *py_retval;
767     PyObject *loader;
768 
769     if (!PyArg_ParseTuple(args, (char *)"O:libxml_xmlSetEntityLoader",
770 		&loader))
771 	return(NULL);
772 
773     if (!PyCallable_Check(loader)) {
774 	PyErr_SetString(PyExc_ValueError, "entity loader is not callable");
775 	return(NULL);
776     }
777 
778 #ifdef DEBUG_LOADER
779     printf("libxml_xmlSetEntityLoader\n");
780 #endif
781     if (defaultExternalEntityLoader == NULL)
782 	defaultExternalEntityLoader = xmlGetExternalEntityLoader();
783 
784     Py_XDECREF(pythonExternalEntityLoaderObjext);
785     pythonExternalEntityLoaderObjext = loader;
786     Py_XINCREF(pythonExternalEntityLoaderObjext);
787     xmlSetExternalEntityLoader(pythonExternalEntityLoader);
788 
789     py_retval = PyLong_FromLong(0);
790     return(py_retval);
791 }
792 
793 /************************************************************************
794  *									*
795  *		Input callback registration				*
796  *									*
797  ************************************************************************/
798 static PyObject *pythonInputOpenCallbackObject;
799 static int pythonInputCallbackID = -1;
800 
801 static int
pythonInputMatchCallback(ATTRIBUTE_UNUSED const char * URI)802 pythonInputMatchCallback(ATTRIBUTE_UNUSED const char *URI)
803 {
804     /* Always return success, real decision whether URI is supported will be
805      * made in open callback.  */
806     return 1;
807 }
808 
809 static void *
pythonInputOpenCallback(const char * URI)810 pythonInputOpenCallback(const char *URI)
811 {
812     PyObject *ret;
813 
814     ret = PyObject_CallFunction(pythonInputOpenCallbackObject,
815 	    (char *)"s", URI);
816     if (ret == Py_None) {
817 	Py_DECREF(Py_None);
818 	return NULL;
819     }
820     return ret;
821 }
822 
823 PyObject *
libxml_xmlRegisterInputCallback(ATTRIBUTE_UNUSED PyObject * self,PyObject * args)824 libxml_xmlRegisterInputCallback(ATTRIBUTE_UNUSED PyObject *self,
825                                 PyObject *args) {
826     PyObject *cb;
827 
828     if (!PyArg_ParseTuple(args,
829 		(const char *)"O:libxml_xmlRegisterInputCallback", &cb))
830 	return(NULL);
831 
832     if (!PyCallable_Check(cb)) {
833 	PyErr_SetString(PyExc_ValueError, "input callback is not callable");
834 	return(NULL);
835     }
836 
837     /* Python module registers a single callback and manages the list of
838      * all callbacks internally. This is necessitated by xmlInputMatchCallback
839      * API, which does not allow for passing of data objects to discriminate
840      * different Python methods.  */
841     if (pythonInputCallbackID == -1) {
842 	pythonInputCallbackID = xmlRegisterInputCallbacks(
843 		pythonInputMatchCallback, pythonInputOpenCallback,
844 		xmlPythonFileReadRaw, xmlPythonFileCloseRaw);
845 	if (pythonInputCallbackID == -1)
846 	    return PyErr_NoMemory();
847 	pythonInputOpenCallbackObject = cb;
848 	Py_INCREF(pythonInputOpenCallbackObject);
849     }
850 
851     Py_INCREF(Py_None);
852     return(Py_None);
853 }
854 
855 PyObject *
libxml_xmlUnregisterInputCallback(ATTRIBUTE_UNUSED PyObject * self,ATTRIBUTE_UNUSED PyObject * args)856 libxml_xmlUnregisterInputCallback(ATTRIBUTE_UNUSED PyObject *self,
857                                 ATTRIBUTE_UNUSED PyObject *args) {
858     int ret;
859 
860     ret = xmlPopInputCallbacks();
861     if (pythonInputCallbackID != -1) {
862 	/* Assert that the right input callback was popped. libxml's API does not
863 	 * allow removal by ID, so all that could be done is an assert.  */
864 	if (pythonInputCallbackID == ret) {
865 	    pythonInputCallbackID = -1;
866 	    Py_DECREF(pythonInputOpenCallbackObject);
867 	    pythonInputOpenCallbackObject = NULL;
868 	} else {
869 	    PyErr_SetString(PyExc_AssertionError, "popped non-python input callback");
870 	    return(NULL);
871 	}
872     } else if (ret == -1) {
873 	/* No more callbacks to pop */
874 	PyErr_SetString(PyExc_IndexError, "no input callbacks to pop");
875 	return(NULL);
876     }
877 
878     Py_INCREF(Py_None);
879     return(Py_None);
880 }
881 
882 /************************************************************************
883  *									*
884  *		Handling SAX/xmllib/sgmlop callback interfaces		*
885  *									*
886  ************************************************************************/
887 
888 static void
pythonStartElement(void * user_data,const xmlChar * name,const xmlChar ** attrs)889 pythonStartElement(void *user_data, const xmlChar * name,
890                    const xmlChar ** attrs)
891 {
892     int i;
893     PyObject *handler;
894     PyObject *dict;
895     PyObject *attrname;
896     PyObject *attrvalue;
897     PyObject *result = NULL;
898     int type = 0;
899 
900 #ifdef DEBUG_SAX
901     printf("pythonStartElement(%s) called\n", name);
902 #endif
903     handler = (PyObject *) user_data;
904     if (PyObject_HasAttrString(handler, (char *) "startElement"))
905         type = 1;
906     else if (PyObject_HasAttrString(handler, (char *) "start"))
907         type = 2;
908     if (type != 0) {
909         /*
910          * the xmllib interface always generates a dictionary,
911          * possibly empty
912          */
913         if ((attrs == NULL) && (type == 1)) {
914             Py_XINCREF(Py_None);
915             dict = Py_None;
916         } else if (attrs == NULL) {
917             dict = PyDict_New();
918         } else {
919             dict = PyDict_New();
920             for (i = 0; attrs[i] != NULL; i++) {
921                 attrname = PY_IMPORT_STRING((char *) attrs[i]);
922                 i++;
923                 if (attrs[i] != NULL) {
924                     attrvalue = PY_IMPORT_STRING((char *) attrs[i]);
925                 } else {
926                     Py_XINCREF(Py_None);
927                     attrvalue = Py_None;
928                 }
929                 PyDict_SetItem(dict, attrname, attrvalue);
930 		Py_DECREF(attrname);
931 		Py_DECREF(attrvalue);
932             }
933         }
934 
935         if (type == 1)
936             result = PyObject_CallMethod(handler, (char *) "startElement",
937                                          (char *) "sO", name, dict);
938         else if (type == 2)
939             result = PyObject_CallMethod(handler, (char *) "start",
940                                          (char *) "sO", name, dict);
941         if (PyErr_Occurred())
942             PyErr_Print();
943         Py_XDECREF(dict);
944         Py_XDECREF(result);
945     }
946 }
947 
948 static void
pythonStartDocument(void * user_data)949 pythonStartDocument(void *user_data)
950 {
951     PyObject *handler;
952     PyObject *result;
953 
954 #ifdef DEBUG_SAX
955     printf("pythonStartDocument() called\n");
956 #endif
957     handler = (PyObject *) user_data;
958     if (PyObject_HasAttrString(handler, (char *) "startDocument")) {
959         result =
960             PyObject_CallMethod(handler, (char *) "startDocument", NULL);
961         if (PyErr_Occurred())
962             PyErr_Print();
963         Py_XDECREF(result);
964     }
965 }
966 
967 static void
pythonEndDocument(void * user_data)968 pythonEndDocument(void *user_data)
969 {
970     PyObject *handler;
971     PyObject *result;
972 
973 #ifdef DEBUG_SAX
974     printf("pythonEndDocument() called\n");
975 #endif
976     handler = (PyObject *) user_data;
977     if (PyObject_HasAttrString(handler, (char *) "endDocument")) {
978         result =
979             PyObject_CallMethod(handler, (char *) "endDocument", NULL);
980         if (PyErr_Occurred())
981             PyErr_Print();
982         Py_XDECREF(result);
983     }
984     /*
985      * The reference to the handler is released there
986      */
987     Py_XDECREF(handler);
988 }
989 
990 static void
pythonEndElement(void * user_data,const xmlChar * name)991 pythonEndElement(void *user_data, const xmlChar * name)
992 {
993     PyObject *handler;
994     PyObject *result;
995 
996 #ifdef DEBUG_SAX
997     printf("pythonEndElement(%s) called\n", name);
998 #endif
999     handler = (PyObject *) user_data;
1000     if (PyObject_HasAttrString(handler, (char *) "endElement")) {
1001         result = PyObject_CallMethod(handler, (char *) "endElement",
1002                                      (char *) "s", name);
1003         if (PyErr_Occurred())
1004             PyErr_Print();
1005         Py_XDECREF(result);
1006     } else if (PyObject_HasAttrString(handler, (char *) "end")) {
1007         result = PyObject_CallMethod(handler, (char *) "end",
1008                                      (char *) "s", name);
1009         if (PyErr_Occurred())
1010             PyErr_Print();
1011         Py_XDECREF(result);
1012     }
1013 }
1014 
1015 static void
pythonReference(void * user_data,const xmlChar * name)1016 pythonReference(void *user_data, const xmlChar * name)
1017 {
1018     PyObject *handler;
1019     PyObject *result;
1020 
1021 #ifdef DEBUG_SAX
1022     printf("pythonReference(%s) called\n", name);
1023 #endif
1024     handler = (PyObject *) user_data;
1025     if (PyObject_HasAttrString(handler, (char *) "reference")) {
1026         result = PyObject_CallMethod(handler, (char *) "reference",
1027                                      (char *) "s", name);
1028         if (PyErr_Occurred())
1029             PyErr_Print();
1030         Py_XDECREF(result);
1031     }
1032 }
1033 
1034 static void
pythonCharacters(void * user_data,const xmlChar * ch,int len)1035 pythonCharacters(void *user_data, const xmlChar * ch, int len)
1036 {
1037     PyObject *handler;
1038     PyObject *result = NULL;
1039     int type = 0;
1040 
1041 #ifdef DEBUG_SAX
1042     printf("pythonCharacters(%s, %d) called\n", ch, len);
1043 #endif
1044     handler = (PyObject *) user_data;
1045     if (PyObject_HasAttrString(handler, (char *) "characters"))
1046         type = 1;
1047     else if (PyObject_HasAttrString(handler, (char *) "data"))
1048         type = 2;
1049     if (type != 0) {
1050         if (type == 1)
1051             result = PyObject_CallMethod(handler, (char *) "characters",
1052                                          (char *) "s#", ch, (Py_ssize_t)len);
1053         else if (type == 2)
1054             result = PyObject_CallMethod(handler, (char *) "data",
1055                                          (char *) "s#", ch, (Py_ssize_t)len);
1056         if (PyErr_Occurred())
1057             PyErr_Print();
1058         Py_XDECREF(result);
1059     }
1060 }
1061 
1062 static void
pythonIgnorableWhitespace(void * user_data,const xmlChar * ch,int len)1063 pythonIgnorableWhitespace(void *user_data, const xmlChar * ch, int len)
1064 {
1065     PyObject *handler;
1066     PyObject *result = NULL;
1067     int type = 0;
1068 
1069 #ifdef DEBUG_SAX
1070     printf("pythonIgnorableWhitespace(%s, %d) called\n", ch, len);
1071 #endif
1072     handler = (PyObject *) user_data;
1073     if (PyObject_HasAttrString(handler, (char *) "ignorableWhitespace"))
1074         type = 1;
1075     else if (PyObject_HasAttrString(handler, (char *) "data"))
1076         type = 2;
1077     if (type != 0) {
1078         if (type == 1)
1079             result =
1080                 PyObject_CallMethod(handler,
1081                                     (char *) "ignorableWhitespace",
1082                                     (char *) "s#", ch, (Py_ssize_t)len);
1083         else if (type == 2)
1084             result =
1085                 PyObject_CallMethod(handler, (char *) "data",
1086                                     (char *) "s#", ch, (Py_ssize_t)len);
1087         Py_XDECREF(result);
1088     }
1089 }
1090 
1091 static void
pythonProcessingInstruction(void * user_data,const xmlChar * target,const xmlChar * data)1092 pythonProcessingInstruction(void *user_data,
1093                             const xmlChar * target, const xmlChar * data)
1094 {
1095     PyObject *handler;
1096     PyObject *result;
1097 
1098 #ifdef DEBUG_SAX
1099     printf("pythonProcessingInstruction(%s, %s) called\n", target, data);
1100 #endif
1101     handler = (PyObject *) user_data;
1102     if (PyObject_HasAttrString(handler, (char *) "processingInstruction")) {
1103         result = PyObject_CallMethod(handler, (char *)
1104                                      "processingInstruction",
1105                                      (char *) "ss", target, data);
1106         Py_XDECREF(result);
1107     }
1108 }
1109 
1110 static void
pythonComment(void * user_data,const xmlChar * value)1111 pythonComment(void *user_data, const xmlChar * value)
1112 {
1113     PyObject *handler;
1114     PyObject *result;
1115 
1116 #ifdef DEBUG_SAX
1117     printf("pythonComment(%s) called\n", value);
1118 #endif
1119     handler = (PyObject *) user_data;
1120     if (PyObject_HasAttrString(handler, (char *) "comment")) {
1121         result =
1122             PyObject_CallMethod(handler, (char *) "comment", (char *) "s",
1123                                 value);
1124         if (PyErr_Occurred())
1125             PyErr_Print();
1126         Py_XDECREF(result);
1127     }
1128 }
1129 
1130 static void
pythonWarning(void * user_data,const char * msg,...)1131 pythonWarning(void *user_data, const char *msg, ...)
1132 {
1133     PyObject *handler;
1134     PyObject *result;
1135     va_list args;
1136     char buf[1024];
1137 
1138 #ifdef DEBUG_SAX
1139     printf("pythonWarning(%s) called\n", msg);
1140 #endif
1141     handler = (PyObject *) user_data;
1142     if (PyObject_HasAttrString(handler, (char *) "warning")) {
1143         va_start(args, msg);
1144         vsnprintf(buf, 1023, msg, args);
1145         va_end(args);
1146         buf[1023] = 0;
1147         result =
1148             PyObject_CallMethod(handler, (char *) "warning", (char *) "s",
1149                                 buf);
1150         if (PyErr_Occurred())
1151             PyErr_Print();
1152         Py_XDECREF(result);
1153     }
1154 }
1155 
1156 static void
pythonError(void * user_data,const char * msg,...)1157 pythonError(void *user_data, const char *msg, ...)
1158 {
1159     PyObject *handler;
1160     PyObject *result;
1161     va_list args;
1162     char buf[1024];
1163 
1164 #ifdef DEBUG_SAX
1165     printf("pythonError(%s) called\n", msg);
1166 #endif
1167     handler = (PyObject *) user_data;
1168     if (PyObject_HasAttrString(handler, (char *) "error")) {
1169         va_start(args, msg);
1170         vsnprintf(buf, 1023, msg, args);
1171         va_end(args);
1172         buf[1023] = 0;
1173         result =
1174             PyObject_CallMethod(handler, (char *) "error", (char *) "s",
1175                                 buf);
1176         if (PyErr_Occurred())
1177             PyErr_Print();
1178         Py_XDECREF(result);
1179     }
1180 }
1181 
1182 static void
pythonFatalError(void * user_data,const char * msg,...)1183 pythonFatalError(void *user_data, const char *msg, ...)
1184 {
1185     PyObject *handler;
1186     PyObject *result;
1187     va_list args;
1188     char buf[1024];
1189 
1190 #ifdef DEBUG_SAX
1191     printf("pythonFatalError(%s) called\n", msg);
1192 #endif
1193     handler = (PyObject *) user_data;
1194     if (PyObject_HasAttrString(handler, (char *) "fatalError")) {
1195         va_start(args, msg);
1196         vsnprintf(buf, 1023, msg, args);
1197         va_end(args);
1198         buf[1023] = 0;
1199         result =
1200             PyObject_CallMethod(handler, (char *) "fatalError",
1201                                 (char *) "s", buf);
1202         if (PyErr_Occurred())
1203             PyErr_Print();
1204         Py_XDECREF(result);
1205     }
1206 }
1207 
1208 static void
pythonCdataBlock(void * user_data,const xmlChar * ch,int len)1209 pythonCdataBlock(void *user_data, const xmlChar * ch, int len)
1210 {
1211     PyObject *handler;
1212     PyObject *result = NULL;
1213     int type = 0;
1214 
1215 #ifdef DEBUG_SAX
1216     printf("pythonCdataBlock(%s, %d) called\n", ch, len);
1217 #endif
1218     handler = (PyObject *) user_data;
1219     if (PyObject_HasAttrString(handler, (char *) "cdataBlock"))
1220         type = 1;
1221     else if (PyObject_HasAttrString(handler, (char *) "cdata"))
1222         type = 2;
1223     if (type != 0) {
1224         if (type == 1)
1225             result =
1226                 PyObject_CallMethod(handler, (char *) "cdataBlock",
1227                                     (char *) "s#", ch, (Py_ssize_t)len);
1228         else if (type == 2)
1229             result =
1230                 PyObject_CallMethod(handler, (char *) "cdata",
1231                                     (char *) "s#", ch, (Py_ssize_t)len);
1232         if (PyErr_Occurred())
1233             PyErr_Print();
1234         Py_XDECREF(result);
1235     }
1236 }
1237 
1238 static void
pythonExternalSubset(void * user_data,const xmlChar * name,const xmlChar * externalID,const xmlChar * systemID)1239 pythonExternalSubset(void *user_data,
1240                      const xmlChar * name,
1241                      const xmlChar * externalID, const xmlChar * systemID)
1242 {
1243     PyObject *handler;
1244     PyObject *result;
1245 
1246 #ifdef DEBUG_SAX
1247     printf("pythonExternalSubset(%s, %s, %s) called\n",
1248            name, externalID, systemID);
1249 #endif
1250     handler = (PyObject *) user_data;
1251     if (PyObject_HasAttrString(handler, (char *) "externalSubset")) {
1252         result =
1253             PyObject_CallMethod(handler, (char *) "externalSubset",
1254                                 (char *) "sss", name, externalID,
1255                                 systemID);
1256         Py_XDECREF(result);
1257     }
1258 }
1259 
1260 static void
pythonEntityDecl(void * user_data,const xmlChar * name,int type,const xmlChar * publicId,const xmlChar * systemId,xmlChar * content)1261 pythonEntityDecl(void *user_data,
1262                  const xmlChar * name,
1263                  int type,
1264                  const xmlChar * publicId,
1265                  const xmlChar * systemId, xmlChar * content)
1266 {
1267     PyObject *handler;
1268     PyObject *result;
1269 
1270     handler = (PyObject *) user_data;
1271     if (PyObject_HasAttrString(handler, (char *) "entityDecl")) {
1272         result = PyObject_CallMethod(handler, (char *) "entityDecl",
1273                                      (char *) "sisss", name, type,
1274                                      publicId, systemId, content);
1275         if (PyErr_Occurred())
1276             PyErr_Print();
1277         Py_XDECREF(result);
1278     }
1279 }
1280 
1281 
1282 
1283 static void
1284 
pythonNotationDecl(void * user_data,const xmlChar * name,const xmlChar * publicId,const xmlChar * systemId)1285 pythonNotationDecl(void *user_data,
1286                    const xmlChar * name,
1287                    const xmlChar * publicId, const xmlChar * systemId)
1288 {
1289     PyObject *handler;
1290     PyObject *result;
1291 
1292     handler = (PyObject *) user_data;
1293     if (PyObject_HasAttrString(handler, (char *) "notationDecl")) {
1294         result = PyObject_CallMethod(handler, (char *) "notationDecl",
1295                                      (char *) "sss", name, publicId,
1296                                      systemId);
1297         if (PyErr_Occurred())
1298             PyErr_Print();
1299         Py_XDECREF(result);
1300     }
1301 }
1302 
1303 static void
pythonAttributeDecl(void * user_data,const xmlChar * elem,const xmlChar * name,int type,int def,const xmlChar * defaultValue,xmlEnumerationPtr tree)1304 pythonAttributeDecl(void *user_data,
1305                     const xmlChar * elem,
1306                     const xmlChar * name,
1307                     int type,
1308                     int def,
1309                     const xmlChar * defaultValue, xmlEnumerationPtr tree)
1310 {
1311     PyObject *handler;
1312     PyObject *nameList;
1313     PyObject *newName;
1314     xmlEnumerationPtr node;
1315     PyObject *result;
1316     int count;
1317 
1318     handler = (PyObject *) user_data;
1319     if (PyObject_HasAttrString(handler, (char *) "attributeDecl")) {
1320         count = 0;
1321         for (node = tree; node != NULL; node = node->next) {
1322             count++;
1323         }
1324         nameList = PyList_New(count);
1325         count = 0;
1326         for (node = tree; node != NULL; node = node->next) {
1327             newName = PY_IMPORT_STRING((char *) node->name);
1328             PyList_SetItem(nameList, count, newName);
1329 	    Py_DECREF(newName);
1330             count++;
1331         }
1332         result = PyObject_CallMethod(handler, (char *) "attributeDecl",
1333                                      (char *) "ssiisO", elem, name, type,
1334                                      def, defaultValue, nameList);
1335         if (PyErr_Occurred())
1336             PyErr_Print();
1337         Py_XDECREF(nameList);
1338         Py_XDECREF(result);
1339     }
1340 }
1341 
1342 static void
pythonElementDecl(void * user_data,const xmlChar * name,int type,ATTRIBUTE_UNUSED xmlElementContentPtr content)1343 pythonElementDecl(void *user_data,
1344                   const xmlChar * name,
1345                   int type, ATTRIBUTE_UNUSED xmlElementContentPtr content)
1346 {
1347     PyObject *handler;
1348     PyObject *obj;
1349     PyObject *result;
1350 
1351     handler = (PyObject *) user_data;
1352     if (PyObject_HasAttrString(handler, (char *) "elementDecl")) {
1353         /* TODO: wrap in an elementContent object */
1354         printf
1355             ("pythonElementDecl: xmlElementContentPtr wrapper missing !\n");
1356         obj = Py_None;
1357         /* Py_XINCREF(Py_None); isn't the reference just borrowed ??? */
1358         result = PyObject_CallMethod(handler, (char *) "elementDecl",
1359                                      (char *) "siO", name, type, obj);
1360         if (PyErr_Occurred())
1361             PyErr_Print();
1362         Py_XDECREF(result);
1363     }
1364 }
1365 
1366 static void
pythonUnparsedEntityDecl(void * user_data,const xmlChar * name,const xmlChar * publicId,const xmlChar * systemId,const xmlChar * notationName)1367 pythonUnparsedEntityDecl(void *user_data,
1368                          const xmlChar * name,
1369                          const xmlChar * publicId,
1370                          const xmlChar * systemId,
1371                          const xmlChar * notationName)
1372 {
1373     PyObject *handler;
1374     PyObject *result;
1375 
1376     handler = (PyObject *) user_data;
1377     if (PyObject_HasAttrString(handler, (char *) "unparsedEntityDecl")) {
1378         result =
1379             PyObject_CallMethod(handler, (char *) "unparsedEntityDecl",
1380                                 (char *) "ssss", name, publicId, systemId,
1381                                 notationName);
1382         if (PyErr_Occurred())
1383             PyErr_Print();
1384         Py_XDECREF(result);
1385     }
1386 }
1387 
1388 static void
pythonInternalSubset(void * user_data,const xmlChar * name,const xmlChar * ExternalID,const xmlChar * SystemID)1389 pythonInternalSubset(void *user_data, const xmlChar * name,
1390                      const xmlChar * ExternalID, const xmlChar * SystemID)
1391 {
1392     PyObject *handler;
1393     PyObject *result;
1394 
1395 #ifdef DEBUG_SAX
1396     printf("pythonInternalSubset(%s, %s, %s) called\n",
1397            name, ExternalID, SystemID);
1398 #endif
1399     handler = (PyObject *) user_data;
1400     if (PyObject_HasAttrString(handler, (char *) "internalSubset")) {
1401         result = PyObject_CallMethod(handler, (char *) "internalSubset",
1402                                      (char *) "sss", name, ExternalID,
1403                                      SystemID);
1404         if (PyErr_Occurred())
1405             PyErr_Print();
1406         Py_XDECREF(result);
1407     }
1408 }
1409 
1410 static xmlSAXHandler pythonSaxHandler = {
1411     pythonInternalSubset,
1412     NULL,                       /* TODO pythonIsStandalone, */
1413     NULL,                       /* TODO pythonHasInternalSubset, */
1414     NULL,                       /* TODO pythonHasExternalSubset, */
1415     NULL,                       /* TODO pythonResolveEntity, */
1416     NULL,                       /* TODO pythonGetEntity, */
1417     pythonEntityDecl,
1418     pythonNotationDecl,
1419     pythonAttributeDecl,
1420     pythonElementDecl,
1421     pythonUnparsedEntityDecl,
1422     NULL,                       /* OBSOLETED pythonSetDocumentLocator, */
1423     pythonStartDocument,
1424     pythonEndDocument,
1425     pythonStartElement,
1426     pythonEndElement,
1427     pythonReference,
1428     pythonCharacters,
1429     pythonIgnorableWhitespace,
1430     pythonProcessingInstruction,
1431     pythonComment,
1432     pythonWarning,
1433     pythonError,
1434     pythonFatalError,
1435     NULL,                       /* TODO pythonGetParameterEntity, */
1436     pythonCdataBlock,
1437     pythonExternalSubset,
1438     1,
1439     NULL,			/* TODO migrate to SAX2 */
1440     NULL,
1441     NULL,
1442     NULL
1443 };
1444 
1445 /************************************************************************
1446  *									*
1447  *		Handling of specific parser context			*
1448  *									*
1449  ************************************************************************/
1450 
1451 PyObject *
libxml_xmlCreatePushParser(ATTRIBUTE_UNUSED PyObject * self,PyObject * args)1452 libxml_xmlCreatePushParser(ATTRIBUTE_UNUSED PyObject * self,
1453                            PyObject * args)
1454 {
1455     const char *chunk;
1456     int size;
1457     const char *URI;
1458     PyObject *pyobj_SAX = NULL;
1459     xmlSAXHandlerPtr SAX = NULL;
1460     xmlParserCtxtPtr ret;
1461     PyObject *pyret;
1462 
1463     if (!PyArg_ParseTuple
1464         (args, (char *) "Oziz:xmlCreatePushParser", &pyobj_SAX, &chunk,
1465          &size, &URI))
1466         return (NULL);
1467 
1468 #ifdef DEBUG
1469     printf("libxml_xmlCreatePushParser(%p, %s, %d, %s) called\n",
1470            pyobj_SAX, chunk, size, URI);
1471 #endif
1472     if (pyobj_SAX != Py_None) {
1473         SAX = &pythonSaxHandler;
1474         Py_INCREF(pyobj_SAX);
1475         /* The reference is released in pythonEndDocument() */
1476     }
1477     ret = xmlCreatePushParserCtxt(SAX, pyobj_SAX, chunk, size, URI);
1478     pyret = libxml_xmlParserCtxtPtrWrap(ret);
1479     return (pyret);
1480 }
1481 
1482 PyObject *
libxml_htmlCreatePushParser(ATTRIBUTE_UNUSED PyObject * self,PyObject * args)1483 libxml_htmlCreatePushParser(ATTRIBUTE_UNUSED PyObject * self,
1484                             PyObject * args)
1485 {
1486 #ifdef LIBXML_HTML_ENABLED
1487     const char *chunk;
1488     int size;
1489     const char *URI;
1490     PyObject *pyobj_SAX = NULL;
1491     xmlSAXHandlerPtr SAX = NULL;
1492     xmlParserCtxtPtr ret;
1493     PyObject *pyret;
1494 
1495     if (!PyArg_ParseTuple
1496         (args, (char *) "Oziz:htmlCreatePushParser", &pyobj_SAX, &chunk,
1497          &size, &URI))
1498         return (NULL);
1499 
1500 #ifdef DEBUG
1501     printf("libxml_htmlCreatePushParser(%p, %s, %d, %s) called\n",
1502            pyobj_SAX, chunk, size, URI);
1503 #endif
1504     if (pyobj_SAX != Py_None) {
1505         SAX = &pythonSaxHandler;
1506         Py_INCREF(pyobj_SAX);
1507         /* The reference is released in pythonEndDocument() */
1508     }
1509     ret = htmlCreatePushParserCtxt(SAX, pyobj_SAX, chunk, size, URI,
1510                                    XML_CHAR_ENCODING_NONE);
1511     pyret = libxml_xmlParserCtxtPtrWrap(ret);
1512     return (pyret);
1513 #else
1514     Py_INCREF(Py_None);
1515     return (Py_None);
1516 #endif /* LIBXML_HTML_ENABLED */
1517 }
1518 
1519 PyObject *
libxml_xmlSAXParseFile(ATTRIBUTE_UNUSED PyObject * self,PyObject * args)1520 libxml_xmlSAXParseFile(ATTRIBUTE_UNUSED PyObject * self, PyObject * args)
1521 {
1522 #ifdef LIBXML_SAX1_ENABLED
1523     int recover;
1524     const char *URI;
1525     PyObject *pyobj_SAX = NULL;
1526     xmlSAXHandlerPtr SAX = NULL;
1527 
1528     if (!PyArg_ParseTuple(args, (char *) "Osi:xmlSAXParseFile", &pyobj_SAX,
1529                           &URI, &recover))
1530         return (NULL);
1531 
1532 #ifdef DEBUG
1533     printf("libxml_xmlSAXParseFile(%p, %s, %d) called\n",
1534            pyobj_SAX, URI, recover);
1535 #endif
1536     if (pyobj_SAX == Py_None) {
1537         Py_INCREF(Py_None);
1538         return (Py_None);
1539     }
1540     SAX = &pythonSaxHandler;
1541     Py_INCREF(pyobj_SAX);
1542     /* The reference is released in pythonEndDocument() */
1543     xmlSAXUserParseFile(SAX, pyobj_SAX, URI);
1544 #endif /* LIBXML_SAX1_ENABLED */
1545     Py_INCREF(Py_None);
1546     return (Py_None);
1547 }
1548 
1549 PyObject *
libxml_htmlSAXParseFile(ATTRIBUTE_UNUSED PyObject * self,PyObject * args)1550 libxml_htmlSAXParseFile(ATTRIBUTE_UNUSED PyObject * self, PyObject * args)
1551 {
1552 #ifdef LIBXML_HTML_ENABLED
1553     const char *URI;
1554     const char *encoding;
1555     PyObject *pyobj_SAX = NULL;
1556     xmlSAXHandlerPtr SAX = NULL;
1557 
1558     if (!PyArg_ParseTuple
1559         (args, (char *) "Osz:htmlSAXParseFile", &pyobj_SAX, &URI,
1560          &encoding))
1561         return (NULL);
1562 
1563 #ifdef DEBUG
1564     printf("libxml_htmlSAXParseFile(%p, %s, %s) called\n",
1565            pyobj_SAX, URI, encoding);
1566 #endif
1567     if (pyobj_SAX == Py_None) {
1568         Py_INCREF(Py_None);
1569         return (Py_None);
1570     }
1571     SAX = &pythonSaxHandler;
1572     Py_INCREF(pyobj_SAX);
1573     /* The reference is released in pythonEndDocument() */
1574     htmlSAXParseFile(URI, encoding, SAX, pyobj_SAX);
1575     Py_INCREF(Py_None);
1576     return (Py_None);
1577 #else
1578     Py_INCREF(Py_None);
1579     return (Py_None);
1580 #endif /* LIBXML_HTML_ENABLED */
1581 }
1582 
1583 /************************************************************************
1584  *									*
1585  *			Error message callback				*
1586  *									*
1587  ************************************************************************/
1588 
1589 static PyObject *libxml_xmlPythonErrorFuncHandler = NULL;
1590 static PyObject *libxml_xmlPythonErrorFuncCtxt = NULL;
1591 
1592 /* helper to build a xmlMalloc'ed string from a format and va_list */
1593 /*
1594  * disabled the loop, the repeated call to vsnprintf without reset of ap
1595  * in case the initial buffer was too small segfaulted on x86_64
1596  * we now directly vsnprintf on a large buffer.
1597  */
1598 static char *
libxml_buildMessage(const char * msg,va_list ap)1599 libxml_buildMessage(const char *msg, va_list ap)
1600 {
1601     int chars;
1602     char *str;
1603 
1604     str = (char *) xmlMalloc(1000);
1605     if (str == NULL)
1606         return NULL;
1607 
1608     chars = vsnprintf(str, 999, msg, ap);
1609     if (chars >= 998)
1610         str[999] = 0;
1611 
1612     return str;
1613 }
1614 
1615 static void
libxml_xmlErrorFuncHandler(ATTRIBUTE_UNUSED void * ctx,const char * msg,...)1616 libxml_xmlErrorFuncHandler(ATTRIBUTE_UNUSED void *ctx, const char *msg,
1617                            ...)
1618 {
1619     va_list ap;
1620     PyObject *list;
1621     PyObject *message;
1622     PyObject *result;
1623     char str[1000];
1624 
1625 #ifdef DEBUG_ERROR
1626     printf("libxml_xmlErrorFuncHandler(%p, %s, ...) called\n", ctx, msg);
1627 #endif
1628 
1629 
1630     if (libxml_xmlPythonErrorFuncHandler == NULL) {
1631         va_start(ap, msg);
1632         vfprintf(stderr, msg, ap);
1633         va_end(ap);
1634     } else {
1635         va_start(ap, msg);
1636         if (vsnprintf(str, 999, msg, ap) >= 998)
1637 	    str[999] = 0;
1638         va_end(ap);
1639 
1640         list = PyTuple_New(2);
1641         PyTuple_SetItem(list, 0, libxml_xmlPythonErrorFuncCtxt);
1642         Py_XINCREF(libxml_xmlPythonErrorFuncCtxt);
1643         message = libxml_charPtrConstWrap(str);
1644         PyTuple_SetItem(list, 1, message);
1645         result = PyEval_CallObject(libxml_xmlPythonErrorFuncHandler, list);
1646         Py_XDECREF(list);
1647         Py_XDECREF(result);
1648     }
1649 }
1650 
1651 static void
libxml_xmlErrorInitialize(void)1652 libxml_xmlErrorInitialize(void)
1653 {
1654 #ifdef DEBUG_ERROR
1655     printf("libxml_xmlErrorInitialize() called\n");
1656 #endif
1657     xmlSetGenericErrorFunc(NULL, libxml_xmlErrorFuncHandler);
1658     xmlThrDefSetGenericErrorFunc(NULL, libxml_xmlErrorFuncHandler);
1659 }
1660 
1661 static PyObject *
libxml_xmlRegisterErrorHandler(ATTRIBUTE_UNUSED PyObject * self,PyObject * args)1662 libxml_xmlRegisterErrorHandler(ATTRIBUTE_UNUSED PyObject * self,
1663                                PyObject * args)
1664 {
1665     PyObject *py_retval;
1666     PyObject *pyobj_f;
1667     PyObject *pyobj_ctx;
1668 
1669     if (!PyArg_ParseTuple
1670         (args, (char *) "OO:xmlRegisterErrorHandler", &pyobj_f,
1671          &pyobj_ctx))
1672         return (NULL);
1673 
1674 #ifdef DEBUG_ERROR
1675     printf("libxml_xmlRegisterErrorHandler(%p, %p) called\n", pyobj_ctx,
1676            pyobj_f);
1677 #endif
1678 
1679     if (libxml_xmlPythonErrorFuncHandler != NULL) {
1680         Py_XDECREF(libxml_xmlPythonErrorFuncHandler);
1681     }
1682     if (libxml_xmlPythonErrorFuncCtxt != NULL) {
1683         Py_XDECREF(libxml_xmlPythonErrorFuncCtxt);
1684     }
1685 
1686     Py_XINCREF(pyobj_ctx);
1687     Py_XINCREF(pyobj_f);
1688 
1689     /* TODO: check f is a function ! */
1690     libxml_xmlPythonErrorFuncHandler = pyobj_f;
1691     libxml_xmlPythonErrorFuncCtxt = pyobj_ctx;
1692 
1693     py_retval = libxml_intWrap(1);
1694     return (py_retval);
1695 }
1696 
1697 
1698 /************************************************************************
1699  *									*
1700  *                      Per parserCtxt error handler                    *
1701  *									*
1702  ************************************************************************/
1703 
1704 typedef struct
1705 {
1706     PyObject *f;
1707     PyObject *arg;
1708 } xmlParserCtxtPyCtxt;
1709 typedef xmlParserCtxtPyCtxt *xmlParserCtxtPyCtxtPtr;
1710 
1711 static void
libxml_xmlParserCtxtGenericErrorFuncHandler(void * ctx,int severity,char * str)1712 libxml_xmlParserCtxtGenericErrorFuncHandler(void *ctx, int severity, char *str)
1713 {
1714     PyObject *list;
1715     PyObject *result;
1716     xmlParserCtxtPtr ctxt;
1717     xmlParserCtxtPyCtxtPtr pyCtxt;
1718 
1719 #ifdef DEBUG_ERROR
1720     printf("libxml_xmlParserCtxtGenericErrorFuncHandler(%p, %s, ...) called\n", ctx, str);
1721 #endif
1722 
1723     ctxt = (xmlParserCtxtPtr)ctx;
1724     pyCtxt = (xmlParserCtxtPyCtxtPtr)ctxt->_private;
1725 
1726     list = PyTuple_New(4);
1727     PyTuple_SetItem(list, 0, pyCtxt->arg);
1728     Py_XINCREF(pyCtxt->arg);
1729     PyTuple_SetItem(list, 1, libxml_charPtrWrap(str));
1730     PyTuple_SetItem(list, 2, libxml_intWrap(severity));
1731     PyTuple_SetItem(list, 3, Py_None);
1732     Py_INCREF(Py_None);
1733     result = PyEval_CallObject(pyCtxt->f, list);
1734     if (result == NULL)
1735     {
1736 	/* TODO: manage for the exception to be propagated... */
1737 	PyErr_Print();
1738     }
1739     Py_XDECREF(list);
1740     Py_XDECREF(result);
1741 }
1742 
1743 static void
libxml_xmlParserCtxtErrorFuncHandler(void * ctx,const char * msg,...)1744 libxml_xmlParserCtxtErrorFuncHandler(void *ctx, const char *msg, ...)
1745 {
1746     va_list ap;
1747 
1748     va_start(ap, msg);
1749     libxml_xmlParserCtxtGenericErrorFuncHandler(ctx,XML_PARSER_SEVERITY_ERROR,libxml_buildMessage(msg,ap));
1750     va_end(ap);
1751 }
1752 
1753 static void
libxml_xmlParserCtxtWarningFuncHandler(void * ctx,const char * msg,...)1754 libxml_xmlParserCtxtWarningFuncHandler(void *ctx, const char *msg, ...)
1755 {
1756     va_list ap;
1757 
1758     va_start(ap, msg);
1759     libxml_xmlParserCtxtGenericErrorFuncHandler(ctx,XML_PARSER_SEVERITY_WARNING,libxml_buildMessage(msg,ap));
1760     va_end(ap);
1761 }
1762 
1763 static void
libxml_xmlParserCtxtValidityErrorFuncHandler(void * ctx,const char * msg,...)1764 libxml_xmlParserCtxtValidityErrorFuncHandler(void *ctx, const char *msg, ...)
1765 {
1766     va_list ap;
1767 
1768     va_start(ap, msg);
1769     libxml_xmlParserCtxtGenericErrorFuncHandler(ctx,XML_PARSER_SEVERITY_VALIDITY_ERROR,libxml_buildMessage(msg,ap));
1770     va_end(ap);
1771 }
1772 
1773 static void
libxml_xmlParserCtxtValidityWarningFuncHandler(void * ctx,const char * msg,...)1774 libxml_xmlParserCtxtValidityWarningFuncHandler(void *ctx, const char *msg, ...)
1775 {
1776     va_list ap;
1777 
1778     va_start(ap, msg);
1779     libxml_xmlParserCtxtGenericErrorFuncHandler(ctx,XML_PARSER_SEVERITY_VALIDITY_WARNING,libxml_buildMessage(msg,ap));
1780     va_end(ap);
1781 }
1782 
1783 static PyObject *
libxml_xmlParserCtxtSetErrorHandler(ATTRIBUTE_UNUSED PyObject * self,PyObject * args)1784 libxml_xmlParserCtxtSetErrorHandler(ATTRIBUTE_UNUSED PyObject *self, PyObject *args)
1785 {
1786     PyObject *py_retval;
1787     xmlParserCtxtPtr ctxt;
1788     xmlParserCtxtPyCtxtPtr pyCtxt;
1789     PyObject *pyobj_ctxt;
1790     PyObject *pyobj_f;
1791     PyObject *pyobj_arg;
1792 
1793     if (!PyArg_ParseTuple(args, (char *)"OOO:xmlParserCtxtSetErrorHandler",
1794 		          &pyobj_ctxt, &pyobj_f, &pyobj_arg))
1795         return(NULL);
1796     ctxt = (xmlParserCtxtPtr) PyparserCtxt_Get(pyobj_ctxt);
1797     if (ctxt->_private == NULL) {
1798 	pyCtxt = xmlMalloc(sizeof(xmlParserCtxtPyCtxt));
1799 	if (pyCtxt == NULL) {
1800 	    py_retval = libxml_intWrap(-1);
1801 	    return(py_retval);
1802 	}
1803 	memset(pyCtxt,0,sizeof(xmlParserCtxtPyCtxt));
1804 	ctxt->_private = pyCtxt;
1805     }
1806     else {
1807 	pyCtxt = (xmlParserCtxtPyCtxtPtr)ctxt->_private;
1808     }
1809     /* TODO: check f is a function ! */
1810     Py_XDECREF(pyCtxt->f);
1811     Py_XINCREF(pyobj_f);
1812     pyCtxt->f = pyobj_f;
1813     Py_XDECREF(pyCtxt->arg);
1814     Py_XINCREF(pyobj_arg);
1815     pyCtxt->arg = pyobj_arg;
1816 
1817     if (pyobj_f != Py_None) {
1818 	ctxt->sax->error = libxml_xmlParserCtxtErrorFuncHandler;
1819 	ctxt->sax->warning = libxml_xmlParserCtxtWarningFuncHandler;
1820 	ctxt->vctxt.error = libxml_xmlParserCtxtValidityErrorFuncHandler;
1821 	ctxt->vctxt.warning = libxml_xmlParserCtxtValidityWarningFuncHandler;
1822     }
1823     else {
1824 	ctxt->sax->error = xmlParserError;
1825 	ctxt->vctxt.error = xmlParserValidityError;
1826 	ctxt->sax->warning = xmlParserWarning;
1827 	ctxt->vctxt.warning = xmlParserValidityWarning;
1828     }
1829 
1830     py_retval = libxml_intWrap(1);
1831     return(py_retval);
1832 }
1833 
1834 static PyObject *
libxml_xmlParserCtxtGetErrorHandler(ATTRIBUTE_UNUSED PyObject * self,PyObject * args)1835 libxml_xmlParserCtxtGetErrorHandler(ATTRIBUTE_UNUSED PyObject *self, PyObject *args)
1836 {
1837     PyObject *py_retval;
1838     xmlParserCtxtPtr ctxt;
1839     xmlParserCtxtPyCtxtPtr pyCtxt;
1840     PyObject *pyobj_ctxt;
1841 
1842     if (!PyArg_ParseTuple(args, (char *)"O:xmlParserCtxtGetErrorHandler",
1843 		          &pyobj_ctxt))
1844         return(NULL);
1845     ctxt = (xmlParserCtxtPtr) PyparserCtxt_Get(pyobj_ctxt);
1846     py_retval = PyTuple_New(2);
1847     if (ctxt->_private != NULL) {
1848 	pyCtxt = (xmlParserCtxtPyCtxtPtr)ctxt->_private;
1849 
1850 	PyTuple_SetItem(py_retval, 0, pyCtxt->f);
1851 	Py_XINCREF(pyCtxt->f);
1852 	PyTuple_SetItem(py_retval, 1, pyCtxt->arg);
1853 	Py_XINCREF(pyCtxt->arg);
1854     }
1855     else {
1856 	/* no python error handler registered */
1857 	PyTuple_SetItem(py_retval, 0, Py_None);
1858 	Py_XINCREF(Py_None);
1859 	PyTuple_SetItem(py_retval, 1, Py_None);
1860 	Py_XINCREF(Py_None);
1861     }
1862     return(py_retval);
1863 }
1864 
1865 static PyObject *
libxml_xmlFreeParserCtxt(ATTRIBUTE_UNUSED PyObject * self,PyObject * args)1866 libxml_xmlFreeParserCtxt(ATTRIBUTE_UNUSED PyObject *self, PyObject *args) {
1867     xmlParserCtxtPtr ctxt;
1868     PyObject *pyobj_ctxt;
1869     xmlParserCtxtPyCtxtPtr pyCtxt;
1870 
1871     if (!PyArg_ParseTuple(args, (char *)"O:xmlFreeParserCtxt", &pyobj_ctxt))
1872         return(NULL);
1873     ctxt = (xmlParserCtxtPtr) PyparserCtxt_Get(pyobj_ctxt);
1874 
1875     if (ctxt != NULL) {
1876 	pyCtxt = (xmlParserCtxtPyCtxtPtr)((xmlParserCtxtPtr)ctxt)->_private;
1877 	if (pyCtxt) {
1878 	    Py_XDECREF(pyCtxt->f);
1879 	    Py_XDECREF(pyCtxt->arg);
1880 	    xmlFree(pyCtxt);
1881 	}
1882 	xmlFreeParserCtxt(ctxt);
1883     }
1884 
1885     Py_INCREF(Py_None);
1886     return(Py_None);
1887 }
1888 
1889 /***
1890  * xmlValidCtxt stuff
1891  */
1892 
1893 typedef struct
1894 {
1895     PyObject *warn;
1896     PyObject *error;
1897     PyObject *arg;
1898 } xmlValidCtxtPyCtxt;
1899 typedef xmlValidCtxtPyCtxt *xmlValidCtxtPyCtxtPtr;
1900 
1901 static void
libxml_xmlValidCtxtGenericErrorFuncHandler(void * ctx,ATTRIBUTE_UNUSED int severity,char * str)1902 libxml_xmlValidCtxtGenericErrorFuncHandler(void *ctx, ATTRIBUTE_UNUSED int severity, char *str)
1903 {
1904     PyObject *list;
1905     PyObject *result;
1906     xmlValidCtxtPyCtxtPtr pyCtxt;
1907 
1908 #ifdef DEBUG_ERROR
1909     printf("libxml_xmlValidCtxtGenericErrorFuncHandler(%p, %d, %s, ...) called\n", ctx, severity, str);
1910 #endif
1911 
1912     pyCtxt = (xmlValidCtxtPyCtxtPtr)ctx;
1913 
1914     list = PyTuple_New(2);
1915     PyTuple_SetItem(list, 0, libxml_charPtrWrap(str));
1916     PyTuple_SetItem(list, 1, pyCtxt->arg);
1917     Py_XINCREF(pyCtxt->arg);
1918     result = PyEval_CallObject(pyCtxt->error, list);
1919     if (result == NULL)
1920     {
1921 	/* TODO: manage for the exception to be propagated... */
1922 	PyErr_Print();
1923     }
1924     Py_XDECREF(list);
1925     Py_XDECREF(result);
1926 }
1927 
1928 static void
libxml_xmlValidCtxtGenericWarningFuncHandler(void * ctx,ATTRIBUTE_UNUSED int severity,char * str)1929 libxml_xmlValidCtxtGenericWarningFuncHandler(void *ctx, ATTRIBUTE_UNUSED int severity, char *str)
1930 {
1931     PyObject *list;
1932     PyObject *result;
1933     xmlValidCtxtPyCtxtPtr pyCtxt;
1934 
1935 #ifdef DEBUG_ERROR
1936     printf("libxml_xmlValidCtxtGenericWarningFuncHandler(%p, %d, %s, ...) called\n", ctx, severity, str);
1937 #endif
1938 
1939     pyCtxt = (xmlValidCtxtPyCtxtPtr)ctx;
1940 
1941     list = PyTuple_New(2);
1942     PyTuple_SetItem(list, 0, libxml_charPtrWrap(str));
1943     PyTuple_SetItem(list, 1, pyCtxt->arg);
1944     Py_XINCREF(pyCtxt->arg);
1945     result = PyEval_CallObject(pyCtxt->warn, list);
1946     if (result == NULL)
1947     {
1948 	/* TODO: manage for the exception to be propagated... */
1949 	PyErr_Print();
1950     }
1951     Py_XDECREF(list);
1952     Py_XDECREF(result);
1953 }
1954 
1955 static void
libxml_xmlValidCtxtErrorFuncHandler(void * ctx,const char * msg,...)1956 libxml_xmlValidCtxtErrorFuncHandler(void *ctx, const char *msg, ...)
1957 {
1958     va_list ap;
1959 
1960     va_start(ap, msg);
1961     libxml_xmlValidCtxtGenericErrorFuncHandler(ctx,XML_PARSER_SEVERITY_VALIDITY_ERROR,libxml_buildMessage(msg,ap));
1962     va_end(ap);
1963 }
1964 
1965 static void
libxml_xmlValidCtxtWarningFuncHandler(void * ctx,const char * msg,...)1966 libxml_xmlValidCtxtWarningFuncHandler(void *ctx, const char *msg, ...)
1967 {
1968     va_list ap;
1969 
1970     va_start(ap, msg);
1971     libxml_xmlValidCtxtGenericWarningFuncHandler(ctx,XML_PARSER_SEVERITY_VALIDITY_WARNING,libxml_buildMessage(msg,ap));
1972     va_end(ap);
1973 }
1974 
1975 static PyObject *
libxml_xmlSetValidErrors(ATTRIBUTE_UNUSED PyObject * self,PyObject * args)1976 libxml_xmlSetValidErrors(ATTRIBUTE_UNUSED PyObject * self, PyObject * args)
1977 {
1978     PyObject *py_retval;
1979     PyObject *pyobj_error;
1980     PyObject *pyobj_warn;
1981     PyObject *pyobj_ctx;
1982     PyObject *pyobj_arg = Py_None;
1983     xmlValidCtxtPtr ctxt;
1984     xmlValidCtxtPyCtxtPtr pyCtxt;
1985 
1986     if (!PyArg_ParseTuple
1987         (args, (char *) "OOO|O:xmlSetValidErrors", &pyobj_ctx, &pyobj_error, &pyobj_warn, &pyobj_arg))
1988         return (NULL);
1989 
1990 #ifdef DEBUG_ERROR
1991     printf("libxml_xmlSetValidErrors(%p, %p, %p) called\n", pyobj_ctx, pyobj_error, pyobj_warn);
1992 #endif
1993 
1994     ctxt = PyValidCtxt_Get(pyobj_ctx);
1995     pyCtxt = xmlMalloc(sizeof(xmlValidCtxtPyCtxt));
1996     if (pyCtxt == NULL) {
1997             py_retval = libxml_intWrap(-1);
1998             return(py_retval);
1999     }
2000     memset(pyCtxt, 0, sizeof(xmlValidCtxtPyCtxt));
2001 
2002 
2003     /* TODO: check warn and error is a function ! */
2004     Py_XDECREF(pyCtxt->error);
2005     Py_XINCREF(pyobj_error);
2006     pyCtxt->error = pyobj_error;
2007 
2008     Py_XDECREF(pyCtxt->warn);
2009     Py_XINCREF(pyobj_warn);
2010     pyCtxt->warn = pyobj_warn;
2011 
2012     Py_XDECREF(pyCtxt->arg);
2013     Py_XINCREF(pyobj_arg);
2014     pyCtxt->arg = pyobj_arg;
2015 
2016     ctxt->error = libxml_xmlValidCtxtErrorFuncHandler;
2017     ctxt->warning = libxml_xmlValidCtxtWarningFuncHandler;
2018     ctxt->userData = pyCtxt;
2019 
2020     py_retval = libxml_intWrap(1);
2021     return (py_retval);
2022 }
2023 
2024 
2025 static PyObject *
libxml_xmlFreeValidCtxt(PyObject * self ATTRIBUTE_UNUSED,PyObject * args)2026 libxml_xmlFreeValidCtxt(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) {
2027     xmlValidCtxtPtr cur;
2028     xmlValidCtxtPyCtxtPtr pyCtxt;
2029     PyObject *pyobj_cur;
2030 
2031     if (!PyArg_ParseTuple(args, (char *)"O:xmlFreeValidCtxt", &pyobj_cur))
2032         return(NULL);
2033     cur = (xmlValidCtxtPtr) PyValidCtxt_Get(pyobj_cur);
2034 
2035     pyCtxt = (xmlValidCtxtPyCtxtPtr)(cur->userData);
2036     if (pyCtxt != NULL)
2037     {
2038             Py_XDECREF(pyCtxt->error);
2039             Py_XDECREF(pyCtxt->warn);
2040             Py_XDECREF(pyCtxt->arg);
2041             xmlFree(pyCtxt);
2042     }
2043 
2044     xmlFreeValidCtxt(cur);
2045     Py_INCREF(Py_None);
2046     return(Py_None);
2047 }
2048 
2049 #ifdef LIBXML_READER_ENABLED
2050 /************************************************************************
2051  *									*
2052  *                      Per xmlTextReader error handler                 *
2053  *									*
2054  ************************************************************************/
2055 
2056 typedef struct
2057 {
2058     PyObject *f;
2059     PyObject *arg;
2060 } xmlTextReaderPyCtxt;
2061 typedef xmlTextReaderPyCtxt *xmlTextReaderPyCtxtPtr;
2062 
2063 static void
libxml_xmlTextReaderErrorCallback(void * arg,const char * msg,int severity,xmlTextReaderLocatorPtr locator)2064 libxml_xmlTextReaderErrorCallback(void *arg,
2065 				  const char *msg,
2066 				  int severity,
2067 				  xmlTextReaderLocatorPtr locator)
2068 {
2069     xmlTextReaderPyCtxt *pyCtxt = (xmlTextReaderPyCtxt *)arg;
2070     PyObject *list;
2071     PyObject *result;
2072 
2073     list = PyTuple_New(4);
2074     PyTuple_SetItem(list, 0, pyCtxt->arg);
2075     Py_XINCREF(pyCtxt->arg);
2076     PyTuple_SetItem(list, 1, libxml_charPtrConstWrap(msg));
2077     PyTuple_SetItem(list, 2, libxml_intWrap(severity));
2078     PyTuple_SetItem(list, 3, libxml_xmlTextReaderLocatorPtrWrap(locator));
2079     result = PyEval_CallObject(pyCtxt->f, list);
2080     if (result == NULL)
2081     {
2082 	/* TODO: manage for the exception to be propagated... */
2083 	PyErr_Print();
2084     }
2085     Py_XDECREF(list);
2086     Py_XDECREF(result);
2087 }
2088 
2089 static PyObject *
libxml_xmlTextReaderSetErrorHandler(ATTRIBUTE_UNUSED PyObject * self,PyObject * args)2090 libxml_xmlTextReaderSetErrorHandler(ATTRIBUTE_UNUSED PyObject *self, PyObject *args)
2091 {
2092     xmlTextReaderPtr reader;
2093     xmlTextReaderPyCtxtPtr pyCtxt;
2094     xmlTextReaderErrorFunc f;
2095     void *arg;
2096     PyObject *pyobj_reader;
2097     PyObject *pyobj_f;
2098     PyObject *pyobj_arg;
2099     PyObject *py_retval;
2100 
2101     if (!PyArg_ParseTuple(args, (char *)"OOO:xmlTextReaderSetErrorHandler", &pyobj_reader, &pyobj_f, &pyobj_arg))
2102         return(NULL);
2103     reader = (xmlTextReaderPtr) PyxmlTextReader_Get(pyobj_reader);
2104     /* clear previous error handler */
2105     xmlTextReaderGetErrorHandler(reader,&f,&arg);
2106     if (arg != NULL) {
2107 	if (f == (xmlTextReaderErrorFunc) libxml_xmlTextReaderErrorCallback) {
2108 	    /* ok, it's our error handler! */
2109 	    pyCtxt = (xmlTextReaderPyCtxtPtr)arg;
2110 	    Py_XDECREF(pyCtxt->f);
2111 	    Py_XDECREF(pyCtxt->arg);
2112 	    xmlFree(pyCtxt);
2113 	}
2114 	else {
2115 	    /*
2116 	     * there already an arg, and it's not ours,
2117 	     * there is definitely something wrong going on here...
2118 	     * we don't know how to free it, so we bail out...
2119 	     */
2120 	    py_retval = libxml_intWrap(-1);
2121 	    return(py_retval);
2122 	}
2123     }
2124     xmlTextReaderSetErrorHandler(reader,NULL,NULL);
2125     /* set new error handler */
2126     if (pyobj_f != Py_None)
2127     {
2128 	pyCtxt = (xmlTextReaderPyCtxtPtr)xmlMalloc(sizeof(xmlTextReaderPyCtxt));
2129 	if (pyCtxt == NULL) {
2130 	    py_retval = libxml_intWrap(-1);
2131 	    return(py_retval);
2132 	}
2133 	Py_XINCREF(pyobj_f);
2134 	pyCtxt->f = pyobj_f;
2135 	Py_XINCREF(pyobj_arg);
2136 	pyCtxt->arg = pyobj_arg;
2137 	xmlTextReaderSetErrorHandler(reader,
2138 	    (xmlTextReaderErrorFunc) libxml_xmlTextReaderErrorCallback,
2139 	                             pyCtxt);
2140     }
2141 
2142     py_retval = libxml_intWrap(1);
2143     return(py_retval);
2144 }
2145 
2146 static PyObject *
libxml_xmlTextReaderGetErrorHandler(ATTRIBUTE_UNUSED PyObject * self,PyObject * args)2147 libxml_xmlTextReaderGetErrorHandler(ATTRIBUTE_UNUSED PyObject *self, PyObject *args)
2148 {
2149     xmlTextReaderPtr reader;
2150     xmlTextReaderPyCtxtPtr pyCtxt;
2151     xmlTextReaderErrorFunc f;
2152     void *arg;
2153     PyObject *pyobj_reader;
2154     PyObject *py_retval;
2155 
2156     if (!PyArg_ParseTuple(args, (char *)"O:xmlTextReaderSetErrorHandler", &pyobj_reader))
2157         return(NULL);
2158     reader = (xmlTextReaderPtr) PyxmlTextReader_Get(pyobj_reader);
2159     xmlTextReaderGetErrorHandler(reader,&f,&arg);
2160     py_retval = PyTuple_New(2);
2161     if (f == (xmlTextReaderErrorFunc)libxml_xmlTextReaderErrorCallback) {
2162 	/* ok, it's our error handler! */
2163 	pyCtxt = (xmlTextReaderPyCtxtPtr)arg;
2164 	PyTuple_SetItem(py_retval, 0, pyCtxt->f);
2165 	Py_XINCREF(pyCtxt->f);
2166 	PyTuple_SetItem(py_retval, 1, pyCtxt->arg);
2167 	Py_XINCREF(pyCtxt->arg);
2168     }
2169     else
2170     {
2171 	/* f is null or it's not our error handler */
2172 	PyTuple_SetItem(py_retval, 0, Py_None);
2173 	Py_XINCREF(Py_None);
2174 	PyTuple_SetItem(py_retval, 1, Py_None);
2175 	Py_XINCREF(Py_None);
2176     }
2177     return(py_retval);
2178 }
2179 
2180 static PyObject *
libxml_xmlFreeTextReader(ATTRIBUTE_UNUSED PyObject * self,PyObject * args)2181 libxml_xmlFreeTextReader(ATTRIBUTE_UNUSED PyObject *self, PyObject *args) {
2182     xmlTextReaderPtr reader;
2183     PyObject *pyobj_reader;
2184     xmlTextReaderPyCtxtPtr pyCtxt;
2185     xmlTextReaderErrorFunc f;
2186     void *arg;
2187 
2188     if (!PyArg_ParseTuple(args, (char *)"O:xmlFreeTextReader", &pyobj_reader))
2189         return(NULL);
2190     if (!PyCapsule_CheckExact(pyobj_reader)) {
2191 	Py_INCREF(Py_None);
2192 	return(Py_None);
2193     }
2194     reader = (xmlTextReaderPtr) PyxmlTextReader_Get(pyobj_reader);
2195     if (reader == NULL) {
2196 	Py_INCREF(Py_None);
2197 	return(Py_None);
2198     }
2199 
2200     xmlTextReaderGetErrorHandler(reader,&f,&arg);
2201     if (arg != NULL) {
2202 	if (f == (xmlTextReaderErrorFunc) libxml_xmlTextReaderErrorCallback) {
2203 	    /* ok, it's our error handler! */
2204 	    pyCtxt = (xmlTextReaderPyCtxtPtr)arg;
2205 	    Py_XDECREF(pyCtxt->f);
2206 	    Py_XDECREF(pyCtxt->arg);
2207 	    xmlFree(pyCtxt);
2208 	}
2209 	/*
2210 	 * else, something wrong happened, because the error handler is
2211 	 * not owned by the python bindings...
2212 	 */
2213     }
2214 
2215     xmlFreeTextReader(reader);
2216     Py_INCREF(Py_None);
2217     return(Py_None);
2218 }
2219 #endif
2220 
2221 /************************************************************************
2222  *									*
2223  *			XPath extensions				*
2224  *									*
2225  ************************************************************************/
2226 
2227 static void
libxml_xmlXPathFuncCallback(xmlXPathParserContextPtr ctxt,int nargs)2228 libxml_xmlXPathFuncCallback(xmlXPathParserContextPtr ctxt, int nargs)
2229 {
2230     PyObject *list, *cur, *result;
2231     xmlXPathObjectPtr obj;
2232     xmlXPathContextPtr rctxt;
2233     PyObject *current_function = NULL;
2234     const xmlChar *name;
2235     const xmlChar *ns_uri;
2236     int i;
2237 
2238     if (ctxt == NULL)
2239         return;
2240     rctxt = ctxt->context;
2241     if (rctxt == NULL)
2242         return;
2243     name = rctxt->function;
2244     ns_uri = rctxt->functionURI;
2245 #ifdef DEBUG_XPATH
2246     printf("libxml_xmlXPathFuncCallback called name %s URI %s\n", name,
2247            ns_uri);
2248 #endif
2249 
2250     /*
2251      * Find the function, it should be there it was there at lookup
2252      */
2253     for (i = 0; i < libxml_xpathCallbacksNb; i++) {
2254         if (                    /* TODO (ctxt == libxml_xpathCallbacks[i].ctx) && */
2255 						(xmlStrEqual(name, (*libxml_xpathCallbacks)[i].name)) &&
2256                (xmlStrEqual(ns_uri, (*libxml_xpathCallbacks)[i].ns_uri))) {
2257 					current_function = (*libxml_xpathCallbacks)[i].function;
2258         }
2259     }
2260     if (current_function == NULL) {
2261         printf
2262             ("libxml_xmlXPathFuncCallback: internal error %s not found !\n",
2263              name);
2264         return;
2265     }
2266 
2267     list = PyTuple_New(nargs + 1);
2268     PyTuple_SetItem(list, 0, libxml_xmlXPathParserContextPtrWrap(ctxt));
2269     for (i = nargs - 1; i >= 0; i--) {
2270         obj = valuePop(ctxt);
2271         cur = libxml_xmlXPathObjectPtrWrap(obj);
2272         PyTuple_SetItem(list, i + 1, cur);
2273     }
2274     result = PyEval_CallObject(current_function, list);
2275     Py_DECREF(list);
2276 
2277     obj = libxml_xmlXPathObjectPtrConvert(result);
2278     valuePush(ctxt, obj);
2279 }
2280 
2281 static xmlXPathFunction
libxml_xmlXPathFuncLookupFunc(void * ctxt,const xmlChar * name,const xmlChar * ns_uri)2282 libxml_xmlXPathFuncLookupFunc(void *ctxt, const xmlChar * name,
2283                               const xmlChar * ns_uri)
2284 {
2285     int i;
2286 
2287 #ifdef DEBUG_XPATH
2288     printf("libxml_xmlXPathFuncLookupFunc(%p, %s, %s) called\n",
2289            ctxt, name, ns_uri);
2290 #endif
2291     /*
2292      * This is called once only. The address is then stored in the
2293      * XPath expression evaluation, the proper object to call can
2294      * then still be found using the execution context function
2295      * and functionURI fields.
2296      */
2297     for (i = 0; i < libxml_xpathCallbacksNb; i++) {
2298 			if ((ctxt == (*libxml_xpathCallbacks)[i].ctx) &&
2299 					(xmlStrEqual(name, (*libxml_xpathCallbacks)[i].name)) &&
2300 					(xmlStrEqual(ns_uri, (*libxml_xpathCallbacks)[i].ns_uri))) {
2301             return (libxml_xmlXPathFuncCallback);
2302         }
2303     }
2304     return (NULL);
2305 }
2306 
2307 static void
libxml_xpathCallbacksInitialize(void)2308 libxml_xpathCallbacksInitialize(void)
2309 {
2310     int i;
2311 
2312     if (libxml_xpathCallbacksInitialized != 0)
2313         return;
2314 
2315 #ifdef DEBUG_XPATH
2316     printf("libxml_xpathCallbacksInitialized called\n");
2317 #endif
2318     libxml_xpathCallbacks = (libxml_xpathCallbackArray*)xmlMalloc(
2319     		libxml_xpathCallbacksAllocd*sizeof(libxml_xpathCallback));
2320 
2321     for (i = 0; i < libxml_xpathCallbacksAllocd; i++) {
2322 			(*libxml_xpathCallbacks)[i].ctx = NULL;
2323 			(*libxml_xpathCallbacks)[i].name = NULL;
2324 			(*libxml_xpathCallbacks)[i].ns_uri = NULL;
2325 			(*libxml_xpathCallbacks)[i].function = NULL;
2326     }
2327     libxml_xpathCallbacksInitialized = 1;
2328 }
2329 
2330 PyObject *
libxml_xmlRegisterXPathFunction(ATTRIBUTE_UNUSED PyObject * self,PyObject * args)2331 libxml_xmlRegisterXPathFunction(ATTRIBUTE_UNUSED PyObject * self,
2332                                 PyObject * args)
2333 {
2334     PyObject *py_retval;
2335     int c_retval = 0;
2336     xmlChar *name;
2337     xmlChar *ns_uri;
2338     xmlXPathContextPtr ctx;
2339     PyObject *pyobj_ctx;
2340     PyObject *pyobj_f;
2341     int i;
2342 
2343     if (!PyArg_ParseTuple
2344         (args, (char *) "OszO:registerXPathFunction", &pyobj_ctx, &name,
2345          &ns_uri, &pyobj_f))
2346         return (NULL);
2347 
2348     ctx = (xmlXPathContextPtr) PyxmlXPathContext_Get(pyobj_ctx);
2349     if (libxml_xpathCallbacksInitialized == 0)
2350         libxml_xpathCallbacksInitialize();
2351     xmlXPathRegisterFuncLookup(ctx, libxml_xmlXPathFuncLookupFunc, ctx);
2352 
2353     if ((pyobj_ctx == NULL) || (name == NULL) || (pyobj_f == NULL)) {
2354         py_retval = libxml_intWrap(-1);
2355         return (py_retval);
2356     }
2357 #ifdef DEBUG_XPATH
2358     printf("libxml_registerXPathFunction(%p, %s, %s) called\n",
2359            ctx, name, ns_uri);
2360 #endif
2361     for (i = 0; i < libxml_xpathCallbacksNb; i++) {
2362 	if ((ctx == (*libxml_xpathCallbacks)[i].ctx) &&
2363             (xmlStrEqual(name, (*libxml_xpathCallbacks)[i].name)) &&
2364             (xmlStrEqual(ns_uri, (*libxml_xpathCallbacks)[i].ns_uri))) {
2365             Py_XINCREF(pyobj_f);
2366             Py_XDECREF((*libxml_xpathCallbacks)[i].function);
2367             (*libxml_xpathCallbacks)[i].function = pyobj_f;
2368             c_retval = 1;
2369             goto done;
2370         }
2371     }
2372     if (libxml_xpathCallbacksNb >= libxml_xpathCallbacksAllocd) {
2373 			libxml_xpathCallbacksAllocd+=10;
2374 	libxml_xpathCallbacks = (libxml_xpathCallbackArray*)xmlRealloc(
2375 		libxml_xpathCallbacks,
2376 		libxml_xpathCallbacksAllocd*sizeof(libxml_xpathCallback));
2377     }
2378     i = libxml_xpathCallbacksNb++;
2379     Py_XINCREF(pyobj_f);
2380     (*libxml_xpathCallbacks)[i].ctx = ctx;
2381     (*libxml_xpathCallbacks)[i].name = xmlStrdup(name);
2382     (*libxml_xpathCallbacks)[i].ns_uri = xmlStrdup(ns_uri);
2383     (*libxml_xpathCallbacks)[i].function = pyobj_f;
2384         c_retval = 1;
2385 
2386   done:
2387     py_retval = libxml_intWrap((int) c_retval);
2388     return (py_retval);
2389 }
2390 
2391 PyObject *
libxml_xmlXPathRegisterVariable(ATTRIBUTE_UNUSED PyObject * self,PyObject * args)2392 libxml_xmlXPathRegisterVariable(ATTRIBUTE_UNUSED PyObject * self,
2393                                 PyObject * args)
2394 {
2395     PyObject *py_retval;
2396     int c_retval = 0;
2397     xmlChar *name;
2398     xmlChar *ns_uri;
2399     xmlXPathContextPtr ctx;
2400     xmlXPathObjectPtr val;
2401     PyObject *pyobj_ctx;
2402     PyObject *pyobj_value;
2403 
2404     if (!PyArg_ParseTuple
2405         (args, (char *) "OszO:xpathRegisterVariable", &pyobj_ctx, &name,
2406          &ns_uri, &pyobj_value))
2407         return (NULL);
2408 
2409     ctx = (xmlXPathContextPtr) PyxmlXPathContext_Get(pyobj_ctx);
2410     val = libxml_xmlXPathObjectPtrConvert(pyobj_value);
2411 
2412     c_retval = xmlXPathRegisterVariableNS(ctx, name, ns_uri, val);
2413     py_retval = libxml_intWrap(c_retval);
2414     return (py_retval);
2415 }
2416 
2417 /************************************************************************
2418  *									*
2419  *			Global properties access			*
2420  *									*
2421  ************************************************************************/
2422 static PyObject *
libxml_name(ATTRIBUTE_UNUSED PyObject * self,PyObject * args)2423 libxml_name(ATTRIBUTE_UNUSED PyObject * self, PyObject * args)
2424 {
2425     PyObject *resultobj, *obj;
2426     xmlNodePtr cur;
2427     const xmlChar *res;
2428 
2429     if (!PyArg_ParseTuple(args, (char *) "O:name", &obj))
2430         return NULL;
2431     cur = PyxmlNode_Get(obj);
2432 
2433 #ifdef DEBUG
2434     printf("libxml_name: cur = %p type %d\n", cur, cur->type);
2435 #endif
2436 
2437     switch (cur->type) {
2438         case XML_DOCUMENT_NODE:
2439 #ifdef LIBXML_DOCB_ENABLED
2440         case XML_DOCB_DOCUMENT_NODE:
2441 #endif
2442         case XML_HTML_DOCUMENT_NODE:{
2443                 xmlDocPtr doc = (xmlDocPtr) cur;
2444 
2445                 res = doc->URL;
2446                 break;
2447             }
2448         case XML_ATTRIBUTE_NODE:{
2449                 xmlAttrPtr attr = (xmlAttrPtr) cur;
2450 
2451                 res = attr->name;
2452                 break;
2453             }
2454         case XML_NAMESPACE_DECL:{
2455                 xmlNsPtr ns = (xmlNsPtr) cur;
2456 
2457                 res = ns->prefix;
2458                 break;
2459             }
2460         default:
2461             res = cur->name;
2462             break;
2463     }
2464     resultobj = libxml_constxmlCharPtrWrap(res);
2465 
2466     return resultobj;
2467 }
2468 
2469 static PyObject *
libxml_doc(ATTRIBUTE_UNUSED PyObject * self,PyObject * args)2470 libxml_doc(ATTRIBUTE_UNUSED PyObject * self, PyObject * args)
2471 {
2472     PyObject *resultobj, *obj;
2473     xmlNodePtr cur;
2474     xmlDocPtr res;
2475 
2476     if (!PyArg_ParseTuple(args, (char *) "O:doc", &obj))
2477         return NULL;
2478     cur = PyxmlNode_Get(obj);
2479 
2480 #ifdef DEBUG
2481     printf("libxml_doc: cur = %p\n", cur);
2482 #endif
2483 
2484     switch (cur->type) {
2485         case XML_DOCUMENT_NODE:
2486 #ifdef LIBXML_DOCB_ENABLED
2487         case XML_DOCB_DOCUMENT_NODE:
2488 #endif
2489         case XML_HTML_DOCUMENT_NODE:
2490             res = NULL;
2491             break;
2492         case XML_ATTRIBUTE_NODE:{
2493                 xmlAttrPtr attr = (xmlAttrPtr) cur;
2494 
2495                 res = attr->doc;
2496                 break;
2497             }
2498         case XML_NAMESPACE_DECL:
2499             res = NULL;
2500             break;
2501         default:
2502             res = cur->doc;
2503             break;
2504     }
2505     resultobj = libxml_xmlDocPtrWrap(res);
2506     return resultobj;
2507 }
2508 
2509 static PyObject *
libxml_properties(ATTRIBUTE_UNUSED PyObject * self,PyObject * args)2510 libxml_properties(ATTRIBUTE_UNUSED PyObject * self, PyObject * args)
2511 {
2512     PyObject *resultobj, *obj;
2513     xmlNodePtr cur;
2514     xmlAttrPtr res;
2515 
2516     if (!PyArg_ParseTuple(args, (char *) "O:properties", &obj))
2517         return NULL;
2518     cur = PyxmlNode_Get(obj);
2519     if ((cur != NULL) && (cur->type == XML_ELEMENT_NODE))
2520         res = cur->properties;
2521     else
2522         res = NULL;
2523     resultobj = libxml_xmlAttrPtrWrap(res);
2524     return resultobj;
2525 }
2526 
2527 static PyObject *
libxml_next(ATTRIBUTE_UNUSED PyObject * self,PyObject * args)2528 libxml_next(ATTRIBUTE_UNUSED PyObject * self, PyObject * args)
2529 {
2530     PyObject *resultobj, *obj;
2531     xmlNodePtr cur;
2532     xmlNodePtr res;
2533 
2534     if (!PyArg_ParseTuple(args, (char *) "O:next", &obj))
2535         return NULL;
2536     cur = PyxmlNode_Get(obj);
2537 
2538 #ifdef DEBUG
2539     printf("libxml_next: cur = %p\n", cur);
2540 #endif
2541 
2542     switch (cur->type) {
2543         case XML_DOCUMENT_NODE:
2544 #ifdef LIBXML_DOCB_ENABLED
2545         case XML_DOCB_DOCUMENT_NODE:
2546 #endif
2547         case XML_HTML_DOCUMENT_NODE:
2548             res = NULL;
2549             break;
2550         case XML_ATTRIBUTE_NODE:{
2551                 xmlAttrPtr attr = (xmlAttrPtr) cur;
2552 
2553                 res = (xmlNodePtr) attr->next;
2554                 break;
2555             }
2556         case XML_NAMESPACE_DECL:{
2557                 xmlNsPtr ns = (xmlNsPtr) cur;
2558 
2559                 res = (xmlNodePtr) ns->next;
2560                 break;
2561             }
2562         default:
2563             res = cur->next;
2564             break;
2565 
2566     }
2567     resultobj = libxml_xmlNodePtrWrap(res);
2568     return resultobj;
2569 }
2570 
2571 static PyObject *
libxml_prev(ATTRIBUTE_UNUSED PyObject * self,PyObject * args)2572 libxml_prev(ATTRIBUTE_UNUSED PyObject * self, PyObject * args)
2573 {
2574     PyObject *resultobj, *obj;
2575     xmlNodePtr cur;
2576     xmlNodePtr res;
2577 
2578     if (!PyArg_ParseTuple(args, (char *) "O:prev", &obj))
2579         return NULL;
2580     cur = PyxmlNode_Get(obj);
2581 
2582 #ifdef DEBUG
2583     printf("libxml_prev: cur = %p\n", cur);
2584 #endif
2585 
2586     switch (cur->type) {
2587         case XML_DOCUMENT_NODE:
2588 #ifdef LIBXML_DOCB_ENABLED
2589         case XML_DOCB_DOCUMENT_NODE:
2590 #endif
2591         case XML_HTML_DOCUMENT_NODE:
2592             res = NULL;
2593             break;
2594         case XML_ATTRIBUTE_NODE:{
2595                 xmlAttrPtr attr = (xmlAttrPtr) cur;
2596 
2597                 res = (xmlNodePtr) attr->prev;
2598             }
2599             break;
2600         case XML_NAMESPACE_DECL:
2601             res = NULL;
2602             break;
2603         default:
2604             res = cur->prev;
2605             break;
2606     }
2607     resultobj = libxml_xmlNodePtrWrap(res);
2608     return resultobj;
2609 }
2610 
2611 static PyObject *
libxml_children(ATTRIBUTE_UNUSED PyObject * self,PyObject * args)2612 libxml_children(ATTRIBUTE_UNUSED PyObject * self, PyObject * args)
2613 {
2614     PyObject *resultobj, *obj;
2615     xmlNodePtr cur;
2616     xmlNodePtr res;
2617 
2618     if (!PyArg_ParseTuple(args, (char *) "O:children", &obj))
2619         return NULL;
2620     cur = PyxmlNode_Get(obj);
2621 
2622 #ifdef DEBUG
2623     printf("libxml_children: cur = %p\n", cur);
2624 #endif
2625 
2626     switch (cur->type) {
2627         case XML_ELEMENT_NODE:
2628         case XML_ENTITY_REF_NODE:
2629         case XML_ENTITY_NODE:
2630         case XML_PI_NODE:
2631         case XML_COMMENT_NODE:
2632         case XML_DOCUMENT_NODE:
2633 #ifdef LIBXML_DOCB_ENABLED
2634         case XML_DOCB_DOCUMENT_NODE:
2635 #endif
2636         case XML_HTML_DOCUMENT_NODE:
2637         case XML_DTD_NODE:
2638             res = cur->children;
2639             break;
2640         case XML_ATTRIBUTE_NODE:{
2641                 xmlAttrPtr attr = (xmlAttrPtr) cur;
2642 
2643                 res = attr->children;
2644                 break;
2645             }
2646         default:
2647             res = NULL;
2648             break;
2649     }
2650     resultobj = libxml_xmlNodePtrWrap(res);
2651     return resultobj;
2652 }
2653 
2654 static PyObject *
libxml_last(ATTRIBUTE_UNUSED PyObject * self,PyObject * args)2655 libxml_last(ATTRIBUTE_UNUSED PyObject * self, PyObject * args)
2656 {
2657     PyObject *resultobj, *obj;
2658     xmlNodePtr cur;
2659     xmlNodePtr res;
2660 
2661     if (!PyArg_ParseTuple(args, (char *) "O:last", &obj))
2662         return NULL;
2663     cur = PyxmlNode_Get(obj);
2664 
2665 #ifdef DEBUG
2666     printf("libxml_last: cur = %p\n", cur);
2667 #endif
2668 
2669     switch (cur->type) {
2670         case XML_ELEMENT_NODE:
2671         case XML_ENTITY_REF_NODE:
2672         case XML_ENTITY_NODE:
2673         case XML_PI_NODE:
2674         case XML_COMMENT_NODE:
2675         case XML_DOCUMENT_NODE:
2676 #ifdef LIBXML_DOCB_ENABLED
2677         case XML_DOCB_DOCUMENT_NODE:
2678 #endif
2679         case XML_HTML_DOCUMENT_NODE:
2680         case XML_DTD_NODE:
2681             res = cur->last;
2682             break;
2683         case XML_ATTRIBUTE_NODE:{
2684                 xmlAttrPtr attr = (xmlAttrPtr) cur;
2685 
2686                 res = attr->last;
2687 		break;
2688             }
2689         default:
2690             res = NULL;
2691             break;
2692     }
2693     resultobj = libxml_xmlNodePtrWrap(res);
2694     return resultobj;
2695 }
2696 
2697 static PyObject *
libxml_parent(ATTRIBUTE_UNUSED PyObject * self,PyObject * args)2698 libxml_parent(ATTRIBUTE_UNUSED PyObject * self, PyObject * args)
2699 {
2700     PyObject *resultobj, *obj;
2701     xmlNodePtr cur;
2702     xmlNodePtr res;
2703 
2704     if (!PyArg_ParseTuple(args, (char *) "O:parent", &obj))
2705         return NULL;
2706     cur = PyxmlNode_Get(obj);
2707 
2708 #ifdef DEBUG
2709     printf("libxml_parent: cur = %p\n", cur);
2710 #endif
2711 
2712     switch (cur->type) {
2713         case XML_DOCUMENT_NODE:
2714         case XML_HTML_DOCUMENT_NODE:
2715 #ifdef LIBXML_DOCB_ENABLED
2716         case XML_DOCB_DOCUMENT_NODE:
2717 #endif
2718             res = NULL;
2719             break;
2720         case XML_ATTRIBUTE_NODE:{
2721                 xmlAttrPtr attr = (xmlAttrPtr) cur;
2722 
2723                 res = attr->parent;
2724             }
2725 	    break;
2726         case XML_ENTITY_DECL:
2727         case XML_NAMESPACE_DECL:
2728         case XML_XINCLUDE_START:
2729         case XML_XINCLUDE_END:
2730             res = NULL;
2731             break;
2732         default:
2733             res = cur->parent;
2734             break;
2735     }
2736     resultobj = libxml_xmlNodePtrWrap(res);
2737     return resultobj;
2738 }
2739 
2740 static PyObject *
libxml_type(ATTRIBUTE_UNUSED PyObject * self,PyObject * args)2741 libxml_type(ATTRIBUTE_UNUSED PyObject * self, PyObject * args)
2742 {
2743     PyObject *resultobj, *obj;
2744     xmlNodePtr cur;
2745     const xmlChar *res = NULL;
2746 
2747     if (!PyArg_ParseTuple(args, (char *) "O:last", &obj))
2748         return NULL;
2749     cur = PyxmlNode_Get(obj);
2750     if (cur == NULL) {
2751         Py_INCREF(Py_None);
2752 	return (Py_None);
2753     }
2754 
2755 #ifdef DEBUG
2756     printf("libxml_type: cur = %p\n", cur);
2757 #endif
2758 
2759     switch (cur->type) {
2760         case XML_ELEMENT_NODE:
2761             res = (const xmlChar *) "element";
2762             break;
2763         case XML_ATTRIBUTE_NODE:
2764             res = (const xmlChar *) "attribute";
2765             break;
2766         case XML_TEXT_NODE:
2767             res = (const xmlChar *) "text";
2768             break;
2769         case XML_CDATA_SECTION_NODE:
2770             res = (const xmlChar *) "cdata";
2771             break;
2772         case XML_ENTITY_REF_NODE:
2773             res = (const xmlChar *) "entity_ref";
2774             break;
2775         case XML_ENTITY_NODE:
2776             res = (const xmlChar *) "entity";
2777             break;
2778         case XML_PI_NODE:
2779             res = (const xmlChar *) "pi";
2780             break;
2781         case XML_COMMENT_NODE:
2782             res = (const xmlChar *) "comment";
2783             break;
2784         case XML_DOCUMENT_NODE:
2785             res = (const xmlChar *) "document_xml";
2786             break;
2787         case XML_DOCUMENT_TYPE_NODE:
2788             res = (const xmlChar *) "doctype";
2789             break;
2790         case XML_DOCUMENT_FRAG_NODE:
2791             res = (const xmlChar *) "fragment";
2792             break;
2793         case XML_NOTATION_NODE:
2794             res = (const xmlChar *) "notation";
2795             break;
2796         case XML_HTML_DOCUMENT_NODE:
2797             res = (const xmlChar *) "document_html";
2798             break;
2799         case XML_DTD_NODE:
2800             res = (const xmlChar *) "dtd";
2801             break;
2802         case XML_ELEMENT_DECL:
2803             res = (const xmlChar *) "elem_decl";
2804             break;
2805         case XML_ATTRIBUTE_DECL:
2806             res = (const xmlChar *) "attribute_decl";
2807             break;
2808         case XML_ENTITY_DECL:
2809             res = (const xmlChar *) "entity_decl";
2810             break;
2811         case XML_NAMESPACE_DECL:
2812             res = (const xmlChar *) "namespace";
2813             break;
2814         case XML_XINCLUDE_START:
2815             res = (const xmlChar *) "xinclude_start";
2816             break;
2817         case XML_XINCLUDE_END:
2818             res = (const xmlChar *) "xinclude_end";
2819             break;
2820 #ifdef LIBXML_DOCB_ENABLED
2821         case XML_DOCB_DOCUMENT_NODE:
2822             res = (const xmlChar *) "document_docbook";
2823             break;
2824 #endif
2825     }
2826 #ifdef DEBUG
2827     printf("libxml_type: cur = %p: %s\n", cur, res);
2828 #endif
2829 
2830     resultobj = libxml_constxmlCharPtrWrap(res);
2831     return resultobj;
2832 }
2833 
2834 /************************************************************************
2835  *									*
2836  *			Specific accessor functions			*
2837  *									*
2838  ************************************************************************/
2839 PyObject *
libxml_xmlNodeGetNsDefs(ATTRIBUTE_UNUSED PyObject * self,PyObject * args)2840 libxml_xmlNodeGetNsDefs(ATTRIBUTE_UNUSED PyObject * self, PyObject * args)
2841 {
2842     PyObject *py_retval;
2843     xmlNsPtr c_retval;
2844     xmlNodePtr node;
2845     PyObject *pyobj_node;
2846 
2847     if (!PyArg_ParseTuple
2848         (args, (char *) "O:xmlNodeGetNsDefs", &pyobj_node))
2849         return (NULL);
2850     node = (xmlNodePtr) PyxmlNode_Get(pyobj_node);
2851 
2852     if ((node == NULL) || (node->type != XML_ELEMENT_NODE)) {
2853         Py_INCREF(Py_None);
2854         return (Py_None);
2855     }
2856     c_retval = node->nsDef;
2857     py_retval = libxml_xmlNsPtrWrap((xmlNsPtr) c_retval);
2858     return (py_retval);
2859 }
2860 
2861 PyObject *
libxml_xmlNodeRemoveNsDef(ATTRIBUTE_UNUSED PyObject * self,PyObject * args)2862 libxml_xmlNodeRemoveNsDef(ATTRIBUTE_UNUSED PyObject * self, PyObject * args)
2863 {
2864     PyObject *py_retval;
2865     xmlNsPtr ns, prev;
2866     xmlNodePtr node;
2867     PyObject *pyobj_node;
2868     xmlChar *href;
2869     xmlNsPtr c_retval;
2870 
2871     if (!PyArg_ParseTuple
2872         (args, (char *) "Oz:xmlNodeRemoveNsDef", &pyobj_node, &href))
2873         return (NULL);
2874     node = (xmlNodePtr) PyxmlNode_Get(pyobj_node);
2875     ns = NULL;
2876 
2877     if ((node == NULL) || (node->type != XML_ELEMENT_NODE)) {
2878         Py_INCREF(Py_None);
2879         return (Py_None);
2880     }
2881 
2882     if (href == NULL) {
2883 	ns = node->nsDef;
2884 	node->nsDef = NULL;
2885 	c_retval = 0;
2886     }
2887     else {
2888 	prev = NULL;
2889 	ns = node->nsDef;
2890 	while (ns != NULL) {
2891 	    if (xmlStrEqual(ns->href, href)) {
2892 		if (prev != NULL)
2893 		    prev->next = ns->next;
2894 		else
2895 		    node->nsDef = ns->next;
2896 		ns->next = NULL;
2897 		c_retval = 0;
2898 		break;
2899 	    }
2900 	    prev = ns;
2901 	    ns = ns->next;
2902 	}
2903     }
2904 
2905     c_retval = ns;
2906     py_retval = libxml_xmlNsPtrWrap((xmlNsPtr) c_retval);
2907     return (py_retval);
2908 }
2909 
2910 PyObject *
libxml_xmlNodeGetNs(ATTRIBUTE_UNUSED PyObject * self,PyObject * args)2911 libxml_xmlNodeGetNs(ATTRIBUTE_UNUSED PyObject * self, PyObject * args)
2912 {
2913     PyObject *py_retval;
2914     xmlNsPtr c_retval;
2915     xmlNodePtr node;
2916     PyObject *pyobj_node;
2917 
2918     if (!PyArg_ParseTuple(args, (char *) "O:xmlNodeGetNs", &pyobj_node))
2919         return (NULL);
2920     node = (xmlNodePtr) PyxmlNode_Get(pyobj_node);
2921 
2922     if ((node == NULL) ||
2923         ((node->type != XML_ELEMENT_NODE) &&
2924 	 (node->type != XML_ATTRIBUTE_NODE))) {
2925         Py_INCREF(Py_None);
2926         return (Py_None);
2927     }
2928     c_retval = node->ns;
2929     py_retval = libxml_xmlNsPtrWrap((xmlNsPtr) c_retval);
2930     return (py_retval);
2931 }
2932 
2933 #ifdef LIBXML_OUTPUT_ENABLED
2934 /************************************************************************
2935  *									*
2936  *			Serialization front-end				*
2937  *									*
2938  ************************************************************************/
2939 
2940 static PyObject *
libxml_serializeNode(ATTRIBUTE_UNUSED PyObject * self,PyObject * args)2941 libxml_serializeNode(ATTRIBUTE_UNUSED PyObject * self, PyObject * args)
2942 {
2943     PyObject *py_retval = NULL;
2944     xmlChar *c_retval;
2945     PyObject *pyobj_node;
2946     xmlNodePtr node;
2947     xmlDocPtr doc;
2948     const char *encoding;
2949     int format;
2950     xmlSaveCtxtPtr ctxt;
2951     xmlBufferPtr buf;
2952     int options = 0;
2953 
2954     if (!PyArg_ParseTuple(args, (char *) "Ozi:serializeNode", &pyobj_node,
2955                           &encoding, &format))
2956         return (NULL);
2957     node = (xmlNodePtr) PyxmlNode_Get(pyobj_node);
2958 
2959     if (node == NULL) {
2960         Py_INCREF(Py_None);
2961         return (Py_None);
2962     }
2963     if (node->type == XML_DOCUMENT_NODE) {
2964         doc = (xmlDocPtr) node;
2965 	node = NULL;
2966 #ifdef LIBXML_HTML_ENABLED
2967     } else if (node->type == XML_HTML_DOCUMENT_NODE) {
2968         doc = (xmlDocPtr) node;
2969 	node = NULL;
2970 #endif
2971     } else {
2972         if (node->type == XML_NAMESPACE_DECL)
2973 	    doc = NULL;
2974 	else
2975             doc = node->doc;
2976         if ((doc == NULL) || (doc->type == XML_DOCUMENT_NODE)) {
2977 #ifdef LIBXML_HTML_ENABLED
2978         } else if (doc->type == XML_HTML_DOCUMENT_NODE) {
2979 #endif /* LIBXML_HTML_ENABLED */
2980         } else {
2981             Py_INCREF(Py_None);
2982             return (Py_None);
2983         }
2984     }
2985 
2986 
2987     buf = xmlBufferCreate();
2988     if (buf == NULL) {
2989 	Py_INCREF(Py_None);
2990 	return (Py_None);
2991     }
2992     if (format) options |= XML_SAVE_FORMAT;
2993     ctxt = xmlSaveToBuffer(buf, encoding, options);
2994     if (ctxt == NULL) {
2995 	xmlBufferFree(buf);
2996 	Py_INCREF(Py_None);
2997 	return (Py_None);
2998     }
2999     if (node == NULL)
3000 	xmlSaveDoc(ctxt, doc);
3001     else
3002 	xmlSaveTree(ctxt, node);
3003     xmlSaveClose(ctxt);
3004 
3005     c_retval = buf->content;
3006     buf->content = NULL;
3007 
3008     xmlBufferFree(buf);
3009     py_retval = libxml_charPtrWrap((char *) c_retval);
3010 
3011     return (py_retval);
3012 }
3013 
3014 static PyObject *
libxml_saveNodeTo(ATTRIBUTE_UNUSED PyObject * self,PyObject * args)3015 libxml_saveNodeTo(ATTRIBUTE_UNUSED PyObject * self, PyObject * args)
3016 {
3017     PyObject *py_file = NULL;
3018     FILE *output;
3019     PyObject *pyobj_node;
3020     xmlNodePtr node;
3021     xmlDocPtr doc;
3022     const char *encoding;
3023     int format;
3024     int len;
3025     xmlOutputBufferPtr buf;
3026     xmlCharEncodingHandlerPtr handler = NULL;
3027 
3028     if (!PyArg_ParseTuple(args, (char *) "OOzi:serializeNode", &pyobj_node,
3029                           &py_file, &encoding, &format))
3030         return (NULL);
3031     node = (xmlNodePtr) PyxmlNode_Get(pyobj_node);
3032     if (node == NULL) {
3033         return (PyLong_FromLong((long) -1));
3034     }
3035     output = PyFile_Get(py_file);
3036     if (output == NULL) {
3037         return (PyLong_FromLong((long) -1));
3038     }
3039 
3040     if (node->type == XML_DOCUMENT_NODE) {
3041         doc = (xmlDocPtr) node;
3042     } else if (node->type == XML_HTML_DOCUMENT_NODE) {
3043         doc = (xmlDocPtr) node;
3044     } else {
3045         doc = node->doc;
3046     }
3047 #ifdef LIBXML_HTML_ENABLED
3048     if (doc->type == XML_HTML_DOCUMENT_NODE) {
3049         if (encoding == NULL)
3050             encoding = (const char *) htmlGetMetaEncoding(doc);
3051     }
3052 #endif /* LIBXML_HTML_ENABLED */
3053     if (encoding != NULL) {
3054         handler = xmlFindCharEncodingHandler(encoding);
3055         if (handler == NULL) {
3056             return (PyLong_FromLong((long) -1));
3057         }
3058     }
3059     if (doc->type == XML_HTML_DOCUMENT_NODE) {
3060         if (handler == NULL)
3061             handler = xmlFindCharEncodingHandler("HTML");
3062         if (handler == NULL)
3063             handler = xmlFindCharEncodingHandler("ascii");
3064     }
3065 
3066     buf = xmlOutputBufferCreateFile(output, handler);
3067     if (node->type == XML_DOCUMENT_NODE) {
3068         len = xmlSaveFormatFileTo(buf, doc, encoding, format);
3069 #ifdef LIBXML_HTML_ENABLED
3070     } else if (node->type == XML_HTML_DOCUMENT_NODE) {
3071         htmlDocContentDumpFormatOutput(buf, doc, encoding, format);
3072         len = xmlOutputBufferClose(buf);
3073     } else if (doc->type == XML_HTML_DOCUMENT_NODE) {
3074         htmlNodeDumpFormatOutput(buf, doc, node, encoding, format);
3075         len = xmlOutputBufferClose(buf);
3076 #endif /* LIBXML_HTML_ENABLED */
3077     } else {
3078         xmlNodeDumpOutput(buf, doc, node, 0, format, encoding);
3079         len = xmlOutputBufferClose(buf);
3080     }
3081     PyFile_Release(output);
3082     return (PyLong_FromLong((long) len));
3083 }
3084 #endif /* LIBXML_OUTPUT_ENABLED */
3085 
3086 /************************************************************************
3087  *									*
3088  *			Extra stuff					*
3089  *									*
3090  ************************************************************************/
3091 PyObject *
libxml_xmlNewNode(ATTRIBUTE_UNUSED PyObject * self,PyObject * args)3092 libxml_xmlNewNode(ATTRIBUTE_UNUSED PyObject * self, PyObject * args)
3093 {
3094     PyObject *py_retval;
3095     xmlChar *name;
3096     xmlNodePtr node;
3097 
3098     if (!PyArg_ParseTuple(args, (char *) "s:xmlNewNode", &name))
3099         return (NULL);
3100     node = (xmlNodePtr) xmlNewNode(NULL, name);
3101 #ifdef DEBUG
3102     printf("NewNode: %s : %p\n", name, (void *) node);
3103 #endif
3104 
3105     if (node == NULL) {
3106         Py_INCREF(Py_None);
3107         return (Py_None);
3108     }
3109     py_retval = libxml_xmlNodePtrWrap(node);
3110     return (py_retval);
3111 }
3112 
3113 
3114 /************************************************************************
3115  *									*
3116  *			Local Catalog stuff				*
3117  *									*
3118  ************************************************************************/
3119 static PyObject *
libxml_addLocalCatalog(ATTRIBUTE_UNUSED PyObject * self,PyObject * args)3120 libxml_addLocalCatalog(ATTRIBUTE_UNUSED PyObject * self, PyObject * args)
3121 {
3122     xmlChar *URL;
3123     xmlParserCtxtPtr ctxt;
3124     PyObject *pyobj_ctxt;
3125 
3126     if (!PyArg_ParseTuple(args, (char *)"Os:addLocalCatalog", &pyobj_ctxt, &URL))
3127         return(NULL);
3128 
3129     ctxt = (xmlParserCtxtPtr) PyparserCtxt_Get(pyobj_ctxt);
3130 
3131     if (URL != NULL) {
3132 	ctxt->catalogs = xmlCatalogAddLocal(ctxt->catalogs, URL);
3133     }
3134 
3135 #ifdef DEBUG
3136     printf("LocalCatalog: %s\n", URL);
3137 #endif
3138 
3139     Py_INCREF(Py_None);
3140     return (Py_None);
3141 }
3142 
3143 #ifdef LIBXML_SCHEMAS_ENABLED
3144 
3145 /************************************************************************
3146  *                                                                      *
3147  * RelaxNG error handler registration                                   *
3148  *                                                                      *
3149  ************************************************************************/
3150 
3151 typedef struct
3152 {
3153     PyObject *warn;
3154     PyObject *error;
3155     PyObject *arg;
3156 } xmlRelaxNGValidCtxtPyCtxt;
3157 typedef xmlRelaxNGValidCtxtPyCtxt *xmlRelaxNGValidCtxtPyCtxtPtr;
3158 
3159 static void
libxml_xmlRelaxNGValidityGenericErrorFuncHandler(void * ctx,char * str)3160 libxml_xmlRelaxNGValidityGenericErrorFuncHandler(void *ctx, char *str)
3161 {
3162     PyObject *list;
3163     PyObject *result;
3164     xmlRelaxNGValidCtxtPyCtxtPtr pyCtxt;
3165 
3166 #ifdef DEBUG_ERROR
3167     printf("libxml_xmlRelaxNGValidityGenericErrorFuncHandler(%p, %s, ...) called\n", ctx, str);
3168 #endif
3169 
3170     pyCtxt = (xmlRelaxNGValidCtxtPyCtxtPtr)ctx;
3171 
3172     list = PyTuple_New(2);
3173     PyTuple_SetItem(list, 0, libxml_charPtrWrap(str));
3174     PyTuple_SetItem(list, 1, pyCtxt->arg);
3175     Py_XINCREF(pyCtxt->arg);
3176     result = PyEval_CallObject(pyCtxt->error, list);
3177     if (result == NULL)
3178     {
3179         /* TODO: manage for the exception to be propagated... */
3180         PyErr_Print();
3181     }
3182     Py_XDECREF(list);
3183     Py_XDECREF(result);
3184 }
3185 
3186 static void
libxml_xmlRelaxNGValidityGenericWarningFuncHandler(void * ctx,char * str)3187 libxml_xmlRelaxNGValidityGenericWarningFuncHandler(void *ctx, char *str)
3188 {
3189     PyObject *list;
3190     PyObject *result;
3191     xmlRelaxNGValidCtxtPyCtxtPtr pyCtxt;
3192 
3193 #ifdef DEBUG_ERROR
3194     printf("libxml_xmlRelaxNGValidityGenericWarningFuncHandler(%p, %s, ...) called\n", ctx, str);
3195 #endif
3196 
3197     pyCtxt = (xmlRelaxNGValidCtxtPyCtxtPtr)ctx;
3198 
3199     list = PyTuple_New(2);
3200     PyTuple_SetItem(list, 0, libxml_charPtrWrap(str));
3201     PyTuple_SetItem(list, 1, pyCtxt->arg);
3202     Py_XINCREF(pyCtxt->arg);
3203     result = PyEval_CallObject(pyCtxt->warn, list);
3204     if (result == NULL)
3205     {
3206         /* TODO: manage for the exception to be propagated... */
3207         PyErr_Print();
3208     }
3209     Py_XDECREF(list);
3210     Py_XDECREF(result);
3211 }
3212 
3213 static void
libxml_xmlRelaxNGValidityErrorFunc(void * ctx,const char * msg,...)3214 libxml_xmlRelaxNGValidityErrorFunc(void *ctx, const char *msg, ...)
3215 {
3216     va_list ap;
3217 
3218     va_start(ap, msg);
3219     libxml_xmlRelaxNGValidityGenericErrorFuncHandler(ctx, libxml_buildMessage(msg, ap));
3220     va_end(ap);
3221 }
3222 
3223 static void
libxml_xmlRelaxNGValidityWarningFunc(void * ctx,const char * msg,...)3224 libxml_xmlRelaxNGValidityWarningFunc(void *ctx, const char *msg, ...)
3225 {
3226     va_list ap;
3227 
3228     va_start(ap, msg);
3229     libxml_xmlRelaxNGValidityGenericWarningFuncHandler(ctx, libxml_buildMessage(msg, ap));
3230     va_end(ap);
3231 }
3232 
3233 static PyObject *
libxml_xmlRelaxNGSetValidErrors(ATTRIBUTE_UNUSED PyObject * self,PyObject * args)3234 libxml_xmlRelaxNGSetValidErrors(ATTRIBUTE_UNUSED PyObject * self, PyObject * args)
3235 {
3236     PyObject *py_retval;
3237     PyObject *pyobj_error;
3238     PyObject *pyobj_warn;
3239     PyObject *pyobj_ctx;
3240     PyObject *pyobj_arg = Py_None;
3241     xmlRelaxNGValidCtxtPtr ctxt;
3242     xmlRelaxNGValidCtxtPyCtxtPtr pyCtxt;
3243 
3244     if (!PyArg_ParseTuple
3245         (args, (char *) "OOO|O:xmlRelaxNGSetValidErrors", &pyobj_ctx, &pyobj_error, &pyobj_warn, &pyobj_arg))
3246         return (NULL);
3247 
3248 #ifdef DEBUG_ERROR
3249     printf("libxml_xmlRelaxNGSetValidErrors(%p, %p, %p) called\n", pyobj_ctx, pyobj_error, pyobj_warn);
3250 #endif
3251 
3252     ctxt = PyrelaxNgValidCtxt_Get(pyobj_ctx);
3253     if (xmlRelaxNGGetValidErrors(ctxt, NULL, NULL, (void **) &pyCtxt) == -1)
3254     {
3255         py_retval = libxml_intWrap(-1);
3256         return(py_retval);
3257     }
3258 
3259     if (pyCtxt == NULL)
3260     {
3261         /* first time to set the error handlers */
3262         pyCtxt = xmlMalloc(sizeof(xmlRelaxNGValidCtxtPyCtxt));
3263         if (pyCtxt == NULL) {
3264             py_retval = libxml_intWrap(-1);
3265             return(py_retval);
3266         }
3267         memset(pyCtxt, 0, sizeof(xmlRelaxNGValidCtxtPyCtxt));
3268     }
3269 
3270     /* TODO: check warn and error is a function ! */
3271     Py_XDECREF(pyCtxt->error);
3272     Py_XINCREF(pyobj_error);
3273     pyCtxt->error = pyobj_error;
3274 
3275     Py_XDECREF(pyCtxt->warn);
3276     Py_XINCREF(pyobj_warn);
3277     pyCtxt->warn = pyobj_warn;
3278 
3279     Py_XDECREF(pyCtxt->arg);
3280     Py_XINCREF(pyobj_arg);
3281     pyCtxt->arg = pyobj_arg;
3282 
3283     xmlRelaxNGSetValidErrors(ctxt, &libxml_xmlRelaxNGValidityErrorFunc, &libxml_xmlRelaxNGValidityWarningFunc, pyCtxt);
3284 
3285     py_retval = libxml_intWrap(1);
3286     return (py_retval);
3287 }
3288 
3289 static PyObject *
libxml_xmlRelaxNGFreeValidCtxt(ATTRIBUTE_UNUSED PyObject * self,PyObject * args)3290 libxml_xmlRelaxNGFreeValidCtxt(ATTRIBUTE_UNUSED PyObject *self, PyObject *args) {
3291     xmlRelaxNGValidCtxtPtr ctxt;
3292     xmlRelaxNGValidCtxtPyCtxtPtr pyCtxt;
3293     PyObject *pyobj_ctxt;
3294 
3295     if (!PyArg_ParseTuple(args, (char *)"O:xmlRelaxNGFreeValidCtxt", &pyobj_ctxt))
3296         return(NULL);
3297     ctxt = (xmlRelaxNGValidCtxtPtr) PyrelaxNgValidCtxt_Get(pyobj_ctxt);
3298 
3299     if (xmlRelaxNGGetValidErrors(ctxt, NULL, NULL, (void **) &pyCtxt) == 0)
3300     {
3301         if (pyCtxt != NULL)
3302         {
3303             Py_XDECREF(pyCtxt->error);
3304             Py_XDECREF(pyCtxt->warn);
3305             Py_XDECREF(pyCtxt->arg);
3306             xmlFree(pyCtxt);
3307         }
3308     }
3309 
3310     xmlRelaxNGFreeValidCtxt(ctxt);
3311     Py_INCREF(Py_None);
3312     return(Py_None);
3313 }
3314 
3315 typedef struct
3316 {
3317 	PyObject *warn;
3318 	PyObject *error;
3319 	PyObject *arg;
3320 } xmlSchemaValidCtxtPyCtxt;
3321 typedef xmlSchemaValidCtxtPyCtxt *xmlSchemaValidCtxtPyCtxtPtr;
3322 
3323 static void
libxml_xmlSchemaValidityGenericErrorFuncHandler(void * ctx,char * str)3324 libxml_xmlSchemaValidityGenericErrorFuncHandler(void *ctx, char *str)
3325 {
3326 	PyObject *list;
3327 	PyObject *result;
3328 	xmlSchemaValidCtxtPyCtxtPtr pyCtxt;
3329 
3330 #ifdef DEBUG_ERROR
3331 	printf("libxml_xmlSchemaValidityGenericErrorFuncHandler(%p, %s, ...) called\n", ctx, str);
3332 #endif
3333 
3334 	pyCtxt = (xmlSchemaValidCtxtPyCtxtPtr) ctx;
3335 
3336 	list = PyTuple_New(2);
3337 	PyTuple_SetItem(list, 0, libxml_charPtrWrap(str));
3338 	PyTuple_SetItem(list, 1, pyCtxt->arg);
3339 	Py_XINCREF(pyCtxt->arg);
3340 	result = PyEval_CallObject(pyCtxt->error, list);
3341 	if (result == NULL)
3342 	{
3343 		/* TODO: manage for the exception to be propagated... */
3344 		PyErr_Print();
3345 	}
3346 	Py_XDECREF(list);
3347 	Py_XDECREF(result);
3348 }
3349 
3350 static void
libxml_xmlSchemaValidityGenericWarningFuncHandler(void * ctx,char * str)3351 libxml_xmlSchemaValidityGenericWarningFuncHandler(void *ctx, char *str)
3352 {
3353 	PyObject *list;
3354 	PyObject *result;
3355 	xmlSchemaValidCtxtPyCtxtPtr pyCtxt;
3356 
3357 #ifdef DEBUG_ERROR
3358 	printf("libxml_xmlSchemaValidityGenericWarningFuncHandler(%p, %s, ...) called\n", ctx, str);
3359 #endif
3360 
3361 	pyCtxt = (xmlSchemaValidCtxtPyCtxtPtr) ctx;
3362 
3363 	list = PyTuple_New(2);
3364 	PyTuple_SetItem(list, 0, libxml_charPtrWrap(str));
3365 	PyTuple_SetItem(list, 1, pyCtxt->arg);
3366 	Py_XINCREF(pyCtxt->arg);
3367 	result = PyEval_CallObject(pyCtxt->warn, list);
3368 	if (result == NULL)
3369 	{
3370 		/* TODO: manage for the exception to be propagated... */
3371 		PyErr_Print();
3372 	}
3373 	Py_XDECREF(list);
3374 	Py_XDECREF(result);
3375 }
3376 
3377 static void
libxml_xmlSchemaValidityErrorFunc(void * ctx,const char * msg,...)3378 libxml_xmlSchemaValidityErrorFunc(void *ctx, const char *msg, ...)
3379 {
3380 	va_list ap;
3381 
3382 	va_start(ap, msg);
3383 	libxml_xmlSchemaValidityGenericErrorFuncHandler(ctx, libxml_buildMessage(msg, ap));
3384 	va_end(ap);
3385 }
3386 
3387 static void
libxml_xmlSchemaValidityWarningFunc(void * ctx,const char * msg,...)3388 libxml_xmlSchemaValidityWarningFunc(void *ctx, const char *msg, ...)
3389 {
3390 	va_list ap;
3391 
3392 	va_start(ap, msg);
3393 	libxml_xmlSchemaValidityGenericWarningFuncHandler(ctx, libxml_buildMessage(msg, ap));
3394 	va_end(ap);
3395 }
3396 
3397 PyObject *
libxml_xmlSchemaSetValidErrors(ATTRIBUTE_UNUSED PyObject * self,PyObject * args)3398 libxml_xmlSchemaSetValidErrors(ATTRIBUTE_UNUSED PyObject * self, PyObject * args)
3399 {
3400 	PyObject *py_retval;
3401 	PyObject *pyobj_error;
3402 	PyObject *pyobj_warn;
3403 	PyObject *pyobj_ctx;
3404 	PyObject *pyobj_arg = Py_None;
3405 	xmlSchemaValidCtxtPtr ctxt;
3406 	xmlSchemaValidCtxtPyCtxtPtr pyCtxt;
3407 
3408 	if (!PyArg_ParseTuple
3409 		(args, (char *) "OOO|O:xmlSchemaSetValidErrors", &pyobj_ctx, &pyobj_error, &pyobj_warn, &pyobj_arg))
3410 		return (NULL);
3411 
3412 #ifdef DEBUG_ERROR
3413 	printf("libxml_xmlSchemaSetValidErrors(%p, %p, %p) called\n", pyobj_ctx, pyobj_error, pyobj_warn);
3414 #endif
3415 
3416 	ctxt = PySchemaValidCtxt_Get(pyobj_ctx);
3417 	if (xmlSchemaGetValidErrors(ctxt, NULL, NULL, (void **) &pyCtxt) == -1)
3418 	{
3419 		py_retval = libxml_intWrap(-1);
3420 		return(py_retval);
3421 	}
3422 
3423 	if (pyCtxt == NULL)
3424 	{
3425 		/* first time to set the error handlers */
3426 		pyCtxt = xmlMalloc(sizeof(xmlSchemaValidCtxtPyCtxt));
3427 		if (pyCtxt == NULL) {
3428 			py_retval = libxml_intWrap(-1);
3429 			return(py_retval);
3430 		}
3431 		memset(pyCtxt, 0, sizeof(xmlSchemaValidCtxtPyCtxt));
3432 	}
3433 
3434 	/* TODO: check warn and error is a function ! */
3435 	Py_XDECREF(pyCtxt->error);
3436 	Py_XINCREF(pyobj_error);
3437 	pyCtxt->error = pyobj_error;
3438 
3439 	Py_XDECREF(pyCtxt->warn);
3440 	Py_XINCREF(pyobj_warn);
3441 	pyCtxt->warn = pyobj_warn;
3442 
3443 	Py_XDECREF(pyCtxt->arg);
3444 	Py_XINCREF(pyobj_arg);
3445 	pyCtxt->arg = pyobj_arg;
3446 
3447 	xmlSchemaSetValidErrors(ctxt, &libxml_xmlSchemaValidityErrorFunc, &libxml_xmlSchemaValidityWarningFunc, pyCtxt);
3448 
3449 	py_retval = libxml_intWrap(1);
3450 	return(py_retval);
3451 }
3452 
3453 static PyObject *
libxml_xmlSchemaFreeValidCtxt(ATTRIBUTE_UNUSED PyObject * self,PyObject * args)3454 libxml_xmlSchemaFreeValidCtxt(ATTRIBUTE_UNUSED PyObject * self, PyObject * args)
3455 {
3456 	xmlSchemaValidCtxtPtr ctxt;
3457 	xmlSchemaValidCtxtPyCtxtPtr pyCtxt;
3458 	PyObject *pyobj_ctxt;
3459 
3460 	if (!PyArg_ParseTuple(args, (char *)"O:xmlSchemaFreeValidCtxt", &pyobj_ctxt))
3461 		return(NULL);
3462 	ctxt = (xmlSchemaValidCtxtPtr) PySchemaValidCtxt_Get(pyobj_ctxt);
3463 
3464 	if (xmlSchemaGetValidErrors(ctxt, NULL, NULL, (void **) &pyCtxt) == 0)
3465 	{
3466 		if (pyCtxt != NULL)
3467 		{
3468 			Py_XDECREF(pyCtxt->error);
3469 			Py_XDECREF(pyCtxt->warn);
3470 			Py_XDECREF(pyCtxt->arg);
3471 			xmlFree(pyCtxt);
3472 		}
3473 	}
3474 
3475 	xmlSchemaFreeValidCtxt(ctxt);
3476 	Py_INCREF(Py_None);
3477 	return(Py_None);
3478 }
3479 
3480 #endif
3481 
3482 #ifdef LIBXML_C14N_ENABLED
3483 #ifdef LIBXML_OUTPUT_ENABLED
3484 
3485 /************************************************************************
3486  *                                                                      *
3487  * XML Canonicalization c14n                                            *
3488  *                                                                      *
3489  ************************************************************************/
3490 
3491 static int
PyxmlNodeSet_Convert(PyObject * py_nodeset,xmlNodeSetPtr * result)3492 PyxmlNodeSet_Convert(PyObject *py_nodeset, xmlNodeSetPtr *result)
3493 {
3494     xmlNodeSetPtr nodeSet;
3495     int is_tuple = 0;
3496 
3497     if (PyTuple_Check(py_nodeset))
3498         is_tuple = 1;
3499     else if (PyList_Check(py_nodeset))
3500         is_tuple = 0;
3501     else if (py_nodeset == Py_None) {
3502         *result = NULL;
3503         return 0;
3504     }
3505     else {
3506         PyErr_SetString(PyExc_TypeError,
3507                         "must be a tuple or list of nodes.");
3508         return -1;
3509     }
3510 
3511     nodeSet = (xmlNodeSetPtr) xmlMalloc(sizeof(xmlNodeSet));
3512     if (nodeSet == NULL) {
3513         PyErr_SetString(PyExc_MemoryError, "");
3514         return -1;
3515     }
3516 
3517     nodeSet->nodeNr = 0;
3518     nodeSet->nodeMax = (is_tuple
3519                         ? PyTuple_GET_SIZE(py_nodeset)
3520                         : PyList_GET_SIZE(py_nodeset));
3521     nodeSet->nodeTab
3522         = (xmlNodePtr *) xmlMalloc (nodeSet->nodeMax
3523                                     * sizeof(xmlNodePtr));
3524     if (nodeSet->nodeTab == NULL) {
3525         xmlFree(nodeSet);
3526         PyErr_SetString(PyExc_MemoryError, "");
3527         return -1;
3528     }
3529     memset(nodeSet->nodeTab, 0 ,
3530            nodeSet->nodeMax * sizeof(xmlNodePtr));
3531 
3532     {
3533         int idx;
3534         for (idx=0; idx < nodeSet->nodeMax; ++idx) {
3535             xmlNodePtr pynode =
3536                 PyxmlNode_Get (is_tuple
3537                                ? PyTuple_GET_ITEM(py_nodeset, idx)
3538                                : PyList_GET_ITEM(py_nodeset, idx));
3539             if (pynode)
3540                 nodeSet->nodeTab[nodeSet->nodeNr++] = pynode;
3541         }
3542     }
3543     *result = nodeSet;
3544     return 0;
3545 }
3546 
3547 static int
PystringSet_Convert(PyObject * py_strings,xmlChar *** result)3548 PystringSet_Convert(PyObject *py_strings, xmlChar *** result)
3549 {
3550     /* NOTE: the array should be freed, but the strings are shared
3551        with the python strings and so must not be freed. */
3552 
3553     xmlChar ** strings;
3554     int is_tuple = 0;
3555     int count;
3556     int init_index = 0;
3557 
3558     if (PyTuple_Check(py_strings))
3559         is_tuple = 1;
3560     else if (PyList_Check(py_strings))
3561         is_tuple = 0;
3562     else if (py_strings == Py_None) {
3563         *result = NULL;
3564         return 0;
3565     }
3566     else {
3567         PyErr_SetString(PyExc_TypeError,
3568                         "must be a tuple or list of strings.");
3569         return -1;
3570     }
3571 
3572     count = (is_tuple
3573              ? PyTuple_GET_SIZE(py_strings)
3574              : PyList_GET_SIZE(py_strings));
3575 
3576     strings = (xmlChar **) xmlMalloc(sizeof(xmlChar *) * count);
3577 
3578     if (strings == NULL) {
3579         PyErr_SetString(PyExc_MemoryError, "");
3580         return -1;
3581     }
3582 
3583     memset(strings, 0 , sizeof(xmlChar *) * count);
3584 
3585     {
3586         int idx;
3587         for (idx=0; idx < count; ++idx) {
3588             char* s = PyBytes_AsString
3589                 (is_tuple
3590                  ? PyTuple_GET_ITEM(py_strings, idx)
3591                  : PyList_GET_ITEM(py_strings, idx));
3592             if (s)
3593                 strings[init_index++] = (xmlChar *)s;
3594             else {
3595                 xmlFree(strings);
3596                 PyErr_SetString(PyExc_TypeError,
3597                                 "must be a tuple or list of strings.");
3598                 return -1;
3599             }
3600         }
3601     }
3602 
3603     *result = strings;
3604     return 0;
3605 }
3606 
3607 static PyObject *
libxml_C14NDocDumpMemory(ATTRIBUTE_UNUSED PyObject * self,PyObject * args)3608 libxml_C14NDocDumpMemory(ATTRIBUTE_UNUSED PyObject * self,
3609                          PyObject * args)
3610 {
3611     PyObject *py_retval = NULL;
3612 
3613     PyObject *pyobj_doc;
3614     PyObject *pyobj_nodes;
3615     int exclusive;
3616     PyObject *pyobj_prefixes;
3617     int with_comments;
3618 
3619     xmlDocPtr doc;
3620     xmlNodeSetPtr nodes;
3621     xmlChar **prefixes = NULL;
3622     xmlChar *doc_txt;
3623 
3624     int result;
3625 
3626     if (!PyArg_ParseTuple(args, (char *) "OOiOi:C14NDocDumpMemory",
3627                           &pyobj_doc,
3628                           &pyobj_nodes,
3629                           &exclusive,
3630                           &pyobj_prefixes,
3631                           &with_comments))
3632         return (NULL);
3633 
3634     doc = (xmlDocPtr) PyxmlNode_Get(pyobj_doc);
3635     if (!doc) {
3636         PyErr_SetString(PyExc_TypeError, "bad document.");
3637         return NULL;
3638     }
3639 
3640     result = PyxmlNodeSet_Convert(pyobj_nodes, &nodes);
3641     if (result < 0) return NULL;
3642 
3643     if (exclusive) {
3644         result = PystringSet_Convert(pyobj_prefixes, &prefixes);
3645         if (result < 0) {
3646             if (nodes) {
3647                 xmlFree(nodes->nodeTab);
3648                 xmlFree(nodes);
3649             }
3650             return NULL;
3651         }
3652     }
3653 
3654     result = xmlC14NDocDumpMemory(doc,
3655                                   nodes,
3656                                   exclusive,
3657                                   prefixes,
3658                                   with_comments,
3659                                   &doc_txt);
3660 
3661     if (nodes) {
3662         xmlFree(nodes->nodeTab);
3663         xmlFree(nodes);
3664     }
3665     if (prefixes) {
3666         xmlChar ** idx = prefixes;
3667         while (*idx) xmlFree(*(idx++));
3668         xmlFree(prefixes);
3669     }
3670 
3671     if (result < 0) {
3672         PyErr_SetString(PyExc_Exception,
3673                         "libxml2 xmlC14NDocDumpMemory failure.");
3674         return NULL;
3675     }
3676     else {
3677         py_retval = PY_IMPORT_STRING_SIZE((const char *) doc_txt,
3678                                                 result);
3679         xmlFree(doc_txt);
3680         return py_retval;
3681     }
3682 }
3683 
3684 static PyObject *
libxml_C14NDocSaveTo(ATTRIBUTE_UNUSED PyObject * self,PyObject * args)3685 libxml_C14NDocSaveTo(ATTRIBUTE_UNUSED PyObject * self,
3686                      PyObject * args)
3687 {
3688     PyObject *pyobj_doc;
3689     PyObject *py_file;
3690     PyObject *pyobj_nodes;
3691     int exclusive;
3692     PyObject *pyobj_prefixes;
3693     int with_comments;
3694 
3695     xmlDocPtr doc;
3696     xmlNodeSetPtr nodes;
3697     xmlChar **prefixes = NULL;
3698     FILE * output;
3699     xmlOutputBufferPtr buf;
3700 
3701     int result;
3702     int len;
3703 
3704     if (!PyArg_ParseTuple(args, (char *) "OOiOiO:C14NDocSaveTo",
3705                           &pyobj_doc,
3706                           &pyobj_nodes,
3707                           &exclusive,
3708                           &pyobj_prefixes,
3709                           &with_comments,
3710                           &py_file))
3711         return (NULL);
3712 
3713     doc = (xmlDocPtr) PyxmlNode_Get(pyobj_doc);
3714     if (!doc) {
3715         PyErr_SetString(PyExc_TypeError, "bad document.");
3716         return NULL;
3717     }
3718 
3719     output = PyFile_Get(py_file);
3720     if (output == NULL) {
3721         PyErr_SetString(PyExc_TypeError, "bad file.");
3722         return NULL;
3723     }
3724     buf = xmlOutputBufferCreateFile(output, NULL);
3725 
3726     result = PyxmlNodeSet_Convert(pyobj_nodes, &nodes);
3727     if (result < 0) return NULL;
3728 
3729     if (exclusive) {
3730         result = PystringSet_Convert(pyobj_prefixes, &prefixes);
3731         if (result < 0) {
3732             if (nodes) {
3733                 xmlFree(nodes->nodeTab);
3734                 xmlFree(nodes);
3735             }
3736             return NULL;
3737         }
3738     }
3739 
3740     result = xmlC14NDocSaveTo(doc,
3741                               nodes,
3742                               exclusive,
3743                               prefixes,
3744                               with_comments,
3745                               buf);
3746 
3747     if (nodes) {
3748         xmlFree(nodes->nodeTab);
3749         xmlFree(nodes);
3750     }
3751     if (prefixes) {
3752         xmlChar ** idx = prefixes;
3753         while (*idx) xmlFree(*(idx++));
3754         xmlFree(prefixes);
3755     }
3756 
3757     PyFile_Release(output);
3758     len = xmlOutputBufferClose(buf);
3759 
3760     if (result < 0) {
3761         PyErr_SetString(PyExc_Exception,
3762                         "libxml2 xmlC14NDocSaveTo failure.");
3763         return NULL;
3764     }
3765     else
3766         return PyLong_FromLong((long) len);
3767 }
3768 
3769 #endif
3770 #endif
3771 
3772 static PyObject *
libxml_getObjDesc(PyObject * self ATTRIBUTE_UNUSED,PyObject * args)3773 libxml_getObjDesc(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) {
3774 
3775     PyObject *obj;
3776     char *str;
3777 
3778     if (!PyArg_ParseTuple(args, (char *)"O:getObjDesc", &obj))
3779         return NULL;
3780     str = PyCapsule_GetPointer(obj, PyCapsule_GetName(obj));
3781     return Py_BuildValue((char *)"s", str);
3782 }
3783 
3784 static PyObject *
libxml_compareNodesEqual(PyObject * self ATTRIBUTE_UNUSED,PyObject * args)3785 libxml_compareNodesEqual(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) {
3786 
3787     PyObject *py_node1, *py_node2;
3788     xmlNodePtr node1, node2;
3789 
3790     if (!PyArg_ParseTuple(args, (char *)"OO:compareNodesEqual",
3791 		&py_node1, &py_node2))
3792         return NULL;
3793     /* To compare two node objects, we compare their pointer addresses */
3794     node1 = PyxmlNode_Get(py_node1);
3795     node2 = PyxmlNode_Get(py_node2);
3796     if ( node1 == node2 )
3797         return Py_BuildValue((char *)"i", 1);
3798     else
3799         return Py_BuildValue((char *)"i", 0);
3800 
3801 }
3802 
3803 static PyObject *
libxml_nodeHash(PyObject * self ATTRIBUTE_UNUSED,PyObject * args)3804 libxml_nodeHash(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) {
3805 
3806     PyObject *py_node1;
3807     xmlNodePtr node1;
3808 
3809     if (!PyArg_ParseTuple(args, (char *)"O:nodeHash", &py_node1))
3810 	    return NULL;
3811     /* For simplicity, we use the node pointer address as a hash value */
3812     node1 = PyxmlNode_Get(py_node1);
3813 
3814     return PyLong_FromVoidPtr(node1);
3815 
3816 }
3817 
3818 /************************************************************************
3819  *									*
3820  *			The registration stuff				*
3821  *									*
3822  ************************************************************************/
3823 static PyMethodDef libxmlMethods[] = {
3824 #include "libxml2-export.c"
3825     {(char *) "name", libxml_name, METH_VARARGS, NULL},
3826     {(char *) "children", libxml_children, METH_VARARGS, NULL},
3827     {(char *) "properties", libxml_properties, METH_VARARGS, NULL},
3828     {(char *) "last", libxml_last, METH_VARARGS, NULL},
3829     {(char *) "prev", libxml_prev, METH_VARARGS, NULL},
3830     {(char *) "next", libxml_next, METH_VARARGS, NULL},
3831     {(char *) "parent", libxml_parent, METH_VARARGS, NULL},
3832     {(char *) "type", libxml_type, METH_VARARGS, NULL},
3833     {(char *) "doc", libxml_doc, METH_VARARGS, NULL},
3834     {(char *) "xmlNewNode", libxml_xmlNewNode, METH_VARARGS, NULL},
3835     {(char *) "xmlNodeRemoveNsDef", libxml_xmlNodeRemoveNsDef, METH_VARARGS, NULL},
3836     {(char *)"xmlSetValidErrors", libxml_xmlSetValidErrors, METH_VARARGS, NULL},
3837     {(char *)"xmlFreeValidCtxt", libxml_xmlFreeValidCtxt, METH_VARARGS, NULL},
3838 #ifdef LIBXML_OUTPUT_ENABLED
3839     {(char *) "serializeNode", libxml_serializeNode, METH_VARARGS, NULL},
3840     {(char *) "saveNodeTo", libxml_saveNodeTo, METH_VARARGS, NULL},
3841     {(char *) "outputBufferCreate", libxml_xmlCreateOutputBuffer, METH_VARARGS, NULL},
3842     {(char *) "outputBufferGetPythonFile", libxml_outputBufferGetPythonFile, METH_VARARGS, NULL},
3843     {(char *) "xmlOutputBufferClose", libxml_xmlOutputBufferClose, METH_VARARGS, NULL},
3844     { (char *)"xmlOutputBufferFlush", libxml_xmlOutputBufferFlush, METH_VARARGS, NULL },
3845     { (char *)"xmlSaveFileTo", libxml_xmlSaveFileTo, METH_VARARGS, NULL },
3846     { (char *)"xmlSaveFormatFileTo", libxml_xmlSaveFormatFileTo, METH_VARARGS, NULL },
3847 #endif /* LIBXML_OUTPUT_ENABLED */
3848     {(char *) "inputBufferCreate", libxml_xmlCreateInputBuffer, METH_VARARGS, NULL},
3849     {(char *) "setEntityLoader", libxml_xmlSetEntityLoader, METH_VARARGS, NULL},
3850     {(char *)"xmlRegisterErrorHandler", libxml_xmlRegisterErrorHandler, METH_VARARGS, NULL },
3851     {(char *)"xmlParserCtxtSetErrorHandler", libxml_xmlParserCtxtSetErrorHandler, METH_VARARGS, NULL },
3852     {(char *)"xmlParserCtxtGetErrorHandler", libxml_xmlParserCtxtGetErrorHandler, METH_VARARGS, NULL },
3853     {(char *)"xmlFreeParserCtxt", libxml_xmlFreeParserCtxt, METH_VARARGS, NULL },
3854 #ifdef LIBXML_READER_ENABLED
3855     {(char *)"xmlTextReaderSetErrorHandler", libxml_xmlTextReaderSetErrorHandler, METH_VARARGS, NULL },
3856     {(char *)"xmlTextReaderGetErrorHandler", libxml_xmlTextReaderGetErrorHandler, METH_VARARGS, NULL },
3857     {(char *)"xmlFreeTextReader", libxml_xmlFreeTextReader, METH_VARARGS, NULL },
3858 #endif
3859     {(char *)"addLocalCatalog", libxml_addLocalCatalog, METH_VARARGS, NULL },
3860 #ifdef LIBXML_SCHEMAS_ENABLED
3861     {(char *)"xmlRelaxNGSetValidErrors", libxml_xmlRelaxNGSetValidErrors, METH_VARARGS, NULL},
3862     {(char *)"xmlRelaxNGFreeValidCtxt", libxml_xmlRelaxNGFreeValidCtxt, METH_VARARGS, NULL},
3863     {(char *)"xmlSchemaSetValidErrors", libxml_xmlSchemaSetValidErrors, METH_VARARGS, NULL},
3864     {(char *)"xmlSchemaFreeValidCtxt", libxml_xmlSchemaFreeValidCtxt, METH_VARARGS, NULL},
3865 #endif
3866 #ifdef LIBXML_C14N_ENABLED
3867 #ifdef LIBXML_OUTPUT_ENABLED
3868     {(char *)"xmlC14NDocDumpMemory", libxml_C14NDocDumpMemory, METH_VARARGS, NULL},
3869     {(char *)"xmlC14NDocSaveTo", libxml_C14NDocSaveTo, METH_VARARGS, NULL},
3870 #endif
3871 #endif
3872     {(char *) "getObjDesc", libxml_getObjDesc, METH_VARARGS, NULL},
3873     {(char *) "compareNodesEqual", libxml_compareNodesEqual, METH_VARARGS, NULL},
3874     {(char *) "nodeHash", libxml_nodeHash, METH_VARARGS, NULL},
3875     {(char *) "xmlRegisterInputCallback", libxml_xmlRegisterInputCallback, METH_VARARGS, NULL},
3876     {(char *) "xmlUnregisterInputCallback", libxml_xmlUnregisterInputCallback, METH_VARARGS, NULL},
3877     {NULL, NULL, 0, NULL}
3878 };
3879 
3880 #if PY_MAJOR_VERSION >= 3
3881 #define INITERROR return NULL
3882 
3883 static struct PyModuleDef moduledef = {
3884         PyModuleDef_HEAD_INIT,
3885         "libxml2mod",
3886         NULL,
3887         -1,
3888         libxmlMethods,
3889         NULL,
3890         NULL,
3891         NULL,
3892         NULL
3893 };
3894 
3895 #else
3896 #define INITERROR return
3897 
3898 #ifdef MERGED_MODULES
3899 extern void initlibxsltmod(void);
3900 #endif
3901 
3902 #endif
3903 
3904 #if PY_MAJOR_VERSION >= 3
PyInit_libxml2mod(void)3905 PyObject *PyInit_libxml2mod(void)
3906 #else
3907 void initlibxml2mod(void)
3908 #endif
3909 {
3910     PyObject *module;
3911 
3912 #if PY_MAJOR_VERSION >= 3
3913     module = PyModule_Create(&moduledef);
3914 #else
3915     /* initialize the python extension module */
3916     module = Py_InitModule((char *) "libxml2mod", libxmlMethods);
3917 #endif
3918     if (module == NULL)
3919         INITERROR;
3920 
3921     /* initialize libxml2 */
3922     xmlInitParser();
3923     /* TODO this probably need to be revamped for Python3 */
3924     libxml_xmlErrorInitialize();
3925 
3926 #if PY_MAJOR_VERSION < 3
3927 #ifdef MERGED_MODULES
3928     initlibxsltmod();
3929 #endif
3930 #endif
3931 
3932 #if PY_MAJOR_VERSION >= 3
3933     return module;
3934 #endif
3935 }
3936