summaryrefslogtreecommitdiff
path: root/python/libxslt.c
blob: d9bc5b8c6af6b2e654153aefc2e5d6e959365f5a (plain)
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
/*
 * libxslt.c: this modules implements the main part of the glue of the
 *           libxslt 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.
 *
 * See Copyright for the status of this software.
 *
 * daniel@veillard.com
 */
#include <Python.h>
#include <libxml/xmlmemory.h>
#include <libxml/tree.h>
#include <libxml/xpath.h>
#include "libxslt_wrap.h"
#include "libxslt-py.h"

/* #define DEBUG */
/* #define DEBUG_XPATH */
/* #define DEBUG_ERROR */
/* #define DEBUG_MEMORY */

/************************************************************************
 *									*
 *			Per type specific glue				*
 *									*
 ************************************************************************/

PyObject *
libxslt_xsltStylesheetPtrWrap(xsltStylesheetPtr style) {
    PyObject *ret;

#ifdef DEBUG
    printf("libxslt_xsltStylesheetPtrWrap: style = %p\n", style);
#endif
    if (style == NULL) {
	Py_INCREF(Py_None);
	return(Py_None);
    }
    ret = PyCObject_FromVoidPtrAndDesc((void *) style, "xsltStylesheetPtr", NULL);
    return(ret);
}

PyObject *
libxslt_xsltTransformContextPtrWrap(xsltTransformContextPtr ctxt) {
    PyObject *ret;

#ifdef DEBUG
    printf("libxslt_xsltTransformContextPtrWrap: ctxt = %p\n", ctxt);
#endif
    if (ctxt == NULL) {
	Py_INCREF(Py_None);
	return(Py_None);
    }
    ret = PyCObject_FromVoidPtrAndDesc((void *) ctxt, "xsltTransformContextPtr", NULL);
    return(ret);
}

/************************************************************************
 *									*
 *		Memory debug interface					*
 *									*
 ************************************************************************/

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);

static int libxsltMemoryDebugActivated = 0;
static long libxsltMemoryAllocatedBase = 0;

static int libxsltMemoryDebug = 0;
static xmlFreeFunc freeFunc = NULL;
static xmlMallocFunc mallocFunc = NULL;
static xmlReallocFunc reallocFunc = NULL;
static xmlStrdupFunc strdupFunc = NULL;

PyObject *
libxslt_xmlDebugMemory(PyObject *self, PyObject *args) {
    int activate;
    PyObject *py_retval;
    long ret;

    if (!PyArg_ParseTuple(args, "i:xmlDebugMemory", &activate))
        return(NULL);

#ifdef DEBUG_MEMORY
    printf("libxslt_xmlDebugMemory(%d) called\n", activate);
#endif

    if (activate != 0) {
	if (libxsltMemoryDebug == 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)) {
		libxsltMemoryAllocatedBase = xmlMemUsed();
	    } else {
		ret = (long) xmlMemSetup(xmlMemFree, xmlMemMalloc,
			                 xmlMemRealloc, xmlMemoryStrdup);
		if (ret < 0)
		    goto error;
		libxsltMemoryAllocatedBase = xmlMemUsed();
	    }
	    xmlInitParser();
	    ret = 0;
	} else if (libxsltMemoryDebugActivated == 0) {
	    libxsltMemoryAllocatedBase = xmlMemUsed();
	    ret = 0;
	} else {
	    ret = xmlMemUsed() - libxsltMemoryAllocatedBase;
	}
	libxsltMemoryDebug = 1;
	libxsltMemoryDebugActivated = 1;
    } else {
	if (libxsltMemoryDebugActivated == 1)
	    ret = xmlMemUsed() - libxsltMemoryAllocatedBase;
	else
	    ret = 0;
	libxsltMemoryDebugActivated = 0;
    }
error:
    py_retval = libxml_longWrap(ret);
    return(py_retval);
}

PyObject *
libxslt_xmlDumpMemory(PyObject *self, PyObject *args) {

    if (libxsltMemoryDebug != 0)
	xmlMemoryDump();
    Py_INCREF(Py_None);
    return(Py_None);
}

/************************************************************************
 *									*
 *			Extending the API				*
 *									*
 ************************************************************************/

static xmlHashTablePtr libxslt_extModuleFunctions = NULL;

static void
libxslt_xmlXPathFuncCallback(xmlXPathParserContextPtr ctxt, int nargs) {
    PyObject *list, *cur, *result;
    xmlXPathObjectPtr obj;
    xmlXPathContextPtr rctxt;
    PyObject *current_function = NULL;
    const xmlChar *name;
    const xmlChar *ns_uri;
    int i;

    if (ctxt == NULL)
	return;
    rctxt = ctxt->context;
    if (rctxt == NULL)
	return;
    name = rctxt->function;
    ns_uri = rctxt->functionURI;
#ifdef DEBUG_XPATH
    printf("libxslt_xmlXPathFuncCallback called name %s URI %s\n", name, ns_uri);
#endif

    /*
     * Find the function, it should be there it was there at lookup
     */
    current_function = xmlHashLookup2(libxslt_extModuleFunctions,
	                              name, ns_uri);
    if (current_function == NULL) {
	printf("libxslt_xmlXPathFuncCallback: internal error %s not found !\n",
	       name);
	return;
    }

    list = PyTuple_New(nargs + 1);
    PyTuple_SetItem(list, 0, libxml_xmlXPathParserContextPtrWrap(ctxt));
    for (i = 0;i < nargs;i++) {
	obj = valuePop(ctxt);
	cur = libxml_xmlXPathObjectPtrWrap(obj);
	PyTuple_SetItem(list, i + 1, cur);
    }
    result = PyEval_CallObject(current_function, list);
    Py_DECREF(list);

    obj = libxml_xmlXPathObjectPtrConvert(result);
    valuePush(ctxt, obj);
}

