python.c (156528B)
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 env[0] = NULL;
2816
2817 if (coro_running == NULL) {
2818 PyErr_SetString(PyExc_RuntimeError,
2819 "kore.proc only available in coroutines");
2820 return (NULL);
2821 }
2822
2823 if (!PyArg_ParseTuple(args, "s|i", &cmd, &timeo))
2824 return (NULL);
2825
2826 if (kwargs != NULL &&
2827 (obj = PyDict_GetItemString(kwargs, "env")) != NULL) {
2828 if (!PyList_CheckExact(obj)) {
2829 PyErr_SetString(PyExc_RuntimeError,
2830 "kore.proc: env is not of type 'list'");
2831 return (NULL);
2832 }
2833
2834 len = PyList_Size(obj);
2835 if (len > PYTHON_PROC_MAX_ENV) {
2836 PyErr_SetString(PyExc_RuntimeError,
2837 "kore.proc: too many entries in 'env' keyword");
2838 return (NULL);
2839 }
2840
2841 for (idx = 0; idx < len; idx++) {
2842 if ((item = PyList_GetItem(obj, idx)) == NULL)
2843 return (NULL);
2844
2845 if (!PyUnicode_CheckExact(item))
2846 return (NULL);
2847
2848 if ((cp.cp = PyUnicode_AsUTF8(item)) == NULL)
2849 return (NULL);
2850
2851 env[idx] = cp.p;
2852 }
2853
2854 env[idx] = NULL;
2855 }
2856
2857 if (pipe(in_pipe) == -1) {
2858 PyErr_SetString(PyExc_RuntimeError, errno_s);
2859 return (NULL);
2860 }
2861
2862 if (pipe(out_pipe) == -1) {
2863 close(in_pipe[0]);
2864 close(in_pipe[1]);
2865 PyErr_SetString(PyExc_RuntimeError, errno_s);
2866 return (NULL);
2867 }
2868
2869 if ((proc = PyObject_New(struct pyproc, &pyproc_type)) == NULL) {
2870 close(in_pipe[0]);
2871 close(in_pipe[1]);
2872 close(out_pipe[0]);
2873 close(out_pipe[1]);
2874 return (NULL);
2875 }
2876
2877 proc->pid = -1;
2878 proc->op = NULL;
2879 proc->apid = -1;
2880 proc->reaped = 0;
2881 proc->status = 0;
2882 proc->timer = NULL;
2883 proc->coro = coro_running;
2884 proc->in = pysocket_alloc();
2885 proc->out = pysocket_alloc();
2886
2887 if (proc->in == NULL || proc->out == NULL) {
2888 Py_DECREF((PyObject *)proc);
2889 return (NULL);
2890 }
2891
2892 TAILQ_INSERT_TAIL(&procs, proc, list);
2893
2894 proc->pid = fork();
2895 if (proc->pid == -1) {
2896 if (errno == ENOSYS) {
2897 Py_DECREF((PyObject *)proc);
2898 PyErr_SetString(PyExc_RuntimeError, errno_s);
2899 return (NULL);
2900 }
2901 fatal("python_kore_proc: fork(): %s", errno_s);
2902 }
2903
2904 if (proc->pid == 0) {
2905 close(in_pipe[1]);
2906 close(out_pipe[0]);
2907
2908 if (dup2(out_pipe[1], STDOUT_FILENO) == -1 ||
2909 dup2(out_pipe[1], STDERR_FILENO) == -1 ||
2910 dup2(in_pipe[0], STDIN_FILENO) == -1)
2911 fatal("dup2: %s", errno_s);
2912
2913 copy = kore_strdup(cmd);
2914 python_split_arguments(copy, argv, 32);
2915
2916 (void)execve(argv[0], argv, env);
2917 kore_log(LOG_ERR, "kore.proc failed to execute %s (%s)",
2918 argv[0], errno_s);
2919 exit(1);
2920 }
2921
2922 close(in_pipe[0]);
2923 close(out_pipe[1]);
2924
2925 if (!kore_connection_nonblock(in_pipe[1], 0) ||
2926 !kore_connection_nonblock(out_pipe[0], 0))
2927 fatal("failed to mark kore.proc pipes are non-blocking");
2928
2929 proc->apid = proc->pid;
2930 proc->in->fd = in_pipe[1];
2931 proc->out->fd = out_pipe[0];
2932
2933 if (timeo != -1) {
2934 proc->timer = kore_timer_add(pyproc_timeout,
2935 timeo, proc, KORE_TIMER_ONESHOT);
2936 }
2937
2938 return ((PyObject *)proc);
2939 }
2940
2941 static PyObject *
2942 python_import(const char *path)
2943 {
2944 struct stat st;
2945 PyObject *module;
2946 char *dir, *file, *copy, *p;
2947
2948 if (stat(path, &st) == -1)
2949 fatal("python_import: stat(%s): %s", path, errno_s);
2950
2951 if (!S_ISDIR(st.st_mode) && !S_ISREG(st.st_mode))
2952 fatal("python_import: '%s' is not a file or directory", path);
2953
2954 copy = kore_strdup(path);
2955 if ((p = dirname(copy)) == NULL)
2956 fatal("dirname: %s: %s", path, errno_s);
2957
2958 dir = kore_strdup(p);
2959 kore_free(copy);
2960
2961 copy = kore_strdup(path);
2962 if ((p = basename(copy)) == NULL)
2963 fatal("basename: %s: %s", path, errno_s);
2964
2965 file = kore_strdup(p);
2966 kore_free(copy);
2967
2968 if ((p = strrchr(file, '.')) != NULL)
2969 *p = '\0';
2970
2971 python_append_path(dir);
2972
2973 if (S_ISDIR(st.st_mode))
2974 python_append_path(path);
2975
2976 module = PyImport_ImportModule(file);
2977 if (module == NULL)
2978 PyErr_Print();
2979
2980 kore_free(dir);
2981 kore_free(file);
2982
2983 return (module);
2984 }
2985
2986 static PyObject *
2987 python_callable(PyObject *module, const char *symbol)
2988 {
2989 char *base, *method;
2990 PyObject *res, *obj, *meth;
2991
2992 res = NULL;
2993 obj = NULL;
2994 base = kore_strdup(symbol);
2995
2996 if ((method = strchr(base, '.')) != NULL)
2997 *(method)++ = '\0';
2998
2999 if ((obj = PyObject_GetAttrString(module, base)) == NULL)
3000 goto out;
3001
3002 if (method != NULL) {
3003 if ((meth = PyObject_GetAttrString(obj, method)) == NULL)
3004 goto out;
3005
3006 Py_DECREF(obj);
3007 obj = meth;
3008 }
3009
3010 if (!PyCallable_Check(obj))
3011 goto out;
3012
3013 res = obj;
3014 obj = NULL;
3015
3016 out:
3017 if (obj != NULL)
3018 Py_DECREF(obj);
3019
3020 PyErr_Clear();
3021 kore_free(base);
3022
3023 return (res);
3024 }
3025
3026 static PyObject *
3027 pyconnection_alloc(struct connection *c)
3028 {
3029 struct pyconnection *pyc;
3030
3031 pyc = PyObject_New(struct pyconnection, &pyconnection_type);
3032 if (pyc == NULL)
3033 return (NULL);
3034
3035 pyc->c = c;
3036
3037 return ((PyObject *)pyc);
3038 }
3039
3040 static PyObject *
3041 pyconnection_disconnect(struct pyconnection *pyc, PyObject *args)
3042 {
3043 kore_connection_disconnect(pyc->c);
3044
3045 Py_RETURN_TRUE;
3046 }
3047
3048 static PyObject *
3049 pyconnection_get_fd(struct pyconnection *pyc, void *closure)
3050 {
3051 PyObject *fd;
3052
3053 if ((fd = PyLong_FromLong(pyc->c->fd)) == NULL)
3054 return (PyErr_NoMemory());
3055
3056 return (fd);
3057 }
3058
3059 static PyObject *
3060 pyconnection_get_addr(struct pyconnection *pyc, void *closure)
3061 {
3062 void *ptr;
3063 PyObject *result;
3064 char addr[INET6_ADDRSTRLEN];
3065
3066 switch (pyc->c->family) {
3067 case AF_INET:
3068 ptr = &pyc->c->addr.ipv4.sin_addr;
3069 break;
3070 case AF_INET6:
3071 ptr = &pyc->c->addr.ipv6.sin6_addr;
3072 break;
3073 default:
3074 PyErr_SetString(PyExc_RuntimeError, "invalid family");
3075 return (NULL);
3076 }
3077
3078 if (inet_ntop(pyc->c->family, ptr, addr, sizeof(addr)) == NULL) {
3079 PyErr_SetString(PyExc_RuntimeError, "inet_ntop failed");
3080 return (NULL);
3081 }
3082
3083 if ((result = PyUnicode_FromString(addr)) == NULL)
3084 return (PyErr_NoMemory());
3085
3086 return (result);
3087 }
3088
3089 static PyObject *
3090 pyconnection_get_peer_x509(struct pyconnection *pyc, void *closure)
3091 {
3092 size_t len;
3093 u_int8_t *der;
3094 PyObject *bytes;
3095
3096 if (pyc->c->tls_cert == NULL) {
3097 Py_RETURN_NONE;
3098 }
3099
3100 if (!kore_tls_x509_data(pyc->c, &der, &len)) {
3101 PyErr_SetString(PyExc_RuntimeError,
3102 "failed to obtain certificate data");
3103 return (NULL);
3104 }
3105
3106 bytes = PyBytes_FromStringAndSize((char *)der, len);
3107 kore_free(der);
3108
3109 return (bytes);
3110 }
3111
3112 static PyObject *
3113 pyconnection_get_peer_x509dict(struct pyconnection *pyc, void *closure)
3114 {
3115 KORE_X509_NAMES *name;
3116 PyObject *dict, *issuer, *subject, *ret;
3117
3118 ret = NULL;
3119 issuer = NULL;
3120 subject = NULL;
3121
3122 if (pyc->c->tls_cert == NULL) {
3123 Py_RETURN_NONE;
3124 }
3125
3126 if ((dict = PyDict_New()) == NULL)
3127 goto out;
3128
3129 if ((issuer = PyDict_New()) == NULL)
3130 goto out;
3131
3132 if (PyDict_SetItemString(dict, "issuer", issuer) == -1)
3133 goto out;
3134
3135 if ((subject = PyDict_New()) == NULL)
3136 goto out;
3137
3138 if (PyDict_SetItemString(dict, "subject", subject) == -1)
3139 goto out;
3140
3141 PyErr_Clear();
3142
3143 if ((name = kore_tls_x509_subject_name(pyc->c)) == NULL) {
3144 PyErr_Format(PyExc_RuntimeError,
3145 "failed to obtain x509 subjectName");
3146 goto out;
3147 }
3148
3149 if (!kore_tls_x509name_foreach(name, 0, subject,
3150 pyconnection_x509_cb)) {
3151 if (PyErr_Occurred() == NULL) {
3152 PyErr_Format(PyExc_RuntimeError,
3153 "failed to add subject name to dictionary");
3154 }
3155 goto out;
3156 }
3157
3158 if ((name = kore_tls_x509_issuer_name(pyc->c)) == NULL) {
3159 PyErr_Format(PyExc_RuntimeError,
3160 "failed to obtain x509 issuerName");
3161 goto out;
3162 }
3163
3164 if (!kore_tls_x509name_foreach(name, 0, issuer, pyconnection_x509_cb)) {
3165 if (PyErr_Occurred() == NULL) {
3166 PyErr_Format(PyExc_RuntimeError,
3167 "failed to add issuer name to dictionary");
3168 }
3169 goto out;
3170 }
3171
3172 ret = dict;
3173 dict = NULL;
3174
3175 out:
3176 Py_XDECREF(dict);
3177 Py_XDECREF(issuer);
3178 Py_XDECREF(subject);
3179
3180 return (ret);
3181 }
3182
3183 static int
3184 pyconnection_x509_cb(void *udata, int islast, int nid, const char *field,
3185 const void *data, size_t len, int flags)
3186 {
3187 PyObject *dict, *obj;
3188
3189 dict = udata;
3190
3191 if ((obj = PyUnicode_FromStringAndSize(data, len)) == NULL)
3192 return (KORE_RESULT_ERROR);
3193
3194 if (PyDict_SetItemString(dict, field, obj) == -1) {
3195 Py_DECREF(obj);
3196 return (KORE_RESULT_ERROR);
3197 }
3198
3199 Py_DECREF(obj);
3200 return (KORE_RESULT_OK);
3201 }
3202
3203 static void
3204 pytimer_run(void *arg, u_int64_t now)
3205 {
3206 PyObject *ret;
3207 struct kore_timer *run;
3208 struct pytimer *timer;
3209
3210 timer = arg;
3211 run = timer->run;
3212 timer->run = NULL;
3213
3214 PyErr_Clear();
3215 ret = PyObject_CallFunctionObjArgs(timer->callable, timer->udata, NULL);
3216 Py_XDECREF(ret);
3217
3218 kore_python_log_error("pytimer_run");
3219
3220 if (timer->flags & KORE_TIMER_ONESHOT) {
3221 run->flags |= KORE_TIMER_ONESHOT;
3222 Py_DECREF((PyObject *)timer);
3223 }
3224 else {
3225 timer->run = run;
3226 }
3227 }
3228
3229
3230 static void
3231 pytimer_dealloc(struct pytimer *timer)
3232 {
3233 if (timer->run != NULL) {
3234 kore_timer_remove(timer->run);
3235 timer->run = NULL;
3236 }
3237
3238 if (timer->callable != NULL) {
3239 Py_DECREF(timer->callable);
3240 timer->callable = NULL;
3241 }
3242
3243 if (timer->udata != NULL) {
3244 Py_DECREF(timer->udata);
3245 timer->udata = NULL;
3246 }
3247
3248 PyObject_Del((PyObject *)timer);
3249 }
3250
3251 static PyObject *
3252 pytimer_close(struct pytimer *timer, PyObject *args)
3253 {
3254 if (timer->run != NULL) {
3255 kore_timer_remove(timer->run);
3256 timer->run = NULL;
3257 Py_DECREF((PyObject *)timer);
3258 } else {
3259 timer->flags |= KORE_TIMER_ONESHOT;
3260 }
3261
3262 Py_RETURN_TRUE;
3263 }
3264
3265 static void
3266 pysuspend_op_dealloc(struct pysuspend_op *op)
3267 {
3268 if (op->timer != NULL) {
3269 kore_timer_remove(op->timer);
3270 op->timer = NULL;
3271 }
3272
3273 PyObject_Del((PyObject *)op);
3274 }
3275
3276 static PyObject *
3277 pysuspend_op_await(PyObject *sop)
3278 {
3279 Py_INCREF(sop);
3280 return (sop);
3281 }
3282
3283 static PyObject *
3284 pysuspend_op_iternext(struct pysuspend_op *op)
3285 {
3286 switch (op->state) {
3287 case PYSUSPEND_OP_INIT:
3288 op->timer = kore_timer_add(pysuspend_wakeup, op->delay,
3289 op, KORE_TIMER_ONESHOT);
3290 op->state = PYSUSPEND_OP_WAIT;
3291 break;
3292 case PYSUSPEND_OP_WAIT:
3293 break;
3294 case PYSUSPEND_OP_CONTINUE:
3295 PyErr_SetNone(PyExc_StopIteration);
3296 return (NULL);
3297 default:
3298 fatal("unknown state %d for pysuspend_op", op->state);
3299 }
3300
3301 Py_RETURN_NONE;
3302 }
3303
3304 static void
3305 pysuspend_wakeup(void *arg, u_int64_t now)
3306 {
3307 struct pysuspend_op *op = arg;
3308
3309 op->timer = NULL;
3310 op->state = PYSUSPEND_OP_CONTINUE;
3311
3312 if (op->coro->request != NULL)
3313 http_request_wakeup(op->coro->request);
3314 else
3315 python_coro_wakeup(op->coro);
3316 }
3317
3318 static struct pysocket *
3319 pysocket_alloc(void)
3320 {
3321 struct pysocket *sock;
3322
3323 if ((sock = PyObject_New(struct pysocket, &pysocket_type)) == NULL)
3324 return (NULL);
3325
3326 sock->fd = -1;
3327 sock->family = -1;
3328 sock->protocol = -1;
3329 sock->scheduled = 0;
3330
3331 sock->socket = NULL;
3332 sock->recvop = NULL;
3333 sock->sendop = NULL;
3334
3335 sock->event.s = sock;
3336 sock->event.evt.flags = 0;
3337 sock->event.evt.type = KORE_TYPE_PYSOCKET;
3338 sock->event.evt.handle = pysocket_evt_handle;
3339
3340 return (sock);
3341 }
3342
3343 static void
3344 pysocket_dealloc(struct pysocket *sock)
3345 {
3346 if (sock->scheduled && sock->fd != -1) {
3347 kore_platform_disable_read(sock->fd);
3348 #if !defined(__linux__)
3349 kore_platform_disable_write(sock->fd);
3350 #endif
3351 }
3352
3353 if (sock->socket != NULL) {
3354 Py_DECREF(sock->socket);
3355 } else if (sock->fd != -1) {
3356 (void)close(sock->fd);
3357 }
3358
3359 PyObject_Del((PyObject *)sock);
3360 }
3361
3362 static PyObject *
3363 pysocket_send(struct pysocket *sock, PyObject *args)
3364 {
3365 Py_buffer buf;
3366 PyObject *ret;
3367
3368 if (!PyArg_ParseTuple(args, "y*", &buf))
3369 return (NULL);
3370
3371 ret = pysocket_op_create(sock, PYSOCKET_TYPE_SEND, buf.buf, buf.len);
3372 PyBuffer_Release(&buf);
3373
3374 return (ret);
3375 }
3376
3377 static PyObject *
3378 pysocket_sendto(struct pysocket *sock, PyObject *args)
3379 {
3380 Py_buffer buf;
3381 struct pysocket_op *op;
3382 PyObject *ret;
3383 int port;
3384 const char *ip, *sockaddr;
3385
3386 switch (sock->family) {
3387 case AF_INET:
3388 if (!PyArg_ParseTuple(args, "siy*", &ip, &port, &buf))
3389 return (NULL);
3390 if (port <= 0 || port >= USHRT_MAX) {
3391 PyErr_SetString(PyExc_RuntimeError, "invalid port");
3392 return (NULL);
3393 }
3394 break;
3395 case AF_UNIX:
3396 if (!PyArg_ParseTuple(args, "sy*", &sockaddr, &buf))
3397 return (NULL);
3398 break;
3399 default:
3400 PyErr_SetString(PyExc_RuntimeError, "unsupported family");
3401 return (NULL);
3402 }
3403
3404 ret = pysocket_op_create(sock, PYSOCKET_TYPE_SENDTO, buf.buf, buf.len);
3405 PyBuffer_Release(&buf);
3406
3407 op = (struct pysocket_op *)ret;
3408
3409 switch (sock->family) {
3410 case AF_INET:
3411 op->sendaddr.ipv4.sin_family = AF_INET;
3412 op->sendaddr.ipv4.sin_port = htons(port);
3413 op->sendaddr.ipv4.sin_addr.s_addr = inet_addr(ip);
3414 break;
3415 case AF_UNIX:
3416 op->sendaddr.sun.sun_family = AF_UNIX;
3417 if (kore_strlcpy(op->sendaddr.sun.sun_path, sockaddr,
3418 sizeof(op->sendaddr.sun.sun_path)) >=
3419 sizeof(op->sendaddr.sun.sun_path)) {
3420 Py_DECREF(ret);
3421 PyErr_SetString(PyExc_RuntimeError,
3422 "unix socket path too long");
3423 return (NULL);
3424 }
3425 break;
3426 default:
3427 Py_DECREF(ret);
3428 PyErr_SetString(PyExc_RuntimeError, "unsupported family");
3429 return (NULL);
3430 }
3431
3432 return (ret);
3433 }
3434
3435 static PyObject *
3436 pysocket_recv(struct pysocket *sock, PyObject *args)
3437 {
3438 Py_ssize_t len;
3439 struct pysocket_op *op;
3440 PyObject *obj;
3441 int timeo;
3442
3443 timeo = -1;
3444
3445 if (!PyArg_ParseTuple(args, "n|i", &len, &timeo))
3446 return (NULL);
3447
3448 obj = pysocket_op_create(sock, PYSOCKET_TYPE_RECV, NULL, len);
3449 if (obj == NULL)
3450 return (NULL);
3451
3452 op = (struct pysocket_op *)obj;
3453
3454 if (timeo != -1) {
3455 op->timer = kore_timer_add(pysocket_op_timeout,
3456 timeo, op, KORE_TIMER_ONESHOT);
3457 }
3458
3459 return (obj);
3460 }
3461
3462 static PyObject *
3463 pysocket_recvmsg(struct pysocket *sock, PyObject *args)
3464 {
3465 Py_ssize_t len;
3466
3467 if (!PyArg_ParseTuple(args, "n", &len))
3468 return (NULL);
3469
3470 return (pysocket_op_create(sock, PYSOCKET_TYPE_RECVMSG, NULL, len));
3471 }
3472
3473 static PyObject *
3474 pysocket_recvfrom(struct pysocket *sock, PyObject *args)
3475 {
3476 Py_ssize_t len;
3477
3478 if (!PyArg_ParseTuple(args, "n", &len))
3479 return (NULL);
3480
3481 return (pysocket_op_create(sock, PYSOCKET_TYPE_RECVFROM, NULL, len));
3482 }
3483
3484 static PyObject *
3485 pysocket_accept(struct pysocket *sock, PyObject *args)
3486 {
3487 return (pysocket_op_create(sock, PYSOCKET_TYPE_ACCEPT, NULL, 0));
3488 }
3489
3490 static PyObject *
3491 pysocket_connect(struct pysocket *sock, PyObject *args)
3492 {
3493 const char *host;
3494 int port, len;
3495
3496 port = 0;
3497
3498 if (!PyArg_ParseTuple(args, "s|i", &host, &port))
3499 return (NULL);
3500
3501 if (port < 0 || port > USHRT_MAX) {
3502 PyErr_SetString(PyExc_RuntimeError, "invalid port number");
3503 return (NULL);
3504 }
3505
3506 switch (sock->family) {
3507 case AF_INET:
3508 sock->addr.ipv4.sin_family = AF_INET;
3509 sock->addr.ipv4.sin_port = htons(port);
3510 if (inet_pton(sock->family, host,
3511 &sock->addr.ipv4.sin_addr) == -1) {
3512 PyErr_SetString(PyExc_RuntimeError, "invalid host");
3513 return (NULL);
3514 }
3515 sock->addr_len = sizeof(sock->addr.ipv4);
3516 break;
3517 case AF_UNIX:
3518 sock->addr.sun.sun_family = AF_UNIX;
3519 len = snprintf(sock->addr.sun.sun_path,
3520 sizeof(sock->addr.sun.sun_path), "%s", host);
3521 if (len == -1 ||
3522 (size_t)len >= sizeof(sock->addr.sun.sun_path)) {
3523 PyErr_SetString(PyExc_RuntimeError, "path too long");
3524 return (NULL);
3525 }
3526 #if defined(__linux__)
3527 /* Assume abstract socket if prefixed with '@'. */
3528 if (sock->addr.sun.sun_path[0] == '@')
3529 sock->addr.sun.sun_path[0] = '\0';
3530 #endif
3531 sock->addr_len = sizeof(sock->addr.sun.sun_family) + len;
3532 break;
3533 default:
3534 fatal("unsupported socket family %d", sock->family);
3535 }
3536
3537 return (pysocket_op_create(sock, PYSOCKET_TYPE_CONNECT, NULL, 0));
3538 }
3539
3540 static PyObject *
3541 pysocket_close(struct pysocket *sock, PyObject *args)
3542 {
3543 if (sock->scheduled) {
3544 sock->scheduled = 0;
3545 kore_platform_disable_read(sock->fd);
3546 #if !defined(__linux__)
3547 kore_platform_disable_write(sock->fd);
3548 #endif
3549 }
3550
3551 if (sock->socket != NULL) {
3552 Py_DECREF(sock->socket);
3553 sock->socket = NULL;
3554 } else if (sock->fd != -1) {
3555 (void)close(sock->fd);
3556 }
3557
3558 sock->fd = -1;
3559 sock->event.evt.handle(&sock->event, 1);
3560
3561 Py_RETURN_TRUE;
3562 }
3563
3564 static void
3565 pysocket_op_dealloc(struct pysocket_op *op)
3566 {
3567 if (op->type == PYSOCKET_TYPE_RECV ||
3568 op->type == PYSOCKET_TYPE_RECVMSG ||
3569 op->type == PYSOCKET_TYPE_RECVFROM ||
3570 op->type == PYSOCKET_TYPE_SEND ||
3571 op->type == PYSOCKET_TYPE_SENDTO)
3572 kore_buf_cleanup(&op->buffer);
3573
3574 switch (op->type) {
3575 case PYSOCKET_TYPE_RECV:
3576 case PYSOCKET_TYPE_ACCEPT:
3577 case PYSOCKET_TYPE_RECVMSG:
3578 case PYSOCKET_TYPE_RECVFROM:
3579 if (op->socket->recvop != op)
3580 fatal("recvop mismatch");
3581 op->socket->recvop = NULL;
3582 break;
3583 case PYSOCKET_TYPE_SEND:
3584 case PYSOCKET_TYPE_SENDTO:
3585 case PYSOCKET_TYPE_CONNECT:
3586 if (op->socket->sendop != op)
3587 fatal("sendop mismatch");
3588 op->socket->sendop = NULL;
3589 break;
3590 }
3591
3592 if (op->timer != NULL) {
3593 kore_timer_remove(op->timer);
3594 op->timer = NULL;
3595 }
3596
3597 op->coro->sockop = NULL;
3598 Py_DECREF(op->socket);
3599
3600 PyObject_Del((PyObject *)op);
3601 }
3602
3603 static PyObject *
3604 pysocket_op_create(struct pysocket *sock, int type, const void *ptr, size_t len)
3605 {
3606 struct pysocket_op *op;
3607
3608 if (coro_running->sockop != NULL)
3609 fatal("pysocket_op_create: coro has active socketop");
3610
3611 switch (type) {
3612 case PYSOCKET_TYPE_RECV:
3613 case PYSOCKET_TYPE_ACCEPT:
3614 case PYSOCKET_TYPE_RECVMSG:
3615 case PYSOCKET_TYPE_RECVFROM:
3616 if (sock->recvop != NULL) {
3617 PyErr_SetString(PyExc_RuntimeError,
3618 "only one recv operation can be done per socket");
3619 return (NULL);
3620 }
3621 break;
3622 case PYSOCKET_TYPE_SEND:
3623 case PYSOCKET_TYPE_SENDTO:
3624 case PYSOCKET_TYPE_CONNECT:
3625 if (sock->sendop != NULL) {
3626 PyErr_SetString(PyExc_RuntimeError,
3627 "only one send operation can be done per socket");
3628 return (NULL);
3629 }
3630 break;
3631 default:
3632 fatal("unknown pysocket_op type %u", type);
3633 }
3634
3635 op = PyObject_New(struct pysocket_op, &pysocket_op_type);
3636 if (op == NULL)
3637 return (NULL);
3638
3639 op->eof = 0;
3640 op->self = op;
3641 op->type = type;
3642 op->timer = NULL;
3643 op->socket = sock;
3644 op->coro = coro_running;
3645
3646 coro_running->sockop = op;
3647 Py_INCREF(op->socket);
3648
3649 switch (type) {
3650 case PYSOCKET_TYPE_RECV:
3651 case PYSOCKET_TYPE_RECVMSG:
3652 case PYSOCKET_TYPE_RECVFROM:
3653 sock->recvop = op;
3654 kore_buf_init(&op->buffer, len);
3655 break;
3656 case PYSOCKET_TYPE_SEND:
3657 case PYSOCKET_TYPE_SENDTO:
3658 sock->sendop = op;
3659 kore_buf_init(&op->buffer, len);
3660 kore_buf_append(&op->buffer, ptr, len);
3661 kore_buf_reset(&op->buffer);
3662 break;
3663 case PYSOCKET_TYPE_ACCEPT:
3664 sock->recvop = op;
3665 break;
3666 case PYSOCKET_TYPE_CONNECT:
3667 sock->sendop = op;
3668 break;
3669 default:
3670 fatal("unknown pysocket_op type %u", type);
3671 }
3672
3673 if (sock->scheduled == 0) {
3674 sock->scheduled = 1;
3675 kore_platform_event_all(sock->fd, &sock->event);
3676 }
3677
3678 return ((PyObject *)op);
3679 }
3680
3681 static PyObject *
3682 pysocket_op_await(PyObject *obj)
3683 {
3684 Py_INCREF(obj);
3685 return (obj);
3686 }
3687
3688 static PyObject *
3689 pysocket_op_iternext(struct pysocket_op *op)
3690 {
3691 PyObject *ret;
3692
3693 if (op->socket->fd == -1) {
3694 PyErr_SetNone(PyExc_StopIteration);
3695 return (NULL);
3696 }
3697
3698 if (op->eof) {
3699 if (op->coro->exception != NULL) {
3700 PyErr_SetString(op->coro->exception,
3701 op->coro->exception_msg);
3702 op->coro->exception = NULL;
3703 return (NULL);
3704 }
3705
3706 if (op->type != PYSOCKET_TYPE_RECV) {
3707 PyErr_SetString(PyExc_RuntimeError, "socket EOF");
3708 return (NULL);
3709 }
3710
3711 /* Drain the recv socket. */
3712 op->socket->event.evt.flags |= KORE_EVENT_READ;
3713 return (pysocket_async_recv(op));
3714 }
3715
3716 switch (op->type) {
3717 case PYSOCKET_TYPE_CONNECT:
3718 ret = pysocket_async_connect(op);
3719 break;
3720 case PYSOCKET_TYPE_ACCEPT:
3721 ret = pysocket_async_accept(op);
3722 break;
3723 case PYSOCKET_TYPE_RECV:
3724 case PYSOCKET_TYPE_RECVMSG:
3725 case PYSOCKET_TYPE_RECVFROM:
3726 ret = pysocket_async_recv(op);
3727 break;
3728 case PYSOCKET_TYPE_SEND:
3729 case PYSOCKET_TYPE_SENDTO:
3730 ret = pysocket_async_send(op);
3731 break;
3732 default:
3733 PyErr_SetString(PyExc_RuntimeError, "invalid op type");
3734 return (NULL);
3735 }
3736
3737 return (ret);
3738 }
3739
3740 static void
3741 pysocket_op_timeout(void *arg, u_int64_t now)
3742 {
3743 struct pysocket_op *op = arg;
3744
3745 op->eof = 1;
3746 op->timer = NULL;
3747
3748 op->coro->exception = PyExc_TimeoutError;
3749 op->coro->exception_msg = "timeout before operation completed";
3750
3751 if (op->coro->request != NULL)
3752 http_request_wakeup(op->coro->request);
3753 else
3754 python_coro_wakeup(op->coro);
3755 }
3756
3757 static PyObject *
3758 pysocket_async_connect(struct pysocket_op *op)
3759 {
3760 if (connect(op->socket->fd, (struct sockaddr *)&op->socket->addr,
3761 op->socket->addr_len) == -1) {
3762 if (errno != EALREADY && errno != EINPROGRESS &&
3763 errno != EISCONN && errno != EAGAIN) {
3764 PyErr_SetString(PyExc_RuntimeError, errno_s);
3765 return (NULL);
3766 }
3767
3768 if (errno != EISCONN) {
3769 Py_RETURN_NONE;
3770 }
3771 }
3772
3773 PyErr_SetNone(PyExc_StopIteration);
3774 return (NULL);
3775 }
3776
3777 static PyObject *
3778 pysocket_async_accept(struct pysocket_op *op)
3779 {
3780 int fd;
3781 struct pysocket *sock;
3782
3783 if (!(op->socket->event.evt.flags & KORE_EVENT_READ)) {
3784 Py_RETURN_NONE;
3785 }
3786
3787 if ((sock = pysocket_alloc()) == NULL)
3788 return (NULL);
3789
3790 sock->addr_len = sizeof(sock->addr);
3791
3792 if ((fd = accept(op->socket->fd,
3793 (struct sockaddr *)&sock->addr, &sock->addr_len)) == -1) {
3794 Py_DECREF((PyObject *)sock);
3795 if (errno == EAGAIN || errno == EWOULDBLOCK) {
3796 op->socket->event.evt.flags &= ~KORE_EVENT_READ;
3797 Py_RETURN_NONE;
3798 }
3799 PyErr_SetString(PyExc_RuntimeError, errno_s);
3800 return (NULL);
3801 }
3802
3803 if (!kore_connection_nonblock(fd, 0)) {
3804 Py_DECREF((PyObject *)sock);
3805 PyErr_SetString(PyExc_RuntimeError, errno_s);
3806 return (NULL);
3807 }
3808
3809 sock->fd = fd;
3810 sock->socket = NULL;
3811 sock->family = op->socket->family;
3812 sock->protocol = op->socket->protocol;
3813
3814 PyErr_SetObject(PyExc_StopIteration, (PyObject *)sock);
3815 Py_DECREF((PyObject *)sock);
3816
3817 return (NULL);
3818 }
3819
3820 static PyObject *
3821 pysocket_async_recv(struct pysocket_op *op)
3822 {
3823 ssize_t ret;
3824 size_t len;
3825 u_int16_t port;
3826 struct iovec iov;
3827 struct msghdr msg;
3828 socklen_t socklen;
3829 struct sockaddr *sendaddr;
3830 const char *ptr, *ip;
3831 u_int8_t ancdata[1024];
3832 PyObject *bytes, *result, *tuple, *list;
3833
3834 if (!(op->socket->event.evt.flags & KORE_EVENT_READ)) {
3835 Py_RETURN_NONE;
3836 }
3837
3838 socklen = 0;
3839
3840 for (;;) {
3841 switch (op->type) {
3842 case PYSOCKET_TYPE_RECV:
3843 ret = read(op->socket->fd, op->buffer.data,
3844 op->buffer.length);
3845 break;
3846 case PYSOCKET_TYPE_RECVMSG:
3847 memset(&msg, 0, sizeof(msg));
3848
3849 iov.iov_base = op->buffer.data;
3850 iov.iov_len = op->buffer.length;
3851
3852 msg.msg_iov = &iov;
3853 msg.msg_iovlen = 1;
3854 msg.msg_name = &op->sendaddr;
3855 msg.msg_namelen = sizeof(op->sendaddr);
3856 msg.msg_control = ancdata;
3857 msg.msg_controllen = sizeof(ancdata);
3858
3859 memset(&op->sendaddr, 0, sizeof(op->sendaddr));
3860 ret = recvmsg(op->socket->fd, &msg, 0);
3861 break;
3862 case PYSOCKET_TYPE_RECVFROM:
3863 sendaddr = (struct sockaddr *)&op->sendaddr;
3864 switch (op->socket->family) {
3865 case AF_INET:
3866 socklen = sizeof(op->sendaddr.ipv4);
3867 break;
3868 case AF_UNIX:
3869 socklen = sizeof(op->sendaddr.sun);
3870 break;
3871 default:
3872 fatal("%s: non AF_INET/AF_UNIX", __func__);
3873 }
3874
3875 memset(sendaddr, 0, socklen);
3876 ret = recvfrom(op->socket->fd, op->buffer.data,
3877 op->buffer.length, 0, sendaddr, &socklen);
3878 break;
3879 default:
3880 fatal("%s: unknown type %d", __func__, op->type);
3881 }
3882
3883 if (ret == -1) {
3884 if (errno == EINTR)
3885 continue;
3886 if (errno == EAGAIN || errno == EWOULDBLOCK) {
3887 op->socket->event.evt.flags &= ~KORE_EVENT_READ;
3888 Py_RETURN_NONE;
3889 }
3890 PyErr_SetString(PyExc_RuntimeError, errno_s);
3891 return (NULL);
3892 }
3893
3894 break;
3895 }
3896
3897 op->coro->exception = NULL;
3898 op->coro->exception_msg = NULL;
3899
3900 if (op->timer != NULL) {
3901 kore_timer_remove(op->timer);
3902 op->timer = NULL;
3903 }
3904
3905 if (op->type == PYSOCKET_TYPE_RECV && ret == 0) {
3906 PyErr_SetNone(PyExc_StopIteration);
3907 return (NULL);
3908 }
3909
3910 ptr = (const char *)op->buffer.data;
3911 if ((bytes = PyBytes_FromStringAndSize(ptr, ret)) == NULL)
3912 return (NULL);
3913
3914 list = NULL;
3915
3916 switch (op->type) {
3917 case PYSOCKET_TYPE_RECV:
3918 PyErr_SetObject(PyExc_StopIteration, bytes);
3919 Py_DECREF(bytes);
3920 return (NULL);
3921 case PYSOCKET_TYPE_RECVMSG:
3922 socklen = msg.msg_namelen;
3923 if ((list = python_cmsg_to_list(&msg)) == NULL) {
3924 Py_DECREF(bytes);
3925 return (NULL);
3926 }
3927 break;
3928 case PYSOCKET_TYPE_RECVFROM:
3929 break;
3930 default:
3931 fatal("%s: unknown type %d", __func__, op->type);
3932 }
3933
3934 switch(op->socket->family) {
3935 case AF_INET:
3936 port = ntohs(op->sendaddr.ipv4.sin_port);
3937 ip = inet_ntoa(op->sendaddr.ipv4.sin_addr);
3938
3939 if (op->type == PYSOCKET_TYPE_RECVFROM)
3940 tuple = Py_BuildValue("(sHN)", ip, port, bytes);
3941 else
3942 tuple = Py_BuildValue("(sHNN)", ip, port, bytes, list);
3943 break;
3944 case AF_UNIX:
3945 len = strlen(op->sendaddr.sun.sun_path);
3946 #if defined(__linux__)
3947 if (len == 0 && socklen > 0) {
3948 len = socklen - sizeof(sa_family_t);
3949 op->sendaddr.sun.sun_path[0] = '@';
3950 op->sendaddr.sun.sun_path[len] = '\0';
3951 }
3952 #endif
3953 if (len == 0) {
3954 if (op->type == PYSOCKET_TYPE_RECVFROM) {
3955 tuple = Py_BuildValue("(ON)", Py_None, bytes);
3956 } else {
3957 tuple = Py_BuildValue("(ONN)",
3958 Py_None, bytes, list);
3959 }
3960 } else {
3961 if (op->type == PYSOCKET_TYPE_RECVFROM) {
3962 tuple = Py_BuildValue("(sN)",
3963 op->sendaddr.sun.sun_path, bytes);
3964 } else {
3965 tuple = Py_BuildValue("(sNN)",
3966 op->sendaddr.sun.sun_path, bytes, list);
3967 }
3968 }
3969 break;
3970 default:
3971 fatal("%s: non AF_INET/AF_UNIX", __func__);
3972 }
3973
3974 if (tuple == NULL) {
3975 Py_XDECREF(list);
3976 Py_DECREF(bytes);
3977 return (NULL);
3978 }
3979
3980 result = PyObject_CallFunctionObjArgs(PyExc_StopIteration, tuple, NULL);
3981 if (result == NULL) {
3982 Py_DECREF(tuple);
3983 return (NULL);
3984 }
3985
3986 Py_DECREF(tuple);
3987 PyErr_SetObject(PyExc_StopIteration, result);
3988 Py_DECREF(result);
3989
3990 return (NULL);
3991 }
3992
3993 static PyObject *
3994 pysocket_async_send(struct pysocket_op *op)
3995 {
3996 ssize_t ret;
3997 socklen_t socklen;
3998 const struct sockaddr *sendaddr;
3999
4000 if (!(op->socket->event.evt.flags & KORE_EVENT_WRITE)) {
4001 Py_RETURN_NONE;
4002 }
4003
4004 for (;;) {
4005 if (op->type == PYSOCKET_TYPE_SEND) {
4006 ret = write(op->socket->fd,
4007 op->buffer.data + op->buffer.offset,
4008 op->buffer.length - op->buffer.offset);
4009 } else {
4010 sendaddr = (const struct sockaddr *)&op->sendaddr;
4011
4012 switch (op->socket->family) {
4013 case AF_INET:
4014 socklen = sizeof(op->sendaddr.ipv4);
4015 break;
4016 case AF_UNIX:
4017 socklen = sizeof(op->sendaddr.sun);
4018 #if defined(__linux__)
4019 if (op->sendaddr.sun.sun_path[0] == '@') {
4020 socklen = sizeof(sa_family_t) +
4021 strlen(op->sendaddr.sun.sun_path);
4022 op->sendaddr.sun.sun_path[0] = '\0';
4023 }
4024 #endif
4025 break;
4026 default:
4027 fatal("non AF_INET/AF_UNIX in %s", __func__);
4028 }
4029
4030 ret = sendto(op->socket->fd,
4031 op->buffer.data + op->buffer.offset,
4032 op->buffer.length - op->buffer.offset,
4033 0, sendaddr, socklen);
4034 }
4035
4036 if (ret == -1) {
4037 if (errno == EINTR)
4038 continue;
4039 if (errno == EAGAIN || errno == EWOULDBLOCK) {
4040 op->socket->event.evt.flags &=
4041 ~KORE_EVENT_WRITE;
4042 Py_RETURN_NONE;
4043 }
4044 PyErr_SetString(PyExc_RuntimeError, errno_s);
4045 return (NULL);
4046 }
4047 break;
4048 }
4049
4050 op->buffer.offset += (size_t)ret;
4051
4052 if (op->buffer.offset == op->buffer.length) {
4053 PyErr_SetNone(PyExc_StopIteration);
4054 return (NULL);
4055 }
4056
4057 Py_RETURN_NONE;
4058 }
4059
4060 static void
4061 pysocket_evt_handle(void *arg, int eof)
4062 {
4063 struct pysocket_event *event = arg;
4064 struct pysocket *socket = event->s;
4065
4066 if ((eof || (event->evt.flags & KORE_EVENT_READ)) &&
4067 socket->recvop != NULL) {
4068 if (socket->recvop->coro->request != NULL)
4069 http_request_wakeup(socket->recvop->coro->request);
4070 else
4071 python_coro_wakeup(socket->recvop->coro);
4072 socket->recvop->eof = eof;
4073 }
4074
4075 if ((eof || (event->evt.flags & KORE_EVENT_WRITE)) &&
4076 socket->sendop != NULL) {
4077 if (socket->sendop->coro->request != NULL)
4078 http_request_wakeup(socket->sendop->coro->request);
4079 else
4080 python_coro_wakeup(socket->sendop->coro);
4081 socket->sendop->eof = eof;
4082 }
4083 }
4084
4085 static void
4086 pyqueue_dealloc(struct pyqueue *queue)
4087 {
4088 struct pyqueue_object *qobj;
4089 struct pyqueue_waiting *waiting;
4090
4091 while ((qobj = TAILQ_FIRST(&queue->objects)) != NULL) {
4092 TAILQ_REMOVE(&queue->objects, qobj, list);
4093 Py_DECREF(qobj->obj);
4094 kore_pool_put(&queue_object_pool, qobj);
4095 }
4096
4097 while ((waiting = TAILQ_FIRST(&queue->waiting)) != NULL) {
4098 TAILQ_REMOVE(&queue->waiting, waiting, list);
4099 if (waiting->op != NULL)
4100 waiting->op->waiting = NULL;
4101 kore_pool_put(&queue_wait_pool, waiting);
4102 }
4103
4104 PyObject_Del((PyObject *)queue);
4105 }
4106
4107 static PyObject *
4108 pyqueue_pop(struct pyqueue *queue, PyObject *args)
4109 {
4110 struct pyqueue_op *op;
4111
4112 if ((op = PyObject_New(struct pyqueue_op, &pyqueue_op_type)) == NULL)
4113 return (NULL);
4114
4115 op->queue = queue;
4116 op->waiting = kore_pool_get(&queue_wait_pool);
4117 op->waiting->op = op;
4118
4119 op->waiting->coro = coro_running;
4120 TAILQ_INSERT_TAIL(&queue->waiting, op->waiting, list);
4121
4122 Py_INCREF((PyObject *)queue);
4123
4124 return ((PyObject *)op);
4125 }
4126
4127 static PyObject *
4128 pyqueue_popnow(struct pyqueue *queue, PyObject *args)
4129 {
4130 PyObject *obj;
4131 struct pyqueue_object *qobj;
4132
4133 if ((qobj = TAILQ_FIRST(&queue->objects)) == NULL) {
4134 Py_RETURN_NONE;
4135 }
4136
4137 TAILQ_REMOVE(&queue->objects, qobj, list);
4138
4139 obj = qobj->obj;
4140 kore_pool_put(&queue_object_pool, qobj);
4141
4142 return (obj);
4143 }
4144
4145 static PyObject *
4146 pyqueue_push(struct pyqueue *queue, PyObject *args)
4147 {
4148 PyObject *obj;
4149 struct pyqueue_object *qobj;
4150 struct pyqueue_waiting *waiting;
4151
4152 if (!PyArg_ParseTuple(args, "O", &obj))
4153 return (NULL);
4154
4155 Py_INCREF(obj);
4156
4157 qobj = kore_pool_get(&queue_object_pool);
4158 qobj ->obj = obj;
4159
4160 TAILQ_INSERT_TAIL(&queue->objects, qobj, list);
4161
4162 /* Wakeup first in line if any. */
4163 if ((waiting = TAILQ_FIRST(&queue->waiting)) != NULL) {
4164 TAILQ_REMOVE(&queue->waiting, waiting, list);
4165
4166 /* wakeup HTTP request if one is tied. */
4167 if (waiting->coro->request != NULL)
4168 http_request_wakeup(waiting->coro->request);
4169 else
4170 python_coro_wakeup(waiting->coro);
4171
4172 waiting->op->waiting = NULL;
4173 kore_pool_put(&queue_wait_pool, waiting);
4174 }
4175
4176 Py_RETURN_TRUE;
4177 }
4178
4179 static void
4180 pyqueue_op_dealloc(struct pyqueue_op *op)
4181 {
4182 if (op->waiting != NULL) {
4183 TAILQ_REMOVE(&op->queue->waiting, op->waiting, list);
4184 kore_pool_put(&queue_wait_pool, op->waiting);
4185 op->waiting = NULL;
4186 }
4187
4188 Py_DECREF((PyObject *)op->queue);
4189 PyObject_Del((PyObject *)op);
4190 }
4191
4192 static PyObject *
4193 pyqueue_op_await(PyObject *obj)
4194 {
4195 Py_INCREF(obj);
4196 return (obj);
4197 }
4198
4199 static PyObject *
4200 pyqueue_op_iternext(struct pyqueue_op *op)
4201 {
4202 PyObject *obj;
4203 struct pyqueue_object *qobj;
4204 struct pyqueue_waiting *waiting;
4205
4206 if ((qobj = TAILQ_FIRST(&op->queue->objects)) == NULL) {
4207 Py_RETURN_NONE;
4208 }
4209
4210 TAILQ_REMOVE(&op->queue->objects, qobj, list);
4211
4212 obj = qobj->obj;
4213 kore_pool_put(&queue_object_pool, qobj);
4214
4215 TAILQ_FOREACH(waiting, &op->queue->waiting, list) {
4216 if (waiting->coro->id == coro_running->id) {
4217 TAILQ_REMOVE(&op->queue->waiting, waiting, list);
4218 waiting->op->waiting = NULL;
4219 kore_pool_put(&queue_wait_pool, waiting);
4220 break;
4221 }
4222 }
4223
4224 PyErr_SetObject(PyExc_StopIteration, obj);
4225 Py_DECREF(obj);
4226
4227 return (NULL);
4228 }
4229
4230 static void
4231 pylock_dealloc(struct pylock *lock)
4232 {
4233 struct pylock_op *op;
4234
4235 while ((op = TAILQ_FIRST(&lock->ops)) != NULL) {
4236 TAILQ_REMOVE(&lock->ops, op, list);
4237 op->active = 0;
4238 op->coro->lockop = NULL;
4239 Py_DECREF((PyObject *)op);
4240 }
4241
4242 PyObject_Del((PyObject *)lock);
4243 }
4244
4245 static PyObject *
4246 pylock_trylock(struct pylock *lock, PyObject *args)
4247 {
4248 if (lock->owner != NULL)
4249 Py_RETURN_FALSE;
4250
4251 lock->owner = coro_running;
4252
4253 Py_RETURN_TRUE;
4254 }
4255
4256 static PyObject *
4257 pylock_release(struct pylock *lock, PyObject *args)
4258 {
4259 if (lock->owner == NULL) {
4260 PyErr_SetString(PyExc_RuntimeError, "no lock owner set");
4261 return (NULL);
4262 }
4263
4264 if (lock->owner->id != coro_running->id) {
4265 PyErr_SetString(PyExc_RuntimeError, "lock not owned by caller");
4266 return (NULL);
4267 }
4268
4269 pylock_do_release(lock);
4270
4271 Py_RETURN_NONE;
4272 }
4273
4274 static PyObject *
4275 pylock_aenter(struct pylock *lock, PyObject *args)
4276 {
4277 struct pylock_op *op;
4278
4279 if (coro_running->lockop != NULL) {
4280 fatal("%s: lockop not NULL for %" PRIu64,
4281 __func__, coro_running->id);
4282 }
4283
4284 if (lock->owner != NULL && lock->owner->id == coro_running->id) {
4285 PyErr_SetString(PyExc_RuntimeError, "recursive lock detected");
4286 return (NULL);
4287 }
4288
4289 if ((op = PyObject_New(struct pylock_op, &pylock_op_type)) == NULL)
4290 return (NULL);
4291
4292 op->active = 1;
4293 op->lock = lock;
4294 op->locking = 1;
4295 op->coro = coro_running;
4296
4297 coro_running->lockop = op;
4298
4299 Py_INCREF((PyObject *)op);
4300 Py_INCREF((PyObject *)lock);
4301
4302 TAILQ_INSERT_TAIL(&lock->ops, op, list);
4303
4304 return ((PyObject *)op);
4305 }
4306
4307 static PyObject *
4308 pylock_aexit(struct pylock *lock, PyObject *args)
4309 {
4310 struct pylock_op *op;
4311
4312 if (coro_running->lockop != NULL) {
4313 fatal("%s: lockop not NULL for %" PRIu64,
4314 __func__, coro_running->id);
4315 }
4316
4317 if (lock->owner == NULL || lock->owner->id != coro_running->id) {
4318 PyErr_SetString(PyExc_RuntimeError, "invalid lock owner");
4319 return (NULL);
4320 }
4321
4322 if ((op = PyObject_New(struct pylock_op, &pylock_op_type)) == NULL)
4323 return (NULL);
4324
4325 op->active = 1;
4326 op->lock = lock;
4327 op->locking = 0;
4328 op->coro = coro_running;
4329
4330 coro_running->lockop = op;
4331
4332 Py_INCREF((PyObject *)op);
4333 Py_INCREF((PyObject *)lock);
4334
4335 TAILQ_INSERT_TAIL(&lock->ops, op, list);
4336
4337 return ((PyObject *)op);
4338 }
4339
4340 static void
4341 pylock_do_release(struct pylock *lock)
4342 {
4343 struct pylock_op *op;
4344
4345 lock->owner = NULL;
4346
4347 TAILQ_FOREACH(op, &lock->ops, list) {
4348 if (op->locking == 0)
4349 continue;
4350
4351 op->active = 0;
4352 op->coro->lockop = NULL;
4353 TAILQ_REMOVE(&lock->ops, op, list);
4354
4355 if (op->coro->request != NULL)
4356 http_request_wakeup(op->coro->request);
4357 else
4358 python_coro_wakeup(op->coro);
4359
4360 Py_DECREF((PyObject *)op);
4361 break;
4362 }
4363 }
4364
4365 static void
4366 pylock_op_dealloc(struct pylock_op *op)
4367 {
4368 if (op->active) {
4369 TAILQ_REMOVE(&op->lock->ops, op, list);
4370 op->active = 0;
4371 }
4372
4373 op->coro->lockop = NULL;
4374
4375 Py_DECREF((PyObject *)op->lock);
4376 PyObject_Del((PyObject *)op);
4377 }
4378
4379 static PyObject *
4380 pylock_op_await(PyObject *obj)
4381 {
4382 Py_INCREF(obj);
4383 return (obj);
4384 }
4385
4386 static PyObject *
4387 pylock_op_iternext(struct pylock_op *op)
4388 {
4389 if (op->locking == 0) {
4390 if (op->lock->owner == NULL) {
4391 PyErr_SetString(PyExc_RuntimeError,
4392 "no lock owner set");
4393 return (NULL);
4394 }
4395
4396 if (op->lock->owner->id != coro_running->id) {
4397 PyErr_SetString(PyExc_RuntimeError,
4398 "lock not owned by caller");
4399 return (NULL);
4400 }
4401
4402 pylock_do_release(op->lock);
4403 } else {
4404 if (op->lock->owner != NULL) {
4405 /*
4406 * We could be beat by another coroutine that grabbed
4407 * the lock even if we were the one woken up for it.
4408 */
4409 if (op->active == 0) {
4410 op->active = 1;
4411 op->coro->lockop = op;
4412 TAILQ_INSERT_HEAD(&op->lock->ops, op, list);
4413 Py_INCREF((PyObject *)op);
4414 }
4415 Py_RETURN_NONE;
4416 }
4417
4418 op->lock->owner = coro_running;
4419 }
4420
4421 if (op->active) {
4422 op->active = 0;
4423 op->coro->lockop = NULL;
4424 TAILQ_REMOVE(&op->lock->ops, op, list);
4425 Py_DECREF((PyObject *)op);
4426 }
4427
4428 PyErr_SetNone(PyExc_StopIteration);
4429
4430 return (NULL);
4431 }
4432
4433 static void
4434 pyproc_timeout(void *arg, u_int64_t now)
4435 {
4436 struct pyproc *proc = arg;
4437
4438 proc->timer = NULL;
4439
4440 if (proc->coro->sockop != NULL)
4441 proc->coro->sockop->eof = 1;
4442
4443 proc->coro->exception = PyExc_TimeoutError;
4444 proc->coro->exception_msg = "timeout before process exited";
4445
4446 if (proc->coro->request != NULL)
4447 http_request_wakeup(proc->coro->request);
4448 else
4449 python_coro_wakeup(proc->coro);
4450 }
4451
4452 static void
4453 pyproc_dealloc(struct pyproc *proc)
4454 {
4455 int status;
4456
4457 TAILQ_REMOVE(&procs, proc, list);
4458
4459 if (proc->timer != NULL) {
4460 kore_timer_remove(proc->timer);
4461 proc->timer = NULL;
4462 }
4463
4464 if (proc->pid != -1) {
4465 if (kill(proc->pid, SIGKILL) == -1) {
4466 kore_log(LOG_NOTICE,
4467 "kore.proc failed to send SIGKILL %d (%s)",
4468 proc->pid, errno_s);
4469 }
4470
4471 for (;;) {
4472 if (waitpid(proc->pid, &status, 0) == -1) {
4473 if (errno == EINTR)
4474 continue;
4475 kore_log(LOG_NOTICE,
4476 "kore.proc failed to wait for %d (%s)",
4477 proc->pid, errno_s);
4478 }
4479 break;
4480 }
4481 }
4482
4483 if (proc->in != NULL) {
4484 Py_DECREF((PyObject *)proc->in);
4485 proc->in = NULL;
4486 }
4487
4488 if (proc->out != NULL) {
4489 Py_DECREF((PyObject *)proc->out);
4490 proc->out = NULL;
4491 }
4492
4493 PyObject_Del((PyObject *)proc);
4494 }
4495
4496 static PyObject *
4497 pyproc_kill(struct pyproc *proc, PyObject *args)
4498 {
4499 if (proc->pid != -1 && kill(proc->pid, SIGKILL) == -1)
4500 kore_log(LOG_NOTICE, "kill(%d): %s", proc->pid, errno_s);
4501
4502 Py_RETURN_TRUE;
4503 }
4504
4505 static PyObject *
4506 pyproc_reap(struct pyproc *proc, PyObject *args)
4507 {
4508 struct pyproc_op *op;
4509
4510 if (proc->op != NULL) {
4511 PyErr_Format(PyExc_RuntimeError,
4512 "process %d already being reaped", proc->apid);
4513 return (NULL);
4514 }
4515
4516 if (proc->timer != NULL) {
4517 kore_timer_remove(proc->timer);
4518 proc->timer = NULL;
4519 }
4520
4521 if ((op = PyObject_New(struct pyproc_op, &pyproc_op_type)) == NULL)
4522 return (NULL);
4523
4524 op->proc = proc;
4525 op->coro = coro_running;
4526
4527 proc->op = op;
4528
4529 Py_INCREF((PyObject *)proc);
4530
4531 return ((PyObject *)op);
4532 }
4533
4534 static PyObject *
4535 pyproc_recv(struct pyproc *proc, PyObject *args)
4536 {
4537 Py_ssize_t len;
4538 struct pysocket_op *op;
4539 PyObject *obj;
4540 int timeo;
4541
4542 timeo = -1;
4543
4544 if (proc->out == NULL) {
4545 PyErr_SetString(PyExc_RuntimeError, "stdout closed");
4546 return (NULL);
4547 }
4548
4549 if (!PyArg_ParseTuple(args, "n|i", &len, &timeo))
4550 return (NULL);
4551
4552 obj = pysocket_op_create(proc->out, PYSOCKET_TYPE_RECV, NULL, len);
4553 if (obj == NULL)
4554 return (NULL);
4555
4556 op = (struct pysocket_op *)obj;
4557
4558 if (timeo != -1) {
4559 op->timer = kore_timer_add(pysocket_op_timeout,
4560 timeo, op, KORE_TIMER_ONESHOT);
4561 }
4562
4563 return (obj);
4564 }
4565
4566 static PyObject *
4567 pyproc_send(struct pyproc *proc, PyObject *args)
4568 {
4569 Py_buffer buf;
4570 PyObject *ret;
4571
4572 if (proc->in == NULL) {
4573 PyErr_SetString(PyExc_RuntimeError, "stdin closed");
4574 return (NULL);
4575 }
4576
4577 if (!PyArg_ParseTuple(args, "y*", &buf))
4578 return (NULL);
4579
4580 ret = pysocket_op_create(proc->in,
4581 PYSOCKET_TYPE_SEND, buf.buf, buf.len);
4582
4583 PyBuffer_Release(&buf);
4584
4585 return (ret);
4586 }
4587
4588 static PyObject *
4589 pyproc_close_stdin(struct pyproc *proc, PyObject *args)
4590 {
4591 if (proc->in != NULL) {
4592 Py_DECREF((PyObject *)proc->in);
4593 proc->in = NULL;
4594 }
4595
4596 Py_RETURN_TRUE;
4597 }
4598
4599 static PyObject *
4600 pyproc_get_pid(struct pyproc *proc, void *closure)
4601 {
4602 return (PyLong_FromLong(proc->apid));
4603 }
4604
4605 static void
4606 pyproc_op_dealloc(struct pyproc_op *op)
4607 {
4608 Py_DECREF((PyObject *)op->proc);
4609 PyObject_Del((PyObject *)op);
4610 }
4611
4612 static PyObject *
4613 pyproc_op_await(PyObject *sop)
4614 {
4615 Py_INCREF(sop);
4616 return (sop);
4617 }
4618
4619 static PyObject *
4620 pyproc_op_iternext(struct pyproc_op *op)
4621 {
4622 int ret;
4623 PyObject *res;
4624
4625 if (op->proc->coro->exception != NULL) {
4626 PyErr_SetString(op->proc->coro->exception,
4627 op->proc->coro->exception_msg);
4628 op->proc->coro->exception = NULL;
4629 return (NULL);
4630 }
4631
4632 if (op->proc->reaped == 0)
4633 Py_RETURN_NONE;
4634
4635 if (WIFSTOPPED(op->proc->status)) {
4636 op->proc->reaped = 0;
4637 Py_RETURN_NONE;
4638 }
4639
4640 if (WIFEXITED(op->proc->status)) {
4641 ret = WEXITSTATUS(op->proc->status);
4642 } else {
4643 ret = op->proc->status;
4644 }
4645
4646 if ((res = PyLong_FromLong(ret)) == NULL)
4647 return (NULL);
4648
4649 PyErr_SetObject(PyExc_StopIteration, res);
4650 Py_DECREF(res);
4651
4652 return (NULL);
4653 }
4654
4655 static void
4656 pygather_reap_coro(struct pygather_op *op, struct python_coro *reap)
4657 {
4658 struct pygather_coro *coro;
4659 struct pygather_result *result;
4660 #if PY_VERSION_HEX >= 0x030A0000
4661 PyObject *type, *traceback;
4662 #endif
4663
4664 TAILQ_FOREACH(coro, &op->coroutines, list) {
4665 if (coro->coro->id == reap->id)
4666 break;
4667 }
4668
4669 if (coro == NULL)
4670 fatal("coroutine %" PRIu64 " not found in gather", reap->id);
4671
4672 op->running--;
4673 if (op->running < 0)
4674 fatal("gatherop: running miscount (%d)", op->running);
4675
4676 result = kore_pool_get(&gather_result_pool);
4677 result->obj = NULL;
4678
4679 #if PY_VERSION_HEX < 0x030A0000
4680 if (_PyGen_FetchStopIterationValue(&result->obj) == -1) {
4681 result->obj = Py_None;
4682 Py_INCREF(Py_None);
4683 }
4684 #else
4685 if (PyErr_Occurred()) {
4686 Py_XDECREF(coro->coro->result);
4687 PyErr_Fetch(&type, &coro->coro->result, &traceback);
4688 Py_DECREF(type);
4689 Py_XDECREF(traceback);
4690 } else {
4691 if (coro->coro->result == NULL) {
4692 coro->coro->result = Py_None;
4693 Py_INCREF(Py_None);
4694 }
4695 }
4696
4697 result->obj = coro->coro->result;
4698 Py_INCREF(result->obj);
4699 #endif
4700
4701 TAILQ_INSERT_TAIL(&op->results, result, list);
4702
4703 TAILQ_REMOVE(&op->coroutines, coro, list);
4704 kore_pool_put(&gather_coro_pool, coro);
4705
4706 kore_python_coro_delete(reap);
4707 }
4708
4709 static void
4710 pygather_op_dealloc(struct pygather_op *op)
4711 {
4712 struct python_coro *old;
4713 struct pygather_coro *coro, *next;
4714 struct pygather_result *res, *rnext;
4715
4716 /*
4717 * Since we are calling kore_python_coro_delete() on all the
4718 * remaining coroutines in this gather op we must remember the
4719 * original coroutine that is running as the removal will end
4720 * up setting coro_running to NULL.
4721 */
4722 old = coro_running;
4723
4724 for (coro = TAILQ_FIRST(&op->coroutines); coro != NULL; coro = next) {
4725 next = TAILQ_NEXT(coro, list);
4726 TAILQ_REMOVE(&op->coroutines, coro, list);
4727
4728 /* Make sure we don't end up in pygather_reap_coro(). */
4729 coro->coro->gatherop = NULL;
4730
4731 kore_python_coro_delete(coro->coro);
4732 kore_pool_put(&gather_coro_pool, coro);
4733 }
4734
4735 coro_running = old;
4736
4737 for (res = TAILQ_FIRST(&op->results); res != NULL; res = rnext) {
4738 rnext = TAILQ_NEXT(res, list);
4739 TAILQ_REMOVE(&op->results, res, list);
4740
4741 Py_DECREF(res->obj);
4742 kore_pool_put(&gather_result_pool, res);
4743 }
4744
4745 PyObject_Del((PyObject *)op);
4746 }
4747
4748 static PyObject *
4749 pygather_op_await(PyObject *obj)
4750 {
4751 Py_INCREF(obj);
4752 return (obj);
4753 }
4754
4755 static PyObject *
4756 pygather_op_iternext(struct pygather_op *op)
4757 {
4758 int idx;
4759 struct pygather_coro *coro;
4760 struct pygather_result *res, *next;
4761 PyObject *list, *obj;
4762
4763 if (!TAILQ_EMPTY(&op->coroutines)) {
4764 if (op->running > 0)
4765 Py_RETURN_NONE;
4766
4767 TAILQ_FOREACH(coro, &op->coroutines, list) {
4768 if (op->running >= op->concurrency)
4769 break;
4770 python_coro_wakeup(coro->coro);
4771 op->running++;
4772 }
4773
4774 Py_RETURN_NONE;
4775 }
4776
4777 if ((list = PyList_New(op->count)) == NULL)
4778 return (NULL);
4779
4780 idx = 0;
4781
4782 for (res = TAILQ_FIRST(&op->results); res != NULL; res = next) {
4783 next = TAILQ_NEXT(res, list);
4784 TAILQ_REMOVE(&op->results, res, list);
4785
4786 obj = res->obj;
4787 res->obj = NULL;
4788 kore_pool_put(&gather_result_pool, res);
4789
4790 if (PyList_SetItem(list, idx++, obj) != 0) {
4791 Py_DECREF(list);
4792 return (NULL);
4793 }
4794 }
4795
4796 PyErr_SetObject(PyExc_StopIteration, list);
4797 Py_DECREF(list);
4798
4799 return (NULL);
4800 }
4801
4802 static PyObject *
4803 pyhttp_request_alloc(const struct http_request *req)
4804 {
4805 union { const void *cp; void *p; } ptr;
4806 struct pyhttp_request *pyreq;
4807
4808 pyreq = PyObject_New(struct pyhttp_request, &pyhttp_request_type);
4809 if (pyreq == NULL)
4810 return (NULL);
4811
4812 /*
4813 * Hack around all http apis taking a non-const pointer and us having
4814 * a const pointer for the req data structure. This is because we
4815 * could potentially be called from a validator where the argument
4816 * is a http_request pointer.
4817 */
4818 ptr.cp = req;
4819 pyreq->req = ptr.p;
4820 pyreq->data = NULL;
4821 pyreq->dict = NULL;
4822
4823 return ((PyObject *)pyreq);
4824 }
4825
4826 static PyObject *
4827 pyhttp_file_alloc(struct http_file *file)
4828 {
4829 struct pyhttp_file *pyfile;
4830
4831 pyfile = PyObject_New(struct pyhttp_file, &pyhttp_file_type);
4832 if (pyfile == NULL)
4833 return (NULL);
4834
4835 pyfile->file = file;
4836
4837 return ((PyObject *)pyfile);
4838 }
4839
4840 static int
4841 pyhttp_preprocess(struct http_request *req)
4842 {
4843 struct reqcall *rq;
4844 PyObject *ret;
4845
4846 rq = req->py_rqnext;
4847
4848 while (rq) {
4849 req->py_rqnext = TAILQ_NEXT(rq, list);
4850
4851 PyErr_Clear();
4852 ret = PyObject_CallFunctionObjArgs(rq->f, req->py_req, NULL);
4853
4854 if (ret == NULL) {
4855 kore_python_log_error("preprocess");
4856 http_response(req, HTTP_STATUS_INTERNAL_ERROR, NULL, 0);
4857 return (KORE_RESULT_ERROR);
4858 }
4859
4860 if (ret == Py_False) {
4861 Py_DECREF(ret);
4862 return (KORE_RESULT_ERROR);
4863 }
4864
4865 if (PyCoro_CheckExact(ret)) {
4866 req->py_coro = python_coro_create(ret, req);
4867 if (python_coro_run(req->py_coro) == KORE_RESULT_OK) {
4868 http_request_wakeup(req);
4869 kore_python_coro_delete(req->py_coro);
4870 req->py_coro = NULL;
4871 rq = req->py_rqnext;
4872 continue;
4873 }
4874 return (KORE_RESULT_RETRY);
4875 }
4876
4877 Py_DECREF(ret);
4878 rq = req->py_rqnext;
4879 }
4880
4881 return (KORE_RESULT_OK);
4882 }
4883
4884 static PyObject *
4885 pyhttp_response(struct pyhttp_request *pyreq, PyObject *args)
4886 {
4887 struct connection *c;
4888 char *ptr;
4889 Py_ssize_t length;
4890 int status;
4891 struct pyhttp_iterobj *iterobj;
4892 PyObject *obj, *iterator;
4893
4894 length = -1;
4895
4896 if (!PyArg_ParseTuple(args, "iO", &status, &obj))
4897 return (NULL);
4898
4899 if (PyBytes_CheckExact(obj)) {
4900 if (PyBytes_AsStringAndSize(obj, &ptr, &length) == -1)
4901 return (NULL);
4902
4903 if (length < 0) {
4904 PyErr_SetString(PyExc_TypeError, "invalid length");
4905 return (NULL);
4906 }
4907
4908 Py_INCREF(obj);
4909
4910 http_response_stream(pyreq->req, status, ptr, length,
4911 pyhttp_response_sent, obj);
4912 } else if (obj == Py_None) {
4913 http_response(pyreq->req, status, NULL, 0);
4914 } else {
4915 c = pyreq->req->owner;
4916 if (c->state == CONN_STATE_DISCONNECTING) {
4917 Py_RETURN_FALSE;
4918 }
4919
4920 if ((iterator = PyObject_GetIter(obj)) == NULL)
4921 return (NULL);
4922
4923 iterobj = kore_pool_get(&iterobj_pool);
4924 iterobj->iterator = iterator;
4925 iterobj->connection = c;
4926 iterobj->remove = 0;
4927
4928 kore_buf_init(&iterobj->buf, 4096);
4929
4930 c->hdlr_extra = iterobj;
4931 c->flags |= CONN_IS_BUSY;
4932 c->disconnect = pyhttp_iterobj_disconnect;
4933
4934 pyreq->req->flags |= HTTP_REQUEST_NO_CONTENT_LENGTH;
4935 http_response_header(pyreq->req, "transfer-encoding",
4936 "chunked");
4937
4938 http_response(pyreq->req, status, NULL, 0);
4939 pyhttp_iterobj_next(iterobj);
4940 }
4941
4942 Py_RETURN_TRUE;
4943 }
4944
4945 static int
4946 pyhttp_response_sent(struct netbuf *nb)
4947 {
4948 PyObject *data;
4949
4950 data = nb->extra;
4951 Py_DECREF(data);
4952
4953 return (KORE_RESULT_OK);
4954 }
4955
4956 static int
4957 pyhttp_iterobj_next(struct pyhttp_iterobj *iterobj)
4958 {
4959 struct netbuf *nb;
4960 PyObject *obj;
4961 const char *ptr;
4962 Py_ssize_t length;
4963
4964 PyErr_Clear();
4965
4966 if ((obj = PyIter_Next(iterobj->iterator)) == NULL) {
4967 if (PyErr_Occurred()) {
4968 kore_python_log_error("pyhttp_iterobj_next");
4969 return (KORE_RESULT_ERROR);
4970 }
4971
4972 return (KORE_RESULT_OK);
4973 }
4974
4975 if ((ptr = PyUnicode_AsUTF8AndSize(obj, &length)) == NULL) {
4976 kore_python_log_error("pyhttp_iterobj_next");
4977 return (KORE_RESULT_ERROR);
4978 }
4979
4980 kore_buf_reset(&iterobj->buf);
4981 kore_buf_appendf(&iterobj->buf, "%lx\r\n", length);
4982 kore_buf_append(&iterobj->buf, ptr, length);
4983 kore_buf_appendf(&iterobj->buf, "\r\n");
4984
4985 Py_DECREF(obj);
4986
4987 net_send_stream(iterobj->connection, iterobj->buf.data,
4988 iterobj->buf.offset, pyhttp_iterobj_chunk_sent, &nb);
4989
4990 nb->extra = iterobj;
4991
4992 return (KORE_RESULT_RETRY);
4993 }
4994
4995 static int
4996 pyhttp_iterobj_chunk_sent(struct netbuf *nb)
4997 {
4998 int ret;
4999 struct pyhttp_iterobj *iterobj;
5000
5001 iterobj = nb->extra;
5002
5003 if (iterobj->remove) {
5004 ret = KORE_RESULT_ERROR;
5005 } else {
5006 ret = pyhttp_iterobj_next(iterobj);
5007 }
5008
5009 if (ret != KORE_RESULT_RETRY) {
5010 iterobj->connection->hdlr_extra = NULL;
5011 iterobj->connection->disconnect = NULL;
5012 iterobj->connection->flags &= ~CONN_IS_BUSY;
5013
5014 if (iterobj->remove == 0)
5015 http_start_recv(iterobj->connection);
5016
5017 kore_buf_reset(&iterobj->buf);
5018 kore_buf_appendf(&iterobj->buf, "0\r\n\r\n");
5019 net_send_queue(iterobj->connection,
5020 iterobj->buf.data, iterobj->buf.offset);
5021
5022 Py_DECREF(iterobj->iterator);
5023
5024 kore_buf_cleanup(&iterobj->buf);
5025 kore_pool_put(&iterobj_pool, iterobj);
5026 } else {
5027 ret = KORE_RESULT_OK;
5028 }
5029
5030 return (ret);
5031 }
5032
5033 static void
5034 pyhttp_iterobj_disconnect(struct connection *c)
5035 {
5036 struct pyhttp_iterobj *iterobj;
5037
5038 iterobj = c->hdlr_extra;
5039 iterobj->remove = 1;
5040 c->hdlr_extra = NULL;
5041 }
5042
5043 static PyObject *
5044 pyhttp_response_header(struct pyhttp_request *pyreq, PyObject *args)
5045 {
5046 const char *header, *value;
5047
5048 if (!PyArg_ParseTuple(args, "ss", &header, &value))
5049 return (NULL);
5050
5051 http_response_header(pyreq->req, header, value);
5052
5053 Py_RETURN_TRUE;
5054 }
5055
5056 static PyObject *
5057 pyhttp_request_header(struct pyhttp_request *pyreq, PyObject *args)
5058 {
5059 const char *value;
5060 const char *header;
5061 PyObject *result;
5062
5063 if (!PyArg_ParseTuple(args, "s", &header))
5064 return (NULL);
5065
5066 if (!http_request_header(pyreq->req, header, &value)) {
5067 Py_RETURN_NONE;
5068 }
5069
5070 if ((result = PyUnicode_FromString(value)) == NULL)
5071 return (PyErr_NoMemory());
5072
5073 return (result);
5074 }
5075
5076 static PyObject *
5077 pyhttp_body_read(struct pyhttp_request *pyreq, PyObject *args)
5078 {
5079 ssize_t ret;
5080 size_t len;
5081 Py_ssize_t pylen;
5082 PyObject *result;
5083 u_int8_t buf[1024];
5084
5085 if (!PyArg_ParseTuple(args, "n", &pylen) || pylen < 0)
5086 return (NULL);
5087
5088 len = (size_t)pylen;
5089 if (len > sizeof(buf)) {
5090 PyErr_SetString(PyExc_RuntimeError, "len > sizeof(buf)");
5091 return (NULL);
5092 }
5093
5094 ret = http_body_read(pyreq->req, buf, len);
5095 if (ret == -1) {
5096 PyErr_SetString(PyExc_RuntimeError, "http_body_read() failed");
5097 return (NULL);
5098 }
5099
5100 result = Py_BuildValue("ny#", ret, buf, ret);
5101 if (result == NULL)
5102 return (PyErr_NoMemory());
5103
5104 return (result);
5105 }
5106
5107 static PyObject *
5108 pyhttp_populate_get(struct pyhttp_request *pyreq, PyObject *args)
5109 {
5110 http_populate_get(pyreq->req);
5111 Py_RETURN_TRUE;
5112 }
5113
5114 static PyObject *
5115 pyhttp_populate_post(struct pyhttp_request *pyreq, PyObject *args)
5116 {
5117 http_populate_post(pyreq->req);
5118 Py_RETURN_TRUE;
5119 }
5120
5121 static PyObject *
5122 pyhttp_populate_multi(struct pyhttp_request *pyreq, PyObject *args)
5123 {
5124 http_populate_multipart_form(pyreq->req);
5125 Py_RETURN_TRUE;
5126 }
5127
5128 static PyObject *
5129 pyhttp_populate_cookies(struct pyhttp_request *pyreq, PyObject *args)
5130 {
5131 http_populate_cookies(pyreq->req);
5132 Py_RETURN_TRUE;
5133 }
5134
5135 static PyObject *
5136 pyhttp_argument(struct pyhttp_request *pyreq, PyObject *args)
5137 {
5138 char *arg;
5139 const char *name;
5140 PyObject *value;
5141
5142 if (!PyArg_ParseTuple(args, "s", &name))
5143 return (NULL);
5144
5145 if (!http_argument_get_string(pyreq->req, name, &arg)) {
5146 Py_RETURN_NONE;
5147 }
5148
5149 if ((value = PyUnicode_FromString(arg)) == NULL)
5150 return (PyErr_NoMemory());
5151
5152 return (value);
5153 }
5154
5155 static PyObject *
5156 pyhttp_cookie(struct pyhttp_request *pyreq, PyObject *args)
5157 {
5158 char *arg;
5159 const char *name;
5160 PyObject *value;
5161
5162 if (!PyArg_ParseTuple(args, "s", &name))
5163 return (NULL);
5164
5165 if (!http_request_cookie(pyreq->req, name, &arg)) {
5166 Py_RETURN_NONE;
5167 }
5168
5169 if ((value = PyUnicode_FromString(arg)) == NULL)
5170 return (NULL);
5171
5172 return (value);
5173 }
5174
5175 static PyObject *
5176 pyhttp_headers(struct pyhttp_request *pyreq, PyObject *args)
5177 {
5178 struct http_header *hdr;
5179 struct http_request *req;
5180 PyObject *obj, *dict, *ret;
5181
5182 ret = NULL;
5183 obj = NULL;
5184 dict = NULL;
5185
5186 req = pyreq->req;
5187
5188 if ((dict = PyDict_New()) == NULL)
5189 goto cleanup;
5190
5191 if ((obj = PyUnicode_FromString(req->host)) == NULL)
5192 goto cleanup;
5193
5194 if (PyDict_SetItemString(dict, "host", obj) == -1)
5195 goto cleanup;
5196
5197 TAILQ_FOREACH(hdr, &req->req_headers, list) {
5198 if ((obj = PyUnicode_FromString(hdr->value)) == NULL)
5199 goto cleanup;
5200 if (PyDict_SetItemString(dict, hdr->header, obj) == -1)
5201 goto cleanup;
5202 }
5203
5204 ret = dict;
5205 obj = NULL;
5206 dict = NULL;
5207
5208 cleanup:
5209 Py_XDECREF(obj);
5210 Py_XDECREF(dict);
5211
5212 return (ret);
5213 }
5214
5215 static PyObject *
5216 pyhttp_file_lookup(struct pyhttp_request *pyreq, PyObject *args)
5217 {
5218 const char *name;
5219 struct http_file *file;
5220 PyObject *pyfile;
5221
5222 if (!PyArg_ParseTuple(args, "s", &name))
5223 return (NULL);
5224
5225 if ((file = http_file_lookup(pyreq->req, name)) == NULL) {
5226 Py_RETURN_NONE;
5227 }
5228
5229 if ((pyfile = pyhttp_file_alloc(file)) == NULL)
5230 return (PyErr_NoMemory());
5231
5232 return (pyfile);
5233 }
5234
5235 static PyObject *
5236 pyhttp_file_read(struct pyhttp_file *pyfile, PyObject *args)
5237 {
5238 ssize_t ret;
5239 size_t len;
5240 Py_ssize_t pylen;
5241 PyObject *result;
5242 u_int8_t buf[1024];
5243
5244 if (!PyArg_ParseTuple(args, "n", &pylen) || pylen < 0)
5245 return (NULL);
5246
5247 len = (size_t)pylen;
5248 if (len > sizeof(buf)) {
5249 PyErr_SetString(PyExc_RuntimeError, "len > sizeof(buf)");
5250 return (NULL);
5251 }
5252
5253 ret = http_file_read(pyfile->file, buf, len);
5254 if (ret == -1) {
5255 PyErr_SetString(PyExc_RuntimeError, "http_file_read() failed");
5256 return (NULL);
5257 }
5258
5259 result = Py_BuildValue("ny#", ret, buf, ret);
5260 if (result == NULL)
5261 return (PyErr_NoMemory());
5262
5263 return (result);
5264 }
5265
5266 static PyObject *
5267 pyhttp_websocket_handshake(struct pyhttp_request *pyreq, PyObject *args)
5268 {
5269 struct connection *c;
5270 PyObject *onconnect, *onmsg, *ondisconnect;
5271
5272 if (!PyArg_ParseTuple(args, "OOO", &onconnect, &onmsg, &ondisconnect))
5273 return (NULL);
5274
5275 kore_websocket_handshake(pyreq->req, NULL, NULL, NULL);
5276
5277 c = pyreq->req->owner;
5278
5279 Py_INCREF(onconnect);
5280 Py_INCREF(onmsg);
5281 Py_INCREF(ondisconnect);
5282
5283 c->ws_connect = kore_calloc(1, sizeof(struct kore_runtime_call));
5284 c->ws_connect->addr = onconnect;
5285 c->ws_connect->runtime = &kore_python_runtime;
5286
5287 c->ws_message = kore_calloc(1, sizeof(struct kore_runtime_call));
5288 c->ws_message->addr = onmsg;
5289 c->ws_message->runtime = &kore_python_runtime;
5290
5291 c->ws_disconnect = kore_calloc(1, sizeof(struct kore_runtime_call));
5292 c->ws_disconnect->addr = ondisconnect;
5293 c->ws_disconnect->runtime = &kore_python_runtime;
5294
5295 python_runtime_connect(onconnect, c);
5296
5297 Py_RETURN_TRUE;
5298 }
5299
5300 static PyObject *
5301 pyconnection_websocket_send(struct pyconnection *pyc, PyObject *args)
5302 {
5303 int op;
5304 ssize_t len;
5305 const char *data;
5306
5307 if (pyc->c->proto != CONN_PROTO_WEBSOCKET) {
5308 PyErr_SetString(PyExc_TypeError, "not a websocket connection");
5309 return (NULL);
5310 }
5311
5312 len = -1;
5313
5314 if (!PyArg_ParseTuple(args, "iy#", &op, &data, &len))
5315 return (NULL);
5316
5317 if (len < 0) {
5318 PyErr_SetString(PyExc_TypeError, "invalid length");
5319 return (NULL);
5320 }
5321
5322 switch (op) {
5323 case WEBSOCKET_OP_TEXT:
5324 case WEBSOCKET_OP_BINARY:
5325 break;
5326 default:
5327 PyErr_SetString(PyExc_TypeError, "invalid op parameter");
5328 return (NULL);
5329 }
5330
5331 kore_websocket_send(pyc->c, op, data, len);
5332
5333 Py_RETURN_TRUE;
5334 }
5335
5336 static PyObject *
5337 python_websocket_broadcast(PyObject *self, PyObject *args)
5338 {
5339 struct connection *c;
5340 ssize_t len;
5341 struct pyconnection *pyc;
5342 const char *data;
5343 PyObject *pysrc;
5344 int op, broadcast;
5345
5346 len = -1;
5347
5348 if (!PyArg_ParseTuple(args, "Oiy#i", &pysrc, &op, &data, &len,
5349 &broadcast))
5350 return (NULL);
5351
5352 if (len < 0) {
5353 PyErr_SetString(PyExc_TypeError, "invalid length");
5354 return (NULL);
5355 }
5356
5357 switch (op) {
5358 case WEBSOCKET_OP_TEXT:
5359 case WEBSOCKET_OP_BINARY:
5360 break;
5361 default:
5362 PyErr_SetString(PyExc_TypeError, "invalid op parameter");
5363 return (NULL);
5364 }
5365
5366 if (pysrc == Py_None) {
5367 c = NULL;
5368 } else {
5369 if (!PyObject_TypeCheck(pysrc, &pyconnection_type))
5370 return (NULL);
5371 pyc = (struct pyconnection *)pysrc;
5372 c = pyc->c;
5373 }
5374
5375 kore_websocket_broadcast(c, op, data, len, broadcast);
5376
5377 Py_RETURN_TRUE;
5378 }
5379
5380 static PyObject *
5381 pyhttp_get_host(struct pyhttp_request *pyreq, void *closure)
5382 {
5383 PyObject *host;
5384
5385 if ((host = PyUnicode_FromString(pyreq->req->host)) == NULL)
5386 return (PyErr_NoMemory());
5387
5388 return (host);
5389 }
5390
5391 static PyObject *
5392 pyhttp_get_path(struct pyhttp_request *pyreq, void *closure)
5393 {
5394 PyObject *path;
5395
5396 if ((path = PyUnicode_FromString(pyreq->req->path)) == NULL)
5397 return (PyErr_NoMemory());
5398
5399 return (path);
5400 }
5401
5402 static PyObject *
5403 pyhttp_get_body(struct pyhttp_request *pyreq, void *closure)
5404 {
5405 ssize_t ret;
5406 struct kore_buf buf;
5407 PyObject *body;
5408 u_int8_t data[BUFSIZ];
5409
5410 kore_buf_init(&buf, 1024);
5411 if (!http_body_rewind(pyreq->req)) {
5412 PyErr_SetString(PyExc_RuntimeError,
5413 "http_body_rewind() failed");
5414 return (NULL);
5415 }
5416
5417 for (;;) {
5418 ret = http_body_read(pyreq->req, data, sizeof(data));
5419 if (ret == -1) {
5420 kore_buf_cleanup(&buf);
5421 PyErr_SetString(PyExc_RuntimeError,
5422 "http_body_read() failed");
5423 return (NULL);
5424 }
5425
5426 if (ret == 0)
5427 break;
5428
5429 kore_buf_append(&buf, data, (size_t)ret);
5430 }
5431
5432 body = PyBytes_FromStringAndSize((char *)buf.data, buf.offset);
5433 kore_buf_free(&buf);
5434
5435 if (body == NULL)
5436 return (PyErr_NoMemory());
5437
5438 return (body);
5439 }
5440
5441 static PyObject *
5442 pyhttp_get_agent(struct pyhttp_request *pyreq, void *closure)
5443 {
5444 return (PyUnicode_FromString(pyreq->req->path));
5445 }
5446
5447 static PyObject *
5448 pyhttp_get_method(struct pyhttp_request *pyreq, void *closure)
5449 {
5450 return (PyLong_FromUnsignedLong(pyreq->req->method));
5451 }
5452
5453 static PyObject *
5454 pyhttp_get_protocol(struct pyhttp_request *pyreq, void *closure)
5455 {
5456 struct connection *c;
5457 const char *proto;
5458
5459 c = pyreq->req->owner;
5460
5461 if (c->owner->server->tls)
5462 proto = "https";
5463 else
5464 proto = "http";
5465
5466 return (PyUnicode_FromString(proto));
5467 }
5468
5469 static PyObject *
5470 pyhttp_get_body_path(struct pyhttp_request *pyreq, void *closure)
5471 {
5472 if (pyreq->req->http_body_path == NULL) {
5473 Py_RETURN_NONE;
5474 }
5475
5476 return (PyUnicode_FromString(pyreq->req->http_body_path));
5477 }
5478
5479 static PyObject *
5480 pyhttp_get_body_digest(struct pyhttp_request *pyreq, void *closure)
5481 {
5482 PyObject *digest;
5483
5484 digest = PyBytes_FromStringAndSize((char *)pyreq->req->http_body_digest,
5485 sizeof(pyreq->req->http_body_digest));
5486
5487 return (digest);
5488 }
5489
5490 static PyObject *
5491 pyhttp_get_connection(struct pyhttp_request *pyreq, void *closure)
5492 {
5493 PyObject *pyc;
5494
5495 if (pyreq->req->owner == NULL) {
5496 Py_RETURN_NONE;
5497 }
5498
5499 if ((pyc = pyconnection_alloc(pyreq->req->owner)) == NULL)
5500 return (PyErr_NoMemory());
5501
5502 return (pyc);
5503 }
5504
5505 static PyObject *
5506 pyhttp_file_get_name(struct pyhttp_file *pyfile, void *closure)
5507 {
5508 PyObject *name;
5509
5510 if ((name = PyUnicode_FromString(pyfile->file->name)) == NULL)
5511 return (PyErr_NoMemory());
5512
5513 return (name);
5514 }
5515
5516 static PyObject *
5517 pyhttp_file_get_filename(struct pyhttp_file *pyfile, void *closure)
5518 {
5519 PyObject *name;
5520
5521 if ((name = PyUnicode_FromString(pyfile->file->filename)) == NULL)
5522 return (PyErr_NoMemory());
5523
5524 return (name);
5525 }
5526
5527 void
5528 pyroute_dealloc(struct pyroute *route)
5529 {
5530 kore_free(route->path);
5531
5532 Py_XDECREF(route->func);
5533 Py_XDECREF(route->kwargs);
5534
5535 PyObject_Del((PyObject *)route);
5536 }
5537
5538 static PyObject *
5539 pyroute_inner(struct pyroute *route, PyObject *args)
5540 {
5541 PyObject *obj;
5542
5543 if (!PyArg_ParseTuple(args, "O", &obj))
5544 return (NULL);
5545
5546 if (!PyCallable_Check(obj))
5547 return (NULL);
5548
5549 route->func = obj;
5550 Py_INCREF(route->func);
5551
5552 TAILQ_INSERT_TAIL(&routes, route, list);
5553
5554 return (route->func);
5555 }
5556
5557 void
5558 pydomain_dealloc(struct pydomain *domain)
5559 {
5560 PyObject_Del((PyObject *)domain);
5561 }
5562
5563 static int
5564 pydomain_set_accesslog(struct pydomain *domain, PyObject *arg, void *closure)
5565 {
5566 const char *path;
5567
5568 if (!PyUnicode_CheckExact(arg))
5569 return (-1);
5570
5571 if (domain->config->accesslog != -1) {
5572 PyErr_Format(PyExc_RuntimeError,
5573 "domain %s accesslog already set", domain->config->domain);
5574 return (-1);
5575 }
5576
5577 path = PyUnicode_AsUTF8(arg);
5578
5579 domain->config->accesslog = open(path,
5580 O_CREAT | O_APPEND | O_WRONLY,
5581 S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
5582
5583 if (domain->config->accesslog == -1) {
5584 PyErr_Format(PyExc_RuntimeError,
5585 "failed to open accesslog for %s (%s:%s)",
5586 domain->config->domain, path, errno_s);
5587 return (-1);
5588 }
5589
5590 return (0);
5591 }
5592
5593 static PyObject *
5594 pydomain_filemaps(struct pydomain *domain, PyObject *args)
5595 {
5596 Py_ssize_t idx;
5597 struct kore_route *rt;
5598 const char *url, *path;
5599 PyObject *dict, *key, *value, *auth;
5600
5601 if (!PyArg_ParseTuple(args, "O", &dict))
5602 return (NULL);
5603
5604 if (!PyDict_CheckExact(dict)) {
5605 PyErr_SetString(PyExc_RuntimeError, "filemaps not a dict");
5606 return (NULL);
5607 }
5608
5609 idx = 0;
5610 while (PyDict_Next(dict, &idx, &key, &value)) {
5611 if (!PyUnicode_CheckExact(key)) {
5612 PyErr_SetString(PyExc_RuntimeError,
5613 "filemap key not a string");
5614 return (NULL);
5615 }
5616
5617 url = PyUnicode_AsUTF8(key);
5618
5619 if (!PyUnicode_CheckExact(value) &&
5620 !PyTuple_CheckExact(value)) {
5621 PyErr_SetString(PyExc_RuntimeError,
5622 "filemap value can be either be a string or tuple");
5623 return (NULL);
5624 }
5625
5626 if (PyTuple_CheckExact(value)) {
5627 auth = PyTuple_GetItem(value, 1);
5628 if (!PyDict_CheckExact(auth)) {
5629 PyErr_SetString(PyExc_RuntimeError,
5630 "filemap value tuple auth is not a dict");
5631 return (NULL);
5632 }
5633
5634 value = PyTuple_GetItem(value, 0);
5635 if (!PyUnicode_CheckExact(value)) {
5636 PyErr_SetString(PyExc_RuntimeError,
5637 "filemap value tuple path is invalid");
5638 return (NULL);
5639 }
5640 } else {
5641 auth = NULL;
5642 }
5643
5644 path = PyUnicode_AsUTF8(value);
5645
5646 rt = kore_filemap_create(domain->config, path, url, NULL);
5647 if (rt == NULL) {
5648 PyErr_Format(PyExc_RuntimeError,
5649 "failed to create filemap %s->%s for %s",
5650 url, path, domain->config->domain);
5651 return (NULL);
5652 }
5653
5654 if (auth != NULL) {
5655 if (!python_route_auth(auth, rt)) {
5656 kore_python_log_error("python_route_auth");
5657 kore_route_free(rt);
5658 return (KORE_RESULT_ERROR);
5659 }
5660 }
5661 }
5662
5663 Py_RETURN_NONE;
5664 }
5665
5666 static PyObject *
5667 pydomain_redirect(struct pydomain *domain, PyObject *args)
5668 {
5669 int status;
5670 const char *src, *dst;
5671
5672 if (!PyArg_ParseTuple(args, "sis", &src, &status, &dst))
5673 return (NULL);
5674
5675 if (!http_redirect_add(domain->config, src, status, dst)) {
5676 fatal("failed to add redirect '%s' on '%s'",
5677 src, domain->config->domain);
5678 }
5679
5680 Py_RETURN_NONE;
5681 }
5682
5683 static PyObject *
5684 pydomain_route(struct pydomain *domain, PyObject *args, PyObject *kwargs)
5685 {
5686 PyObject *obj;
5687 const char *path;
5688 struct pyroute *route;
5689
5690 if (!PyArg_ParseTuple(args, "sO", &path, &obj))
5691 return (NULL);
5692
5693 if (!PyCallable_Check(obj))
5694 return (NULL);
5695
5696 if ((route = PyObject_New(struct pyroute, &pyroute_type)) == NULL)
5697 return (NULL);
5698
5699 route->kwargs = kwargs;
5700 route->domain = domain->config;
5701 route->path = kore_strdup(path);
5702
5703 Py_XINCREF(route->kwargs);
5704
5705 route->func = obj;
5706 Py_INCREF(route->func);
5707
5708 TAILQ_INSERT_TAIL(&routes, route, list);
5709
5710 Py_RETURN_NONE;
5711 }
5712
5713 static int
5714 python_route_install(struct pyroute *route)
5715 {
5716 const char *val;
5717 struct kore_domain *domain;
5718 struct kore_route *rt, *entry;
5719 PyObject *kwargs, *repr, *obj;
5720
5721 if ((repr = PyObject_Repr(route->func)) == NULL) {
5722 kore_python_log_error("python_route_install");
5723 return (KORE_RESULT_ERROR);
5724 }
5725
5726 domain = python_route_domain_resolve(route);
5727
5728 rt = kore_calloc(1, sizeof(*rt));
5729 rt->dom = domain;
5730 rt->methods = HTTP_METHOD_ALL;
5731 rt->path = kore_strdup(route->path);
5732
5733 TAILQ_INIT(&rt->params);
5734
5735 val = PyUnicode_AsUTF8(repr);
5736 rt->func = kore_strdup(val);
5737
5738 kwargs = route->kwargs;
5739
5740 rt->rcall = kore_calloc(1, sizeof(struct kore_runtime_call));
5741 rt->rcall->addr = route->func;
5742 rt->rcall->runtime = &kore_python_runtime;
5743 Py_INCREF(rt->rcall->addr);
5744
5745 if (kwargs != NULL) {
5746 if ((obj = PyDict_GetItemString(kwargs, "methods")) != NULL) {
5747 if (!python_route_methods(obj, kwargs, rt)) {
5748 kore_python_log_error("python_route_install");
5749 kore_route_free(rt);
5750 return (KORE_RESULT_ERROR);
5751 }
5752 }
5753
5754 if ((obj = PyDict_GetItemString(kwargs, "auth")) != NULL) {
5755 if (!python_route_auth(obj, rt)) {
5756 kore_python_log_error("python_route_install");
5757 kore_route_free(rt);
5758 return (KORE_RESULT_ERROR);
5759 }
5760 }
5761
5762 if ((obj = PyDict_GetItemString(kwargs, "hooks")) != NULL) {
5763 if (!python_route_hooks(obj, rt)) {
5764 kore_python_log_error("python_route_install");
5765 kore_route_free(rt);
5766 return (KORE_RESULT_ERROR);
5767 }
5768 }
5769 }
5770
5771 if (rt->path[0] == '/') {
5772 rt->type = HANDLER_TYPE_STATIC;
5773 } else {
5774 rt->type = HANDLER_TYPE_DYNAMIC;
5775 if (regcomp(&rt->rctx, rt->path, REG_EXTENDED))
5776 fatal("failed to compile regex for '%s'", rt->path);
5777 }
5778
5779 TAILQ_FOREACH(entry, &domain->routes, list) {
5780 if (!strcmp(entry->path, rt->path) &&
5781 (entry->methods & rt->methods))
5782 fatal("duplicate route for '%s'", route->path);
5783 }
5784
5785 TAILQ_INSERT_TAIL(&domain->routes, rt, list);
5786
5787 return (KORE_RESULT_OK);
5788 }
5789
5790 static struct kore_domain *
5791 python_route_domain_resolve(struct pyroute *route)
5792 {
5793 struct kore_server *srv;
5794 const char *name;
5795 struct kore_domain *domain;
5796
5797 if (route->domain != NULL)
5798 return (route->domain);
5799
5800 if (route->kwargs != NULL)
5801 name = python_string_from_dict(route->kwargs, "domain");
5802 else
5803 name = NULL;
5804
5805 if (name != NULL) {
5806 domain = NULL;
5807 LIST_FOREACH(srv, &kore_servers, list) {
5808 TAILQ_FOREACH(domain, &srv->domains, list) {
5809 if (!strcmp(domain->domain, name))
5810 break;
5811 }
5812 }
5813
5814 if (domain == NULL)
5815 fatal("domain '%s' does not exist", name);
5816 } else {
5817 if ((domain = kore_domain_byid(1)) != NULL)
5818 fatal("ambiguous domain on route, please specify one");
5819 if ((domain = kore_domain_byid(0)) == NULL)
5820 fatal("no domains configured, please configure one");
5821 }
5822
5823 return (domain);
5824 }
5825
5826 static int
5827 python_route_methods(PyObject *obj, PyObject *kwargs, struct kore_route *rt)
5828 {
5829 const char *val;
5830 PyObject *item;
5831 int method;
5832 Py_ssize_t list_len, idx;
5833
5834 if (!PyList_CheckExact(obj)) {
5835 PyErr_SetString(PyExc_RuntimeError, "methods not a list");
5836 return (KORE_RESULT_ERROR);
5837 }
5838
5839 rt->methods = 0;
5840 list_len = PyList_Size(obj);
5841
5842 for (idx = 0; idx < list_len; idx++) {
5843 if ((item = PyList_GetItem(obj, idx)) == NULL)
5844 return (KORE_RESULT_ERROR);
5845
5846 if ((val = PyUnicode_AsUTF8(item)) == NULL)
5847 return (KORE_RESULT_ERROR);
5848
5849 if ((method = http_method_value(val)) == 0) {
5850 PyErr_Format(PyExc_RuntimeError,
5851 "unknown HTTP method: %s", val);
5852 return (KORE_RESULT_ERROR);
5853 }
5854
5855 rt->methods |= method;
5856 if (method == HTTP_METHOD_GET)
5857 rt->methods |= HTTP_METHOD_HEAD;
5858
5859 if (!python_route_params(kwargs, rt, val, method, 0))
5860 return (KORE_RESULT_ERROR);
5861
5862 if (!python_route_params(kwargs, rt, "qs", method, 1))
5863 return (KORE_RESULT_ERROR);
5864 }
5865
5866 return (KORE_RESULT_OK);
5867 }
5868
5869 static int
5870 python_route_params(PyObject *kwargs, struct kore_route *rt,
5871 const char *method, int type, int qs)
5872 {
5873 Py_ssize_t idx;
5874 const char *val;
5875 int vtype;
5876 struct kore_validator *vldr;
5877 struct kore_route_params *param;
5878 PyObject *obj, *key, *item;
5879
5880 if ((obj = PyDict_GetItemString(kwargs, method)) == NULL)
5881 return (KORE_RESULT_OK);
5882
5883 if (!PyDict_CheckExact(obj))
5884 return (KORE_RESULT_ERROR);
5885
5886 idx = 0;
5887 while (PyDict_Next(obj, &idx, &key, &item)) {
5888 if (!PyUnicode_CheckExact(key))
5889 return (KORE_RESULT_ERROR);
5890
5891 val = PyUnicode_AsUTF8(key);
5892
5893 if (PyUnicode_CheckExact(item)) {
5894 vtype = KORE_VALIDATOR_TYPE_REGEX;
5895 } else if (PyCallable_Check(item)) {
5896 vtype = KORE_VALIDATOR_TYPE_FUNCTION;
5897 } else {
5898 PyErr_Format(PyExc_RuntimeError,
5899 "validator '%s' must be regex or function", val);
5900 return (KORE_RESULT_ERROR);
5901 }
5902
5903 vldr = kore_calloc(1, sizeof(*vldr));
5904 vldr->type = vtype;
5905
5906 if (vtype == KORE_VALIDATOR_TYPE_REGEX) {
5907 val = PyUnicode_AsUTF8(item);
5908 if (regcomp(&(vldr->rctx),
5909 val, REG_EXTENDED | REG_NOSUB)) {
5910 PyErr_Format(PyExc_RuntimeError,
5911 "Invalid regex (%s)", val);
5912 kore_free(vldr);
5913 return (KORE_RESULT_ERROR);
5914 }
5915 } else {
5916 vldr->rcall = kore_calloc(1, sizeof(*vldr->rcall));
5917 vldr->rcall->addr = item;
5918 vldr->rcall->runtime = &kore_python_runtime;
5919 Py_INCREF(item);
5920 }
5921
5922 val = PyUnicode_AsUTF8(key);
5923 vldr->name = kore_strdup(val);
5924
5925 param = kore_calloc(1, sizeof(*param));
5926 param->flags = 0;
5927 param->method = type;
5928 param->validator = vldr;
5929 param->name = kore_strdup(val);
5930
5931 if (type == HTTP_METHOD_GET || qs == 1)
5932 param->flags = KORE_PARAMS_QUERY_STRING;
5933
5934 TAILQ_INSERT_TAIL(&rt->params, param, list);
5935 }
5936
5937 return (KORE_RESULT_OK);
5938 }
5939
5940 static int
5941 python_route_auth(PyObject *dict, struct kore_route *rt)
5942 {
5943 int type;
5944 struct kore_auth *auth;
5945 struct kore_validator *vldr;
5946 PyObject *obj, *repr;
5947 const char *value, *redir;
5948
5949 if (!PyDict_CheckExact(dict))
5950 return (KORE_RESULT_ERROR);
5951
5952 if ((value = python_string_from_dict(dict, "type")) == NULL) {
5953 PyErr_SetString(PyExc_RuntimeError,
5954 "missing or invalid 'type' keyword");
5955 return (KORE_RESULT_ERROR);
5956 }
5957
5958 if (!strcmp(value, "cookie")) {
5959 type = KORE_AUTH_TYPE_COOKIE;
5960 } else if (!strcmp(value, "header")) {
5961 type = KORE_AUTH_TYPE_HEADER;
5962 } else {
5963 PyErr_Format(PyExc_RuntimeError,
5964 "invalid 'type' (%s) in auth dictionary for '%s'",
5965 value, rt->path);
5966 return (KORE_RESULT_ERROR);
5967 }
5968
5969 if ((value = python_string_from_dict(dict, "value")) == NULL) {
5970 PyErr_SetString(PyExc_RuntimeError,
5971 "missing or invalid 'value' keyword");
5972 return (KORE_RESULT_ERROR);
5973 }
5974
5975 redir = python_string_from_dict(dict, "redirect");
5976
5977 if ((obj = PyDict_GetItemString(dict, "verify")) == NULL ||
5978 !PyCallable_Check(obj)) {
5979 PyErr_Format(PyExc_RuntimeError,
5980 "missing 'verify' in auth dictionary for '%s'", rt->path);
5981 return (KORE_RESULT_ERROR);
5982 }
5983
5984 auth = kore_calloc(1, sizeof(*auth));
5985 auth->type = type;
5986 auth->value = kore_strdup(value);
5987
5988 if (redir != NULL)
5989 auth->redirect = kore_strdup(redir);
5990
5991 vldr = kore_calloc(1, sizeof(*vldr));
5992 vldr->type = KORE_VALIDATOR_TYPE_FUNCTION;
5993
5994 vldr->rcall = kore_calloc(1, sizeof(*vldr->rcall));
5995 vldr->rcall->addr = obj;
5996 vldr->rcall->runtime = &kore_python_runtime;
5997 Py_INCREF(obj);
5998
5999 if ((repr = PyObject_Repr(obj)) == NULL) {
6000 kore_free(vldr->rcall);
6001 kore_free(vldr);
6002 kore_free(auth);
6003 return (KORE_RESULT_ERROR);
6004 }
6005
6006 value = PyUnicode_AsUTF8(repr);
6007 vldr->name = kore_strdup(value);
6008 Py_DECREF(repr);
6009
6010 auth->validator = vldr;
6011 rt->auth = auth;
6012
6013 return (KORE_RESULT_OK);
6014 }
6015
6016 static int
6017 python_route_hooks(PyObject *dict, struct kore_route *rt)
6018 {
6019 if (!PyDict_CheckExact(dict))
6020 return (KORE_RESULT_ERROR);
6021
6022 if (!python_route_hook_set(dict, "on_free", &rt->on_free))
6023 return (KORE_RESULT_ERROR);
6024
6025 if (!python_route_hook_set(dict, "on_headers", &rt->on_headers))
6026 return (KORE_RESULT_ERROR);
6027
6028 if (!python_route_hook_set(dict, "on_body_chunk", &rt->on_body_chunk))
6029 return (KORE_RESULT_ERROR);
6030
6031 return (KORE_RESULT_OK);
6032 }
6033
6034 static int
6035 python_route_hook_set(PyObject *dict, const char *name,
6036 struct kore_runtime_call **out)
6037 {
6038 PyObject *obj;
6039 struct kore_runtime_call *rcall;
6040
6041 if ((obj = PyDict_GetItemString(dict, name)) == NULL)
6042 return (KORE_RESULT_OK);
6043
6044 if (!PyCallable_Check(obj)) {
6045 PyErr_Format(PyExc_RuntimeError,
6046 "%s for a route not callable", name);
6047 Py_DECREF(obj);
6048 return (KORE_RESULT_ERROR);
6049 }
6050
6051 rcall = kore_calloc(1, sizeof(struct kore_runtime_call));
6052 rcall->addr = obj;
6053 rcall->runtime = &kore_python_runtime;
6054
6055 Py_INCREF(rcall->addr);
6056 *out = rcall;
6057
6058 return (KORE_RESULT_OK);
6059 }
6060
6061 #if defined(KORE_USE_PGSQL)
6062 static PyObject *
6063 python_kore_pgsql_query(PyObject *self, PyObject *args, PyObject *kwargs)
6064 {
6065 struct pykore_pgsql *op;
6066 PyObject *obj;
6067 const char *db, *query;
6068
6069 if (!PyArg_ParseTuple(args, "ss", &db, &query))
6070 return (NULL);
6071
6072 op = PyObject_New(struct pykore_pgsql, &pykore_pgsql_type);
6073 if (op == NULL)
6074 return (NULL);
6075
6076 op->binary = 0;
6077 op->param.count = 0;
6078 op->param.objs = NULL;
6079 op->param.values = NULL;
6080 op->param.lengths = NULL;
6081 op->param.formats = NULL;
6082
6083 op->result = NULL;
6084 op->coro = coro_running;
6085 op->db = kore_strdup(db);
6086 op->query = kore_strdup(query);
6087 op->state = PYKORE_PGSQL_PREINIT;
6088
6089 memset(&op->sql, 0, sizeof(op->sql));
6090
6091 if (kwargs != NULL) {
6092 if ((obj = PyDict_GetItemString(kwargs, "params")) != NULL) {
6093 if (!pykore_pgsql_params(op, obj)) {
6094 Py_DECREF((PyObject *)op);
6095 return (NULL);
6096 }
6097 }
6098
6099 if ((obj = PyDict_GetItemString(kwargs, "binary")) != NULL) {
6100 if (obj == Py_True) {
6101 op->binary = 1;
6102 } else if (obj == Py_False) {
6103 op->binary = 0;
6104 } else {
6105 Py_DECREF((PyObject *)op);
6106 PyErr_SetString(PyExc_RuntimeError,
6107 "pgsql: binary not True or False");
6108 return (NULL);
6109 }
6110 }
6111 }
6112
6113 return ((PyObject *)op);
6114 }
6115
6116 static int
6117 pykore_pgsql_params(struct pykore_pgsql *op, PyObject *list)
6118 {
6119 union { const char *cp; char *p; } ptr;
6120 PyObject *item;
6121 int format;
6122 Py_ssize_t i, len, vlen;
6123
6124 if (!PyList_CheckExact(list)) {
6125 if (list == Py_None)
6126 return (KORE_RESULT_OK);
6127
6128 PyErr_SetString(PyExc_RuntimeError,
6129 "pgsql: params keyword must be a list");
6130 return (KORE_RESULT_ERROR);
6131 }
6132
6133 len = PyList_Size(list);
6134 if (len == 0)
6135 return (KORE_RESULT_OK);
6136
6137 if (len > INT_MAX) {
6138 PyErr_SetString(PyExc_RuntimeError,
6139 "pgsql: list length too large");
6140 return (KORE_RESULT_ERROR);
6141 }
6142
6143 op->param.count = len;
6144 op->param.lengths = kore_calloc(len, sizeof(int));
6145 op->param.formats = kore_calloc(len, sizeof(int));
6146 op->param.values = kore_calloc(len, sizeof(char *));
6147 op->param.objs = kore_calloc(len, sizeof(PyObject *));
6148
6149 for (i = 0; i < len; i++) {
6150 if ((item = PyList_GetItem(list, i)) == NULL)
6151 return (KORE_RESULT_ERROR);
6152
6153 if (PyUnicode_CheckExact(item)) {
6154 format = 0;
6155 ptr.cp = PyUnicode_AsUTF8AndSize(item, &vlen);
6156 } else if (PyBytes_CheckExact(item)) {
6157 format = 1;
6158 if (PyBytes_AsStringAndSize(item, &ptr.p, &vlen) == -1)
6159 ptr.p = NULL;
6160 } else {
6161 PyErr_Format(PyExc_RuntimeError,
6162 "pgsql: item %zu is not a string or bytes", i);
6163 return (KORE_RESULT_ERROR);
6164 }
6165
6166 if (ptr.cp == NULL)
6167 return (KORE_RESULT_ERROR);
6168
6169 op->param.lengths[i] = vlen;
6170 op->param.values[i] = ptr.cp;
6171 op->param.formats[i] = format;
6172
6173 /* Hold on to it since we are directly referencing its data. */
6174 op->param.objs[i] = item;
6175 Py_INCREF(item);
6176 }
6177
6178 return (KORE_RESULT_OK);
6179 }
6180
6181 static void
6182 pykore_pgsql_dealloc(struct pykore_pgsql *pysql)
6183 {
6184 Py_ssize_t i;
6185
6186 kore_free(pysql->db);
6187 kore_free(pysql->query);
6188 kore_pgsql_cleanup(&pysql->sql);
6189
6190 if (pysql->result != NULL)
6191 Py_DECREF(pysql->result);
6192
6193 for (i = 0; i < pysql->param.count; i++)
6194 Py_XDECREF(pysql->param.objs[i]);
6195
6196 kore_free(pysql->param.objs);
6197 kore_free(pysql->param.values);
6198 kore_free(pysql->param.lengths);
6199 kore_free(pysql->param.formats);
6200
6201 PyObject_Del((PyObject *)pysql);
6202 }
6203
6204 static PyObject *
6205 pykore_pgsql_iternext(struct pykore_pgsql *pysql)
6206 {
6207 switch (pysql->state) {
6208 case PYKORE_PGSQL_PREINIT:
6209 kore_pgsql_init(&pysql->sql);
6210 kore_pgsql_bind_callback(&pysql->sql,
6211 pykore_pgsql_callback, pysql);
6212 pysql->state = PYKORE_PGSQL_INITIALIZE;
6213 /* fallthrough */
6214 case PYKORE_PGSQL_INITIALIZE:
6215 if (!kore_pgsql_setup(&pysql->sql, pysql->db,
6216 KORE_PGSQL_ASYNC)) {
6217 if (pysql->sql.state == KORE_PGSQL_STATE_INIT)
6218 break;
6219 PyErr_Format(PyExc_RuntimeError, "pgsql error: %s",
6220 pysql->sql.error);
6221 return (NULL);
6222 }
6223 /* fallthrough */
6224 case PYKORE_PGSQL_QUERY:
6225 if (pysql->param.count > 0) {
6226 if (!kore_pgsql_query_param_fields(&pysql->sql,
6227 pysql->query, pysql->binary,
6228 pysql->param.count, pysql->param.values,
6229 pysql->param.lengths, pysql->param.formats)) {
6230 PyErr_Format(PyExc_RuntimeError,
6231 "pgsql error: %s", pysql->sql.error);
6232 return (NULL);
6233 }
6234 } else {
6235 if (!kore_pgsql_query(&pysql->sql, pysql->query)) {
6236 PyErr_Format(PyExc_RuntimeError,
6237 "pgsql error: %s", pysql->sql.error);
6238 return (NULL);
6239 }
6240 }
6241 pysql->state = PYKORE_PGSQL_WAIT;
6242 break;
6243 wait_again:
6244 case PYKORE_PGSQL_WAIT:
6245 switch (pysql->sql.state) {
6246 case KORE_PGSQL_STATE_WAIT:
6247 break;
6248 case KORE_PGSQL_STATE_COMPLETE:
6249 PyErr_SetNone(PyExc_StopIteration);
6250 if (pysql->result != NULL) {
6251 PyErr_SetObject(PyExc_StopIteration,
6252 pysql->result);
6253 Py_DECREF(pysql->result);
6254 pysql->result = NULL;
6255 } else {
6256 PyErr_SetObject(PyExc_StopIteration, Py_None);
6257 }
6258 return (NULL);
6259 case KORE_PGSQL_STATE_ERROR:
6260 PyErr_Format(PyExc_RuntimeError,
6261 "failed to perform query: %s", pysql->sql.error);
6262 return (NULL);
6263 case KORE_PGSQL_STATE_RESULT:
6264 if (!pykore_pgsql_result(pysql))
6265 return (NULL);
6266 goto wait_again;
6267 default:
6268 kore_pgsql_continue(&pysql->sql);
6269 goto wait_again;
6270 }
6271 break;
6272 default:
6273 PyErr_SetString(PyExc_RuntimeError, "bad pykore_pgsql state");
6274 return (NULL);
6275 }
6276
6277 /* tell caller to wait. */
6278 Py_RETURN_NONE;
6279 }
6280
6281 static void
6282 pykore_pgsql_callback(struct kore_pgsql *pgsql, void *arg)
6283 {
6284 struct pykore_pgsql *op = arg;
6285
6286 if (op->coro->request != NULL)
6287 http_request_wakeup(op->coro->request);
6288 else
6289 python_coro_wakeup(op->coro);
6290 }
6291
6292 static PyObject *
6293 pykore_pgsql_await(PyObject *obj)
6294 {
6295 Py_INCREF(obj);
6296 return (obj);
6297 }
6298
6299 static int
6300 pykore_pgsql_result(struct pykore_pgsql *pysql)
6301 {
6302 const char *val;
6303 char key[64];
6304 PyObject *list, *pyrow, *pyval;
6305 int rows, row, field, fields, len;
6306
6307 if ((list = PyList_New(0)) == NULL) {
6308 PyErr_SetNone(PyExc_MemoryError);
6309 return (KORE_RESULT_ERROR);
6310 }
6311
6312 rows = kore_pgsql_ntuples(&pysql->sql);
6313 fields = kore_pgsql_nfields(&pysql->sql);
6314
6315 for (row = 0; row < rows; row++) {
6316 if ((pyrow = PyDict_New()) == NULL) {
6317 Py_DECREF(list);
6318 PyErr_SetNone(PyExc_MemoryError);
6319 return (KORE_RESULT_ERROR);
6320 }
6321
6322 for (field = 0; field < fields; field++) {
6323 val = kore_pgsql_getvalue(&pysql->sql, row, field);
6324 len = kore_pgsql_getlength(&pysql->sql, row, field);
6325
6326 if (kore_pgsql_column_binary(&pysql->sql, field)) {
6327 pyval = PyBytes_FromStringAndSize(val, len);
6328 } else {
6329 pyval = PyUnicode_FromString(val);
6330 }
6331
6332 if (pyval == NULL) {
6333 Py_DECREF(pyrow);
6334 Py_DECREF(list);
6335 PyErr_SetNone(PyExc_MemoryError);
6336 return (KORE_RESULT_ERROR);
6337 }
6338
6339 (void)snprintf(key, sizeof(key), "%s",
6340 kore_pgsql_fieldname(&pysql->sql, field));
6341
6342 if (PyDict_SetItemString(pyrow, key, pyval) == -1) {
6343 Py_DECREF(pyval);
6344 Py_DECREF(pyrow);
6345 Py_DECREF(list);
6346 PyErr_SetString(PyExc_RuntimeError,
6347 "failed to add new value to row");
6348 return (KORE_RESULT_ERROR);
6349 }
6350
6351 Py_DECREF(pyval);
6352 }
6353
6354 if (PyList_Insert(list, row, pyrow) == -1) {
6355 Py_DECREF(pyrow);
6356 Py_DECREF(list);
6357 PyErr_SetString(PyExc_RuntimeError,
6358 "failed to add new row to list");
6359 return (KORE_RESULT_ERROR);
6360 }
6361
6362 Py_DECREF(pyrow);
6363 }
6364
6365 pysql->result = list;
6366 kore_pgsql_continue(&pysql->sql);
6367
6368 return (KORE_RESULT_OK);
6369 }
6370 #endif
6371
6372 #if defined(KORE_USE_CURL)
6373 static PyObject *
6374 python_curlopt_set(struct pycurl_data *data, long opt, PyObject *value)
6375 {
6376 int i;
6377
6378 for (i = 0; py_curlopt[i].name != NULL; i++) {
6379 if (py_curlopt[i].value == opt)
6380 break;
6381 }
6382
6383 if (py_curlopt[i].name == NULL) {
6384 PyErr_Format(PyExc_RuntimeError, "invalid option '%ld'", opt);
6385 return (NULL);
6386 }
6387
6388 if (py_curlopt[i].cb == NULL) {
6389 PyErr_Format(PyExc_RuntimeError, "option '%s' not implemented",
6390 py_curlopt[i].name);
6391 return (NULL);
6392 }
6393
6394 return (py_curlopt[i].cb(data, i, value));
6395 }
6396
6397 static int
6398 python_curlopt_from_dict(struct pycurl_data *data, PyObject *dict)
6399 {
6400 long opt;
6401 Py_ssize_t idx;
6402 PyObject *key, *value, *obj;
6403
6404 idx = 0;
6405
6406 if (!PyDict_CheckExact(dict)) {
6407 PyErr_SetString(PyExc_RuntimeError,
6408 "curlopt must be a dictionary");
6409 return (KORE_RESULT_ERROR);
6410 }
6411
6412 while (PyDict_Next(dict, &idx, &key, &value)) {
6413 if (!PyLong_CheckExact(key)) {
6414 PyErr_Format(PyExc_RuntimeError,
6415 "invalid key in curlopt keyword");
6416 return (KORE_RESULT_ERROR);
6417 }
6418
6419 opt = PyLong_AsLong(key);
6420
6421 if ((obj = python_curlopt_set(data, opt, value)) == NULL)
6422 return (KORE_RESULT_ERROR);
6423
6424 Py_DECREF(obj);
6425 }
6426
6427 return (KORE_RESULT_OK);
6428 }
6429
6430 static PyObject *
6431 python_kore_curl_handle(PyObject *self, PyObject *args)
6432 {
6433 const char *url;
6434 struct pycurl_handle *handle;
6435
6436 if (!PyArg_ParseTuple(args, "s", &url))
6437 return (NULL);
6438
6439 handle = PyObject_New(struct pycurl_handle, &pycurl_handle_type);
6440 if (handle == NULL)
6441 return (NULL);
6442
6443 handle->url = kore_strdup(url);
6444 memset(&handle->data.curl, 0, sizeof(handle->data.curl));
6445
6446 handle->body = NULL;
6447 LIST_INIT(&handle->data.slists);
6448
6449 if (!kore_curl_init(&handle->data.curl, handle->url, KORE_CURL_ASYNC)) {
6450 Py_DECREF((PyObject *)handle);
6451 PyErr_SetString(PyExc_RuntimeError, "failed to setup call");
6452 return (NULL);
6453 }
6454
6455 return ((PyObject *)handle);
6456 }
6457
6458 static void
6459 pycurl_handle_dealloc(struct pycurl_handle *handle)
6460 {
6461 struct pycurl_slist *psl;
6462
6463 while ((psl = LIST_FIRST(&handle->data.slists))) {
6464 LIST_REMOVE(psl, list);
6465 curl_slist_free_all(psl->slist);
6466 kore_free(psl);
6467 }
6468
6469 if (handle->body != NULL)
6470 kore_buf_free(handle->body);
6471
6472 kore_free(handle->url);
6473 kore_curl_cleanup(&handle->data.curl);
6474
6475 PyObject_Del((PyObject *)handle);
6476 }
6477
6478 static PyObject *
6479 pycurl_handle_setbody(struct pycurl_handle *handle, PyObject *args)
6480 {
6481 PyObject *obj;
6482 char *ptr;
6483 Py_ssize_t length;
6484
6485 if (!PyArg_ParseTuple(args, "O", &obj))
6486 return (NULL);
6487
6488 if (handle->body != NULL) {
6489 PyErr_SetString(PyExc_RuntimeError,
6490 "curl handle already has body attached");
6491 return (NULL);
6492 }
6493
6494 if (!PyBytes_CheckExact(obj)) {
6495 PyErr_SetString(PyExc_RuntimeError,
6496 "curl.setbody expects bytes");
6497 return (NULL);
6498 }
6499
6500 if (PyBytes_AsStringAndSize(obj, &ptr, &length) == -1)
6501 return (NULL);
6502
6503 if (length < 0) {
6504 PyErr_SetString(PyExc_TypeError, "invalid length");
6505 return (NULL);
6506 }
6507
6508 handle->body = kore_buf_alloc(length);
6509 kore_buf_append(handle->body, ptr, length);
6510 kore_buf_reset(handle->body);
6511
6512 curl_easy_setopt(handle->data.curl.handle,
6513 CURLOPT_READFUNCTION, kore_curl_frombuf);
6514 curl_easy_setopt(handle->data.curl.handle,
6515 CURLOPT_READDATA, handle->body);
6516
6517 curl_easy_setopt(handle->data.curl.handle, CURLOPT_UPLOAD, 1);
6518
6519 Py_RETURN_TRUE;
6520 }
6521
6522 static PyObject *
6523 pycurl_handle_setopt(struct pycurl_handle *handle, PyObject *args)
6524 {
6525 int opt;
6526 PyObject *value;
6527
6528 if (!PyArg_ParseTuple(args, "iO", &opt, &value))
6529 return (NULL);
6530
6531 return (python_curlopt_set(&handle->data, opt, value));
6532 }
6533
6534 static PyObject *
6535 pycurl_handle_setopt_string(struct pycurl_data *data, int idx, PyObject *obj)
6536 {
6537 const char *str;
6538 CURLoption option;
6539
6540 if (!PyUnicode_Check(obj)) {
6541 PyErr_Format(PyExc_RuntimeError,
6542 "option '%s' requires a string as argument",
6543 py_curlopt[idx].name);
6544 return (NULL);
6545 }
6546
6547 if ((str = PyUnicode_AsUTF8(obj)) == NULL)
6548 return (NULL);
6549
6550 option = CURLOPTTYPE_OBJECTPOINT + py_curlopt[idx].value;
6551 curl_easy_setopt(data->curl.handle, option, str);
6552
6553 Py_RETURN_TRUE;
6554 }
6555
6556 static PyObject *
6557 pycurl_handle_setopt_long(struct pycurl_data *data, int idx, PyObject *obj)
6558 {
6559 long val;
6560 CURLoption option;
6561
6562 if (!PyLong_CheckExact(obj)) {
6563 PyErr_Format(PyExc_RuntimeError,
6564 "option '%s' requires a long as argument",
6565 py_curlopt[idx].name);
6566 return (NULL);
6567 }
6568
6569 PyErr_Clear();
6570 val = PyLong_AsLong(obj);
6571 if (val == -1 && PyErr_Occurred())
6572 return (NULL);
6573
6574 option = CURLOPTTYPE_LONG + py_curlopt[idx].value;
6575 curl_easy_setopt(data->curl.handle, option, val);
6576
6577 Py_RETURN_TRUE;
6578 }
6579
6580 static PyObject *
6581 pycurl_handle_setopt_slist(struct pycurl_data *data, int idx, PyObject *obj)
6582 {
6583 struct pycurl_slist *psl;
6584 PyObject *item;
6585 const char *sval;
6586 struct curl_slist *slist;
6587 CURLoption option;
6588 Py_ssize_t list_len, i;
6589
6590 if (!PyList_CheckExact(obj)) {
6591 PyErr_Format(PyExc_RuntimeError,
6592 "option '%s' requires a list as argument",
6593 py_curlopt[idx].name);
6594 return (NULL);
6595 }
6596
6597 slist = NULL;
6598 list_len = PyList_Size(obj);
6599
6600 for (i = 0; i < list_len; i++) {
6601 if ((item = PyList_GetItem(obj, i)) == NULL)
6602 return (NULL);
6603
6604 if (!PyUnicode_Check(item))
6605 return (NULL);
6606
6607 if ((sval = PyUnicode_AsUTF8AndSize(item, NULL)) == NULL)
6608 return (NULL);
6609
6610 if ((slist = curl_slist_append(slist, sval)) == NULL)
6611 fatal("%s: curl_slist_append failed", __func__);
6612 }
6613
6614 psl = kore_calloc(1, sizeof(*psl));
6615 psl->slist = slist;
6616 LIST_INSERT_HEAD(&data->slists, psl, list);
6617
6618 option = CURLOPTTYPE_OBJECTPOINT + py_curlopt[idx].value;
6619 curl_easy_setopt(data->curl.handle, option, slist);
6620
6621 Py_RETURN_TRUE;
6622 }
6623
6624 static PyObject *
6625 pycurl_handle_run(struct pycurl_handle *handle, PyObject *args)
6626 {
6627 struct pycurl_handle_op *op;
6628
6629 op = PyObject_New(struct pycurl_handle_op, &pycurl_handle_op_type);
6630 if (op == NULL)
6631 return (NULL);
6632
6633 Py_INCREF(handle);
6634
6635 op->handle = handle;
6636 op->coro = coro_running;
6637 op->state = CURL_CLIENT_OP_RUN;
6638
6639 kore_curl_bind_callback(&handle->data.curl,
6640 python_curl_handle_callback, op);
6641
6642 return ((PyObject *)op);
6643 }
6644
6645 static void
6646 pycurl_handle_op_dealloc(struct pycurl_handle_op *op)
6647 {
6648 Py_DECREF(op->handle);
6649 PyObject_Del((PyObject *)op);
6650 }
6651
6652 static PyObject *
6653 pycurl_handle_op_await(PyObject *op)
6654 {
6655 Py_INCREF(op);
6656 return (op);
6657 }
6658
6659 static PyObject *
6660 pycurl_handle_op_iternext(struct pycurl_handle_op *op)
6661 {
6662 size_t len;
6663 PyObject *result;
6664 const u_int8_t *response;
6665
6666 if (op->state == CURL_CLIENT_OP_RUN) {
6667 kore_curl_run(&op->handle->data.curl);
6668 op->state = CURL_CLIENT_OP_RESULT;
6669 Py_RETURN_NONE;
6670 }
6671
6672 if (op->handle->body != NULL) {
6673 kore_buf_free(op->handle->body);
6674 op->handle->body = NULL;
6675 }
6676
6677 if (!kore_curl_success(&op->handle->data.curl)) {
6678 /* Do not log the url here, may contain some sensitive data. */
6679 PyErr_Format(PyExc_RuntimeError, "request failed: %s",
6680 kore_curl_strerror(&op->handle->data.curl));
6681 return (NULL);
6682 }
6683
6684 kore_curl_response_as_bytes(&op->handle->data.curl, &response, &len);
6685
6686 if ((result = PyBytes_FromStringAndSize((const char *)response,
6687 len)) == NULL)
6688 return (NULL);
6689
6690 PyErr_SetObject(PyExc_StopIteration, result);
6691 Py_DECREF(result);
6692
6693 return (NULL);
6694 }
6695
6696 static PyObject *
6697 python_kore_httpclient(PyObject *self, PyObject *args, PyObject *kwargs)
6698 {
6699 struct pyhttp_client *client;
6700 const char *url, *v;
6701
6702 if (!PyArg_ParseTuple(args, "s", &url))
6703 return (NULL);
6704
6705 client = PyObject_New(struct pyhttp_client, &pyhttp_client_type);
6706 if (client == NULL)
6707 return (NULL);
6708
6709 client->unix = NULL;
6710 client->tlskey = NULL;
6711 client->curlopt = NULL;
6712 client->tlscert = NULL;
6713 client->cabundle = NULL;
6714
6715 client->tlsverify = 1;
6716 client->url = kore_strdup(url);
6717
6718 if (kwargs != NULL) {
6719 if ((v = python_string_from_dict(kwargs, "tlscert")) != NULL)
6720 client->tlscert = kore_strdup(v);
6721
6722 if ((v = python_string_from_dict(kwargs, "tlskey")) != NULL)
6723 client->tlskey = kore_strdup(v);
6724
6725 if ((v = python_string_from_dict(kwargs, "cabundle")) != NULL)
6726 client->cabundle = kore_strdup(v);
6727
6728 if ((v = python_string_from_dict(kwargs, "unix")) != NULL)
6729 client->unix = kore_strdup(v);
6730
6731 client->curlopt = PyDict_GetItemString(kwargs, "curlopt");
6732 Py_XINCREF(client->curlopt);
6733
6734 python_bool_from_dict(kwargs, "tlsverify", &client->tlsverify);
6735 }
6736
6737 if ((client->tlscert != NULL && client->tlskey == NULL) ||
6738 (client->tlskey != NULL && client->tlscert == NULL)) {
6739 Py_DECREF((PyObject *)client);
6740 PyErr_SetString(PyExc_RuntimeError,
6741 "invalid TLS client configuration");
6742 return (NULL);
6743 }
6744
6745 return ((PyObject *)client);
6746 }
6747
6748 static void
6749 pyhttp_client_dealloc(struct pyhttp_client *client)
6750 {
6751 kore_free(client->url);
6752 kore_free(client->unix);
6753 kore_free(client->tlskey);
6754 kore_free(client->tlscert);
6755 kore_free(client->cabundle);
6756
6757 Py_XDECREF(client->curlopt);
6758
6759 PyObject_Del((PyObject *)client);
6760 }
6761
6762 static PyObject *
6763 pyhttp_client_get(struct pyhttp_client *client, PyObject *args,
6764 PyObject *kwargs)
6765 {
6766 return (pyhttp_client_request(client, HTTP_METHOD_GET, kwargs));
6767 }
6768
6769 static PyObject *
6770 pyhttp_client_put(struct pyhttp_client *client, PyObject *args,
6771 PyObject *kwargs)
6772 {
6773 return (pyhttp_client_request(client, HTTP_METHOD_PUT, kwargs));
6774 }
6775
6776 static PyObject *
6777 pyhttp_client_post(struct pyhttp_client *client, PyObject *args,
6778 PyObject *kwargs)
6779 {
6780 return (pyhttp_client_request(client, HTTP_METHOD_POST, kwargs));
6781 }
6782
6783 static PyObject *
6784 pyhttp_client_head(struct pyhttp_client *client, PyObject *args,
6785 PyObject *kwargs)
6786 {
6787 return (pyhttp_client_request(client, HTTP_METHOD_HEAD, kwargs));
6788 }
6789
6790 static PyObject *
6791 pyhttp_client_patch(struct pyhttp_client *client, PyObject *args,
6792 PyObject *kwargs)
6793 {
6794 return (pyhttp_client_request(client, HTTP_METHOD_PATCH, kwargs));
6795 }
6796
6797 static PyObject *
6798 pyhttp_client_delete(struct pyhttp_client *client, PyObject *args,
6799 PyObject *kwargs)
6800 {
6801 return (pyhttp_client_request(client, HTTP_METHOD_DELETE, kwargs));
6802 }
6803
6804 static PyObject *
6805 pyhttp_client_options(struct pyhttp_client *client, PyObject *args,
6806 PyObject *kwargs)
6807 {
6808 return (pyhttp_client_request(client, HTTP_METHOD_OPTIONS, kwargs));
6809 }
6810
6811 static PyObject *
6812 pyhttp_client_request(struct pyhttp_client *client, int m, PyObject *kwargs)
6813 {
6814 struct pyhttp_client_op *op;
6815 char *ptr;
6816 const char *k, *v;
6817 Py_ssize_t length, idx;
6818 PyObject *data, *headers, *key, *obj;
6819
6820 ptr = NULL;
6821 length = 0;
6822 headers = NULL;
6823
6824 if (kwargs != NULL &&
6825 ((headers = PyDict_GetItemString(kwargs, "headers")) != NULL)) {
6826 if (!PyDict_CheckExact(headers)) {
6827 PyErr_SetString(PyExc_RuntimeError,
6828 "headers keyword must be a dict");
6829 return (NULL);
6830 }
6831 }
6832
6833 switch (m) {
6834 case HTTP_METHOD_GET:
6835 case HTTP_METHOD_HEAD:
6836 case HTTP_METHOD_OPTIONS:
6837 break;
6838 case HTTP_METHOD_PUT:
6839 case HTTP_METHOD_POST:
6840 case HTTP_METHOD_PATCH:
6841 case HTTP_METHOD_DELETE:
6842 length = -1;
6843
6844 if (kwargs == NULL) {
6845 if (m == HTTP_METHOD_DELETE) {
6846 length = 0;
6847 break;
6848 }
6849
6850 PyErr_Format(PyExc_RuntimeError,
6851 "no keyword arguments given, but body expected ",
6852 http_method_text(m));
6853 return (NULL);
6854 }
6855
6856 if ((data = PyDict_GetItemString(kwargs, "body")) == NULL)
6857 return (NULL);
6858
6859 if (PyBytes_AsStringAndSize(data, &ptr, &length) == -1)
6860 return (NULL);
6861
6862 if (length < 0) {
6863 PyErr_SetString(PyExc_TypeError, "invalid length");
6864 return (NULL);
6865 }
6866 break;
6867 default:
6868 fatal("%s: unknown method %d", __func__, m);
6869 }
6870
6871 op = PyObject_New(struct pyhttp_client_op, &pyhttp_client_op_type);
6872 if (op == NULL)
6873 return (NULL);
6874
6875 if (!kore_curl_init(&op->data.curl, client->url, KORE_CURL_ASYNC)) {
6876 Py_DECREF((PyObject *)op);
6877 PyErr_SetString(PyExc_RuntimeError, "failed to setup call");
6878 return (NULL);
6879 }
6880
6881 op->headers = 0;
6882 op->coro = coro_running;
6883 op->state = CURL_CLIENT_OP_RUN;
6884 LIST_INIT(&op->data.slists);
6885
6886 Py_INCREF(client);
6887 op->client = client;
6888
6889 kore_curl_http_setup(&op->data.curl, m, ptr, length);
6890 kore_curl_bind_callback(&op->data.curl, python_curl_http_callback, op);
6891
6892 /* Go in with our own bare hands. */
6893 if (client->unix != NULL) {
6894 #if defined(__linux__)
6895 if (client->unix[0] == '@') {
6896 curl_easy_setopt(op->data.curl.handle,
6897 CURLOPT_ABSTRACT_UNIX_SOCKET, client->unix + 1);
6898 } else {
6899 curl_easy_setopt(op->data.curl.handle,
6900 CURLOPT_UNIX_SOCKET_PATH, client->unix);
6901 }
6902 #else
6903 curl_easy_setopt(op->data.curl.handle, CURLOPT_UNIX_SOCKET_PATH,
6904 client->unix);
6905 #endif
6906 }
6907
6908 if (client->tlskey != NULL && client->tlscert != NULL) {
6909 curl_easy_setopt(op->data.curl.handle, CURLOPT_SSLCERT,
6910 client->tlscert);
6911 curl_easy_setopt(op->data.curl.handle, CURLOPT_SSLKEY,
6912 client->tlskey);
6913 }
6914
6915 if (client->tlsverify == 0) {
6916 curl_easy_setopt(op->data.curl.handle,
6917 CURLOPT_SSL_VERIFYHOST, 0);
6918 curl_easy_setopt(op->data.curl.handle,
6919 CURLOPT_SSL_VERIFYPEER, 0);
6920 }
6921
6922 if (client->curlopt != NULL) {
6923 if (!python_curlopt_from_dict(&op->data, client->curlopt)) {
6924 Py_DECREF((PyObject *)op);
6925 return (NULL);
6926 }
6927 }
6928
6929 if (client->cabundle != NULL) {
6930 curl_easy_setopt(op->data.curl.handle, CURLOPT_CAINFO,
6931 client->cabundle);
6932 }
6933
6934 if (headers != NULL) {
6935 idx = 0;
6936 while (PyDict_Next(headers, &idx, &key, &obj)) {
6937 if ((k = PyUnicode_AsUTF8(key)) == NULL) {
6938 Py_DECREF((PyObject *)op);
6939 return (NULL);
6940 }
6941
6942 if ((v = PyUnicode_AsUTF8(obj)) == NULL) {
6943 Py_DECREF((PyObject *)op);
6944 return (NULL);
6945 }
6946
6947 kore_curl_http_set_header(&op->data.curl, k, v);
6948 }
6949 }
6950
6951 if (kwargs != NULL) {
6952 if ((obj = PyDict_GetItemString(kwargs, "curlopt")) != NULL) {
6953 if (!python_curlopt_from_dict(&op->data, obj)) {
6954 Py_DECREF((PyObject *)op);
6955 return (NULL);
6956 }
6957 }
6958
6959 python_bool_from_dict(kwargs, "return_headers", &op->headers);
6960 }
6961
6962 return ((PyObject *)op);
6963 }
6964
6965 static void
6966 pyhttp_client_op_dealloc(struct pyhttp_client_op *op)
6967 {
6968 struct pycurl_slist *psl;
6969
6970 while ((psl = LIST_FIRST(&op->data.slists))) {
6971 LIST_REMOVE(psl, list);
6972 curl_slist_free_all(psl->slist);
6973 kore_free(psl);
6974 }
6975
6976 Py_DECREF(op->client);
6977 kore_curl_cleanup(&op->data.curl);
6978 PyObject_Del((PyObject *)op);
6979 }
6980
6981 static PyObject *
6982 pyhttp_client_op_await(PyObject *op)
6983 {
6984 Py_INCREF(op);
6985 return (op);
6986 }
6987
6988 static PyObject *
6989 pyhttp_client_op_iternext(struct pyhttp_client_op *op)
6990 {
6991 size_t len;
6992 struct http_header *hdr;
6993 const u_int8_t *response;
6994 PyObject *result, *tuple, *dict, *value;
6995
6996 if (op->state == CURL_CLIENT_OP_RUN) {
6997 kore_curl_run(&op->data.curl);
6998 op->state = CURL_CLIENT_OP_RESULT;
6999 Py_RETURN_NONE;
7000 }
7001
7002 if (!kore_curl_success(&op->data.curl)) {
7003 PyErr_Format(PyExc_RuntimeError, "request to '%s' failed: %s",
7004 op->data.curl.url, kore_curl_strerror(&op->data.curl));
7005 return (NULL);
7006 }
7007
7008 kore_curl_response_as_bytes(&op->data.curl, &response, &len);
7009
7010 if (op->headers) {
7011 kore_curl_http_parse_headers(&op->data.curl);
7012
7013 if ((dict = PyDict_New()) == NULL)
7014 return (NULL);
7015
7016 TAILQ_FOREACH(hdr, &op->data.curl.http.resp_hdrs, list) {
7017 value = PyUnicode_FromString(hdr->value);
7018 if (value == NULL) {
7019 Py_DECREF(dict);
7020 return (NULL);
7021 }
7022
7023 if (PyDict_SetItemString(dict,
7024 hdr->header, value) == -1) {
7025 Py_DECREF(dict);
7026 Py_DECREF(value);
7027 return (NULL);
7028 }
7029
7030 Py_DECREF(value);
7031 }
7032
7033 if ((tuple = Py_BuildValue("(iOy#)", op->data.curl.http.status,
7034 dict, (const char *)response, len)) == NULL)
7035 return (NULL);
7036
7037 Py_DECREF(dict);
7038 } else {
7039 if ((tuple = Py_BuildValue("(iy#)", op->data.curl.http.status,
7040 (const char *)response, len)) == NULL)
7041 return (NULL);
7042 }
7043
7044 result = PyObject_CallFunctionObjArgs(PyExc_StopIteration, tuple, NULL);
7045 if (result == NULL) {
7046 Py_DECREF(tuple);
7047 return (NULL);
7048 }
7049
7050 Py_DECREF(tuple);
7051 PyErr_SetObject(PyExc_StopIteration, result);
7052 Py_DECREF(result);
7053
7054 return (NULL);
7055 }
7056
7057 static void
7058 python_curl_http_callback(struct kore_curl *curl, void *arg)
7059 {
7060 struct pyhttp_client_op *op = arg;
7061
7062 if (op->coro->request != NULL)
7063 http_request_wakeup(op->coro->request);
7064 else
7065 python_coro_wakeup(op->coro);
7066 }
7067
7068 static void
7069 python_curl_handle_callback(struct kore_curl *curl, void *arg)
7070 {
7071 struct pycurl_handle_op *op = arg;
7072
7073 if (op->coro->request != NULL)
7074 http_request_wakeup(op->coro->request);
7075 else
7076 python_coro_wakeup(op->coro);
7077 }
7078 #endif