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>
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 static struct kd_conf *listener_conf;
48 static struct imsgev *iev_main;
50 static void listener_sig_handler(int, short, void *);
51 __dead void listener_shutdown(void);
53 SPLAY_HEAD(clients_tree_id, client) clients;
55 struct client {
56 uint32_t id;
57 uint32_t lid;
58 uint32_t msize;
59 int fd;
60 int done;
61 struct tls *ctx;
62 struct event event;
63 struct imsgev iev;
64 struct bufferevent *bev;
65 SPLAY_ENTRY(client) sp_entry;
66 };
68 static void listener_imsg_event_add(struct imsgev *, void *);
69 static void listener_dispatch_client(int, short, void *);
70 static int listener_imsg_compose_client(struct client *, int,
71 uint32_t, const void *, uint16_t);
73 static void apply_config(struct kd_conf *);
74 static void handle_accept(int, short, void *);
76 static void handle_handshake(int, short, void *);
77 static void client_read(struct bufferevent *, void *);
78 static void client_write(struct bufferevent *, void *);
79 static void client_error(struct bufferevent *, short, void *);
80 static void client_tls_readcb(int, short, void *);
81 static void client_tls_writecb(int, short, void *);
82 static void close_conn(struct client *);
83 static void handle_close(int, short, void *);
85 static inline int
86 clients_tree_cmp(struct client *a, struct client *b)
87 {
88 if (a->id == b->id)
89 return 0;
90 else if (a->id < b->id)
91 return -1;
92 else
93 return +1;
94 }
96 SPLAY_PROTOTYPE(clients_tree_id, client, sp_entry, clients_tree_cmp);
97 SPLAY_GENERATE(clients_tree_id, client, sp_entry, clients_tree_cmp)
99 static void
100 listener_sig_handler(int sig, short event, void *d)
102 /*
103 * Normal signal handler rules don't apply because libevent
104 * decouples for us.
105 */
107 switch (sig) {
108 case SIGINT:
109 case SIGTERM:
110 listener_shutdown();
111 default:
112 fatalx("unexpected signal %d", sig);
116 void
117 listener(int debug, int verbose)
119 struct event ev_sigint, ev_sigterm;
120 struct passwd *pw;
122 /* listener_conf = config_new_empty(); */
124 log_init(debug, LOG_DAEMON);
125 log_setverbose(verbose);
127 if ((pw = getpwnam(KD_USER)) == NULL)
128 fatal("getpwnam");
130 if (chroot(pw->pw_dir) == -1)
131 fatal("chroot");
132 if (chdir("/") == -1)
133 fatal("chdir(\"/\")");
135 setproctitle("listener");
136 log_procinit("listener");
138 if (setgroups(1, &pw->pw_gid) ||
139 setresgid(pw->pw_gid, pw->pw_gid, pw->pw_gid) ||
140 setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid))
141 fatal("can't drop privileges");
143 event_init();
145 /* Setup signal handlers(s). */
146 signal_set(&ev_sigint, SIGINT, listener_sig_handler, NULL);
147 signal_set(&ev_sigterm, SIGTERM, listener_sig_handler, NULL);
149 signal_add(&ev_sigint, NULL);
150 signal_add(&ev_sigterm, NULL);
152 signal(SIGPIPE, SIG_IGN);
153 signal(SIGHUP, SIG_IGN);
155 /* Setup pipe and event handler to the main process. */
156 if ((iev_main = malloc(sizeof(*iev_main))) == NULL)
157 fatal(NULL);
159 imsg_init(&iev_main->ibuf, 3);
160 iev_main->handler = listener_dispatch_main;
162 /* Setup event handlers. */
163 iev_main->events = EV_READ;
164 event_set(&iev_main->ev, iev_main->ibuf.fd, iev_main->events,
165 iev_main->handler, iev_main);
166 event_add(&iev_main->ev, NULL);
168 sandbox_listener();
169 event_dispatch();
170 listener_shutdown();
173 __dead void
174 listener_shutdown(void)
176 msgbuf_clear(&iev_main->ibuf.w);
177 close(iev_main->ibuf.fd);
179 config_clear(listener_conf);
181 free(iev_main);
183 log_info("listener exiting");
184 exit(0);
187 static void
188 listener_receive_config(struct imsg *imsg, struct kd_conf **nconf,
189 struct kd_pki_conf **pki)
191 struct kd_listen_conf *listen;
192 char *t;
194 switch (imsg->hdr.type) {
195 case IMSG_RECONF_CONF:
196 if (*nconf != NULL)
197 fatalx("%s: IMSG_RECONF_CONF already in "
198 "progress", __func__);
200 if (listener_conf != NULL)
201 fatalx("%s: don't know how reload the "
202 "configuration yet", __func__);
204 if (IMSG_DATA_SIZE(*imsg) != sizeof(struct kd_conf))
205 fatalx("%s: IMSG_RECONF_CONF wrong length: %lu",
206 __func__, IMSG_DATA_SIZE(*imsg));
207 if ((*nconf = malloc(sizeof(**nconf))) == NULL)
208 fatal(NULL);
209 memcpy(*nconf, imsg->data, sizeof(**nconf));
210 memset(&(*nconf)->pki_head, 0, sizeof((*nconf)->pki_head));
211 memset(&(*nconf)->table_head, 0, sizeof((*nconf)->table_head));
212 memset(&(*nconf)->listen_head, 0, sizeof((*nconf)->listen_head));
213 break;
214 case IMSG_RECONF_PKI:
215 if (*nconf == NULL)
216 fatalx("%s: IMSG_RECONF_PKI without "
217 "IMSG_RECONF_CONF", __func__);
218 *pki = xcalloc(1, sizeof(**pki));
219 t = imsg->data;
220 t[IMSG_DATA_SIZE(*imsg)-1] = '\0';
221 strlcpy((*pki)->name, t, sizeof((*pki)->name));
222 break;
223 case IMSG_RECONF_PKI_CERT:
224 if (*pki == NULL)
225 fatalx("%s: IMSG_RECONF_PKI_CERT without "
226 "IMSG_RECONF_PKI", __func__);
227 (*pki)->certlen = IMSG_DATA_SIZE(*imsg);
228 (*pki)->cert = xmemdup(imsg->data, (*pki)->certlen);
229 break;
230 case IMSG_RECONF_PKI_KEY:
231 if (*pki == NULL)
232 fatalx("%s: IMSG_RECONF_PKI_KEY without "
233 "IMSG_RECONF_PKI", __func__);
234 (*pki)->keylen = IMSG_DATA_SIZE(*imsg);
235 (*pki)->key = xmemdup(imsg->data, (*pki)->keylen);
236 STAILQ_INSERT_HEAD(&(*nconf)->pki_head, *pki, entry);
237 pki = NULL;
238 break;
239 case IMSG_RECONF_LISTEN:
240 if (*nconf == NULL)
241 fatalx("%s: IMSG_RECONF_LISTEN without "
242 "IMSG_RECONF_CONF", __func__);
243 if (IMSG_DATA_SIZE(*imsg) != sizeof(*listen))
244 fatalx("%s: IMSG_RECONF_LISTEN wrong length: %lu",
245 __func__, IMSG_DATA_SIZE(*imsg));
246 listen = xcalloc(1, sizeof(*listen));
247 memcpy(listen, imsg->data, sizeof(*listen));
248 memset(&listen->entry, 0, sizeof(listen->entry));
249 if ((listen->fd = imsg->fd) == -1)
250 fatalx("%s: IMSG_RECONF_LISTEN no fd",
251 __func__);
252 listen->auth_table = NULL;
253 memset(&listen->ev, 0, sizeof(listen->ev));
254 STAILQ_INSERT_HEAD(&(*nconf)->listen_head, listen, entry);
255 break;
256 case IMSG_RECONF_END:
257 if (*nconf == NULL)
258 fatalx("%s: IMSG_RECONF_END without "
259 "IMSG_RECONF_CONF", __func__);
260 /* merge_config(listener_conf, nconf); */
261 apply_config(*nconf);
262 *nconf = NULL;
263 break;
267 static inline struct kd_listen_conf *
268 listen_by_id(uint32_t id)
270 struct kd_listen_conf *l;
272 STAILQ_FOREACH(l, &listener_conf->listen_head, entry) {
273 if (l->id == id)
274 return l;
276 return NULL;
279 void
280 listener_dispatch_main(int fd, short event, void *d)
282 static struct kd_conf *nconf;
283 static struct kd_pki_conf *pki;
284 struct kd_listen_conf *listen;
285 struct client *client, find;
286 struct imsg imsg;
287 struct imsgev *iev = d;
288 struct imsgbuf *ibuf;
289 ssize_t n;
290 int shut = 0;
292 ibuf = &iev->ibuf;
294 if (event & EV_READ) {
295 if ((n = imsg_read(ibuf)) == -1 && errno != EAGAIN)
296 fatal("imsg_read error");
297 if (n == 0) /* Connection closed. */
298 shut = 1;
300 if (event & EV_WRITE) {
301 if ((n = msgbuf_write(&ibuf->w)) == -1 && errno != EAGAIN)
302 fatal("msgbuf_write");
303 if (n == 0) /* Connection closed. */
304 shut = 1;
307 for (;;) {
308 if ((n = imsg_get(ibuf, &imsg)) == -1)
309 fatal("%s: imsg_get error", __func__);
310 if (n == 0) /* No more messages. */
311 break;
313 switch (imsg.hdr.type) {
314 case IMSG_CONTROLFD:
315 if ((fd = imsg.fd) == -1)
316 fatalx("%s: expected to receive imsg "
317 "control fd but didn't receive any",
318 __func__);
319 /* Listen on control socket. */
320 control_listen(fd);
321 break;
322 case IMSG_RECONF_CONF:
323 case IMSG_RECONF_PKI:
324 case IMSG_RECONF_PKI_CERT:
325 case IMSG_RECONF_PKI_KEY:
326 case IMSG_RECONF_LISTEN:
327 case IMSG_RECONF_END:
328 listener_receive_config(&imsg, &nconf, &pki);
329 break;
330 case IMSG_AUTH:
331 find.id = imsg.hdr.peerid;
332 client = SPLAY_FIND(clients_tree_id, &clients, &find);
333 if (client == NULL) {
334 if (imsg.fd != -1)
335 close(imsg.fd);
336 break;
338 if (imsg.fd == -1) {
339 log_info("got fd = -1, auth failed?");
340 close_conn(client);
341 break;
343 imsg_init(&client->iev.ibuf, imsg.fd);
344 client->iev.events = EV_READ;
345 client->iev.handler = listener_dispatch_client;
346 event_set(&client->iev.ev, client->iev.ibuf.fd,
347 client->iev.events, client->iev.handler, client);
348 listener_imsg_compose_client(client, IMSG_AUTH,
349 client->id, imsg.data, IMSG_DATA_SIZE(imsg));
350 break;
351 case IMSG_AUTH_DIR:
352 find.id = imsg.hdr.peerid;
353 client = SPLAY_FIND(clients_tree_id, &clients, &find);
354 if (client == NULL) {
355 log_info("got AUTH_DIR but client gone");
356 break;
359 listener_imsg_compose_client(client, IMSG_AUTH_DIR,
360 0, imsg.data, IMSG_DATA_SIZE(imsg));
362 client->bev = bufferevent_new(client->fd,
363 client_read, client_write, client_error,
364 client);
365 if (client->bev == NULL) {
366 log_info("failed to allocate client buffer");
367 close_conn(client);
368 return;
371 #if HAVE_EVENT2
372 evbuffer_unfreeze(client->bev->input, 0);
373 evbuffer_unfreeze(client->bev->output, 1);
374 #endif
376 listen = listen_by_id(client->lid);
377 if (listen->flags & L_TLS) {
378 event_set(&client->bev->ev_read, client->fd,
379 EV_READ, client_tls_readcb, client->bev);
380 event_set(&client->bev->ev_write, client->fd,
381 EV_WRITE, client_tls_writecb, client->bev);
384 /*
385 * Read or write at least a header before
386 * firing the callbacks. High watermark of 0
387 * to never stop reading/writing; probably to
388 * be revisited.
389 */
390 /* bufferevent_setwatermark(client->bev, EV_READ|EV_WRITE, */
391 /* sizeof(struct np_msg_header), 0); */
392 bufferevent_enable(client->bev, EV_READ|EV_WRITE);
393 break;
395 default:
396 log_debug("%s: unexpected imsg %d", __func__,
397 imsg.hdr.type);
398 break;
400 imsg_free(&imsg);
403 if (!shut)
404 listener_imsg_event_add(iev, d);
405 else {
406 /* This pipe is dead. Remove its event handler. */
407 event_del(&iev->ev);
408 log_warnx("pipe closed, shutting down...");
409 event_loopexit(NULL);
413 int
414 listener_imsg_compose_main(int type, uint32_t peerid, const void *data,
415 uint16_t datalen)
417 return imsg_compose_event(iev_main, type, peerid, 0, -1, data,
418 datalen);
421 static void
422 listener_imsg_event_add(struct imsgev *iev, void *d)
424 iev->events = EV_READ;
425 if (iev->ibuf.w.queued)
426 iev->events |= EV_WRITE;
428 event_del(&iev->ev);
429 event_set(&iev->ev, iev->ibuf.fd, iev->events, iev->handler, d);
430 event_add(&iev->ev, NULL);
433 static void
434 listener_dispatch_client(int fd, short event, void *d)
436 struct client find, *client = d;
437 struct imsg imsg;
438 struct imsgev *iev;
439 struct imsgbuf *ibuf;
440 ssize_t n;
441 int r, shut = 0;
443 iev = &client->iev;
444 ibuf = &iev->ibuf;
446 if (event & EV_READ) {
447 if ((n = imsg_read(ibuf)) == -1 && errno != EAGAIN)
448 fatal("imsg_read error");
449 if (n == 0) /* Connection closed */
450 shut = 1;
453 if (event & EV_WRITE) {
454 if ((n = msgbuf_write(&ibuf->w)) == -1 && errno != EAGAIN)
455 fatal("msgbuf_write");
456 if (n == 0) /* Connection closed. */
457 shut = 1;
460 for (;;) {
461 if ((n = imsg_get(ibuf, &imsg)) == -1)
462 fatal("%s: imsg_get error", __func__);
463 if (n == 0) /* No more messages. */
464 break;
466 switch (imsg.hdr.type) {
467 case IMSG_BUF:
468 find.id = imsg.hdr.peerid;
469 client = SPLAY_FIND(clients_tree_id, &clients, &find);
470 if (client == NULL) {
471 log_info("got IMSG_BUF but client (%d) gone",
472 imsg.hdr.peerid);
473 break;
475 r = bufferevent_write(client->bev, imsg.data,
476 IMSG_DATA_SIZE(imsg));
477 if (r == -1) {
478 log_warn("%s: bufferevent_write failed",
479 __func__);
480 close_conn(client);
481 break;
483 break;
485 case IMSG_MSIZE:
486 if (IMSG_DATA_SIZE(imsg) != sizeof(client->msize))
487 fatal("IMSG_MSIZE size mismatch: "
488 "got %zu want %zu", IMSG_DATA_SIZE(imsg),
489 sizeof(client->msize));
491 memcpy(&client->msize, imsg.data,
492 sizeof(client->msize));
494 if (client->msize == 0)
495 fatal("IMSG_MSIZE got msize = 0");
497 break;
499 case IMSG_CLOSE:
500 /*
501 * Both EVBUFFER_READ or EVBUFFER_WRITE should
502 * be fine.
503 */
504 client_error(client->bev, EVBUFFER_READ, client);
505 break;
507 default:
508 log_debug("%s: unexpected imsg %d", __func__,
509 imsg.hdr.type);
510 break;
512 imsg_free(&imsg);
515 if (!shut)
516 listener_imsg_event_add(iev, d);
517 else {
518 /* This pipe is dead. Remove its handler */
519 log_debug("client proc vanished");
520 close_conn(client);
524 static int
525 listener_imsg_compose_client(struct client *client, int type,
526 uint32_t peerid, const void *data, uint16_t len)
528 int ret;
530 if ((ret = imsg_compose(&client->iev.ibuf, type, peerid, 0, -1,
531 data, len)) != -1)
532 listener_imsg_event_add(&client->iev, client);
534 return ret;
537 static inline struct kd_pki_conf *
538 pki_by_name(const char *name)
540 struct kd_pki_conf *pki;
542 STAILQ_FOREACH(pki, &listener_conf->pki_head, entry) {
543 if (!strcmp(name, pki->name))
544 return pki;
547 return NULL;
550 static void
551 apply_config(struct kd_conf *conf)
553 struct kd_pki_conf *pki;
554 struct kd_listen_conf *listen;
556 listener_conf = conf;
558 /* prepare the various tls_config */
559 STAILQ_FOREACH(pki, &listener_conf->pki_head, entry) {
560 if ((pki->tlsconf = tls_config_new()) == NULL)
561 fatal("tls_config_new");
562 tls_config_verify_client_optional(pki->tlsconf);
563 tls_config_insecure_noverifycert(pki->tlsconf);
564 if (tls_config_set_keypair_mem(pki->tlsconf,
565 pki->cert, pki->certlen,
566 pki->key, pki->keylen) == -1)
567 fatalx("tls_config_set_keypair_mem: %s",
568 tls_config_error(pki->tlsconf));
571 /* prepare and kickoff the listeners */
572 STAILQ_FOREACH(listen, &listener_conf->listen_head, entry) {
573 if ((listen->ctx = tls_server()) == NULL)
574 fatal("tls_server");
576 pki = pki_by_name(listen->pki);
577 if (tls_configure(listen->ctx, pki->tlsconf) == -1)
578 fatalx("tls_configure: %s",
579 tls_config_error(pki->tlsconf));
581 event_set(&listen->ev, listen->fd, EV_READ|EV_PERSIST,
582 handle_accept, listen);
583 event_add(&listen->ev, NULL);
587 static inline void
588 yield_r(struct client *c, void (*fn)(int, short, void *))
590 if (event_pending(&c->event, EV_WRITE|EV_READ, NULL))
591 event_del(&c->event);
592 event_set(&c->event, c->fd, EV_READ, fn, c);
593 event_add(&c->event, NULL);
596 static inline void
597 yield_w(struct client *c, void (*fn)(int, short, void *))
599 if (event_pending(&c->event, EV_WRITE|EV_READ, NULL))
600 event_del(&c->event);
601 event_set(&c->event, c->fd, EV_WRITE, fn, c);
602 event_add(&c->event, NULL);
605 static inline uint32_t
606 random_id(void)
608 #if HAVE_ARC4RANDOM
609 # define RANDID() arc4random()
610 #else
611 /* not as pretty as a random id */
612 static uint32_t counter = 0;
613 # define RANDID() counter++
614 #endif
616 struct client find, *res;
618 for (;;) {
619 find.id = RANDID();
620 res = SPLAY_FIND(clients_tree_id, &clients, &find);
621 if (res == NULL)
622 return find.id;
625 #undef RANDID
628 static void
629 handle_accept(int fd, short ev, void *data)
631 struct kd_listen_conf *listen = data;
632 struct client *c;
633 int s;
635 if ((s = accept(fd, NULL, NULL)) == -1) {
636 log_warn("accept");
637 return;
640 c = xcalloc(1, sizeof(*c));
641 c->msize = MSIZE9P;
642 c->lid = listen->id;
643 c->iev.ibuf.fd = -1;
645 if (tls_accept_socket(listen->ctx, &c->ctx, s) == -1) {
646 log_warnx("tls_accept_socket: %s",
647 tls_error(listen->ctx));
648 free(c);
649 close(s);
650 return;
653 c->fd = s;
654 c->id = random_id();
656 SPLAY_INSERT(clients_tree_id, &clients, c);
658 /* initialize the event */
659 event_set(&c->event, c->fd, EV_READ, NULL, NULL);
661 yield_r(c, handle_handshake);
664 static void
665 handle_handshake(int fd, short ev, void *data)
667 struct client *c = data;
668 struct kd_auth_req auth;
669 ssize_t r;
670 const char *hash;
672 switch (r = tls_handshake(c->ctx)) {
673 case TLS_WANT_POLLIN:
674 yield_r(c, handle_handshake);
675 return;
676 case TLS_WANT_POLLOUT:
677 yield_w(c, handle_handshake);
678 return;
679 case -1:
680 log_debug("handhsake failed: %s", tls_error(c->ctx));
681 close_conn(c);
682 return;
685 if ((hash = tls_peer_cert_hash(c->ctx)) == NULL) {
686 log_warnx("client didn't provide certificate");
687 close_conn(c);
688 return;
691 memset(&auth, 0, sizeof(auth));
692 auth.listen_id = c->lid;
693 strlcpy(auth.hash, hash, sizeof(auth.hash));
694 log_debug("sending hash %s", auth.hash);
696 listener_imsg_compose_main(IMSG_AUTH_TLS, c->id,
697 &auth, sizeof(auth));
700 static void
701 client_read(struct bufferevent *bev, void *d)
703 struct client *client = d;
704 struct evbuffer *src = EVBUFFER_INPUT(bev);
705 uint32_t len;
707 for (;;) {
708 if (EVBUFFER_LENGTH(src) < 4)
709 return;
711 memcpy(&len, EVBUFFER_DATA(src), sizeof(len));
712 len = le32toh(len);
713 log_debug("expecting a message %"PRIu32" bytes long "
714 "(of wich %zu already read)",
715 len, EVBUFFER_LENGTH(src));
717 if (len < HEADERSIZE) {
718 log_warnx("invalid message size %d (too low)", len);
719 client_error(bev, EVBUFFER_READ, client);
720 return;
723 if (len > client->msize) {
724 log_warnx("incoming message bigger than msize "
725 "(%"PRIu32" vs %"PRIu32")", len, client->msize);
726 client_error(bev, EVBUFFER_READ, client);
727 return;
730 if (len > EVBUFFER_LENGTH(src))
731 return;
733 listener_imsg_compose_client(client, IMSG_BUF, client->id,
734 EVBUFFER_DATA(src), len);
735 evbuffer_drain(src, len);
739 static void
740 client_write(struct bufferevent *bev, void *d)
742 /*
743 * here we can do some fancy logic like deciding when to call
745 * (*bev->errorcb)(bev, EVBUFFER_WRITE, bev->cbarg)
747 * to signal the end of the transaction.
748 */
750 return;
753 static void
754 client_error(struct bufferevent *bev, short err, void *d)
756 struct client *client = d;
757 struct evbuffer *buf;
759 if (err & EVBUFFER_ERROR) {
760 if (errno == EFBIG) {
761 bufferevent_enable(bev, EV_READ);
762 return;
764 log_debug("buffer event error");
765 close_conn(client);
766 return;
769 if (err & EVBUFFER_EOF) {
770 close_conn(client);
771 return;
774 if (err & (EVBUFFER_READ|EVBUFFER_WRITE)) {
775 bufferevent_disable(bev, EV_READ|EV_WRITE);
776 client->done = 1;
778 buf = EVBUFFER_OUTPUT(client->bev);
779 if (EVBUFFER_LENGTH(buf) != 0) {
780 /* finish writing all the data first */
781 bufferevent_enable(client->bev, EV_WRITE);
782 return;
785 close_conn(client);
786 return;
789 log_warnx("unknown event error, closing client connection");
790 close_conn(client);
793 static void
794 client_tls_readcb(int fd, short event, void *d)
796 struct bufferevent *bufev = d;
797 struct client *client = bufev->cbarg;
798 char buf[IBUF_READ_SIZE];
799 int what = EVBUFFER_READ;
800 int howmuch = IBUF_READ_SIZE;
801 ssize_t ret;
802 size_t len;
804 if (event == EV_TIMEOUT) {
805 what |= EVBUFFER_TIMEOUT;
806 goto err;
809 if (bufev->wm_read.high != 0)
810 howmuch = MIN(sizeof(buf), bufev->wm_read.high);
812 switch (ret = tls_read(client->ctx, buf, howmuch)) {
813 case TLS_WANT_POLLIN:
814 case TLS_WANT_POLLOUT:
815 goto retry;
816 case -1:
817 what |= EVBUFFER_ERROR;
818 goto err;
820 len = ret;
822 if (len == 0) {
823 what |= EVBUFFER_EOF;
824 goto err;
827 if (evbuffer_add(bufev->input, buf, len) == -1) {
828 what |= EVBUFFER_ERROR;
829 goto err;
832 event_add(&bufev->ev_read, NULL);
834 len = EVBUFFER_LENGTH(bufev->input);
835 if (bufev->wm_read.low != 0 && len < bufev->wm_read.low)
836 return;
837 if (bufev->wm_read.high != 0 && len > bufev->wm_read.high) {
838 /*
839 * here we could implement some read pressure
840 * mechanism.
841 */
844 if (bufev->readcb != NULL)
845 (*bufev->readcb)(bufev, bufev->cbarg);
847 return;
849 retry:
850 event_add(&bufev->ev_read, NULL);
851 return;
853 err:
854 (*bufev->errorcb)(bufev, what, bufev->cbarg);
857 static void
858 client_tls_writecb(int fd, short event, void *d)
860 struct bufferevent *bufev = d;
861 struct client *client = bufev->cbarg;
862 ssize_t ret;
863 size_t len;
864 short what = EVBUFFER_WRITE;
866 if (event == EV_TIMEOUT) {
867 what |= EVBUFFER_TIMEOUT;
868 goto err;
871 if (EVBUFFER_LENGTH(bufev->output) != 0) {
872 ret = tls_write(client->ctx,
873 EVBUFFER_DATA(bufev->output),
874 EVBUFFER_LENGTH(bufev->output));
875 switch (ret) {
876 case TLS_WANT_POLLIN:
877 case TLS_WANT_POLLOUT:
878 goto retry;
879 case -1:
880 what |= EVBUFFER_ERROR;
881 goto err;
883 len = ret;
884 evbuffer_drain(bufev->output, len);
887 if (EVBUFFER_LENGTH(bufev->output) != 0)
888 event_add(&bufev->ev_write, NULL);
890 if (bufev->writecb != NULL &&
891 EVBUFFER_LENGTH(bufev->output) <= bufev->wm_write.low)
892 (*bufev->writecb)(bufev, bufev->cbarg);
893 return;
895 retry:
896 event_add(&bufev->ev_write, NULL);
897 return;
899 err:
900 (*bufev->errorcb)(bufev, what, bufev->cbarg);
903 static void
904 close_conn(struct client *c)
906 log_debug("closing connection");
908 if (c->iev.ibuf.fd != -1) {
909 listener_imsg_compose_client(c, IMSG_CONN_GONE, 0, NULL, 0);
910 imsg_flush(&c->iev.ibuf);
911 msgbuf_clear(&c->iev.ibuf.w);
912 event_del(&c->iev.ev);
913 close(c->iev.ibuf.fd);
916 handle_close(c->fd, 0, c);
919 static void
920 handle_close(int fd, short ev, void *d)
922 struct client *c = d;
924 switch (tls_close(c->ctx)) {
925 case TLS_WANT_POLLIN:
926 yield_r(c, handle_close);
927 return;
928 case TLS_WANT_POLLOUT:
929 yield_w(c, handle_close);
930 return;
933 event_del(&c->event);
934 tls_free(c->ctx);
935 close(c->fd);
936 free(c);