python.c (156512B)
1 /*
2 * Copyright (c) 2016 Stanislav Yudin <stan@endlessinsomnia.com>
3 * Copyright (c) 2017-2022 Joris Vink <joris@coders.se>
4 *
5 * Permission to use, copy, modify, and distribute this software for any
6 * purpose with or without fee is hereby granted, provided that the above
7 * copyright notice and this permission notice appear in all copies.
8 *
9 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
10 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
14 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
15 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
16 */
17
18 #include <sys/param.h>
19 #include <sys/types.h>
20 #include <sys/stat.h>
21 #include <sys/socket.h>
22 #include <sys/wait.h>
23 #include <sys/un.h>
24
25 #include <ctype.h>
26 #include <libgen.h>
27 #include <inttypes.h>
28 #include <signal.h>
29 #include <fcntl.h>
30 #include <unistd.h>
31 #include <stdarg.h>
32 #include <stddef.h>
33
34 #include "kore.h"
35 #include "http.h"
36
37 #if defined(KORE_USE_PGSQL)
38 #include "pgsql.h"
39 #endif
40
41 #if defined(KORE_USE_CURL)
42 #include "curl.h"
43 #endif
44
45 #if defined(KORE_USE_ACME)
46 #include "acme.h"
47 #endif
48
49 #include "python_api.h"
50 #include "python_methods.h"
51
52 #if defined(KORE_USE_CURL)
53 #include "python_curlopt.h"
54 #endif
55
56 #include <frameobject.h>
57
58 /*
59 * Since 3.13.x we have to do a lot of nasty hacks to get some form
60 * of insight into the internals so we can keep providing the same
61 * functionality we've had before.
62 */
63 #if PY_VERSION_HEX >= 0x030d0000
64 #define Py_BUILD_CORE 1
65 #pragma GCC diagnostic push
66 #pragma GCC diagnostic ignored "-Wpedantic"
67 #endif
68
69 #if PY_VERSION_HEX >= 0x030e0000
70 #pragma GCC diagnostic ignored "-Wcast-qual"
71 #if defined(__clang__)
72 #pragma GCC diagnostic ignored "-Wtypedef-redefinition"
73 #endif
74 #endif
75
76 #if PY_VERSION_HEX < 0x030d0000
77 #define _PyFrame_GetCode(frame) (frame->f_code)
78 #endif
79
80 #if PY_VERSION_HEX >= 0x030e0000
81 #include <internal/pycore_interpframe.h>
82 #endif
83
84 #if PY_VERSION_HEX >= 0x030b0000
85 #include <internal/pycore_frame.h>
86 #endif
87
88 #if PY_VERSION_HEX >= 0x030d0000
89 #pragma GCC diagnostic pop
90 #endif
91
92 #if PY_VERSION_HEX < 0x030A0000
93 typedef enum {
94 PYGEN_RETURN = 0,
95 PYGEN_ERROR = -1,
96 PYGEN_NEXT = 1,
97 } PySendResult;
98 #endif
99
100 struct reqcall {
101 PyObject *f;
102 TAILQ_ENTRY(reqcall) list;
103 };
104
105 union deconst {
106 char *p;
107 const char *cp;
108 };
109
110 TAILQ_HEAD(reqcall_list, reqcall);
111
112 PyMODINIT_FUNC python_module_init(void);
113
114 static PyObject *python_import(const char *);
115 static int python_resolve_frame_line(void *);
116 static PyObject *pyconnection_alloc(struct connection *);
117 static PyObject *python_callable(PyObject *, const char *);
118 static void python_split_arguments(char *, char **, size_t);
119 static void python_kore_recvobj(struct kore_msg *, const void *);
120
121 static PyObject *python_cmsg_to_list(struct msghdr *);
122 static const char *python_string_from_dict(PyObject *, const char *);
123 static int python_bool_from_dict(PyObject *, const char *, int *);
124 static int python_long_from_dict(PyObject *, const char *, long *);
125
126 static int pyhttp_response_sent(struct netbuf *);
127 static PyObject *pyhttp_file_alloc(struct http_file *);
128 static PyObject *pyhttp_request_alloc(const struct http_request *);
129
130 static struct python_coro *python_coro_create(PyObject *,
131 struct http_request *);
132 static struct kore_domain *python_route_domain_resolve(struct pyroute *);
133
134 static int python_route_install(struct pyroute *);
135 static int python_route_params(PyObject *, struct kore_route *,
136 const char *, int, int);
137 static int python_route_methods(PyObject *, PyObject *,
138 struct kore_route *);
139 static int python_route_auth(PyObject *, struct kore_route *);
140 static int python_route_hooks(PyObject *, struct kore_route *);
141 static int python_route_hook_set(PyObject *, const char *,
142 struct kore_runtime_call **);
143
144 static int python_coro_run(struct python_coro *);
145 static void python_coro_wakeup(struct python_coro *);
146 static void python_coro_suspend(struct python_coro *);
147 static void python_coro_trace(const char *, struct python_coro *);
148
149 static void pysocket_evt_handle(void *, int);
150 static void pysocket_op_timeout(void *, u_int64_t);
151 static PyObject *pysocket_op_create(struct pysocket *,
152 int, const void *, size_t);
153
154 static struct pysocket *pysocket_alloc(void);
155 static PyObject *pysocket_async_recv(struct pysocket_op *);
156 static PyObject *pysocket_async_send(struct pysocket_op *);
157 static PyObject *pysocket_async_accept(struct pysocket_op *);
158 static PyObject *pysocket_async_connect(struct pysocket_op *);
159
160 static void pylock_do_release(struct pylock *);
161
162 static void pytimer_run(void *, u_int64_t);
163 static void pyproc_timeout(void *, u_int64_t);
164 static void pysuspend_wakeup(void *, u_int64_t);
165
166 static void pygather_reap_coro(struct pygather_op *,
167 struct python_coro *);
168
169 static int pyhttp_preprocess(struct http_request *);
170 static int pyhttp_iterobj_chunk_sent(struct netbuf *);
171 static int pyhttp_iterobj_next(struct pyhttp_iterobj *);
172 static void pyhttp_iterobj_disconnect(struct connection *);
173
174 static int pyconnection_x509_cb(void *, int, int, const char *,
175 const void *, size_t, int);
176
177 #if defined(KORE_USE_PGSQL)
178 static int pykore_pgsql_result(struct pykore_pgsql *);
179 static void pykore_pgsql_callback(struct kore_pgsql *, void *);
180 static int pykore_pgsql_params(struct pykore_pgsql *, PyObject *);
181 static int pykore_pgsql_params(struct pykore_pgsql *, PyObject *);
182 #endif
183
184 #if defined(KORE_USE_CURL)
185 static void python_curl_http_callback(struct kore_curl *, void *);
186 static void python_curl_handle_callback(struct kore_curl *, void *);
187 static PyObject *pyhttp_client_request(struct pyhttp_client *, int,
188 PyObject *);
189 static PyObject *python_curlopt_set(struct pycurl_data *,
190 long, PyObject *);
191 static int python_curlopt_from_dict(struct pycurl_data *,
192 PyObject *);
193 #endif
194
195 static void python_append_path(const char *);
196 static void python_push_integer(PyObject *, const char *, long);
197 static void python_push_type(const char *, PyObject *, PyTypeObject *);
198
199 static int python_validator_check(PyObject *);
200 static int python_runtime_resolve(const char *, const struct stat *);
201 static int python_runtime_http_request(void *, struct http_request *);
202 static void python_runtime_http_request_free(void *, struct http_request *);
203 static int python_runtime_http_body_chunk(void *, struct http_request *,
204 const void *, size_t);
205 static int python_runtime_validator(void *, struct http_request *,
206 const void *);
207 static void python_runtime_wsmessage(void *, struct connection *,
208 u_int8_t, const void *, size_t);
209 static void python_runtime_execute(void *);
210 static int python_runtime_onload(void *, int);
211 static void python_runtime_signal(void *, int);
212 static void python_runtime_configure(void *, int, char **);
213 static void python_runtime_connect(void *, struct connection *);
214
215 static void python_module_load(struct kore_module *);
216 static void python_module_free(struct kore_module *);
217 static void python_module_reload(struct kore_module *);
218 static void *python_module_getsym(struct kore_module *, const char *);
219
220 static void *python_malloc(void *, size_t);
221 static void *python_calloc(void *, size_t, size_t);
222 static void *python_realloc(void *, void *, size_t);
223 static void python_free(void *, void *);
224
225 struct kore_module_functions kore_python_module = {
226 .free = python_module_free,
227 .load = python_module_load,
228 .getsym = python_module_getsym,
229 .reload = python_module_reload
230 };
231
232 struct kore_runtime kore_python_runtime = {
233 KORE_RUNTIME_PYTHON,
234 .resolve = python_runtime_resolve,
235 .http_request = python_runtime_http_request,
236 .http_body_chunk = python_runtime_http_body_chunk,
237 .http_request_free = python_runtime_http_request_free,
238 .validator = python_runtime_validator,
239 .wsconnect = python_runtime_connect,
240 .wsmessage = python_runtime_wsmessage,
241 .wsdisconnect = python_runtime_connect,
242 .onload = python_runtime_onload,
243 .signal = python_runtime_signal,
244 .connect = python_runtime_connect,
245 .execute = python_runtime_execute,
246 .configure = python_runtime_configure,
247 };
248
249 static struct {
250 const char *symbol;
251 int value;
252 } python_integers[] = {
253 { "LOG_ERR", LOG_ERR },
254 { "LOG_INFO", LOG_INFO },
255 { "LOG_NOTICE", LOG_NOTICE },
256 { "RESULT_OK", KORE_RESULT_OK },
257 { "RESULT_RETRY", KORE_RESULT_RETRY },
258 { "RESULT_ERROR", KORE_RESULT_ERROR },
259 { "MODULE_LOAD", KORE_MODULE_LOAD },
260 { "MODULE_UNLOAD", KORE_MODULE_UNLOAD },
261 { "TIMER_ONESHOT", KORE_TIMER_ONESHOT },
262 { "CONN_PROTO_HTTP", CONN_PROTO_HTTP },
263 { "CONN_PROTO_UNKNOWN", CONN_PROTO_UNKNOWN },
264 { "CONN_PROTO_WEBSOCKET", CONN_PROTO_WEBSOCKET },
265 { "CONN_STATE_ESTABLISHED", CONN_STATE_ESTABLISHED },
266 { "HTTP_METHOD_GET", HTTP_METHOD_GET },
267 { "HTTP_METHOD_PUT", HTTP_METHOD_PUT },
268 { "HTTP_METHOD_HEAD", HTTP_METHOD_HEAD },
269 { "HTTP_METHOD_POST", HTTP_METHOD_POST },
270 { "HTTP_METHOD_DELETE", HTTP_METHOD_DELETE },
271 { "HTTP_METHOD_OPTIONS", HTTP_METHOD_OPTIONS },
272 { "HTTP_METHOD_PATCH", HTTP_METHOD_PATCH },
273 { "WEBSOCKET_OP_TEXT", WEBSOCKET_OP_TEXT },
274 { "WEBSOCKET_OP_BINARY", WEBSOCKET_OP_BINARY },
275 { "WEBSOCKET_BROADCAST_LOCAL", WEBSOCKET_BROADCAST_LOCAL },
276 { "WEBSOCKET_BROADCAST_GLOBAL", WEBSOCKET_BROADCAST_GLOBAL },
277 { NULL, -1 }
278 };
279
280 static PyMemAllocatorEx allocator = {
281 .ctx = NULL,
282 .malloc = python_malloc,
283 .calloc = python_calloc,
284 .realloc = python_realloc,
285 .free = python_free
286 };
287
288 #if defined(__linux__)
289 #include "seccomp.h"
290
291 static struct sock_filter filter_python[] = {
292 /* Required for kore.proc */
293 #if defined(SYS_dup2)
294 KORE_SYSCALL_ALLOW(dup2),
295 #endif
296 #if defined(SYS_dup3)
297 KORE_SYSCALL_ALLOW(dup3),
298 #endif
299 #if defined(SYS_pipe)
300 KORE_SYSCALL_ALLOW(pipe),
301 #endif
302 #if defined(SYS_pipe2)
303 KORE_SYSCALL_ALLOW(pipe2),
304 #endif
305 KORE_SYSCALL_ALLOW(wait4),
306 KORE_SYSCALL_ALLOW(execve),
307
308 /* Socket related. */
309 KORE_SYSCALL_ALLOW(bind),
310 KORE_SYSCALL_ALLOW(listen),
311 KORE_SYSCALL_ALLOW(sendto),
312 KORE_SYSCALL_ALLOW(recvfrom),
313 KORE_SYSCALL_ALLOW(getsockname),
314 KORE_SYSCALL_ALLOW(getpeername),
315 KORE_SYSCALL_ALLOW_ARG(socket, 0, AF_INET),
316 KORE_SYSCALL_ALLOW_ARG(socket, 0, AF_INET6),
317 KORE_SYSCALL_ALLOW_ARG(socket, 0, AF_UNIX),
318 };
319
320 #define PYSECCOMP_ACTION_ALLOW 1
321 #define PYSECCOMP_ACTION_DENY 2
322
323 #define PYSECCOMP_SYSCALL_FILTER 1
324 #define PYSECCOMP_SYSCALL_ARG 2
325 #define PYSECCOMP_SYSCALL_MASK 3
326 #define PYSECCOMP_SYSCALL_FLAG 4
327
328 static int pyseccomp_filter_install(struct pyseccomp *,
329 const char *, int, int, int, int);
330 static PyObject *pyseccomp_common_action(struct pyseccomp *, PyObject *,
331 PyObject *, int, int);
332
333 static struct pyseccomp *py_seccomp = NULL;
334 #endif
335
336 static TAILQ_HEAD(, pyproc) procs;
337 static TAILQ_HEAD(, pyroute) routes;
338 static struct reqcall_list prereq;
339
340 static struct kore_pool coro_pool;
341 static struct kore_pool iterobj_pool;
342 static struct kore_pool queue_wait_pool;
343 static struct kore_pool gather_coro_pool;
344 static struct kore_pool queue_object_pool;
345 static struct kore_pool gather_result_pool;
346
347 static u_int64_t coro_id;
348 static int coro_count;
349 static int coro_tracing;
350 static struct coro_list coro_runnable;
351 static struct coro_list coro_suspended;
352
353 extern const char *__progname;
354
355 static PyObject *pickle = NULL;
356 static PyObject *kore_app = NULL;
357 static PyObject *pickle_dumps = NULL;
358 static PyObject *pickle_loads = NULL;
359 static PyObject *python_tracer = NULL;
360
361 /* XXX */
362 static struct python_coro *coro_running = NULL;
363
364 #if !defined(KORE_SINGLE_BINARY)
365 static const char *kore_pymodule = NULL;
366 #endif
367
368 void
369 kore_python_init(void)
370 {
371 struct kore_runtime_call *rcall;
372
373 coro_id = 0;
374 coro_count = 0;
375 coro_tracing = 0;
376
377 TAILQ_INIT(&prereq);
378
379 TAILQ_INIT(&procs);
380 TAILQ_INIT(&routes);
381 TAILQ_INIT(&coro_runnable);
382 TAILQ_INIT(&coro_suspended);
383
384 kore_pool_init(&coro_pool, "coropool", sizeof(struct python_coro), 100);
385
386 kore_pool_init(&iterobj_pool, "iterobj_pool",
387 sizeof(struct pyhttp_iterobj), 100);
388 kore_pool_init(&queue_wait_pool, "queue_wait_pool",
389 sizeof(struct pyqueue_waiting), 100);
390 kore_pool_init(&gather_coro_pool, "gather_coro_pool",
391 sizeof(struct pygather_coro), 100);
392 kore_pool_init(&queue_object_pool, "queue_object_pool",
393 sizeof(struct pyqueue_object), 100);
394 kore_pool_init(&gather_result_pool, "gather_result_pool",
395 sizeof(struct pygather_result), 100);
396
397 PyMem_SetAllocator(PYMEM_DOMAIN_OBJ, &allocator);
398 PyMem_SetAllocator(PYMEM_DOMAIN_MEM, &allocator);
399 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &allocator);
400
401 #if defined(KORE_DEBUG)
402 PyMem_SetupDebugHooks();
403 #endif
404
405 kore_msg_register(KORE_PYTHON_SEND_OBJ, python_kore_recvobj);
406
407 if (PyImport_AppendInittab("kore", &python_module_init) == -1)
408 fatal("kore_python_init: failed to add new module");
409
410 rcall = kore_runtime_getcall("kore_python_preinit");
411 if (rcall != NULL) {
412 kore_runtime_execute(rcall);
413 kore_free(rcall);
414 }
415
416 Py_InitializeEx(0);
417
418 if ((pickle = PyImport_ImportModule("pickle")) == NULL)
419 fatal("failed to import pickle module");
420
421 if ((pickle_dumps = PyObject_GetAttrString(pickle, "dumps")) == NULL)
422 fatal("pickle module has no dumps method");
423
424 if ((pickle_loads = PyObject_GetAttrString(pickle, "loads")) == NULL)
425 fatal("pickle module has no loads method");
426
427 #if defined(__linux__)
428 kore_seccomp_filter("python", filter_python,
429 KORE_FILTER_LEN(filter_python));
430 #endif
431
432 #if !defined(KORE_SINGLE_BINARY)
433 if (kore_pymodule) {
434 if (!kore_configure_setting("deployment", "dev"))
435 fatal("failed to set initial deployment");
436 }
437 #endif
438 }
439
440 void
441 kore_python_cleanup(void)
442 {
443 if (Py_IsInitialized()) {
444 PyErr_Clear();
445 Py_Finalize();
446 }
447 }
448
449 void
450 kore_python_path(const char *path)
451 {
452 python_append_path(path);
453 }
454
455 void
456 kore_python_coro_run(void)
457 {
458 struct pygather_op *op;
459 struct python_coro *coro;
460
461 while ((coro = TAILQ_FIRST(&coro_runnable)) != NULL) {
462 if (coro->state != CORO_STATE_RUNNABLE)
463 fatal("non-runnable coro on coro_runnable");
464
465 if (python_coro_run(coro) == KORE_RESULT_OK) {
466 if (coro->gatherop != NULL) {
467 op = coro->gatherop;
468 if (op->coro->request != NULL)
469 http_request_wakeup(op->coro->request);
470 else
471 python_coro_wakeup(op->coro);
472 pygather_reap_coro(op, coro);
473 } else {
474 kore_python_coro_delete(coro);
475 }
476 }
477 }
478
479 /*
480 * Let Kore do HTTP processing so awoken coroutines run asap without
481 * having to wait for a tick from the event loop.
482 *
483 * Maybe it is more beneficial that we track if something related
484 * to HTTP requests was awoken and only run if true?
485 */
486 http_process();
487
488 #if defined(KORE_USE_CURL)
489 /*
490 * If a coroutine fired off a curl instance, immediately
491 * let it make progress.
492 */
493 kore_curl_do_timeout();
494 #endif
495 }
496
497 void
498 kore_python_coro_delete(void *obj)
499 {
500 struct python_coro *coro;
501
502 coro = obj;
503 coro_count--;
504
505 python_coro_trace(coro->killed ? "killed" : "deleted", coro);
506
507 coro_running = coro;
508
509 if (coro->lockop != NULL) {
510 coro->lockop->active = 0;
511 TAILQ_REMOVE(&coro->lockop->lock->ops, coro->lockop, list);
512 Py_DECREF((PyObject *)coro->lockop);
513 coro->lockop = NULL;
514 }
515
516 Py_DECREF(coro->obj);
517 coro_running = NULL;
518
519 if (coro->state == CORO_STATE_RUNNABLE)
520 TAILQ_REMOVE(&coro_runnable, coro, list);
521 else
522 TAILQ_REMOVE(&coro_suspended, coro, list);
523
524 kore_free(coro->name);
525 Py_XDECREF(coro->result);
526
527 kore_pool_put(&coro_pool, coro);
528 }
529
530 int
531 kore_python_coro_pending(void)
532 {
533 return (!TAILQ_EMPTY(&coro_runnable));
534 }
535
536 void
537 kore_python_routes_resolve(void)
538 {
539 struct pyroute *route;
540
541 while ((route = TAILQ_FIRST(&routes)) != NULL) {
542 TAILQ_REMOVE(&routes, route, list);
543 if (!python_route_install(route))
544 fatalx("failed to install route for %s", route->path);
545 Py_DECREF((PyObject *)route);
546 }
547 }
548
549 void
550 kore_python_log_error(const char *function)
551 {
552 const char *sval;
553 PyObject *ret, *repr, *type, *value, *traceback;
554
555 if (!PyErr_Occurred() || PyErr_ExceptionMatches(PyExc_StopIteration))
556 return;
557
558 PyErr_Fetch(&type, &value, &traceback);
559
560 if (type == NULL || value == NULL) {
561 kore_log(LOG_ERR, "unknown python exception in '%s'", function);
562 return;
563 }
564
565 if (value == NULL || !PyObject_IsInstance(value, type))
566 PyErr_NormalizeException(&type, &value, &traceback);
567
568 /*
569 * If we're in an active coroutine and it was tied to a gather
570 * operation we have to make sure we can use the Exception that
571 * was thrown as the result value so we can propagate it via the
572 * return list of kore.gather().
573 */
574 if (coro_running != NULL && coro_running->gatherop != NULL) {
575 PyErr_SetObject(PyExc_StopIteration, value);
576 } else if (python_tracer != NULL) {
577 /*
578 * Call the user-supplied tracer callback.
579 */
580 ret = PyObject_CallFunctionObjArgs(python_tracer,
581 type, value, traceback, NULL);
582 Py_XDECREF(ret);
583 } else {
584 if ((repr = PyObject_Repr(value)) == NULL)
585 sval = "unknown";
586 else
587 sval = PyUnicode_AsUTF8(repr);
588
589 kore_log(LOG_ERR,
590 "uncaught exception %s in '%s'", sval, function);
591
592 Py_XDECREF(repr);
593 }
594
595 Py_DECREF(type);
596 Py_DECREF(value);
597 Py_XDECREF(traceback);
598 }
599
600 void
601 kore_python_proc_reap(void)
602 {
603 struct pyproc *proc;
604 struct python_coro *coro;
605 pid_t child;
606 int status;
607
608 for (;;) {
609 if ((child = waitpid(-1, &status, WNOHANG)) == -1) {
610 if (errno == ECHILD)
611 return;
612 if (errno == EINTR)
613 continue;
614 kore_log(LOG_NOTICE, "waitpid: %s", errno_s);
615 return;
616 }
617
618 if (child == 0)
619 return;
620
621 proc = NULL;
622
623 TAILQ_FOREACH(proc, &procs, list) {
624 if (proc->pid == child)
625 break;
626 }
627
628 if (proc == NULL)
629 continue;
630
631 proc->pid = -1;
632 proc->reaped = 1;
633 proc->status = status;
634
635 if (proc->timer != NULL) {
636 kore_timer_remove(proc->timer);
637 proc->timer = NULL;
638 }
639
640 /*
641 * If someone is waiting on proc.reap() then wakeup that
642 * coroutine, otherwise wakeup the coroutine that created
643 * the process.
644 */
645 if (proc->op != NULL)
646 coro = proc->op->coro;
647 else
648 coro = proc->coro;
649
650 if (coro->request != NULL)
651 http_request_wakeup(coro->request);
652 else
653 python_coro_wakeup(coro);
654 }
655 }
656
657 #if defined(__linux__)
658 void
659 kore_python_seccomp_hook(const char *method)
660 {
661 struct kore_runtime *rt;
662 PyObject *func, *result;
663
664 if ((func = kore_module_getsym(method, &rt)) == NULL)
665 return;
666
667 if (rt->type != KORE_RUNTIME_PYTHON)
668 return;
669
670 py_seccomp = PyObject_New(struct pyseccomp, &pyseccomp_type);
671 if (py_seccomp == NULL)
672 fatal("failed to create seccomp object");
673
674 py_seccomp->elm = 0;
675 py_seccomp->filters = NULL;
676
677 result = PyObject_CallFunctionObjArgs(func,
678 (PyObject *)py_seccomp, NULL);
679 kore_python_log_error(method);
680
681 kore_seccomp_filter("koreapp", py_seccomp->filters, py_seccomp->elm);
682
683 Py_XDECREF(result);
684 }
685
686 void
687 kore_python_seccomp_cleanup(void)
688 {
689 Py_XDECREF(py_seccomp);
690 py_seccomp = NULL;
691 }
692
693 static void
694 pyseccomp_dealloc(struct pyseccomp *seccomp)
695 {
696 kore_free(seccomp->filters);
697
698 seccomp->elm = 0;
699 seccomp->filters = NULL;
700 }
701
702 static PyObject *
703 pyseccomp_bpf_stmt(struct pyseccomp *seccomp, PyObject *args)
704 {
705 u_int32_t k;
706 u_int16_t code;
707 size_t len, off;
708 struct sock_filter filter[1];
709
710 if (!PyArg_ParseTuple(args, "HI", &code, &k))
711 return (NULL);
712
713 filter[0].k = k;
714 filter[0].jt = 0;
715 filter[0].jf = 0;
716 filter[0].code = code;
717
718 len = sizeof(struct sock_filter);
719 off = seccomp->elm * sizeof(struct sock_filter);
720 seccomp->filters = kore_realloc(seccomp->filters, off + len);
721
722 memcpy(seccomp->filters + off, filter, len);
723 seccomp->elm += 1;
724
725 Py_RETURN_NONE;
726 }
727
728 static PyObject *
729 pyseccomp_allow(struct pyseccomp *seccomp, PyObject *args)
730 {
731 const char *syscall;
732
733 if (!PyArg_ParseTuple(args, "s", &syscall))
734 return (NULL);
735
736 if (!pyseccomp_filter_install(seccomp, syscall,
737 PYSECCOMP_SYSCALL_FILTER, 0, 0, SECCOMP_RET_ALLOW))
738 return (NULL);
739
740 Py_RETURN_NONE;
741 }
742
743 static PyObject *
744 pyseccomp_allow_arg(struct pyseccomp *seccomp, PyObject *args)
745 {
746 return (pyseccomp_common_action(seccomp, args, NULL,
747 PYSECCOMP_SYSCALL_ARG, PYSECCOMP_ACTION_ALLOW));
748 }
749
750 static PyObject *
751 pyseccomp_allow_flag(struct pyseccomp *seccomp, PyObject *args)
752 {
753 return (pyseccomp_common_action(seccomp, args, NULL,
754 PYSECCOMP_SYSCALL_FLAG, PYSECCOMP_ACTION_ALLOW));
755 }
756
757 static PyObject *
758 pyseccomp_allow_mask(struct pyseccomp *seccomp, PyObject *args)
759 {
760 return (pyseccomp_common_action(seccomp, args, NULL,
761 PYSECCOMP_SYSCALL_MASK, PYSECCOMP_ACTION_ALLOW));
762 }
763
764 static PyObject *
765 pyseccomp_deny(struct pyseccomp *seccomp, PyObject *args, PyObject *kwargs)
766 {
767 long err;
768 const char *syscall;
769
770 if (!PyArg_ParseTuple(args, "s", &syscall))
771 return (NULL);
772
773 err = EACCES;
774
775 if (kwargs != NULL)
776 python_long_from_dict(kwargs, "errno", &err);
777
778 if (!pyseccomp_filter_install(seccomp, syscall,
779 PYSECCOMP_SYSCALL_FILTER, 0, 0, SECCOMP_RET_ERRNO | (int)err))
780 return (NULL);
781
782 Py_RETURN_NONE;
783 }
784
785 static PyObject *
786 pyseccomp_deny_arg(struct pyseccomp *seccomp, PyObject *args, PyObject *kwargs)
787 {
788 return (pyseccomp_common_action(seccomp, args, kwargs,
789 PYSECCOMP_SYSCALL_ARG, PYSECCOMP_ACTION_DENY));
790 }
791
792 static PyObject *
793 pyseccomp_deny_flag(struct pyseccomp *seccomp, PyObject *args, PyObject *kwargs)
794 {
795 return (pyseccomp_common_action(seccomp, args, kwargs,
796 PYSECCOMP_SYSCALL_FLAG, PYSECCOMP_ACTION_DENY));
797 }
798
799 static PyObject *
800 pyseccomp_deny_mask(struct pyseccomp *seccomp, PyObject *args, PyObject *kwargs)
801 {
802 return (pyseccomp_common_action(seccomp, args, kwargs,
803 PYSECCOMP_SYSCALL_MASK, PYSECCOMP_ACTION_DENY));
804 }
805
806 static PyObject *
807 pyseccomp_common_action(struct pyseccomp *sc, PyObject *args,
808 PyObject *kwargs, int which, int action)
809 {
810 long err;
811 const char *syscall;
812 int arg, val;
813
814 if (!PyArg_ParseTuple(args, "sii", &syscall, &arg, &val))
815 return (NULL);
816
817 switch (action) {
818 case PYSECCOMP_ACTION_ALLOW:
819 action = SECCOMP_RET_ALLOW;
820 break;
821 case PYSECCOMP_ACTION_DENY:
822 err = EACCES;
823 if (kwargs != NULL)
824 python_long_from_dict(kwargs, "errno", &err);
825 action = SECCOMP_RET_ERRNO | (int)err;
826 break;
827 default:
828 fatal("%s: bad action %d", __func__, action);
829 }
830
831 if (!pyseccomp_filter_install(sc, syscall, which, arg, val, action))
832 return (NULL);
833
834 Py_RETURN_NONE;
835 }
836
837 static int
838 pyseccomp_filter_install(struct pyseccomp *seccomp, const char *syscall,
839 int which, int arg, int val, int action)
840 {
841 struct sock_filter *filter;
842 size_t elm, len, off;
843
844 switch (which) {
845 case PYSECCOMP_SYSCALL_FILTER:
846 filter = kore_seccomp_syscall_filter(syscall, action);
847 break;
848 case PYSECCOMP_SYSCALL_ARG:
849 filter = kore_seccomp_syscall_arg(syscall, action, arg, val);
850 break;
851 case PYSECCOMP_SYSCALL_MASK:
852 filter = kore_seccomp_syscall_mask(syscall, action, arg, val);
853 break;
854 case PYSECCOMP_SYSCALL_FLAG:
855 filter = kore_seccomp_syscall_flag(syscall, action, arg, val);
856 break;
857 default:
858 fatal("%s: invalid syscall instruction %d", __func__, which);
859 }
860
861 if (filter == NULL) {
862 PyErr_Format(PyExc_RuntimeError,
863 "system call '%s' does not exist", syscall);
864 return (KORE_RESULT_ERROR);
865 }
866
867 elm = 0;
868
869 /*
870 * Find the number of elements in the BPF program, by looking for
871 * the KORE_BPF_GUARD element.
872 */
873 for (;;) {
874 if (filter[elm].code == USHRT_MAX &&
875 filter[elm].jt == UCHAR_MAX &&
876 filter[elm].jf == UCHAR_MAX &&
877 filter[elm].k == UINT_MAX)
878 break;
879
880 elm++;
881 }
882
883 len = elm * sizeof(struct sock_filter);
884 off = seccomp->elm * sizeof(struct sock_filter);
885 seccomp->filters = kore_realloc(seccomp->filters, off + len);
886
887 memcpy(seccomp->filters + off, filter, len);
888 seccomp->elm += elm;
889
890 kore_free(filter);
891
892 return (KORE_RESULT_OK);
893 }
894 #endif
895
896 static int
897 python_long_from_dict(PyObject *dict, const char *key, long *result)
898 {
899 PyObject *obj;
900
901 if ((obj = PyDict_GetItemString(dict, key)) == NULL)
902 return (KORE_RESULT_ERROR);
903
904 if (!PyLong_CheckExact(obj))
905 return (KORE_RESULT_ERROR);
906
907 PyErr_Clear();
908 *result = PyLong_AsLong(obj);
909 if (*result == -1 && PyErr_Occurred()) {
910 PyErr_Clear();
911 return (KORE_RESULT_ERROR);
912 }
913
914 return (KORE_RESULT_OK);
915 }
916
917 static int
918 python_bool_from_dict(PyObject *dict, const char *key, int *result)
919 {
920 PyObject *obj;
921
922 if ((obj = PyDict_GetItemString(dict, key)) == NULL)
923 return (KORE_RESULT_ERROR);
924
925 if (!PyBool_Check(obj))
926 return (KORE_RESULT_ERROR);
927
928 *result = (obj == Py_True);
929
930 return (KORE_RESULT_OK);
931 }
932
933 static const char *
934 python_string_from_dict(PyObject *dict, const char *key)
935 {
936 PyObject *obj;
937
938 if ((obj = PyDict_GetItemString(dict, key)) == NULL)
939 return (NULL);
940
941 if (!PyUnicode_Check(obj))
942 return (NULL);
943
944 return (PyUnicode_AsUTF8AndSize(obj, NULL));
945 }
946
947 static PyObject *
948 python_cmsg_to_list(struct msghdr *msg)
949 {
950 struct cmsghdr *c;
951 size_t len;
952 Py_ssize_t idx;
953 PyObject *list, *tuple;
954
955 if ((list = PyList_New(0)) == NULL)
956 return (NULL);
957
958 idx = 0;
959
960 for (c = CMSG_FIRSTHDR(msg); c != NULL; c = CMSG_NXTHDR(msg, c)) {
961 len = c->cmsg_len - sizeof(*c);
962
963 tuple = Py_BuildValue("(Iiiy#)", len,
964 c->cmsg_level, c->cmsg_type, CMSG_DATA(c), len);
965
966 if (tuple == NULL) {
967 Py_DECREF(list);
968 return (NULL);
969 }
970
971 /* Steals a reference to tuple. */
972 if (PyList_Insert(list, idx++, tuple) == -1) {
973 Py_DECREF(tuple);
974 Py_DECREF(list);
975 return (NULL);
976 }
977 }
978
979 return (list);
980 }
981
982 static void *
983 python_malloc(void *ctx, size_t len)
984 {
985 return (kore_malloc(len));
986 }
987
988 static void *
989 python_calloc(void *ctx, size_t memb, size_t len)
990 {
991 return (kore_calloc(memb, len));
992 }
993
994 static void *
995 python_realloc(void *ctx, void *ptr, size_t len)
996 {
997 return (kore_realloc(ptr, len));
998 }
999
1000 static void
1001 python_free(void *ctx, void *ptr)
1002 {
1003 kore_free(ptr);
1004 }
1005
1006 static void
1007 python_module_free(struct kore_module *module)
1008 {
1009 kore_free(module->path);
1010 Py_DECREF(module->handle);
1011 kore_free(module);
1012 }
1013
1014 static void
1015 python_split_arguments(char *args, char **argv, size_t elm)
1016 {
1017 size_t idx;
1018 char *p, *line, *end;
1019
1020 if (elm <= 1)
1021 fatal("not enough elements (%zu)", elm);
1022
1023 idx = 0;
1024 line = args;
1025
1026 for (p = line; *p != '\0'; p++) {
1027 if (idx >= elm - 1)
1028 break;
1029
1030 if (*p == ' ') {
1031 *p = '\0';
1032 if (*line != '\0')
1033 argv[idx++] = line;
1034 line = p + 1;
1035 continue;
1036 }
1037
1038 if (*p != '"')
1039 continue;
1040
1041 line = p + 1;
1042 if ((end = strchr(line, '"')) == NULL)
1043 break;
1044
1045 *end = '\0';
1046 argv[idx++] = line;
1047 line = end + 1;
1048
1049 while (isspace(*(unsigned char *)line))
1050 line++;
1051
1052 p = line;
1053 }
1054
1055 if (idx < elm - 1 && *line != '\0')
1056 argv[idx++] = line;
1057
1058 argv[idx] = NULL;
1059 }
1060
1061 static void
1062 python_module_reload(struct kore_module *module)
1063 {
1064 PyObject *handle;
1065
1066 PyErr_Clear();
1067 if ((handle = PyImport_ReloadModule(module->handle)) == NULL) {
1068 kore_python_log_error("python_module_reload");
1069 return;
1070 }
1071
1072 Py_DECREF(module->handle);
1073 module->handle = handle;
1074 }
1075
1076 static void
1077 python_module_load(struct kore_module *module)
1078 {
1079 module->handle = python_import(module->path);
1080 if (module->handle == NULL)
1081 fatal("%s: failed to import module", module->path);
1082 }
1083
1084 static void *
1085 python_module_getsym(struct kore_module *module, const char *symbol)
1086 {
1087 return (python_callable(module->handle, symbol));
1088 }
1089
1090 static struct python_coro *
1091 python_coro_create(PyObject *obj, struct http_request *req)
1092 {
1093 struct python_coro *coro;
1094
1095 if (!PyCoro_CheckExact(obj))
1096 fatal("%s: object is not a coroutine", __func__);
1097
1098 coro = kore_pool_get(&coro_pool);
1099 coro_count++;
1100
1101 coro->name = NULL;
1102 coro->result = NULL;
1103 coro->sockop = NULL;
1104 coro->lockop = NULL;
1105 coro->gatherop = NULL;
1106 coro->exception = NULL;
1107 coro->exception_msg = NULL;
1108
1109 coro->obj = obj;
1110 coro->killed = 0;
1111 coro->request = req;
1112 coro->id = coro_id++;
1113 coro->state = CORO_STATE_RUNNABLE;
1114
1115 TAILQ_INSERT_TAIL(&coro_runnable, coro, list);
1116
1117 if (coro->request != NULL)
1118 http_request_sleep(coro->request);
1119
1120 python_coro_trace("created", coro);
1121
1122 return (coro);
1123 }
1124
1125 static int
1126 python_coro_run(struct python_coro *coro)
1127 {
1128 PySendResult res;
1129 PyObject *item;
1130 PyObject *type, *traceback;
1131
1132 if (coro->state != CORO_STATE_RUNNABLE)
1133 fatal("non-runnable coro attempted to run");
1134
1135 coro_running = coro;
1136
1137 for (;;) {
1138 python_coro_trace("running", coro);
1139
1140 PyErr_Clear();
1141 #if PY_VERSION_HEX < 0x030A0000
1142 res = PYGEN_RETURN;
1143 item = _PyGen_Send((PyGenObject *)coro->obj, NULL);
1144 #else
1145 /*
1146 * Python 3.10.x its PyIter_Send() will return a PYGEN_ERROR
1147 * if the coro returned (instead of yielding) and the result
1148 * ends up being Py_None. This means the returned item is
1149 * NULL but no StopIteration exception has occurred.
1150 */
1151 res = PyIter_Send(coro->obj, NULL, &item);
1152 #endif
1153 if (item == NULL || res == PYGEN_ERROR) {
1154 Py_XDECREF(item);
1155 if (coro->gatherop == NULL && PyErr_Occurred() &&
1156 PyErr_ExceptionMatches(PyExc_StopIteration)) {
1157 PyErr_Fetch(&type, &coro->result, &traceback);
1158 Py_DECREF(type);
1159 Py_XDECREF(traceback);
1160 } else if (PyErr_Occurred()) {
1161 kore_python_log_error("coroutine");
1162 if (coro->request != NULL) {
1163 http_response(coro->request,
1164 HTTP_STATUS_INTERNAL_ERROR,
1165 NULL, 0);
1166 }
1167 }
1168
1169 coro_running = NULL;
1170 return (KORE_RESULT_OK);
1171 }
1172
1173 #if PY_VERSION_HEX >= 0x030A0000
1174 if (res == PYGEN_RETURN) {
1175 coro->result = item;
1176 coro_running = NULL;
1177 return (KORE_RESULT_OK);
1178 }
1179 #endif
1180
1181 if (item == Py_None) {
1182 Py_DECREF(item);
1183 break;
1184 }
1185
1186 Py_DECREF(item);
1187 }
1188
1189 python_coro_suspend(coro);
1190 coro_running = NULL;
1191
1192 if (coro->request != NULL)
1193 http_request_sleep(coro->request);
1194
1195 return (KORE_RESULT_RETRY);
1196 }
1197
1198 static void
1199 python_coro_wakeup(struct python_coro *coro)
1200 {
1201 if (coro->state != CORO_STATE_SUSPENDED)
1202 return;
1203
1204 coro->state = CORO_STATE_RUNNABLE;
1205 TAILQ_REMOVE(&coro_suspended, coro, list);
1206 TAILQ_INSERT_TAIL(&coro_runnable, coro, list);
1207
1208 python_coro_trace("wokeup", coro);
1209 }
1210
1211 static void
1212 python_coro_suspend(struct python_coro *coro)
1213 {
1214 if (coro->state != CORO_STATE_RUNNABLE)
1215 return;
1216
1217 coro->state = CORO_STATE_SUSPENDED;
1218 TAILQ_REMOVE(&coro_runnable, coro, list);
1219 TAILQ_INSERT_TAIL(&coro_suspended, coro, list);
1220
1221 python_coro_trace("suspended", coro);
1222 }
1223
1224 static int
1225 python_resolve_frame_line(void *ptr)
1226 {
1227 int line;
1228 #if PY_VERSION_HEX >= 0x030b0000
1229 int addr;
1230 _PyInterpreterFrame *frame;
1231
1232 frame = ptr;
1233 addr = _PyInterpreterFrame_LASTI(frame) * sizeof(_Py_CODEUNIT);
1234 line = PyCode_Addr2Line(_PyFrame_GetCode(frame), addr);
1235 #else
1236 line = PyFrame_GetLineNumber(ptr);
1237 #endif
1238
1239 return (line);
1240 }
1241
1242 static void
1243 python_coro_trace(const char *label, struct python_coro *coro)
1244 {
1245 int line;
1246 PyCoroObject *obj;
1247 PyCodeObject *code;
1248 #if PY_VERSION_HEX >= 0x030b0000
1249 _PyInterpreterFrame *frame;
1250 #else
1251 PyFrameObject *frame;
1252 #endif
1253 const char *func, *fname, *file;
1254
1255 if (coro_tracing == 0)
1256 return;
1257
1258 obj = (PyCoroObject *)coro->obj;
1259
1260 #if PY_VERSION_HEX >= 0x030e0000
1261 frame = (_PyInterpreterFrame *)&obj->cr_iframe;
1262 #elif PY_VERSION_HEX >= 0x030b0000
1263 frame = (_PyInterpreterFrame *)obj->cr_iframe;
1264 #else
1265 frame = obj->cr_frame;
1266 #endif
1267 if (frame != NULL && _PyFrame_GetCode(frame) != NULL) {
1268 code = _PyFrame_GetCode(frame);
1269 func = PyUnicode_AsUTF8AndSize(code->co_name, NULL);
1270 file = PyUnicode_AsUTF8AndSize(code->co_filename, NULL);
1271
1272 if ((fname = strrchr(file, '/')) == NULL)
1273 fname = file;
1274 else
1275 fname++;
1276 } else {
1277 func = "unknown";
1278 fname = "unknown";
1279 }
1280
1281 if (frame != NULL)
1282 line = python_resolve_frame_line(frame);
1283 else
1284 line = -1;
1285
1286 if (coro->name) {
1287 kore_log(LOG_NOTICE, "coro '%s' %s <%s> @ [%s:%d]",
1288 coro->name, label, func, fname, line);
1289 } else {
1290 kore_log(LOG_NOTICE, "coro %" PRIu64 " %s <%s> @ [%s:%d]",
1291 coro->id, label, func, fname, line);
1292 }
1293 }
1294
1295 static void
1296 pyconnection_dealloc(struct pyconnection *pyc)
1297 {
1298 PyObject_Del((PyObject *)pyc);
1299 }
1300
1301 static void
1302 pyhttp_dealloc(struct pyhttp_request *pyreq)
1303 {
1304 Py_XDECREF(pyreq->dict);
1305 Py_XDECREF(pyreq->data);
1306 PyObject_Del((PyObject *)pyreq);
1307 }
1308
1309 static void
1310 pyhttp_file_dealloc(struct pyhttp_file *pyfile)
1311 {
1312 PyObject_Del((PyObject *)pyfile);
1313 }
1314
1315 static int
1316 python_runtime_resolve(const char *module, const struct stat *st)
1317 {
1318 const char *ext;
1319
1320 if (!S_ISDIR(st->st_mode) && !S_ISREG(st->st_mode))
1321 return (KORE_RESULT_ERROR);
1322
1323 if (S_ISDIR(st->st_mode)) {
1324 kore_module_load(module, NULL, KORE_MODULE_PYTHON);
1325 if (chdir(module) == -1)
1326 fatal("chdir(%s): %s", module, errno_s);
1327 } else {
1328 if ((ext = strrchr(module, '.')) == NULL)
1329 return (KORE_RESULT_ERROR);
1330
1331 if (strcasecmp(ext, ".py"))
1332 return (KORE_RESULT_ERROR);
1333
1334 kore_module_load(module, NULL, KORE_MODULE_PYTHON);
1335 }
1336
1337 #if !defined(KORE_SINGLE_BINARY)
1338 kore_pymodule = module;
1339 #endif
1340
1341 kore_hooks_set(KORE_PYTHON_CONFIG_HOOK,
1342 KORE_PYTHON_TEARDOWN_HOOK, KORE_PYTHON_DAEMONIZED_HOOK);
1343
1344 return (KORE_RESULT_OK);
1345 }
1346
1347 static int
1348 python_runtime_http_request(void *addr, struct http_request *req)
1349 {
1350 int ret, idx, cnt;
1351 PyObject *pyret, *args, *callable;
1352 PyObject *cargs[HTTP_CAPTURE_GROUPS + 1];
1353
1354 if (req->py_coro != NULL) {
1355 python_coro_wakeup(req->py_coro);
1356 if (python_coro_run(req->py_coro) == KORE_RESULT_OK) {
1357 kore_python_coro_delete(req->py_coro);
1358 req->py_coro = NULL;
1359
1360 if (req->fsm_state != PYHTTP_STATE_PREPROCESS)
1361 return (KORE_RESULT_OK);
1362 }
1363 return (KORE_RESULT_RETRY);
1364 }
1365
1366 switch (req->fsm_state) {
1367 case PYHTTP_STATE_INIT:
1368 req->py_rqnext = TAILQ_FIRST(&prereq);
1369 req->fsm_state = PYHTTP_STATE_PREPROCESS;
1370 if (req->py_req == NULL) {
1371 if ((req->py_req = pyhttp_request_alloc(req)) == NULL)
1372 fatal("%s: pyreq alloc failed", __func__);
1373 }
1374 /* fallthrough */
1375 case PYHTTP_STATE_PREPROCESS:
1376 ret = pyhttp_preprocess(req);
1377 switch (ret) {
1378 case KORE_RESULT_OK:
1379 req->fsm_state = PYHTTP_STATE_RUN;
1380 break;
1381 case KORE_RESULT_RETRY:
1382 return (KORE_RESULT_RETRY);
1383 case KORE_RESULT_ERROR:
1384 return (KORE_RESULT_OK);
1385 default:
1386 fatal("invalid state pyhttp state %d", req->fsm_state);
1387 }
1388 /* fallthrough */
1389 case PYHTTP_STATE_RUN:
1390 break;
1391 }
1392
1393 cnt = 0;
1394 callable = (PyObject *)addr;
1395
1396 /* starts at 1 to skip the full path. */
1397 if (req->rt->type == HANDLER_TYPE_DYNAMIC) {
1398 for (idx = 1; idx < HTTP_CAPTURE_GROUPS - 1; idx++) {
1399 if (req->cgroups[idx].rm_so == -1 ||
1400 req->cgroups[idx].rm_eo == -1)
1401 break;
1402
1403 cargs[cnt] = PyUnicode_FromStringAndSize(req->path +
1404 req->cgroups[idx].rm_so,
1405 req->cgroups[idx].rm_eo - req->cgroups[idx].rm_so);
1406
1407 if (cargs[cnt] == NULL) {
1408 while (cnt >= 0)
1409 Py_XDECREF(cargs[cnt--]);
1410 kore_python_log_error("http request");
1411 http_response(req,
1412 HTTP_STATUS_INTERNAL_ERROR, NULL, 0);
1413 return (KORE_RESULT_OK);
1414 }
1415
1416 cnt++;
1417 }
1418 }
1419
1420 cargs[cnt] = NULL;
1421
1422 if ((args = PyTuple_New(cnt + 1)) == NULL)
1423 fatal("%s: PyTuple_New failed", __func__);
1424
1425 Py_INCREF(req->py_req);
1426 if (PyTuple_SetItem(args, 0, req->py_req) != 0)
1427 fatal("python_runtime_http_request: PyTuple_SetItem failed");
1428
1429 for (idx = 0; cargs[idx] != NULL; idx++) {
1430 if (PyTuple_SetItem(args, 1 + idx, cargs[idx]) != 0)
1431 fatal("%s: PyTuple_SetItem failed (%d)", __func__, idx);
1432 }
1433
1434 PyErr_Clear();
1435 pyret = PyObject_Call(callable, args, NULL);
1436 Py_DECREF(args);
1437
1438 if (pyret == NULL) {
1439 kore_python_log_error("python_runtime_http_request");
1440 http_response(req, HTTP_STATUS_INTERNAL_ERROR, NULL, 0);
1441 return (KORE_RESULT_OK);
1442 }
1443
1444 if (PyCoro_CheckExact(pyret)) {
1445 req->py_coro = python_coro_create(pyret, req);
1446 if (python_coro_run(req->py_coro) == KORE_RESULT_OK) {
1447 http_request_wakeup(req);
1448 kore_python_coro_delete(req->py_coro);
1449 req->py_coro = NULL;
1450 return (KORE_RESULT_OK);
1451 }
1452 return (KORE_RESULT_RETRY);
1453 }
1454
1455 if (pyret != Py_None)
1456 fatal("python_runtime_http_request: unexpected return type");
1457
1458 Py_DECREF(pyret);
1459
1460 return (KORE_RESULT_OK);
1461 }
1462
1463 static void
1464 python_runtime_http_request_free(void *addr, struct http_request *req)
1465 {
1466 PyObject *ret;
1467
1468 if (req->py_req == NULL) {
1469 if ((req->py_req = pyhttp_request_alloc(req)) == NULL)
1470 fatal("%s: pyreq alloc failed", __func__);
1471 }
1472
1473 PyErr_Clear();
1474 ret = PyObject_CallFunctionObjArgs(addr, req->py_req, NULL);
1475
1476 if (ret == NULL)
1477 kore_python_log_error("python_runtime_http_request_free");
1478
1479 Py_XDECREF(ret);
1480 }
1481
1482 static int
1483 python_runtime_http_body_chunk(void *addr, struct http_request *req,
1484 const void *data, size_t len)
1485 {
1486 int result;
1487 PyObject *args, *ret;
1488
1489 if (req->py_req == NULL) {
1490 if ((req->py_req = pyhttp_request_alloc(req)) == NULL)
1491 fatal("%s: pyreq alloc failed", __func__);
1492 }
1493
1494 if ((args = Py_BuildValue("(Oy#)", req->py_req, data, len)) == NULL) {
1495 kore_python_log_error("python_runtime_http_body_chunk");
1496 return (KORE_RESULT_ERROR);
1497 }
1498
1499 PyErr_Clear();
1500 ret = PyObject_Call(addr, args, NULL);
1501
1502 if (ret == NULL)
1503 kore_python_log_error("python_runtime_http_body_chunk");
1504
1505 if (ret == Py_True)
1506 result = KORE_RESULT_OK;
1507 else
1508 result = KORE_RESULT_ERROR;
1509
1510 Py_XDECREF(ret);
1511 Py_DECREF(args);
1512
1513 return (result);
1514 }
1515
1516 static int
1517 python_runtime_validator(void *addr, struct http_request *req, const void *data)
1518 {
1519 int ret;
1520 struct python_coro *coro;
1521 PyObject *pyret, *args, *callable, *arg;
1522
1523 if (req->py_req == NULL) {
1524 if ((req->py_req = pyhttp_request_alloc(req)) == NULL)
1525 fatal("%s: pyreq alloc failed", __func__);
1526 }
1527
1528 if (req->py_validator != NULL) {
1529 coro = req->py_validator;
1530 python_coro_wakeup(coro);
1531 if (python_coro_run(coro) == KORE_RESULT_OK) {
1532 ret = python_validator_check(coro->result);
1533 kore_python_coro_delete(coro);
1534 req->py_validator = NULL;
1535 return (ret);
1536 }
1537
1538 return (KORE_RESULT_RETRY);
1539 }
1540
1541 callable = (PyObject *)addr;
1542
1543 if (req->flags & HTTP_VALIDATOR_IS_REQUEST) {
1544 if ((args = PyTuple_New(1)) == NULL)
1545 fatal("%s: PyTuple_New failed", __func__);
1546
1547 Py_INCREF(req->py_req);
1548 if (PyTuple_SetItem(args, 0, req->py_req) != 0)
1549 fatal("%s: PyTuple_SetItem failed", __func__);
1550 } else {
1551 if ((arg = PyUnicode_FromString(data)) == NULL)
1552 fatal("python_runtime_validator: PyUnicode failed");
1553
1554 if ((args = PyTuple_New(2)) == NULL)
1555 fatal("%s: PyTuple_New failed", __func__);
1556
1557 Py_INCREF(req->py_req);
1558 if (PyTuple_SetItem(args, 0, req->py_req) != 0 ||
1559 PyTuple_SetItem(args, 1, arg) != 0)
1560 fatal("%s: PyTuple_SetItem failed", __func__);
1561 }
1562
1563 PyErr_Clear();
1564 pyret = PyObject_Call(callable, args, NULL);
1565 Py_DECREF(args);
1566
1567 if (pyret == NULL) {
1568 kore_python_log_error("python_runtime_validator");
1569 fatal("failed to execute python call");
1570 }
1571
1572 if (PyCoro_CheckExact(pyret)) {
1573 coro = python_coro_create(pyret, req);
1574 req->py_validator = coro;
1575 if (python_coro_run(coro) == KORE_RESULT_OK) {
1576 http_request_wakeup(req);
1577 ret = python_validator_check(coro->result);
1578 kore_python_coro_delete(coro);
1579 req->py_validator = NULL;
1580 return (ret);
1581 }
1582 return (KORE_RESULT_RETRY);
1583 }
1584
1585 ret = python_validator_check(pyret);
1586 Py_DECREF(pyret);
1587
1588 return (ret);
1589 }
1590
1591 static int
1592 python_validator_check(PyObject *obj)
1593 {
1594 int ret;
1595
1596 if (obj == NULL)
1597 return (KORE_RESULT_ERROR);
1598
1599 if (!PyBool_Check(obj)) {
1600 kore_log(LOG_WARNING,
1601 "validator did not return True/False");
1602 ret = KORE_RESULT_ERROR;
1603 }
1604
1605 if (obj == Py_True)
1606 ret = KORE_RESULT_OK;
1607 else
1608 ret = KORE_RESULT_ERROR;
1609
1610 return (ret);
1611 }
1612
1613 static void
1614 python_runtime_wsmessage(void *addr, struct connection *c, u_int8_t op,
1615 const void *data, size_t len)
1616 {
1617 PyObject *callable, *args, *pyret, *pyc, *pyop, *pydata;
1618
1619 callable = (PyObject *)addr;
1620
1621 if ((pyc = pyconnection_alloc(c)) == NULL)
1622 fatal("python_runtime_wsmessage: pyc alloc failed");
1623
1624 if ((pyop = PyLong_FromLong((long)op)) == NULL)
1625 fatal("python_runtime_wsmessage: PyLong_FromLong failed");
1626
1627 switch (op) {
1628 case WEBSOCKET_OP_TEXT:
1629 if ((pydata = PyUnicode_FromStringAndSize(data, len)) == NULL)
1630 fatal("wsmessage: PyUnicode_AsUTF8AndSize failed");
1631 break;
1632 case WEBSOCKET_OP_BINARY:
1633 if ((pydata = PyBytes_FromStringAndSize(data, len)) == NULL)
1634 fatal("wsmessage: PyBytes_FromString failed");
1635 break;
1636 default:
1637 fatal("python_runtime_wsmessage: invalid op");
1638 }
1639
1640 if ((args = PyTuple_New(3)) == NULL)
1641 fatal("python_runtime_wsmessage: PyTuple_New failed");
1642
1643 if (PyTuple_SetItem(args, 0, pyc) != 0 ||
1644 PyTuple_SetItem(args, 1, pyop) != 0 ||
1645 PyTuple_SetItem(args, 2, pydata) != 0)
1646 fatal("python_runtime_wsmessage: PyTuple_SetItem failed");
1647
1648 PyErr_Clear();
1649 pyret = PyObject_Call(callable, args, NULL);
1650 Py_DECREF(args);
1651
1652 if (pyret == NULL) {
1653 kore_python_log_error("python_runtime_wsconnect");
1654 fatal("failed to execute python call");
1655 }
1656
1657 Py_DECREF(pyret);
1658 }
1659
1660 static void
1661 python_runtime_execute(void *addr)
1662 {
1663 PyObject *callable, *args, *pyret;
1664
1665 callable = (PyObject *)addr;
1666
1667 if ((args = PyTuple_New(0)) == NULL)
1668 fatal("python_runtime_execute: PyTuple_New failed");
1669
1670 PyErr_Clear();
1671 pyret = PyObject_Call(callable, args, NULL);
1672 Py_DECREF(args);
1673
1674 if (pyret == NULL) {
1675 kore_python_log_error("python_runtime_execute");
1676 fatal("failed to execute python call");
1677 }
1678
1679 Py_DECREF(pyret);
1680 }
1681
1682 static void
1683 python_runtime_configure(void *addr, int argc, char **argv)
1684 {
1685 int i;
1686 PyObject *callable, *args, *pyret, *pyarg, *list;
1687
1688 callable = (PyObject *)addr;
1689
1690 if ((args = PyTuple_New(1)) == NULL)
1691 fatal("python_runtime_configure: PyTuple_New failed");
1692
1693 if ((list = PyList_New(argc + 1)) == NULL)
1694 fatal("python_runtime_configure: PyList_New failed");
1695
1696 if ((pyarg = PyUnicode_FromString(__progname)) == NULL)
1697 fatal("python_runtime_configure: PyUnicode_FromString");
1698
1699 if (PyList_SetItem(list, 0, pyarg) == -1)
1700 fatal("python_runtime_configure: PyList_SetItem");
1701
1702 for (i = 0; i < argc; i++) {
1703 if ((pyarg = PyUnicode_FromString(argv[i])) == NULL)
1704 fatal("python_runtime_configure: PyUnicode_FromString");
1705
1706 if (PyList_SetItem(list, i + 1, pyarg) == -1)
1707 fatal("python_runtime_configure: PyList_SetItem");
1708 }
1709
1710 if (PyTuple_SetItem(args, 0, list) != 0)
1711 fatal("python_runtime_configure: PyTuple_SetItem");
1712
1713 PyErr_Clear();
1714 pyret = PyObject_Call(callable, args, NULL);
1715 Py_DECREF(args);
1716
1717 if (pyret == NULL) {
1718 kore_python_log_error("python_runtime_configure");
1719 fatal("failed to configure your application");
1720 }
1721
1722 Py_DECREF(pyret);
1723 }
1724
1725 static int
1726 python_runtime_onload(void *addr, int action)
1727 {
1728 int ret;
1729 PyObject *pyret, *args, *pyact, *callable;
1730
1731 callable = (PyObject *)addr;
1732
1733 if ((pyact = PyLong_FromLong(action)) == NULL)
1734 fatal("python_runtime_onload: PyLong_FromLong failed");
1735
1736 if ((args = PyTuple_New(1)) == NULL)
1737 fatal("python_runtime_onload: PyTuple_New failed");
1738
1739 if (PyTuple_SetItem(args, 0, pyact) != 0)
1740 fatal("python_runtime_onload: PyTuple_SetItem failed");
1741
1742 PyErr_Clear();
1743 pyret = PyObject_Call(callable, args, NULL);
1744 Py_DECREF(args);
1745
1746 if (pyret == NULL) {
1747 kore_python_log_error("python_runtime_onload");
1748 return (KORE_RESULT_ERROR);
1749 }
1750
1751 if (!PyLong_Check(pyret))
1752 fatal("python_runtime_onload: unexpected return type");
1753
1754 ret = (int)PyLong_AsLong(pyret);
1755 Py_DECREF(pyret);
1756
1757 return (ret);
1758 }
1759
1760 static void
1761 python_runtime_connect(void *addr, struct connection *c)
1762 {
1763 PyObject *pyc, *pyret, *args, *callable;
1764
1765 callable = (PyObject *)addr;
1766
1767 if ((pyc = pyconnection_alloc(c)) == NULL)
1768 fatal("python_runtime_connect: pyc alloc failed");
1769
1770 if ((args = PyTuple_New(1)) == NULL)
1771 fatal("python_runtime_connect: PyTuple_New failed");
1772
1773 if (PyTuple_SetItem(args, 0, pyc) != 0)
1774 fatal("python_runtime_connect: PyTuple_SetItem failed");
1775
1776 PyErr_Clear();
1777 pyret = PyObject_Call(callable, args, NULL);
1778 Py_DECREF(args);
1779
1780 if (pyret == NULL) {
1781 kore_python_log_error("python_runtime_connect");
1782 kore_connection_disconnect(c);
1783 }
1784
1785 Py_DECREF(pyret);
1786 }
1787
1788 static void
1789 python_runtime_signal(void *addr, int sig)
1790 {
1791 PyObject *obj, *ret;
1792
1793 if ((obj = Py_BuildValue("i", sig)) == NULL) {
1794 kore_python_log_error("python_runtime_signal");
1795 return;
1796 }
1797
1798 ret = PyObject_CallFunctionObjArgs(addr, obj, NULL);
1799
1800 Py_DECREF(obj);
1801 Py_XDECREF(ret);
1802 }
1803
1804 PyMODINIT_FUNC
1805 python_module_init(void)
1806 {
1807 int i;
1808 struct pyconfig *config;
1809 PyObject *pykore;
1810
1811 if ((pykore = PyModule_Create(&pykore_module)) == NULL)
1812 fatal("python_module_init: failed to setup pykore module");
1813
1814 python_push_type("pyproc", pykore, &pyproc_type);
1815 python_push_type("pylock", pykore, &pylock_type);
1816 python_push_type("pytimer", pykore, &pytimer_type);
1817 python_push_type("pyqueue", pykore, &pyqueue_type);
1818 python_push_type("pyroute", pykore, &pyroute_type);
1819 python_push_type("pysocket", pykore, &pysocket_type);
1820 python_push_type("pydomain", pykore, &pydomain_type);
1821 python_push_type("pyconnection", pykore, &pyconnection_type);
1822
1823 #if defined(__linux__)
1824 python_push_type("pyseccomp", pykore, &pyseccomp_type);
1825 #endif
1826
1827 #if defined(KORE_USE_CURL)
1828 python_push_type("pycurlhandle", pykore, &pycurl_handle_type);
1829 python_push_type("pyhttpclient", pykore, &pyhttp_client_type);
1830
1831 for (i = 0; py_curlopt[i].name != NULL; i++) {
1832 python_push_integer(pykore, py_curlopt[i].name,
1833 py_curlopt[i].value);
1834 }
1835 #endif
1836
1837 python_push_type("pyhttp_file", pykore, &pyhttp_file_type);
1838 python_push_type("pyhttp_request", pykore, &pyhttp_request_type);
1839
1840 for (i = 0; python_integers[i].symbol != NULL; i++) {
1841 python_push_integer(pykore, python_integers[i].symbol,
1842 python_integers[i].value);
1843 }
1844
1845 if ((config = PyObject_New(struct pyconfig, &pyconfig_type)) == NULL)
1846 fatal("failed to create config object");
1847
1848 if (PyObject_SetAttrString(pykore, "config", (PyObject *)config) == -1)
1849 fatal("failed to add config object");
1850
1851 return (pykore);
1852 }
1853
1854 static int
1855 pyconfig_setattr(PyObject *self, PyObject *attr, PyObject *val)
1856 {
1857 char *v;
1858 int ret;
1859 PyObject *repr;
1860 const char *name, *value;
1861
1862 ret = -1;
1863 repr = NULL;
1864
1865 if (!PyUnicode_Check(attr))
1866 fatal("setattr: attribute name not a unicode string");
1867
1868 if (PyLong_CheckExact(val)) {
1869 if ((repr = PyObject_Repr(val)) == NULL)
1870 return (-1);
1871 value = PyUnicode_AsUTF8(repr);
1872 } else if (PyUnicode_CheckExact(val)) {
1873 value = PyUnicode_AsUTF8(val);
1874 } else if (PyBool_Check(val)) {
1875 if (val == Py_False)
1876 value = "False";
1877 else
1878 value = "True";
1879 } else {
1880 fatal("invalid object, config expects integer, bool or string");
1881 }
1882
1883 name = PyUnicode_AsUTF8(attr);
1884 v = kore_strdup(value);
1885
1886 if (!kore_configure_setting(name, v)) {
1887 ret = -1;
1888 PyErr_SetString(PyExc_RuntimeError,
1889 "configured cannot be changed at runtime");
1890 } else {
1891 ret = 0;
1892 }
1893
1894 kore_free(v);
1895
1896 Py_XDECREF(repr);
1897
1898 return (ret);
1899 }
1900
1901 static void
1902 python_append_path(const char *path)
1903 {
1904 PyObject *mpath, *spath;
1905
1906 if ((mpath = PyUnicode_FromString(path)) == NULL)
1907 fatal("python_append_path: PyUnicode_FromString failed");
1908
1909 if ((spath = PySys_GetObject("path")) == NULL)
1910 fatal("python_append_path: PySys_GetObject failed");
1911
1912 PyList_Append(spath, mpath);
1913 Py_DECREF(mpath);
1914 }
1915
1916 static void
1917 python_push_type(const char *name, PyObject *module, PyTypeObject *type)
1918 {
1919 if (PyType_Ready(type) == -1)
1920 fatal("python_push_type: failed to ready %s", name);
1921
1922 Py_INCREF(type);
1923
1924 if (PyModule_AddObject(module, name, (PyObject *)type) == -1)
1925 fatal("python_push_type: failed to push %s", name);
1926 }
1927
1928 static void
1929 python_push_integer(PyObject *module, const char *name, long value)
1930 {
1931 if (PyModule_AddIntConstant(module, name, value) == -1)
1932 fatal("python_push_integer: failed to add %s", name);
1933 }
1934
1935 #if defined(KORE_USE_PGSQL)
1936 static PyObject *
1937 python_kore_pgsql_register(PyObject *self, PyObject *args)
1938 {
1939 const char *db, *conninfo;
1940
1941 if (!PyArg_ParseTuple(args, "ss", &db, &conninfo))
1942 return (NULL);
1943
1944 (void)kore_pgsql_register(db, conninfo);
1945
1946 Py_RETURN_TRUE;
1947 }
1948 #endif
1949
1950 static PyObject *
1951 python_kore_app(PyObject *self, PyObject *args)
1952 {
1953 PyObject *obj;
1954
1955 if (!PyArg_ParseTuple(args, "O", &obj)) {
1956 PyErr_Clear();
1957
1958 if (kore_app == NULL)
1959 Py_RETURN_NONE;
1960
1961 Py_INCREF(kore_app);
1962 return (kore_app);
1963 }
1964
1965 Py_XDECREF(kore_app);
1966
1967 kore_app = obj;
1968 Py_INCREF(kore_app);
1969
1970 Py_RETURN_TRUE;
1971 }
1972
1973 static PyObject *
1974 python_kore_log(PyObject *self, PyObject *args)
1975 {
1976 int prio;
1977 const char *message;
1978
1979 if (!PyArg_ParseTuple(args, "is", &prio, &message))
1980 return (NULL);
1981
1982 kore_log(prio, "%s", message);
1983
1984 Py_RETURN_TRUE;
1985 }
1986
1987 static PyObject *
1988 python_kore_time(PyObject *self, PyObject *args)
1989 {
1990 u_int64_t now;
1991
1992 now = kore_time_ms();
1993
1994 return (PyLong_FromUnsignedLongLong(now));
1995 }
1996
1997 static PyObject *
1998 python_kore_server(PyObject *self, PyObject *args, PyObject *kwargs)
1999 {
2000 struct kore_server *srv;
2001 const char *name, *ip, *port, *path;
2002
2003 if (kwargs == NULL) {
2004 PyErr_SetString(PyExc_RuntimeError, "missing keyword args");
2005 return (NULL);
2006 }
2007
2008 ip = python_string_from_dict(kwargs, "ip");
2009 path = python_string_from_dict(kwargs, "path");
2010
2011 if (ip == NULL && path == NULL) {
2012 PyErr_SetString(PyExc_RuntimeError,
2013 "missing ip or path keywords");
2014 return (NULL);
2015 }
2016
2017 if (ip != NULL && path != NULL) {
2018 PyErr_SetString(PyExc_RuntimeError, "ip/path are exclusive");
2019 return (NULL);
2020 }
2021
2022 name = python_string_from_dict(kwargs, "name");
2023 if (name == NULL)
2024 name = "default";
2025
2026 if ((srv = kore_server_lookup(name)) != NULL) {
2027 PyErr_Format(PyExc_RuntimeError,
2028 "server '%s' already exist", name);
2029 return (NULL);
2030 }
2031
2032 srv = kore_server_create(name);
2033 python_bool_from_dict(kwargs, "tls", &srv->tls);
2034
2035 if (srv->tls && !kore_tls_supported()) {
2036 kore_server_free(srv);
2037 PyErr_SetString(PyExc_RuntimeError,
2038 "TLS not supported in this Kore build");
2039 return (NULL);
2040 }
2041
2042 if (ip != NULL) {
2043 if ((port = python_string_from_dict(kwargs, "port")) == NULL) {
2044 kore_server_free(srv);
2045 PyErr_SetString(PyExc_RuntimeError,
2046 "missing or invalid 'port' keyword");
2047 return (NULL);
2048 }
2049
2050 if (!kore_server_bind(srv, ip, port, NULL)) {
2051 PyErr_Format(PyExc_RuntimeError,
2052 "failed to bind to '%s:%s'", ip, port);
2053 return (NULL);
2054 }
2055 } else {
2056 if (!kore_server_bind_unix(srv, path, NULL)) {
2057 PyErr_Format(PyExc_RuntimeError,
2058 "failed to bind to '%s'", path);
2059 return (NULL);
2060 }
2061 }
2062
2063 kore_server_finalize(srv);
2064
2065 Py_RETURN_NONE;
2066 }
2067
2068 static PyObject *
2069 python_kore_privsep(PyObject *self, PyObject *args, PyObject *kwargs)
2070 {
2071 struct kore_privsep *ps;
2072 const char *val;
2073 PyObject *skip, *obj;
2074 Py_ssize_t list_len, idx;
2075
2076 if (!PyArg_ParseTuple(args, "s", &val))
2077 return (NULL);
2078
2079 if (!strcmp(val, "worker")) {
2080 ps = &worker_privsep;
2081 } else if (!strcmp(val, "keymgr")) {
2082 ps = &keymgr_privsep;
2083 #if defined(KORE_USE_ACME)
2084 } else if (!strcmp(val, "acme")) {
2085 ps = &acme_privsep;
2086 #endif
2087 } else {
2088 PyErr_Format(PyExc_RuntimeError,
2089 "unknown privsep process '%s'", val);
2090 return (NULL);
2091 }
2092
2093 if ((val = python_string_from_dict(kwargs, "root")) != NULL) {
2094 kore_free(ps->root);
2095 ps->root = kore_strdup(val);
2096 }
2097
2098 if ((val = python_string_from_dict(kwargs, "runas")) != NULL) {
2099 kore_free(ps->runas);
2100 ps->runas = kore_strdup(val);
2101 }
2102
2103 if ((skip = PyDict_GetItemString(kwargs, "skip")) != NULL) {
2104 if (!PyList_CheckExact(skip)) {
2105 PyErr_Format(PyExc_RuntimeError,
2106 "privsep skip keyword needs to be a list");
2107 return (NULL);
2108 }
2109
2110 list_len = PyList_Size(skip);
2111
2112 for (idx = 0; idx < list_len; idx++) {
2113 if ((obj = PyList_GetItem(skip, idx)) == NULL)
2114 return (NULL);
2115
2116 if (!PyUnicode_Check(obj))
2117 return (NULL);
2118
2119 if ((val = PyUnicode_AsUTF8AndSize(obj, NULL)) == NULL)
2120 return (NULL);
2121
2122 if (!strcmp(val, "chroot")) {
2123 ps->skip_chroot = 1;
2124 } else {
2125 PyErr_Format(PyExc_RuntimeError,
2126 "unknown skip keyword '%s'", val);
2127 return (NULL);
2128 }
2129 }
2130 }
2131
2132 Py_RETURN_NONE;
2133 }
2134
2135 static PyObject *
2136 python_kore_prerequest(PyObject *self, PyObject *args)
2137 {
2138 PyObject *f;
2139 struct reqcall *rq;
2140
2141 if (!PyArg_ParseTuple(args, "O", &f))
2142 return (NULL);
2143
2144 rq = kore_calloc(1, sizeof(*rq));
2145 rq->f = f;
2146
2147 Py_INCREF(f);
2148 TAILQ_INSERT_TAIL(&prereq, rq, list);
2149
2150 return (f);
2151 }
2152
2153 static PyObject *
2154 python_kore_task_create(PyObject *self, PyObject *args)
2155 {
2156 PyObject *obj;
2157 struct python_coro *coro;
2158
2159 if (!PyArg_ParseTuple(args, "O", &obj))
2160 return (NULL);
2161
2162 if (!PyCoro_CheckExact(obj))
2163 fatal("%s: object is not a coroutine", __func__);
2164
2165 coro = python_coro_create(obj, NULL);
2166 Py_INCREF(obj);
2167
2168 return (PyLong_FromUnsignedLongLong(coro->id));
2169 }
2170
2171 static PyObject *
2172 python_kore_task_id(PyObject *self, PyObject *args)
2173 {
2174 if (coro_running == NULL) {
2175 PyErr_SetString(PyExc_RuntimeError,
2176 "no coroutine active");
2177 return (NULL);
2178 }
2179
2180 return (PyLong_FromUnsignedLongLong(coro_running->id));
2181 }
2182
2183 static PyObject *
2184 python_kore_task_kill(PyObject *self, PyObject *args)
2185 {
2186 u_int64_t id;
2187 struct python_coro *coro, *active;
2188
2189 if (!PyArg_ParseTuple(args, "K", &id))
2190 return (NULL);
2191
2192 if (coro_running != NULL && coro_running->id == id) {
2193 PyErr_SetString(PyExc_RuntimeError,
2194 "refusing to kill active coroutine");
2195 return (NULL);
2196 }
2197
2198 /* Remember active coro, as delete sets coro_running to NULL. */
2199 active = coro_running;
2200
2201 TAILQ_FOREACH(coro, &coro_runnable, list) {
2202 if (coro->id == id) {
2203 coro->killed++;
2204 kore_python_coro_delete(coro);
2205 coro_running = active;
2206 Py_RETURN_TRUE;
2207 }
2208 }
2209
2210 TAILQ_FOREACH(coro, &coro_suspended, list) {
2211 if (coro->id == id) {
2212 coro->killed++;
2213 kore_python_coro_delete(coro);
2214 coro_running = active;
2215 Py_RETURN_TRUE;
2216 }
2217 }
2218
2219 Py_RETURN_FALSE;
2220 }
2221
2222 static PyObject *
2223 python_kore_socket_wrap(PyObject *self, PyObject *args)
2224 {
2225 struct pysocket *sock;
2226 PyObject *pysock, *pyfd, *pyfam, *pyproto;
2227
2228 sock = NULL;
2229 pyfd = NULL;
2230 pyfam = NULL;
2231 pyproto = NULL;
2232
2233 if (!PyArg_ParseTuple(args, "O", &pysock))
2234 return (NULL);
2235
2236 if ((pyfd = PyObject_CallMethod(pysock, "fileno", NULL)) == NULL)
2237 return (NULL);
2238
2239 if ((pyfam = PyObject_GetAttrString(pysock, "family")) == NULL)
2240 goto out;
2241
2242 if ((pyproto = PyObject_GetAttrString(pysock, "proto")) == NULL)
2243 goto out;
2244
2245 if ((sock = pysocket_alloc()) == NULL)
2246 goto out;
2247
2248 sock->socket = pysock;
2249 Py_INCREF(sock->socket);
2250
2251 sock->fd = (int)PyLong_AsLong(pyfd);
2252 sock->family = (int)PyLong_AsLong(pyfam);
2253 sock->protocol = (int)PyLong_AsLong(pyproto);
2254
2255 memset(&sock->addr, 0, sizeof(sock->addr));
2256
2257 switch (sock->family) {
2258 case AF_INET:
2259 case AF_UNIX:
2260 break;
2261 default:
2262 PyErr_SetString(PyExc_RuntimeError, "unsupported family");
2263 Py_DECREF((PyObject *)sock);
2264 sock = NULL;
2265 goto out;
2266 }
2267
2268 out:
2269 Py_XDECREF(pyfd);
2270 Py_XDECREF(pyfam);
2271 Py_XDECREF(pyproto);
2272
2273 return ((PyObject *)sock);
2274 }
2275
2276 static PyObject *
2277 python_kore_queue(PyObject *self, PyObject *args)
2278 {
2279 struct pyqueue *queue;
2280
2281 if ((queue = PyObject_New(struct pyqueue, &pyqueue_type)) == NULL)
2282 return (NULL);
2283
2284 TAILQ_INIT(&queue->objects);
2285 TAILQ_INIT(&queue->waiting);
2286
2287 return ((PyObject *)queue);
2288 }
2289
2290 static PyObject *
2291 python_kore_worker(PyObject *self, PyObject *args)
2292 {
2293 if (worker == NULL) {
2294 Py_RETURN_NONE;
2295 }
2296
2297 return (PyLong_FromLong(worker->id));
2298 }
2299
2300 static PyObject *
2301 python_kore_tracer(PyObject *self, PyObject *args)
2302 {
2303 PyObject *obj;
2304
2305 if (python_tracer != NULL) {
2306 PyErr_SetString(PyExc_RuntimeError, "tracer already set");
2307 return (NULL);
2308 }
2309
2310 if (!PyArg_ParseTuple(args, "O", &obj))
2311 return (NULL);
2312
2313 if (!PyCallable_Check(obj)) {
2314 PyErr_SetString(PyExc_RuntimeError, "object not callable");
2315 Py_DECREF(obj);
2316 return (NULL);
2317 }
2318
2319 Py_INCREF(obj);
2320 python_tracer = obj;
2321
2322 Py_RETURN_TRUE;
2323 }
2324
2325 static PyObject *
2326 python_kore_domain(PyObject *self, PyObject *args, PyObject *kwargs)
2327 {
2328 #if defined(KORE_USE_ACME)
2329 int acme;
2330 char *acert, *akey;
2331 #endif
2332 struct kore_server *srv;
2333 long depth;
2334 const char *name;
2335 struct pydomain *domain;
2336 const char *cert, *key, *ca, *attach, *crl;
2337
2338 ca = NULL;
2339 depth = -1;
2340 key = NULL;
2341 crl = NULL;
2342 cert = NULL;
2343 attach = NULL;
2344
2345 #if defined(KORE_USE_ACME)
2346 acme = 0;
2347 #endif
2348
2349 if (!PyArg_ParseTuple(args, "s", &name))
2350 return (NULL);
2351
2352 if (kwargs != NULL)
2353 attach = python_string_from_dict(kwargs, "attach");
2354
2355 if (attach == NULL)
2356 attach = "default";
2357
2358 if ((srv = kore_server_lookup(attach)) == NULL) {
2359 PyErr_Format(PyExc_RuntimeError,
2360 "server '%s' does not exist", attach);
2361 return (NULL);
2362 }
2363
2364 if (srv->tls) {
2365 if (kwargs == NULL) {
2366 PyErr_Format(PyExc_RuntimeError,
2367 "no keywords for TLS enabled domain %s", name);
2368 return (NULL);
2369 }
2370 key = python_string_from_dict(kwargs, "key");
2371 cert = python_string_from_dict(kwargs, "cert");
2372
2373 #if defined(KORE_USE_ACME)
2374 python_bool_from_dict(kwargs, "acme", &acme);
2375
2376 if (acme) {
2377 kore_acme_get_paths(name, &akey, &acert);
2378 acme_domains++;
2379 key = akey;
2380 cert = acert;
2381 }
2382 #endif
2383
2384 if (key == NULL || cert == NULL) {
2385 PyErr_Format(PyExc_RuntimeError,
2386 "missing key or cert keywords for TLS listener");
2387 return (NULL);
2388 }
2389
2390 ca = python_string_from_dict(kwargs, "client_verify");
2391 if (ca != NULL) {
2392 python_long_from_dict(kwargs, "verify_depth", &depth);
2393 if (depth < 0) {
2394 PyErr_Format(PyExc_RuntimeError,
2395 "invalid depth '%d'", depth);
2396 return (NULL);
2397 }
2398 crl = python_string_from_dict(kwargs, "crl");
2399 }
2400 } else if (key != NULL || cert != NULL || ca != NULL) {
2401 kore_log(LOG_INFO, "ignoring tls settings for '%s'", name);
2402 }
2403
2404 if (kore_domain_lookup(srv, name) != NULL) {
2405 PyErr_SetString(PyExc_RuntimeError, "domain exists");
2406 return (NULL);
2407 }
2408
2409 if ((domain = PyObject_New(struct pydomain, &pydomain_type)) == NULL)
2410 return (NULL);
2411
2412 domain->next = NULL;
2413 domain->kwargs = NULL;
2414
2415 if ((domain->config = kore_domain_new(name)) == NULL)
2416 fatal("failed to create new domain configuration");
2417
2418 if (!kore_domain_attach(domain->config, srv))
2419 fatal("failed to attach domain configuration");
2420
2421 if (srv->tls) {
2422 domain->config->certkey = kore_strdup(key);
2423 domain->config->certfile = kore_strdup(cert);
2424
2425 #if defined(KORE_USE_ACME)
2426 domain->config->acme = acme;
2427
2428 if (domain->config->acme) {
2429 kore_free(akey);
2430 kore_free(acert);
2431 }
2432 #endif
2433 if (ca != NULL) {
2434 domain->config->cafile = kore_strdup(ca);
2435 domain->config->x509_verify_depth = depth;
2436 if (crl != NULL)
2437 domain->config->crlfile = kore_strdup(crl);
2438 }
2439 }
2440
2441 return ((PyObject *)domain);
2442 }
2443
2444 static PyObject *
2445 python_kore_route(PyObject *self, PyObject *args, PyObject *kwargs)
2446 {
2447 const char *path;
2448 PyObject *inner;
2449 struct pyroute *route;
2450
2451 if ((route = PyObject_New(struct pyroute, &pyroute_type)) == NULL)
2452 return (NULL);
2453
2454 if (!PyArg_ParseTuple(args, "s", &path))
2455 return (NULL);
2456
2457 route->domain = NULL;
2458 route->kwargs = kwargs;
2459 route->path = kore_strdup(path);
2460
2461 Py_XINCREF(route->kwargs);
2462
2463 inner = PyObject_GetAttrString((PyObject *)route, "inner");
2464 if (inner == NULL) {
2465 Py_DECREF((PyObject *)route);
2466 PyErr_SetString(PyExc_RuntimeError, "failed to find inner");
2467 return (NULL);
2468 }
2469
2470 return (inner);
2471 }
2472
2473 static PyObject *
2474 python_kore_gather(PyObject *self, PyObject *args, PyObject *kwargs)
2475 {
2476 struct pygather_op *op;
2477 PyObject *obj;
2478 struct pygather_coro *coro;
2479 Py_ssize_t sz, idx;
2480 int concurrency;
2481
2482 if (coro_running == NULL) {
2483 PyErr_SetString(PyExc_RuntimeError,
2484 "kore.gather only available in coroutines");
2485 return (NULL);
2486 }
2487
2488 sz = PyTuple_Size(args);
2489
2490 if (sz > INT_MAX) {
2491 PyErr_SetString(PyExc_TypeError, "too many arguments");
2492 return (NULL);
2493 }
2494
2495 if (kwargs != NULL &&
2496 (obj = PyDict_GetItemString(kwargs, "concurrency")) != NULL) {
2497 if (!PyLong_Check(obj)) {
2498 PyErr_SetString(PyExc_TypeError,
2499 "concurrency level must be an integer");
2500 return (NULL);
2501 }
2502
2503 PyErr_Clear();
2504 concurrency = (int)PyLong_AsLong(obj);
2505 if (concurrency == -1 && PyErr_Occurred())
2506 return (NULL);
2507
2508 if (concurrency == 0)
2509 concurrency = sz;
2510 } else {
2511 concurrency = sz;
2512 }
2513
2514 op = PyObject_New(struct pygather_op, &pygather_op_type);
2515 if (op == NULL)
2516 return (NULL);
2517
2518 op->running = 0;
2519 op->count = (int)sz;
2520 op->coro = coro_running;
2521 op->concurrency = concurrency;
2522
2523 TAILQ_INIT(&op->results);
2524 TAILQ_INIT(&op->coroutines);
2525
2526 for (idx = 0; idx < sz; idx++) {
2527 if ((obj = PyTuple_GetItem(args, idx)) == NULL) {
2528 Py_DECREF((PyObject *)op);
2529 return (NULL);
2530 }
2531
2532 if (!PyCoro_CheckExact(obj)) {
2533 Py_DECREF((PyObject *)op);
2534 PyErr_SetString(PyExc_TypeError, "not a coroutine");
2535 return (NULL);
2536 }
2537
2538 Py_INCREF(obj);
2539
2540 coro = kore_pool_get(&gather_coro_pool);
2541 coro->coro = python_coro_create(obj, NULL);
2542 coro->coro->gatherop = op;
2543 TAILQ_INSERT_TAIL(&op->coroutines, coro, list);
2544
2545 if (idx > concurrency - 1)
2546 python_coro_suspend(coro->coro);
2547 else
2548 op->running++;
2549 }
2550
2551 return ((PyObject *)op);
2552 }
2553
2554 static PyObject *
2555 python_kore_lock(PyObject *self, PyObject *args)
2556 {
2557 struct pylock *lock;
2558
2559 if ((lock = PyObject_New(struct pylock, &pylock_type)) == NULL)
2560 return (NULL);
2561
2562 lock->owner = NULL;
2563 TAILQ_INIT(&lock->ops);
2564
2565 return ((PyObject *)lock);
2566 }
2567
2568 static PyObject *
2569 python_kore_fatal(PyObject *self, PyObject *args)
2570 {
2571 const char *reason;
2572
2573 if (!PyArg_ParseTuple(args, "s", &reason))
2574 reason = "python_kore_fatal: PyArg_ParseTuple failed";
2575
2576 fatal("%s", reason);
2577
2578 /* not reached */
2579 Py_RETURN_TRUE;
2580 }
2581
2582 static PyObject *
2583 python_kore_fatalx(PyObject *self, PyObject *args)
2584 {
2585 const char *reason;
2586
2587 if (!PyArg_ParseTuple(args, "s", &reason))
2588 reason = "python_kore_fatalx: PyArg_ParseTuple failed";
2589
2590 fatalx("%s", reason);
2591
2592 /* not reached */
2593 Py_RETURN_TRUE;
2594 }
2595
2596 static PyObject *
2597 python_kore_setname(PyObject *self, PyObject *args)
2598 {
2599 const char *name;
2600 extern char *kore_progname;
2601
2602 if (!PyArg_ParseTuple(args, "s", &name))
2603 return (NULL);
2604
2605 kore_free(kore_progname);
2606 kore_progname = kore_strdup(name);
2607
2608 Py_RETURN_NONE;
2609 }
2610
2611 static PyObject *
2612 python_kore_sigtrap(PyObject *self, PyObject *args)
2613 {
2614 int sig;
2615
2616 if (!PyArg_ParseTuple(args, "i", &sig))
2617 return (NULL);
2618
2619 kore_signal_trap(sig);
2620
2621 Py_RETURN_NONE;
2622 }
2623
2624 static PyObject *
2625 python_kore_sendobj(PyObject *self, PyObject *args, PyObject *kwargs)
2626 {
2627 long val;
2628 u_int16_t dst;
2629 char *ptr;
2630 Py_ssize_t length;
2631 PyObject *obj, *bytes;
2632
2633 if (!PyArg_ParseTuple(args, "O", &obj))
2634 return (NULL);
2635
2636 bytes = PyObject_CallFunctionObjArgs(pickle_dumps, obj, NULL);
2637 if (bytes == NULL)
2638 return (NULL);
2639
2640 if (PyBytes_AsStringAndSize(bytes, &ptr, &length) == -1) {
2641 Py_DECREF(bytes);
2642 return (NULL);
2643 }
2644
2645 dst = KORE_MSG_WORKER_ALL;
2646
2647 if (kwargs != NULL) {
2648 if (python_long_from_dict(kwargs, "worker", &val)) {
2649 if (val <= 0 || val > worker_count ||
2650 val >= KORE_WORKER_MAX) {
2651 PyErr_Format(PyExc_RuntimeError,
2652 "worker %ld invalid", val);
2653 Py_DECREF(bytes);
2654 return (NULL);
2655 }
2656
2657 dst = val;
2658 }
2659 }
2660
2661 kore_msg_send(dst, KORE_PYTHON_SEND_OBJ, ptr, length);
2662 Py_DECREF(bytes);
2663
2664 Py_RETURN_NONE;
2665 }
2666
2667 static void
2668 python_kore_recvobj(struct kore_msg *msg, const void *data)
2669 {
2670 struct kore_runtime *rt;
2671 PyObject *onmsg, *ret, *bytes, *obj;
2672
2673 if ((onmsg = kore_module_getsym("koreapp.onmsg", &rt)) == NULL)
2674 return;
2675
2676 if (rt->type != KORE_RUNTIME_PYTHON)
2677 return;
2678
2679 if ((bytes = PyBytes_FromStringAndSize(data, msg->length)) == NULL) {
2680 Py_DECREF(onmsg);
2681 kore_python_log_error("koreapp.onmsg");
2682 return;
2683 }
2684
2685 obj = PyObject_CallFunctionObjArgs(pickle_loads, bytes, NULL);
2686 Py_DECREF(bytes);
2687
2688 if (obj == NULL) {
2689 Py_DECREF(onmsg);
2690 kore_python_log_error("koreapp.onmsg");
2691 return;
2692 }
2693
2694 ret = PyObject_CallFunctionObjArgs(onmsg, obj, NULL);
2695 kore_python_log_error("koreapp.onmsg");
2696
2697 Py_DECREF(obj);
2698 Py_DECREF(onmsg);
2699 Py_XDECREF(ret);
2700 }
2701
2702 static PyObject *
2703 python_kore_suspend(PyObject *self, PyObject *args)
2704 {
2705 struct pysuspend_op *op;
2706 int delay;
2707
2708 if (!PyArg_ParseTuple(args, "i", &delay))
2709 return (NULL);
2710
2711 op = PyObject_New(struct pysuspend_op, &pysuspend_op_type);
2712 if (op == NULL)
2713 return (NULL);
2714
2715 op->timer = NULL;
2716 op->delay = delay;
2717 op->coro = coro_running;
2718 op->state = PYSUSPEND_OP_INIT;
2719
2720 return ((PyObject *)op);
2721 }
2722
2723 static PyObject *
2724 python_kore_shutdown(PyObject *self, PyObject *args)
2725 {
2726 kore_shutdown();
2727
2728 Py_RETURN_TRUE;
2729 }
2730
2731 static PyObject *
2732 python_kore_coroname(PyObject *self, PyObject *args)
2733 {
2734 const char *name;
2735
2736 if (coro_running == NULL) {
2737 PyErr_SetString(PyExc_RuntimeError,
2738 "kore.coroname() only available in coroutines");
2739 return (NULL);
2740 }
2741
2742 if (!PyArg_ParseTuple(args, "s", &name))
2743 return (NULL);
2744
2745 kore_free(coro_running->name);
2746 coro_running->name = kore_strdup(name);
2747
2748 Py_RETURN_NONE;
2749 }
2750
2751 static PyObject *
2752 python_kore_corotrace(PyObject *self, PyObject *args)
2753 {
2754 if (!PyArg_ParseTuple(args, "b", &coro_tracing))
2755 return (NULL);
2756
2757 Py_RETURN_NONE;
2758 }
2759
2760 static PyObject *
2761 python_kore_timer(PyObject *self, PyObject *args, PyObject *kwargs)
2762 {
2763 u_int64_t ms;
2764 PyObject *obj;
2765 int flags;
2766 struct pytimer *timer;
2767
2768 if (worker == NULL) {
2769 PyErr_SetString(PyExc_RuntimeError,
2770 "kore.timer not supported on parent process");
2771 return (NULL);
2772 }
2773
2774 if (!PyArg_ParseTuple(args, "OKi", &obj, &ms, &flags))
2775 return (NULL);
2776
2777 if (flags & ~(KORE_TIMER_FLAGS)) {
2778 PyErr_SetString(PyExc_RuntimeError, "invalid flags");
2779 return (NULL);
2780 }
2781
2782 if ((timer = PyObject_New(struct pytimer, &pytimer_type)) == NULL)
2783 return (NULL);
2784
2785 timer->udata = NULL;
2786 timer->flags = flags;
2787 timer->callable = obj;
2788 timer->run = kore_timer_add(pytimer_run, ms, timer, flags);
2789
2790 Py_INCREF((PyObject *)timer);
2791 Py_INCREF(timer->callable);
2792
2793 if (kwargs != NULL) {
2794 if ((obj = PyDict_GetItemString(kwargs, "data")) != NULL) {
2795 Py_INCREF(obj);
2796 timer->udata = obj;
2797 }
2798 }
2799
2800 return ((PyObject *)timer);
2801 }
2802
2803 static PyObject *
2804 python_kore_proc(PyObject *self, PyObject *args, PyObject *kwargs)
2805 {
2806 union deconst cp;
2807 const char *cmd;
2808 struct pyproc *proc;
2809 Py_ssize_t idx, len;
2810 PyObject *obj, *item;
2811 int timeo, in_pipe[2], out_pipe[2];
2812 char *copy, *argv[32], *env[PYTHON_PROC_MAX_ENV + 1];
2813
2814 timeo = -1;
2815
2816 if (coro_running == NULL) {
2817 PyErr_SetString(PyExc_RuntimeError,
2818 "kore.proc only available in coroutines");
2819 return (NULL);
2820 }
2821
2822 if (!PyArg_ParseTuple(args, "s|i", &cmd, &timeo))
2823 return (NULL);
2824
2825 if (kwargs != NULL &&
2826 (obj = PyDict_GetItemString(kwargs, "env")) != NULL) {
2827 if (!PyList_CheckExact(obj)) {
2828 PyErr_SetString(PyExc_RuntimeError,
2829 "kore.proc: env is not of type 'list'");
2830 return (NULL);
2831 }
2832
2833 len = PyList_Size(obj);
2834 if (len > PYTHON_PROC_MAX_ENV) {
2835 PyErr_SetString(PyExc_RuntimeError,
2836 "kore.proc: too many entries in 'env' keyword");
2837 return (NULL);
2838 }
2839
2840 for (idx = 0; idx < len; idx++) {
2841 if ((item = PyList_GetItem(obj, idx)) == NULL)
2842 return (NULL);
2843
2844 if (!PyUnicode_CheckExact(item))
2845 return (NULL);
2846
2847 if ((cp.cp = PyUnicode_AsUTF8(item)) == NULL)
2848 return (NULL);
2849
2850 env[idx] = cp.p;
2851 }
2852
2853 env[idx] = NULL;
2854 }
2855
2856 if (pipe(in_pipe) == -1) {
2857 PyErr_SetString(PyExc_RuntimeError, errno_s);
2858 return (NULL);
2859 }
2860
2861 if (pipe(out_pipe) == -1) {
2862 close(in_pipe[0]);
2863 close(in_pipe[1]);
2864 PyErr_SetString(PyExc_RuntimeError, errno_s);
2865 return (NULL);
2866 }
2867
2868 if ((proc = PyObject_New(struct pyproc, &pyproc_type)) == NULL) {
2869 close(in_pipe[0]);
2870 close(in_pipe[1]);
2871 close(out_pipe[0]);
2872 close(out_pipe[1]);
2873 return (NULL);
2874 }
2875
2876 proc->pid = -1;
2877 proc->op = NULL;
2878 proc->apid = -1;
2879 proc->reaped = 0;
2880 proc->status = 0;
2881 proc->timer = NULL;
2882 proc->coro = coro_running;
2883 proc->in = pysocket_alloc();
2884 proc->out = pysocket_alloc();
2885
2886 if (proc->in == NULL || proc->out == NULL) {
2887 Py_DECREF((PyObject *)proc);
2888 return (NULL);
2889 }
2890
2891 TAILQ_INSERT_TAIL(&procs, proc, list);
2892
2893 proc->pid = fork();
2894 if (proc->pid == -1) {
2895 if (errno == ENOSYS) {
2896 Py_DECREF((PyObject *)proc);
2897 PyErr_SetString(PyExc_RuntimeError, errno_s);
2898 return (NULL);
2899 }
2900 fatal("python_kore_proc: fork(): %s", errno_s);
2901 }
2902
2903 if (proc->pid == 0) {
2904 close(in_pipe[1]);
2905 close(out_pipe[0]);
2906
2907 if (dup2(out_pipe[1], STDOUT_FILENO) == -1 ||
2908 dup2(out_pipe[1], STDERR_FILENO) == -1 ||
2909 dup2(in_pipe[0], STDIN_FILENO) == -1)
2910 fatal("dup2: %s", errno_s);
2911
2912 copy = kore_strdup(cmd);
2913 python_split_arguments(copy, argv, 32);
2914
2915 (void)execve(argv[0], argv, env);
2916 kore_log(LOG_ERR, "kore.proc failed to execute %s (%s)",
2917 argv[0], errno_s);
2918 exit(1);
2919 }
2920
2921 close(in_pipe[0]);
2922 close(out_pipe[1]);
2923
2924 if (!kore_connection_nonblock(in_pipe[1], 0) ||
2925 !kore_connection_nonblock(out_pipe[0], 0))
2926 fatal("failed to mark kore.proc pipes are non-blocking");
2927
2928 proc->apid = proc->pid;
2929 proc->in->fd = in_pipe[1];
2930 proc->out->fd = out_pipe[0];
2931
2932 if (timeo != -1) {
2933 proc->timer = kore_timer_add(pyproc_timeout,
2934 timeo, proc, KORE_TIMER_ONESHOT);
2935 }
2936
2937 return ((PyObject *)proc);
2938 }
2939
2940 static PyObject *
2941 python_import(const char *path)
2942 {
2943 struct stat st;
2944 PyObject *module;
2945 char *dir, *file, *copy, *p;
2946
2947 if (stat(path, &st) == -1)
2948 fatal("python_import: stat(%s): %s", path, errno_s);
2949
2950 if (!S_ISDIR(st.st_mode) && !S_ISREG(st.st_mode))
2951 fatal("python_import: '%s' is not a file or directory", path);
2952
2953 copy = kore_strdup(path);
2954 if ((p = dirname(copy)) == NULL)
2955 fatal("dirname: %s: %s", path, errno_s);
2956
2957 dir = kore_strdup(p);
2958 kore_free(copy);
2959
2960 copy = kore_strdup(path);
2961 if ((p = basename(copy)) == NULL)
2962 fatal("basename: %s: %s", path, errno_s);
2963
2964 file = kore_strdup(p);
2965 kore_free(copy);
2966
2967 if ((p = strrchr(file, '.')) != NULL)
2968 *p = '\0';
2969
2970 python_append_path(dir);
2971
2972 if (S_ISDIR(st.st_mode))
2973 python_append_path(path);
2974
2975 module = PyImport_ImportModule(file);
2976 if (module == NULL)
2977 PyErr_Print();
2978
2979 kore_free(dir);
2980 kore_free(file);
2981
2982 return (module);
2983 }
2984
2985 static PyObject *
2986 python_callable(PyObject *module, const char *symbol)
2987 {
2988 char *base, *method;
2989 PyObject *res, *obj, *meth;
2990
2991 res = NULL;
2992 obj = NULL;
2993 base = kore_strdup(symbol);
2994
2995 if ((method = strchr(base, '.')) != NULL)
2996 *(method)++ = '\0';
2997
2998 if ((obj = PyObject_GetAttrString(module, base)) == NULL)
2999 goto out;
3000
3001 if (method != NULL) {
3002 if ((meth = PyObject_GetAttrString(obj, method)) == NULL)
3003 goto out;
3004
3005 Py_DECREF(obj);
3006 obj = meth;
3007 }
3008
3009 if (!PyCallable_Check(obj))
3010 goto out;
3011
3012 res = obj;
3013 obj = NULL;
3014
3015 out:
3016 if (obj != NULL)
3017 Py_DECREF(obj);
3018
3019 PyErr_Clear();
3020 kore_free(base);
3021
3022 return (res);
3023 }
3024
3025 static PyObject *
3026 pyconnection_alloc(struct connection *c)
3027 {
3028 struct pyconnection *pyc;
3029
3030 pyc = PyObject_New(struct pyconnection, &pyconnection_type);
3031 if (pyc == NULL)
3032 return (NULL);
3033
3034 pyc->c = c;
3035
3036 return ((PyObject *)pyc);
3037 }
3038
3039 static PyObject *
3040 pyconnection_disconnect(struct pyconnection *pyc, PyObject *args)
3041 {
3042 kore_connection_disconnect(pyc->c);
3043
3044 Py_RETURN_TRUE;
3045 }
3046
3047 static PyObject *
3048 pyconnection_get_fd(struct pyconnection *pyc, void *closure)
3049 {
3050 PyObject *fd;
3051
3052 if ((fd = PyLong_FromLong(pyc->c->fd)) == NULL)
3053 return (PyErr_NoMemory());
3054
3055 return (fd);
3056 }
3057
3058 static PyObject *
3059 pyconnection_get_addr(struct pyconnection *pyc, void *closure)
3060 {
3061 void *ptr;
3062 PyObject *result;
3063 char addr[INET6_ADDRSTRLEN];
3064
3065 switch (pyc->c->family) {
3066 case AF_INET:
3067 ptr = &pyc->c->addr.ipv4.sin_addr;
3068 break;
3069 case AF_INET6:
3070 ptr = &pyc->c->addr.ipv6.sin6_addr;
3071 break;
3072 default:
3073 PyErr_SetString(PyExc_RuntimeError, "invalid family");
3074 return (NULL);
3075 }
3076
3077 if (inet_ntop(pyc->c->family, ptr, addr, sizeof(addr)) == NULL) {
3078 PyErr_SetString(PyExc_RuntimeError, "inet_ntop failed");
3079 return (NULL);
3080 }
3081
3082 if ((result = PyUnicode_FromString(addr)) == NULL)
3083 return (PyErr_NoMemory());
3084
3085 return (result);
3086 }
3087
3088 static PyObject *
3089 pyconnection_get_peer_x509(struct pyconnection *pyc, void *closure)
3090 {
3091 size_t len;
3092 u_int8_t *der;
3093 PyObject *bytes;
3094
3095 if (pyc->c->tls_cert == NULL) {
3096 Py_RETURN_NONE;
3097 }
3098
3099 if (!kore_tls_x509_data(pyc->c, &der, &len)) {
3100 PyErr_SetString(PyExc_RuntimeError,
3101 "failed to obtain certificate data");
3102 return (NULL);
3103 }
3104
3105 bytes = PyBytes_FromStringAndSize((char *)der, len);
3106 kore_free(der);
3107
3108 return (bytes);
3109 }
3110
3111 static PyObject *
3112 pyconnection_get_peer_x509dict(struct pyconnection *pyc, void *closure)
3113 {
3114 KORE_X509_NAMES *name;
3115 PyObject *dict, *issuer, *subject, *ret;
3116
3117 ret = NULL;
3118 issuer = NULL;
3119 subject = NULL;
3120
3121 if (pyc->c->tls_cert == NULL) {
3122 Py_RETURN_NONE;
3123 }
3124
3125 if ((dict = PyDict_New()) == NULL)
3126 goto out;
3127
3128 if ((issuer = PyDict_New()) == NULL)
3129 goto out;
3130
3131 if (PyDict_SetItemString(dict, "issuer", issuer) == -1)
3132 goto out;
3133
3134 if ((subject = PyDict_New()) == NULL)
3135 goto out;
3136
3137 if (PyDict_SetItemString(dict, "subject", subject) == -1)
3138 goto out;
3139
3140 PyErr_Clear();
3141
3142 if ((name = kore_tls_x509_subject_name(pyc->c)) == NULL) {
3143 PyErr_Format(PyExc_RuntimeError,
3144 "failed to obtain x509 subjectName");
3145 goto out;
3146 }
3147
3148 if (!kore_tls_x509name_foreach(name, 0, subject,
3149 pyconnection_x509_cb)) {
3150 if (PyErr_Occurred() == NULL) {
3151 PyErr_Format(PyExc_RuntimeError,
3152 "failed to add subject name to dictionary");
3153 }
3154 goto out;
3155 }
3156
3157 if ((name = kore_tls_x509_issuer_name(pyc->c)) == NULL) {
3158 PyErr_Format(PyExc_RuntimeError,
3159 "failed to obtain x509 issuerName");
3160 goto out;
3161 }
3162
3163 if (!kore_tls_x509name_foreach(name, 0, issuer, pyconnection_x509_cb)) {
3164 if (PyErr_Occurred() == NULL) {
3165 PyErr_Format(PyExc_RuntimeError,
3166 "failed to add issuer name to dictionary");
3167 }
3168 goto out;
3169 }
3170
3171 ret = dict;
3172 dict = NULL;
3173
3174 out:
3175 Py_XDECREF(dict);
3176 Py_XDECREF(issuer);
3177 Py_XDECREF(subject);
3178
3179 return (ret);
3180 }
3181
3182 static int
3183 pyconnection_x509_cb(void *udata, int islast, int nid, const char *field,
3184 const void *data, size_t len, int flags)
3185 {
3186 PyObject *dict, *obj;
3187
3188 dict = udata;
3189
3190 if ((obj = PyUnicode_FromStringAndSize(data, len)) == NULL)
3191 return (KORE_RESULT_ERROR);
3192
3193 if (PyDict_SetItemString(dict, field, obj) == -1) {
3194 Py_DECREF(obj);
3195 return (KORE_RESULT_ERROR);
3196 }
3197
3198 Py_DECREF(obj);
3199 return (KORE_RESULT_OK);
3200 }
3201
3202 static void
3203 pytimer_run(void *arg, u_int64_t now)
3204 {
3205 PyObject *ret;
3206 struct kore_timer *run;
3207 struct pytimer *timer;
3208
3209 timer = arg;
3210 run = timer->run;
3211 timer->run = NULL;
3212
3213 PyErr_Clear();
3214 ret = PyObject_CallFunctionObjArgs(timer->callable, timer->udata, NULL);
3215 Py_XDECREF(ret);
3216
3217 kore_python_log_error("pytimer_run");
3218
3219 if (timer->flags & KORE_TIMER_ONESHOT) {
3220 run->flags |= KORE_TIMER_ONESHOT;
3221 Py_DECREF((PyObject *)timer);
3222 }
3223 else {
3224 timer->run = run;
3225 }
3226 }
3227
3228
3229 static void
3230 pytimer_dealloc(struct pytimer *timer)
3231 {
3232 if (timer->run != NULL) {
3233 kore_timer_remove(timer->run);
3234 timer->run = NULL;
3235 }
3236
3237 if (timer->callable != NULL) {
3238 Py_DECREF(timer->callable);
3239 timer->callable = NULL;
3240 }
3241
3242 if (timer->udata != NULL) {
3243 Py_DECREF(timer->udata);
3244 timer->udata = NULL;
3245 }
3246
3247 PyObject_Del((PyObject *)timer);
3248 }
3249
3250 static PyObject *
3251 pytimer_close(struct pytimer *timer, PyObject *args)
3252 {
3253 if (timer->run != NULL) {
3254 kore_timer_remove(timer->run);
3255 timer->run = NULL;
3256 Py_DECREF((PyObject *)timer);
3257 } else {
3258 timer->flags |= KORE_TIMER_ONESHOT;
3259 }
3260
3261 Py_RETURN_TRUE;
3262 }
3263
3264 static void
3265 pysuspend_op_dealloc(struct pysuspend_op *op)
3266 {
3267 if (op->timer != NULL) {
3268 kore_timer_remove(op->timer);
3269 op->timer = NULL;
3270 }
3271
3272 PyObject_Del((PyObject *)op);
3273 }
3274
3275 static PyObject *
3276 pysuspend_op_await(PyObject *sop)
3277 {
3278 Py_INCREF(sop);
3279 return (sop);
3280 }
3281
3282 static PyObject *
3283 pysuspend_op_iternext(struct pysuspend_op *op)
3284 {
3285 switch (op->state) {
3286 case PYSUSPEND_OP_INIT:
3287 op->timer = kore_timer_add(pysuspend_wakeup, op->delay,
3288 op, KORE_TIMER_ONESHOT);
3289 op->state = PYSUSPEND_OP_WAIT;
3290 break;
3291 case PYSUSPEND_OP_WAIT:
3292 break;
3293 case PYSUSPEND_OP_CONTINUE:
3294 PyErr_SetNone(PyExc_StopIteration);
3295 return (NULL);
3296 default:
3297 fatal("unknown state %d for pysuspend_op", op->state);
3298 }
3299
3300 Py_RETURN_NONE;
3301 }
3302
3303 static void
3304 pysuspend_wakeup(void *arg, u_int64_t now)
3305 {
3306 struct pysuspend_op *op = arg;
3307
3308 op->timer = NULL;
3309 op->state = PYSUSPEND_OP_CONTINUE;
3310
3311 if (op->coro->request != NULL)
3312 http_request_wakeup(op->coro->request);
3313 else
3314 python_coro_wakeup(op->coro);
3315 }
3316
3317 static struct pysocket *
3318 pysocket_alloc(void)
3319 {
3320 struct pysocket *sock;
3321
3322 if ((sock = PyObject_New(struct pysocket, &pysocket_type)) == NULL)
3323 return (NULL);
3324
3325 sock->fd = -1;
3326 sock->family = -1;
3327 sock->protocol = -1;
3328 sock->scheduled = 0;
3329
3330 sock->socket = NULL;
3331 sock->recvop = NULL;
3332 sock->sendop = NULL;
3333
3334 sock->event.s = sock;
3335 sock->event.evt.flags = 0;
3336 sock->event.evt.type = KORE_TYPE_PYSOCKET;
3337 sock->event.evt.handle = pysocket_evt_handle;
3338
3339 return (sock);
3340 }
3341
3342 static void
3343 pysocket_dealloc(struct pysocket *sock)
3344 {
3345 if (sock->scheduled && sock->fd != -1) {
3346 kore_platform_disable_read(sock->fd);
3347 #if !defined(__linux__)
3348 kore_platform_disable_write(sock->fd);
3349 #endif
3350 }
3351
3352 if (sock->socket != NULL) {
3353 Py_DECREF(sock->socket);
3354 } else if (sock->fd != -1) {
3355 (void)close(sock->fd);
3356 }
3357
3358 PyObject_Del((PyObject *)sock);
3359 }
3360
3361 static PyObject *
3362 pysocket_send(struct pysocket *sock, PyObject *args)
3363 {
3364 Py_buffer buf;
3365 PyObject *ret;
3366
3367 if (!PyArg_ParseTuple(args, "y*", &buf))
3368 return (NULL);
3369
3370 ret = pysocket_op_create(sock, PYSOCKET_TYPE_SEND, buf.buf, buf.len);
3371 PyBuffer_Release(&buf);
3372
3373 return (ret);
3374 }
3375
3376 static PyObject *
3377 pysocket_sendto(struct pysocket *sock, PyObject *args)
3378 {
3379 Py_buffer buf;
3380 struct pysocket_op *op;
3381 PyObject *ret;
3382 int port;
3383 const char *ip, *sockaddr;
3384
3385 switch (sock->family) {
3386 case AF_INET:
3387 if (!PyArg_ParseTuple(args, "siy*", &ip, &port, &buf))
3388 return (NULL);
3389 if (port <= 0 || port >= USHRT_MAX) {
3390 PyErr_SetString(PyExc_RuntimeError, "invalid port");
3391 return (NULL);
3392 }
3393 break;
3394 case AF_UNIX:
3395 if (!PyArg_ParseTuple(args, "sy*", &sockaddr, &buf))
3396 return (NULL);
3397 break;
3398 default:
3399 PyErr_SetString(PyExc_RuntimeError, "unsupported family");
3400 return (NULL);
3401 }
3402
3403 ret = pysocket_op_create(sock, PYSOCKET_TYPE_SENDTO, buf.buf, buf.len);
3404 PyBuffer_Release(&buf);
3405
3406 op = (struct pysocket_op *)ret;
3407
3408 switch (sock->family) {
3409 case AF_INET:
3410 op->sendaddr.ipv4.sin_family = AF_INET;
3411 op->sendaddr.ipv4.sin_port = htons(port);
3412 op->sendaddr.ipv4.sin_addr.s_addr = inet_addr(ip);
3413 break;
3414 case AF_UNIX:
3415 op->sendaddr.sun.sun_family = AF_UNIX;
3416 if (kore_strlcpy(op->sendaddr.sun.sun_path, sockaddr,
3417 sizeof(op->sendaddr.sun.sun_path)) >=
3418 sizeof(op->sendaddr.sun.sun_path)) {
3419 Py_DECREF(ret);
3420 PyErr_SetString(PyExc_RuntimeError,
3421 "unix socket path too long");
3422 return (NULL);
3423 }
3424 break;
3425 default:
3426 Py_DECREF(ret);
3427 PyErr_SetString(PyExc_RuntimeError, "unsupported family");
3428 return (NULL);
3429 }
3430
3431 return (ret);
3432 }
3433
3434 static PyObject *
3435 pysocket_recv(struct pysocket *sock, PyObject *args)
3436 {
3437 Py_ssize_t len;
3438 struct pysocket_op *op;
3439 PyObject *obj;
3440 int timeo;
3441
3442 timeo = -1;
3443
3444 if (!PyArg_ParseTuple(args, "n|i", &len, &timeo))
3445 return (NULL);
3446
3447 obj = pysocket_op_create(sock, PYSOCKET_TYPE_RECV, NULL, len);
3448 if (obj == NULL)
3449 return (NULL);
3450
3451 op = (struct pysocket_op *)obj;
3452
3453 if (timeo != -1) {
3454 op->timer = kore_timer_add(pysocket_op_timeout,
3455 timeo, op, KORE_TIMER_ONESHOT);
3456 }
3457
3458 return (obj);
3459 }
3460
3461 static PyObject *
3462 pysocket_recvmsg(struct pysocket *sock, PyObject *args)
3463 {
3464 Py_ssize_t len;
3465
3466 if (!PyArg_ParseTuple(args, "n", &len))
3467 return (NULL);
3468
3469 return (pysocket_op_create(sock, PYSOCKET_TYPE_RECVMSG, NULL, len));
3470 }
3471
3472 static PyObject *
3473 pysocket_recvfrom(struct pysocket *sock, PyObject *args)
3474 {
3475 Py_ssize_t len;
3476
3477 if (!PyArg_ParseTuple(args, "n", &len))
3478 return (NULL);
3479
3480 return (pysocket_op_create(sock, PYSOCKET_TYPE_RECVFROM, NULL, len));
3481 }
3482
3483 static PyObject *
3484 pysocket_accept(struct pysocket *sock, PyObject *args)
3485 {
3486 return (pysocket_op_create(sock, PYSOCKET_TYPE_ACCEPT, NULL, 0));
3487 }
3488
3489 static PyObject *
3490 pysocket_connect(struct pysocket *sock, PyObject *args)
3491 {
3492 const char *host;
3493 int port, len;
3494
3495 port = 0;
3496
3497 if (!PyArg_ParseTuple(args, "s|i", &host, &port))
3498 return (NULL);
3499
3500 if (port < 0 || port > USHRT_MAX) {
3501 PyErr_SetString(PyExc_RuntimeError, "invalid port number");
3502 return (NULL);
3503 }
3504
3505 switch (sock->family) {
3506 case AF_INET:
3507 sock->addr.ipv4.sin_family = AF_INET;
3508 sock->addr.ipv4.sin_port = htons(port);
3509 if (inet_pton(sock->family, host,
3510 &sock->addr.ipv4.sin_addr) == -1) {
3511 PyErr_SetString(PyExc_RuntimeError, "invalid host");
3512 return (NULL);
3513 }
3514 sock->addr_len = sizeof(sock->addr.ipv4);
3515 break;
3516 case AF_UNIX:
3517 sock->addr.sun.sun_family = AF_UNIX;
3518 len = snprintf(sock->addr.sun.sun_path,
3519 sizeof(sock->addr.sun.sun_path), "%s", host);
3520 if (len == -1 ||
3521 (size_t)len >= sizeof(sock->addr.sun.sun_path)) {
3522 PyErr_SetString(PyExc_RuntimeError, "path too long");
3523 return (NULL);
3524 }
3525 #if defined(__linux__)
3526 /* Assume abstract socket if prefixed with '@'. */
3527 if (sock->addr.sun.sun_path[0] == '@')
3528 sock->addr.sun.sun_path[0] = '\0';
3529 #endif
3530 sock->addr_len = sizeof(sock->addr.sun.sun_family) + len;
3531 break;
3532 default:
3533 fatal("unsupported socket family %d", sock->family);
3534 }
3535
3536 return (pysocket_op_create(sock, PYSOCKET_TYPE_CONNECT, NULL, 0));
3537 }
3538
3539 static PyObject *
3540 pysocket_close(struct pysocket *sock, PyObject *args)
3541 {
3542 if (sock->scheduled) {
3543 sock->scheduled = 0;
3544 kore_platform_disable_read(sock->fd);
3545 #if !defined(__linux__)
3546 kore_platform_disable_write(sock->fd);
3547 #endif
3548 }
3549
3550 if (sock->socket != NULL) {
3551 Py_DECREF(sock->socket);
3552 sock->socket = NULL;
3553 } else if (sock->fd != -1) {
3554 (void)close(sock->fd);
3555 }
3556
3557 sock->fd = -1;
3558 sock->event.evt.handle(&sock->event, 1);
3559
3560 Py_RETURN_TRUE;
3561 }
3562
3563 static void
3564 pysocket_op_dealloc(struct pysocket_op *op)
3565 {
3566 if (op->type == PYSOCKET_TYPE_RECV ||
3567 op->type == PYSOCKET_TYPE_RECVMSG ||
3568 op->type == PYSOCKET_TYPE_RECVFROM ||
3569 op->type == PYSOCKET_TYPE_SEND ||
3570 op->type == PYSOCKET_TYPE_SENDTO)
3571 kore_buf_cleanup(&op->buffer);
3572
3573 switch (op->type) {
3574 case PYSOCKET_TYPE_RECV:
3575 case PYSOCKET_TYPE_ACCEPT:
3576 case PYSOCKET_TYPE_RECVMSG:
3577 case PYSOCKET_TYPE_RECVFROM:
3578 if (op->socket->recvop != op)
3579 fatal("recvop mismatch");
3580 op->socket->recvop = NULL;
3581 break;
3582 case PYSOCKET_TYPE_SEND:
3583 case PYSOCKET_TYPE_SENDTO:
3584 case PYSOCKET_TYPE_CONNECT:
3585 if (op->socket->sendop != op)
3586 fatal("sendop mismatch");
3587 op->socket->sendop = NULL;
3588 break;
3589 }
3590
3591 if (op->timer != NULL) {
3592 kore_timer_remove(op->timer);
3593 op->timer = NULL;
3594 }
3595
3596 op->coro->sockop = NULL;
3597 Py_DECREF(op->socket);
3598
3599 PyObject_Del((PyObject *)op);
3600 }
3601
3602 static PyObject *
3603 pysocket_op_create(struct pysocket *sock, int type, const void *ptr, size_t len)
3604 {
3605 struct pysocket_op *op;
3606
3607 if (coro_running->sockop != NULL)
3608 fatal("pysocket_op_create: coro has active socketop");
3609
3610 switch (type) {
3611 case PYSOCKET_TYPE_RECV:
3612 case PYSOCKET_TYPE_ACCEPT:
3613 case PYSOCKET_TYPE_RECVMSG:
3614 case PYSOCKET_TYPE_RECVFROM:
3615 if (sock->recvop != NULL) {
3616 PyErr_SetString(PyExc_RuntimeError,
3617 "only one recv operation can be done per socket");
3618 return (NULL);
3619 }
3620 break;
3621 case PYSOCKET_TYPE_SEND:
3622 case PYSOCKET_TYPE_SENDTO:
3623 case PYSOCKET_TYPE_CONNECT:
3624 if (sock->sendop != NULL) {
3625 PyErr_SetString(PyExc_RuntimeError,
3626 "only one send operation can be done per socket");
3627 return (NULL);
3628 }
3629 break;
3630 default:
3631 fatal("unknown pysocket_op type %u", type);
3632 }
3633
3634 op = PyObject_New(struct pysocket_op, &pysocket_op_type);
3635 if (op == NULL)
3636 return (NULL);
3637
3638 op->eof = 0;
3639 op->self = op;
3640 op->type = type;
3641 op->timer = NULL;
3642 op->socket = sock;
3643 op->coro = coro_running;
3644
3645 coro_running->sockop = op;
3646 Py_INCREF(op->socket);
3647
3648 switch (type) {
3649 case PYSOCKET_TYPE_RECV:
3650 case PYSOCKET_TYPE_RECVMSG:
3651 case PYSOCKET_TYPE_RECVFROM:
3652 sock->recvop = op;
3653 kore_buf_init(&op->buffer, len);
3654 break;
3655 case PYSOCKET_TYPE_SEND:
3656 case PYSOCKET_TYPE_SENDTO:
3657 sock->sendop = op;
3658 kore_buf_init(&op->buffer, len);
3659 kore_buf_append(&op->buffer, ptr, len);
3660 kore_buf_reset(&op->buffer);
3661 break;
3662 case PYSOCKET_TYPE_ACCEPT:
3663 sock->recvop = op;
3664 break;
3665 case PYSOCKET_TYPE_CONNECT:
3666 sock->sendop = op;
3667 break;
3668 default:
3669 fatal("unknown pysocket_op type %u", type);
3670 }
3671
3672 if (sock->scheduled == 0) {
3673 sock->scheduled = 1;
3674 kore_platform_event_all(sock->fd, &sock->event);
3675 }
3676
3677 return ((PyObject *)op);
3678 }
3679
3680 static PyObject *
3681 pysocket_op_await(PyObject *obj)
3682 {
3683 Py_INCREF(obj);
3684 return (obj);
3685 }
3686
3687 static PyObject *
3688 pysocket_op_iternext(struct pysocket_op *op)
3689 {
3690 PyObject *ret;
3691
3692 if (op->socket->fd == -1) {
3693 PyErr_SetNone(PyExc_StopIteration);
3694 return (NULL);
3695 }
3696
3697 if (op->eof) {
3698 if (op->coro->exception != NULL) {
3699 PyErr_SetString(op->coro->exception,
3700 op->coro->exception_msg);
3701 op->coro->exception = NULL;
3702 return (NULL);
3703 }
3704
3705 if (op->type != PYSOCKET_TYPE_RECV) {
3706 PyErr_SetString(PyExc_RuntimeError, "socket EOF");
3707 return (NULL);
3708 }
3709
3710 /* Drain the recv socket. */
3711 op->socket->event.evt.flags |= KORE_EVENT_READ;
3712 return (pysocket_async_recv(op));
3713 }
3714
3715 switch (op->type) {
3716 case PYSOCKET_TYPE_CONNECT:
3717 ret = pysocket_async_connect(op);
3718 break;
3719 case PYSOCKET_TYPE_ACCEPT:
3720 ret = pysocket_async_accept(op);
3721 break;
3722 case PYSOCKET_TYPE_RECV:
3723 case PYSOCKET_TYPE_RECVMSG:
3724 case PYSOCKET_TYPE_RECVFROM:
3725 ret = pysocket_async_recv(op);
3726 break;
3727 case PYSOCKET_TYPE_SEND:
3728 case PYSOCKET_TYPE_SENDTO:
3729 ret = pysocket_async_send(op);
3730 break;
3731 default:
3732 PyErr_SetString(PyExc_RuntimeError, "invalid op type");
3733 return (NULL);
3734 }
3735
3736 return (ret);
3737 }
3738
3739 static void
3740 pysocket_op_timeout(void *arg, u_int64_t now)
3741 {
3742 struct pysocket_op *op = arg;
3743
3744 op->eof = 1;
3745 op->timer = NULL;
3746
3747 op->coro->exception = PyExc_TimeoutError;
3748 op->coro->exception_msg = "timeout before operation completed";
3749
3750 if (op->coro->request != NULL)
3751 http_request_wakeup(op->coro->request);
3752 else
3753 python_coro_wakeup(op->coro);
3754 }
3755
3756 static PyObject *
3757 pysocket_async_connect(struct pysocket_op *op)
3758 {
3759 if (connect(op->socket->fd, (struct sockaddr *)&op->socket->addr,
3760 op->socket->addr_len) == -1) {
3761 if (errno != EALREADY && errno != EINPROGRESS &&
3762 errno != EISCONN && errno != EAGAIN) {
3763 PyErr_SetString(PyExc_RuntimeError, errno_s);
3764 return (NULL);
3765 }
3766
3767 if (errno != EISCONN) {
3768 Py_RETURN_NONE;
3769 }
3770 }
3771
3772 PyErr_SetNone(PyExc_StopIteration);
3773 return (NULL);
3774 }
3775
3776 static PyObject *
3777 pysocket_async_accept(struct pysocket_op *op)
3778 {
3779 int fd;
3780 struct pysocket *sock;
3781
3782 if (!(op->socket->event.evt.flags & KORE_EVENT_READ)) {
3783 Py_RETURN_NONE;
3784 }
3785
3786 if ((sock = pysocket_alloc()) == NULL)
3787 return (NULL);
3788
3789 sock->addr_len = sizeof(sock->addr);
3790
3791 if ((fd = accept(op->socket->fd,
3792 (struct sockaddr *)&sock->addr, &sock->addr_len)) == -1) {
3793 Py_DECREF((PyObject *)sock);
3794 if (errno == EAGAIN || errno == EWOULDBLOCK) {
3795 op->socket->event.evt.flags &= ~KORE_EVENT_READ;
3796 Py_RETURN_NONE;
3797 }
3798 PyErr_SetString(PyExc_RuntimeError, errno_s);
3799 return (NULL);
3800 }
3801
3802 if (!kore_connection_nonblock(fd, 0)) {
3803 Py_DECREF((PyObject *)sock);
3804 PyErr_SetString(PyExc_RuntimeError, errno_s);
3805 return (NULL);
3806 }
3807
3808 sock->fd = fd;
3809 sock->socket = NULL;
3810 sock->family = op->socket->family;
3811 sock->protocol = op->socket->protocol;
3812
3813 PyErr_SetObject(PyExc_StopIteration, (PyObject *)sock);
3814 Py_DECREF((PyObject *)sock);
3815
3816 return (NULL);
3817 }
3818
3819 static PyObject *
3820 pysocket_async_recv(struct pysocket_op *op)
3821 {
3822 ssize_t ret;
3823 size_t len;
3824 u_int16_t port;
3825 struct iovec iov;
3826 struct msghdr msg;
3827 socklen_t socklen;
3828 struct sockaddr *sendaddr;
3829 const char *ptr, *ip;
3830 u_int8_t ancdata[1024];
3831 PyObject *bytes, *result, *tuple, *list;
3832
3833 if (!(op->socket->event.evt.flags & KORE_EVENT_READ)) {
3834 Py_RETURN_NONE;
3835 }
3836
3837 socklen = 0;
3838
3839 for (;;) {
3840 switch (op->type) {
3841 case PYSOCKET_TYPE_RECV:
3842 ret = read(op->socket->fd, op->buffer.data,
3843 op->buffer.length);
3844 break;
3845 case PYSOCKET_TYPE_RECVMSG:
3846 memset(&msg, 0, sizeof(msg));
3847
3848 iov.iov_base = op->buffer.data;
3849 iov.iov_len = op->buffer.length;
3850
3851 msg.msg_iov = &iov;
3852 msg.msg_iovlen = 1;
3853 msg.msg_name = &op->sendaddr;
3854 msg.msg_namelen = sizeof(op->sendaddr);
3855 msg.msg_control = ancdata;
3856 msg.msg_controllen = sizeof(ancdata);
3857
3858 memset(&op->sendaddr, 0, sizeof(op->sendaddr));
3859 ret = recvmsg(op->socket->fd, &msg, 0);
3860 break;
3861 case PYSOCKET_TYPE_RECVFROM:
3862 sendaddr = (struct sockaddr *)&op->sendaddr;
3863 switch (op->socket->family) {
3864 case AF_INET:
3865 socklen = sizeof(op->sendaddr.ipv4);
3866 break;
3867 case AF_UNIX:
3868 socklen = sizeof(op->sendaddr.sun);
3869 break;
3870 default:
3871 fatal("%s: non AF_INET/AF_UNIX", __func__);
3872 }
3873
3874 memset(sendaddr, 0, socklen);
3875 ret = recvfrom(op->socket->fd, op->buffer.data,
3876 op->buffer.length, 0, sendaddr, &socklen);
3877 break;
3878 default:
3879 fatal("%s: unknown type %d", __func__, op->type);
3880 }
3881
3882 if (ret == -1) {
3883 if (errno == EINTR)
3884 continue;
3885 if (errno == EAGAIN || errno == EWOULDBLOCK) {
3886 op->socket->event.evt.flags &= ~KORE_EVENT_READ;
3887 Py_RETURN_NONE;
3888 }
3889 PyErr_SetString(PyExc_RuntimeError, errno_s);
3890 return (NULL);
3891 }
3892
3893 break;
3894 }
3895
3896 op->coro->exception = NULL;
3897 op->coro->exception_msg = NULL;
3898
3899 if (op->timer != NULL) {
3900 kore_timer_remove(op->timer);
3901 op->timer = NULL;
3902 }
3903
3904 if (op->type == PYSOCKET_TYPE_RECV && ret == 0) {
3905 PyErr_SetNone(PyExc_StopIteration);
3906 return (NULL);
3907 }
3908
3909 ptr = (const char *)op->buffer.data;
3910 if ((bytes = PyBytes_FromStringAndSize(ptr, ret)) == NULL)
3911 return (NULL);
3912
3913 list = NULL;
3914
3915 switch (op->type) {
3916 case PYSOCKET_TYPE_RECV:
3917 PyErr_SetObject(PyExc_StopIteration, bytes);
3918 Py_DECREF(bytes);
3919 return (NULL);
3920 case PYSOCKET_TYPE_RECVMSG:
3921 socklen = msg.msg_namelen;
3922 if ((list = python_cmsg_to_list(&msg)) == NULL) {
3923 Py_DECREF(bytes);
3924 return (NULL);
3925 }
3926 break;
3927 case PYSOCKET_TYPE_RECVFROM:
3928 break;
3929 default:
3930 fatal("%s: unknown type %d", __func__, op->type);
3931 }
3932
3933 switch(op->socket->family) {
3934 case AF_INET:
3935 port = ntohs(op->sendaddr.ipv4.sin_port);
3936 ip = inet_ntoa(op->sendaddr.ipv4.sin_addr);
3937
3938 if (op->type == PYSOCKET_TYPE_RECVFROM)
3939 tuple = Py_BuildValue("(sHN)", ip, port, bytes);
3940 else
3941 tuple = Py_BuildValue("(sHNN)", ip, port, bytes, list);
3942 break;
3943 case AF_UNIX:
3944 len = strlen(op->sendaddr.sun.sun_path);
3945 #if defined(__linux__)
3946 if (len == 0 && socklen > 0) {
3947 len = socklen - sizeof(sa_family_t);
3948 op->sendaddr.sun.sun_path[0] = '@';
3949 op->sendaddr.sun.sun_path[len] = '\0';
3950 }
3951 #endif
3952 if (len == 0) {
3953 if (op->type == PYSOCKET_TYPE_RECVFROM) {
3954 tuple = Py_BuildValue("(ON)", Py_None, bytes);
3955 } else {
3956 tuple = Py_BuildValue("(ONN)",
3957 Py_None, bytes, list);
3958 }
3959 } else {
3960 if (op->type == PYSOCKET_TYPE_RECVFROM) {
3961 tuple = Py_BuildValue("(sN)",
3962 op->sendaddr.sun.sun_path, bytes);
3963 } else {
3964 tuple = Py_BuildValue("(sNN)",
3965 op->sendaddr.sun.sun_path, bytes, list);
3966 }
3967 }
3968 break;
3969 default:
3970 fatal("%s: non AF_INET/AF_UNIX", __func__);
3971 }
3972
3973 if (tuple == NULL) {
3974 Py_XDECREF(list);
3975 Py_DECREF(bytes);
3976 return (NULL);
3977 }
3978
3979 result = PyObject_CallFunctionObjArgs(PyExc_StopIteration, tuple, NULL);
3980 if (result == NULL) {
3981 Py_DECREF(tuple);
3982 return (NULL);
3983 }
3984
3985 Py_DECREF(tuple);
3986 PyErr_SetObject(PyExc_StopIteration, result);
3987 Py_DECREF(result);
3988
3989 return (NULL);
3990 }
3991
3992 static PyObject *
3993 pysocket_async_send(struct pysocket_op *op)
3994 {
3995 ssize_t ret;
3996 socklen_t socklen;
3997 const struct sockaddr *sendaddr;
3998
3999 if (!(op->socket->event.evt.flags & KORE_EVENT_WRITE)) {
4000 Py_RETURN_NONE;
4001 }
4002
4003 for (;;) {
4004 if (op->type == PYSOCKET_TYPE_SEND) {
4005 ret = write(op->socket->fd,
4006 op->buffer.data + op->buffer.offset,
4007 op->buffer.length - op->buffer.offset);
4008 } else {
4009 sendaddr = (const struct sockaddr *)&op->sendaddr;
4010
4011 switch (op->socket->family) {
4012 case AF_INET:
4013 socklen = sizeof(op->sendaddr.ipv4);
4014 break;
4015 case AF_UNIX:
4016 socklen = sizeof(op->sendaddr.sun);
4017 #if defined(__linux__)
4018 if (op->sendaddr.sun.sun_path[0] == '@') {
4019 socklen = sizeof(sa_family_t) +
4020 strlen(op->sendaddr.sun.sun_path);
4021 op->sendaddr.sun.sun_path[0] = '\0';
4022 }
4023 #endif
4024 break;
4025 default:
4026 fatal("non AF_INET/AF_UNIX in %s", __func__);
4027 }
4028
4029 ret = sendto(op->socket->fd,
4030 op->buffer.data + op->buffer.offset,
4031 op->buffer.length - op->buffer.offset,
4032 0, sendaddr, socklen);
4033 }
4034
4035 if (ret == -1) {
4036 if (errno == EINTR)
4037 continue;
4038 if (errno == EAGAIN || errno == EWOULDBLOCK) {
4039 op->socket->event.evt.flags &=
4040 ~KORE_EVENT_WRITE;
4041 Py_RETURN_NONE;
4042 }
4043 PyErr_SetString(PyExc_RuntimeError, errno_s);
4044 return (NULL);
4045 }
4046 break;
4047 }
4048
4049 op->buffer.offset += (size_t)ret;
4050
4051 if (op->buffer.offset == op->buffer.length) {
4052 PyErr_SetNone(PyExc_StopIteration);
4053 return (NULL);
4054 }
4055
4056 Py_RETURN_NONE;
4057 }
4058
4059 static void
4060 pysocket_evt_handle(void *arg, int eof)
4061 {
4062 struct pysocket_event *event = arg;
4063 struct pysocket *socket = event->s;
4064
4065 if ((eof || (event->evt.flags & KORE_EVENT_READ)) &&
4066 socket->recvop != NULL) {
4067 if (socket->recvop->coro->request != NULL)
4068 http_request_wakeup(socket->recvop->coro->request);
4069 else
4070 python_coro_wakeup(socket->recvop->coro);
4071 socket->recvop->eof = eof;
4072 }
4073
4074 if ((eof || (event->evt.flags & KORE_EVENT_WRITE)) &&
4075 socket->sendop != NULL) {
4076 if (socket->sendop->coro->request != NULL)
4077 http_request_wakeup(socket->sendop->coro->request);
4078 else
4079 python_coro_wakeup(socket->sendop->coro);
4080 socket->sendop->eof = eof;
4081 }
4082 }
4083
4084 static void
4085 pyqueue_dealloc(struct pyqueue *queue)
4086 {
4087 struct pyqueue_object *qobj;
4088 struct pyqueue_waiting *waiting;
4089
4090 while ((qobj = TAILQ_FIRST(&queue->objects)) != NULL) {
4091 TAILQ_REMOVE(&queue->objects, qobj, list);
4092 Py_DECREF(qobj->obj);
4093 kore_pool_put(&queue_object_pool, qobj);
4094 }
4095
4096 while ((waiting = TAILQ_FIRST(&queue->waiting)) != NULL) {
4097 TAILQ_REMOVE(&queue->waiting, waiting, list);
4098 if (waiting->op != NULL)
4099 waiting->op->waiting = NULL;
4100 kore_pool_put(&queue_wait_pool, waiting);
4101 }
4102
4103 PyObject_Del((PyObject *)queue);
4104 }
4105
4106 static PyObject *
4107 pyqueue_pop(struct pyqueue *queue, PyObject *args)
4108 {
4109 struct pyqueue_op *op;
4110
4111 if ((op = PyObject_New(struct pyqueue_op, &pyqueue_op_type)) == NULL)
4112 return (NULL);
4113
4114 op->queue = queue;
4115 op->waiting = kore_pool_get(&queue_wait_pool);
4116 op->waiting->op = op;
4117
4118 op->waiting->coro = coro_running;
4119 TAILQ_INSERT_TAIL(&queue->waiting, op->waiting, list);
4120
4121 Py_INCREF((PyObject *)queue);
4122
4123 return ((PyObject *)op);
4124 }
4125
4126 static PyObject *
4127 pyqueue_popnow(struct pyqueue *queue, PyObject *args)
4128 {
4129 PyObject *obj;
4130 struct pyqueue_object *qobj;
4131
4132 if ((qobj = TAILQ_FIRST(&queue->objects)) == NULL) {
4133 Py_RETURN_NONE;
4134 }
4135
4136 TAILQ_REMOVE(&queue->objects, qobj, list);
4137
4138 obj = qobj->obj;
4139 kore_pool_put(&queue_object_pool, qobj);
4140
4141 return (obj);
4142 }
4143
4144 static PyObject *
4145 pyqueue_push(struct pyqueue *queue, PyObject *args)
4146 {
4147 PyObject *obj;
4148 struct pyqueue_object *qobj;
4149 struct pyqueue_waiting *waiting;
4150
4151 if (!PyArg_ParseTuple(args, "O", &obj))
4152 return (NULL);
4153
4154 Py_INCREF(obj);
4155
4156 qobj = kore_pool_get(&queue_object_pool);
4157 qobj ->obj = obj;
4158
4159 TAILQ_INSERT_TAIL(&queue->objects, qobj, list);
4160
4161 /* Wakeup first in line if any. */
4162 if ((waiting = TAILQ_FIRST(&queue->waiting)) != NULL) {
4163 TAILQ_REMOVE(&queue->waiting, waiting, list);
4164
4165 /* wakeup HTTP request if one is tied. */
4166 if (waiting->coro->request != NULL)
4167 http_request_wakeup(waiting->coro->request);
4168 else
4169 python_coro_wakeup(waiting->coro);
4170
4171 waiting->op->waiting = NULL;
4172 kore_pool_put(&queue_wait_pool, waiting);
4173 }
4174
4175 Py_RETURN_TRUE;
4176 }
4177
4178 static void
4179 pyqueue_op_dealloc(struct pyqueue_op *op)
4180 {
4181 if (op->waiting != NULL) {
4182 TAILQ_REMOVE(&op->queue->waiting, op->waiting, list);
4183 kore_pool_put(&queue_wait_pool, op->waiting);
4184 op->waiting = NULL;
4185 }
4186
4187 Py_DECREF((PyObject *)op->queue);
4188 PyObject_Del((PyObject *)op);
4189 }
4190
4191 static PyObject *
4192 pyqueue_op_await(PyObject *obj)
4193 {
4194 Py_INCREF(obj);
4195 return (obj);
4196 }
4197
4198 static PyObject *
4199 pyqueue_op_iternext(struct pyqueue_op *op)
4200 {
4201 PyObject *obj;
4202 struct pyqueue_object *qobj;
4203 struct pyqueue_waiting *waiting;
4204
4205 if ((qobj = TAILQ_FIRST(&op->queue->objects)) == NULL) {
4206 Py_RETURN_NONE;
4207 }
4208
4209 TAILQ_REMOVE(&op->queue->objects, qobj, list);
4210
4211 obj = qobj->obj;
4212 kore_pool_put(&queue_object_pool, qobj);
4213
4214 TAILQ_FOREACH(waiting, &op->queue->waiting, list) {
4215 if (waiting->coro->id == coro_running->id) {
4216 TAILQ_REMOVE(&op->queue->waiting, waiting, list);
4217 waiting->op->waiting = NULL;
4218 kore_pool_put(&queue_wait_pool, waiting);
4219 break;
4220 }
4221 }
4222
4223 PyErr_SetObject(PyExc_StopIteration, obj);
4224 Py_DECREF(obj);
4225
4226 return (NULL);
4227 }
4228
4229 static void
4230 pylock_dealloc(struct pylock *lock)
4231 {
4232 struct pylock_op *op;
4233
4234 while ((op = TAILQ_FIRST(&lock->ops)) != NULL) {
4235 TAILQ_REMOVE(&lock->ops, op, list);
4236 op->active = 0;
4237 op->coro->lockop = NULL;
4238 Py_DECREF((PyObject *)op);
4239 }
4240
4241 PyObject_Del((PyObject *)lock);
4242 }
4243
4244 static PyObject *
4245 pylock_trylock(struct pylock *lock, PyObject *args)
4246 {
4247 if (lock->owner != NULL)
4248 Py_RETURN_FALSE;
4249
4250 lock->owner = coro_running;
4251
4252 Py_RETURN_TRUE;
4253 }
4254
4255 static PyObject *
4256 pylock_release(struct pylock *lock, PyObject *args)
4257 {
4258 if (lock->owner == NULL) {
4259 PyErr_SetString(PyExc_RuntimeError, "no lock owner set");
4260 return (NULL);
4261 }
4262
4263 if (lock->owner->id != coro_running->id) {
4264 PyErr_SetString(PyExc_RuntimeError, "lock not owned by caller");
4265 return (NULL);
4266 }
4267
4268 pylock_do_release(lock);
4269
4270 Py_RETURN_NONE;
4271 }
4272
4273 static PyObject *
4274 pylock_aenter(struct pylock *lock, PyObject *args)
4275 {
4276 struct pylock_op *op;
4277
4278 if (coro_running->lockop != NULL) {
4279 fatal("%s: lockop not NULL for %" PRIu64,
4280 __func__, coro_running->id);
4281 }
4282
4283 if (lock->owner != NULL && lock->owner->id == coro_running->id) {
4284 PyErr_SetString(PyExc_RuntimeError, "recursive lock detected");
4285 return (NULL);
4286 }
4287
4288 if ((op = PyObject_New(struct pylock_op, &pylock_op_type)) == NULL)
4289 return (NULL);
4290
4291 op->active = 1;
4292 op->lock = lock;
4293 op->locking = 1;
4294 op->coro = coro_running;
4295
4296 coro_running->lockop = op;
4297
4298 Py_INCREF((PyObject *)op);
4299 Py_INCREF((PyObject *)lock);
4300
4301 TAILQ_INSERT_TAIL(&lock->ops, op, list);
4302
4303 return ((PyObject *)op);
4304 }
4305
4306 static PyObject *
4307 pylock_aexit(struct pylock *lock, PyObject *args)
4308 {
4309 struct pylock_op *op;
4310
4311 if (coro_running->lockop != NULL) {
4312 fatal("%s: lockop not NULL for %" PRIu64,
4313 __func__, coro_running->id);
4314 }
4315
4316 if (lock->owner == NULL || lock->owner->id != coro_running->id) {
4317 PyErr_SetString(PyExc_RuntimeError, "invalid lock owner");
4318 return (NULL);
4319 }
4320
4321 if ((op = PyObject_New(struct pylock_op, &pylock_op_type)) == NULL)
4322 return (NULL);
4323
4324 op->active = 1;
4325 op->lock = lock;
4326 op->locking = 0;
4327 op->coro = coro_running;
4328
4329 coro_running->lockop = op;
4330
4331 Py_INCREF((PyObject *)op);
4332 Py_INCREF((PyObject *)lock);
4333
4334 TAILQ_INSERT_TAIL(&lock->ops, op, list);
4335
4336 return ((PyObject *)op);
4337 }
4338
4339 static void
4340 pylock_do_release(struct pylock *lock)
4341 {
4342 struct pylock_op *op;
4343
4344 lock->owner = NULL;
4345
4346 TAILQ_FOREACH(op, &lock->ops, list) {
4347 if (op->locking == 0)
4348 continue;
4349
4350 op->active = 0;
4351 op->coro->lockop = NULL;
4352 TAILQ_REMOVE(&lock->ops, op, list);
4353
4354 if (op->coro->request != NULL)
4355 http_request_wakeup(op->coro->request);
4356 else
4357 python_coro_wakeup(op->coro);
4358
4359 Py_DECREF((PyObject *)op);
4360 break;
4361 }
4362 }
4363
4364 static void
4365 pylock_op_dealloc(struct pylock_op *op)
4366 {
4367 if (op->active) {
4368 TAILQ_REMOVE(&op->lock->ops, op, list);
4369 op->active = 0;
4370 }
4371
4372 op->coro->lockop = NULL;
4373
4374 Py_DECREF((PyObject *)op->lock);
4375 PyObject_Del((PyObject *)op);
4376 }
4377
4378 static PyObject *
4379 pylock_op_await(PyObject *obj)
4380 {
4381 Py_INCREF(obj);
4382 return (obj);
4383 }
4384
4385 static PyObject *
4386 pylock_op_iternext(struct pylock_op *op)
4387 {
4388 if (op->locking == 0) {
4389 if (op->lock->owner == NULL) {
4390 PyErr_SetString(PyExc_RuntimeError,
4391 "no lock owner set");
4392 return (NULL);
4393 }
4394
4395 if (op->lock->owner->id != coro_running->id) {
4396 PyErr_SetString(PyExc_RuntimeError,
4397 "lock not owned by caller");
4398 return (NULL);
4399 }
4400
4401 pylock_do_release(op->lock);
4402 } else {
4403 if (op->lock->owner != NULL) {
4404 /*
4405 * We could be beat by another coroutine that grabbed
4406 * the lock even if we were the one woken up for it.
4407 */
4408 if (op->active == 0) {
4409 op->active = 1;
4410 op->coro->lockop = op;
4411 TAILQ_INSERT_HEAD(&op->lock->ops, op, list);
4412 Py_INCREF((PyObject *)op);
4413 }
4414 Py_RETURN_NONE;
4415 }
4416
4417 op->lock->owner = coro_running;
4418 }
4419
4420 if (op->active) {
4421 op->active = 0;
4422 op->coro->lockop = NULL;
4423 TAILQ_REMOVE(&op->lock->ops, op, list);
4424 Py_DECREF((PyObject *)op);
4425 }
4426
4427 PyErr_SetNone(PyExc_StopIteration);
4428
4429 return (NULL);
4430 }
4431
4432 static void
4433 pyproc_timeout(void *arg, u_int64_t now)
4434 {
4435 struct pyproc *proc = arg;
4436
4437 proc->timer = NULL;
4438
4439 if (proc->coro->sockop != NULL)
4440 proc->coro->sockop->eof = 1;
4441
4442 proc->coro->exception = PyExc_TimeoutError;
4443 proc->coro->exception_msg = "timeout before process exited";
4444
4445 if (proc->coro->request != NULL)
4446 http_request_wakeup(proc->coro->request);
4447 else
4448 python_coro_wakeup(proc->coro);
4449 }
4450
4451 static void
4452 pyproc_dealloc(struct pyproc *proc)
4453 {
4454 int status;
4455
4456 TAILQ_REMOVE(&procs, proc, list);
4457
4458 if (proc->timer != NULL) {
4459 kore_timer_remove(proc->timer);
4460 proc->timer = NULL;
4461 }
4462
4463 if (proc->pid != -1) {
4464 if (kill(proc->pid, SIGKILL) == -1) {
4465 kore_log(LOG_NOTICE,
4466 "kore.proc failed to send SIGKILL %d (%s)",
4467 proc->pid, errno_s);
4468 }
4469
4470 for (;;) {
4471 if (waitpid(proc->pid, &status, 0) == -1) {
4472 if (errno == EINTR)
4473 continue;
4474 kore_log(LOG_NOTICE,
4475 "kore.proc failed to wait for %d (%s)",
4476 proc->pid, errno_s);
4477 }
4478 break;
4479 }
4480 }
4481
4482 if (proc->in != NULL) {
4483 Py_DECREF((PyObject *)proc->in);
4484 proc->in = NULL;
4485 }
4486
4487 if (proc->out != NULL) {
4488 Py_DECREF((PyObject *)proc->out);
4489 proc->out = NULL;
4490 }
4491
4492 PyObject_Del((PyObject *)proc);
4493 }
4494
4495 static PyObject *
4496 pyproc_kill(struct pyproc *proc, PyObject *args)
4497 {
4498 if (proc->pid != -1 && kill(proc->pid, SIGKILL) == -1)
4499 kore_log(LOG_NOTICE, "kill(%d): %s", proc->pid, errno_s);
4500
4501 Py_RETURN_TRUE;
4502 }
4503
4504 static PyObject *
4505 pyproc_reap(struct pyproc *proc, PyObject *args)
4506 {
4507 struct pyproc_op *op;
4508
4509 if (proc->op != NULL) {
4510 PyErr_Format(PyExc_RuntimeError,
4511 "process %d already being reaped", proc->apid);
4512 return (NULL);
4513 }
4514
4515 if (proc->timer != NULL) {
4516 kore_timer_remove(proc->timer);
4517 proc->timer = NULL;
4518 }
4519
4520 if ((op = PyObject_New(struct pyproc_op, &pyproc_op_type)) == NULL)
4521 return (NULL);
4522
4523 op->proc = proc;
4524 op->coro = coro_running;
4525
4526 proc->op = op;
4527
4528 Py_INCREF((PyObject *)proc);
4529
4530 return ((PyObject *)op);
4531 }
4532
4533 static PyObject *
4534 pyproc_recv(struct pyproc *proc, PyObject *args)
4535 {
4536 Py_ssize_t len;
4537 struct pysocket_op *op;
4538 PyObject *obj;
4539 int timeo;
4540
4541 timeo = -1;
4542
4543 if (proc->out == NULL) {
4544 PyErr_SetString(PyExc_RuntimeError, "stdout closed");
4545 return (NULL);
4546 }
4547
4548 if (!PyArg_ParseTuple(args, "n|i", &len, &timeo))
4549 return (NULL);
4550
4551 obj = pysocket_op_create(proc->out, PYSOCKET_TYPE_RECV, NULL, len);
4552 if (obj == NULL)
4553 return (NULL);
4554
4555 op = (struct pysocket_op *)obj;
4556
4557 if (timeo != -1) {
4558 op->timer = kore_timer_add(pysocket_op_timeout,
4559 timeo, op, KORE_TIMER_ONESHOT);
4560 }
4561
4562 return (obj);
4563 }
4564
4565 static PyObject *
4566 pyproc_send(struct pyproc *proc, PyObject *args)
4567 {
4568 Py_buffer buf;
4569 PyObject *ret;
4570
4571 if (proc->in == NULL) {
4572 PyErr_SetString(PyExc_RuntimeError, "stdin closed");
4573 return (NULL);
4574 }
4575
4576 if (!PyArg_ParseTuple(args, "y*", &buf))
4577 return (NULL);
4578
4579 ret = pysocket_op_create(proc->in,
4580 PYSOCKET_TYPE_SEND, buf.buf, buf.len);
4581
4582 PyBuffer_Release(&buf);
4583
4584 return (ret);
4585 }
4586
4587 static PyObject *
4588 pyproc_close_stdin(struct pyproc *proc, PyObject *args)
4589 {
4590 if (proc->in != NULL) {
4591 Py_DECREF((PyObject *)proc->in);
4592 proc->in = NULL;
4593 }
4594
4595 Py_RETURN_TRUE;
4596 }
4597
4598 static PyObject *
4599 pyproc_get_pid(struct pyproc *proc, void *closure)
4600 {
4601 return (PyLong_FromLong(proc->apid));
4602 }
4603
4604 static void
4605 pyproc_op_dealloc(struct pyproc_op *op)
4606 {
4607 Py_DECREF((PyObject *)op->proc);
4608 PyObject_Del((PyObject *)op);
4609 }
4610
4611 static PyObject *
4612 pyproc_op_await(PyObject *sop)
4613 {
4614 Py_INCREF(sop);
4615 return (sop);
4616 }
4617
4618 static PyObject *
4619 pyproc_op_iternext(struct pyproc_op *op)
4620 {
4621 int ret;
4622 PyObject *res;
4623
4624 if (op->proc->coro->exception != NULL) {
4625 PyErr_SetString(op->proc->coro->exception,
4626 op->proc->coro->exception_msg);
4627 op->proc->coro->exception = NULL;
4628 return (NULL);
4629 }
4630
4631 if (op->proc->reaped == 0)
4632 Py_RETURN_NONE;
4633
4634 if (WIFSTOPPED(op->proc->status)) {
4635 op->proc->reaped = 0;
4636 Py_RETURN_NONE;
4637 }
4638
4639 if (WIFEXITED(op->proc->status)) {
4640 ret = WEXITSTATUS(op->proc->status);
4641 } else {
4642 ret = op->proc->status;
4643 }
4644
4645 if ((res = PyLong_FromLong(ret)) == NULL)
4646 return (NULL);
4647
4648 PyErr_SetObject(PyExc_StopIteration, res);
4649 Py_DECREF(res);
4650
4651 return (NULL);
4652 }
4653
4654 static void
4655 pygather_reap_coro(struct pygather_op *op, struct python_coro *reap)
4656 {
4657 struct pygather_coro *coro;
4658 struct pygather_result *result;
4659 #if PY_VERSION_HEX >= 0x030A0000
4660 PyObject *type, *traceback;
4661 #endif
4662
4663 TAILQ_FOREACH(coro, &op->coroutines, list) {
4664 if (coro->coro->id == reap->id)
4665 break;
4666 }
4667
4668 if (coro == NULL)
4669 fatal("coroutine %" PRIu64 " not found in gather", reap->id);
4670
4671 op->running--;
4672 if (op->running < 0)
4673 fatal("gatherop: running miscount (%d)", op->running);
4674
4675 result = kore_pool_get(&gather_result_pool);
4676 result->obj = NULL;
4677
4678 #if PY_VERSION_HEX < 0x030A0000
4679 if (_PyGen_FetchStopIterationValue(&result->obj) == -1) {
4680 result->obj = Py_None;
4681 Py_INCREF(Py_None);
4682 }
4683 #else
4684 if (PyErr_Occurred()) {
4685 Py_XDECREF(coro->coro->result);
4686 PyErr_Fetch(&type, &coro->coro->result, &traceback);
4687 Py_DECREF(type);
4688 Py_XDECREF(traceback);
4689 } else {
4690 if (coro->coro->result == NULL) {
4691 coro->coro->result = Py_None;
4692 Py_INCREF(Py_None);
4693 }
4694 }
4695
4696 result->obj = coro->coro->result;
4697 Py_INCREF(result->obj);
4698 #endif
4699
4700 TAILQ_INSERT_TAIL(&op->results, result, list);
4701
4702 TAILQ_REMOVE(&op->coroutines, coro, list);
4703 kore_pool_put(&gather_coro_pool, coro);
4704
4705 kore_python_coro_delete(reap);
4706 }
4707
4708 static void
4709 pygather_op_dealloc(struct pygather_op *op)
4710 {
4711 struct python_coro *old;
4712 struct pygather_coro *coro, *next;
4713 struct pygather_result *res, *rnext;
4714
4715 /*
4716 * Since we are calling kore_python_coro_delete() on all the
4717 * remaining coroutines in this gather op we must remember the
4718 * original coroutine that is running as the removal will end
4719 * up setting coro_running to NULL.
4720 */
4721 old = coro_running;
4722
4723 for (coro = TAILQ_FIRST(&op->coroutines); coro != NULL; coro = next) {
4724 next = TAILQ_NEXT(coro, list);
4725 TAILQ_REMOVE(&op->coroutines, coro, list);
4726
4727 /* Make sure we don't end up in pygather_reap_coro(). */
4728 coro->coro->gatherop = NULL;
4729
4730 kore_python_coro_delete(coro->coro);
4731 kore_pool_put(&gather_coro_pool, coro);
4732 }
4733
4734 coro_running = old;
4735
4736 for (res = TAILQ_FIRST(&op->results); res != NULL; res = rnext) {
4737 rnext = TAILQ_NEXT(res, list);
4738 TAILQ_REMOVE(&op->results, res, list);
4739
4740 Py_DECREF(res->obj);
4741 kore_pool_put(&gather_result_pool, res);
4742 }
4743
4744 PyObject_Del((PyObject *)op);
4745 }
4746
4747 static PyObject *
4748 pygather_op_await(PyObject *obj)
4749 {
4750 Py_INCREF(obj);
4751 return (obj);
4752 }
4753
4754 static PyObject *
4755 pygather_op_iternext(struct pygather_op *op)
4756 {
4757 int idx;
4758 struct pygather_coro *coro;
4759 struct pygather_result *res, *next;
4760 PyObject *list, *obj;
4761
4762 if (!TAILQ_EMPTY(&op->coroutines)) {
4763 if (op->running > 0)
4764 Py_RETURN_NONE;
4765
4766 TAILQ_FOREACH(coro, &op->coroutines, list) {
4767 if (op->running >= op->concurrency)
4768 break;
4769 python_coro_wakeup(coro->coro);
4770 op->running++;
4771 }
4772
4773 Py_RETURN_NONE;
4774 }
4775
4776 if ((list = PyList_New(op->count)) == NULL)
4777 return (NULL);
4778
4779 idx = 0;
4780
4781 for (res = TAILQ_FIRST(&op->results); res != NULL; res = next) {
4782 next = TAILQ_NEXT(res, list);
4783 TAILQ_REMOVE(&op->results, res, list);
4784
4785 obj = res->obj;
4786 res->obj = NULL;
4787 kore_pool_put(&gather_result_pool, res);
4788
4789 if (PyList_SetItem(list, idx++, obj) != 0) {
4790 Py_DECREF(list);
4791 return (NULL);
4792 }
4793 }
4794
4795 PyErr_SetObject(PyExc_StopIteration, list);
4796 Py_DECREF(list);
4797
4798 return (NULL);
4799 }
4800
4801 static PyObject *
4802 pyhttp_request_alloc(const struct http_request *req)
4803 {
4804 union { const void *cp; void *p; } ptr;
4805 struct pyhttp_request *pyreq;
4806
4807 pyreq = PyObject_New(struct pyhttp_request, &pyhttp_request_type);
4808 if (pyreq == NULL)
4809 return (NULL);
4810
4811 /*
4812 * Hack around all http apis taking a non-const pointer and us having
4813 * a const pointer for the req data structure. This is because we
4814 * could potentially be called from a validator where the argument
4815 * is a http_request pointer.
4816 */
4817 ptr.cp = req;
4818 pyreq->req = ptr.p;
4819 pyreq->data = NULL;
4820 pyreq->dict = NULL;
4821
4822 return ((PyObject *)pyreq);
4823 }
4824
4825 static PyObject *
4826 pyhttp_file_alloc(struct http_file *file)
4827 {
4828 struct pyhttp_file *pyfile;
4829
4830 pyfile = PyObject_New(struct pyhttp_file, &pyhttp_file_type);
4831 if (pyfile == NULL)
4832 return (NULL);
4833
4834 pyfile->file = file;
4835
4836 return ((PyObject *)pyfile);
4837 }
4838
4839 static int
4840 pyhttp_preprocess(struct http_request *req)
4841 {
4842 struct reqcall *rq;
4843 PyObject *ret;
4844
4845 rq = req->py_rqnext;
4846
4847 while (rq) {
4848 req->py_rqnext = TAILQ_NEXT(rq, list);
4849
4850 PyErr_Clear();
4851 ret = PyObject_CallFunctionObjArgs(rq->f, req->py_req, NULL);
4852
4853 if (ret == NULL) {
4854 kore_python_log_error("preprocess");
4855 http_response(req, HTTP_STATUS_INTERNAL_ERROR, NULL, 0);
4856 return (KORE_RESULT_ERROR);
4857 }
4858
4859 if (ret == Py_False) {
4860 Py_DECREF(ret);
4861 return (KORE_RESULT_ERROR);
4862 }
4863
4864 if (PyCoro_CheckExact(ret)) {
4865 req->py_coro = python_coro_create(ret, req);
4866 if (python_coro_run(req->py_coro) == KORE_RESULT_OK) {
4867 http_request_wakeup(req);
4868 kore_python_coro_delete(req->py_coro);
4869 req->py_coro = NULL;
4870 rq = req->py_rqnext;
4871 continue;
4872 }
4873 return (KORE_RESULT_RETRY);
4874 }
4875
4876 Py_DECREF(ret);
4877 rq = req->py_rqnext;
4878 }
4879
4880 return (KORE_RESULT_OK);
4881 }
4882
4883 static PyObject *
4884 pyhttp_response(struct pyhttp_request *pyreq, PyObject *args)
4885 {
4886 struct connection *c;
4887 char *ptr;
4888 Py_ssize_t length;
4889 int status;
4890 struct pyhttp_iterobj *iterobj;
4891 PyObject *obj, *iterator;
4892
4893 length = -1;
4894
4895 if (!PyArg_ParseTuple(args, "iO", &status, &obj))
4896 return (NULL);
4897
4898 if (PyBytes_CheckExact(obj)) {
4899 if (PyBytes_AsStringAndSize(obj, &ptr, &length) == -1)
4900 return (NULL);
4901
4902 if (length < 0) {
4903 PyErr_SetString(PyExc_TypeError, "invalid length");
4904 return (NULL);
4905 }
4906
4907 Py_INCREF(obj);
4908
4909 http_response_stream(pyreq->req, status, ptr, length,
4910 pyhttp_response_sent, obj);
4911 } else if (obj == Py_None) {
4912 http_response(pyreq->req, status, NULL, 0);
4913 } else {
4914 c = pyreq->req->owner;
4915 if (c->state == CONN_STATE_DISCONNECTING) {
4916 Py_RETURN_FALSE;
4917 }
4918
4919 if ((iterator = PyObject_GetIter(obj)) == NULL)
4920 return (NULL);
4921
4922 iterobj = kore_pool_get(&iterobj_pool);
4923 iterobj->iterator = iterator;
4924 iterobj->connection = c;
4925 iterobj->remove = 0;
4926
4927 kore_buf_init(&iterobj->buf, 4096);
4928
4929 c->hdlr_extra = iterobj;
4930 c->flags |= CONN_IS_BUSY;
4931 c->disconnect = pyhttp_iterobj_disconnect;
4932
4933 pyreq->req->flags |= HTTP_REQUEST_NO_CONTENT_LENGTH;
4934 http_response_header(pyreq->req, "transfer-encoding",
4935 "chunked");
4936
4937 http_response(pyreq->req, status, NULL, 0);
4938 pyhttp_iterobj_next(iterobj);
4939 }
4940
4941 Py_RETURN_TRUE;
4942 }
4943
4944 static int
4945 pyhttp_response_sent(struct netbuf *nb)
4946 {
4947 PyObject *data;
4948
4949 data = nb->extra;
4950 Py_DECREF(data);
4951
4952 return (KORE_RESULT_OK);
4953 }
4954
4955 static int
4956 pyhttp_iterobj_next(struct pyhttp_iterobj *iterobj)
4957 {
4958 struct netbuf *nb;
4959 PyObject *obj;
4960 const char *ptr;
4961 Py_ssize_t length;
4962
4963 PyErr_Clear();
4964
4965 if ((obj = PyIter_Next(iterobj->iterator)) == NULL) {
4966 if (PyErr_Occurred()) {
4967 kore_python_log_error("pyhttp_iterobj_next");
4968 return (KORE_RESULT_ERROR);
4969 }
4970
4971 return (KORE_RESULT_OK);
4972 }
4973
4974 if ((ptr = PyUnicode_AsUTF8AndSize(obj, &length)) == NULL) {
4975 kore_python_log_error("pyhttp_iterobj_next");
4976 return (KORE_RESULT_ERROR);
4977 }
4978
4979 kore_buf_reset(&iterobj->buf);
4980 kore_buf_appendf(&iterobj->buf, "%lx\r\n", length);
4981 kore_buf_append(&iterobj->buf, ptr, length);
4982 kore_buf_appendf(&iterobj->buf, "\r\n");
4983
4984 Py_DECREF(obj);
4985
4986 net_send_stream(iterobj->connection, iterobj->buf.data,
4987 iterobj->buf.offset, pyhttp_iterobj_chunk_sent, &nb);
4988
4989 nb->extra = iterobj;
4990
4991 return (KORE_RESULT_RETRY);
4992 }
4993
4994 static int
4995 pyhttp_iterobj_chunk_sent(struct netbuf *nb)
4996 {
4997 int ret;
4998 struct pyhttp_iterobj *iterobj;
4999
5000 iterobj = nb->extra;
5001
5002 if (iterobj->remove) {
5003 ret = KORE_RESULT_ERROR;
5004 } else {
5005 ret = pyhttp_iterobj_next(iterobj);
5006 }
5007
5008 if (ret != KORE_RESULT_RETRY) {
5009 iterobj->connection->hdlr_extra = NULL;
5010 iterobj->connection->disconnect = NULL;
5011 iterobj->connection->flags &= ~CONN_IS_BUSY;
5012
5013 if (iterobj->remove == 0)
5014 http_start_recv(iterobj->connection);
5015
5016 kore_buf_reset(&iterobj->buf);
5017 kore_buf_appendf(&iterobj->buf, "0\r\n\r\n");
5018 net_send_queue(iterobj->connection,
5019 iterobj->buf.data, iterobj->buf.offset);
5020
5021 Py_DECREF(iterobj->iterator);
5022
5023 kore_buf_cleanup(&iterobj->buf);
5024 kore_pool_put(&iterobj_pool, iterobj);
5025 } else {
5026 ret = KORE_RESULT_OK;
5027 }
5028
5029 return (ret);
5030 }
5031
5032 static void
5033 pyhttp_iterobj_disconnect(struct connection *c)
5034 {
5035 struct pyhttp_iterobj *iterobj;
5036
5037 iterobj = c->hdlr_extra;
5038 iterobj->remove = 1;
5039 c->hdlr_extra = NULL;
5040 }
5041
5042 static PyObject *
5043 pyhttp_response_header(struct pyhttp_request *pyreq, PyObject *args)
5044 {
5045 const char *header, *value;
5046
5047 if (!PyArg_ParseTuple(args, "ss", &header, &value))
5048 return (NULL);
5049
5050 http_response_header(pyreq->req, header, value);
5051
5052 Py_RETURN_TRUE;
5053 }
5054
5055 static PyObject *
5056 pyhttp_request_header(struct pyhttp_request *pyreq, PyObject *args)
5057 {
5058 const char *value;
5059 const char *header;
5060 PyObject *result;
5061
5062 if (!PyArg_ParseTuple(args, "s", &header))
5063 return (NULL);
5064
5065 if (!http_request_header(pyreq->req, header, &value)) {
5066 Py_RETURN_NONE;
5067 }
5068
5069 if ((result = PyUnicode_FromString(value)) == NULL)
5070 return (PyErr_NoMemory());
5071
5072 return (result);
5073 }
5074
5075 static PyObject *
5076 pyhttp_body_read(struct pyhttp_request *pyreq, PyObject *args)
5077 {
5078 ssize_t ret;
5079 size_t len;
5080 Py_ssize_t pylen;
5081 PyObject *result;
5082 u_int8_t buf[1024];
5083
5084 if (!PyArg_ParseTuple(args, "n", &pylen) || pylen < 0)
5085 return (NULL);
5086
5087 len = (size_t)pylen;
5088 if (len > sizeof(buf)) {
5089 PyErr_SetString(PyExc_RuntimeError, "len > sizeof(buf)");
5090 return (NULL);
5091 }
5092
5093 ret = http_body_read(pyreq->req, buf, len);
5094 if (ret == -1) {
5095 PyErr_SetString(PyExc_RuntimeError, "http_body_read() failed");
5096 return (NULL);
5097 }
5098
5099 result = Py_BuildValue("ny#", ret, buf, ret);
5100 if (result == NULL)
5101 return (PyErr_NoMemory());
5102
5103 return (result);
5104 }
5105
5106 static PyObject *
5107 pyhttp_populate_get(struct pyhttp_request *pyreq, PyObject *args)
5108 {
5109 http_populate_get(pyreq->req);
5110 Py_RETURN_TRUE;
5111 }
5112
5113 static PyObject *
5114 pyhttp_populate_post(struct pyhttp_request *pyreq, PyObject *args)
5115 {
5116 http_populate_post(pyreq->req);
5117 Py_RETURN_TRUE;
5118 }
5119
5120 static PyObject *
5121 pyhttp_populate_multi(struct pyhttp_request *pyreq, PyObject *args)
5122 {
5123 http_populate_multipart_form(pyreq->req);
5124 Py_RETURN_TRUE;
5125 }
5126
5127 static PyObject *
5128 pyhttp_populate_cookies(struct pyhttp_request *pyreq, PyObject *args)
5129 {
5130 http_populate_cookies(pyreq->req);
5131 Py_RETURN_TRUE;
5132 }
5133
5134 static PyObject *
5135 pyhttp_argument(struct pyhttp_request *pyreq, PyObject *args)
5136 {
5137 char *arg;
5138 const char *name;
5139 PyObject *value;
5140
5141 if (!PyArg_ParseTuple(args, "s", &name))
5142 return (NULL);
5143
5144 if (!http_argument_get_string(pyreq->req, name, &arg)) {
5145 Py_RETURN_NONE;
5146 }
5147
5148 if ((value = PyUnicode_FromString(arg)) == NULL)
5149 return (PyErr_NoMemory());
5150
5151 return (value);
5152 }
5153
5154 static PyObject *
5155 pyhttp_cookie(struct pyhttp_request *pyreq, PyObject *args)
5156 {
5157 char *arg;
5158 const char *name;
5159 PyObject *value;
5160
5161 if (!PyArg_ParseTuple(args, "s", &name))
5162 return (NULL);
5163
5164 if (!http_request_cookie(pyreq->req, name, &arg)) {
5165 Py_RETURN_NONE;
5166 }
5167
5168 if ((value = PyUnicode_FromString(arg)) == NULL)
5169 return (NULL);
5170
5171 return (value);
5172 }
5173
5174 static PyObject *
5175 pyhttp_headers(struct pyhttp_request *pyreq, PyObject *args)
5176 {
5177 struct http_header *hdr;
5178 struct http_request *req;
5179 PyObject *obj, *dict, *ret;
5180
5181 ret = NULL;
5182 obj = NULL;
5183 dict = NULL;
5184
5185 req = pyreq->req;
5186
5187 if ((dict = PyDict_New()) == NULL)
5188 goto cleanup;
5189
5190 if ((obj = PyUnicode_FromString(req->host)) == NULL)
5191 goto cleanup;
5192
5193 if (PyDict_SetItemString(dict, "host", obj) == -1)
5194 goto cleanup;
5195
5196 TAILQ_FOREACH(hdr, &req->req_headers, list) {
5197 if ((obj = PyUnicode_FromString(hdr->value)) == NULL)
5198 goto cleanup;
5199 if (PyDict_SetItemString(dict, hdr->header, obj) == -1)
5200 goto cleanup;
5201 }
5202
5203 ret = dict;
5204 obj = NULL;
5205 dict = NULL;
5206
5207 cleanup:
5208 Py_XDECREF(obj);
5209 Py_XDECREF(dict);
5210
5211 return (ret);
5212 }
5213
5214 static PyObject *
5215 pyhttp_file_lookup(struct pyhttp_request *pyreq, PyObject *args)
5216 {
5217 const char *name;
5218 struct http_file *file;
5219 PyObject *pyfile;
5220
5221 if (!PyArg_ParseTuple(args, "s", &name))
5222 return (NULL);
5223
5224 if ((file = http_file_lookup(pyreq->req, name)) == NULL) {
5225 Py_RETURN_NONE;
5226 }
5227
5228 if ((pyfile = pyhttp_file_alloc(file)) == NULL)
5229 return (PyErr_NoMemory());
5230
5231 return (pyfile);
5232 }
5233
5234 static PyObject *
5235 pyhttp_file_read(struct pyhttp_file *pyfile, PyObject *args)
5236 {
5237 ssize_t ret;
5238 size_t len;
5239 Py_ssize_t pylen;
5240 PyObject *result;
5241 u_int8_t buf[1024];
5242
5243 if (!PyArg_ParseTuple(args, "n", &pylen) || pylen < 0)
5244 return (NULL);
5245
5246 len = (size_t)pylen;
5247 if (len > sizeof(buf)) {
5248 PyErr_SetString(PyExc_RuntimeError, "len > sizeof(buf)");
5249 return (NULL);
5250 }
5251
5252 ret = http_file_read(pyfile->file, buf, len);
5253 if (ret == -1) {
5254 PyErr_SetString(PyExc_RuntimeError, "http_file_read() failed");
5255 return (NULL);
5256 }
5257
5258 result = Py_BuildValue("ny#", ret, buf, ret);
5259 if (result == NULL)
5260 return (PyErr_NoMemory());
5261
5262 return (result);
5263 }
5264
5265 static PyObject *
5266 pyhttp_websocket_handshake(struct pyhttp_request *pyreq, PyObject *args)
5267 {
5268 struct connection *c;
5269 PyObject *onconnect, *onmsg, *ondisconnect;
5270
5271 if (!PyArg_ParseTuple(args, "OOO", &onconnect, &onmsg, &ondisconnect))
5272 return (NULL);
5273
5274 kore_websocket_handshake(pyreq->req, NULL, NULL, NULL);
5275
5276 c = pyreq->req->owner;
5277
5278 Py_INCREF(onconnect);
5279 Py_INCREF(onmsg);
5280 Py_INCREF(ondisconnect);
5281
5282 c->ws_connect = kore_calloc(1, sizeof(struct kore_runtime_call));
5283 c->ws_connect->addr = onconnect;
5284 c->ws_connect->runtime = &kore_python_runtime;
5285
5286 c->ws_message = kore_calloc(1, sizeof(struct kore_runtime_call));
5287 c->ws_message->addr = onmsg;
5288 c->ws_message->runtime = &kore_python_runtime;
5289
5290 c->ws_disconnect = kore_calloc(1, sizeof(struct kore_runtime_call));
5291 c->ws_disconnect->addr = ondisconnect;
5292 c->ws_disconnect->runtime = &kore_python_runtime;
5293
5294 python_runtime_connect(onconnect, c);
5295
5296 Py_RETURN_TRUE;
5297 }
5298
5299 static PyObject *
5300 pyconnection_websocket_send(struct pyconnection *pyc, PyObject *args)
5301 {
5302 int op;
5303 ssize_t len;
5304 const char *data;
5305
5306 if (pyc->c->proto != CONN_PROTO_WEBSOCKET) {
5307 PyErr_SetString(PyExc_TypeError, "not a websocket connection");
5308 return (NULL);
5309 }
5310
5311 len = -1;
5312
5313 if (!PyArg_ParseTuple(args, "iy#", &op, &data, &len))
5314 return (NULL);
5315
5316 if (len < 0) {
5317 PyErr_SetString(PyExc_TypeError, "invalid length");
5318 return (NULL);
5319 }
5320
5321 switch (op) {
5322 case WEBSOCKET_OP_TEXT:
5323 case WEBSOCKET_OP_BINARY:
5324 break;
5325 default:
5326 PyErr_SetString(PyExc_TypeError, "invalid op parameter");
5327 return (NULL);
5328 }
5329
5330 kore_websocket_send(pyc->c, op, data, len);
5331
5332 Py_RETURN_TRUE;
5333 }
5334
5335 static PyObject *
5336 python_websocket_broadcast(PyObject *self, PyObject *args)
5337 {
5338 struct connection *c;
5339 ssize_t len;
5340 struct pyconnection *pyc;
5341 const char *data;
5342 PyObject *pysrc;
5343 int op, broadcast;
5344
5345 len = -1;
5346
5347 if (!PyArg_ParseTuple(args, "Oiy#i", &pysrc, &op, &data, &len,
5348 &broadcast))
5349 return (NULL);
5350
5351 if (len < 0) {
5352 PyErr_SetString(PyExc_TypeError, "invalid length");
5353 return (NULL);
5354 }
5355
5356 switch (op) {
5357 case WEBSOCKET_OP_TEXT:
5358 case WEBSOCKET_OP_BINARY:
5359 break;
5360 default:
5361 PyErr_SetString(PyExc_TypeError, "invalid op parameter");
5362 return (NULL);
5363 }
5364
5365 if (pysrc == Py_None) {
5366 c = NULL;
5367 } else {
5368 if (!PyObject_TypeCheck(pysrc, &pyconnection_type))
5369 return (NULL);
5370 pyc = (struct pyconnection *)pysrc;
5371 c = pyc->c;
5372 }
5373
5374 kore_websocket_broadcast(c, op, data, len, broadcast);
5375
5376 Py_RETURN_TRUE;
5377 }
5378
5379 static PyObject *
5380 pyhttp_get_host(struct pyhttp_request *pyreq, void *closure)
5381 {
5382 PyObject *host;
5383
5384 if ((host = PyUnicode_FromString(pyreq->req->host)) == NULL)
5385 return (PyErr_NoMemory());
5386
5387 return (host);
5388 }
5389
5390 static PyObject *
5391 pyhttp_get_path(struct pyhttp_request *pyreq, void *closure)
5392 {
5393 PyObject *path;
5394
5395 if ((path = PyUnicode_FromString(pyreq->req->path)) == NULL)
5396 return (PyErr_NoMemory());
5397
5398 return (path);
5399 }
5400
5401 static PyObject *
5402 pyhttp_get_body(struct pyhttp_request *pyreq, void *closure)
5403 {
5404 ssize_t ret;
5405 struct kore_buf buf;
5406 PyObject *body;
5407 u_int8_t data[BUFSIZ];
5408
5409 kore_buf_init(&buf, 1024);
5410 if (!http_body_rewind(pyreq->req)) {
5411 PyErr_SetString(PyExc_RuntimeError,
5412 "http_body_rewind() failed");
5413 return (NULL);
5414 }
5415
5416 for (;;) {
5417 ret = http_body_read(pyreq->req, data, sizeof(data));
5418 if (ret == -1) {
5419 kore_buf_cleanup(&buf);
5420 PyErr_SetString(PyExc_RuntimeError,
5421 "http_body_read() failed");
5422 return (NULL);
5423 }
5424
5425 if (ret == 0)
5426 break;
5427
5428 kore_buf_append(&buf, data, (size_t)ret);
5429 }
5430
5431 body = PyBytes_FromStringAndSize((char *)buf.data, buf.offset);
5432 kore_buf_free(&buf);
5433
5434 if (body == NULL)
5435 return (PyErr_NoMemory());
5436
5437 return (body);
5438 }
5439
5440 static PyObject *
5441 pyhttp_get_agent(struct pyhttp_request *pyreq, void *closure)
5442 {
5443 return (PyUnicode_FromString(pyreq->req->path));
5444 }
5445
5446 static PyObject *
5447 pyhttp_get_method(struct pyhttp_request *pyreq, void *closure)
5448 {
5449 return (PyLong_FromUnsignedLong(pyreq->req->method));
5450 }
5451
5452 static PyObject *
5453 pyhttp_get_protocol(struct pyhttp_request *pyreq, void *closure)
5454 {
5455 struct connection *c;
5456 const char *proto;
5457
5458 c = pyreq->req->owner;
5459
5460 if (c->owner->server->tls)
5461 proto = "https";
5462 else
5463 proto = "http";
5464
5465 return (PyUnicode_FromString(proto));
5466 }
5467
5468 static PyObject *
5469 pyhttp_get_body_path(struct pyhttp_request *pyreq, void *closure)
5470 {
5471 if (pyreq->req->http_body_path == NULL) {
5472 Py_RETURN_NONE;
5473 }
5474
5475 return (PyUnicode_FromString(pyreq->req->http_body_path));
5476 }
5477
5478 static PyObject *
5479 pyhttp_get_body_digest(struct pyhttp_request *pyreq, void *closure)
5480 {
5481 PyObject *digest;
5482
5483 digest = PyBytes_FromStringAndSize((char *)pyreq->req->http_body_digest,
5484 sizeof(pyreq->req->http_body_digest));
5485
5486 return (digest);
5487 }
5488
5489 static PyObject *
5490 pyhttp_get_connection(struct pyhttp_request *pyreq, void *closure)
5491 {
5492 PyObject *pyc;
5493
5494 if (pyreq->req->owner == NULL) {
5495 Py_RETURN_NONE;
5496 }
5497
5498 if ((pyc = pyconnection_alloc(pyreq->req->owner)) == NULL)
5499 return (PyErr_NoMemory());
5500
5501 return (pyc);
5502 }
5503
5504 static PyObject *
5505 pyhttp_file_get_name(struct pyhttp_file *pyfile, void *closure)
5506 {
5507 PyObject *name;
5508
5509 if ((name = PyUnicode_FromString(pyfile->file->name)) == NULL)
5510 return (PyErr_NoMemory());
5511
5512 return (name);
5513 }
5514
5515 static PyObject *
5516 pyhttp_file_get_filename(struct pyhttp_file *pyfile, void *closure)
5517 {
5518 PyObject *name;
5519
5520 if ((name = PyUnicode_FromString(pyfile->file->filename)) == NULL)
5521 return (PyErr_NoMemory());
5522
5523 return (name);
5524 }
5525
5526 void
5527 pyroute_dealloc(struct pyroute *route)
5528 {
5529 kore_free(route->path);
5530
5531 Py_XDECREF(route->func);
5532 Py_XDECREF(route->kwargs);
5533
5534 PyObject_Del((PyObject *)route);
5535 }
5536
5537 static PyObject *
5538 pyroute_inner(struct pyroute *route, PyObject *args)
5539 {
5540 PyObject *obj;
5541
5542 if (!PyArg_ParseTuple(args, "O", &obj))
5543 return (NULL);
5544
5545 if (!PyCallable_Check(obj))
5546 return (NULL);
5547
5548 route->func = obj;
5549 Py_INCREF(route->func);
5550
5551 TAILQ_INSERT_TAIL(&routes, route, list);
5552
5553 return (route->func);
5554 }
5555
5556 void
5557 pydomain_dealloc(struct pydomain *domain)
5558 {
5559 PyObject_Del((PyObject *)domain);
5560 }
5561
5562 static int
5563 pydomain_set_accesslog(struct pydomain *domain, PyObject *arg, void *closure)
5564 {
5565 const char *path;
5566
5567 if (!PyUnicode_CheckExact(arg))
5568 return (-1);
5569
5570 if (domain->config->accesslog != -1) {
5571 PyErr_Format(PyExc_RuntimeError,
5572 "domain %s accesslog already set", domain->config->domain);
5573 return (-1);
5574 }
5575
5576 path = PyUnicode_AsUTF8(arg);
5577
5578 domain->config->accesslog = open(path,
5579 O_CREAT | O_APPEND | O_WRONLY,
5580 S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
5581
5582 if (domain->config->accesslog == -1) {
5583 PyErr_Format(PyExc_RuntimeError,
5584 "failed to open accesslog for %s (%s:%s)",
5585 domain->config->domain, path, errno_s);
5586 return (-1);
5587 }
5588
5589 return (0);
5590 }
5591
5592 static PyObject *
5593 pydomain_filemaps(struct pydomain *domain, PyObject *args)
5594 {
5595 Py_ssize_t idx;
5596 struct kore_route *rt;
5597 const char *url, *path;
5598 PyObject *dict, *key, *value, *auth;
5599
5600 if (!PyArg_ParseTuple(args, "O", &dict))
5601 return (NULL);
5602
5603 if (!PyDict_CheckExact(dict)) {
5604 PyErr_SetString(PyExc_RuntimeError, "filemaps not a dict");
5605 return (NULL);
5606 }
5607
5608 idx = 0;
5609 while (PyDict_Next(dict, &idx, &key, &value)) {
5610 if (!PyUnicode_CheckExact(key)) {
5611 PyErr_SetString(PyExc_RuntimeError,
5612 "filemap key not a string");
5613 return (NULL);
5614 }
5615
5616 url = PyUnicode_AsUTF8(key);
5617
5618 if (!PyUnicode_CheckExact(value) &&
5619 !PyTuple_CheckExact(value)) {
5620 PyErr_SetString(PyExc_RuntimeError,
5621 "filemap value can be either be a string or tuple");
5622 return (NULL);
5623 }
5624
5625 if (PyTuple_CheckExact(value)) {
5626 auth = PyTuple_GetItem(value, 1);
5627 if (!PyDict_CheckExact(auth)) {
5628 PyErr_SetString(PyExc_RuntimeError,
5629 "filemap value tuple auth is not a dict");
5630 return (NULL);
5631 }
5632
5633 value = PyTuple_GetItem(value, 0);
5634 if (!PyUnicode_CheckExact(value)) {
5635 PyErr_SetString(PyExc_RuntimeError,
5636 "filemap value tuple path is invalid");
5637 return (NULL);
5638 }
5639 } else {
5640 auth = NULL;
5641 }
5642
5643 path = PyUnicode_AsUTF8(value);
5644
5645 rt = kore_filemap_create(domain->config, path, url, NULL);
5646 if (rt == NULL) {
5647 PyErr_Format(PyExc_RuntimeError,
5648 "failed to create filemap %s->%s for %s",
5649 url, path, domain->config->domain);
5650 return (NULL);
5651 }
5652
5653 if (auth != NULL) {
5654 if (!python_route_auth(auth, rt)) {
5655 kore_python_log_error("python_route_auth");
5656 kore_route_free(rt);
5657 return (KORE_RESULT_ERROR);
5658 }
5659 }
5660 }
5661
5662 Py_RETURN_NONE;
5663 }
5664
5665 static PyObject *
5666 pydomain_redirect(struct pydomain *domain, PyObject *args)
5667 {
5668 int status;
5669 const char *src, *dst;
5670
5671 if (!PyArg_ParseTuple(args, "sis", &src, &status, &dst))
5672 return (NULL);
5673
5674 if (!http_redirect_add(domain->config, src, status, dst)) {
5675 fatal("failed to add redirect '%s' on '%s'",
5676 src, domain->config->domain);
5677 }
5678
5679 Py_RETURN_NONE;
5680 }
5681
5682 static PyObject *
5683 pydomain_route(struct pydomain *domain, PyObject *args, PyObject *kwargs)
5684 {
5685 PyObject *obj;
5686 const char *path;
5687 struct pyroute *route;
5688
5689 if (!PyArg_ParseTuple(args, "sO", &path, &obj))
5690 return (NULL);
5691
5692 if (!PyCallable_Check(obj))
5693 return (NULL);
5694
5695 if ((route = PyObject_New(struct pyroute, &pyroute_type)) == NULL)
5696 return (NULL);
5697
5698 route->kwargs = kwargs;
5699 route->domain = domain->config;
5700 route->path = kore_strdup(path);
5701
5702 Py_XINCREF(route->kwargs);
5703
5704 route->func = obj;
5705 Py_INCREF(route->func);
5706
5707 TAILQ_INSERT_TAIL(&routes, route, list);
5708
5709 Py_RETURN_NONE;
5710 }
5711
5712 static int
5713 python_route_install(struct pyroute *route)
5714 {
5715 const char *val;
5716 struct kore_domain *domain;
5717 struct kore_route *rt, *entry;
5718 PyObject *kwargs, *repr, *obj;
5719
5720 if ((repr = PyObject_Repr(route->func)) == NULL) {
5721 kore_python_log_error("python_route_install");
5722 return (KORE_RESULT_ERROR);
5723 }
5724
5725 domain = python_route_domain_resolve(route);
5726
5727 rt = kore_calloc(1, sizeof(*rt));
5728 rt->dom = domain;
5729 rt->methods = HTTP_METHOD_ALL;
5730 rt->path = kore_strdup(route->path);
5731
5732 TAILQ_INIT(&rt->params);
5733
5734 val = PyUnicode_AsUTF8(repr);
5735 rt->func = kore_strdup(val);
5736
5737 kwargs = route->kwargs;
5738
5739 rt->rcall = kore_calloc(1, sizeof(struct kore_runtime_call));
5740 rt->rcall->addr = route->func;
5741 rt->rcall->runtime = &kore_python_runtime;
5742 Py_INCREF(rt->rcall->addr);
5743
5744 if (kwargs != NULL) {
5745 if ((obj = PyDict_GetItemString(kwargs, "methods")) != NULL) {
5746 if (!python_route_methods(obj, kwargs, rt)) {
5747 kore_python_log_error("python_route_install");
5748 kore_route_free(rt);
5749 return (KORE_RESULT_ERROR);
5750 }
5751 }
5752
5753 if ((obj = PyDict_GetItemString(kwargs, "auth")) != NULL) {
5754 if (!python_route_auth(obj, rt)) {
5755 kore_python_log_error("python_route_install");
5756 kore_route_free(rt);
5757 return (KORE_RESULT_ERROR);
5758 }
5759 }
5760
5761 if ((obj = PyDict_GetItemString(kwargs, "hooks")) != NULL) {
5762 if (!python_route_hooks(obj, rt)) {
5763 kore_python_log_error("python_route_install");
5764 kore_route_free(rt);
5765 return (KORE_RESULT_ERROR);
5766 }
5767 }
5768 }
5769
5770 if (rt->path[0] == '/') {
5771 rt->type = HANDLER_TYPE_STATIC;
5772 } else {
5773 rt->type = HANDLER_TYPE_DYNAMIC;
5774 if (regcomp(&rt->rctx, rt->path, REG_EXTENDED))
5775 fatal("failed to compile regex for '%s'", rt->path);
5776 }
5777
5778 TAILQ_FOREACH(entry, &domain->routes, list) {
5779 if (!strcmp(entry->path, rt->path) &&
5780 (entry->methods & rt->methods))
5781 fatal("duplicate route for '%s'", route->path);
5782 }
5783
5784 TAILQ_INSERT_TAIL(&domain->routes, rt, list);
5785
5786 return (KORE_RESULT_OK);
5787 }
5788
5789 static struct kore_domain *
5790 python_route_domain_resolve(struct pyroute *route)
5791 {
5792 struct kore_server *srv;
5793 const char *name;
5794 struct kore_domain *domain;
5795
5796 if (route->domain != NULL)
5797 return (route->domain);
5798
5799 if (route->kwargs != NULL)
5800 name = python_string_from_dict(route->kwargs, "domain");
5801 else
5802 name = NULL;
5803
5804 if (name != NULL) {
5805 domain = NULL;
5806 LIST_FOREACH(srv, &kore_servers, list) {
5807 TAILQ_FOREACH(domain, &srv->domains, list) {
5808 if (!strcmp(domain->domain, name))
5809 break;
5810 }
5811 }
5812
5813 if (domain == NULL)
5814 fatal("domain '%s' does not exist", name);
5815 } else {
5816 if ((domain = kore_domain_byid(1)) != NULL)
5817 fatal("ambiguous domain on route, please specify one");
5818 if ((domain = kore_domain_byid(0)) == NULL)
5819 fatal("no domains configured, please configure one");
5820 }
5821
5822 return (domain);
5823 }
5824
5825 static int
5826 python_route_methods(PyObject *obj, PyObject *kwargs, struct kore_route *rt)
5827 {
5828 const char *val;
5829 PyObject *item;
5830 int method;
5831 Py_ssize_t list_len, idx;
5832
5833 if (!PyList_CheckExact(obj)) {
5834 PyErr_SetString(PyExc_RuntimeError, "methods not a list");
5835 return (KORE_RESULT_ERROR);
5836 }
5837
5838 rt->methods = 0;
5839 list_len = PyList_Size(obj);
5840
5841 for (idx = 0; idx < list_len; idx++) {
5842 if ((item = PyList_GetItem(obj, idx)) == NULL)
5843 return (KORE_RESULT_ERROR);
5844
5845 if ((val = PyUnicode_AsUTF8(item)) == NULL)
5846 return (KORE_RESULT_ERROR);
5847
5848 if ((method = http_method_value(val)) == 0) {
5849 PyErr_Format(PyExc_RuntimeError,
5850 "unknown HTTP method: %s", val);
5851 return (KORE_RESULT_ERROR);
5852 }
5853
5854 rt->methods |= method;
5855 if (method == HTTP_METHOD_GET)
5856 rt->methods |= HTTP_METHOD_HEAD;
5857
5858 if (!python_route_params(kwargs, rt, val, method, 0))
5859 return (KORE_RESULT_ERROR);
5860
5861 if (!python_route_params(kwargs, rt, "qs", method, 1))
5862 return (KORE_RESULT_ERROR);
5863 }
5864
5865 return (KORE_RESULT_OK);
5866 }
5867
5868 static int
5869 python_route_params(PyObject *kwargs, struct kore_route *rt,
5870 const char *method, int type, int qs)
5871 {
5872 Py_ssize_t idx;
5873 const char *val;
5874 int vtype;
5875 struct kore_validator *vldr;
5876 struct kore_route_params *param;
5877 PyObject *obj, *key, *item;
5878
5879 if ((obj = PyDict_GetItemString(kwargs, method)) == NULL)
5880 return (KORE_RESULT_OK);
5881
5882 if (!PyDict_CheckExact(obj))
5883 return (KORE_RESULT_ERROR);
5884
5885 idx = 0;
5886 while (PyDict_Next(obj, &idx, &key, &item)) {
5887 if (!PyUnicode_CheckExact(key))
5888 return (KORE_RESULT_ERROR);
5889
5890 val = PyUnicode_AsUTF8(key);
5891
5892 if (PyUnicode_CheckExact(item)) {
5893 vtype = KORE_VALIDATOR_TYPE_REGEX;
5894 } else if (PyCallable_Check(item)) {
5895 vtype = KORE_VALIDATOR_TYPE_FUNCTION;
5896 } else {
5897 PyErr_Format(PyExc_RuntimeError,
5898 "validator '%s' must be regex or function", val);
5899 return (KORE_RESULT_ERROR);
5900 }
5901
5902 vldr = kore_calloc(1, sizeof(*vldr));
5903 vldr->type = vtype;
5904
5905 if (vtype == KORE_VALIDATOR_TYPE_REGEX) {
5906 val = PyUnicode_AsUTF8(item);
5907 if (regcomp(&(vldr->rctx),
5908 val, REG_EXTENDED | REG_NOSUB)) {
5909 PyErr_Format(PyExc_RuntimeError,
5910 "Invalid regex (%s)", val);
5911 kore_free(vldr);
5912 return (KORE_RESULT_ERROR);
5913 }
5914 } else {
5915 vldr->rcall = kore_calloc(1, sizeof(*vldr->rcall));
5916 vldr->rcall->addr = item;
5917 vldr->rcall->runtime = &kore_python_runtime;
5918 Py_INCREF(item);
5919 }
5920
5921 val = PyUnicode_AsUTF8(key);
5922 vldr->name = kore_strdup(val);
5923
5924 param = kore_calloc(1, sizeof(*param));
5925 param->flags = 0;
5926 param->method = type;
5927 param->validator = vldr;
5928 param->name = kore_strdup(val);
5929
5930 if (type == HTTP_METHOD_GET || qs == 1)
5931 param->flags = KORE_PARAMS_QUERY_STRING;
5932
5933 TAILQ_INSERT_TAIL(&rt->params, param, list);
5934 }
5935
5936 return (KORE_RESULT_OK);
5937 }
5938
5939 static int
5940 python_route_auth(PyObject *dict, struct kore_route *rt)
5941 {
5942 int type;
5943 struct kore_auth *auth;
5944 struct kore_validator *vldr;
5945 PyObject *obj, *repr;
5946 const char *value, *redir;
5947
5948 if (!PyDict_CheckExact(dict))
5949 return (KORE_RESULT_ERROR);
5950
5951 if ((value = python_string_from_dict(dict, "type")) == NULL) {
5952 PyErr_SetString(PyExc_RuntimeError,
5953 "missing or invalid 'type' keyword");
5954 return (KORE_RESULT_ERROR);
5955 }
5956
5957 if (!strcmp(value, "cookie")) {
5958 type = KORE_AUTH_TYPE_COOKIE;
5959 } else if (!strcmp(value, "header")) {
5960 type = KORE_AUTH_TYPE_HEADER;
5961 } else {
5962 PyErr_Format(PyExc_RuntimeError,
5963 "invalid 'type' (%s) in auth dictionary for '%s'",
5964 value, rt->path);
5965 return (KORE_RESULT_ERROR);
5966 }
5967
5968 if ((value = python_string_from_dict(dict, "value")) == NULL) {
5969 PyErr_SetString(PyExc_RuntimeError,
5970 "missing or invalid 'value' keyword");
5971 return (KORE_RESULT_ERROR);
5972 }
5973
5974 redir = python_string_from_dict(dict, "redirect");
5975
5976 if ((obj = PyDict_GetItemString(dict, "verify")) == NULL ||
5977 !PyCallable_Check(obj)) {
5978 PyErr_Format(PyExc_RuntimeError,
5979 "missing 'verify' in auth dictionary for '%s'", rt->path);
5980 return (KORE_RESULT_ERROR);
5981 }
5982
5983 auth = kore_calloc(1, sizeof(*auth));
5984 auth->type = type;
5985 auth->value = kore_strdup(value);
5986
5987 if (redir != NULL)
5988 auth->redirect = kore_strdup(redir);
5989
5990 vldr = kore_calloc(1, sizeof(*vldr));
5991 vldr->type = KORE_VALIDATOR_TYPE_FUNCTION;
5992
5993 vldr->rcall = kore_calloc(1, sizeof(*vldr->rcall));
5994 vldr->rcall->addr = obj;
5995 vldr->rcall->runtime = &kore_python_runtime;
5996 Py_INCREF(obj);
5997
5998 if ((repr = PyObject_Repr(obj)) == NULL) {
5999 kore_free(vldr->rcall);
6000 kore_free(vldr);
6001 kore_free(auth);
6002 return (KORE_RESULT_ERROR);
6003 }
6004
6005 value = PyUnicode_AsUTF8(repr);
6006 vldr->name = kore_strdup(value);
6007 Py_DECREF(repr);
6008
6009 auth->validator = vldr;
6010 rt->auth = auth;
6011
6012 return (KORE_RESULT_OK);
6013 }
6014
6015 static int
6016 python_route_hooks(PyObject *dict, struct kore_route *rt)
6017 {
6018 if (!PyDict_CheckExact(dict))
6019 return (KORE_RESULT_ERROR);
6020
6021 if (!python_route_hook_set(dict, "on_free", &rt->on_free))
6022 return (KORE_RESULT_ERROR);
6023
6024 if (!python_route_hook_set(dict, "on_headers", &rt->on_headers))
6025 return (KORE_RESULT_ERROR);
6026
6027 if (!python_route_hook_set(dict, "on_body_chunk", &rt->on_body_chunk))
6028 return (KORE_RESULT_ERROR);
6029
6030 return (KORE_RESULT_OK);
6031 }
6032
6033 static int
6034 python_route_hook_set(PyObject *dict, const char *name,
6035 struct kore_runtime_call **out)
6036 {
6037 PyObject *obj;
6038 struct kore_runtime_call *rcall;
6039
6040 if ((obj = PyDict_GetItemString(dict, name)) == NULL)
6041 return (KORE_RESULT_OK);
6042
6043 if (!PyCallable_Check(obj)) {
6044 PyErr_Format(PyExc_RuntimeError,
6045 "%s for a route not callable", name);
6046 Py_DECREF(obj);
6047 return (KORE_RESULT_ERROR);
6048 }
6049
6050 rcall = kore_calloc(1, sizeof(struct kore_runtime_call));
6051 rcall->addr = obj;
6052 rcall->runtime = &kore_python_runtime;
6053
6054 Py_INCREF(rcall->addr);
6055 *out = rcall;
6056
6057 return (KORE_RESULT_OK);
6058 }
6059
6060 #if defined(KORE_USE_PGSQL)
6061 static PyObject *
6062 python_kore_pgsql_query(PyObject *self, PyObject *args, PyObject *kwargs)
6063 {
6064 struct pykore_pgsql *op;
6065 PyObject *obj;
6066 const char *db, *query;
6067
6068 if (!PyArg_ParseTuple(args, "ss", &db, &query))
6069 return (NULL);
6070
6071 op = PyObject_New(struct pykore_pgsql, &pykore_pgsql_type);
6072 if (op == NULL)
6073 return (NULL);
6074
6075 op->binary = 0;
6076 op->param.count = 0;
6077 op->param.objs = NULL;
6078 op->param.values = NULL;
6079 op->param.lengths = NULL;
6080 op->param.formats = NULL;
6081
6082 op->result = NULL;
6083 op->coro = coro_running;
6084 op->db = kore_strdup(db);
6085 op->query = kore_strdup(query);
6086 op->state = PYKORE_PGSQL_PREINIT;
6087
6088 memset(&op->sql, 0, sizeof(op->sql));
6089
6090 if (kwargs != NULL) {
6091 if ((obj = PyDict_GetItemString(kwargs, "params")) != NULL) {
6092 if (!pykore_pgsql_params(op, obj)) {
6093 Py_DECREF((PyObject *)op);
6094 return (NULL);
6095 }
6096 }
6097
6098 if ((obj = PyDict_GetItemString(kwargs, "binary")) != NULL) {
6099 if (obj == Py_True) {
6100 op->binary = 1;
6101 } else if (obj == Py_False) {
6102 op->binary = 0;
6103 } else {
6104 Py_DECREF((PyObject *)op);
6105 PyErr_SetString(PyExc_RuntimeError,
6106 "pgsql: binary not True or False");
6107 return (NULL);
6108 }
6109 }
6110 }
6111
6112 return ((PyObject *)op);
6113 }
6114
6115 static int
6116 pykore_pgsql_params(struct pykore_pgsql *op, PyObject *list)
6117 {
6118 union { const char *cp; char *p; } ptr;
6119 PyObject *item;
6120 int format;
6121 Py_ssize_t i, len, vlen;
6122
6123 if (!PyList_CheckExact(list)) {
6124 if (list == Py_None)
6125 return (KORE_RESULT_OK);
6126
6127 PyErr_SetString(PyExc_RuntimeError,
6128 "pgsql: params keyword must be a list");
6129 return (KORE_RESULT_ERROR);
6130 }
6131
6132 len = PyList_Size(list);
6133 if (len == 0)
6134 return (KORE_RESULT_OK);
6135
6136 if (len > INT_MAX) {
6137 PyErr_SetString(PyExc_RuntimeError,
6138 "pgsql: list length too large");
6139 return (KORE_RESULT_ERROR);
6140 }
6141
6142 op->param.count = len;
6143 op->param.lengths = kore_calloc(len, sizeof(int));
6144 op->param.formats = kore_calloc(len, sizeof(int));
6145 op->param.values = kore_calloc(len, sizeof(char *));
6146 op->param.objs = kore_calloc(len, sizeof(PyObject *));
6147
6148 for (i = 0; i < len; i++) {
6149 if ((item = PyList_GetItem(list, i)) == NULL)
6150 return (KORE_RESULT_ERROR);
6151
6152 if (PyUnicode_CheckExact(item)) {
6153 format = 0;
6154 ptr.cp = PyUnicode_AsUTF8AndSize(item, &vlen);
6155 } else if (PyBytes_CheckExact(item)) {
6156 format = 1;
6157 if (PyBytes_AsStringAndSize(item, &ptr.p, &vlen) == -1)
6158 ptr.p = NULL;
6159 } else {
6160 PyErr_Format(PyExc_RuntimeError,
6161 "pgsql: item %zu is not a string or bytes", i);
6162 return (KORE_RESULT_ERROR);
6163 }
6164
6165 if (ptr.cp == NULL)
6166 return (KORE_RESULT_ERROR);
6167
6168 op->param.lengths[i] = vlen;
6169 op->param.values[i] = ptr.cp;
6170 op->param.formats[i] = format;
6171
6172 /* Hold on to it since we are directly referencing its data. */
6173 op->param.objs[i] = item;
6174 Py_INCREF(item);
6175 }
6176
6177 return (KORE_RESULT_OK);
6178 }
6179
6180 static void
6181 pykore_pgsql_dealloc(struct pykore_pgsql *pysql)
6182 {
6183 Py_ssize_t i;
6184
6185 kore_free(pysql->db);
6186 kore_free(pysql->query);
6187 kore_pgsql_cleanup(&pysql->sql);
6188
6189 if (pysql->result != NULL)
6190 Py_DECREF(pysql->result);
6191
6192 for (i = 0; i < pysql->param.count; i++)
6193 Py_XDECREF(pysql->param.objs[i]);
6194
6195 kore_free(pysql->param.objs);
6196 kore_free(pysql->param.values);
6197 kore_free(pysql->param.lengths);
6198 kore_free(pysql->param.formats);
6199
6200 PyObject_Del((PyObject *)pysql);
6201 }
6202
6203 static PyObject *
6204 pykore_pgsql_iternext(struct pykore_pgsql *pysql)
6205 {
6206 switch (pysql->state) {
6207 case PYKORE_PGSQL_PREINIT:
6208 kore_pgsql_init(&pysql->sql);
6209 kore_pgsql_bind_callback(&pysql->sql,
6210 pykore_pgsql_callback, pysql);
6211 pysql->state = PYKORE_PGSQL_INITIALIZE;
6212 /* fallthrough */
6213 case PYKORE_PGSQL_INITIALIZE:
6214 if (!kore_pgsql_setup(&pysql->sql, pysql->db,
6215 KORE_PGSQL_ASYNC)) {
6216 if (pysql->sql.state == KORE_PGSQL_STATE_INIT)
6217 break;
6218 PyErr_Format(PyExc_RuntimeError, "pgsql error: %s",
6219 pysql->sql.error);
6220 return (NULL);
6221 }
6222 /* fallthrough */
6223 case PYKORE_PGSQL_QUERY:
6224 if (pysql->param.count > 0) {
6225 if (!kore_pgsql_query_param_fields(&pysql->sql,
6226 pysql->query, pysql->binary,
6227 pysql->param.count, pysql->param.values,
6228 pysql->param.lengths, pysql->param.formats)) {
6229 PyErr_Format(PyExc_RuntimeError,
6230 "pgsql error: %s", pysql->sql.error);
6231 return (NULL);
6232 }
6233 } else {
6234 if (!kore_pgsql_query(&pysql->sql, pysql->query)) {
6235 PyErr_Format(PyExc_RuntimeError,
6236 "pgsql error: %s", pysql->sql.error);
6237 return (NULL);
6238 }
6239 }
6240 pysql->state = PYKORE_PGSQL_WAIT;
6241 break;
6242 wait_again:
6243 case PYKORE_PGSQL_WAIT:
6244 switch (pysql->sql.state) {
6245 case KORE_PGSQL_STATE_WAIT:
6246 break;
6247 case KORE_PGSQL_STATE_COMPLETE:
6248 PyErr_SetNone(PyExc_StopIteration);
6249 if (pysql->result != NULL) {
6250 PyErr_SetObject(PyExc_StopIteration,
6251 pysql->result);
6252 Py_DECREF(pysql->result);
6253 pysql->result = NULL;
6254 } else {
6255 PyErr_SetObject(PyExc_StopIteration, Py_None);
6256 }
6257 return (NULL);
6258 case KORE_PGSQL_STATE_ERROR:
6259 PyErr_Format(PyExc_RuntimeError,
6260 "failed to perform query: %s", pysql->sql.error);
6261 return (NULL);
6262 case KORE_PGSQL_STATE_RESULT:
6263 if (!pykore_pgsql_result(pysql))
6264 return (NULL);
6265 goto wait_again;
6266 default:
6267 kore_pgsql_continue(&pysql->sql);
6268 goto wait_again;
6269 }
6270 break;
6271 default:
6272 PyErr_SetString(PyExc_RuntimeError, "bad pykore_pgsql state");
6273 return (NULL);
6274 }
6275
6276 /* tell caller to wait. */
6277 Py_RETURN_NONE;
6278 }
6279
6280 static void
6281 pykore_pgsql_callback(struct kore_pgsql *pgsql, void *arg)
6282 {
6283 struct pykore_pgsql *op = arg;
6284
6285 if (op->coro->request != NULL)
6286 http_request_wakeup(op->coro->request);
6287 else
6288 python_coro_wakeup(op->coro);
6289 }
6290
6291 static PyObject *
6292 pykore_pgsql_await(PyObject *obj)
6293 {
6294 Py_INCREF(obj);
6295 return (obj);
6296 }
6297
6298 static int
6299 pykore_pgsql_result(struct pykore_pgsql *pysql)
6300 {
6301 const char *val;
6302 char key[64];
6303 PyObject *list, *pyrow, *pyval;
6304 int rows, row, field, fields, len;
6305
6306 if ((list = PyList_New(0)) == NULL) {
6307 PyErr_SetNone(PyExc_MemoryError);
6308 return (KORE_RESULT_ERROR);
6309 }
6310
6311 rows = kore_pgsql_ntuples(&pysql->sql);
6312 fields = kore_pgsql_nfields(&pysql->sql);
6313
6314 for (row = 0; row < rows; row++) {
6315 if ((pyrow = PyDict_New()) == NULL) {
6316 Py_DECREF(list);
6317 PyErr_SetNone(PyExc_MemoryError);
6318 return (KORE_RESULT_ERROR);
6319 }
6320
6321 for (field = 0; field < fields; field++) {
6322 val = kore_pgsql_getvalue(&pysql->sql, row, field);
6323 len = kore_pgsql_getlength(&pysql->sql, row, field);
6324
6325 if (kore_pgsql_column_binary(&pysql->sql, field)) {
6326 pyval = PyBytes_FromStringAndSize(val, len);
6327 } else {
6328 pyval = PyUnicode_FromString(val);
6329 }
6330
6331 if (pyval == NULL) {
6332 Py_DECREF(pyrow);
6333 Py_DECREF(list);
6334 PyErr_SetNone(PyExc_MemoryError);
6335 return (KORE_RESULT_ERROR);
6336 }
6337
6338 (void)snprintf(key, sizeof(key), "%s",
6339 kore_pgsql_fieldname(&pysql->sql, field));
6340
6341 if (PyDict_SetItemString(pyrow, key, pyval) == -1) {
6342 Py_DECREF(pyval);
6343 Py_DECREF(pyrow);
6344 Py_DECREF(list);
6345 PyErr_SetString(PyExc_RuntimeError,
6346 "failed to add new value to row");
6347 return (KORE_RESULT_ERROR);
6348 }
6349
6350 Py_DECREF(pyval);
6351 }
6352
6353 if (PyList_Insert(list, row, pyrow) == -1) {
6354 Py_DECREF(pyrow);
6355 Py_DECREF(list);
6356 PyErr_SetString(PyExc_RuntimeError,
6357 "failed to add new row to list");
6358 return (KORE_RESULT_ERROR);
6359 }
6360
6361 Py_DECREF(pyrow);
6362 }
6363
6364 pysql->result = list;
6365 kore_pgsql_continue(&pysql->sql);
6366
6367 return (KORE_RESULT_OK);
6368 }
6369 #endif
6370
6371 #if defined(KORE_USE_CURL)
6372 static PyObject *
6373 python_curlopt_set(struct pycurl_data *data, long opt, PyObject *value)
6374 {
6375 int i;
6376
6377 for (i = 0; py_curlopt[i].name != NULL; i++) {
6378 if (py_curlopt[i].value == opt)
6379 break;
6380 }
6381
6382 if (py_curlopt[i].name == NULL) {
6383 PyErr_Format(PyExc_RuntimeError, "invalid option '%ld'", opt);
6384 return (NULL);
6385 }
6386
6387 if (py_curlopt[i].cb == NULL) {
6388 PyErr_Format(PyExc_RuntimeError, "option '%s' not implemented",
6389 py_curlopt[i].name);
6390 return (NULL);
6391 }
6392
6393 return (py_curlopt[i].cb(data, i, value));
6394 }
6395
6396 static int
6397 python_curlopt_from_dict(struct pycurl_data *data, PyObject *dict)
6398 {
6399 long opt;
6400 Py_ssize_t idx;
6401 PyObject *key, *value, *obj;
6402
6403 idx = 0;
6404
6405 if (!PyDict_CheckExact(dict)) {
6406 PyErr_SetString(PyExc_RuntimeError,
6407 "curlopt must be a dictionary");
6408 return (KORE_RESULT_ERROR);
6409 }
6410
6411 while (PyDict_Next(dict, &idx, &key, &value)) {
6412 if (!PyLong_CheckExact(key)) {
6413 PyErr_Format(PyExc_RuntimeError,
6414 "invalid key in curlopt keyword");
6415 return (KORE_RESULT_ERROR);
6416 }
6417
6418 opt = PyLong_AsLong(key);
6419
6420 if ((obj = python_curlopt_set(data, opt, value)) == NULL)
6421 return (KORE_RESULT_ERROR);
6422
6423 Py_DECREF(obj);
6424 }
6425
6426 return (KORE_RESULT_OK);
6427 }
6428
6429 static PyObject *
6430 python_kore_curl_handle(PyObject *self, PyObject *args)
6431 {
6432 const char *url;
6433 struct pycurl_handle *handle;
6434
6435 if (!PyArg_ParseTuple(args, "s", &url))
6436 return (NULL);
6437
6438 handle = PyObject_New(struct pycurl_handle, &pycurl_handle_type);
6439 if (handle == NULL)
6440 return (NULL);
6441
6442 handle->url = kore_strdup(url);
6443 memset(&handle->data.curl, 0, sizeof(handle->data.curl));
6444
6445 handle->body = NULL;
6446 LIST_INIT(&handle->data.slists);
6447
6448 if (!kore_curl_init(&handle->data.curl, handle->url, KORE_CURL_ASYNC)) {
6449 Py_DECREF((PyObject *)handle);
6450 PyErr_SetString(PyExc_RuntimeError, "failed to setup call");
6451 return (NULL);
6452 }
6453
6454 return ((PyObject *)handle);
6455 }
6456
6457 static void
6458 pycurl_handle_dealloc(struct pycurl_handle *handle)
6459 {
6460 struct pycurl_slist *psl;
6461
6462 while ((psl = LIST_FIRST(&handle->data.slists))) {
6463 LIST_REMOVE(psl, list);
6464 curl_slist_free_all(psl->slist);
6465 kore_free(psl);
6466 }
6467
6468 if (handle->body != NULL)
6469 kore_buf_free(handle->body);
6470
6471 kore_free(handle->url);
6472 kore_curl_cleanup(&handle->data.curl);
6473
6474 PyObject_Del((PyObject *)handle);
6475 }
6476
6477 static PyObject *
6478 pycurl_handle_setbody(struct pycurl_handle *handle, PyObject *args)
6479 {
6480 PyObject *obj;
6481 char *ptr;
6482 Py_ssize_t length;
6483
6484 if (!PyArg_ParseTuple(args, "O", &obj))
6485 return (NULL);
6486
6487 if (handle->body != NULL) {
6488 PyErr_SetString(PyExc_RuntimeError,
6489 "curl handle already has body attached");
6490 return (NULL);
6491 }
6492
6493 if (!PyBytes_CheckExact(obj)) {
6494 PyErr_SetString(PyExc_RuntimeError,
6495 "curl.setbody expects bytes");
6496 return (NULL);
6497 }
6498
6499 if (PyBytes_AsStringAndSize(obj, &ptr, &length) == -1)
6500 return (NULL);
6501
6502 if (length < 0) {
6503 PyErr_SetString(PyExc_TypeError, "invalid length");
6504 return (NULL);
6505 }
6506
6507 handle->body = kore_buf_alloc(length);
6508 kore_buf_append(handle->body, ptr, length);
6509 kore_buf_reset(handle->body);
6510
6511 curl_easy_setopt(handle->data.curl.handle,
6512 CURLOPT_READFUNCTION, kore_curl_frombuf);
6513 curl_easy_setopt(handle->data.curl.handle,
6514 CURLOPT_READDATA, handle->body);
6515
6516 curl_easy_setopt(handle->data.curl.handle, CURLOPT_UPLOAD, 1);
6517
6518 Py_RETURN_TRUE;
6519 }
6520
6521 static PyObject *
6522 pycurl_handle_setopt(struct pycurl_handle *handle, PyObject *args)
6523 {
6524 int opt;
6525 PyObject *value;
6526
6527 if (!PyArg_ParseTuple(args, "iO", &opt, &value))
6528 return (NULL);
6529
6530 return (python_curlopt_set(&handle->data, opt, value));
6531 }
6532
6533 static PyObject *
6534 pycurl_handle_setopt_string(struct pycurl_data *data, int idx, PyObject *obj)
6535 {
6536 const char *str;
6537 CURLoption option;
6538
6539 if (!PyUnicode_Check(obj)) {
6540 PyErr_Format(PyExc_RuntimeError,
6541 "option '%s' requires a string as argument",
6542 py_curlopt[idx].name);
6543 return (NULL);
6544 }
6545
6546 if ((str = PyUnicode_AsUTF8(obj)) == NULL)
6547 return (NULL);
6548
6549 option = CURLOPTTYPE_OBJECTPOINT + py_curlopt[idx].value;
6550 curl_easy_setopt(data->curl.handle, option, str);
6551
6552 Py_RETURN_TRUE;
6553 }
6554
6555 static PyObject *
6556 pycurl_handle_setopt_long(struct pycurl_data *data, int idx, PyObject *obj)
6557 {
6558 long val;
6559 CURLoption option;
6560
6561 if (!PyLong_CheckExact(obj)) {
6562 PyErr_Format(PyExc_RuntimeError,
6563 "option '%s' requires a long as argument",
6564 py_curlopt[idx].name);
6565 return (NULL);
6566 }
6567
6568 PyErr_Clear();
6569 val = PyLong_AsLong(obj);
6570 if (val == -1 && PyErr_Occurred())
6571 return (NULL);
6572
6573 option = CURLOPTTYPE_LONG + py_curlopt[idx].value;
6574 curl_easy_setopt(data->curl.handle, option, val);
6575
6576 Py_RETURN_TRUE;
6577 }
6578
6579 static PyObject *
6580 pycurl_handle_setopt_slist(struct pycurl_data *data, int idx, PyObject *obj)
6581 {
6582 struct pycurl_slist *psl;
6583 PyObject *item;
6584 const char *sval;
6585 struct curl_slist *slist;
6586 CURLoption option;
6587 Py_ssize_t list_len, i;
6588
6589 if (!PyList_CheckExact(obj)) {
6590 PyErr_Format(PyExc_RuntimeError,
6591 "option '%s' requires a list as argument",
6592 py_curlopt[idx].name);
6593 return (NULL);
6594 }
6595
6596 slist = NULL;
6597 list_len = PyList_Size(obj);
6598
6599 for (i = 0; i < list_len; i++) {
6600 if ((item = PyList_GetItem(obj, i)) == NULL)
6601 return (NULL);
6602
6603 if (!PyUnicode_Check(item))
6604 return (NULL);
6605
6606 if ((sval = PyUnicode_AsUTF8AndSize(item, NULL)) == NULL)
6607 return (NULL);
6608
6609 if ((slist = curl_slist_append(slist, sval)) == NULL)
6610 fatal("%s: curl_slist_append failed", __func__);
6611 }
6612
6613 psl = kore_calloc(1, sizeof(*psl));
6614 psl->slist = slist;
6615 LIST_INSERT_HEAD(&data->slists, psl, list);
6616
6617 option = CURLOPTTYPE_OBJECTPOINT + py_curlopt[idx].value;
6618 curl_easy_setopt(data->curl.handle, option, slist);
6619
6620 Py_RETURN_TRUE;
6621 }
6622
6623 static PyObject *
6624 pycurl_handle_run(struct pycurl_handle *handle, PyObject *args)
6625 {
6626 struct pycurl_handle_op *op;
6627
6628 op = PyObject_New(struct pycurl_handle_op, &pycurl_handle_op_type);
6629 if (op == NULL)
6630 return (NULL);
6631
6632 Py_INCREF(handle);
6633
6634 op->handle = handle;
6635 op->coro = coro_running;
6636 op->state = CURL_CLIENT_OP_RUN;
6637
6638 kore_curl_bind_callback(&handle->data.curl,
6639 python_curl_handle_callback, op);
6640
6641 return ((PyObject *)op);
6642 }
6643
6644 static void
6645 pycurl_handle_op_dealloc(struct pycurl_handle_op *op)
6646 {
6647 Py_DECREF(op->handle);
6648 PyObject_Del((PyObject *)op);
6649 }
6650
6651 static PyObject *
6652 pycurl_handle_op_await(PyObject *op)
6653 {
6654 Py_INCREF(op);
6655 return (op);
6656 }
6657
6658 static PyObject *
6659 pycurl_handle_op_iternext(struct pycurl_handle_op *op)
6660 {
6661 size_t len;
6662 PyObject *result;
6663 const u_int8_t *response;
6664
6665 if (op->state == CURL_CLIENT_OP_RUN) {
6666 kore_curl_run(&op->handle->data.curl);
6667 op->state = CURL_CLIENT_OP_RESULT;
6668 Py_RETURN_NONE;
6669 }
6670
6671 if (op->handle->body != NULL) {
6672 kore_buf_free(op->handle->body);
6673 op->handle->body = NULL;
6674 }
6675
6676 if (!kore_curl_success(&op->handle->data.curl)) {
6677 /* Do not log the url here, may contain some sensitive data. */
6678 PyErr_Format(PyExc_RuntimeError, "request failed: %s",
6679 kore_curl_strerror(&op->handle->data.curl));
6680 return (NULL);
6681 }
6682
6683 kore_curl_response_as_bytes(&op->handle->data.curl, &response, &len);
6684
6685 if ((result = PyBytes_FromStringAndSize((const char *)response,
6686 len)) == NULL)
6687 return (NULL);
6688
6689 PyErr_SetObject(PyExc_StopIteration, result);
6690 Py_DECREF(result);
6691
6692 return (NULL);
6693 }
6694
6695 static PyObject *
6696 python_kore_httpclient(PyObject *self, PyObject *args, PyObject *kwargs)
6697 {
6698 struct pyhttp_client *client;
6699 const char *url, *v;
6700
6701 if (!PyArg_ParseTuple(args, "s", &url))
6702 return (NULL);
6703
6704 client = PyObject_New(struct pyhttp_client, &pyhttp_client_type);
6705 if (client == NULL)
6706 return (NULL);
6707
6708 client->unix = NULL;
6709 client->tlskey = NULL;
6710 client->curlopt = NULL;
6711 client->tlscert = NULL;
6712 client->cabundle = NULL;
6713
6714 client->tlsverify = 1;
6715 client->url = kore_strdup(url);
6716
6717 if (kwargs != NULL) {
6718 if ((v = python_string_from_dict(kwargs, "tlscert")) != NULL)
6719 client->tlscert = kore_strdup(v);
6720
6721 if ((v = python_string_from_dict(kwargs, "tlskey")) != NULL)
6722 client->tlskey = kore_strdup(v);
6723
6724 if ((v = python_string_from_dict(kwargs, "cabundle")) != NULL)
6725 client->cabundle = kore_strdup(v);
6726
6727 if ((v = python_string_from_dict(kwargs, "unix")) != NULL)
6728 client->unix = kore_strdup(v);
6729
6730 client->curlopt = PyDict_GetItemString(kwargs, "curlopt");
6731 Py_XINCREF(client->curlopt);
6732
6733 python_bool_from_dict(kwargs, "tlsverify", &client->tlsverify);
6734 }
6735
6736 if ((client->tlscert != NULL && client->tlskey == NULL) ||
6737 (client->tlskey != NULL && client->tlscert == NULL)) {
6738 Py_DECREF((PyObject *)client);
6739 PyErr_SetString(PyExc_RuntimeError,
6740 "invalid TLS client configuration");
6741 return (NULL);
6742 }
6743
6744 return ((PyObject *)client);
6745 }
6746
6747 static void
6748 pyhttp_client_dealloc(struct pyhttp_client *client)
6749 {
6750 kore_free(client->url);
6751 kore_free(client->unix);
6752 kore_free(client->tlskey);
6753 kore_free(client->tlscert);
6754 kore_free(client->cabundle);
6755
6756 Py_XDECREF(client->curlopt);
6757
6758 PyObject_Del((PyObject *)client);
6759 }
6760
6761 static PyObject *
6762 pyhttp_client_get(struct pyhttp_client *client, PyObject *args,
6763 PyObject *kwargs)
6764 {
6765 return (pyhttp_client_request(client, HTTP_METHOD_GET, kwargs));
6766 }
6767
6768 static PyObject *
6769 pyhttp_client_put(struct pyhttp_client *client, PyObject *args,
6770 PyObject *kwargs)
6771 {
6772 return (pyhttp_client_request(client, HTTP_METHOD_PUT, kwargs));
6773 }
6774
6775 static PyObject *
6776 pyhttp_client_post(struct pyhttp_client *client, PyObject *args,
6777 PyObject *kwargs)
6778 {
6779 return (pyhttp_client_request(client, HTTP_METHOD_POST, kwargs));
6780 }
6781
6782 static PyObject *
6783 pyhttp_client_head(struct pyhttp_client *client, PyObject *args,
6784 PyObject *kwargs)
6785 {
6786 return (pyhttp_client_request(client, HTTP_METHOD_HEAD, kwargs));
6787 }
6788
6789 static PyObject *
6790 pyhttp_client_patch(struct pyhttp_client *client, PyObject *args,
6791 PyObject *kwargs)
6792 {
6793 return (pyhttp_client_request(client, HTTP_METHOD_PATCH, kwargs));
6794 }
6795
6796 static PyObject *
6797 pyhttp_client_delete(struct pyhttp_client *client, PyObject *args,
6798 PyObject *kwargs)
6799 {
6800 return (pyhttp_client_request(client, HTTP_METHOD_DELETE, kwargs));
6801 }
6802
6803 static PyObject *
6804 pyhttp_client_options(struct pyhttp_client *client, PyObject *args,
6805 PyObject *kwargs)
6806 {
6807 return (pyhttp_client_request(client, HTTP_METHOD_OPTIONS, kwargs));
6808 }
6809
6810 static PyObject *
6811 pyhttp_client_request(struct pyhttp_client *client, int m, PyObject *kwargs)
6812 {
6813 struct pyhttp_client_op *op;
6814 char *ptr;
6815 const char *k, *v;
6816 Py_ssize_t length, idx;
6817 PyObject *data, *headers, *key, *obj;
6818
6819 ptr = NULL;
6820 length = 0;
6821 headers = NULL;
6822
6823 if (kwargs != NULL &&
6824 ((headers = PyDict_GetItemString(kwargs, "headers")) != NULL)) {
6825 if (!PyDict_CheckExact(headers)) {
6826 PyErr_SetString(PyExc_RuntimeError,
6827 "headers keyword must be a dict");
6828 return (NULL);
6829 }
6830 }
6831
6832 switch (m) {
6833 case HTTP_METHOD_GET:
6834 case HTTP_METHOD_HEAD:
6835 case HTTP_METHOD_OPTIONS:
6836 break;
6837 case HTTP_METHOD_PUT:
6838 case HTTP_METHOD_POST:
6839 case HTTP_METHOD_PATCH:
6840 case HTTP_METHOD_DELETE:
6841 length = -1;
6842
6843 if (kwargs == NULL) {
6844 if (m == HTTP_METHOD_DELETE) {
6845 length = 0;
6846 break;
6847 }
6848
6849 PyErr_Format(PyExc_RuntimeError,
6850 "no keyword arguments given, but body expected ",
6851 http_method_text(m));
6852 return (NULL);
6853 }
6854
6855 if ((data = PyDict_GetItemString(kwargs, "body")) == NULL)
6856 return (NULL);
6857
6858 if (PyBytes_AsStringAndSize(data, &ptr, &length) == -1)
6859 return (NULL);
6860
6861 if (length < 0) {
6862 PyErr_SetString(PyExc_TypeError, "invalid length");
6863 return (NULL);
6864 }
6865 break;
6866 default:
6867 fatal("%s: unknown method %d", __func__, m);
6868 }
6869
6870 op = PyObject_New(struct pyhttp_client_op, &pyhttp_client_op_type);
6871 if (op == NULL)
6872 return (NULL);
6873
6874 if (!kore_curl_init(&op->data.curl, client->url, KORE_CURL_ASYNC)) {
6875 Py_DECREF((PyObject *)op);
6876 PyErr_SetString(PyExc_RuntimeError, "failed to setup call");
6877 return (NULL);
6878 }
6879
6880 op->headers = 0;
6881 op->coro = coro_running;
6882 op->state = CURL_CLIENT_OP_RUN;
6883 LIST_INIT(&op->data.slists);
6884
6885 Py_INCREF(client);
6886 op->client = client;
6887
6888 kore_curl_http_setup(&op->data.curl, m, ptr, length);
6889 kore_curl_bind_callback(&op->data.curl, python_curl_http_callback, op);
6890
6891 /* Go in with our own bare hands. */
6892 if (client->unix != NULL) {
6893 #if defined(__linux__)
6894 if (client->unix[0] == '@') {
6895 curl_easy_setopt(op->data.curl.handle,
6896 CURLOPT_ABSTRACT_UNIX_SOCKET, client->unix + 1);
6897 } else {
6898 curl_easy_setopt(op->data.curl.handle,
6899 CURLOPT_UNIX_SOCKET_PATH, client->unix);
6900 }
6901 #else
6902 curl_easy_setopt(op->data.curl.handle, CURLOPT_UNIX_SOCKET_PATH,
6903 client->unix);
6904 #endif
6905 }
6906
6907 if (client->tlskey != NULL && client->tlscert != NULL) {
6908 curl_easy_setopt(op->data.curl.handle, CURLOPT_SSLCERT,
6909 client->tlscert);
6910 curl_easy_setopt(op->data.curl.handle, CURLOPT_SSLKEY,
6911 client->tlskey);
6912 }
6913
6914 if (client->tlsverify == 0) {
6915 curl_easy_setopt(op->data.curl.handle,
6916 CURLOPT_SSL_VERIFYHOST, 0);
6917 curl_easy_setopt(op->data.curl.handle,
6918 CURLOPT_SSL_VERIFYPEER, 0);
6919 }
6920
6921 if (client->curlopt != NULL) {
6922 if (!python_curlopt_from_dict(&op->data, client->curlopt)) {
6923 Py_DECREF((PyObject *)op);
6924 return (NULL);
6925 }
6926 }
6927
6928 if (client->cabundle != NULL) {
6929 curl_easy_setopt(op->data.curl.handle, CURLOPT_CAINFO,
6930 client->cabundle);
6931 }
6932
6933 if (headers != NULL) {
6934 idx = 0;
6935 while (PyDict_Next(headers, &idx, &key, &obj)) {
6936 if ((k = PyUnicode_AsUTF8(key)) == NULL) {
6937 Py_DECREF((PyObject *)op);
6938 return (NULL);
6939 }
6940
6941 if ((v = PyUnicode_AsUTF8(obj)) == NULL) {
6942 Py_DECREF((PyObject *)op);
6943 return (NULL);
6944 }
6945
6946 kore_curl_http_set_header(&op->data.curl, k, v);
6947 }
6948 }
6949
6950 if (kwargs != NULL) {
6951 if ((obj = PyDict_GetItemString(kwargs, "curlopt")) != NULL) {
6952 if (!python_curlopt_from_dict(&op->data, obj)) {
6953 Py_DECREF((PyObject *)op);
6954 return (NULL);
6955 }
6956 }
6957
6958 python_bool_from_dict(kwargs, "return_headers", &op->headers);
6959 }
6960
6961 return ((PyObject *)op);
6962 }
6963
6964 static void
6965 pyhttp_client_op_dealloc(struct pyhttp_client_op *op)
6966 {
6967 struct pycurl_slist *psl;
6968
6969 while ((psl = LIST_FIRST(&op->data.slists))) {
6970 LIST_REMOVE(psl, list);
6971 curl_slist_free_all(psl->slist);
6972 kore_free(psl);
6973 }
6974
6975 Py_DECREF(op->client);
6976 kore_curl_cleanup(&op->data.curl);
6977 PyObject_Del((PyObject *)op);
6978 }
6979
6980 static PyObject *
6981 pyhttp_client_op_await(PyObject *op)
6982 {
6983 Py_INCREF(op);
6984 return (op);
6985 }
6986
6987 static PyObject *
6988 pyhttp_client_op_iternext(struct pyhttp_client_op *op)
6989 {
6990 size_t len;
6991 struct http_header *hdr;
6992 const u_int8_t *response;
6993 PyObject *result, *tuple, *dict, *value;
6994
6995 if (op->state == CURL_CLIENT_OP_RUN) {
6996 kore_curl_run(&op->data.curl);
6997 op->state = CURL_CLIENT_OP_RESULT;
6998 Py_RETURN_NONE;
6999 }
7000
7001 if (!kore_curl_success(&op->data.curl)) {
7002 PyErr_Format(PyExc_RuntimeError, "request to '%s' failed: %s",
7003 op->data.curl.url, kore_curl_strerror(&op->data.curl));
7004 return (NULL);
7005 }
7006
7007 kore_curl_response_as_bytes(&op->data.curl, &response, &len);
7008
7009 if (op->headers) {
7010 kore_curl_http_parse_headers(&op->data.curl);
7011
7012 if ((dict = PyDict_New()) == NULL)
7013 return (NULL);
7014
7015 TAILQ_FOREACH(hdr, &op->data.curl.http.resp_hdrs, list) {
7016 value = PyUnicode_FromString(hdr->value);
7017 if (value == NULL) {
7018 Py_DECREF(dict);
7019 return (NULL);
7020 }
7021
7022 if (PyDict_SetItemString(dict,
7023 hdr->header, value) == -1) {
7024 Py_DECREF(dict);
7025 Py_DECREF(value);
7026 return (NULL);
7027 }
7028
7029 Py_DECREF(value);
7030 }
7031
7032 if ((tuple = Py_BuildValue("(iOy#)", op->data.curl.http.status,
7033 dict, (const char *)response, len)) == NULL)
7034 return (NULL);
7035
7036 Py_DECREF(dict);
7037 } else {
7038 if ((tuple = Py_BuildValue("(iy#)", op->data.curl.http.status,
7039 (const char *)response, len)) == NULL)
7040 return (NULL);
7041 }
7042
7043 result = PyObject_CallFunctionObjArgs(PyExc_StopIteration, tuple, NULL);
7044 if (result == NULL) {
7045 Py_DECREF(tuple);
7046 return (NULL);
7047 }
7048
7049 Py_DECREF(tuple);
7050 PyErr_SetObject(PyExc_StopIteration, result);
7051 Py_DECREF(result);
7052
7053 return (NULL);
7054 }
7055
7056 static void
7057 python_curl_http_callback(struct kore_curl *curl, void *arg)
7058 {
7059 struct pyhttp_client_op *op = arg;
7060
7061 if (op->coro->request != NULL)
7062 http_request_wakeup(op->coro->request);
7063 else
7064 python_coro_wakeup(op->coro);
7065 }
7066
7067 static void
7068 python_curl_handle_callback(struct kore_curl *curl, void *arg)
7069 {
7070 struct pycurl_handle_op *op = arg;
7071
7072 if (op->coro->request != NULL)
7073 http_request_wakeup(op->coro->request);
7074 else
7075 python_coro_wakeup(op->coro);
7076 }
7077 #endif