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