summaryrefslogtreecommitdiff
path: root/source4/web_server/wsgi.c
blob: 00c9535cac4388f85eb740e170d9d50fe93fd968 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
/* 
   Unix SMB/CIFS implementation.
   Samba utility functions
   Copyright © Jelmer Vernooij <jelmer@samba.org> 2008

   Implementation of the WSGI interface described in PEP0333 
   (http://www.python.org/dev/peps/pep-0333)

   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 3 of the License, or
   (at your option) any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include <Python.h>
#include "includes.h"
#include "web_server/web_server.h"
#include "../lib/util/dlinklist.h"
#include "lib/tls/tls.h"
#include "lib/tsocket/tsocket.h"
#include "scripting/python/modules.h"

/* There's no Py_ssize_t in 2.4, apparently */
#if PY_MAJOR_VERSION == 2 && PY_MINOR_VERSION < 5
typedef int Py_ssize_t;
typedef inquiry lenfunc;
typedef intargfunc ssizeargfunc;
#endif

typedef struct {
	PyObject_HEAD
	struct websrv_context *web;
} web_request_Object;

static PyObject *start_response(PyObject *self, PyObject *args, PyObject *kwargs)
{
	PyObject *response_header, *exc_info = NULL;
	char *status;
	Py_ssize_t i;
	const char *kwnames[] = {
		"status", "response_header", "exc_info", NULL
	};
	web_request_Object *py_web = (web_request_Object *)self;
	struct websrv_context *web = py_web->web;
	struct http_header *headers = NULL;

	if (!PyArg_ParseTupleAndKeywords(args, kwargs, "sO|O:start_response", discard_const_p(char *, kwnames), &status, &response_header, &exc_info)) {
		return NULL;
	}

	/* FIXME: exc_info */

	if (!PyList_Check(response_header)) {
		PyErr_SetString(PyExc_TypeError, "response_header should be list");
		return NULL;
	}

	for (i = 0; i < PyList_Size(response_header); i++) {
		struct http_header *hdr = talloc_zero(web, struct http_header);
		PyObject *item = PyList_GetItem(response_header, i);
		PyObject *py_name, *py_value;

		if (!PyTuple_Check(item)) {
			PyErr_SetString(PyExc_TypeError, "Expected tuple");
			return NULL;
		}

		if (PyTuple_Size(item) != 2) {
			PyErr_SetString(PyExc_TypeError, "header tuple has invalid size, expected 2");
			return NULL;
		}

		py_name = PyTuple_GetItem(item, 0);

		if (!PyString_Check(py_name)) {
			PyErr_SetString(PyExc_TypeError, "header name should be string");
			return NULL;
		}

		py_value = PyTuple_GetItem(item, 1);
		if (!PyString_Check(py_value)) {
			PyErr_SetString(PyExc_TypeError, "header value should be string");
			return NULL;
		}

		hdr->name = talloc_strdup(hdr, PyString_AsString(py_name));
		hdr->value = talloc_strdup(hdr, PyString_AsString(py_value));
		DLIST_ADD(headers, hdr);
	}

	websrv_output_headers(web, status, headers);

	Py_RETURN_NONE;
}

static PyMethodDef web_request_methods[] = {
	{ "start_response", (PyCFunction)start_response, METH_VARARGS|METH_KEYWORDS, NULL },
	{ NULL }
};


PyTypeObject web_request_Type = {
	PyObject_HEAD_INIT(NULL) 0,
	.tp_name = "wsgi.Request",
	.tp_methods = web_request_methods,
	.tp_basicsize = sizeof(web_request_Object),
	.tp_flags = Py_TPFLAGS_DEFAULT,
};

typedef struct {
	PyObject_HEAD
} error_Stream_Object;

static PyObject *py_error_flush(PyObject *self, PyObject *args, PyObject *kwargs)
{
	/* Nothing to do here */
	Py_RETURN_NONE;
}

static PyObject *py_error_write(PyObject *self, PyObject *args, PyObject *kwargs)
{
	const char *kwnames[] = { "str", NULL };
	char *str = NULL;

	if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s:write", discard_const_p(char *, kwnames), &str)) {
		return NULL;
	}

	DEBUG(0, ("WSGI App: %s", str));

	Py_RETURN_NONE;
}

static PyObject *py_error_writelines(PyObject *self, PyObject *args, PyObject *kwargs)
{
	const char *kwnames[] = { "seq", NULL };
	PyObject *seq = NULL, *item;

	if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O:writelines", discard_const_p(char *, kwnames), &seq)) {
		return NULL;
	}
	
	while ((item = PyIter_Next(seq))) {
		char *str = PyString_AsString(item);

		DEBUG(0, ("WSGI App: %s", str));
	}

	Py_RETURN_NONE;
}

static PyMethodDef error_Stream_methods[] = {
	{ "flush", (PyCFunction)py_error_flush, METH_VARARGS|METH_KEYWORDS, NULL },
	{ "write", (PyCFunction)py_error_write, METH_VARARGS|METH_KEYWORDS, NULL },
	{ "writelines", (PyCFunction)py_error_writelines, METH_VARARGS|METH_KEYWORDS, NULL },
	{ NULL, NULL, 0, NULL }
};

