tevent: Remove reference to nonexistant configure.developer from autogen.sh.
[Samba.git] / source4 / web_server / wsgi.c
blob73e668ebfd7c6ce4eef945a33906080a45b367f0
1 /*
2 Unix SMB/CIFS implementation.
3 Samba utility functions
4 Copyright © Jelmer Vernooij <jelmer@samba.org> 2008
6 Implementation of the WSGI interface described in PEP0333
7 (http://www.python.org/dev/peps/pep-0333)
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.
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.
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/>.
23 #include <Python.h>
24 #include "includes.h"
25 #include "web_server/web_server.h"
26 #include "../lib/util/dlinklist.h"
27 #include "lib/tls/tls.h"
28 #include "lib/tsocket/tsocket.h"
30 /* There's no Py_ssize_t in 2.4, apparently */
31 #if PY_MAJOR_VERSION == 2 && PY_MINOR_VERSION < 5
32 typedef int Py_ssize_t;
33 typedef inquiry lenfunc;
34 typedef intargfunc ssizeargfunc;
35 #endif
37 typedef struct {
38 PyObject_HEAD
39 struct websrv_context *web;
40 } web_request_Object;
42 static PyObject *start_response(PyObject *self, PyObject *args, PyObject *kwargs)
44 PyObject *response_header, *exc_info = NULL;
45 char *status;
46 Py_ssize_t i;
47 const char *kwnames[] = {
48 "status", "response_header", "exc_info", NULL
50 web_request_Object *py_web = (web_request_Object *)self;
51 struct websrv_context *web = py_web->web;
52 struct http_header *headers = NULL;
54 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "sO|O:start_response", discard_const_p(char *, kwnames), &status, &response_header, &exc_info)) {
55 return NULL;
58 /* FIXME: exc_info */
60 if (!PyList_Check(response_header)) {
61 PyErr_SetString(PyExc_TypeError, "response_header should be list");
62 return NULL;
65 for (i = 0; i < PyList_Size(response_header); i++) {
66 struct http_header *hdr = talloc_zero(web, struct http_header);
67 PyObject *item = PyList_GetItem(response_header, i);
68 PyObject *py_name, *py_value;
70 if (!PyTuple_Check(item)) {
71 PyErr_SetString(PyExc_TypeError, "Expected tuple");
72 return NULL;
75 if (PyTuple_Size(item) != 2) {
76 PyErr_SetString(PyExc_TypeError, "header tuple has invalid size, expected 2");
77 return NULL;
80 py_name = PyTuple_GetItem(item, 0);
82 if (!PyString_Check(py_name)) {
83 PyErr_SetString(PyExc_TypeError, "header name should be string");
84 return NULL;
87 py_value = PyTuple_GetItem(item, 1);
88 if (!PyString_Check(py_value)) {
89 PyErr_SetString(PyExc_TypeError, "header value should be string");
90 return NULL;
93 hdr->name = talloc_strdup(hdr, PyString_AsString(py_name));
94 hdr->value = talloc_strdup(hdr, PyString_AsString(py_value));
95 DLIST_ADD(headers, hdr);
98 websrv_output_headers(web, status, headers);
100 Py_RETURN_NONE;
103 static PyMethodDef web_request_methods[] = {
104 { "start_response", (PyCFunction)start_response, METH_VARARGS|METH_KEYWORDS, NULL },
105 { NULL }
109 PyTypeObject web_request_Type = {
110 PyObject_HEAD_INIT(NULL) 0,
111 .tp_name = "wsgi.Request",
112 .tp_methods = web_request_methods,
113 .tp_basicsize = sizeof(web_request_Object),
114 .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
117 typedef struct {
118 PyObject_HEAD
119 } error_Stream_Object;
121 static PyObject *py_error_flush(PyObject *self, PyObject *args, PyObject *kwargs)
123 /* Nothing to do here */
124 Py_RETURN_NONE;
127 static PyObject *py_error_write(PyObject *self, PyObject *args, PyObject *kwargs)
129 const char *kwnames[] = { "str", NULL };
130 char *str = NULL;
132 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s:write", discard_const_p(char *, kwnames), &str)) {
133 return NULL;
136 DEBUG(0, ("WSGI App: %s", str));
138 Py_RETURN_NONE;
141 static PyObject *py_error_writelines(PyObject *self, PyObject *args, PyObject *kwargs)
143 const char *kwnames[] = { "seq", NULL };
144 PyObject *seq = NULL, *item;
146 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O:writelines", discard_const_p(char *, kwnames), &seq)) {
147 return NULL;
150 while ((item = PyIter_Next(seq))) {
151 char *str = PyString_AsString(item);
153 DEBUG(0, ("WSGI App: %s", str));
156 Py_RETURN_NONE;
159 static PyMethodDef error_Stream_methods[] = {
160 { "flush", (PyCFunction)py_error_flush, METH_VARARGS|METH_KEYWORDS, NULL },
161 { "write", (PyCFunction)py_error_write, METH_VARARGS|METH_KEYWORDS, NULL },
162 { "writelines", (PyCFunction)py_error_writelines, METH_VARARGS|METH_KEYWORDS, NULL },
163 { NULL, NULL, 0, NULL }
166 PyTypeObject error_Stream_Type = {
167 PyObject_HEAD_INIT(NULL) 0,
168 .tp_name = "wsgi.ErrorStream",
169 .tp_basicsize = sizeof(error_Stream_Object),
170 .tp_methods = error_Stream_methods,
171 .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
174 typedef struct {
175 PyObject_HEAD
176 struct websrv_context *web;
177 size_t offset;
178 } input_Stream_Object;
180 static PyObject *py_input_read(PyObject *_self, PyObject *args, PyObject *kwargs)
182 const char *kwnames[] = { "size", NULL };
183 PyObject *ret;
184 input_Stream_Object *self = (input_Stream_Object *)_self;
185 int size = -1;
187 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|i", discard_const_p(char *, kwnames), &size))
188 return NULL;
190 /* Don't read beyond buffer boundaries */
191 if (size == -1)
192 size = self->web->input.partial.length-self->offset;
193 else
194 size = MIN(size, self->web->input.partial.length-self->offset);
196 ret = PyString_FromStringAndSize((char *)self->web->input.partial.data+self->offset, size);
197 self->offset += size;
199 return ret;
202 static PyObject *py_input_readline(PyObject *_self)
204 /* FIXME */
205 PyErr_SetString(PyExc_NotImplementedError,
206 "readline() not yet implemented");
207 return NULL;
210 static PyObject *py_input_readlines(PyObject *_self, PyObject *args, PyObject *kwargs)
212 const char *kwnames[] = { "hint", NULL };
213 int hint;
215 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|i", discard_const_p(char *, kwnames), &hint))
216 return NULL;
218 /* FIXME */
219 PyErr_SetString(PyExc_NotImplementedError,
220 "readlines() not yet implemented");
221 return NULL;
224 static PyObject *py_input___iter__(PyObject *_self)
226 /* FIXME */
227 PyErr_SetString(PyExc_NotImplementedError,
228 "__iter__() not yet implemented");
229 return NULL;
232 static PyMethodDef input_Stream_methods[] = {
233 { "read", (PyCFunction)py_input_read, METH_VARARGS|METH_KEYWORDS, NULL },
234 { "readline", (PyCFunction)py_input_readline, METH_NOARGS, NULL },
235 { "readlines", (PyCFunction)py_input_readlines, METH_VARARGS|METH_KEYWORDS, NULL },
236 { "__iter__", (PyCFunction)py_input___iter__, METH_NOARGS, NULL },
237 { NULL, NULL, 0, NULL }
240 PyTypeObject input_Stream_Type = {
241 PyObject_HEAD_INIT(NULL) 0,
242 .tp_name = "wsgi.InputStream",
243 .tp_basicsize = sizeof(input_Stream_Object),
244 .tp_methods = input_Stream_methods,
245 .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
248 static PyObject *Py_InputHttpStream(struct websrv_context *web)
250 input_Stream_Object *ret = PyObject_New(input_Stream_Object, &input_Stream_Type);
251 ret->web = web;
252 ret->offset = 0;
253 return (PyObject *)ret;
256 static PyObject *Py_ErrorHttpStream(void)
258 error_Stream_Object *ret = PyObject_New(error_Stream_Object, &error_Stream_Type);
259 return (PyObject *)ret;
262 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)
264 PyObject *env;
265 PyObject *errorstream;
266 PyObject *py_scheme;
267 struct http_header *hdr;
268 char *questionmark;
270 env = PyDict_New();
271 if (env == NULL) {
272 return NULL;
275 errorstream = Py_ErrorHttpStream();
276 if (errorstream == NULL) {
277 Py_DECREF(env);
278 Py_DECREF(inputstream);
279 return NULL;
282 PyDict_SetItemString(env, "wsgi.input", inputstream);
283 PyDict_SetItemString(env, "wsgi.errors", errorstream);
284 PyDict_SetItemString(env, "wsgi.version", Py_BuildValue("(i,i)", 1, 0));
285 PyDict_SetItemString(env, "wsgi.multithread", Py_False);
286 PyDict_SetItemString(env, "wsgi.multiprocess", Py_True);
287 PyDict_SetItemString(env, "wsgi.run_once", Py_False);
288 PyDict_SetItemString(env, "SERVER_PROTOCOL", PyString_FromString("HTTP/1.0"));
289 if (content_length > 0) {
290 PyDict_SetItemString(env, "CONTENT_LENGTH", PyLong_FromLong(content_length));
292 PyDict_SetItemString(env, "REQUEST_METHOD", PyString_FromString(request_method));
294 questionmark = strchr(request_string, '?');
295 if (questionmark == NULL) {
296 PyDict_SetItemString(env, "SCRIPT_NAME", PyString_FromString(request_string));
297 } else {
298 PyDict_SetItemString(env, "QUERY_STRING", PyString_FromString(questionmark+1));
299 PyDict_SetItemString(env, "SCRIPT_NAME", PyString_FromStringAndSize(request_string, questionmark-request_string));
302 PyDict_SetItemString(env, "SERVER_NAME", PyString_FromString(servername));
303 PyDict_SetItemString(env, "SERVER_PORT", PyInt_FromLong(serverport));
304 for (hdr = headers; hdr; hdr = hdr->next) {
305 char *name;
306 if (!strcasecmp(hdr->name, "Content-Type")) {
307 PyDict_SetItemString(env, "CONTENT_TYPE", PyString_FromString(hdr->value));
308 } else {
309 if (asprintf(&name, "HTTP_%s", hdr->name) < 0) {
310 Py_DECREF(env);
311 Py_DECREF(inputstream);
312 PyErr_NoMemory();
313 return NULL;
315 PyDict_SetItemString(env, name, PyString_FromString(hdr->value));
316 free(name);
320 if (tls) {
321 py_scheme = PyString_FromString("https");
322 } else {
323 py_scheme = PyString_FromString("http");
325 PyDict_SetItemString(env, "wsgi.url_scheme", py_scheme);
327 return env;
330 static void wsgi_process_http_input(struct web_server_data *wdata,
331 struct websrv_context *web)
333 PyObject *py_environ, *result, *item, *iter;
334 PyObject *request_handler = (PyObject *)wdata->private_data;
335 struct tsocket_address *my_address = web->conn->local_address;
336 const char *addr = "0.0.0.0";
337 uint16_t port = 0;
338 web_request_Object *py_web = PyObject_New(web_request_Object, &web_request_Type);
339 py_web->web = web;
341 if (tsocket_address_is_inet(my_address, "ip")) {
342 addr = tsocket_address_inet_addr_string(my_address, wdata);
343 port = tsocket_address_inet_port(my_address);
346 py_environ = create_environ(tls_enabled(web->conn->socket),
347 web->input.content_length,
348 web->input.headers,
349 web->input.post_request?"POST":"GET",
350 addr,
351 port,
352 Py_InputHttpStream(web),
353 web->input.url
355 if (py_environ == NULL) {
356 DEBUG(0, ("Unable to create WSGI environment object\n"));
357 return;
360 result = PyObject_CallMethod(request_handler, discard_const_p(char, "__call__"), discard_const_p(char, "OO"),
361 py_environ, PyObject_GetAttrString((PyObject *)py_web, "start_response"));
363 if (result == NULL) {
364 DEBUG(0, ("error while running WSGI code\n"));
365 return;
368 iter = PyObject_GetIter(result);
369 Py_DECREF(result);
371 /* Now, iter over all the data returned */
373 while ((item = PyIter_Next(iter))) {
374 websrv_output(web, PyString_AsString(item), PyString_Size(item));
375 Py_DECREF(item);
378 Py_DECREF(iter);
381 bool wsgi_initialize(struct web_server_data *wdata)
383 PyObject *py_swat;
385 Py_Initialize();
387 if (PyType_Ready(&web_request_Type) < 0)
388 return false;
390 if (PyType_Ready(&input_Stream_Type) < 0)
391 return false;
393 if (PyType_Ready(&error_Stream_Type) < 0)
394 return false;
396 wdata->http_process_input = wsgi_process_http_input;
397 py_swat = PyImport_Import(PyString_FromString("swat"));
398 if (py_swat == NULL) {
399 DEBUG(0, ("Unable to find SWAT\n"));
400 return false;
402 wdata->private_data = py_swat;
403 return true;