• 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             PyFile_Release(output);
3057             return (PyLong_FromLong((long) -1));
3058         }
3059     }
3060     if (doc->type == XML_HTML_DOCUMENT_NODE) {
3061         if (handler == NULL)
3062             handler = xmlFindCharEncodingHandler("HTML");
3063         if (handler == NULL)
3064             handler = xmlFindCharEncodingHandler("ascii");
3065     }
3066 
3067     buf = xmlOutputBufferCreateFile(output, handler);
3068     if (node->type == XML_DOCUMENT_NODE) {
3069         len = xmlSaveFormatFileTo(buf, doc, encoding, format);
3070 #ifdef LIBXML_HTML_ENABLED
3071     } else if (node->type == XML_HTML_DOCUMENT_NODE) {
3072         htmlDocContentDumpFormatOutput(buf, doc, encoding, format);
3073         len = xmlOutputBufferClose(buf);
3074     } else if (doc->type == XML_HTML_DOCUMENT_NODE) {
3075         htmlNodeDumpFormatOutput(buf, doc, node, encoding, format);
3076         len = xmlOutputBufferClose(buf);
3077 #endif /* LIBXML_HTML_ENABLED */
3078     } else {
3079         xmlNodeDumpOutput(buf, doc, node, 0, format, encoding);
3080         len = xmlOutputBufferClose(buf);
3081     }
3082     PyFile_Release(output);
3083     return (PyLong_FromLong((long) len));
3084 }
3085 #endif /* LIBXML_OUTPUT_ENABLED */
3086 
3087 /************************************************************************
3088  *									*
3089  *			Extra stuff					*
3090  *									*
3091  ************************************************************************/
3092 PyObject *
libxml_xmlNewNode(ATTRIBUTE_UNUSED PyObject * self,PyObject * args)3093 libxml_xmlNewNode(ATTRIBUTE_UNUSED PyObject * self, PyObject * args)
3094 {
3095     PyObject *py_retval;
3096     xmlChar *name;
3097     xmlNodePtr node;
3098 
3099     if (!PyArg_ParseTuple(args, (char *) "s:xmlNewNode", &name))
3100         return (NULL);
3101     node = (xmlNodePtr) xmlNewNode(NULL, name);
3102 #ifdef DEBUG
3103     printf("NewNode: %s : %p\n", name, (void *) node);
3104 #endif
3105 
3106     if (node == NULL) {
3107         Py_INCREF(Py_None);
3108         return (Py_None);
3109     }
3110     py_retval = libxml_xmlNodePtrWrap(node);
3111     return (py_retval);
3112 }
3113 
3114 
3115 /************************************************************************
3116  *									*
3117  *			Local Catalog stuff				*
3118  *									*
3119  ************************************************************************/
3120 static PyObject *
libxml_addLocalCatalog(ATTRIBUTE_UNUSED PyObject * self,PyObject * args)3121 libxml_addLocalCatalog(ATTRIBUTE_UNUSED PyObject * self, PyObject * args)
3122 {
3123     xmlChar *URL;
3124     xmlParserCtxtPtr ctxt;
3125     PyObject *pyobj_ctxt;
3126 
3127     if (!PyArg_ParseTuple(args, (char *)"Os:addLocalCatalog", &pyobj_ctxt, &URL))
3128         return(NULL);
3129 
3130     ctxt = (xmlParserCtxtPtr) PyparserCtxt_Get(pyobj_ctxt);
3131 
3132     if (URL != NULL) {
3133 	ctxt->catalogs = xmlCatalogAddLocal(ctxt->catalogs, URL);
3134     }
3135 
3136 #ifdef DEBUG
3137     printf("LocalCatalog: %s\n", URL);
3138 #endif
3139 
3140     Py_INCREF(Py_None);
3141     return (Py_None);
3142 }
3143 
3144 #ifdef LIBXML_SCHEMAS_ENABLED
3145 
3146 /************************************************************************
3147  *                                                                      *
3148  * RelaxNG error handler registration                                   *
3149  *                                                                      *
3150  ************************************************************************/
3151 
3152 typedef struct
3153 {
3154     PyObject *warn;
3155     PyObject *error;
3156     PyObject *arg;
3157 } xmlRelaxNGValidCtxtPyCtxt;
3158 typedef xmlRelaxNGValidCtxtPyCtxt *xmlRelaxNGValidCtxtPyCtxtPtr;
3159 
3160 static void
libxml_xmlRelaxNGValidityGenericErrorFuncHandler(void * ctx,char * str)3161 libxml_xmlRelaxNGValidityGenericErrorFuncHandler(void *ctx, char *str)
3162 {
3163     PyObject *list;
3164     PyObject *result;
3165     xmlRelaxNGValidCtxtPyCtxtPtr pyCtxt;
3166 
3167 #ifdef DEBUG_ERROR
3168     printf("libxml_xmlRelaxNGValidityGenericErrorFuncHandler(%p, %s, ...) called\n", ctx, str);
3169 #endif
3170 
3171     pyCtxt = (xmlRelaxNGValidCtxtPyCtxtPtr)ctx;
3172 
3173     list = PyTuple_New(2);
3174     PyTuple_SetItem(list, 0, libxml_charPtrWrap(str));
3175     PyTuple_SetItem(list, 1, pyCtxt->arg);
3176     Py_XINCREF(pyCtxt->arg);
3177     result = PyEval_CallObject(pyCtxt->error, list);
3178     if (result == NULL)
3179     {
3180         /* TODO: manage for the exception to be propagated... */
3181         PyErr_Print();
3182     }
3183     Py_XDECREF(list);
3184     Py_XDECREF(result);
3185 }
3186 
3187 static void
libxml_xmlRelaxNGValidityGenericWarningFuncHandler(void * ctx,char * str)3188 libxml_xmlRelaxNGValidityGenericWarningFuncHandler(void *ctx, char *str)
3189 {
3190     PyObject *list;
3191     PyObject *result;
3192     xmlRelaxNGValidCtxtPyCtxtPtr pyCtxt;
3193 
3194 #ifdef DEBUG_ERROR
3195     printf("libxml_xmlRelaxNGValidityGenericWarningFuncHandler(%p, %s, ...) called\n", ctx, str);
3196 #endif
3197 
3198     pyCtxt = (xmlRelaxNGValidCtxtPyCtxtPtr)ctx;
3199 
3200     list = PyTuple_New(2);
3201     PyTuple_SetItem(list, 0, libxml_charPtrWrap(str));
3202     PyTuple_SetItem(list, 1, pyCtxt->arg);
3203     Py_XINCREF(pyCtxt->arg);
3204     result = PyEval_CallObject(pyCtxt->warn, list);
3205     if (result == NULL)
3206     {
3207         /* TODO: manage for the exception to be propagated... */
3208         PyErr_Print();
3209     }
3210     Py_XDECREF(list);
3211     Py_XDECREF(result);
3212 }
3213 
3214 static void
libxml_xmlRelaxNGValidityErrorFunc(void * ctx,const char * msg,...)3215 libxml_xmlRelaxNGValidityErrorFunc(void *ctx, const char *msg, ...)
3216 {
3217     va_list ap;
3218 
3219     va_start(ap, msg);
3220     libxml_xmlRelaxNGValidityGenericErrorFuncHandler(ctx, libxml_buildMessage(msg, ap));
3221     va_end(ap);
3222 }
3223 
3224 static void
libxml_xmlRelaxNGValidityWarningFunc(void * ctx,const char * msg,...)3225 libxml_xmlRelaxNGValidityWarningFunc(void *ctx, const char *msg, ...)
3226 {
3227     va_list ap;
3228 
3229     va_start(ap, msg);
3230     libxml_xmlRelaxNGValidityGenericWarningFuncHandler(ctx, libxml_buildMessage(msg, ap));
3231     va_end(ap);
3232 }
3233 
3234 static PyObject *
libxml_xmlRelaxNGSetValidErrors(ATTRIBUTE_UNUSED PyObject * self,PyObject * args)3235 libxml_xmlRelaxNGSetValidErrors(ATTRIBUTE_UNUSED PyObject * self, PyObject * args)
3236 {
3237     PyObject *py_retval;
3238     PyObject *pyobj_error;
3239     PyObject *pyobj_warn;
3240     PyObject *pyobj_ctx;
3241     PyObject *pyobj_arg = Py_None;
3242     xmlRelaxNGValidCtxtPtr ctxt;
3243     xmlRelaxNGValidCtxtPyCtxtPtr pyCtxt;
3244 
3245     if (!PyArg_ParseTuple
3246         (args, (char *) "OOO|O:xmlRelaxNGSetValidErrors", &pyobj_ctx, &pyobj_error, &pyobj_warn, &pyobj_arg))
3247         return (NULL);
3248 
3249 #ifdef DEBUG_ERROR
3250     printf("libxml_xmlRelaxNGSetValidErrors(%p, %p, %p) called\n", pyobj_ctx, pyobj_error, pyobj_warn);
3251 #endif
3252 
3253     ctxt = PyrelaxNgValidCtxt_Get(pyobj_ctx);
3254     if (xmlRelaxNGGetValidErrors(ctxt, NULL, NULL, (void **) &pyCtxt) == -1)
3255     {
3256         py_retval = libxml_intWrap(-1);
3257         return(py_retval);
3258     }
3259 
3260     if (pyCtxt == NULL)
3261     {
3262         /* first time to set the error handlers */
3263         pyCtxt = xmlMalloc(sizeof(xmlRelaxNGValidCtxtPyCtxt));
3264         if (pyCtxt == NULL) {
3265             py_retval = libxml_intWrap(-1);
3266             return(py_retval);
3267         }
3268         memset(pyCtxt, 0, sizeof(xmlRelaxNGValidCtxtPyCtxt));
3269     }
3270 
3271     /* TODO: check warn and error is a function ! */
3272     Py_XDECREF(pyCtxt->error);
3273     Py_XINCREF(pyobj_error);
3274     pyCtxt->error = pyobj_error;
3275 
3276     Py_XDECREF(pyCtxt->warn);
3277     Py_XINCREF(pyobj_warn);
3278     pyCtxt->warn = pyobj_warn;
3279 
3280     Py_XDECREF(pyCtxt->arg);
3281     Py_XINCREF(pyobj_arg);
3282     pyCtxt->arg = pyobj_arg;
3283 
3284     xmlRelaxNGSetValidErrors(ctxt, &libxml_xmlRelaxNGValidityErrorFunc, &libxml_xmlRelaxNGValidityWarningFunc, pyCtxt);
3285 
3286     py_retval = libxml_intWrap(1);
3287     return (py_retval);
3288 }
3289 
3290 static PyObject *
libxml_xmlRelaxNGFreeValidCtxt(ATTRIBUTE_UNUSED PyObject * self,PyObject * args)3291 libxml_xmlRelaxNGFreeValidCtxt(ATTRIBUTE_UNUSED PyObject *self, PyObject *args) {
3292     xmlRelaxNGValidCtxtPtr ctxt;
3293     xmlRelaxNGValidCtxtPyCtxtPtr pyCtxt;
3294     PyObject *pyobj_ctxt;
3295 
3296     if (!PyArg_ParseTuple(args, (char *)"O:xmlRelaxNGFreeValidCtxt", &pyobj_ctxt))
3297         return(NULL);
3298     ctxt = (xmlRelaxNGValidCtxtPtr) PyrelaxNgValidCtxt_Get(pyobj_ctxt);
3299 
3300     if (xmlRelaxNGGetValidErrors(ctxt, NULL, NULL, (void **) &pyCtxt) == 0)
3301     {
3302         if (pyCtxt != NULL)
3303         {
3304             Py_XDECREF(pyCtxt->error);
3305             Py_XDECREF(pyCtxt->warn);
3306             Py_XDECREF(pyCtxt->arg);
3307             xmlFree(pyCtxt);
3308         }
3309     }
3310 
3311     xmlRelaxNGFreeValidCtxt(ctxt);
3312     Py_INCREF(Py_None);
3313     return(Py_None);
3314 }
3315 
3316 typedef struct
3317 {
3318 	PyObject *warn;
3319 	PyObject *error;
3320 	PyObject *arg;
3321 } xmlSchemaValidCtxtPyCtxt;
3322 typedef xmlSchemaValidCtxtPyCtxt *xmlSchemaValidCtxtPyCtxtPtr;
3323 
3324 static void
libxml_xmlSchemaValidityGenericErrorFuncHandler(void * ctx,char * str)3325 libxml_xmlSchemaValidityGenericErrorFuncHandler(void *ctx, char *str)
3326 {
3327 	PyObject *list;
3328 	PyObject *result;
3329 	xmlSchemaValidCtxtPyCtxtPtr pyCtxt;
3330 
3331 #ifdef DEBUG_ERROR
3332 	printf("libxml_xmlSchemaValidityGenericErrorFuncHandler(%p, %s, ...) called\n", ctx, str);
3333 #endif
3334 
3335 	pyCtxt = (xmlSchemaValidCtxtPyCtxtPtr) ctx;
3336 
3337 	list = PyTuple_New(2);
3338 	PyTuple_SetItem(list, 0, libxml_charPtrWrap(str));
3339 	PyTuple_SetItem(list, 1, pyCtxt->arg);
3340 	Py_XINCREF(pyCtxt->arg);
3341 	result = PyEval_CallObject(pyCtxt->error, list);
3342 	if (result == NULL)
3343 	{
3344 		/* TODO: manage for the exception to be propagated... */
3345 		PyErr_Print();
3346 	}
3347 	Py_XDECREF(list);
3348 	Py_XDECREF(result);
3349 }
3350 
3351 static void
libxml_xmlSchemaValidityGenericWarningFuncHandler(void * ctx,char * str)3352 libxml_xmlSchemaValidityGenericWarningFuncHandler(void *ctx, char *str)
3353 {
3354 	PyObject *list;
3355 	PyObject *result;
3356 	xmlSchemaValidCtxtPyCtxtPtr pyCtxt;
3357 
3358 #ifdef DEBUG_ERROR
3359 	printf("libxml_xmlSchemaValidityGenericWarningFuncHandler(%p, %s, ...) called\n", ctx, str);
3360 #endif
3361 
3362 	pyCtxt = (xmlSchemaValidCtxtPyCtxtPtr) ctx;
3363 
3364 	list = PyTuple_New(2);
3365 	PyTuple_SetItem(list, 0, libxml_charPtrWrap(str));
3366 	PyTuple_SetItem(list, 1, pyCtxt->arg);
3367 	Py_XINCREF(pyCtxt->arg);
3368 	result = PyEval_CallObject(pyCtxt->warn, list);
3369 	if (result == NULL)
3370 	{
3371 		/* TODO: manage for the exception to be propagated... */
3372 		PyErr_Print();
3373 	}
3374 	Py_XDECREF(list);
3375 	Py_XDECREF(result);
3376 }
3377 
3378 static void
libxml_xmlSchemaValidityErrorFunc(void * ctx,const char * msg,...)3379 libxml_xmlSchemaValidityErrorFunc(void *ctx, const char *msg, ...)
3380 {
3381 	va_list ap;
3382 
3383 	va_start(ap, msg);
3384 	libxml_xmlSchemaValidityGenericErrorFuncHandler(ctx, libxml_buildMessage(msg, ap));
3385 	va_end(ap);
3386 }
3387 
3388 static void
libxml_xmlSchemaValidityWarningFunc(void * ctx,const char * msg,...)3389 libxml_xmlSchemaValidityWarningFunc(void *ctx, const char *msg, ...)
3390 {
3391 	va_list ap;
3392 
3393 	va_start(ap, msg);
3394 	libxml_xmlSchemaValidityGenericWarningFuncHandler(ctx, libxml_buildMessage(msg, ap));
3395 	va_end(ap);
3396 }
3397 
3398 PyObject *
libxml_xmlSchemaSetValidErrors(ATTRIBUTE_UNUSED PyObject * self,PyObject * args)3399 libxml_xmlSchemaSetValidErrors(ATTRIBUTE_UNUSED PyObject * self, PyObject * args)
3400 {
3401 	PyObject *py_retval;
3402 	PyObject *pyobj_error;
3403 	PyObject *pyobj_warn;
3404 	PyObject *pyobj_ctx;
3405 	PyObject *pyobj_arg = Py_None;
3406 	xmlSchemaValidCtxtPtr ctxt;
3407 	xmlSchemaValidCtxtPyCtxtPtr pyCtxt;
3408 
3409 	if (!PyArg_ParseTuple
3410 		(args, (char *) "OOO|O:xmlSchemaSetValidErrors", &pyobj_ctx, &pyobj_error, &pyobj_warn, &pyobj_arg))
3411 		return (NULL);
3412 
3413 #ifdef DEBUG_ERROR
3414 	printf("libxml_xmlSchemaSetValidErrors(%p, %p, %p) called\n", pyobj_ctx, pyobj_error, pyobj_warn);
3415 #endif
3416 
3417 	ctxt = PySchemaValidCtxt_Get(pyobj_ctx);
3418 	if (xmlSchemaGetValidErrors(ctxt, NULL, NULL, (void **) &pyCtxt) == -1)
3419 	{
3420 		py_retval = libxml_intWrap(-1);
3421 		return(py_retval);
3422 	}
3423 
3424 	if (pyCtxt == NULL)
3425 	{
3426 		/* first time to set the error handlers */
3427 		pyCtxt = xmlMalloc(sizeof(xmlSchemaValidCtxtPyCtxt));
3428 		if (pyCtxt == NULL) {
3429 			py_retval = libxml_intWrap(-1);
3430 			return(py_retval);
3431 		}
3432 		memset(pyCtxt, 0, sizeof(xmlSchemaValidCtxtPyCtxt));
3433 	}
3434 
3435 	/* TODO: check warn and error is a function ! */
3436 	Py_XDECREF(pyCtxt->error);
3437 	Py_XINCREF(pyobj_error);
3438 	pyCtxt->error = pyobj_error;
3439 
3440 	Py_XDECREF(pyCtxt->warn);
3441 	Py_XINCREF(pyobj_warn);
3442 	pyCtxt->warn = pyobj_warn;
3443 
3444 	Py_XDECREF(pyCtxt->arg);
3445 	Py_XINCREF(pyobj_arg);
3446 	pyCtxt->arg = pyobj_arg;
3447 
3448 	xmlSchemaSetValidErrors(ctxt, &libxml_xmlSchemaValidityErrorFunc, &libxml_xmlSchemaValidityWarningFunc, pyCtxt);
3449 
3450 	py_retval = libxml_intWrap(1);
3451 	return(py_retval);
3452 }
3453 
3454 static PyObject *
libxml_xmlSchemaFreeValidCtxt(ATTRIBUTE_UNUSED PyObject * self,PyObject * args)3455 libxml_xmlSchemaFreeValidCtxt(ATTRIBUTE_UNUSED PyObject * self, PyObject * args)
3456 {
3457 	xmlSchemaValidCtxtPtr ctxt;
3458 	xmlSchemaValidCtxtPyCtxtPtr pyCtxt;
3459 	PyObject *pyobj_ctxt;
3460 
3461 	if (!PyArg_ParseTuple(args, (char *)"O:xmlSchemaFreeValidCtxt", &pyobj_ctxt))
3462 		return(NULL);
3463 	ctxt = (xmlSchemaValidCtxtPtr) PySchemaValidCtxt_Get(pyobj_ctxt);
3464 
3465 	if (xmlSchemaGetValidErrors(ctxt, NULL, NULL, (void **) &pyCtxt) == 0)
3466 	{
3467 		if (pyCtxt != NULL)
3468 		{
3469 			Py_XDECREF(pyCtxt->error);
3470 			Py_XDECREF(pyCtxt->warn);
3471 			Py_XDECREF(pyCtxt->arg);
3472 			xmlFree(pyCtxt);
3473 		}
3474 	}
3475 
3476 	xmlSchemaFreeValidCtxt(ctxt);
3477 	Py_INCREF(Py_None);
3478 	return(Py_None);
3479 }
3480 
3481 #endif
3482 
3483 #ifdef LIBXML_C14N_ENABLED
3484 #ifdef LIBXML_OUTPUT_ENABLED
3485 
3486 /************************************************************************
3487  *                                                                      *
3488  * XML Canonicalization c14n                                            *
3489  *                                                                      *
3490  ************************************************************************/
3491 
3492 static int
PyxmlNodeSet_Convert(PyObject * py_nodeset,xmlNodeSetPtr * result)3493 PyxmlNodeSet_Convert(PyObject *py_nodeset, xmlNodeSetPtr *result)
3494 {
3495     xmlNodeSetPtr nodeSet;
3496     int is_tuple = 0;
3497 
3498     if (PyTuple_Check(py_nodeset))
3499         is_tuple = 1;
3500     else if (PyList_Check(py_nodeset))
3501         is_tuple = 0;
3502     else if (py_nodeset == Py_None) {
3503         *result = NULL;
3504         return 0;
3505     }
3506     else {
3507         PyErr_SetString(PyExc_TypeError,
3508                         "must be a tuple or list of nodes.");
3509         return -1;
3510     }
3511 
3512     nodeSet = (xmlNodeSetPtr) xmlMalloc(sizeof(xmlNodeSet));
3513     if (nodeSet == NULL) {
3514         PyErr_SetString(PyExc_MemoryError, "");
3515         return -1;
3516     }
3517 
3518     nodeSet->nodeNr = 0;
3519     nodeSet->nodeMax = (is_tuple
3520                         ? PyTuple_GET_SIZE(py_nodeset)
3521                         : PyList_GET_SIZE(py_nodeset));
3522     nodeSet->nodeTab
3523         = (xmlNodePtr *) xmlMalloc (nodeSet->nodeMax
3524                                     * sizeof(xmlNodePtr));
3525     if (nodeSet->nodeTab == NULL) {
3526         xmlFree(nodeSet);
3527         PyErr_SetString(PyExc_MemoryError, "");
3528         return -1;
3529     }
3530     memset(nodeSet->nodeTab, 0 ,
3531            nodeSet->nodeMax * sizeof(xmlNodePtr));
3532 
3533     {
3534         int idx;
3535         for (idx=0; idx < nodeSet->nodeMax; ++idx) {
3536             xmlNodePtr pynode =
3537                 PyxmlNode_Get (is_tuple
3538                                ? PyTuple_GET_ITEM(py_nodeset, idx)
3539                                : PyList_GET_ITEM(py_nodeset, idx));
3540             if (pynode)
3541                 nodeSet->nodeTab[nodeSet->nodeNr++] = pynode;
3542         }
3543     }
3544     *result = nodeSet;
3545     return 0;
3546 }
3547 
3548 static int
PystringSet_Convert(PyObject * py_strings,xmlChar *** result)3549 PystringSet_Convert(PyObject *py_strings, xmlChar *** result)
3550 {
3551     /* NOTE: the array should be freed, but the strings are shared
3552        with the python strings and so must not be freed. */
3553 
3554     xmlChar ** strings;
3555     int is_tuple = 0;
3556     int count;
3557     int init_index = 0;
3558 
3559     if (PyTuple_Check(py_strings))
3560         is_tuple = 1;
3561     else if (PyList_Check(py_strings))
3562         is_tuple = 0;
3563     else if (py_strings == Py_None) {
3564         *result = NULL;
3565         return 0;
3566     }
3567     else {
3568         PyErr_SetString(PyExc_TypeError,
3569                         "must be a tuple or list of strings.");
3570         return -1;
3571     }
3572 
3573     count = (is_tuple
3574              ? PyTuple_GET_SIZE(py_strings)
3575              : PyList_GET_SIZE(py_strings));
3576 
3577     strings = (xmlChar **) xmlMalloc(sizeof(xmlChar *) * count);
3578 
3579     if (strings == NULL) {
3580         PyErr_SetString(PyExc_MemoryError, "");
3581         return -1;
3582     }
3583 
3584     memset(strings, 0 , sizeof(xmlChar *) * count);
3585 
3586     {
3587         int idx;
3588         for (idx=0; idx < count; ++idx) {
3589             char* s = PyBytes_AsString
3590                 (is_tuple
3591                  ? PyTuple_GET_ITEM(py_strings, idx)
3592                  : PyList_GET_ITEM(py_strings, idx));
3593             if (s)
3594                 strings[init_index++] = (xmlChar *)s;
3595             else {
3596                 xmlFree(strings);
3597                 PyErr_SetString(PyExc_TypeError,
3598                                 "must be a tuple or list of strings.");
3599                 return -1;
3600             }
3601         }
3602     }
3603 
3604     *result = strings;
3605     return 0;
3606 }
3607 
3608 static PyObject *
libxml_C14NDocDumpMemory(ATTRIBUTE_UNUSED PyObject * self,PyObject * args)3609 libxml_C14NDocDumpMemory(ATTRIBUTE_UNUSED PyObject * self,
3610                          PyObject * args)
3611 {
3612     PyObject *py_retval = NULL;
3613 
3614     PyObject *pyobj_doc;
3615     PyObject *pyobj_nodes;
3616     int exclusive;
3617     PyObject *pyobj_prefixes;
3618     int with_comments;
3619 
3620     xmlDocPtr doc;
3621     xmlNodeSetPtr nodes;
3622     xmlChar **prefixes = NULL;
3623     xmlChar *doc_txt;
3624 
3625     int result;
3626 
3627     if (!PyArg_ParseTuple(args, (char *) "OOiOi:C14NDocDumpMemory",
3628                           &pyobj_doc,
3629                           &pyobj_nodes,
3630                           &exclusive,
3631                           &pyobj_prefixes,
3632                           &with_comments))
3633         return (NULL);
3634 
3635     doc = (xmlDocPtr) PyxmlNode_Get(pyobj_doc);
3636     if (!doc) {
3637         PyErr_SetString(PyExc_TypeError, "bad document.");
3638         return NULL;
3639     }
3640 
3641     result = PyxmlNodeSet_Convert(pyobj_nodes, &nodes);
3642     if (result < 0) return NULL;
3643 
3644     if (exclusive) {
3645         result = PystringSet_Convert(pyobj_prefixes, &prefixes);
3646         if (result < 0) {
3647             if (nodes) {
3648                 xmlFree(nodes->nodeTab);
3649                 xmlFree(nodes);
3650             }
3651             return NULL;
3652         }
3653     }
3654 
3655     result = xmlC14NDocDumpMemory(doc,
3656                                   nodes,
3657                                   exclusive,
3658                                   prefixes,
3659                                   with_comments,
3660                                   &doc_txt);
3661 
3662     if (nodes) {
3663         xmlFree(nodes->nodeTab);
3664         xmlFree(nodes);
3665     }
3666     if (prefixes) {
3667         xmlChar ** idx = prefixes;
3668         while (*idx) xmlFree(*(idx++));
3669         xmlFree(prefixes);
3670     }
3671 
3672     if (result < 0) {
3673         PyErr_SetString(PyExc_Exception,
3674                         "libxml2 xmlC14NDocDumpMemory failure.");
3675         return NULL;
3676     }
3677     else {
3678         py_retval = PY_IMPORT_STRING_SIZE((const char *) doc_txt,
3679                                                 result);
3680         xmlFree(doc_txt);
3681         return py_retval;
3682     }
3683 }
3684 
3685 static PyObject *
libxml_C14NDocSaveTo(ATTRIBUTE_UNUSED PyObject * self,PyObject * args)3686 libxml_C14NDocSaveTo(ATTRIBUTE_UNUSED PyObject * self,
3687                      PyObject * args)
3688 {
3689     PyObject *pyobj_doc;
3690     PyObject *py_file;
3691     PyObject *pyobj_nodes;
3692     int exclusive;
3693     PyObject *pyobj_prefixes;
3694     int with_comments;
3695 
3696     xmlDocPtr doc;
3697     xmlNodeSetPtr nodes;
3698     xmlChar **prefixes = NULL;
3699     FILE * output;
3700     xmlOutputBufferPtr buf;
3701 
3702     int result;
3703     int len;
3704 
3705     if (!PyArg_ParseTuple(args, (char *) "OOiOiO:C14NDocSaveTo",
3706                           &pyobj_doc,
3707                           &pyobj_nodes,
3708                           &exclusive,
3709                           &pyobj_prefixes,
3710                           &with_comments,
3711                           &py_file))
3712         return (NULL);
3713 
3714     doc = (xmlDocPtr) PyxmlNode_Get(pyobj_doc);
3715     if (!doc) {
3716         PyErr_SetString(PyExc_TypeError, "bad document.");
3717         return NULL;
3718     }
3719 
3720     output = PyFile_Get(py_file);
3721     if (output == NULL) {
3722         PyErr_SetString(PyExc_TypeError, "bad file.");
3723         return NULL;
3724     }
3725     buf = xmlOutputBufferCreateFile(output, NULL);
3726 
3727     result = PyxmlNodeSet_Convert(pyobj_nodes, &nodes);
3728     if (result < 0) {
3729         xmlOutputBufferClose(buf);
3730         return NULL;
3731     }
3732 
3733     if (exclusive) {
3734         result = PystringSet_Convert(pyobj_prefixes, &prefixes);
3735         if (result < 0) {
3736             if (nodes) {
3737                 xmlFree(nodes->nodeTab);
3738                 xmlFree(nodes);
3739             }
3740             xmlOutputBufferClose(buf);
3741             return NULL;
3742         }
3743     }
3744 
3745     result = xmlC14NDocSaveTo(doc,
3746                               nodes,
3747                               exclusive,
3748                               prefixes,
3749                               with_comments,
3750                               buf);
3751 
3752     if (nodes) {
3753         xmlFree(nodes->nodeTab);
3754         xmlFree(nodes);
3755     }
3756     if (prefixes) {
3757         xmlChar ** idx = prefixes;
3758         while (*idx) xmlFree(*(idx++));
3759         xmlFree(prefixes);
3760     }
3761 
3762     PyFile_Release(output);
3763     len = xmlOutputBufferClose(buf);
3764 
3765     if (result < 0) {
3766         PyErr_SetString(PyExc_Exception,
3767                         "libxml2 xmlC14NDocSaveTo failure.");
3768         return NULL;
3769     }
3770     else
3771         return PyLong_FromLong((long) len);
3772 }
3773 
3774 #endif
3775 #endif
3776 
3777 static PyObject *
libxml_getObjDesc(PyObject * self ATTRIBUTE_UNUSED,PyObject * args)3778 libxml_getObjDesc(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) {
3779 
3780     PyObject *obj;
3781     char *str;
3782 
3783     if (!PyArg_ParseTuple(args, (char *)"O:getObjDesc", &obj))
3784         return NULL;
3785     str = PyCapsule_GetPointer(obj, PyCapsule_GetName(obj));
3786     return Py_BuildValue((char *)"s", str);
3787 }
3788 
3789 static PyObject *
libxml_compareNodesEqual(PyObject * self ATTRIBUTE_UNUSED,PyObject * args)3790 libxml_compareNodesEqual(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) {
3791 
3792     PyObject *py_node1, *py_node2;
3793     xmlNodePtr node1, node2;
3794 
3795     if (!PyArg_ParseTuple(args, (char *)"OO:compareNodesEqual",
3796 		&py_node1, &py_node2))
3797         return NULL;
3798     /* To compare two node objects, we compare their pointer addresses */
3799     node1 = PyxmlNode_Get(py_node1);
3800     node2 = PyxmlNode_Get(py_node2);
3801     if ( node1 == node2 )
3802         return Py_BuildValue((char *)"i", 1);
3803     else
3804         return Py_BuildValue((char *)"i", 0);
3805 
3806 }
3807 
3808 static PyObject *
libxml_nodeHash(PyObject * self ATTRIBUTE_UNUSED,PyObject * args)3809 libxml_nodeHash(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) {
3810 
3811     PyObject *py_node1;
3812     xmlNodePtr node1;
3813 
3814     if (!PyArg_ParseTuple(args, (char *)"O:nodeHash", &py_node1))
3815 	    return NULL;
3816     /* For simplicity, we use the node pointer address as a hash value */
3817     node1 = PyxmlNode_Get(py_node1);
3818 
3819     return PyLong_FromVoidPtr(node1);
3820 
3821 }
3822 
3823 /************************************************************************
3824  *									*
3825  *			The registration stuff				*
3826  *									*
3827  ************************************************************************/
3828 static PyMethodDef libxmlMethods[] = {
3829 #include "libxml2-export.c"
3830     {(char *) "name", libxml_name, METH_VARARGS, NULL},
3831     {(char *) "children", libxml_children, METH_VARARGS, NULL},
3832     {(char *) "properties", libxml_properties, METH_VARARGS, NULL},
3833     {(char *) "last", libxml_last, METH_VARARGS, NULL},
3834     {(char *) "prev", libxml_prev, METH_VARARGS, NULL},
3835     {(char *) "next", libxml_next, METH_VARARGS, NULL},
3836     {(char *) "parent", libxml_parent, METH_VARARGS, NULL},
3837     {(char *) "type", libxml_type, METH_VARARGS, NULL},
3838     {(char *) "doc", libxml_doc, METH_VARARGS, NULL},
3839     {(char *) "xmlNewNode", libxml_xmlNewNode, METH_VARARGS, NULL},
3840     {(char *) "xmlNodeRemoveNsDef", libxml_xmlNodeRemoveNsDef, METH_VARARGS, NULL},
3841     {(char *)"xmlSetValidErrors", libxml_xmlSetValidErrors, METH_VARARGS, NULL},
3842     {(char *)"xmlFreeValidCtxt", libxml_xmlFreeValidCtxt, METH_VARARGS, NULL},
3843 #ifdef LIBXML_OUTPUT_ENABLED
3844     {(char *) "serializeNode", libxml_serializeNode, METH_VARARGS, NULL},
3845     {(char *) "saveNodeTo", libxml_saveNodeTo, METH_VARARGS, NULL},
3846     {(char *) "outputBufferCreate", libxml_xmlCreateOutputBuffer, METH_VARARGS, NULL},
3847     {(char *) "outputBufferGetPythonFile", libxml_outputBufferGetPythonFile, METH_VARARGS, NULL},
3848     {(char *) "xmlOutputBufferClose", libxml_xmlOutputBufferClose, METH_VARARGS, NULL},
3849     { (char *)"xmlOutputBufferFlush", libxml_xmlOutputBufferFlush, METH_VARARGS, NULL },
3850     { (char *)"xmlSaveFileTo", libxml_xmlSaveFileTo, METH_VARARGS, NULL },
3851     { (char *)"xmlSaveFormatFileTo", libxml_xmlSaveFormatFileTo, METH_VARARGS, NULL },
3852 #endif /* LIBXML_OUTPUT_ENABLED */
3853     {(char *) "inputBufferCreate", libxml_xmlCreateInputBuffer, METH_VARARGS, NULL},
3854     {(char *) "setEntityLoader", libxml_xmlSetEntityLoader, METH_VARARGS, NULL},
3855     {(char *)"xmlRegisterErrorHandler", libxml_xmlRegisterErrorHandler, METH_VARARGS, NULL },
3856     {(char *)"xmlParserCtxtSetErrorHandler", libxml_xmlParserCtxtSetErrorHandler, METH_VARARGS, NULL },
3857     {(char *)"xmlParserCtxtGetErrorHandler", libxml_xmlParserCtxtGetErrorHandler, METH_VARARGS, NULL },
3858     {(char *)"xmlFreeParserCtxt", libxml_xmlFreeParserCtxt, METH_VARARGS, NULL },
3859 #ifdef LIBXML_READER_ENABLED
3860     {(char *)"xmlTextReaderSetErrorHandler", libxml_xmlTextReaderSetErrorHandler, METH_VARARGS, NULL },
3861     {(char *)"xmlTextReaderGetErrorHandler", libxml_xmlTextReaderGetErrorHandler, METH_VARARGS, NULL },
3862     {(char *)"xmlFreeTextReader", libxml_xmlFreeTextReader, METH_VARARGS, NULL },
3863 #endif
3864     {(char *)"addLocalCatalog", libxml_addLocalCatalog, METH_VARARGS, NULL },
3865 #ifdef LIBXML_SCHEMAS_ENABLED
3866     {(char *)"xmlRelaxNGSetValidErrors", libxml_xmlRelaxNGSetValidErrors, METH_VARARGS, NULL},
3867     {(char *)"xmlRelaxNGFreeValidCtxt", libxml_xmlRelaxNGFreeValidCtxt, METH_VARARGS, NULL},
3868     {(char *)"xmlSchemaSetValidErrors", libxml_xmlSchemaSetValidErrors, METH_VARARGS, NULL},
3869     {(char *)"xmlSchemaFreeValidCtxt", libxml_xmlSchemaFreeValidCtxt, METH_VARARGS, NULL},
3870 #endif
3871 #ifdef LIBXML_C14N_ENABLED
3872 #ifdef LIBXML_OUTPUT_ENABLED
3873     {(char *)"xmlC14NDocDumpMemory", libxml_C14NDocDumpMemory, METH_VARARGS, NULL},
3874     {(char *)"xmlC14NDocSaveTo", libxml_C14NDocSaveTo, METH_VARARGS, NULL},
3875 #endif
3876 #endif
3877     {(char *) "getObjDesc", libxml_getObjDesc, METH_VARARGS, NULL},
3878     {(char *) "compareNodesEqual", libxml_compareNodesEqual, METH_VARARGS, NULL},
3879     {(char *) "nodeHash", libxml_nodeHash, METH_VARARGS, NULL},
3880     {(char *) "xmlRegisterInputCallback", libxml_xmlRegisterInputCallback, METH_VARARGS, NULL},
3881     {(char *) "xmlUnregisterInputCallback", libxml_xmlUnregisterInputCallback, METH_VARARGS, NULL},
3882     {NULL, NULL, 0, NULL}
3883 };
3884 
3885 #if PY_MAJOR_VERSION >= 3
3886 #define INITERROR return NULL
3887 
3888 static struct PyModuleDef moduledef = {
3889         PyModuleDef_HEAD_INIT,
3890         "libxml2mod",
3891         NULL,
3892         -1,
3893         libxmlMethods,
3894         NULL,
3895         NULL,
3896         NULL,
3897         NULL
3898 };
3899 
3900 #else
3901 #define INITERROR return
3902 
3903 #ifdef MERGED_MODULES
3904 extern void initlibxsltmod(void);
3905 #endif
3906 
3907 #endif
3908 
3909 #if PY_MAJOR_VERSION >= 3
PyInit_libxml2mod(void)3910 PyObject *PyInit_libxml2mod(void)
3911 #else
3912 void initlibxml2mod(void)
3913 #endif
3914 {
3915     PyObject *module;
3916 
3917 #if PY_MAJOR_VERSION >= 3
3918     module = PyModule_Create(&moduledef);
3919 #else
3920     /* initialize the python extension module */
3921     module = Py_InitModule((char *) "libxml2mod", libxmlMethods);
3922 #endif
3923     if (module == NULL)
3924         INITERROR;
3925 
3926     /* initialize libxml2 */
3927     xmlInitParser();
3928     /* TODO this probably need to be revamped for Python3 */
3929     libxml_xmlErrorInitialize();
3930 
3931 #if PY_MAJOR_VERSION < 3
3932 #ifdef MERGED_MODULES
3933     initlibxsltmod();
3934 #endif
3935 #endif
3936 
3937 #if PY_MAJOR_VERSION >= 3
3938     return module;
3939 #endif
3940 }
3941