s4:web_server/wsgi.c - fix a counter type
[sfrench/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 <Python.h>
24 #include "includes.h"
25 #include "web_server/web_server.h"
26 #include "../lib/util/dlinklist.h"
27 #include "../lib/util/data_blob.h"
28 #include "lib/tls/tls.h"
29 #include "lib/tsocket/tsocket.h"
30
31 /* There's no Py_ssize_t in 2.4, apparently */
32 #if PY_MAJOR_VERSION == 2 && PY_MINOR_VERSION < 5
33 typedef int Py_ssize_t;
34 typedef inquiry lenfunc;
35 typedef intargfunc ssizeargfunc;
36 #endif
37
38 #ifndef Py_RETURN_NONE
39 #define Py_RETURN_NONE return Py_INCREF(Py_None), Py_None
40 #endif
41
42 typedef struct {
43         PyObject_HEAD
44         struct websrv_context *web;
45 } web_request_Object;
46
47 static PyObject *start_response(PyObject *self, PyObject *args, PyObject *kwargs)
48 {
49         PyObject *response_header, *exc_info = NULL;
50         char *status;
51         Py_ssize_t i;
52         const char *kwnames[] = {
53                 "status", "response_header", "exc_info", NULL
54         };
55         web_request_Object *py_web = (web_request_Object *)self;
56         struct websrv_context *web = py_web->web;
57         struct http_header *headers = NULL;
58
59         if (!PyArg_ParseTupleAndKeywords(args, kwargs, "sO|O:start_response", discard_const_p(char *, kwnames), &status, &response_header, &exc_info)) {
60                 return NULL;
61         }
62
63         /* FIXME: exc_info */
64
65         if (!PyList_Check(response_header)) {
66                 PyErr_SetString(PyExc_TypeError, "response_header should be list");
67                 return NULL;
68         }
69
70         for (i = 0; i < PyList_Size(response_header); i++) {
71                 struct http_header *hdr = talloc_zero(web, struct http_header);
72                 PyObject *item = PyList_GetItem(response_header, i);
73                 PyObject *py_name, *py_value;
74
75                 if (!PyTuple_Check(item)) {
76                         PyErr_SetString(PyExc_TypeError, "Expected tuple");
77                         return NULL;
78                 }
79
80                 if (PyTuple_Size(item) != 2) {
81                         PyErr_SetString(PyExc_TypeError, "header tuple has invalid size, expected 2");
82                         return NULL;
83                 }
84
85                 py_name = PyTuple_GetItem(item, 0);
86
87                 if (!PyString_Check(py_name)) {
88                         PyErr_SetString(PyExc_TypeError, "header name should be string");
89                         return NULL;
90                 }
91
92                 py_value = PyTuple_GetItem(item, 1);
93                 if (!PyString_Check(py_value)) {
94                         PyErr_SetString(PyExc_TypeError, "header value should be string");
95                         return NULL;
96                 }
97
98                 hdr->name = talloc_strdup(hdr, PyString_AsString(py_name));
99                 hdr->value = talloc_strdup(hdr, PyString_AsString(py_value));
100                 DLIST_ADD(headers, hdr);
101         }
102
103         websrv_output_headers(web, status, headers);
104
105         Py_RETURN_NONE;
106 }
107
108 static PyMethodDef web_request_methods[] = {
109         { "start_response", (PyCFunction)start_response, METH_VARARGS|METH_KEYWORDS, NULL },
110         { NULL }
111 };
112
113
114 PyTypeObject web_request_Type = {
115         PyObject_HEAD_INIT(NULL) 0,
116         .tp_name = "wsgi.Request",
117         .tp_methods = web_request_methods,
118         .tp_basicsize = sizeof(web_request_Object),
119         .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
120 };
121
122 typedef struct {
123         PyObject_HEAD
124 } error_Stream_Object;
125
126 static PyObject *py_error_flush(PyObject *self, PyObject *args, PyObject *kwargs)
127 {
128         /* Nothing to do here */
129         Py_RETURN_NONE;
130 }
131
132 static PyObject *py_error_write(PyObject *self, PyObject *args, PyObject *kwargs)
133 {
134         const char *kwnames[] = { "str", NULL };
135         char *str = NULL;
136
137         if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s:write", discard_const_p(char *, kwnames), &str)) {
138                 return NULL;
139         }
140
141         DEBUG(0, ("WSGI App: %s", str));
142
143         Py_RETURN_NONE;
144 }
145
146 static PyObject *py_error_writelines(PyObject *self, PyObject *args, PyObject *kwargs)
147 {
148         const char *kwnames[] = { "seq", NULL };
149         PyObject *seq = NULL, *item;
150
151         if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O:writelines", discard_const_p(char *, kwnames), &seq)) {
152                 return NULL;
153         }
154         
155         while ((item = PyIter_Next(seq))) {
156                 char *str = PyString_AsString(item);
157
158                 DEBUG(0, ("WSGI App: %s", str));
159         }
160
161         Py_RETURN_NONE;
162 }
163
164 static PyMethodDef error_Stream_methods[] = {
165         { "flush", (PyCFunction)py_error_flush, METH_VARARGS|METH_KEYWORDS, NULL },
166         { "write", (PyCFunction)py_error_write, METH_VARARGS|METH_KEYWORDS, NULL },
167         { "writelines", (PyCFunction)py_error_writelines, METH_VARARGS|METH_KEYWORDS, NULL },
168         { NULL, NULL, 0, NULL }
169 };
170
171 PyTypeObject error_Stream_Type = {
172         PyObject_HEAD_INIT(NULL) 0,
173         .tp_name = "wsgi.ErrorStream",
174         .tp_basicsize = sizeof(error_Stream_Object),
175         .tp_methods = error_Stream_methods,
176         .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
177 };
178
179 typedef struct {
180         PyObject_HEAD
181         struct websrv_context *web;
182         size_t offset;
183 } input_Stream_Object;
184
185 static PyObject *py_input_read(PyObject *_self, PyObject *args, PyObject *kwargs)
186 {
187         const char *kwnames[] = { "size", NULL };
188         PyObject *ret;
189         input_Stream_Object *self = (input_Stream_Object *)_self;
190         int size = -1;
191
192         if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|i", discard_const_p(char *, kwnames), &size))
193                 return NULL;
194         
195         /* Don't read beyond buffer boundaries */
196         if (size == -1)
197                 size = self->web->input.partial.length-self->offset;
198         else
199                 size = MIN(size, self->web->input.partial.length-self->offset);
200
201         ret = PyString_FromStringAndSize((char *)self->web->input.partial.data+self->offset, size);
202         self->offset += size;
203
204         return ret;
205 }
206
207 static PyObject *py_input_readline(PyObject *_self)
208 {
209         /* FIXME */
210         PyErr_SetString(PyExc_NotImplementedError, 
211                         "readline() not yet implemented");
212         return NULL;
213 }
214
215 static PyObject *py_input_readlines(PyObject *_self, PyObject *args, PyObject *kwargs)
216 {
217         const char *kwnames[] = { "hint", NULL };
218         int hint;
219
220         if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|i", discard_const_p(char *, kwnames), &hint))
221                 return NULL;
222         
223         /* FIXME */
224         PyErr_SetString(PyExc_NotImplementedError, 
225                         "readlines() not yet implemented");
226         return NULL;
227 }
228
229 static PyObject *py_input___iter__(PyObject *_self)
230 {
231         /* FIXME */
232         PyErr_SetString(PyExc_NotImplementedError, 
233                         "__iter__() not yet implemented");
234         return NULL;
235 }
236
237 static PyMethodDef input_Stream_methods[] = {
238         { "read", (PyCFunction)py_input_read, METH_VARARGS|METH_KEYWORDS, NULL },
239         { "readline", (PyCFunction)py_input_readline, METH_NOARGS, NULL },
240         { "readlines", (PyCFunction)py_input_readlines, METH_VARARGS|METH_KEYWORDS, NULL },
241         { "__iter__", (PyCFunction)py_input___iter__, METH_NOARGS, NULL },
242         { NULL, NULL, 0, NULL }
243 };
244
245 PyTypeObject input_Stream_Type = {
246         PyObject_HEAD_INIT(NULL) 0,
247         .tp_name = "wsgi.InputStream",
248         .tp_basicsize = sizeof(input_Stream_Object),
249         .tp_methods = input_Stream_methods,
250         .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
251 };
252
253 static PyObject *Py_InputHttpStream(struct websrv_context *web)
254 {
255         input_Stream_Object *ret = PyObject_New(input_Stream_Object, &input_Stream_Type);
256         ret->web = web;
257         ret->offset = 0;
258         return (PyObject *)ret;
259 }
260
261 static PyObject *Py_ErrorHttpStream(void)
262 {
263         error_Stream_Object *ret = PyObject_New(error_Stream_Object, &error_Stream_Type);
264         return (PyObject *)ret;
265 }
266
267 static PyObject *create_environ(bool tls, int content_length, struct http_header *headers, const char *request_method, const char *servername, int serverport, PyObject *inputstream, const char *request_string)
268 {
269         PyObject *env;
270         PyObject *errorstream;
271         PyObject *py_scheme;
272         struct http_header *hdr;
273         char *questionmark;
274         
275         env = PyDict_New();
276         if (env == NULL) {
277                 return NULL;
278         }
279
280         errorstream = Py_ErrorHttpStream();
281         if (errorstream == NULL) {
282                 Py_DECREF(env);
283                 Py_DECREF(inputstream);
284                 return NULL;
285         }
286
287         PyDict_SetItemString(env, "wsgi.input", inputstream);
288         PyDict_SetItemString(env, "wsgi.errors", errorstream);
289         PyDict_SetItemString(env, "wsgi.version", Py_BuildValue("(i,i)", 1, 0));
290         PyDict_SetItemString(env, "wsgi.multithread", Py_False);
291         PyDict_SetItemString(env, "wsgi.multiprocess", Py_True);
292         PyDict_SetItemString(env, "wsgi.run_once", Py_False);
293         PyDict_SetItemString(env, "SERVER_PROTOCOL", PyString_FromString("HTTP/1.0"));
294         if (content_length > 0) {
295                 PyDict_SetItemString(env, "CONTENT_LENGTH", PyLong_FromLong(content_length));
296         }
297         PyDict_SetItemString(env, "REQUEST_METHOD", PyString_FromString(request_method));
298
299         questionmark = strchr(request_string, '?');
300         if (questionmark == NULL) {
301                 PyDict_SetItemString(env, "SCRIPT_NAME", PyString_FromString(request_string));
302         } else {
303                 PyDict_SetItemString(env, "QUERY_STRING", PyString_FromString(questionmark+1));
304                 PyDict_SetItemString(env, "SCRIPT_NAME", PyString_FromStringAndSize(request_string, questionmark-request_string));
305         }
306         
307         PyDict_SetItemString(env, "SERVER_NAME", PyString_FromString(servername));
308         PyDict_SetItemString(env, "SERVER_PORT", PyInt_FromLong(serverport));
309         for (hdr = headers; hdr; hdr = hdr->next) {
310                 char *name;
311                 if (!strcasecmp(hdr->name, "Content-Type")) {
312                         PyDict_SetItemString(env, "CONTENT_TYPE", PyString_FromString(hdr->value));
313                 } else { 
314                         if (asprintf(&name, "HTTP_%s", hdr->name) < 0) {
315                                 Py_DECREF(env);
316                                 Py_DECREF(inputstream);
317                                 PyErr_NoMemory();
318                                 return NULL;
319                         }
320                         PyDict_SetItemString(env, name, PyString_FromString(hdr->value));
321                         free(name);
322                 }
323         }
324
325         if (tls) {
326                 py_scheme = PyString_FromString("https");
327         } else {
328                 py_scheme = PyString_FromString("http");
329         }
330         PyDict_SetItemString(env, "wsgi.url_scheme", py_scheme);
331
332         return env;
333 }
334
335 static void wsgi_process_http_input(struct web_server_data *wdata,
336                                     struct websrv_context *web)
337 {
338         PyObject *py_environ, *result, *item, *iter;
339         PyObject *request_handler = (PyObject *)wdata->private_data;
340         struct tsocket_address *my_address = web->conn->local_address;
341         const char *addr = "0.0.0.0";
342         uint16_t port = 0;
343         web_request_Object *py_web = PyObject_New(web_request_Object, &web_request_Type);
344         py_web->web = web;
345
346         if (tsocket_address_is_inet(my_address, "ip")) {
347                 addr = tsocket_address_inet_addr_string(my_address, wdata);
348                 port = tsocket_address_inet_port(my_address);
349         }
350
351         py_environ = create_environ(tls_enabled(web->conn->socket),
352                                     web->input.content_length, 
353                                     web->input.headers, 
354                                     web->input.post_request?"POST":"GET",
355                                     addr,
356                                     port,
357                                     Py_InputHttpStream(web),
358                                     web->input.url
359                                     );
360         if (py_environ == NULL) {
361                 DEBUG(0, ("Unable to create WSGI environment object\n"));
362                 return;
363         }
364
365         result = PyObject_CallMethod(request_handler, discard_const_p(char, "__call__"), discard_const_p(char, "OO"),
366                                        py_environ, PyObject_GetAttrString((PyObject *)py_web, "start_response"));
367
368         if (result == NULL) {
369                 DEBUG(0, ("error while running WSGI code\n"));
370                 return;
371         }
372
373         iter = PyObject_GetIter(result);
374         Py_DECREF(result);
375
376         /* Now, iter over all the data returned */
377
378         while ((item = PyIter_Next(iter))) {
379                 websrv_output(web, PyString_AsString(item), PyString_Size(item));
380                 Py_DECREF(item);
381         }
382
383         Py_DECREF(iter);
384 }
385
386 bool wsgi_initialize(struct web_server_data *wdata)
387 {
388         PyObject *py_swat;
389
390         Py_Initialize();
391
392         if (PyType_Ready(&web_request_Type) < 0)
393                 return false;
394
395         if (PyType_Ready(&input_Stream_Type) < 0)
396                 return false;
397
398         if (PyType_Ready(&error_Stream_Type) < 0)
399                 return false;
400
401         wdata->http_process_input = wsgi_process_http_input;
402         py_swat = PyImport_Import(PyString_FromString("swat"));
403         if (py_swat == NULL) {
404                 DEBUG(0, ("Unable to find SWAT\n"));
405                 return false;
406         }
407         wdata->private_data = py_swat;
408         return true;
409 }