]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - pythonmod/pythonmod.c
import unbound 1.5.4
[FreeBSD/FreeBSD.git] / pythonmod / pythonmod.c
1 /*
2  * pythonmod.c: unbound module C wrapper
3  * 
4  * Copyright (c) 2009, Zdenek Vasicek (vasicek AT fit.vutbr.cz)
5  *                     Marek Vavrusa  (xvavru00 AT stud.fit.vutbr.cz)
6  *
7  * This software is open source.
8  * 
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  * 
13  *    * Redistributions of source code must retain the above copyright notice,
14  *      this list of conditions and the following disclaimer.
15  * 
16  *    * Redistributions in binary form must reproduce the above copyright notice,
17  *      this list of conditions and the following disclaimer in the documentation
18  *      and/or other materials provided with the distribution.
19  * 
20  *    * Neither the name of the organization nor the names of its
21  *      contributors may be used to endorse or promote products derived from this
22  *      software without specific prior written permission.
23  *
24  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
25  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
26  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
27  * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE
28  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
29  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
30  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
31  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
32  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
33  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
34  * POSSIBILITY OF SUCH DAMAGE.
35  */
36 /**
37  * \file
38  * Python module for unbound.  Calls python script.
39  */
40
41 /* ignore the varargs unused warning from SWIGs internal vararg support */
42 #ifdef __GNUC__
43 #pragma GCC diagnostic ignored "-Wunused-parameter"
44 #pragma GCC diagnostic ignored "-Wunused-but-set-variable"
45 #endif
46
47 #include "config.h"
48 #include "sldns/sbuffer.h"
49
50 #undef _POSIX_C_SOURCE
51 #undef _XOPEN_SOURCE
52 #include <Python.h>
53
54 #include "pythonmod/pythonmod.h"
55 #include "util/module.h"
56 #include "util/config_file.h"
57 #include "pythonmod_utils.h"
58
59 #ifdef S_SPLINT_S
60 typedef struct PyObject PyObject;
61 typedef struct PyThreadState PyThreadState;
62 typedef void* PyGILState_STATE;
63 #endif
64
65 /**
66  * Global state for the module. 
67  */
68 struct pythonmod_env {
69
70         /** Python script filename. */
71         const char* fname;
72
73         /** Python main thread */
74         PyThreadState* mainthr;
75         /** Python module. */
76         PyObject* module;
77
78         /** Module init function */
79         PyObject* func_init;
80         /** Module deinit function */
81         PyObject* func_deinit;
82         /** Module operate function */
83         PyObject* func_operate;
84         /** Module super_inform function */
85         PyObject* func_inform;
86
87         /** Python dictionary. */
88         PyObject* dict;
89
90         /** Module data. */
91         PyObject* data;
92
93         /** Module qstate. */
94         struct module_qstate* qstate;
95 };
96
97 /**
98  * Per query state for the iterator module.
99  */
100 struct pythonmod_qstate {
101
102         /** Module per query data. */
103         PyObject* data;
104 };
105
106 /* Generated */
107 #ifndef S_SPLINT_S
108 #include "pythonmod/interface.h"
109 #endif
110
111 int pythonmod_init(struct module_env* env, int id)
112 {
113    /* Initialize module */
114    FILE* script_py = NULL;
115    PyObject* py_cfg, *res;
116    PyGILState_STATE gil;
117    struct pythonmod_env* pe = (struct pythonmod_env*)calloc(1, sizeof(struct pythonmod_env));
118    if (!pe) 
119    {
120       log_err("pythonmod: malloc failure");
121       return 0;
122    }
123
124    env->modinfo[id] = (void*) pe;
125
126    /* Initialize module */
127    pe->fname = env->cfg->python_script;
128    if(pe->fname==NULL || pe->fname[0]==0) {
129       log_err("pythonmod: no script given.");
130       return 0;
131    }
132
133    /* Initialize Python libraries */
134    if (!Py_IsInitialized()) 
135    {
136 #if PY_MAJOR_VERSION >= 3
137       wchar_t progname[8];
138       mbstowcs(progname, "unbound", 8);
139 #else
140       char *progname = "unbound";
141 #endif
142       Py_SetProgramName(progname);
143       Py_NoSiteFlag = 1;
144       Py_Initialize();
145       PyEval_InitThreads();
146       SWIG_init();
147       pe->mainthr = PyEval_SaveThread();
148    }
149
150    gil = PyGILState_Ensure();
151
152    /* Initialize Python */
153    PyRun_SimpleString("import sys \n");
154    PyRun_SimpleString("sys.path.append('.') \n");
155    if(env->cfg->directory && env->cfg->directory[0]) {
156         char wdir[1524];
157         snprintf(wdir, sizeof(wdir), "sys.path.append('%s') \n",
158                 env->cfg->directory);
159         PyRun_SimpleString(wdir);
160    }
161    PyRun_SimpleString("sys.path.append('"RUN_DIR"') \n");
162    PyRun_SimpleString("sys.path.append('"SHARE_DIR"') \n");
163    PyRun_SimpleString("import distutils.sysconfig \n");
164    PyRun_SimpleString("sys.path.append(distutils.sysconfig.get_python_lib(1,0)) \n");
165    if (PyRun_SimpleString("from unboundmodule import *\n") < 0)
166    {
167       log_err("pythonmod: cannot initialize core module: unboundmodule.py"); 
168       PyGILState_Release(gil);
169       return 0;
170    }
171
172    /* Check Python file load */
173    if ((script_py = fopen(pe->fname, "r")) == NULL) 
174    {
175       log_err("pythonmod: can't open file %s for reading", pe->fname);
176       PyGILState_Release(gil);
177       return 0;
178    }
179
180    /* Load file */
181    pe->module = PyImport_AddModule("__main__");
182    pe->dict = PyModule_GetDict(pe->module);
183    pe->data = Py_None;
184    Py_INCREF(pe->data);
185    PyModule_AddObject(pe->module, "mod_env", pe->data);
186
187    /* TODO: deallocation of pe->... if an error occurs */
188   
189    if (PyRun_SimpleFile(script_py, pe->fname) < 0) 
190    {
191       log_err("pythonmod: can't parse Python script %s", pe->fname);
192       PyGILState_Release(gil);
193       return 0;
194    }
195
196    fclose(script_py);
197
198    if ((pe->func_init = PyDict_GetItemString(pe->dict, "init")) == NULL) 
199    {
200       log_err("pythonmod: function init is missing in %s", pe->fname);
201       PyGILState_Release(gil);
202       return 0;
203    }
204    if ((pe->func_deinit = PyDict_GetItemString(pe->dict, "deinit")) == NULL) 
205    {
206       log_err("pythonmod: function deinit is missing in %s", pe->fname);
207       PyGILState_Release(gil);
208       return 0;
209    }
210    if ((pe->func_operate = PyDict_GetItemString(pe->dict, "operate")) == NULL) 
211    {
212       log_err("pythonmod: function operate is missing in %s", pe->fname);
213       PyGILState_Release(gil);
214       return 0;
215    }
216    if ((pe->func_inform = PyDict_GetItemString(pe->dict, "inform_super")) == NULL) 
217    {
218       log_err("pythonmod: function inform_super is missing in %s", pe->fname);
219       PyGILState_Release(gil);
220       return 0;
221    }
222
223    py_cfg = SWIG_NewPointerObj((void*) env->cfg, SWIGTYPE_p_config_file, 0);
224    res = PyObject_CallFunction(pe->func_init, "iO", id, py_cfg);
225    if (PyErr_Occurred()) 
226    {
227       log_err("pythonmod: Exception occurred in function init");
228       PyErr_Print();
229    }
230
231    Py_XDECREF(res);
232    Py_XDECREF(py_cfg);
233    PyGILState_Release(gil);
234
235    return 1;
236 }
237
238 void pythonmod_deinit(struct module_env* env, int id)
239 {
240    struct pythonmod_env* pe = env->modinfo[id];
241    if(pe == NULL)
242       return;
243
244    /* Free Python resources */
245    if(pe->module != NULL)
246    {
247       PyObject* res;
248       PyGILState_STATE gil = PyGILState_Ensure();
249
250       /* Deinit module */
251       res = PyObject_CallFunction(pe->func_deinit, "i", id);
252       if (PyErr_Occurred()) {
253          log_err("pythonmod: Exception occurred in function deinit");
254          PyErr_Print();
255       }
256       /* Free result if any */
257       Py_XDECREF(res);
258       /* Free shared data if any */
259       Py_XDECREF(pe->data);
260       PyGILState_Release(gil);
261
262       PyEval_RestoreThread(pe->mainthr);
263       Py_Finalize();
264       pe->mainthr = NULL;
265    }
266    pe->fname = NULL;
267    free(pe);
268
269    /* Module is deallocated in Python */
270    env->modinfo[id] = NULL;
271 }
272
273 void pythonmod_inform_super(struct module_qstate* qstate, int id, struct module_qstate* super)
274 {
275    struct pythonmod_env* pe = (struct pythonmod_env*)qstate->env->modinfo[id];
276    struct pythonmod_qstate* pq = (struct pythonmod_qstate*)qstate->minfo[id];
277    PyObject* py_qstate, *py_sqstate, *res;
278    PyGILState_STATE gil = PyGILState_Ensure();
279
280    log_query_info(VERB_ALGO, "pythonmod: inform_super, sub is", &qstate->qinfo);
281    log_query_info(VERB_ALGO, "super is", &super->qinfo);
282
283    py_qstate = SWIG_NewPointerObj((void*) qstate, SWIGTYPE_p_module_qstate, 0);
284    py_sqstate = SWIG_NewPointerObj((void*) super, SWIGTYPE_p_module_qstate, 0);
285
286    res = PyObject_CallFunction(pe->func_inform, "iOOO", id, py_qstate, 
287         py_sqstate, pq->data);
288
289    if (PyErr_Occurred()) 
290    {
291       log_err("pythonmod: Exception occurred in function inform_super");
292       PyErr_Print();
293       qstate->ext_state[id] = module_error;
294    } 
295    else if ((res == NULL)  || (!PyObject_IsTrue(res))) 
296    {
297       log_err("pythonmod: python returned bad code in inform_super");
298       qstate->ext_state[id] = module_error;
299    } 
300
301    Py_XDECREF(res);
302    Py_XDECREF(py_sqstate);
303    Py_XDECREF(py_qstate);
304
305    PyGILState_Release(gil);
306 }
307
308 void pythonmod_operate(struct module_qstate* qstate, enum module_ev event, 
309         int id, struct outbound_entry* ATTR_UNUSED(outbound))
310 {
311    struct pythonmod_env* pe = (struct pythonmod_env*)qstate->env->modinfo[id];
312    struct pythonmod_qstate* pq = (struct pythonmod_qstate*)qstate->minfo[id];
313    PyObject* py_qstate, *res;
314    PyGILState_STATE gil = PyGILState_Ensure();
315
316    if ( pq == NULL)
317    { 
318       /* create qstate */
319       pq = qstate->minfo[id] = malloc(sizeof(struct pythonmod_qstate));
320       
321       /* Initialize per query data */
322       pq->data = Py_None;
323       Py_INCREF(pq->data);
324    }
325
326    /* Call operate */
327    py_qstate = SWIG_NewPointerObj((void*) qstate, SWIGTYPE_p_module_qstate, 0);
328    res = PyObject_CallFunction(pe->func_operate, "iiOO", id, (int) event, 
329         py_qstate, pq->data);
330    if (PyErr_Occurred()) 
331    {
332       log_err("pythonmod: Exception occurred in function operate, event: %s", strmodulevent(event));
333       PyErr_Print();
334       qstate->ext_state[id] = module_error;
335    } 
336    else if ((res == NULL)  || (!PyObject_IsTrue(res))) 
337    {
338       log_err("pythonmod: python returned bad code, event: %s", strmodulevent(event));
339       qstate->ext_state[id] = module_error;
340    } 
341    Py_XDECREF(res);
342    Py_XDECREF(py_qstate);
343
344    PyGILState_Release(gil);
345 }
346
347 void pythonmod_clear(struct module_qstate* qstate, int id)
348 {
349    struct pythonmod_qstate* pq;
350    if (qstate == NULL)
351       return;
352
353    pq = (struct pythonmod_qstate*)qstate->minfo[id];
354    verbose(VERB_ALGO, "pythonmod: clear, id: %d, pq:%lX", id, 
355         (unsigned long int)pq);
356    if(pq != NULL)
357    {
358       PyGILState_STATE gil = PyGILState_Ensure();
359       Py_DECREF(pq->data);
360       PyGILState_Release(gil);
361       /* Free qstate */
362       free(pq);
363    }
364
365    qstate->minfo[id] = NULL;
366 }
367
368 size_t pythonmod_get_mem(struct module_env* env, int id)
369 {
370    struct pythonmod_env* pe = (struct pythonmod_env*)env->modinfo[id];
371    verbose(VERB_ALGO, "pythonmod: get_mem, id: %d, pe:%lX", id, 
372         (unsigned long int)pe);
373    if(!pe)
374       return 0;
375    return sizeof(*pe);
376 }
377
378 /**
379  * The module function block 
380  */
381 static struct module_func_block pythonmod_block = {
382    "python",
383    &pythonmod_init, &pythonmod_deinit, &pythonmod_operate, &pythonmod_inform_super, 
384    &pythonmod_clear, &pythonmod_get_mem
385 };
386
387 struct module_func_block* pythonmod_get_funcblock(void)
388 {
389    return &pythonmod_block;
390 }