PyObject *
libxslt_xsltRegisterExtModuleFunction(PyObject *self, PyObject *args) {
    PyObject *py_retval;
    int ret = 0;
    xmlChar *name;
    xmlChar *ns_uri;
    PyObject *pyobj_f;

    if (!PyArg_ParseTuple(args, "szO:registerXPathFunction",
		          &name, &ns_uri, &pyobj_f))
        return(NULL);

    if ((name == NULL) || (pyobj_f == NULL)) {
	py_retval = libxml_intWrap(-1);
	return(py_retval);
    }

#ifdef DEBUG_XPATH
    printf("libxslt_xsltRegisterExtModuleFunction(%s, %s) called\n",
	   name, ns_uri);
#endif

    if (libxslt_extModuleFunctions == NULL)
	libxslt_extModuleFunctions = xmlHashCreate(10);
    if (libxslt_extModuleFunctions == NULL) {
	py_retval = libxml_intWrap(-1);
	return(py_retval);
    }
    ret = xmlHashAddEntry2(libxslt_extModuleFunctions, name, ns_uri, pyobj_f);
    if (ret != 0) {
	py_retval = libxml_intWrap(-1);
	return(py_retval);
    }
    Py_XINCREF(pyobj_f);

    ret = xsltRegisterExtModuleFunction(name, ns_uri, 
	                                     libxslt_xmlXPathFuncCallback);
    py_retval = libxml_intWrap((int) ret);
    return(py_retval);
}

void
deallocateCallback(void *payload, xmlChar *name) {
    PyObject *function = (PyObject *) payload;

#ifdef DEBUG_XPATH
    printf("deallocateCallback(%s) called\n", name);
#endif

    Py_XDECREF(function);
}

/************************************************************************
 *									*
 *			Some customized front-ends			*
 *									*
 ************************************************************************/

PyObject *
libxslt_xsltApplyStylesheet(PyObject *self, PyObject *args) {
    PyObject *py_retval;
    xmlDocPtr c_retval;
    xsltStylesheetPtr style;
    PyObject *pyobj_style;
    xmlDocPtr doc;
    PyObject *pyobj_doc;
    PyObject *pyobj_params;
    const char **params = NULL;
    int len = 0, i = 0, j;
    PyObject *name;
    PyObject *value;

    if (!PyArg_ParseTuple(args, "OOO:xsltApplyStylesheet", &pyobj_style, &pyobj_doc, &pyobj_params))
        return(NULL);

    if (pyobj_params != Py_None) {
	if (PyDict_Check(pyobj_params)) {
	    len = PyDict_Size(pyobj_params);
	    if (len > 0) {
		params = (const char **) xmlMalloc((len + 1) * 2 *
			                           sizeof(char *));
		if (params == NULL) {
		    printf("libxslt_xsltApplyStylesheet: out of memory\n");
		    Py_INCREF(Py_None);
		    return(Py_None);
		}
		j = 0;
		while (PyDict_Next(pyobj_params, &i, &name, &value)) {
		    const char *tmp;
		    int size;

		    tmp = PyString_AS_STRING(name);
		    size = PyString_GET_SIZE(name);
		    params[j * 2] = xmlCharStrndup(tmp, size);
		    if (PyString_Check(value)) {
			tmp = PyString_AS_STRING(value);
			size = PyString_GET_SIZE(value);
			params[(j * 2) + 1] = xmlCharStrndup(tmp, size);
		    } else {
			params[(j * 2) + 1] = NULL;
		    }
		    j = j + 1;
		}
		params[j * 2] = NULL;
		params[(j * 2) + 1] = NULL;
	    }
	} else {
	    printf("libxslt_xsltApplyStylesheet: parameters not a dict\n");
	    Py_INCREF(Py_None);
	    return(Py_None);
	}
    }
    style = (xsltStylesheetPtr) Pystylesheet_Get(pyobj_style);
    doc = (xmlDocPtr) PyxmlNode_Get(pyobj_doc);

    c_retval = xsltApplyStylesheet(style, doc, params);
    py_retval = libxml_xmlDocPtrWrap((xmlDocPtr) c_retval);
    if (params != NULL) {
	if (len > 0) {
	    for (i = 0;i < 2 * len;i++) {
		if (params[i] != NULL)
		    xmlFree((char *)params[i]);
	    }
	    xmlFree(params);
	}
    }
    return(py_retval);
}

/************************************************************************
 *									*
 *			Integrated cleanup				*
 *									*
 ************************************************************************/

PyObject *
libxslt_xsltCleanup(PyObject *self, PyObject *args) {

    if (libxslt_extModuleFunctions != NULL) {
	xmlHashFree(libxslt_extModuleFunctions, deallocateCallback);
    }
    xsltCleanupGlobals();
    xmlCleanupParser();
    Py_INCREF(Py_None);
    return(Py_None);
}

/************************************************************************
 *									*
 *			The registration stuff				*
 *									*
 ************************************************************************/
static PyMethodDef libxsltMethods[] = {
#include "libxslt-export.c"
};

void init_libxslt(void) {
    PyObject *m;
    m = Py_InitModule("_libxslt", libxsltMethods);
    /* libxslt_xmlErrorInitialize(); */
    /*
     * Specific XSLT initializations
     */
    /* xmlInitParser(); */
    xmlInitMemory();
    /* LIBXML_TEST_VERSION */
    xmlLoadExtDtdDefaultValue = XML_DETECT_IDS | XML_COMPLETE_ATTRS;
    /* xmlDefaultSAXHandlerInit(); */
    xmlDefaultSAXHandler.cdataBlock = NULL;
}