-
Notifications
You must be signed in to change notification settings - Fork 1
/
libxml.c
3934 lines (3468 loc) · 107 KB
/
libxml.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* libxml.c: this modules implements the main part of the glue of the
* libxml2 library and the Python interpreter. It provides the
* entry points where an automatically generated stub is either
* unpractical or would not match cleanly the Python model.
*
* If compiled with MERGED_MODULES, the entry point will be used to
* initialize both the libxml2 and the libxslt wrappers
*
* See Copyright for the status of this software.
*
* daniel@veillard.com
*/
#include <Python.h>
#include <fileobject.h>
/* #include "config.h" */
#include <libxml/xmlmemory.h>
#include <libxml/parser.h>
#include <libxml/tree.h>
#include <libxml/xpath.h>
#include <libxml/xmlerror.h>
#include <libxml/xpathInternals.h>
#include <libxml/xmlmemory.h>
#include <libxml/xmlIO.h>
#include <libxml/c14n.h>
#include <libxml/xmlreader.h>
#include <libxml/xmlsave.h>
#include "libxml_wrap.h"
#include "libxml2-py.h"
#if defined(WITH_TRIO)
#include "trio.h"
#define vsnprintf trio_vsnprintf
#endif
/* #define DEBUG */
/* #define DEBUG_SAX */
/* #define DEBUG_XPATH */
/* #define DEBUG_ERROR */
/* #define DEBUG_MEMORY */
/* #define DEBUG_FILES */
/* #define DEBUG_LOADER */
#if PY_MAJOR_VERSION >= 3
PyObject *PyInit_libxml2mod(void);
#define PY_IMPORT_STRING_SIZE PyUnicode_FromStringAndSize
#define PY_IMPORT_STRING PyUnicode_FromString
#else
void initlibxml2mod(void);
#define PY_IMPORT_STRING_SIZE PyString_FromStringAndSize
#define PY_IMPORT_STRING PyString_FromString
#endif
/**
* TODO:
*
* macro to flag unimplemented blocks
*/
#define TODO \
xmlGenericError(xmlGenericErrorContext, \
"Unimplemented block at %s:%d\n", \
__FILE__, __LINE__);
/*
* the following vars are used for XPath extensions, but
* are also referenced within the parser cleanup routine.
*/
static int libxml_xpathCallbacksInitialized = 0;
typedef struct libxml_xpathCallback {
xmlXPathContextPtr ctx;
xmlChar *name;
xmlChar *ns_uri;
PyObject *function;
} libxml_xpathCallback, *libxml_xpathCallbackPtr;
typedef libxml_xpathCallback libxml_xpathCallbackArray[];
static int libxml_xpathCallbacksAllocd = 10;
static libxml_xpathCallbackArray *libxml_xpathCallbacks = NULL;
static int libxml_xpathCallbacksNb = 0;
/************************************************************************
* *
* Memory debug interface *
* *
************************************************************************/
#if 0
extern void xmlMemFree(void *ptr);
extern void *xmlMemMalloc(size_t size);
extern void *xmlMemRealloc(void *ptr, size_t size);
extern char *xmlMemoryStrdup(const char *str);
#endif
static int libxmlMemoryDebugActivated = 0;
static long libxmlMemoryAllocatedBase = 0;
static int libxmlMemoryDebug = 0;
static xmlFreeFunc freeFunc = NULL;
static xmlMallocFunc mallocFunc = NULL;
static xmlReallocFunc reallocFunc = NULL;
static xmlStrdupFunc strdupFunc = NULL;
static void
libxml_xmlErrorInitialize(void); /* forward declare */
PyObject *
libxml_xmlMemoryUsed(PyObject * self ATTRIBUTE_UNUSED,
PyObject * args ATTRIBUTE_UNUSED)
{
long ret;
PyObject *py_retval;
ret = xmlMemUsed();
py_retval = libxml_longWrap(ret);
return (py_retval);
}
PyObject *
libxml_xmlDebugMemory(PyObject * self ATTRIBUTE_UNUSED, PyObject * args)
{
int activate;
PyObject *py_retval;
long ret;
if (!PyArg_ParseTuple(args, (char *) "i:xmlDebugMemory", &activate))
return (NULL);
#ifdef DEBUG_MEMORY
printf("libxml_xmlDebugMemory(%d) called\n", activate);
#endif
if (activate != 0) {
if (libxmlMemoryDebug == 0) {
/*
* First initialize the library and grab the old memory handlers
* and switch the library to memory debugging
*/
xmlMemGet((xmlFreeFunc *) & freeFunc,
(xmlMallocFunc *) & mallocFunc,
(xmlReallocFunc *) & reallocFunc,
(xmlStrdupFunc *) & strdupFunc);
if ((freeFunc == xmlMemFree) && (mallocFunc == xmlMemMalloc) &&
(reallocFunc == xmlMemRealloc) &&
(strdupFunc == xmlMemoryStrdup)) {
libxmlMemoryAllocatedBase = xmlMemUsed();
} else {
/*
* cleanup first, because some memory has been
* allocated with the non-debug malloc in xmlInitParser
* when the python module was imported
*/
xmlCleanupParser();
ret = (long) xmlMemSetup(xmlMemFree, xmlMemMalloc,
xmlMemRealloc, xmlMemoryStrdup);
if (ret < 0)
goto error;
libxmlMemoryAllocatedBase = xmlMemUsed();
/* reinitialize */
xmlInitParser();
libxml_xmlErrorInitialize();
}
ret = 0;
} else if (libxmlMemoryDebugActivated == 0) {
libxmlMemoryAllocatedBase = xmlMemUsed();
ret = 0;
} else {
ret = xmlMemUsed() - libxmlMemoryAllocatedBase;
}
libxmlMemoryDebug = 1;
libxmlMemoryDebugActivated = 1;
} else {
if (libxmlMemoryDebugActivated == 1)
ret = xmlMemUsed() - libxmlMemoryAllocatedBase;
else
ret = 0;
libxmlMemoryDebugActivated = 0;
}
error:
py_retval = libxml_longWrap(ret);
return (py_retval);
}
PyObject *
libxml_xmlPythonCleanupParser(PyObject *self ATTRIBUTE_UNUSED,
PyObject *args ATTRIBUTE_UNUSED) {
int ix;
long freed = -1;
if (libxmlMemoryDebug) {
freed = xmlMemUsed();
}
xmlCleanupParser();
/*
* Need to confirm whether we really want to do this (required for
* memcheck) in all cases...
*/
if (libxml_xpathCallbacks != NULL) { /* if ext funcs declared */
for (ix=0; ix<libxml_xpathCallbacksNb; ix++) {
if ((*libxml_xpathCallbacks)[ix].name != NULL)
xmlFree((*libxml_xpathCallbacks)[ix].name);
if ((*libxml_xpathCallbacks)[ix].ns_uri != NULL)
xmlFree((*libxml_xpathCallbacks)[ix].ns_uri);
}
libxml_xpathCallbacksNb = 0;
xmlFree(libxml_xpathCallbacks);
libxml_xpathCallbacks = NULL;
}
if (libxmlMemoryDebug) {
freed -= xmlMemUsed();
libxmlMemoryAllocatedBase -= freed;
if (libxmlMemoryAllocatedBase < 0)
libxmlMemoryAllocatedBase = 0;
}
Py_INCREF(Py_None);
return(Py_None);
}
PyObject *
libxml_xmlDumpMemory(ATTRIBUTE_UNUSED PyObject * self,
ATTRIBUTE_UNUSED PyObject * args)
{
if (libxmlMemoryDebug != 0)
xmlMemoryDump();
Py_INCREF(Py_None);
return (Py_None);
}
/************************************************************************
* *
* Handling Python FILE I/O at the C level *
* The raw I/O attack diectly the File objects, while the *
* other routines address the ioWrapper instance instead *
* *
************************************************************************/
/**
* xmlPythonFileCloseUnref:
* @context: the I/O context
*
* Close an I/O channel
*/
static int
xmlPythonFileCloseRaw (void * context) {
PyObject *file, *ret;
#ifdef DEBUG_FILES
printf("xmlPythonFileCloseUnref\n");
#endif
file = (PyObject *) context;
if (file == NULL) return(-1);
ret = PyEval_CallMethod(file, (char *) "close", (char *) "()");
if (ret != NULL) {
Py_DECREF(ret);
}
Py_DECREF(file);
return(0);
}
/**
* xmlPythonFileReadRaw:
* @context: the I/O context
* @buffer: where to drop data
* @len: number of bytes to write
*
* Read @len bytes to @buffer from the Python file in the I/O channel
*
* Returns the number of bytes read
*/
static int
xmlPythonFileReadRaw (void * context, char * buffer, int len) {
PyObject *file;
PyObject *ret;
int lenread = -1;
char *data;
#ifdef DEBUG_FILES
printf("xmlPythonFileReadRaw: %d\n", len);
#endif
file = (PyObject *) context;
if (file == NULL) return(-1);
ret = PyEval_CallMethod(file, (char *) "read", (char *) "(i)", len);
if (ret == NULL) {
printf("xmlPythonFileReadRaw: result is NULL\n");
return(-1);
} else if (PyBytes_Check(ret)) {
lenread = PyBytes_Size(ret);
data = PyBytes_AsString(ret);
#ifdef PyUnicode_Check
} else if PyUnicode_Check (ret) {
#if PY_VERSION_HEX >= 0x03030000
size_t size;
const char *tmp;
/* tmp doesn't need to be deallocated */
tmp = PyUnicode_AsUTF8AndSize(ret, &size);
lenread = (int) size;
data = (char *) tmp;
#else
PyObject *b;
b = PyUnicode_AsUTF8String(ret);
if (b == NULL) {
printf("xmlPythonFileReadRaw: failed to convert to UTF-8\n");
return(-1);
}
lenread = PyBytes_Size(b);
data = PyBytes_AsString(b);
Py_DECREF(b);
#endif
#endif
} else {
printf("xmlPythonFileReadRaw: result is not a String\n");
Py_DECREF(ret);
return(-1);
}
if (lenread > len)
memcpy(buffer, data, len);
else
memcpy(buffer, data, lenread);
Py_DECREF(ret);
return(lenread);
}
/**
* xmlPythonFileRead:
* @context: the I/O context
* @buffer: where to drop data
* @len: number of bytes to write
*
* Read @len bytes to @buffer from the I/O channel.
*
* Returns the number of bytes read
*/
static int
xmlPythonFileRead (void * context, char * buffer, int len) {
PyObject *file;
PyObject *ret;
int lenread = -1;
char *data;
#ifdef DEBUG_FILES
printf("xmlPythonFileRead: %d\n", len);
#endif
file = (PyObject *) context;
if (file == NULL) return(-1);
ret = PyEval_CallMethod(file, (char *) "io_read", (char *) "(i)", len);
if (ret == NULL) {
printf("xmlPythonFileRead: result is NULL\n");
return(-1);
} else if (PyBytes_Check(ret)) {
lenread = PyBytes_Size(ret);
data = PyBytes_AsString(ret);
#ifdef PyUnicode_Check
} else if PyUnicode_Check (ret) {
#if PY_VERSION_HEX >= 0x03030000
size_t size;
const char *tmp;
/* tmp doesn't need to be deallocated */
tmp = PyUnicode_AsUTF8AndSize(ret, &size);
lenread = (int) size;
data = (char *) tmp;
#else
PyObject *b;
b = PyUnicode_AsUTF8String(ret);
if (b == NULL) {
printf("xmlPythonFileRead: failed to convert to UTF-8\n");
return(-1);
}
lenread = PyBytes_Size(b);
data = PyBytes_AsString(b);
Py_DECREF(b);
#endif
#endif
} else {
printf("xmlPythonFileRead: result is not a String\n");
Py_DECREF(ret);
return(-1);
}
if (lenread > len)
memcpy(buffer, data, len);
else
memcpy(buffer, data, lenread);
Py_DECREF(ret);
return(lenread);
}
/**
* xmlFileWrite:
* @context: the I/O context
* @buffer: where to drop data
* @len: number of bytes to write
*
* Write @len bytes from @buffer to the I/O channel.
*
* Returns the number of bytes written
*/
static int
xmlPythonFileWrite (void * context, const char * buffer, int len) {
PyObject *file;
PyObject *string;
PyObject *ret = NULL;
int written = -1;
#ifdef DEBUG_FILES
printf("xmlPythonFileWrite: %d\n", len);
#endif
file = (PyObject *) context;
if (file == NULL) return(-1);
string = PY_IMPORT_STRING_SIZE(buffer, len);
if (string == NULL) return(-1);
if (PyObject_HasAttrString(file, (char *) "io_write")) {
ret = PyEval_CallMethod(file, (char *) "io_write", (char *) "(O)",
string);
} else if (PyObject_HasAttrString(file, (char *) "write")) {
ret = PyEval_CallMethod(file, (char *) "write", (char *) "(O)",
string);
}
Py_DECREF(string);
if (ret == NULL) {
printf("xmlPythonFileWrite: result is NULL\n");
return(-1);
} else if (PyLong_Check(ret)) {
written = (int) PyLong_AsLong(ret);
Py_DECREF(ret);
} else if (ret == Py_None) {
written = len;
Py_DECREF(ret);
} else {
printf("xmlPythonFileWrite: result is not an Int nor None\n");
Py_DECREF(ret);
}
return(written);
}
/**
* xmlPythonFileClose:
* @context: the I/O context
*
* Close an I/O channel
*/
static int
xmlPythonFileClose (void * context) {
PyObject *file, *ret = NULL;
#ifdef DEBUG_FILES
printf("xmlPythonFileClose\n");
#endif
file = (PyObject *) context;
if (file == NULL) return(-1);
if (PyObject_HasAttrString(file, (char *) "io_close")) {
ret = PyEval_CallMethod(file, (char *) "io_close", (char *) "()");
} else if (PyObject_HasAttrString(file, (char *) "flush")) {
ret = PyEval_CallMethod(file, (char *) "flush", (char *) "()");
}
if (ret != NULL) {
Py_DECREF(ret);
}
return(0);
}
#ifdef LIBXML_OUTPUT_ENABLED
/**
* xmlOutputBufferCreatePythonFile:
* @file: a PyFile_Type
* @encoder: the encoding converter or NULL
*
* Create a buffered output for the progressive saving to a PyFile_Type
* buffered C I/O
*
* Returns the new parser output or NULL
*/
static xmlOutputBufferPtr
xmlOutputBufferCreatePythonFile(PyObject *file,
xmlCharEncodingHandlerPtr encoder) {
xmlOutputBufferPtr ret;
if (file == NULL) return(NULL);
ret = xmlAllocOutputBuffer(encoder);
if (ret != NULL) {
ret->context = file;
/* Py_INCREF(file); */
ret->writecallback = xmlPythonFileWrite;
ret->closecallback = xmlPythonFileClose;
}
return(ret);
}
PyObject *
libxml_xmlCreateOutputBuffer(ATTRIBUTE_UNUSED PyObject *self, PyObject *args) {
PyObject *py_retval;
PyObject *file;
xmlChar *encoding;
xmlCharEncodingHandlerPtr handler = NULL;
xmlOutputBufferPtr buffer;
if (!PyArg_ParseTuple(args, (char *)"Oz:xmlOutputBufferCreate",
&file, &encoding))
return(NULL);
if ((encoding != NULL) && (encoding[0] != 0)) {
handler = xmlFindCharEncodingHandler((const char *) encoding);
}
buffer = xmlOutputBufferCreatePythonFile(file, handler);
if (buffer == NULL)
printf("libxml_xmlCreateOutputBuffer: buffer == NULL\n");
py_retval = libxml_xmlOutputBufferPtrWrap(buffer);
return(py_retval);
}
/**
* libxml_outputBufferGetPythonFile:
* @buffer: the I/O buffer
*
* read the Python I/O from the CObject
*
* Returns the new parser output or NULL
*/
static PyObject *
libxml_outputBufferGetPythonFile(ATTRIBUTE_UNUSED PyObject *self,
PyObject *args) {
PyObject *buffer;
PyObject *file;
xmlOutputBufferPtr obj;
if (!PyArg_ParseTuple(args, (char *)"O:outputBufferGetPythonFile",
&buffer))
return(NULL);
obj = PyoutputBuffer_Get(buffer);
if (obj == NULL) {
fprintf(stderr,
"outputBufferGetPythonFile: obj == NULL\n");
Py_INCREF(Py_None);
return(Py_None);
}
if (obj->closecallback != xmlPythonFileClose) {
fprintf(stderr,
"outputBufferGetPythonFile: not a python file wrapper\n");
Py_INCREF(Py_None);
return(Py_None);
}
file = (PyObject *) obj->context;
if (file == NULL) {
Py_INCREF(Py_None);
return(Py_None);
}
Py_INCREF(file);
return(file);
}
static PyObject *
libxml_xmlOutputBufferClose(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) {
PyObject *py_retval;
int c_retval;
xmlOutputBufferPtr out;
PyObject *pyobj_out;
if (!PyArg_ParseTuple(args, (char *)"O:xmlOutputBufferClose", &pyobj_out))
return(NULL);
out = (xmlOutputBufferPtr) PyoutputBuffer_Get(pyobj_out);
/* Buffer may already have been destroyed elsewhere. This is harmless. */
if (out == NULL) {
Py_INCREF(Py_None);
return(Py_None);
}
c_retval = xmlOutputBufferClose(out);
py_retval = libxml_intWrap((int) c_retval);
return(py_retval);
}
static PyObject *
libxml_xmlOutputBufferFlush(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) {
PyObject *py_retval;
int c_retval;
xmlOutputBufferPtr out;
PyObject *pyobj_out;
if (!PyArg_ParseTuple(args, (char *)"O:xmlOutputBufferFlush", &pyobj_out))
return(NULL);
out = (xmlOutputBufferPtr) PyoutputBuffer_Get(pyobj_out);
c_retval = xmlOutputBufferFlush(out);
py_retval = libxml_intWrap((int) c_retval);
return(py_retval);
}
static PyObject *
libxml_xmlSaveFileTo(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) {
PyObject *py_retval;
int c_retval;
xmlOutputBufferPtr buf;
PyObject *pyobj_buf;
xmlDocPtr cur;
PyObject *pyobj_cur;
char * encoding;
if (!PyArg_ParseTuple(args, (char *)"OOz:xmlSaveFileTo", &pyobj_buf, &pyobj_cur, &encoding))
return(NULL);
buf = (xmlOutputBufferPtr) PyoutputBuffer_Get(pyobj_buf);
cur = (xmlDocPtr) PyxmlNode_Get(pyobj_cur);
c_retval = xmlSaveFileTo(buf, cur, encoding);
/* xmlSaveTo() freed the memory pointed to by buf, so record that in the
* Python object. */
((PyoutputBuffer_Object *)(pyobj_buf))->obj = NULL;
py_retval = libxml_intWrap((int) c_retval);
return(py_retval);
}
static PyObject *
libxml_xmlSaveFormatFileTo(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) {
PyObject *py_retval;
int c_retval;
xmlOutputBufferPtr buf;
PyObject *pyobj_buf;
xmlDocPtr cur;
PyObject *pyobj_cur;
char * encoding;
int format;
if (!PyArg_ParseTuple(args, (char *)"OOzi:xmlSaveFormatFileTo", &pyobj_buf, &pyobj_cur, &encoding, &format))
return(NULL);
buf = (xmlOutputBufferPtr) PyoutputBuffer_Get(pyobj_buf);
cur = (xmlDocPtr) PyxmlNode_Get(pyobj_cur);
c_retval = xmlSaveFormatFileTo(buf, cur, encoding, format);
/* xmlSaveFormatFileTo() freed the memory pointed to by buf, so record that
* in the Python object */
((PyoutputBuffer_Object *)(pyobj_buf))->obj = NULL;
py_retval = libxml_intWrap((int) c_retval);
return(py_retval);
}
#endif /* LIBXML_OUTPUT_ENABLED */
/**
* xmlParserInputBufferCreatePythonFile:
* @file: a PyFile_Type
* @encoder: the encoding converter or NULL
*
* Create a buffered output for the progressive saving to a PyFile_Type
* buffered C I/O
*
* Returns the new parser output or NULL
*/
static xmlParserInputBufferPtr
xmlParserInputBufferCreatePythonFile(PyObject *file,
xmlCharEncoding encoding) {
xmlParserInputBufferPtr ret;
if (file == NULL) return(NULL);
ret = xmlAllocParserInputBuffer(encoding);
if (ret != NULL) {
ret->context = file;
/* Py_INCREF(file); */
ret->readcallback = xmlPythonFileRead;
ret->closecallback = xmlPythonFileClose;
}
return(ret);
}
PyObject *
libxml_xmlCreateInputBuffer(ATTRIBUTE_UNUSED PyObject *self, PyObject *args) {
PyObject *py_retval;
PyObject *file;
xmlChar *encoding;
xmlCharEncoding enc = XML_CHAR_ENCODING_NONE;
xmlParserInputBufferPtr buffer;
if (!PyArg_ParseTuple(args, (char *)"Oz:xmlParserInputBufferCreate",
&file, &encoding))
return(NULL);
if ((encoding != NULL) && (encoding[0] != 0)) {
enc = xmlParseCharEncoding((const char *) encoding);
}
buffer = xmlParserInputBufferCreatePythonFile(file, enc);
if (buffer == NULL)
printf("libxml_xmlParserInputBufferCreate: buffer == NULL\n");
py_retval = libxml_xmlParserInputBufferPtrWrap(buffer);
return(py_retval);
}
/************************************************************************
* *
* Providing the resolver at the Python level *
* *
************************************************************************/
static xmlExternalEntityLoader defaultExternalEntityLoader = NULL;
static PyObject *pythonExternalEntityLoaderObjext;
static xmlParserInputPtr
pythonExternalEntityLoader(const char *URL, const char *ID,
xmlParserCtxtPtr ctxt) {
xmlParserInputPtr result = NULL;
if (pythonExternalEntityLoaderObjext != NULL) {
PyObject *ret;
PyObject *ctxtobj;
ctxtobj = libxml_xmlParserCtxtPtrWrap(ctxt);
#ifdef DEBUG_LOADER
printf("pythonExternalEntityLoader: ready to call\n");
#endif
ret = PyObject_CallFunction(pythonExternalEntityLoaderObjext,
(char *) "(ssO)", URL, ID, ctxtobj);
Py_XDECREF(ctxtobj);
#ifdef DEBUG_LOADER
printf("pythonExternalEntityLoader: result ");
PyObject_Print(ret, stdout, 0);
printf("\n");
#endif
if (ret != NULL) {
if (PyObject_HasAttrString(ret, (char *) "read")) {
xmlParserInputBufferPtr buf;
buf = xmlAllocParserInputBuffer(XML_CHAR_ENCODING_NONE);
if (buf != NULL) {
buf->context = ret;
buf->readcallback = xmlPythonFileReadRaw;
buf->closecallback = xmlPythonFileCloseRaw;
result = xmlNewIOInputStream(ctxt, buf,
XML_CHAR_ENCODING_NONE);
}
#if 0
} else {
if (URL != NULL)
printf("pythonExternalEntityLoader: can't read %s\n",
URL);
#endif
}
if (result == NULL) {
Py_DECREF(ret);
} else if (URL != NULL) {
result->filename = (char *) xmlStrdup((const xmlChar *)URL);
result->directory = xmlParserGetDirectory((const char *) URL);
}
}
}
if ((result == NULL) && (defaultExternalEntityLoader != NULL)) {
result = defaultExternalEntityLoader(URL, ID, ctxt);
}
return(result);
}
PyObject *
libxml_xmlSetEntityLoader(ATTRIBUTE_UNUSED PyObject *self, PyObject *args) {
PyObject *py_retval;
PyObject *loader;
if (!PyArg_ParseTuple(args, (char *)"O:libxml_xmlSetEntityLoader",
&loader))
return(NULL);
if (!PyCallable_Check(loader)) {
PyErr_SetString(PyExc_ValueError, "entity loader is not callable");
return(NULL);
}
#ifdef DEBUG_LOADER
printf("libxml_xmlSetEntityLoader\n");
#endif
if (defaultExternalEntityLoader == NULL)
defaultExternalEntityLoader = xmlGetExternalEntityLoader();
Py_XDECREF(pythonExternalEntityLoaderObjext);
pythonExternalEntityLoaderObjext = loader;
Py_XINCREF(pythonExternalEntityLoaderObjext);
xmlSetExternalEntityLoader(pythonExternalEntityLoader);
py_retval = PyLong_FromLong(0);
return(py_retval);
}
/************************************************************************
* *
* Input callback registration *
* *
************************************************************************/
static PyObject *pythonInputOpenCallbackObject;
static int pythonInputCallbackID = -1;
static int
pythonInputMatchCallback(ATTRIBUTE_UNUSED const char *URI)
{
/* Always return success, real decision whether URI is supported will be
* made in open callback. */
return 1;
}
static void *
pythonInputOpenCallback(const char *URI)
{
PyObject *ret;
ret = PyObject_CallFunction(pythonInputOpenCallbackObject,
(char *)"s", URI);
if (ret == Py_None) {
Py_DECREF(Py_None);
return NULL;
}
return ret;
}
PyObject *
libxml_xmlRegisterInputCallback(ATTRIBUTE_UNUSED PyObject *self,
PyObject *args) {
PyObject *cb;
if (!PyArg_ParseTuple(args,
(const char *)"O:libxml_xmlRegisterInputCallback", &cb))
return(NULL);
if (!PyCallable_Check(cb)) {
PyErr_SetString(PyExc_ValueError, "input callback is not callable");
return(NULL);
}
/* Python module registers a single callback and manages the list of
* all callbacks internally. This is necessitated by xmlInputMatchCallback
* API, which does not allow for passing of data objects to discriminate
* different Python methods. */
if (pythonInputCallbackID == -1) {
pythonInputCallbackID = xmlRegisterInputCallbacks(
pythonInputMatchCallback, pythonInputOpenCallback,
xmlPythonFileReadRaw, xmlPythonFileCloseRaw);
if (pythonInputCallbackID == -1)
return PyErr_NoMemory();
pythonInputOpenCallbackObject = cb;
Py_INCREF(pythonInputOpenCallbackObject);
}
Py_INCREF(Py_None);
return(Py_None);
}
PyObject *
libxml_xmlUnregisterInputCallback(ATTRIBUTE_UNUSED PyObject *self,
ATTRIBUTE_UNUSED PyObject *args) {
int ret;
ret = xmlPopInputCallbacks();
if (pythonInputCallbackID != -1) {
/* Assert that the right input callback was popped. libxml's API does not
* allow removal by ID, so all that could be done is an assert. */
if (pythonInputCallbackID == ret) {
pythonInputCallbackID = -1;
Py_DECREF(pythonInputOpenCallbackObject);
pythonInputOpenCallbackObject = NULL;
} else {
PyErr_SetString(PyExc_AssertionError, "popped non-python input callback");
return(NULL);
}
} else if (ret == -1) {
/* No more callbacks to pop */
PyErr_SetString(PyExc_IndexError, "no input callbacks to pop");
return(NULL);
}
Py_INCREF(Py_None);
return(Py_None);
}
/************************************************************************
* *
* Handling SAX/xmllib/sgmlop callback interfaces *
* *
************************************************************************/
static void
pythonStartElement(void *user_data, const xmlChar * name,
const xmlChar ** attrs)
{
int i;
PyObject *handler;
PyObject *dict;
PyObject *attrname;
PyObject *attrvalue;
PyObject *result = NULL;
int type = 0;
#ifdef DEBUG_SAX
printf("pythonStartElement(%s) called\n", name);
#endif
handler = (PyObject *) user_data;
if (PyObject_HasAttrString(handler, (char *) "startElement"))
type = 1;
else if (PyObject_HasAttrString(handler, (char *) "start"))
type = 2;
if (type != 0) {
/*
* the xmllib interface always generate a dictionnary,
* possibly empty
*/
if ((attrs == NULL) && (type == 1)) {
Py_XINCREF(Py_None);
dict = Py_None;
} else if (attrs == NULL) {
dict = PyDict_New();
} else {
dict = PyDict_New();
for (i = 0; attrs[i] != NULL; i++) {
attrname = PY_IMPORT_STRING((char *) attrs[i]);
i++;
if (attrs[i] != NULL) {
attrvalue = PY_IMPORT_STRING((char *) attrs[i]);
} else {
Py_XINCREF(Py_None);
attrvalue = Py_None;
}
PyDict_SetItem(dict, attrname, attrvalue);
Py_DECREF(attrname);
Py_DECREF(attrvalue);
}
}
if (type == 1)
result = PyObject_CallMethod(handler, (char *) "startElement",
(char *) "sO", name, dict);
else if (type == 2)
result = PyObject_CallMethod(handler, (char *) "start",
(char *) "sO", name, dict);
if (PyErr_Occurred())
PyErr_Print();
Py_XDECREF(dict);
Py_XDECREF(result);
}
}
static void
pythonStartDocument(void *user_data)
{
PyObject *handler;
PyObject *result;
#ifdef DEBUG_SAX
printf("pythonStartDocument() called\n");
#endif
handler = (PyObject *) user_data;
if (PyObject_HasAttrString(handler, (char *) "startDocument")) {
result =
PyObject_CallMethod(handler, (char *) "startDocument", NULL);
if (PyErr_Occurred())
PyErr_Print();
Py_XDECREF(result);
}
}
static void
pythonEndDocument(void *user_data)
{
PyObject *handler;
PyObject *result;
#ifdef DEBUG_SAX
printf("pythonEndDocument() called\n");
#endif
handler = (PyObject *) user_data;
if (PyObject_HasAttrString(handler, (char *) "endDocument")) {
result =
PyObject_CallMethod(handler, (char *) "endDocument", NULL);
if (PyErr_Occurred())
PyErr_Print();
Py_XDECREF(result);
}
/*
* The reference to the handler is released there
*/
Py_XDECREF(handler);
}
static void
pythonEndElement(void *user_data, const xmlChar * name)
{
PyObject *handler;
PyObject *result;
#ifdef DEBUG_SAX
printf("pythonEndElement(%s) called\n", name);
#endif
handler = (PyObject *) user_data;
if (PyObject_HasAttrString(handler, (char *) "endElement")) {
result = PyObject_CallMethod(handler, (char *) "endElement",