Blob


1 /*
2 * Copyright (c) 2021, 2022 Omar Polo <op@omarpolo.com>
3 * Copyright (c) 2018 Florian Obser <florian@openbsd.org>
4 * Copyright (c) 2004, 2005 Claudio Jeker <claudio@openbsd.org>
5 * Copyright (c) 2004 Esben Norby <norby@openbsd.org>
6 * Copyright (c) 2003, 2004 Henning Brauer <henning@openbsd.org>
7 *
8 * Permission to use, copy, modify, and distribute this software for any
9 * purpose with or without fee is hereby granted, provided that the above
10 * copyright notice and this permission notice appear in all copies.
11 *
12 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
13 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
14 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
15 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
16 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
17 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
18 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
19 */
21 #include "compat.h"
23 #include <sys/socket.h>
24 #include <sys/types.h>
25 #include <sys/uio.h>
27 #include <endian.h>
28 #include <errno.h>
29 #include <inttypes.h>
30 #include <pwd.h>
31 #include <signal.h>
32 #include <stdint.h>
33 #include <stdio.h>
34 #include <stdlib.h>
35 #include <string.h>
36 #include <syslog.h>
37 #include <unistd.h>
39 #include "control.h"
40 #include "kami.h"
41 #include "kamid.h"
42 #include "listener.h"
43 #include "log.h"
44 #include "sandbox.h"
45 #include "utils.h"
47 #define IMSG_MAXSIZE (MAX_IMSGSIZE - IMSG_HEADER_SIZE)
49 static struct kd_conf *listener_conf;
50 static struct imsgev *iev_main;
52 static void listener_sig_handler(int, short, void *);
53 __dead void listener_shutdown(void);
55 SPLAY_HEAD(clients_tree_id, client) clients;
57 struct client {
58 uint32_t id;
59 uint32_t lid;
60 uint32_t lflags;
61 uint32_t msize;
62 uint32_t left;
63 int fd;
64 struct tls *ctx;
65 struct event event;
66 struct imsgev iev;
67 struct bufferevent *bev;
68 SPLAY_ENTRY(client) sp_entry;
69 };
71 static void listener_imsg_event_add(struct imsgev *, void *);
72 static void listener_dispatch_client(int, short, void *);
73 static int listener_imsg_compose_client(struct client *, int,
74 uint32_t, const void *, uint16_t);
76 static void apply_config(struct kd_conf *);
77 static void handle_accept(int, short, void *);
79 static void handle_handshake(int, short, void *);
80 static void client_read(struct bufferevent *, void *);
81 static void client_write(struct bufferevent *, void *);
82 static void client_error(struct bufferevent *, short, void *);
83 static void client_tls_readcb(int, short, void *);
84 static void client_tls_writecb(int, short, void *);
85 static void close_conn(struct client *);
86 static void handle_close(int, short, void *);
88 static inline int
89 clients_tree_cmp(struct client *a, struct client *b)
90 {
91 if (a->id == b->id)
92 return 0;
93 else if (a->id < b->id)
94 return -1;
95 else
96 return +1;
97 }
99 SPLAY_PROTOTYPE(clients_tree_id, client, sp_entry, clients_tree_cmp);
100 SPLAY_GENERATE(clients_tree_id, client, sp_entry, clients_tree_cmp)
102 static void
103 listener_sig_handler(int sig, short event, void *d)
105 /*
106 * Normal signal handler rules don't apply because libevent
107 * decouples for us.
108 */
110 switch (sig) {
111 case SIGINT:
112 case SIGTERM:
113 listener_shutdown();
114 default:
115 fatalx("unexpected signal %d", sig);
119 void
120 listener(int debug, int verbose)
122 struct event ev_sigint, ev_sigterm;
123 struct passwd *pw;
125 /* listener_conf = config_new_empty(); */
127 log_init(debug, LOG_DAEMON);
128 log_setverbose(verbose);
130 if ((pw = getpwnam(KD_USER)) == NULL)
131 fatal("getpwnam");
133 if (chroot(pw->pw_dir) == -1)
134 fatal("chroot");
135 if (chdir("/") == -1)
136 fatal("chdir(\"/\")");
138 setproctitle("listener");
139 log_procinit("listener");
141 if (setgroups(1, &pw->pw_gid) ||
142 setresgid(pw->pw_gid, pw->pw_gid, pw->pw_gid) ||
143 setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid))
144 fatal("can't drop privileges");
146 event_init();
148 /* Setup signal handlers(s). */
149 signal_set(&ev_sigint, SIGINT, listener_sig_handler, NULL);
150 signal_set(&ev_sigterm, SIGTERM, listener_sig_handler, NULL);
152 signal_add(&ev_sigint, NULL);
153 signal_add(&ev_sigterm, NULL);
155 signal(SIGPIPE, SIG_IGN);
156 signal(SIGHUP, SIG_IGN);
158 /* Setup pipe and event handler to the main process. */
159 if ((iev_main = malloc(sizeof(*iev_main))) == NULL)
160 fatal(NULL);
162 imsg_init(&iev_main->ibuf, 3);
163 iev_main->handler = listener_dispatch_main;
165 /* Setup event handlers. */
166 iev_main->events = EV_READ;
167 event_set(&iev_main->ev, iev_main->ibuf.fd, iev_main->events,
168 iev_main->handler, iev_main);
169 event_add(&iev_main->ev, NULL);
171 sandbox_listener();
172 event_dispatch();
173 listener_shutdown();
176 __dead void
177 listener_shutdown(void)
179 msgbuf_clear(&iev_main->ibuf.w);
180 close(iev_main->ibuf.fd);
182 clear_config(listener_conf);
184 free(iev_main);
186 log_info("listener exiting");
187 exit(0);
190 static void
191 listener_receive_config(struct imsg *imsg, struct kd_conf **nconf,
192 struct kd_pki_conf **pki)
194 struct kd_listen_conf *listen;
195 char *t;
197 switch (imsg->hdr.type) {
198 case IMSG_RECONF_CONF:
199 if (*nconf != NULL)
200 fatalx("%s: IMSG_RECONF_CONF already in "
201 "progress", __func__);
203 if (IMSG_DATA_SIZE(*imsg) != sizeof(struct kd_conf))
204 fatalx("%s: IMSG_RECONF_CONF wrong length: %lu",
205 __func__, IMSG_DATA_SIZE(*imsg));
206 if ((*nconf = malloc(sizeof(**nconf))) == NULL)
207 fatal(NULL);
208 memcpy(*nconf, imsg->data, sizeof(**nconf));
209 STAILQ_INIT(&(*nconf)->pki_head);
210 STAILQ_INIT(&(*nconf)->table_head);
211 STAILQ_INIT(&(*nconf)->listen_head);
212 break;
213 case IMSG_RECONF_PKI:
214 if (*nconf == NULL)
215 fatalx("%s: IMSG_RECONF_PKI without "
216 "IMSG_RECONF_CONF", __func__);
217 *pki = xcalloc(1, sizeof(**pki));
218 t = imsg->data;
219 t[IMSG_DATA_SIZE(*imsg)-1] = '\0';
220 strlcpy((*pki)->name, t, sizeof((*pki)->name));
221 break;
222 case IMSG_RECONF_PKI_CERT:
223 if (*pki == NULL)
224 fatalx("%s: IMSG_RECONF_PKI_CERT without "
225 "IMSG_RECONF_PKI", __func__);
226 (*pki)->certlen = IMSG_DATA_SIZE(*imsg);
227 (*pki)->cert = xmemdup(imsg->data, (*pki)->certlen);
228 break;
229 case IMSG_RECONF_PKI_KEY:
230 if (*pki == NULL)
231 fatalx("%s: IMSG_RECONF_PKI_KEY without "
232 "IMSG_RECONF_PKI", __func__);
233 (*pki)->keylen = IMSG_DATA_SIZE(*imsg);
234 (*pki)->key = xmemdup(imsg->data, (*pki)->keylen);
235 STAILQ_INSERT_HEAD(&(*nconf)->pki_head, *pki, entry);
236 pki = NULL;
237 break;
238 case IMSG_RECONF_LISTEN:
239 if (*nconf == NULL)
240 fatalx("%s: IMSG_RECONF_LISTEN without "
241 "IMSG_RECONF_CONF", __func__);
242 if (IMSG_DATA_SIZE(*imsg) != sizeof(*listen))
243 fatalx("%s: IMSG_RECONF_LISTEN wrong length: %lu",
244 __func__, IMSG_DATA_SIZE(*imsg));
245 listen = xcalloc(1, sizeof(*listen));
246 memcpy(listen, imsg->data, sizeof(*listen));
247 memset(&listen->entry, 0, sizeof(listen->entry));
248 if ((listen->fd = imsg->fd) == -1)
249 fatalx("%s: IMSG_RECONF_LISTEN no fd",
250 __func__);
251 listen->auth_table = NULL;
252 memset(&listen->ev, 0, sizeof(listen->ev));
253 STAILQ_INSERT_HEAD(&(*nconf)->listen_head, listen, entry);
254 break;
255 case IMSG_RECONF_END:
256 if (*nconf == NULL)
257 fatalx("%s: IMSG_RECONF_END without "
258 "IMSG_RECONF_CONF", __func__);
259 apply_config(*nconf);
260 *nconf = NULL;
261 break;
265 void
266 listener_dispatch_main(int fd, short event, void *d)
268 static struct kd_conf *nconf;
269 static struct kd_pki_conf *pki;
270 struct client *client, find;
271 struct imsg imsg;
272 struct imsgev *iev = d;
273 struct imsgbuf *ibuf;
274 ssize_t n;
275 int shut = 0;
277 ibuf = &iev->ibuf;
279 if (event & EV_READ) {
280 if ((n = imsg_read(ibuf)) == -1 && errno != EAGAIN)
281 fatal("imsg_read error");
282 if (n == 0) /* Connection closed. */
283 shut = 1;
285 if (event & EV_WRITE) {
286 if ((n = msgbuf_write(&ibuf->w)) == -1 && errno != EAGAIN)
287 fatal("msgbuf_write");
288 if (n == 0) /* Connection closed. */
289 shut = 1;
292 for (;;) {
293 if ((n = imsg_get(ibuf, &imsg)) == -1)
294 fatal("%s: imsg_get error", __func__);
295 if (n == 0) /* No more messages. */
296 break;
298 switch (imsg.hdr.type) {
299 case IMSG_CTL_LOG_VERBOSE:
300 if (IMSG_DATA_SIZE(imsg) != sizeof(verbose))
301 fatalx("wrong size for IMSG_CTL_LOG_VERBOSE");
302 memcpy(&verbose, imsg.data, sizeof(verbose));
303 log_setverbose(verbose);
304 SPLAY_FOREACH(client, clients_tree_id, &clients)
305 listener_imsg_compose_client(client,
306 imsg.hdr.type, 0,
307 &verbose, sizeof(verbose));
308 break;
309 case IMSG_CTL_DEBUG:
310 if (SPLAY_EMPTY(&clients))
311 listener_imsg_compose_main(IMSG_CTL_DEBUG_END,
312 imsg.hdr.peerid, NULL, 0);
313 SPLAY_FOREACH(client, clients_tree_id, &clients)
314 listener_imsg_compose_client(client,
315 imsg.hdr.type, imsg.hdr.peerid,
316 imsg.data, IMSG_DATA_SIZE(imsg));
317 break;
318 case IMSG_RECONF_CONF:
319 case IMSG_RECONF_PKI:
320 case IMSG_RECONF_PKI_CERT:
321 case IMSG_RECONF_PKI_KEY:
322 case IMSG_RECONF_LISTEN:
323 case IMSG_RECONF_END:
324 listener_receive_config(&imsg, &nconf, &pki);
325 break;
326 case IMSG_AUTH:
327 if (IMSG_DATA_SIZE(imsg) != sizeof(struct kd_auth_proc))
328 fatalx("mismatching size for IMSG_AUTH");
330 find.id = imsg.hdr.peerid;
331 client = SPLAY_FIND(clients_tree_id, &clients, &find);
332 if (client == NULL) {
333 if (imsg.fd != -1)
334 close(imsg.fd);
335 break;
337 if (imsg.fd == -1) {
338 log_info("got fd = -1, auth failed?");
339 close_conn(client);
340 break;
342 imsg_init(&client->iev.ibuf, imsg.fd);
343 client->iev.events = EV_READ;
344 client->iev.handler = listener_dispatch_client;
345 event_set(&client->iev.ev, client->iev.ibuf.fd,
346 client->iev.events, client->iev.handler, client);
347 listener_imsg_compose_client(client, IMSG_AUTH,
348 client->id, imsg.data, IMSG_DATA_SIZE(imsg));
350 client->bev = bufferevent_new(client->fd,
351 client_read, client_write, client_error,
352 client);
353 if (client->bev == NULL) {
354 log_info("failed to allocate client buffer");
355 close_conn(client);
356 return;
359 #if HAVE_EVENT2
360 evbuffer_unfreeze(client->bev->input, 0);
361 evbuffer_unfreeze(client->bev->output, 1);
362 #endif
364 if (client->lflags & L_TLS) {
365 event_set(&client->bev->ev_read, client->fd,
366 EV_READ, client_tls_readcb, client->bev);
367 event_set(&client->bev->ev_write, client->fd,
368 EV_WRITE, client_tls_writecb, client->bev);
371 /*
372 * Read or write at least a header before
373 * firing the callbacks. High watermark of 0
374 * to never stop reading/writing; probably to
375 * be revisited.
376 */
377 /* bufferevent_setwatermark(client->bev, EV_READ|EV_WRITE, */
378 /* sizeof(struct np_msg_header), 0); */
379 bufferevent_enable(client->bev, EV_READ|EV_WRITE);
380 break;
382 default:
383 log_debug("%s: unexpected imsg %d", __func__,
384 imsg.hdr.type);
385 break;
387 imsg_free(&imsg);
390 if (!shut)
391 listener_imsg_event_add(iev, d);
392 else {
393 /* This pipe is dead. Remove its event handler. */
394 event_del(&iev->ev);
395 log_warnx("pipe closed, shutting down...");
396 event_loopexit(NULL);
400 int
401 listener_imsg_compose_main(int type, uint32_t peerid, const void *data,
402 uint16_t datalen)
404 return imsg_compose_event(iev_main, type, peerid, 0, -1, data,
405 datalen);
408 static void
409 listener_imsg_event_add(struct imsgev *iev, void *d)
411 iev->events = EV_READ;
412 if (iev->ibuf.w.queued)
413 iev->events |= EV_WRITE;
415 event_del(&iev->ev);
416 event_set(&iev->ev, iev->ibuf.fd, iev->events, iev->handler, d);
417 event_add(&iev->ev, NULL);
420 static void
421 listener_dispatch_client(int fd, short event, void *d)
423 struct client find, *client = d;
424 struct imsg imsg;
425 struct imsgev *iev;
426 struct imsgbuf *ibuf;
427 ssize_t n;
428 int r, shut = 0;
430 iev = &client->iev;
431 ibuf = &iev->ibuf;
433 if (event & EV_READ) {
434 if ((n = imsg_read(ibuf)) == -1 && errno != EAGAIN)
435 fatal("imsg_read error");
436 if (n == 0) /* Connection closed */
437 shut = 1;
440 if (event & EV_WRITE) {
441 if ((n = msgbuf_write(&ibuf->w)) == -1 && errno != EAGAIN)
442 fatal("msgbuf_write");
443 if (n == 0) /* Connection closed. */
444 shut = 1;
447 for (;;) {
448 if ((n = imsg_get(ibuf, &imsg)) == -1)
449 fatal("%s: imsg_get error", __func__);
450 if (n == 0) /* No more messages. */
451 break;
453 switch (imsg.hdr.type) {
454 case IMSG_CTL_DEBUG_BACK:
455 case IMSG_CTL_DEBUG_END:
456 listener_imsg_compose_main(imsg.hdr.type,
457 imsg.hdr.peerid, imsg.data, IMSG_DATA_SIZE(imsg));
458 break;
460 case IMSG_BUF:
461 find.id = imsg.hdr.peerid;
462 client = SPLAY_FIND(clients_tree_id, &clients, &find);
463 if (client == NULL) {
464 log_info("got IMSG_BUF but client %d gone",
465 imsg.hdr.peerid);
466 break;
468 r = bufferevent_write(client->bev, imsg.data,
469 IMSG_DATA_SIZE(imsg));
470 if (r == -1) {
471 log_warn("%s: bufferevent_write failed",
472 __func__);
473 close_conn(client);
474 break;
476 break;
478 case IMSG_MSIZE:
479 if (IMSG_DATA_SIZE(imsg) != sizeof(client->msize))
480 fatal("IMSG_MSIZE size mismatch: "
481 "got %zu want %zu", IMSG_DATA_SIZE(imsg),
482 sizeof(client->msize));
484 memcpy(&client->msize, imsg.data,
485 sizeof(client->msize));
487 if (client->msize == 0)
488 fatal("IMSG_MSIZE got msize = 0");
489 log_debug("set msize to %d", client->msize);
490 break;
492 case IMSG_CLOSE:
493 /*
494 * Both EVBUFFER_READ or EVBUFFER_WRITE should
495 * be fine.
496 */
497 client_error(client->bev, EVBUFFER_READ, client);
498 break;
500 default:
501 log_debug("%s: unexpected imsg %d", __func__,
502 imsg.hdr.type);
503 break;
505 imsg_free(&imsg);
508 if (!shut)
509 listener_imsg_event_add(iev, d);
510 else {
511 /* This pipe is dead. Remove its handler */
512 log_debug("client proc vanished");
513 close_conn(client);
517 static int
518 listener_imsg_compose_client(struct client *client, int type,
519 uint32_t peerid, const void *data, uint16_t len)
521 int ret;
523 if ((ret = imsg_compose(&client->iev.ibuf, type, peerid, 0, -1,
524 data, len)) != -1)
525 listener_imsg_event_add(&client->iev, client);
527 return ret;
530 static inline struct kd_pki_conf *
531 pki_by_name(const char *name)
533 struct kd_pki_conf *pki;
535 STAILQ_FOREACH(pki, &listener_conf->pki_head, entry) {
536 if (!strcmp(name, pki->name))
537 return pki;
540 return NULL;
543 static void
544 apply_config(struct kd_conf *conf)
546 struct kd_pki_conf *pki;
547 struct kd_listen_conf *listen;
548 struct client *c;
550 /* drop any pre-auth inflight connections */
551 SPLAY_FOREACH(c, clients_tree_id, &clients) {
552 /*
553 * c->event is set only during the handshake and the teardown
554 * of the connection; c->bev is set only after auth. Checking
555 * for both ensures we drop only incoming connection in the
556 * pre-auth state.
557 */
558 if (event_pending(&c->event, EV_READ|EV_WRITE, NULL) &&
559 c->bev == NULL) {
560 log_warn("closing in-flight connection due to reload");
561 close_conn(c);
565 /* swap the now config with the current one */
566 clear_config(listener_conf);
567 listener_conf = conf;
569 /* prepare the various tls_config */
570 STAILQ_FOREACH(pki, &listener_conf->pki_head, entry) {
571 if ((pki->tlsconf = tls_config_new()) == NULL)
572 fatal("tls_config_new");
573 tls_config_verify_client_optional(pki->tlsconf);
574 tls_config_insecure_noverifycert(pki->tlsconf);
575 if (tls_config_set_keypair_mem(pki->tlsconf,
576 pki->cert, pki->certlen,
577 pki->key, pki->keylen) == -1)
578 fatalx("tls_config_set_keypair_mem: %s",
579 tls_config_error(pki->tlsconf));
582 /* prepare and kickoff the listeners */
583 STAILQ_FOREACH(listen, &listener_conf->listen_head, entry) {
584 if ((listen->ctx = tls_server()) == NULL)
585 fatal("tls_server");
587 pki = pki_by_name(listen->pki);
588 if (tls_configure(listen->ctx, pki->tlsconf) == -1)
589 fatalx("tls_configure: %s",
590 tls_config_error(pki->tlsconf));
592 event_set(&listen->ev, listen->fd, EV_READ|EV_PERSIST,
593 handle_accept, listen);
594 event_add(&listen->ev, NULL);
598 static inline void
599 yield_r(struct client *c, void (*fn)(int, short, void *))
601 if (event_pending(&c->event, EV_WRITE|EV_READ, NULL))
602 event_del(&c->event);
603 event_set(&c->event, c->fd, EV_READ, fn, c);
604 event_add(&c->event, NULL);
607 static inline void
608 yield_w(struct client *c, void (*fn)(int, short, void *))
610 if (event_pending(&c->event, EV_WRITE|EV_READ, NULL))
611 event_del(&c->event);
612 event_set(&c->event, c->fd, EV_WRITE, fn, c);
613 event_add(&c->event, NULL);
616 static void
617 handle_accept(int fd, short ev, void *data)
619 static uint32_t counter;
620 struct kd_listen_conf *listen = data;
621 struct client *c;
622 int s;
624 if ((s = accept(fd, NULL, NULL)) == -1) {
625 log_warn("accept");
626 return;
629 c = xcalloc(1, sizeof(*c));
630 c->msize = MSIZE9P;
631 c->lid = listen->id;
632 c->lflags = listen->flags;
633 c->iev.ibuf.fd = -1;
635 if (tls_accept_socket(listen->ctx, &c->ctx, s) == -1) {
636 log_warnx("tls_accept_socket: %s",
637 tls_error(listen->ctx));
638 free(c);
639 close(s);
640 return;
643 c->fd = s;
644 c->id = counter++;
646 SPLAY_INSERT(clients_tree_id, &clients, c);
648 /* initialize the event */
649 event_set(&c->event, c->fd, EV_READ, NULL, NULL);
651 yield_r(c, handle_handshake);
654 static void
655 handle_handshake(int fd, short ev, void *data)
657 struct client *c = data;
658 struct kd_auth_req auth;
659 ssize_t r;
660 const char *hash;
662 switch (r = tls_handshake(c->ctx)) {
663 case TLS_WANT_POLLIN:
664 yield_r(c, handle_handshake);
665 return;
666 case TLS_WANT_POLLOUT:
667 yield_w(c, handle_handshake);
668 return;
669 case -1:
670 log_debug("handhsake failed: %s", tls_error(c->ctx));
671 close_conn(c);
672 return;
675 if ((hash = tls_peer_cert_hash(c->ctx)) == NULL) {
676 log_warnx("client didn't provide certificate");
677 close_conn(c);
678 return;
681 memset(&auth, 0, sizeof(auth));
682 auth.listen_id = c->lid;
683 strlcpy(auth.hash, hash, sizeof(auth.hash));
684 log_debug("sending hash %s", auth.hash);
686 listener_imsg_compose_main(IMSG_AUTH_TLS, c->id,
687 &auth, sizeof(auth));
690 static void
691 client_read(struct bufferevent *bev, void *d)
693 struct client *client = d;
694 struct evbuffer *src = EVBUFFER_INPUT(bev);
695 size_t evlen;
696 uint32_t len;
698 for (;;) {
699 evlen = EVBUFFER_LENGTH(src);
701 if (client->left != 0) {
702 /* wait to fill a whole imsg if possible */
703 if (client->left >= IMSG_MAXSIZE &&
704 evlen < IMSG_MAXSIZE)
705 return;
707 len = MIN(client->left, evlen);
708 len = MIN(len, IMSG_MAXSIZE);
710 listener_imsg_compose_client(client, IMSG_BUF_CONT,
711 client->id, EVBUFFER_DATA(src), len);
712 evbuffer_drain(src, len);
713 client->left -= len;
714 continue;
717 if (evlen < 4)
718 return;
720 memcpy(&len, EVBUFFER_DATA(src), sizeof(len));
721 len = le32toh(len);
722 log_debug("expecting a message %"PRIu32" bytes long "
723 "(of wich %zu already read)", len, evlen);
725 if (len < HEADERSIZE) {
726 log_warnx("invalid message size %d (too low)", len);
727 client_error(bev, EVBUFFER_READ, client);
728 return;
731 if (len > client->msize) {
732 log_warnx("incoming message bigger than msize "
733 "(%"PRIu32" vs %"PRIu32")", len, client->msize);
734 client_error(bev, EVBUFFER_READ, client);
735 return;
738 if (len > IMSG_MAXSIZE && evlen >= len) {
739 listener_imsg_compose_client(client, IMSG_BUF,
740 client->id, EVBUFFER_DATA(src), IMSG_MAXSIZE);
741 evbuffer_drain(src, IMSG_MAXSIZE);
742 client->left = len - IMSG_MAXSIZE;
743 continue;
746 if (len > evlen)
747 return;
749 listener_imsg_compose_client(client, IMSG_BUF, client->id,
750 EVBUFFER_DATA(src), len);
751 evbuffer_drain(src, len);
755 static void
756 client_write(struct bufferevent *bev, void *d)
758 /*
759 * here we can do some fancy logic like deciding when to call
761 * (*bev->errorcb)(bev, EVBUFFER_WRITE, bev->cbarg)
763 * to signal the end of the transaction.
764 */
766 return;
769 static void
770 client_error(struct bufferevent *bev, short err, void *d)
772 struct client *client = d;
773 struct evbuffer *buf;
775 if (err & EVBUFFER_ERROR) {
776 if (errno == EFBIG) {
777 bufferevent_enable(bev, EV_READ);
778 return;
780 log_debug("buffer event error");
781 close_conn(client);
782 return;
785 if (err & EVBUFFER_EOF) {
786 close_conn(client);
787 return;
790 if (err & (EVBUFFER_READ|EVBUFFER_WRITE)) {
791 bufferevent_disable(bev, EV_READ|EV_WRITE);
793 buf = EVBUFFER_OUTPUT(client->bev);
794 if (EVBUFFER_LENGTH(buf) != 0) {
795 /* finish writing all the data first */
796 bufferevent_enable(client->bev, EV_WRITE);
797 return;
800 close_conn(client);
801 return;
804 log_warnx("unknown event error, closing client connection");
805 close_conn(client);
808 static void
809 client_tls_readcb(int fd, short event, void *d)
811 struct bufferevent *bufev = d;
812 struct client *client = bufev->cbarg;
813 char buf[IBUF_READ_SIZE];
814 int what = EVBUFFER_READ;
815 int howmuch = IBUF_READ_SIZE;
816 ssize_t ret;
817 size_t len;
819 if (event == EV_TIMEOUT) {
820 what |= EVBUFFER_TIMEOUT;
821 goto err;
824 if (bufev->wm_read.high != 0)
825 howmuch = MIN(sizeof(buf), bufev->wm_read.high);
827 switch (ret = tls_read(client->ctx, buf, howmuch)) {
828 case TLS_WANT_POLLIN:
829 case TLS_WANT_POLLOUT:
830 goto retry;
831 case -1:
832 what |= EVBUFFER_ERROR;
833 goto err;
835 len = ret;
837 if (len == 0) {
838 what |= EVBUFFER_EOF;
839 goto err;
842 if (evbuffer_add(bufev->input, buf, len) == -1) {
843 what |= EVBUFFER_ERROR;
844 goto err;
847 event_add(&bufev->ev_read, NULL);
849 len = EVBUFFER_LENGTH(bufev->input);
850 if (bufev->wm_read.low != 0 && len < bufev->wm_read.low)
851 return;
852 if (bufev->wm_read.high != 0 && len > bufev->wm_read.high) {
853 /*
854 * here we could implement some read pressure
855 * mechanism.
856 */
859 if (bufev->readcb != NULL)
860 (*bufev->readcb)(bufev, bufev->cbarg);
862 return;
864 retry:
865 event_add(&bufev->ev_read, NULL);
866 return;
868 err:
869 (*bufev->errorcb)(bufev, what, bufev->cbarg);
872 static void
873 client_tls_writecb(int fd, short event, void *d)
875 struct bufferevent *bufev = d;
876 struct client *client = bufev->cbarg;
877 ssize_t ret;
878 size_t len;
879 short what = EVBUFFER_WRITE;
881 if (event == EV_TIMEOUT) {
882 what |= EVBUFFER_TIMEOUT;
883 goto err;
886 if (EVBUFFER_LENGTH(bufev->output) != 0) {
887 ret = tls_write(client->ctx,
888 EVBUFFER_DATA(bufev->output),
889 EVBUFFER_LENGTH(bufev->output));
890 switch (ret) {
891 case TLS_WANT_POLLIN:
892 case TLS_WANT_POLLOUT:
893 goto retry;
894 case -1:
895 what |= EVBUFFER_ERROR;
896 goto err;
898 len = ret;
899 evbuffer_drain(bufev->output, len);
902 if (EVBUFFER_LENGTH(bufev->output) != 0)
903 event_add(&bufev->ev_write, NULL);
905 if (bufev->writecb != NULL &&
906 EVBUFFER_LENGTH(bufev->output) <= bufev->wm_write.low)
907 (*bufev->writecb)(bufev, bufev->cbarg);
908 return;
910 retry:
911 event_add(&bufev->ev_write, NULL);
912 return;
914 err:
915 (*bufev->errorcb)(bufev, what, bufev->cbarg);
918 static void
919 close_conn(struct client *c)
921 log_debug("closing connection");
923 SPLAY_REMOVE(clients_tree_id, &clients, c);
925 if (c->iev.ibuf.fd != -1) {
926 listener_imsg_compose_client(c, IMSG_CONN_GONE, 0, NULL, 0);
927 imsg_flush(&c->iev.ibuf);
928 msgbuf_clear(&c->iev.ibuf.w);
929 event_del(&c->iev.ev);
930 close(c->iev.ibuf.fd);
933 handle_close(c->fd, 0, c);
936 static void
937 handle_close(int fd, short ev, void *d)
939 struct client *c = d;
941 switch (tls_close(c->ctx)) {
942 case TLS_WANT_POLLIN:
943 yield_r(c, handle_close);
944 return;
945 case TLS_WANT_POLLOUT:
946 yield_w(c, handle_close);
947 return;
950 event_del(&c->event);
951 tls_free(c->ctx);
952 close(c->fd);
953 free(c);