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 <sys/socket.h>
22 #include <sys/types.h>
23 #include <sys/tree.h>
24 #include <sys/queue.h>
25 #include <sys/uio.h>
27 #include <endian.h>
28 #include <errno.h>
29 #include <event.h>
30 #include <inttypes.h>
31 #include <pwd.h>
32 #include <signal.h>
33 #include <stdint.h>
34 #include <stdio.h>
35 #include <stdlib.h>
36 #include <string.h>
37 #include <syslog.h>
38 #include <unistd.h>
39 #include <imsg.h>
41 #include "control.h"
42 #include "kami.h"
43 #include "kamid.h"
44 #include "listener.h"
45 #include "log.h"
46 #include "sandbox.h"
47 #include "utils.h"
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 msize;
61 int fd;
62 int done;
63 struct tls *ctx;
64 struct event event;
65 struct imsgev iev;
66 struct bufferevent *bev;
67 SPLAY_ENTRY(client) sp_entry;
68 };
70 static void listener_imsg_event_add(struct imsgev *, void *);
71 static void listener_dispatch_client(int, short, void *);
72 static int listener_imsg_compose_client(struct client *, int,
73 uint32_t, const void *, uint16_t);
75 static void apply_config(struct kd_conf *);
76 static void handle_accept(int, short, void *);
78 static void handle_handshake(int, short, void *);
79 static void client_read(struct bufferevent *, void *);
80 static void client_write(struct bufferevent *, void *);
81 static void client_error(struct bufferevent *, short, void *);
82 static void client_tls_readcb(int, short, void *);
83 static void client_tls_writecb(int, short, void *);
84 static void close_conn(struct client *);
85 static void handle_close(int, short, void *);
87 static inline int
88 clients_tree_cmp(struct client *a, struct client *b)
89 {
90 if (a->id == b->id)
91 return 0;
92 else if (a->id < b->id)
93 return -1;
94 else
95 return +1;
96 }
98 SPLAY_PROTOTYPE(clients_tree_id, client, sp_entry, clients_tree_cmp);
99 SPLAY_GENERATE(clients_tree_id, client, sp_entry, clients_tree_cmp)
101 static void
102 listener_sig_handler(int sig, short event, void *d)
104 /*
105 * Normal signal handler rules don't apply because libevent
106 * decouples for us.
107 */
109 switch (sig) {
110 case SIGINT:
111 case SIGTERM:
112 listener_shutdown();
113 default:
114 fatalx("unexpected signal %d", sig);
118 void
119 listener(int debug, int verbose)
121 struct event ev_sigint, ev_sigterm;
122 struct passwd *pw;
124 /* listener_conf = config_new_empty(); */
126 log_init(debug, LOG_DAEMON);
127 log_setverbose(verbose);
129 if ((pw = getpwnam(KD_USER)) == NULL)
130 fatal("getpwnam");
132 if (chroot(pw->pw_dir) == -1)
133 fatal("chroot");
134 if (chdir("/") == -1)
135 fatal("chdir(\"/\")");
137 setproctitle("listener");
138 log_procinit("listener");
140 if (setgroups(1, &pw->pw_gid) ||
141 setresgid(pw->pw_gid, pw->pw_gid, pw->pw_gid) ||
142 setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid))
143 fatal("can't drop privileges");
145 event_init();
147 /* Setup signal handlers(s). */
148 signal_set(&ev_sigint, SIGINT, listener_sig_handler, NULL);
149 signal_set(&ev_sigterm, SIGTERM, listener_sig_handler, NULL);
151 signal_add(&ev_sigint, NULL);
152 signal_add(&ev_sigterm, NULL);
154 signal(SIGPIPE, SIG_IGN);
155 signal(SIGHUP, SIG_IGN);
157 /* Setup pipe and event handler to the main process. */
158 if ((iev_main = malloc(sizeof(*iev_main))) == NULL)
159 fatal(NULL);
161 imsg_init(&iev_main->ibuf, 3);
162 iev_main->handler = listener_dispatch_main;
164 /* Setup event handlers. */
165 iev_main->events = EV_READ;
166 event_set(&iev_main->ev, iev_main->ibuf.fd, iev_main->events,
167 iev_main->handler, iev_main);
168 event_add(&iev_main->ev, NULL);
170 sandbox_listener();
171 event_dispatch();
172 listener_shutdown();
175 __dead void
176 listener_shutdown(void)
178 msgbuf_clear(&iev_main->ibuf.w);
179 close(iev_main->ibuf.fd);
181 config_clear(listener_conf);
183 free(iev_main);
185 log_info("listener exiting");
186 exit(0);
189 static void
190 listener_receive_config(struct imsg *imsg, struct kd_conf **nconf,
191 struct kd_pki_conf **pki)
193 struct kd_listen_conf *listen;
194 char *t;
196 switch (imsg->hdr.type) {
197 case IMSG_RECONF_CONF:
198 if (*nconf != NULL)
199 fatalx("%s: IMSG_RECONF_CONF already in "
200 "progress", __func__);
202 if (listener_conf != NULL)
203 fatalx("%s: don't know how reload the "
204 "configuration yet", __func__);
206 if (IMSG_DATA_SIZE(*imsg) != sizeof(struct kd_conf))
207 fatalx("%s: IMSG_RECONF_CONF wrong length: %lu",
208 __func__, IMSG_DATA_SIZE(*imsg));
209 if ((*nconf = malloc(sizeof(**nconf))) == NULL)
210 fatal(NULL);
211 memcpy(*nconf, imsg->data, sizeof(**nconf));
212 memset(&(*nconf)->pki_head, 0, sizeof((*nconf)->pki_head));
213 memset(&(*nconf)->table_head, 0, sizeof((*nconf)->table_head));
214 memset(&(*nconf)->listen_head, 0, sizeof((*nconf)->listen_head));
215 break;
216 case IMSG_RECONF_PKI:
217 if (*nconf == NULL)
218 fatalx("%s: IMSG_RECONF_PKI without "
219 "IMSG_RECONF_CONF", __func__);
220 *pki = xcalloc(1, sizeof(**pki));
221 t = imsg->data;
222 t[IMSG_DATA_SIZE(*imsg)-1] = '\0';
223 strlcpy((*pki)->name, t, sizeof((*pki)->name));
224 break;
225 case IMSG_RECONF_PKI_CERT:
226 if (*pki == NULL)
227 fatalx("%s: IMSG_RECONF_PKI_CERT without "
228 "IMSG_RECONF_PKI", __func__);
229 (*pki)->certlen = IMSG_DATA_SIZE(*imsg);
230 (*pki)->cert = xmemdup(imsg->data, (*pki)->certlen);
231 break;
232 case IMSG_RECONF_PKI_KEY:
233 if (*pki == NULL)
234 fatalx("%s: IMSG_RECONF_PKI_KEY without "
235 "IMSG_RECONF_PKI", __func__);
236 (*pki)->keylen = IMSG_DATA_SIZE(*imsg);
237 (*pki)->key = xmemdup(imsg->data, (*pki)->keylen);
238 STAILQ_INSERT_HEAD(&(*nconf)->pki_head, *pki, entry);
239 pki = NULL;
240 break;
241 case IMSG_RECONF_LISTEN:
242 if (*nconf == NULL)
243 fatalx("%s: IMSG_RECONF_LISTEN without "
244 "IMSG_RECONF_CONF", __func__);
245 if (IMSG_DATA_SIZE(*imsg) != sizeof(*listen))
246 fatalx("%s: IMSG_RECONF_LISTEN wrong length: %lu",
247 __func__, IMSG_DATA_SIZE(*imsg));
248 listen = xcalloc(1, sizeof(*listen));
249 memcpy(listen, imsg->data, sizeof(*listen));
250 memset(&listen->entry, 0, sizeof(listen->entry));
251 if ((listen->fd = imsg->fd) == -1)
252 fatalx("%s: IMSG_RECONF_LISTEN no fd",
253 __func__);
254 listen->auth_table = NULL;
255 memset(&listen->ev, 0, sizeof(listen->ev));
256 STAILQ_INSERT_HEAD(&(*nconf)->listen_head, listen, entry);
257 break;
258 case IMSG_RECONF_END:
259 if (*nconf == NULL)
260 fatalx("%s: IMSG_RECONF_END without "
261 "IMSG_RECONF_CONF", __func__);
262 /* merge_config(listener_conf, nconf); */
263 apply_config(*nconf);
264 *nconf = NULL;
265 break;
269 static inline struct kd_listen_conf *
270 listen_by_id(uint32_t id)
272 struct kd_listen_conf *l;
274 STAILQ_FOREACH(l, &listener_conf->listen_head, entry) {
275 if (l->id == id)
276 return l;
278 return NULL;
281 void
282 listener_dispatch_main(int fd, short event, void *d)
284 static struct kd_conf *nconf;
285 static struct kd_pki_conf *pki;
286 struct kd_listen_conf *listen;
287 struct client *client, find;
288 struct imsg imsg;
289 struct imsgev *iev = d;
290 struct imsgbuf *ibuf;
291 ssize_t n;
292 int shut = 0;
294 ibuf = &iev->ibuf;
296 if (event & EV_READ) {
297 if ((n = imsg_read(ibuf)) == -1 && errno != EAGAIN)
298 fatal("imsg_read error");
299 if (n == 0) /* Connection closed. */
300 shut = 1;
302 if (event & EV_WRITE) {
303 if ((n = msgbuf_write(&ibuf->w)) == -1 && errno != EAGAIN)
304 fatal("msgbuf_write");
305 if (n == 0) /* Connection closed. */
306 shut = 1;
309 for (;;) {
310 if ((n = imsg_get(ibuf, &imsg)) == -1)
311 fatal("%s: imsg_get error", __func__);
312 if (n == 0) /* No more messages. */
313 break;
315 switch (imsg.hdr.type) {
316 case IMSG_CONTROLFD:
317 if ((fd = imsg.fd) == -1)
318 fatalx("%s: expected to receive imsg "
319 "control fd but didn't receive any",
320 __func__);
321 /* Listen on control socket. */
322 control_listen(fd);
323 break;
324 case IMSG_RECONF_CONF:
325 case IMSG_RECONF_PKI:
326 case IMSG_RECONF_PKI_CERT:
327 case IMSG_RECONF_PKI_KEY:
328 case IMSG_RECONF_LISTEN:
329 case IMSG_RECONF_END:
330 listener_receive_config(&imsg, &nconf, &pki);
331 break;
332 case IMSG_AUTH:
333 find.id = imsg.hdr.peerid;
334 client = SPLAY_FIND(clients_tree_id, &clients, &find);
335 if (client == NULL) {
336 if (imsg.fd != -1)
337 close(imsg.fd);
338 break;
340 if (imsg.fd == -1) {
341 log_info("got fd = -1, auth failed?");
342 close_conn(client);
343 break;
345 imsg_init(&client->iev.ibuf, imsg.fd);
346 client->iev.events = EV_READ;
347 client->iev.handler = listener_dispatch_client;
348 event_set(&client->iev.ev, client->iev.ibuf.fd,
349 client->iev.events, client->iev.handler, client);
350 listener_imsg_compose_client(client, IMSG_AUTH,
351 client->id, imsg.data, IMSG_DATA_SIZE(imsg));
352 break;
353 case IMSG_AUTH_DIR:
354 find.id = imsg.hdr.peerid;
355 client = SPLAY_FIND(clients_tree_id, &clients, &find);
356 if (client == NULL) {
357 log_info("got AUTH_DIR but client gone");
358 break;
361 listener_imsg_compose_client(client, IMSG_AUTH_DIR,
362 0, imsg.data, IMSG_DATA_SIZE(imsg));
364 client->bev = bufferevent_new(client->fd,
365 client_read, client_write, client_error,
366 client);
367 if (client->bev == NULL) {
368 log_info("failed to allocate client buffer");
369 close_conn(client);
370 return;
373 #if HAVE_EVENT2
374 evbuffer_unfreeze(client->bev->input, 0);
375 evbuffer_unfreeze(client->bev->output, 1);
376 #endif
378 listen = listen_by_id(client->lid);
379 if (listen->flags & L_TLS) {
380 event_set(&client->bev->ev_read, client->fd,
381 EV_READ, client_tls_readcb, client->bev);
382 event_set(&client->bev->ev_write, client->fd,
383 EV_WRITE, client_tls_writecb, client->bev);
386 /*
387 * Read or write at least a header before
388 * firing the callbacks. High watermark of 0
389 * to never stop reading/writing; probably to
390 * be revisited.
391 */
392 /* bufferevent_setwatermark(client->bev, EV_READ|EV_WRITE, */
393 /* sizeof(struct np_msg_header), 0); */
394 bufferevent_enable(client->bev, EV_READ|EV_WRITE);
395 break;
397 default:
398 log_debug("%s: unexpected imsg %d", __func__,
399 imsg.hdr.type);
400 break;
402 imsg_free(&imsg);
405 if (!shut)
406 listener_imsg_event_add(iev, d);
407 else {
408 /* This pipe is dead. Remove its event handler. */
409 event_del(&iev->ev);
410 log_warnx("pipe closed, shutting down...");
411 event_loopexit(NULL);
415 int
416 listener_imsg_compose_main(int type, uint32_t peerid, const void *data,
417 uint16_t datalen)
419 return imsg_compose_event(iev_main, type, peerid, 0, -1, data,
420 datalen);
423 static void
424 listener_imsg_event_add(struct imsgev *iev, void *d)
426 iev->events = EV_READ;
427 if (iev->ibuf.w.queued)
428 iev->events |= EV_WRITE;
430 event_del(&iev->ev);
431 event_set(&iev->ev, iev->ibuf.fd, iev->events, iev->handler, d);
432 event_add(&iev->ev, NULL);
435 static void
436 listener_dispatch_client(int fd, short event, void *d)
438 struct client find, *client = d;
439 struct imsg imsg;
440 struct imsgev *iev;
441 struct imsgbuf *ibuf;
442 ssize_t n;
443 int r, shut = 0;
445 iev = &client->iev;
446 ibuf = &iev->ibuf;
448 if (event & EV_READ) {
449 if ((n = imsg_read(ibuf)) == -1 && errno != EAGAIN)
450 fatal("imsg_read error");
451 if (n == 0) /* Connection closed */
452 shut = 1;
455 if (event & EV_WRITE) {
456 if ((n = msgbuf_write(&ibuf->w)) == -1 && errno != EAGAIN)
457 fatal("msgbuf_write");
458 if (n == 0) /* Connection closed. */
459 shut = 1;
462 for (;;) {
463 if ((n = imsg_get(ibuf, &imsg)) == -1)
464 fatal("%s: imsg_get error", __func__);
465 if (n == 0) /* No more messages. */
466 break;
468 switch (imsg.hdr.type) {
469 case IMSG_BUF:
470 find.id = imsg.hdr.peerid;
471 client = SPLAY_FIND(clients_tree_id, &clients, &find);
472 if (client == NULL) {
473 log_info("got IMSG_BUF but client (%d) gone",
474 imsg.hdr.peerid);
475 break;
477 r = bufferevent_write(client->bev, imsg.data,
478 IMSG_DATA_SIZE(imsg));
479 if (r == -1) {
480 log_warn("%s: bufferevent_write failed",
481 __func__);
482 close_conn(client);
483 break;
485 break;
487 case IMSG_MSIZE:
488 if (IMSG_DATA_SIZE(imsg) != sizeof(client->msize))
489 fatal("IMSG_MSIZE size mismatch: "
490 "got %zu want %zu", IMSG_DATA_SIZE(imsg),
491 sizeof(client->msize));
493 memcpy(&client->msize, imsg.data,
494 sizeof(client->msize));
496 if (client->msize == 0)
497 fatal("IMSG_MSIZE got msize = 0");
499 break;
501 case IMSG_CLOSE:
502 /*
503 * Both EVBUFFER_READ or EVBUFFER_WRITE should
504 * be fine.
505 */
506 client_error(client->bev, EVBUFFER_READ, client);
507 break;
509 default:
510 log_debug("%s: unexpected imsg %d", __func__,
511 imsg.hdr.type);
512 break;
514 imsg_free(&imsg);
517 if (!shut)
518 listener_imsg_event_add(iev, d);
519 else {
520 /* This pipe is dead. Remove its handler */
521 log_debug("client proc vanished");
522 close_conn(client);
526 static int
527 listener_imsg_compose_client(struct client *client, int type,
528 uint32_t peerid, const void *data, uint16_t len)
530 int ret;
532 if ((ret = imsg_compose(&client->iev.ibuf, type, peerid, 0, -1,
533 data, len)) != -1)
534 listener_imsg_event_add(&client->iev, client);
536 return ret;
539 static inline struct kd_pki_conf *
540 pki_by_name(const char *name)
542 struct kd_pki_conf *pki;
544 STAILQ_FOREACH(pki, &listener_conf->pki_head, entry) {
545 if (!strcmp(name, pki->name))
546 return pki;
549 return NULL;
552 static void
553 apply_config(struct kd_conf *conf)
555 struct kd_pki_conf *pki;
556 struct kd_listen_conf *listen;
558 listener_conf = conf;
560 /* prepare the various tls_config */
561 STAILQ_FOREACH(pki, &listener_conf->pki_head, entry) {
562 if ((pki->tlsconf = tls_config_new()) == NULL)
563 fatal("tls_config_new");
564 tls_config_verify_client_optional(pki->tlsconf);
565 tls_config_insecure_noverifycert(pki->tlsconf);
566 if (tls_config_set_keypair_mem(pki->tlsconf,
567 pki->cert, pki->certlen,
568 pki->key, pki->keylen) == -1)
569 fatalx("tls_config_set_keypair_mem: %s",
570 tls_config_error(pki->tlsconf));
573 /* prepare and kickoff the listeners */
574 STAILQ_FOREACH(listen, &listener_conf->listen_head, entry) {
575 if ((listen->ctx = tls_server()) == NULL)
576 fatal("tls_server");
578 pki = pki_by_name(listen->pki);
579 if (tls_configure(listen->ctx, pki->tlsconf) == -1)
580 fatalx("tls_configure: %s",
581 tls_config_error(pki->tlsconf));
583 event_set(&listen->ev, listen->fd, EV_READ|EV_PERSIST,
584 handle_accept, listen);
585 event_add(&listen->ev, NULL);
589 static inline void
590 yield_r(struct client *c, void (*fn)(int, short, void *))
592 if (event_pending(&c->event, EV_WRITE|EV_READ, NULL))
593 event_del(&c->event);
594 event_set(&c->event, c->fd, EV_READ, fn, c);
595 event_add(&c->event, NULL);
598 static inline void
599 yield_w(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_WRITE, fn, c);
604 event_add(&c->event, NULL);
607 static inline uint32_t
608 random_id(void)
610 #if HAVE_ARC4RANDOM
611 # define RANDID() arc4random()
612 #else
613 /* not as pretty as a random id */
614 static uint32_t counter = 0;
615 # define RANDID() counter++
616 #endif
618 struct client find, *res;
620 for (;;) {
621 find.id = RANDID();
622 res = SPLAY_FIND(clients_tree_id, &clients, &find);
623 if (res == NULL)
624 return find.id;
627 #undef RANDID
630 static void
631 handle_accept(int fd, short ev, void *data)
633 struct kd_listen_conf *listen = data;
634 struct client *c;
635 int s;
637 if ((s = accept(fd, NULL, NULL)) == -1) {
638 log_warn("accept");
639 return;
642 c = xcalloc(1, sizeof(*c));
643 c->msize = MSIZE9P;
644 c->lid = listen->id;
645 c->iev.ibuf.fd = -1;
647 if (tls_accept_socket(listen->ctx, &c->ctx, s) == -1) {
648 log_warnx("tls_accept_socket: %s",
649 tls_error(listen->ctx));
650 free(c);
651 close(s);
652 return;
655 c->fd = s;
656 c->id = random_id();
658 SPLAY_INSERT(clients_tree_id, &clients, c);
660 /* initialize the event */
661 event_set(&c->event, c->fd, EV_READ, NULL, NULL);
663 yield_r(c, handle_handshake);
666 static void
667 handle_handshake(int fd, short ev, void *data)
669 struct client *c = data;
670 struct kd_auth_req auth;
671 ssize_t r;
672 const char *hash;
674 switch (r = tls_handshake(c->ctx)) {
675 case TLS_WANT_POLLIN:
676 yield_r(c, handle_handshake);
677 return;
678 case TLS_WANT_POLLOUT:
679 yield_w(c, handle_handshake);
680 return;
681 case -1:
682 log_debug("handhsake failed: %s", tls_error(c->ctx));
683 close_conn(c);
684 return;
687 if ((hash = tls_peer_cert_hash(c->ctx)) == NULL) {
688 log_warnx("client didn't provide certificate");
689 close_conn(c);
690 return;
693 memset(&auth, 0, sizeof(auth));
694 auth.listen_id = c->lid;
695 strlcpy(auth.hash, hash, sizeof(auth.hash));
696 log_debug("sending hash %s", auth.hash);
698 listener_imsg_compose_main(IMSG_AUTH_TLS, c->id,
699 &auth, sizeof(auth));
702 static void
703 client_read(struct bufferevent *bev, void *d)
705 struct client *client = d;
706 struct evbuffer *src = EVBUFFER_INPUT(bev);
707 uint32_t len;
709 for (;;) {
710 if (EVBUFFER_LENGTH(src) < 4)
711 return;
713 memcpy(&len, EVBUFFER_DATA(src), sizeof(len));
714 len = le32toh(len);
715 log_debug("expecting a message %"PRIu32" bytes long "
716 "(of wich %zu already read)",
717 len, EVBUFFER_LENGTH(src));
719 if (len < HEADERSIZE) {
720 log_warnx("invalid message size %d (too low)", len);
721 client_error(bev, EVBUFFER_READ, client);
722 return;
725 if (len > client->msize) {
726 log_warnx("incoming message bigger than msize "
727 "(%"PRIu32" vs %"PRIu32")", len, client->msize);
728 client_error(bev, EVBUFFER_READ, client);
729 return;
732 if (len > EVBUFFER_LENGTH(src))
733 return;
735 listener_imsg_compose_client(client, IMSG_BUF, client->id,
736 EVBUFFER_DATA(src), len);
737 evbuffer_drain(src, len);
741 static void
742 client_write(struct bufferevent *bev, void *d)
744 /*
745 * here we can do some fancy logic like deciding when to call
747 * (*bev->errorcb)(bev, EVBUFFER_WRITE, bev->cbarg)
749 * to signal the end of the transaction.
750 */
752 return;
755 static void
756 client_error(struct bufferevent *bev, short err, void *d)
758 struct client *client = d;
759 struct evbuffer *buf;
761 if (err & EVBUFFER_ERROR) {
762 if (errno == EFBIG) {
763 bufferevent_enable(bev, EV_READ);
764 return;
766 log_debug("buffer event error");
767 close_conn(client);
768 return;
771 if (err & EVBUFFER_EOF) {
772 close_conn(client);
773 return;
776 if (err & (EVBUFFER_READ|EVBUFFER_WRITE)) {
777 bufferevent_disable(bev, EV_READ|EV_WRITE);
778 client->done = 1;
780 buf = EVBUFFER_OUTPUT(client->bev);
781 if (EVBUFFER_LENGTH(buf) != 0) {
782 /* finish writing all the data first */
783 bufferevent_enable(client->bev, EV_WRITE);
784 return;
787 close_conn(client);
788 return;
791 log_warnx("unknown event error, closing client connection");
792 close_conn(client);
795 static void
796 client_tls_readcb(int fd, short event, void *d)
798 struct bufferevent *bufev = d;
799 struct client *client = bufev->cbarg;
800 char buf[IBUF_READ_SIZE];
801 int what = EVBUFFER_READ;
802 int howmuch = IBUF_READ_SIZE;
803 ssize_t ret;
804 size_t len;
806 if (event == EV_TIMEOUT) {
807 what |= EVBUFFER_TIMEOUT;
808 goto err;
811 if (bufev->wm_read.high != 0)
812 howmuch = MIN(sizeof(buf), bufev->wm_read.high);
814 switch (ret = tls_read(client->ctx, buf, howmuch)) {
815 case TLS_WANT_POLLIN:
816 case TLS_WANT_POLLOUT:
817 goto retry;
818 case -1:
819 what |= EVBUFFER_ERROR;
820 goto err;
822 len = ret;
824 if (len == 0) {
825 what |= EVBUFFER_EOF;
826 goto err;
829 if (evbuffer_add(bufev->input, buf, len) == -1) {
830 what |= EVBUFFER_ERROR;
831 goto err;
834 event_add(&bufev->ev_read, NULL);
836 len = EVBUFFER_LENGTH(bufev->input);
837 if (bufev->wm_read.low != 0 && len < bufev->wm_read.low)
838 return;
839 if (bufev->wm_read.high != 0 && len > bufev->wm_read.high) {
840 /*
841 * here we could implement some read pressure
842 * mechanism.
843 */
846 if (bufev->readcb != NULL)
847 (*bufev->readcb)(bufev, bufev->cbarg);
849 return;
851 retry:
852 event_add(&bufev->ev_read, NULL);
853 return;
855 err:
856 (*bufev->errorcb)(bufev, what, bufev->cbarg);
859 static void
860 client_tls_writecb(int fd, short event, void *d)
862 struct bufferevent *bufev = d;
863 struct client *client = bufev->cbarg;
864 ssize_t ret;
865 size_t len;
866 short what = EVBUFFER_WRITE;
868 if (event == EV_TIMEOUT) {
869 what |= EVBUFFER_TIMEOUT;
870 goto err;
873 if (EVBUFFER_LENGTH(bufev->output) != 0) {
874 ret = tls_write(client->ctx,
875 EVBUFFER_DATA(bufev->output),
876 EVBUFFER_LENGTH(bufev->output));
877 switch (ret) {
878 case TLS_WANT_POLLIN:
879 case TLS_WANT_POLLOUT:
880 goto retry;
881 case -1:
882 what |= EVBUFFER_ERROR;
883 goto err;
885 len = ret;
886 evbuffer_drain(bufev->output, len);
889 if (EVBUFFER_LENGTH(bufev->output) != 0)
890 event_add(&bufev->ev_write, NULL);
892 if (bufev->writecb != NULL &&
893 EVBUFFER_LENGTH(bufev->output) <= bufev->wm_write.low)
894 (*bufev->writecb)(bufev, bufev->cbarg);
895 return;
897 retry:
898 event_add(&bufev->ev_write, NULL);
899 return;
901 err:
902 (*bufev->errorcb)(bufev, what, bufev->cbarg);
905 static void
906 close_conn(struct client *c)
908 log_debug("closing connection");
910 if (c->iev.ibuf.fd != -1) {
911 listener_imsg_compose_client(c, IMSG_CONN_GONE, 0, NULL, 0);
912 imsg_flush(&c->iev.ibuf);
913 msgbuf_clear(&c->iev.ibuf.w);
914 event_del(&c->iev.ev);
915 close(c->iev.ibuf.fd);
918 handle_close(c->fd, 0, c);
921 static void
922 handle_close(int fd, short ev, void *d)
924 struct client *c = d;
926 switch (tls_close(c->ctx)) {
927 case TLS_WANT_POLLIN:
928 yield_r(c, handle_close);
929 return;
930 case TLS_WANT_POLLOUT:
931 yield_w(c, handle_close);
932 return;
935 event_del(&c->event);
936 tls_free(c->ctx);
937 close(c->fd);
938 free(c);