Blob


1 /*
2 * Copyright (c) 2021 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>
25 #include <endian.h>
26 #include <errno.h>
27 #include <inttypes.h>
28 #include <pwd.h>
29 #include <signal.h>
30 #include <stdio.h>
31 #include <stdlib.h>
32 #include <string.h>
33 #include <syslog.h>
34 #include <unistd.h>
36 #include "control.h"
37 #include "kamid.h"
38 #include "listener.h"
39 #include "log.h"
40 #include "sandbox.h"
41 #include "utils.h"
43 static struct kd_conf *listener_conf;
44 static struct imsgev *iev_main;
46 static void listener_sig_handler(int, short, void *);
47 ATTR_DEAD void listener_shutdown(void);
49 SPLAY_HEAD(clients_tree_id, client) clients;
51 struct client {
52 uint32_t id;
53 uint32_t lid;
54 uint32_t msize;
55 int fd;
56 int done;
57 struct tls *ctx;
58 struct event event;
59 struct imsgev iev;
60 struct bufferevent *bev;
61 SPLAY_ENTRY(client) sp_entry;
62 };
64 static void listener_imsg_event_add(struct imsgev *, void *);
65 static void listener_dispatch_client(int, short, void *);
66 static int listener_imsg_compose_client(struct client *, int,
67 uint32_t, const void *, uint16_t);
69 static void apply_config(struct kd_conf *);
70 static void handle_accept(int, short, void *);
72 static void handle_handshake(int, short, void *);
73 static void client_read(struct bufferevent *, void *);
74 static void client_write(struct bufferevent *, void *);
75 static void client_error(struct bufferevent *, short, void *);
76 static void client_tls_readcb(int, short, void *);
77 static void client_tls_writecb(int, short, void *);
78 static void close_conn(struct client *);
79 static void handle_close(int, short, void *);
81 static inline int
82 clients_tree_cmp(struct client *a, struct client *b)
83 {
84 if (a->id == b->id)
85 return 0;
86 else if (a->id < b->id)
87 return -1;
88 else
89 return +1;
90 }
92 SPLAY_PROTOTYPE(clients_tree_id, client, sp_entry, clients_tree_cmp);
93 SPLAY_GENERATE(clients_tree_id, client, sp_entry, clients_tree_cmp)
95 static void
96 listener_sig_handler(int sig, short event, void *d)
97 {
98 /*
99 * Normal signal handler rules don't apply because libevent
100 * decouples for us.
101 */
103 switch (sig) {
104 case SIGINT:
105 case SIGTERM:
106 listener_shutdown();
107 default:
108 fatalx("unexpected signal %d", sig);
112 void
113 listener(int debug, int verbose)
115 struct event ev_sigint, ev_sigterm;
116 struct passwd *pw;
118 /* listener_conf = config_new_empty(); */
120 log_init(debug, LOG_DAEMON);
121 log_setverbose(verbose);
123 if ((pw = getpwnam(KD_USER)) == NULL)
124 fatal("getpwnam");
126 if (chroot(pw->pw_dir) == -1)
127 fatal("chroot");
128 if (chdir("/") == -1)
129 fatal("chdir(\"/\")");
131 setproctitle("listener");
132 log_procinit("listener");
134 if (setgroups(1, &pw->pw_gid) ||
135 setresgid(pw->pw_gid, pw->pw_gid, pw->pw_gid) ||
136 setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid))
137 fatal("can't drop privileges");
139 event_init();
141 /* Setup signal handlers(s). */
142 signal_set(&ev_sigint, SIGINT, listener_sig_handler, NULL);
143 signal_set(&ev_sigterm, SIGTERM, listener_sig_handler, NULL);
145 signal_add(&ev_sigint, NULL);
146 signal_add(&ev_sigterm, NULL);
148 signal(SIGPIPE, SIG_IGN);
149 signal(SIGHUP, SIG_IGN);
151 /* Setup pipe and event handler to the main process. */
152 if ((iev_main = malloc(sizeof(*iev_main))) == NULL)
153 fatal(NULL);
155 imsg_init(&iev_main->ibuf, 3);
156 iev_main->handler = listener_dispatch_main;
158 /* Setup event handlers. */
159 iev_main->events = EV_READ;
160 event_set(&iev_main->ev, iev_main->ibuf.fd, iev_main->events,
161 iev_main->handler, iev_main);
162 event_add(&iev_main->ev, NULL);
164 sandbox_listener();
165 event_dispatch();
166 listener_shutdown();
169 ATTR_DEAD void
170 listener_shutdown(void)
172 msgbuf_clear(&iev_main->ibuf.w);
173 close(iev_main->ibuf.fd);
175 config_clear(listener_conf);
177 free(iev_main);
179 log_info("listener exiting");
180 exit(0);
183 static void
184 listener_receive_config(struct imsg *imsg, struct kd_conf **nconf,
185 struct kd_pki_conf **pki)
187 struct kd_listen_conf *listen;
188 char *t;
190 switch (imsg->hdr.type) {
191 case IMSG_RECONF_CONF:
192 if (*nconf != NULL)
193 fatalx("%s: IMSG_RECONF_CONF already in "
194 "progress", __func__);
196 if (listener_conf != NULL)
197 fatalx("%s: don't know how reload the "
198 "configuration yet", __func__);
200 if (IMSG_DATA_SIZE(*imsg) != sizeof(struct kd_conf))
201 fatalx("%s: IMSG_RECONF_CONF wrong length: %lu",
202 __func__, IMSG_DATA_SIZE(*imsg));
203 if ((*nconf = malloc(sizeof(**nconf))) == NULL)
204 fatal(NULL);
205 memcpy(*nconf, imsg->data, sizeof(**nconf));
206 memset(&(*nconf)->pki_head, 0, sizeof((*nconf)->pki_head));
207 memset(&(*nconf)->table_head, 0, sizeof((*nconf)->table_head));
208 memset(&(*nconf)->listen_head, 0, sizeof((*nconf)->listen_head));
209 break;
210 case IMSG_RECONF_PKI:
211 if (*nconf == NULL)
212 fatalx("%s: IMSG_RECONF_PKI without "
213 "IMSG_RECONF_CONF", __func__);
214 *pki = xcalloc(1, sizeof(**pki));
215 t = imsg->data;
216 t[IMSG_DATA_SIZE(*imsg)-1] = '\0';
217 strlcpy((*pki)->name, t, sizeof((*pki)->name));
218 break;
219 case IMSG_RECONF_PKI_CERT:
220 if (*pki == NULL)
221 fatalx("%s: IMSG_RECONF_PKI_CERT without "
222 "IMSG_RECONF_PKI", __func__);
223 (*pki)->certlen = IMSG_DATA_SIZE(*imsg);
224 (*pki)->cert = xmemdup(imsg->data, (*pki)->certlen);
225 break;
226 case IMSG_RECONF_PKI_KEY:
227 if (*pki == NULL)
228 fatalx("%s: IMSG_RECONF_PKI_KEY without "
229 "IMSG_RECONF_PKI", __func__);
230 (*pki)->keylen = IMSG_DATA_SIZE(*imsg);
231 (*pki)->key = xmemdup(imsg->data, (*pki)->keylen);
232 STAILQ_INSERT_HEAD(&(*nconf)->pki_head, *pki, entry);
233 pki = NULL;
234 break;
235 case IMSG_RECONF_LISTEN:
236 if (*nconf == NULL)
237 fatalx("%s: IMSG_RECONF_LISTEN without "
238 "IMSG_RECONF_CONF", __func__);
239 if (IMSG_DATA_SIZE(*imsg) != sizeof(*listen))
240 fatalx("%s: IMSG_RECONF_LISTEN wrong length: %lu",
241 __func__, IMSG_DATA_SIZE(*imsg));
242 listen = xcalloc(1, sizeof(*listen));
243 memcpy(listen, imsg->data, sizeof(*listen));
244 memset(&listen->entry, 0, sizeof(listen->entry));
245 if ((listen->fd = imsg->fd) == -1)
246 fatalx("%s: IMSG_RECONF_LISTEN no fd",
247 __func__);
248 listen->auth_table = NULL;
249 memset(&listen->ev, 0, sizeof(listen->ev));
250 STAILQ_INSERT_HEAD(&(*nconf)->listen_head, listen, entry);
251 break;
252 case IMSG_RECONF_END:
253 if (*nconf == NULL)
254 fatalx("%s: IMSG_RECONF_END without "
255 "IMSG_RECONF_CONF", __func__);
256 /* merge_config(listener_conf, nconf); */
257 apply_config(*nconf);
258 *nconf = NULL;
259 break;
263 static inline struct kd_listen_conf *
264 listen_by_id(uint32_t id)
266 struct kd_listen_conf *l;
268 STAILQ_FOREACH(l, &listener_conf->listen_head, entry) {
269 if (l->id == id)
270 return l;
272 return NULL;
275 void
276 listener_dispatch_main(int fd, short event, void *d)
278 static struct kd_conf *nconf;
279 static struct kd_pki_conf *pki;
280 struct kd_listen_conf *listen;
281 struct client *client, find;
282 struct imsg imsg;
283 struct imsgev *iev = d;
284 struct imsgbuf *ibuf;
285 ssize_t n;
286 int shut = 0;
288 ibuf = &iev->ibuf;
290 if (event & EV_READ) {
291 if ((n = imsg_read(ibuf)) == -1 && errno != EAGAIN)
292 fatal("imsg_read error");
293 if (n == 0) /* Connection closed. */
294 shut = 1;
296 if (event & EV_WRITE) {
297 if ((n = msgbuf_write(&ibuf->w)) == -1 && errno != EAGAIN)
298 fatal("msgbuf_write");
299 if (n == 0) /* Connection closed. */
300 shut = 1;
303 for (;;) {
304 if ((n = imsg_get(ibuf, &imsg)) == -1)
305 fatal("%s: imsg_get error", __func__);
306 if (n == 0) /* No more messages. */
307 break;
309 switch (imsg.hdr.type) {
310 case IMSG_CONTROLFD:
311 if ((fd = imsg.fd) == -1)
312 fatalx("%s: expected to receive imsg "
313 "control fd but didn't receive any",
314 __func__);
315 /* Listen on control socket. */
316 control_listen(fd);
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 find.id = imsg.hdr.peerid;
328 client = SPLAY_FIND(clients_tree_id, &clients, &find);
329 if (client == NULL) {
330 if (imsg.fd != -1)
331 close(imsg.fd);
332 break;
334 if (imsg.fd == -1) {
335 log_info("got fd = -1, auth failed?");
336 close_conn(client);
337 break;
339 imsg_init(&client->iev.ibuf, imsg.fd);
340 client->iev.events = EV_READ;
341 client->iev.handler = listener_dispatch_client;
342 event_set(&client->iev.ev, client->iev.ibuf.fd,
343 client->iev.events, client->iev.handler, client);
344 listener_imsg_compose_client(client, IMSG_AUTH,
345 client->id, imsg.data, IMSG_DATA_SIZE(imsg));
346 break;
347 case IMSG_AUTH_DIR:
348 find.id = imsg.hdr.peerid;
349 client = SPLAY_FIND(clients_tree_id, &clients, &find);
350 if (client == NULL) {
351 log_info("got AUTH_DIR but client gone");
352 break;
355 listener_imsg_compose_client(client, IMSG_AUTH_DIR,
356 0, imsg.data, IMSG_DATA_SIZE(imsg));
358 client->bev = bufferevent_new(client->fd,
359 client_read, client_write, client_error,
360 client);
361 if (client->bev == NULL) {
362 log_info("failed to allocate client buffer");
363 close_conn(client);
364 return;
367 #if HAVE_EVENT2
368 evbuffer_unfreeze(client->bev->input, 0);
369 evbuffer_unfreeze(client->bev->output, 1);
370 #endif
372 listen = listen_by_id(client->lid);
373 if (listen->flags & L_TLS) {
374 event_set(&client->bev->ev_read, client->fd,
375 EV_READ, client_tls_readcb, client->bev);
376 event_set(&client->bev->ev_write, client->fd,
377 EV_WRITE, client_tls_writecb, client->bev);
380 /*
381 * Read or write at least a header before
382 * firing the callbacks. High watermark of 0
383 * to never stop reading/writing; probably to
384 * be revisited.
385 */
386 /* bufferevent_setwatermark(client->bev, EV_READ|EV_WRITE, */
387 /* sizeof(struct np_msg_header), 0); */
388 bufferevent_enable(client->bev, EV_READ|EV_WRITE);
389 break;
391 default:
392 log_debug("%s: unexpected imsg %d", __func__,
393 imsg.hdr.type);
394 break;
396 imsg_free(&imsg);
399 if (!shut)
400 listener_imsg_event_add(iev, d);
401 else {
402 /* This pipe is dead. Remove its event handler. */
403 event_del(&iev->ev);
404 log_warnx("pipe closed, shutting down...");
405 event_loopexit(NULL);
409 int
410 listener_imsg_compose_main(int type, uint32_t peerid, const void *data,
411 uint16_t datalen)
413 return imsg_compose_event(iev_main, type, peerid, 0, -1, data,
414 datalen);
417 static void
418 listener_imsg_event_add(struct imsgev *iev, void *d)
420 iev->events = EV_READ;
421 if (iev->ibuf.w.queued)
422 iev->events |= EV_WRITE;
424 event_del(&iev->ev);
425 event_set(&iev->ev, iev->ibuf.fd, iev->events, iev->handler, d);
426 event_add(&iev->ev, NULL);
429 static void
430 listener_dispatch_client(int fd, short event, void *d)
432 struct client find, *client = d;
433 struct imsg imsg;
434 struct imsgev *iev;
435 struct imsgbuf *ibuf;
436 ssize_t n;
437 int r, shut = 0;
439 iev = &client->iev;
440 ibuf = &iev->ibuf;
442 if (event & EV_READ) {
443 if ((n = imsg_read(ibuf)) == -1 && errno != EAGAIN)
444 fatal("imsg_read error");
445 if (n == 0) /* Connection closed */
446 shut = 1;
449 if (event & EV_WRITE) {
450 if ((n = msgbuf_write(&ibuf->w)) == -1 && errno != EAGAIN)
451 fatal("msgbuf_write");
452 if (n == 0) /* Connection closed. */
453 shut = 1;
456 for (;;) {
457 if ((n = imsg_get(ibuf, &imsg)) == -1)
458 fatal("%s: imsg_get error", __func__);
459 if (n == 0) /* No more messages. */
460 break;
462 switch (imsg.hdr.type) {
463 case IMSG_BUF:
464 find.id = imsg.hdr.peerid;
465 client = SPLAY_FIND(clients_tree_id, &clients, &find);
466 if (client == NULL) {
467 log_info("got IMSG_BUF but client (%d) gone",
468 imsg.hdr.peerid);
469 break;
471 r = bufferevent_write(client->bev, imsg.data,
472 IMSG_DATA_SIZE(imsg));
473 if (r == -1) {
474 log_warn("%s: bufferevent_write failed",
475 __func__);
476 close_conn(client);
477 break;
479 break;
481 case IMSG_MSIZE:
482 if (IMSG_DATA_SIZE(imsg) != sizeof(client->msize))
483 fatal("IMSG_MSIZE size mismatch: "
484 "got %zu want %zu", IMSG_DATA_SIZE(imsg),
485 sizeof(client->msize));
487 memcpy(&client->msize, imsg.data,
488 sizeof(client->msize));
490 if (client->msize == 0)
491 fatal("IMSG_MSIZE got msize = 0");
493 break;
495 case IMSG_CLOSE:
496 /*
497 * Both EVBUFFER_READ or EVBUFFER_WRITE should
498 * be fine.
499 */
500 client_error(client->bev, EVBUFFER_READ, client);
501 break;
503 default:
504 log_debug("%s: unexpected imsg %d", __func__,
505 imsg.hdr.type);
506 break;
508 imsg_free(&imsg);
511 if (!shut)
512 listener_imsg_event_add(iev, d);
513 else {
514 /* This pipe is dead. Remove its handler */
515 log_debug("client proc vanished");
516 close_conn(client);
520 static int
521 listener_imsg_compose_client(struct client *client, int type,
522 uint32_t peerid, const void *data, uint16_t len)
524 int ret;
526 if ((ret = imsg_compose(&client->iev.ibuf, type, peerid, 0, -1,
527 data, len)) != -1)
528 listener_imsg_event_add(&client->iev, client);
530 return ret;
533 static inline struct kd_pki_conf *
534 pki_by_name(const char *name)
536 struct kd_pki_conf *pki;
538 STAILQ_FOREACH(pki, &listener_conf->pki_head, entry) {
539 if (!strcmp(name, pki->name))
540 return pki;
543 return NULL;
546 static void
547 apply_config(struct kd_conf *conf)
549 struct kd_pki_conf *pki;
550 struct kd_listen_conf *listen;
552 listener_conf = conf;
554 /* prepare the various tls_config */
555 STAILQ_FOREACH(pki, &listener_conf->pki_head, entry) {
556 if ((pki->tlsconf = tls_config_new()) == NULL)
557 fatal("tls_config_new");
558 tls_config_verify_client_optional(pki->tlsconf);
559 tls_config_insecure_noverifycert(pki->tlsconf);
560 if (tls_config_set_keypair_mem(pki->tlsconf,
561 pki->cert, pki->certlen,
562 pki->key, pki->keylen) == -1)
563 fatalx("tls_config_set_keypair_mem: %s",
564 tls_config_error(pki->tlsconf));
567 /* prepare and kickoff the listeners */
568 STAILQ_FOREACH(listen, &listener_conf->listen_head, entry) {
569 if ((listen->ctx = tls_server()) == NULL)
570 fatal("tls_server");
572 pki = pki_by_name(listen->pki);
573 if (tls_configure(listen->ctx, pki->tlsconf) == -1)
574 fatalx("tls_configure: %s",
575 tls_config_error(pki->tlsconf));
577 event_set(&listen->ev, listen->fd, EV_READ|EV_PERSIST,
578 handle_accept, listen);
579 event_add(&listen->ev, NULL);
583 static inline void
584 yield_r(struct client *c, void (*fn)(int, short, void *))
586 if (event_pending(&c->event, EV_WRITE|EV_READ, NULL))
587 event_del(&c->event);
588 event_set(&c->event, c->fd, EV_READ, fn, c);
589 event_add(&c->event, NULL);
592 static inline void
593 yield_w(struct client *c, void (*fn)(int, short, void *))
595 if (event_pending(&c->event, EV_WRITE|EV_READ, NULL))
596 event_del(&c->event);
597 event_set(&c->event, c->fd, EV_WRITE, fn, c);
598 event_add(&c->event, NULL);
601 static inline uint32_t
602 random_id(void)
604 #if HAVE_ARC4RANDOM
605 # define RANDID() arc4random()
606 #else
607 /* not as pretty as a random id */
608 static uint32_t counter = 0;
609 # define RANDID() counter++
610 #endif
612 struct client find, *res;
614 for (;;) {
615 find.id = RANDID();
616 res = SPLAY_FIND(clients_tree_id, &clients, &find);
617 if (res == NULL)
618 return find.id;
621 #undef RANDID
624 static void
625 handle_accept(int fd, short ev, void *data)
627 struct kd_listen_conf *listen = data;
628 struct client *c;
629 int s;
631 if ((s = accept(fd, NULL, NULL)) == -1) {
632 log_warn("accept");
633 return;
636 c = xcalloc(1, sizeof(*c));
637 c->msize = MSIZE9P;
638 c->lid = listen->id;
639 c->iev.ibuf.fd = -1;
641 if (tls_accept_socket(listen->ctx, &c->ctx, s) == -1) {
642 log_warnx("tls_accept_socket: %s",
643 tls_error(listen->ctx));
644 free(c);
645 close(s);
646 return;
649 c->fd = s;
650 c->id = random_id();
652 SPLAY_INSERT(clients_tree_id, &clients, c);
654 /* initialize the event */
655 event_set(&c->event, c->fd, EV_READ, NULL, NULL);
657 yield_r(c, handle_handshake);
660 static void
661 handle_handshake(int fd, short ev, void *data)
663 struct client *c = data;
664 struct kd_auth_req auth;
665 ssize_t r;
666 const char *hash;
668 switch (r = tls_handshake(c->ctx)) {
669 case TLS_WANT_POLLIN:
670 yield_r(c, handle_handshake);
671 return;
672 case TLS_WANT_POLLOUT:
673 yield_w(c, handle_handshake);
674 return;
675 case -1:
676 log_debug("handhsake failed: %s", tls_error(c->ctx));
677 close_conn(c);
678 return;
681 if ((hash = tls_peer_cert_hash(c->ctx)) == NULL) {
682 log_warnx("client didn't provide certificate");
683 close_conn(c);
684 return;
687 memset(&auth, 0, sizeof(auth));
688 auth.listen_id = c->lid;
689 strlcpy(auth.hash, hash, sizeof(auth.hash));
690 log_debug("sending hash %s", auth.hash);
692 listener_imsg_compose_main(IMSG_AUTH_TLS, c->id,
693 &auth, sizeof(auth));
696 static void
697 client_read(struct bufferevent *bev, void *d)
699 struct client *client = d;
700 struct evbuffer *src = EVBUFFER_INPUT(bev);
701 uint32_t len;
703 for (;;) {
704 if (EVBUFFER_LENGTH(src) < 4)
705 return;
707 memcpy(&len, EVBUFFER_DATA(src), sizeof(len));
708 len = le32toh(len);
709 log_debug("expecting a message %"PRIu32" bytes long "
710 "(of wich %zu already read)",
711 len, EVBUFFER_LENGTH(src));
713 if (len < HEADERSIZE) {
714 log_warnx("invalid message size %d (too low)", len);
715 client_error(bev, EVBUFFER_READ, client);
716 return;
719 if (len > client->msize) {
720 log_warnx("incoming message bigger than msize "
721 "(%"PRIu32" vs %"PRIu32")", len, client->msize);
722 client_error(bev, EVBUFFER_READ, client);
723 return;
726 if (len > EVBUFFER_LENGTH(src))
727 return;
729 listener_imsg_compose_client(client, IMSG_BUF, client->id,
730 EVBUFFER_DATA(src), len);
731 evbuffer_drain(src, len);
735 static void
736 client_write(struct bufferevent *bev, void *d)
738 /*
739 * here we can do some fancy logic like deciding when to call
741 * (*bev->errorcb)(bev, EVBUFFER_WRITE, bev->cbarg)
743 * to signal the end of the transaction.
744 */
746 return;
749 static void
750 client_error(struct bufferevent *bev, short err, void *d)
752 struct client *client = d;
753 struct evbuffer *buf;
755 if (err & EVBUFFER_ERROR) {
756 if (errno == EFBIG) {
757 bufferevent_enable(bev, EV_READ);
758 return;
760 log_debug("buffer event error");
761 close_conn(client);
762 return;
765 if (err & EVBUFFER_EOF) {
766 close_conn(client);
767 return;
770 if (err & (EVBUFFER_READ|EVBUFFER_WRITE)) {
771 bufferevent_disable(bev, EV_READ|EV_WRITE);
772 client->done = 1;
774 buf = EVBUFFER_OUTPUT(client->bev);
775 if (EVBUFFER_LENGTH(buf) != 0) {
776 /* finish writing all the data first */
777 bufferevent_enable(client->bev, EV_WRITE);
778 return;
781 close_conn(client);
782 return;
785 log_warnx("unknown event error, closing client connection");
786 close_conn(client);
789 static void
790 client_tls_readcb(int fd, short event, void *d)
792 struct bufferevent *bufev = d;
793 struct client *client = bufev->cbarg;
794 char buf[IBUF_READ_SIZE];
795 int what = EVBUFFER_READ;
796 int howmuch = IBUF_READ_SIZE;
797 ssize_t ret;
798 size_t len;
800 if (event == EV_TIMEOUT) {
801 what |= EVBUFFER_TIMEOUT;
802 goto err;
805 if (bufev->wm_read.high != 0)
806 howmuch = MIN(sizeof(buf), bufev->wm_read.high);
808 switch (ret = tls_read(client->ctx, buf, howmuch)) {
809 case TLS_WANT_POLLIN:
810 case TLS_WANT_POLLOUT:
811 goto retry;
812 case -1:
813 what |= EVBUFFER_ERROR;
814 goto err;
816 len = ret;
818 if (len == 0) {
819 what |= EVBUFFER_EOF;
820 goto err;
823 if (evbuffer_add(bufev->input, buf, len) == -1) {
824 what |= EVBUFFER_ERROR;
825 goto err;
828 event_add(&bufev->ev_read, NULL);
830 len = EVBUFFER_LENGTH(bufev->input);
831 if (bufev->wm_read.low != 0 && len < bufev->wm_read.low)
832 return;
833 if (bufev->wm_read.high != 0 && len > bufev->wm_read.high) {
834 /*
835 * here we could implement some read pressure
836 * mechanism.
837 */
840 if (bufev->readcb != NULL)
841 (*bufev->readcb)(bufev, bufev->cbarg);
843 return;
845 retry:
846 event_add(&bufev->ev_read, NULL);
847 return;
849 err:
850 (*bufev->errorcb)(bufev, what, bufev->cbarg);
853 static void
854 client_tls_writecb(int fd, short event, void *d)
856 struct bufferevent *bufev = d;
857 struct client *client = bufev->cbarg;
858 ssize_t ret;
859 size_t len;
860 short what = EVBUFFER_WRITE;
862 if (event == EV_TIMEOUT) {
863 what |= EVBUFFER_TIMEOUT;
864 goto err;
867 if (EVBUFFER_LENGTH(bufev->output) != 0) {
868 ret = tls_write(client->ctx,
869 EVBUFFER_DATA(bufev->output),
870 EVBUFFER_LENGTH(bufev->output));
871 switch (ret) {
872 case TLS_WANT_POLLIN:
873 case TLS_WANT_POLLOUT:
874 goto retry;
875 case -1:
876 what |= EVBUFFER_ERROR;
877 goto err;
879 len = ret;
880 evbuffer_drain(bufev->output, len);
883 if (EVBUFFER_LENGTH(bufev->output) != 0)
884 event_add(&bufev->ev_write, NULL);
886 if (bufev->writecb != NULL &&
887 EVBUFFER_LENGTH(bufev->output) <= bufev->wm_write.low)
888 (*bufev->writecb)(bufev, bufev->cbarg);
889 return;
891 retry:
892 event_add(&bufev->ev_write, NULL);
893 return;
895 err:
896 (*bufev->errorcb)(bufev, what, bufev->cbarg);
899 static void
900 close_conn(struct client *c)
902 log_debug("closing connection");
904 if (c->iev.ibuf.fd != -1) {
905 listener_imsg_compose_client(c, IMSG_CONN_GONE, 0, NULL, 0);
906 imsg_flush(&c->iev.ibuf);
907 msgbuf_clear(&c->iev.ibuf.w);
908 event_del(&c->iev.ev);
909 close(c->iev.ibuf.fd);
912 handle_close(c->fd, 0, c);
915 static void
916 handle_close(int fd, short ev, void *d)
918 struct client *c = d;
920 switch (tls_close(c->ctx)) {
921 case TLS_WANT_POLLIN:
922 yield_r(c, handle_close);
923 return;
924 case TLS_WANT_POLLOUT:
925 yield_w(c, handle_close);
926 return;
929 event_del(&c->event);
930 tls_free(c->ctx);
931 close(c->fd);
932 free(c);