PyTypeObject error_Stream_Type = {
	PyObject_HEAD_INIT(NULL) 0,
	.tp_name = "wsgi.ErrorStream",
	.tp_basicsize = sizeof(error_Stream_Object),
	.tp_methods = error_Stream_methods,
	.tp_flags = Py_TPFLAGS_DEFAULT,
};

typedef struct {
	PyObject_HEAD
	struct websrv_context *web;
	size_t offset;
} input_Stream_Object;

static PyObject *py_input_read(PyObject *_self, PyObject *args, PyObject *kwargs)
{
	const char *kwnames[] = { "size", NULL };
	PyObject *ret;
	input_Stream_Object *self = (input_Stream_Object *)_self;
	int size = -1;

	if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|i", discard_const_p(char *, kwnames), &size))
		return NULL;
	
	/* Don't read beyond buffer boundaries */
	if (size == -1)
		size = self->web->input.partial.length-self->offset;
	else
		size = MIN(size, self->web->input.partial.length-self->offset);

	ret = PyString_FromStringAndSize((char *)self->web->input.partial.data+self->offset, size);
	self->offset += size;

	return ret;
}

static PyObject *py_input_readline(PyObject *_self)
{
	/* FIXME */
	PyErr_SetString(PyExc_NotImplementedError, 
			"readline() not yet implemented");
	return NULL;
}

static PyObject *py_input_readlines(PyObject *_self, PyObject *args, PyObject *kwargs)
{
	const char *kwnames[] = { "hint", NULL };
	int hint;

	if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|i", discard_const_p(char *, kwnames), &hint))
		return NULL;
	
	/* FIXME */
	PyErr_SetString(PyExc_NotImplementedError, 
			"readlines() not yet implemented");
	return NULL;
}

static PyObject *py_input___iter__(PyObject *_self)
{
	/* FIXME */
	PyErr_SetString(PyExc_NotImplementedError, 
			"__iter__() not yet implemented");
	return NULL;
}

static PyMethodDef input_Stream_methods[] = {
	{ "read", (PyCFunction)py_input_read, METH_VARARGS|METH_KEYWORDS, NULL },
	{ "readline", (PyCFunction)py_input_readline, METH_NOARGS, NULL },
	{ "readlines", (PyCFunction)py_input_readlines, METH_VARARGS|METH_KEYWORDS, NULL },
	{ "__iter__", (PyCFunction)py_input___iter__, METH_NOARGS, NULL },
	{ NULL, NULL, 0, NULL }
};

PyTypeObject input_Stream_Type = {
	PyObject_HEAD_INIT(NULL) 0,
	.tp_name = "wsgi.InputStream",
	.tp_basicsize = sizeof(input_Stream_Object),
	.tp_methods = input_Stream_methods,
	.tp_flags = Py_TPFLAGS_DEFAULT,
};

static PyObject *Py_InputHttpStream(struct websrv_context *web)
{
	input_Stream_Object *ret = PyObject_New(input_Stream_Object, &input_Stream_Type);
	ret->web = web;
	ret->offset = 0;
	return (PyObject *)ret;
}

