Properly call WSGI request handler when requests come in.
[bbaumbach/samba-autobuild/.git] / source4 / web_server / wsgi.c
1 /* 
2    Unix SMB/CIFS implementation.
3    Samba utility functions
4    Copyright © Jelmer Vernooij <jelmer@samba.org> 2008
5
6    Implementation of the WSGI interface described in PEP0333 
7    (http://www.python.org/dev/peps/pep-0333)
8    
9    This program is free software; you can redistribute it and/or modify
10    it under the terms of the GNU General Public License as published by
11    the Free Software Foundation; either version 3 of the License, or
12    (at your option) any later version.
13    
14    This program is distributed in the hope that it will be useful,
15    but WITHOUT ANY WARRANTY; without even the implied warranty of
16    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17    GNU General Public License for more details.
18    
19    You should have received a copy of the GNU General Public License
20    along with this program.  If not, see <http://www.gnu.org/licenses/>.
21 */
22
23 #include "includes.h"
24 #include "web_server/web_server.h"
25 #include "lib/util/dlinklist.h"
26 #include "lib/util/data_blob.h"
27 #include <Python.h>
28
29 typedef struct {
30         PyObject_HEAD
31         struct websrv_context *web;
32 } web_request_Object;
33
34 static PyObject *start_response(PyObject *self, PyObject *args, PyObject *kwargs)
35 {
36         PyObject *response_header, *exc_info = NULL;
37         char *status;
38         int i;
39         const char *kwnames[] = {
40                 "status", "response_header", "exc_info", NULL
41         };
42         web_request_Object *py_web = (web_request_Object *)self;
43         struct websrv_context *web = py_web->web;
44         struct http_header *headers = NULL;
45
46         if (!PyArg_ParseTupleAndKeywords(args, kwargs, "sO|O:start_response", discard_const_p(char *, kwnames), &status, &response_header, &exc_info)) {
47                 return NULL;
48         }
49
50         /* FIXME: exc_info */
51
52         if (!PyList_Check(response_header)) {
53                 PyErr_SetString(PyExc_TypeError, "response_header should be list");
54                 return NULL;
55         }
56
57         for (i = 0; i < PyList_Size(response_header); i++) {
58                 struct http_header *hdr = talloc_zero(web, struct http_header);
59                 PyObject *item = PyList_GetItem(response_header, i);
60                 PyObject *py_name, *py_value;
61
62                 if (!PyTuple_Check(item)) {
63                         PyErr_SetString(PyExc_TypeError, "Expected tuple");
64                         return NULL;
65                 }
66
67                 if (PyTuple_Size(item) != 2) {
68                         PyErr_SetString(PyExc_TypeError, "header tuple has invalid size, expected 2");
69                         return NULL;
70                 }
71
72                 py_name = PyTuple_GetItem(item, 0);
73
74                 if (!PyString_Check(py_name)) {
75                         PyErr_SetString(PyExc_TypeError, "header name should be string");
76                         return NULL;
77                 }
78
79                 py_value = PyTuple_GetItem(item, 1);
80                 if (!PyString_Check(py_value)) {
81                         PyErr_SetString(PyExc_TypeError, "header value should be string");
82                         return NULL;
83                 }
84
85                 hdr->name = talloc_strdup(hdr, PyString_AsString(py_name));
86                 hdr->value = talloc_strdup(hdr, PyString_AsString(py_value));
87                 DLIST_ADD(headers, hdr);
88         }
89
90         websrv_output_headers(web, status, headers);
91
92         return Py_None;
93 }
94
95 static PyMethodDef web_request_methods[] = {
96         { "start_response", (PyCFunction)start_response, METH_VARARGS|METH_KEYWORDS, NULL },
97         { NULL }
98 };
99
100
101 PyTypeObject web_request_Type = {
102         PyObject_HEAD_INIT(NULL) 0,
103         .tp_name = "wsgi.Request",
104         .tp_methods = web_request_methods,
105         .tp_basicsize = sizeof(web_request_Object),
106         .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
107 };
108
109 typedef struct {
110         PyObject_HEAD
111 } error_Stream_Object;
112
113 static PyObject *py_error_flush(PyObject *self, PyObject *args, PyObject *kwargs)
114 {
115         /* Nothing to do here */
116         return Py_None;
117 }
118
119 static PyObject *py_error_write(PyObject *self, PyObject *args, PyObject *kwargs)
120 {
121         const char *kwnames[] = { "str", NULL };
122         char *str = NULL;
123
124         if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s:write", discard_const_p(char *, kwnames), &str)) {
125                 return NULL;
126         }
127
128         DEBUG(0, ("WSGI App: %s", str));
129
130         return Py_None;
131 }
132
133 static PyObject *py_error_writelines(PyObject *self, PyObject *args, PyObject *kwargs)
134 {
135         const char *kwnames[] = { "seq", NULL };
136         PyObject *seq = NULL, *item;
137
138         if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O:writelines", discard_const_p(char *, kwnames), &seq)) {
139                 return NULL;
140         }
141         
142         while ((item = PyIter_Next(seq))) {
143                 char *str = PyString_AsString(item);
144
145                 DEBUG(0, ("WSGI App: %s", str));
146         }
147
148         return Py_None;
149 }
150
151 static PyMethodDef error_Stream_methods[] = {
152         { "flush", (PyCFunction)py_error_flush, METH_VARARGS|METH_KEYWORDS, NULL },
153         { "write", (PyCFunction)py_error_write, METH_VARARGS|METH_KEYWORDS, NULL },
154         { "writelines", (PyCFunction)py_error_writelines, METH_VARARGS|METH_KEYWORDS, NULL },
155         { NULL, NULL, 0, NULL }
156 };
157
158 PyTypeObject error_Stream_Type = {
159         PyObject_HEAD_INIT(NULL) 0,
160         .tp_name = "wsgi.ErrorStream",
161         .tp_basicsize = sizeof(error_Stream_Object),
162         .tp_methods = error_Stream_methods,
163         .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
164 };
165
166 typedef struct {
167         PyObject_HEAD
168 } input_Stream_Object;
169
170 static PyObject *py_input_read(PyObject *self, PyObject *args, PyObject *kwargs)
171 {
172         /* FIXME */
173         return NULL;
174 }
175
176 static PyObject *py_input_readline(PyObject *self, PyObject *args, PyObject *kwargs)
177 {
178         /* FIXME */
179         return NULL;
180 }
181
182 static PyObject *py_input_readlines(PyObject *self, PyObject *args, PyObject *kwargs)
183 {
184         /* FIXME */
185         return NULL;
186 }
187
188 static PyObject *py_input___iter__(PyObject *self, PyObject *args, PyObject *kwargs)
189 {
190         /* FIXME */
191         return NULL;
192 }
193
194 static PyMethodDef input_Stream_methods[] = {
195         { "read", (PyCFunction)py_input_read, METH_VARARGS|METH_KEYWORDS, NULL },
196         { "readline", (PyCFunction)py_input_readline, METH_VARARGS|METH_KEYWORDS, NULL },
197         { "readlines", (PyCFunction)py_input_readlines, METH_VARARGS|METH_KEYWORDS, NULL },
198         { "__iter__", (PyCFunction)py_input___iter__, METH_VARARGS|METH_KEYWORDS, NULL },
199         { NULL, NULL, 0, NULL }
200 };
201
202 PyTypeObject input_Stream_Type = {
203         PyObject_HEAD_INIT(NULL) 0,
204         .tp_name = "wsgi.InputStream",
205         .tp_basicsize = sizeof(input_Stream_Object),
206         .tp_methods = input_Stream_methods,
207         .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
208 };
209
210 static PyObject *Py_InputHttpStream(void *foo)
211 {
212         input_Stream_Object *ret = PyObject_New(input_Stream_Object, &input_Stream_Type);
213         return (PyObject *)ret;
214 }
215
216 static PyObject *Py_ErrorHttpStream(void)
217 {
218         error_Stream_Object *ret = PyObject_New(error_Stream_Object, &error_Stream_Type);
219         return (PyObject *)ret;
220 }
221
222 static PyObject *create_environ(bool tls, int content_length, const char *content_type, struct http_header *headers, const char *request_method)
223 {
224         PyObject *env;
225         PyObject *inputstream, *errorstream;
226         PyObject *py_scheme;
227         struct http_header *hdr;
228         
229         env = PyDict_New();
230         if (env == NULL) {
231                 return NULL;
232         }
233
234         inputstream = Py_InputHttpStream(NULL);
235         if (inputstream == NULL) {
236                 Py_DECREF(env);
237                 return NULL;
238         }
239
240         errorstream = Py_ErrorHttpStream();
241         if (errorstream == NULL) {
242                 Py_DECREF(env);
243                 Py_DECREF(inputstream);
244                 return NULL;
245         }
246
247         PyDict_SetItemString(env, "wsgi.input", inputstream);
248         PyDict_SetItemString(env, "wsgi.errors", errorstream);
249         PyDict_SetItemString(env, "wsgi.version", Py_BuildValue("(i,i)", 1, 0));
250         PyDict_SetItemString(env, "wsgi.multithread", Py_False);
251         PyDict_SetItemString(env, "wsgi.multiprocess", Py_True);
252         PyDict_SetItemString(env, "wsgi.run_once", Py_False);
253         PyDict_SetItemString(env, "SERVER_PROTOCOL", PyString_FromString("HTTP/1.0"));
254         if (content_type != NULL) {
255                 PyDict_SetItemString(env, "CONTENT_TYPE", PyString_FromString(content_type));
256         }
257         if (content_length > 0) {
258                 PyDict_SetItemString(env, "CONTENT_LENGTH", PyLong_FromLong(content_length));
259         }
260         PyDict_SetItemString(env, "REQUEST_METHOD", PyString_FromString(request_method));
261
262         /* FIXME: SCRIPT_NAME */
263         /* FIXME: PATH_INFO */
264         /* FIXME: QUERY_STRING */
265         /* FIXME: SERVER_NAME, SERVER_PORT */
266
267         for (hdr = headers; hdr; hdr = hdr->next) {
268                 char *name;
269                 asprintf(&name, "HTTP_%s", hdr->name);
270                 PyDict_SetItemString(env, name, PyString_FromString(hdr->value));
271                 free(name);
272         }
273
274         if (tls) {
275                 py_scheme = PyString_FromString("https");
276         } else {
277                 py_scheme = PyString_FromString("http");
278         }
279         PyDict_SetItemString(env, "wsgi.url_scheme", py_scheme);
280
281         return env;
282 }
283
284 static void wsgi_process_http_input(struct web_server_data *wdata,
285                                     struct websrv_context *web)
286 {
287         PyObject *py_environ, *result, *item, *iter;
288         PyObject *request_handler = wdata->private;
289
290         web_request_Object *py_web = PyObject_New(web_request_Object, &web_request_Type);
291         py_web->web = web;
292
293         py_environ = create_environ(false /* FIXME: Figure out whether we're using tls */, 
294                                     web->input.content_length, 
295                                     web->input.content_type, 
296                                     web->input.headers, 
297                                     web->input.post_request?"POST":"GET");
298         if (py_environ == NULL) {
299                 DEBUG(0, ("Unable to create WSGI environment object\n"));
300                 return;
301         }
302
303         result = PyObject_CallMethod(request_handler, discard_const_p(char, "__call__"), discard_const_p(char, "OO"),
304                                        py_environ, PyObject_GetAttrString((PyObject *)py_web, "start_response"));
305
306         if (result == NULL) {
307                 DEBUG(0, ("error while running WSGI code\n"));
308                 return;
309         }
310
311         iter = PyObject_GetIter(result);
312         Py_DECREF(result);
313
314         /* Now, iter over all the data returned */
315
316         while ((item = PyIter_Next(iter))) {
317                 data_blob_append(web, &web->output.content, 
318                                  PyString_AsString(item), PyString_Size(item));
319                 Py_DECREF(item);
320         }
321
322         Py_DECREF(iter);
323 }
324
325 bool wsgi_initialize(struct web_server_data *wdata)
326 {
327         PyObject *py_swat;
328
329         Py_Initialize();
330
331         if (PyType_Ready(&web_request_Type) < 0)
332                 return false;
333
334         if (PyType_Ready(&input_Stream_Type) < 0)
335                 return false;
336
337         if (PyType_Ready(&error_Stream_Type) < 0)
338                 return false;
339
340         wdata->http_process_input = wsgi_process_http_input;
341         py_swat = PyImport_Import(PyString_FromString("swat"));
342         if (py_swat == NULL) {
343                 DEBUG(0, ("Unable to find SWAT\n"));
344                 return false;
345         }
346         wdata->private = py_swat;
347         return true;
348 }