static PyObject *Py_ErrorHttpStream(void)
{
	error_Stream_Object *ret = PyObject_New(error_Stream_Object, &error_Stream_Type);
	return (PyObject *)ret;
}

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)
{
	PyObject *env;
	PyObject *py_scheme;
	PyObject *py_val;
	struct http_header *hdr;
	char *questionmark;

	env = PyDict_New();
	if (env == NULL) {
		return NULL;
	}

	PyDict_SetItemString(env, "wsgi.input", inputstream);

	py_val = Py_ErrorHttpStream();
	if (py_val == NULL) goto error;
	PyDict_SetItemString(env, "wsgi.errors", py_val);
	Py_DECREF(py_val);

	py_val = Py_BuildValue("(i,i)", 1, 0);
	if (py_val == NULL) goto error;
	PyDict_SetItemString(env, "wsgi.version", py_val);
	Py_DECREF(py_val);
	PyDict_SetItemString(env, "wsgi.multithread", Py_False);
	PyDict_SetItemString(env, "wsgi.multiprocess", Py_False);
	PyDict_SetItemString(env, "wsgi.run_once", Py_False);
	py_val = PyString_FromString("HTTP/1.0");
	if (py_val == NULL) goto error;
	PyDict_SetItemString(env, "SERVER_PROTOCOL", py_val);
	Py_DECREF(py_val);
	if (content_length > 0) {
		py_val = PyLong_FromLong(content_length);
		if (py_val == NULL) goto error;
		PyDict_SetItemString(env, "CONTENT_LENGTH", py_val);
		Py_DECREF(py_val);
	}
	py_val = PyString_FromString(request_method);
	if (py_val == NULL) goto error;
	PyDict_SetItemString(env, "REQUEST_METHOD", py_val);
	Py_DECREF(py_val);

	/* There is always a single wsgi app to which all requests are redirected,
	 * so SCRIPT_NAME will be / */
	py_val = PyString_FromString("/");
	if (py_val == NULL) goto error;
	PyDict_SetItemString(env, "SCRIPT_NAME", py_val);
	Py_DECREF(py_val);
	questionmark = strchr(request_string, '?');
	if (questionmark == NULL) {
		py_val = PyString_FromString(request_string);
		if (py_val == NULL) goto error;
		PyDict_SetItemString(env, "PATH_INFO", py_val);
		Py_DECREF(py_val);
	} else {
		py_val = PyString_FromString(questionmark+1);
		if (py_val == NULL) goto error;
		PyDict_SetItemString(env, "QUERY_STRING", py_val);
		Py_DECREF(py_val);
		py_val = PyString_FromStringAndSize(request_string, questionmark-request_string);
		if (py_val == NULL) goto error;
		PyDict_SetItemString(env, "PATH_INFO", py_val);
		Py_DECREF(py_val);
	}

	py_val = PyString_FromString(servername);
	if (py_val == NULL) goto error;
	PyDict_SetItemString(env, "SERVER_NAME", py_val);
	Py_DECREF(py_val);
	py_val = PyString_FromFormat("%d", serverport);
	if (py_val == NULL) goto error;
	PyDict_SetItemString(env, "SERVER_PORT", py_val);
	Py_DECREF(py_val);

	for (hdr = headers; hdr; hdr = hdr->next) {
		char *name;
		if (!strcasecmp(hdr->name, "Content-Type")) {
			py_val = PyString_FromString(hdr->value);
			PyDict_SetItemString(env, "CONTENT_TYPE", py_val);
			Py_DECREF(py_val);
		} else {
			if (asprintf(&name, "HTTP_%s", hdr->name) < 0) {
				PyErr_NoMemory();
				goto error;
			}
			py_val = PyString_FromString(hdr->value);
			PyDict_SetItemString(env, name, py_val);
			Py_DECREF(py_val);
			free(name);
		}
	}

	if (tls) {
		py_scheme = PyString_FromString("https");
	} else {
		py_scheme = PyString_FromString("http");
	}
	if (py_scheme == NULL) goto error;
	PyDict_SetItemString(env, "wsgi.url_scheme", py_scheme);
	Py_DECREF(py_scheme);

	return env;
error:
	Py_DECREF(env);
	return NULL;
}

static void wsgi_process_http_input(struct web_server_data *wdata,
				    struct websrv_context *web)
{
	PyObject *py_environ, *result, *item, *iter;
	PyObject *request_handler = (PyObject *)wdata->private_data;
	struct tsocket_address *my_address = web->conn->local_address;
	const char *addr = "0.0.0.0";
	uint16_t port = 0;
	web_request_Object *py_web;
	PyObject *py_input_stream;

	py_web = PyObject_New(web_request_Object, &web_request_Type);
	if (py_web == NULL) {
		DEBUG(0, ("Unable to allocate web request"));
		return;
	}
	py_web->web = web;

	if (tsocket_address_is_inet(my_address, "ip")) {
		addr = tsocket_address_inet_addr_string(my_address, wdata);
		port = tsocket_address_inet_port(my_address);
	}

	py_input_stream = Py_InputHttpStream(web);
	if (py_input_stream == NULL) {
		DEBUG(0, ("unable to create python input stream"));
		return;
	}

	py_environ = create_environ(tls_enabled(web->conn->socket),
				    web->input.content_length, 
				    web->input.headers, 
				    web->input.post_request?"POST":"GET",
				    addr,
				    port,
				    py_input_stream,
				    web->input.url
				    );

	Py_DECREF(py_input_stream);

	if (py_environ == NULL) {
		DEBUG(0, ("Unable to create WSGI environment object\n"));
		return;
	}

	result = PyObject_CallMethod(request_handler, discard_const_p(char, "__call__"), discard_const_p(char, "OO"),
				       py_environ, PyObject_GetAttrString((PyObject *)py_web, "start_response"));

	if (result == NULL) {
		DEBUG(0, ("error while running WSGI code\n"));
		return;
	}

	iter = PyObject_GetIter(result);
	Py_DECREF(result);

	if (iter == NULL) {
		DEBUG(0, ("wsgi application did not return iterable\n"));
		return;
	}

	/* Now, iter over all the data returned */

	while ((item = PyIter_Next(iter))) {
		websrv_output(web, PyString_AsString(item), PyString_Size(item));
		Py_DECREF(item);
	}

	Py_DECREF(iter);
}

bool wsgi_initialize(struct web_server_data *wdata)
{
	PyObject *py_web_server;

	Py_Initialize();

	py_update_path(); /* Ensure that we have the Samba paths at
			   * the start of the sys.path() */

	if (PyType_Ready(&web_request_Type) < 0)
		return false;

	if (PyType_Ready(&input_Stream_Type) < 0)
		return false;

	if (PyType_Ready(&error_Stream_Type) < 0)
		return false;

	wdata->http_process_input = wsgi_process_http_input;
	py_web_server = PyImport_ImportModule("samba.web_server");
	if (py_web_server == NULL) {
		DEBUG(0, ("Unable to find web server\n"));
		return false;
	}
	wdata->private_data = py_web_server;
	return true;
}