1 /* $OpenBSD: ioev.c,v 1.42 2019/06/12 17:42:53 eric Exp $ */
3 * Copyright (c) 2012 Eric Faurot <eric@openbsd.org>
5 * Permission to use, copy, modify, and distribute this software for any
6 * purpose with or without fee is hereby granted, provided that the above
7 * copyright notice and this permission notice appear in all copies.
9 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
10 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
14 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
15 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
18 #include <sys/types.h>
19 #include <sys/queue.h>
20 #include <sys/socket.h>
36 #include <openssl/err.h>
37 #include <openssl/ssl.h>
50 #define IO_PAUSE_IN IO_IN
51 #define IO_PAUSE_OUT IO_OUT
54 #define IO_RW (IO_READ | IO_WRITE)
55 #define IO_RESET 0x10 /* internal */
56 #define IO_HELD 0x20 /* internal */
61 void (*cb)(struct io*, int, void *);
69 const char *error; /* only valid immediately on callback */
72 const char* io_strflags(int);
73 const char* io_evstr(short);
76 void io_hold(struct io *);
77 void io_release(struct io *);
78 void io_callback(struct io*, int);
79 void io_dispatch(int, short, void *);
80 void io_dispatch_connect(int, short, void *);
81 size_t io_pending(struct io *);
82 size_t io_queued(struct io*);
83 void io_reset(struct io *, short, void (*)(int, short, void*));
84 void io_frame_enter(const char *, struct io *, int);
85 void io_frame_leave(struct io *);
88 void ssl_error(const char *); /* XXX external */
90 static const char* io_tls_error(void);
91 void io_dispatch_accept_tls(int, short, void *);
92 void io_dispatch_connect_tls(int, short, void *);
93 void io_dispatch_read_tls(int, short, void *);
94 void io_dispatch_write_tls(int, short, void *);
95 void io_reload_tls(struct io *io);
98 static struct io *current = NULL;
99 static uint64_t frame = 0;
100 static int _io_debug = 0;
102 #define io_debug(args...) do { if (_io_debug) printf(args); } while(0)
106 io_strio(struct io *io)
108 static char buf[128];
114 (void)snprintf(ssl, sizeof ssl, " tls=%s:%s:%d",
115 SSL_get_version(io->tls),
116 SSL_get_cipher_name(io->tls),
117 SSL_get_cipher_bits(io->tls, NULL));
121 (void)snprintf(buf, sizeof buf,
122 "<io:%p fd=%d to=%d fl=%s%s ib=%zu ob=%zu>",
123 io, io->sock, io->timeout, io_strflags(io->flags), ssl,
124 io_pending(io), io_queued(io));
129 #define CASE(x) case x : return #x
141 CASE(IO_DISCONNECTED);
145 (void)snprintf(buf, sizeof(buf), "IO_? %d", evt);
151 io_set_nonblocking(int fd)
155 if ((flags = fcntl(fd, F_GETFL)) == -1)
156 err(1, "io_set_blocking:fcntl(F_GETFL)");
160 if (fcntl(fd, F_SETFL, flags) == -1)
161 err(1, "io_set_blocking:fcntl(F_SETFL)");
165 io_set_nolinger(int fd)
169 memset(&l, 0, sizeof(l));
170 if (setsockopt(fd, SOL_SOCKET, SO_LINGER, &l, sizeof(l)) == -1)
171 err(1, "io_set_linger:setsockopt()");
175 * Event framing must not rely on an io pointer to refer to the "same" io
176 * throughout the frame, because this is not always the case:
178 * 1) enter(addr0) -> free(addr0) -> leave(addr0) = SEGV
179 * 2) enter(addr0) -> free(addr0) -> malloc == addr0 -> leave(addr0) = BAD!
181 * In both case, the problem is that the io is freed in the callback, so
182 * the pointer becomes invalid. If that happens, the user is required to
183 * call io_clear, so we can adapt the frame state there.
186 io_frame_enter(const char *where, struct io *io, int ev)
188 io_debug("\n=== %" PRIu64 " ===\n"
189 "io_frame_enter(%s, %s, %s)\n",
190 frame, where, io_evstr(ev), io_strio(io));
193 errx(1, "io_frame_enter: interleaved frames");
201 io_frame_leave(struct io *io)
203 io_debug("io_frame_leave(%" PRIu64 ")\n", frame);
205 if (current && current != io)
206 errx(1, "io_frame_leave: io mismatch");
208 /* io has been cleared */
212 /* TODO: There is a possible optimization there:
213 * In a typical half-duplex request/response scenario,
214 * the io is waiting to read a request, and when done, it queues
215 * the response in the output buffer and goes to write mode.
216 * There, the write event is set and will be triggered in the next
217 * event frame. In most case, the write call could be done
218 * immediately as part of the last read frame, thus avoiding to go
219 * through the event loop machinery. So, as an optimisation, we
220 * could detect that case here and force an event dispatching.
223 /* Reload the io if it has not been reset already. */
227 io_debug("=== /%" PRIu64 "\n", frame);
241 _io_debug = getenv("IO_DEBUG") != NULL;
251 if ((io = calloc(1, sizeof(*io))) == NULL)
257 if (iobuf_init(&io->iobuf, 0, 0) == -1) {
266 io_free(struct io *io)
268 io_debug("io_clear(%p)\n", io);
270 /* the current io is virtually dead */
279 if (event_initialized(&io->ev))
281 if (io->sock != -1) {
286 iobuf_clear(&io->iobuf);
291 io_hold(struct io *io)
293 io_debug("io_enter(%p)\n", io);
295 if (io->flags & IO_HELD)
296 errx(1, "io_hold: io is already held");
298 io->flags &= ~IO_RESET;
299 io->flags |= IO_HELD;
303 io_release(struct io *io)
305 if (!(io->flags & IO_HELD))
306 errx(1, "io_release: io is not held");
308 io->flags &= ~IO_HELD;
309 if (!(io->flags & IO_RESET))
314 io_set_fd(struct io *io, int fd)
322 io_set_callback(struct io *io, void(*cb)(struct io *, int, void *), void *arg)
329 io_set_timeout(struct io *io, int msec)
331 io_debug("io_set_timeout(%p, %d)\n", io, msec);
337 io_set_lowat(struct io *io, size_t lowat)
339 io_debug("io_set_lowat(%p, %zu)\n", io, lowat);
345 io_pause(struct io *io, int dir)
347 io_debug("io_pause(%p, %x)\n", io, dir);
349 io->flags |= dir & (IO_PAUSE_IN | IO_PAUSE_OUT);
354 io_resume(struct io *io, int dir)
356 io_debug("io_resume(%p, %x)\n", io, dir);
358 io->flags &= ~(dir & (IO_PAUSE_IN | IO_PAUSE_OUT));
363 io_set_read(struct io *io)
367 io_debug("io_set_read(%p)\n", io);
369 mode = io->flags & IO_RW;
370 if (!(mode == 0 || mode == IO_WRITE))
371 errx(1, "io_set_read(): full-duplex or reading");
374 io->flags |= IO_READ;
379 io_set_write(struct io *io)
383 io_debug("io_set_write(%p)\n", io);
385 mode = io->flags & IO_RW;
386 if (!(mode == 0 || mode == IO_READ))
387 errx(1, "io_set_write(): full-duplex or writing");
390 io->flags |= IO_WRITE;
395 io_error(struct io *io)
401 io_tls(struct io *io)
407 io_fileno(struct io *io)
413 io_paused(struct io *io, int what)
415 return (io->flags & (IO_PAUSE_IN | IO_PAUSE_OUT)) == what;
419 * Buffered output functions
423 io_write(struct io *io, const void *buf, size_t len)
427 r = iobuf_queue(&io->iobuf, buf, len);
435 io_writev(struct io *io, const struct iovec *iov, int iovcount)
439 r = iobuf_queuev(&io->iobuf, iov, iovcount);
447 io_print(struct io *io, const char *s)
449 return io_write(io, s, strlen(s));
453 io_printf(struct io *io, const char *fmt, ...)
459 r = io_vprintf(io, fmt, ap);
466 io_vprintf(struct io *io, const char *fmt, va_list ap)
472 len = vasprintf(&buf, fmt, ap);
475 len = io_write(io, buf, len);
482 io_queued(struct io *io)
484 return iobuf_queued(&io->iobuf);
488 * Buffered input functions
492 io_data(struct io *io)
494 return iobuf_data(&io->iobuf);
498 io_datalen(struct io *io)
500 return iobuf_len(&io->iobuf);
504 io_getline(struct io *io, size_t *sz)
506 return iobuf_getline(&io->iobuf, sz);
510 io_drop(struct io *io, size_t sz)
512 return iobuf_drop(&io->iobuf, sz);
516 #define IO_READING(io) (((io)->flags & IO_RW) != IO_WRITE)
517 #define IO_WRITING(io) (((io)->flags & IO_RW) != IO_READ)
520 * Setup the necessary events as required by the current io state,
521 * honouring duplex mode and i/o pauses.
524 io_reload(struct io *io)
528 /* io will be reloaded at release time */
529 if (io->flags & IO_HELD)
532 iobuf_normalize(&io->iobuf);
541 io_debug("io_reload(%p)\n", io);
544 if (IO_READING(io) && !(io->flags & IO_PAUSE_IN))
546 if (IO_WRITING(io) && !(io->flags & IO_PAUSE_OUT) && io_queued(io))
549 io_reset(io, events, io_dispatch);
552 /* Set the requested event. */
554 io_reset(struct io *io, short events, void (*dispatch)(int, short, void*))
556 struct timeval tv, *ptv;
558 io_debug("io_reset(%p, %s, %p) -> %s\n",
559 io, io_evstr(events), dispatch, io_strio(io));
562 * Indicate that the event has already been reset so that reload
563 * is not called on frame_leave.
565 io->flags |= IO_RESET;
567 if (event_initialized(&io->ev))
571 * The io is paused by the user, so we don't want the timeout to be
577 event_set(&io->ev, io->sock, events, dispatch, io);
578 if (io->timeout >= 0) {
579 tv.tv_sec = io->timeout / 1000;
580 tv.tv_usec = (io->timeout % 1000) * 1000;
585 event_add(&io->ev, ptv);
589 io_pending(struct io *io)
591 return iobuf_len(&io->iobuf);
595 io_strflags(int flags)
601 switch (flags & IO_RW) {
603 (void)strlcat(buf, "rw", sizeof buf);
606 (void)strlcat(buf, "R", sizeof buf);
609 (void)strlcat(buf, "W", sizeof buf);
612 (void)strlcat(buf, "RW", sizeof buf);
616 if (flags & IO_PAUSE_IN)
617 (void)strlcat(buf, ",F_PI", sizeof buf);
618 if (flags & IO_PAUSE_OUT)
619 (void)strlcat(buf, ",F_PO", sizeof buf);
635 (void)strlcat(buf, "<NONE>", sizeof(buf));
639 if (ev & EV_TIMEOUT) {
640 (void)strlcat(buf, "EV_TIMEOUT", sizeof(buf));
647 (void)strlcat(buf, "|", sizeof(buf));
648 (void)strlcat(buf, "EV_READ", sizeof(buf));
655 (void)strlcat(buf, "|", sizeof(buf));
656 (void)strlcat(buf, "EV_WRITE", sizeof(buf));
661 if (ev & EV_SIGNAL) {
663 (void)strlcat(buf, "|", sizeof(buf));
664 (void)strlcat(buf, "EV_SIGNAL", sizeof(buf));
671 (void)strlcat(buf, "|", sizeof(buf));
672 (void)strlcat(buf, "EV_?=0x", sizeof(buf));
673 (void)snprintf(buf2, sizeof(buf2), "%hx", ev);
674 (void)strlcat(buf, buf2, sizeof(buf));
681 io_dispatch(int fd, short ev, void *humppa)
683 struct io *io = humppa;
688 io_frame_enter("io_dispatch", io, ev);
690 if (ev == EV_TIMEOUT) {
691 io_callback(io, IO_TIMEOUT);
695 if (ev & EV_WRITE && (w = io_queued(io))) {
696 if ((n = iobuf_write(&io->iobuf, io->sock)) < 0) {
697 if (n == IOBUF_WANT_WRITE) /* kqueue bug? */
699 if (n == IOBUF_CLOSED)
700 io_callback(io, IO_DISCONNECTED);
703 io->error = strerror(errno);
705 io_callback(io, IO_ERROR);
709 if (w > io->lowat && w - n <= io->lowat)
710 io_callback(io, IO_LOWAT);
715 iobuf_normalize(&io->iobuf);
716 if ((n = iobuf_read(&io->iobuf, io->sock)) < 0) {
717 if (n == IOBUF_CLOSED)
718 io_callback(io, IO_DISCONNECTED);
721 io->error = strerror(errno);
723 io_callback(io, IO_ERROR);
728 io_callback(io, IO_DATAIN);
736 io_callback(struct io *io, int evt)
738 io->cb(io, evt, io->arg);
742 io_connect(struct io *io, const struct sockaddr *sa, const struct sockaddr *bsa)
744 int sock, errno_save;
746 if ((sock = socket(sa->sa_family, SOCK_STREAM, 0)) == -1)
749 io_set_nonblocking(sock);
750 io_set_nolinger(sock);
752 if (bsa && bind(sock, bsa, bsa->sa_len) == -1)
755 if (connect(sock, sa, sa->sa_len) == -1)
756 if (errno != EINPROGRESS)
760 io_reset(io, EV_WRITE, io_dispatch_connect);
769 io->error = strerror(errno);
775 io_dispatch_connect(int fd, short ev, void *humppa)
777 struct io *io = humppa;
781 io_frame_enter("io_dispatch_connect", io, ev);
783 if (ev == EV_TIMEOUT) {
786 io_callback(io, IO_TIMEOUT);
789 r = getsockopt(fd, SOL_SOCKET, SO_ERROR, &e, &sl);
791 warn("io_dispatch_connect: getsockopt");
797 io->error = strerror(e);
798 io_callback(io, e == ETIMEDOUT ? IO_TIMEOUT : IO_ERROR);
801 io->state = IO_STATE_UP;
802 io_callback(io, IO_CONNECTED);
814 static char buf[128];
817 e = ERR_peek_last_error();
819 ERR_error_string(e, buf);
823 return ("No TLS error");
827 io_start_tls(struct io *io, void *tls)
831 mode = io->flags & IO_RW;
832 if (mode == 0 || mode == IO_RW)
833 errx(1, "io_start_tls(): full-duplex or unset");
836 errx(1, "io_start_tls(): TLS already started");
839 if (SSL_set_fd(io->tls, io->sock) == 0) {
840 ssl_error("io_start_tls:SSL_set_fd");
844 if (mode == IO_WRITE) {
845 io->state = IO_STATE_CONNECT_TLS;
846 SSL_set_connect_state(io->tls);
847 io_reset(io, EV_WRITE, io_dispatch_connect_tls);
849 io->state = IO_STATE_ACCEPT_TLS;
850 SSL_set_accept_state(io->tls);
851 io_reset(io, EV_READ, io_dispatch_accept_tls);
858 io_dispatch_accept_tls(int fd, short event, void *humppa)
860 struct io *io = humppa;
863 io_frame_enter("io_dispatch_accept_tls", io, event);
865 if (event == EV_TIMEOUT) {
866 io_callback(io, IO_TIMEOUT);
870 if ((ret = SSL_accept(io->tls)) > 0) {
871 io->state = IO_STATE_UP;
872 io_callback(io, IO_TLSREADY);
876 switch ((e = SSL_get_error(io->tls, ret))) {
877 case SSL_ERROR_WANT_READ:
878 io_reset(io, EV_READ, io_dispatch_accept_tls);
880 case SSL_ERROR_WANT_WRITE:
881 io_reset(io, EV_WRITE, io_dispatch_accept_tls);
884 io->error = io_tls_error();
885 ssl_error("io_dispatch_accept_tls:SSL_accept");
886 io_callback(io, IO_ERROR);
895 io_dispatch_connect_tls(int fd, short event, void *humppa)
897 struct io *io = humppa;
900 io_frame_enter("io_dispatch_connect_tls", io, event);
902 if (event == EV_TIMEOUT) {
903 io_callback(io, IO_TIMEOUT);
907 if ((ret = SSL_connect(io->tls)) > 0) {
908 io->state = IO_STATE_UP;
909 io_callback(io, IO_TLSREADY);
913 switch ((e = SSL_get_error(io->tls, ret))) {
914 case SSL_ERROR_WANT_READ:
915 io_reset(io, EV_READ, io_dispatch_connect_tls);
917 case SSL_ERROR_WANT_WRITE:
918 io_reset(io, EV_WRITE, io_dispatch_connect_tls);
921 io->error = io_tls_error();
922 ssl_error("io_dispatch_connect_ssl:SSL_connect");
923 io_callback(io, IO_TLSERROR);
932 io_dispatch_read_tls(int fd, short event, void *humppa)
934 struct io *io = humppa;
937 io_frame_enter("io_dispatch_read_tls", io, event);
939 if (event == EV_TIMEOUT) {
940 io_callback(io, IO_TIMEOUT);
945 iobuf_normalize(&io->iobuf);
946 switch ((n = iobuf_read_tls(&io->iobuf, (SSL*)io->tls))) {
947 case IOBUF_WANT_READ:
948 io_reset(io, EV_READ, io_dispatch_read_tls);
950 case IOBUF_WANT_WRITE:
951 io_reset(io, EV_WRITE, io_dispatch_read_tls);
954 io_callback(io, IO_DISCONNECTED);
958 io->error = strerror(errno);
960 io_callback(io, IO_ERROR);
963 io->error = io_tls_error();
964 ssl_error("io_dispatch_read_tls:SSL_read");
965 io_callback(io, IO_ERROR);
968 io_debug("io_dispatch_read_tls(...) -> r=%d\n", n);
969 io_callback(io, IO_DATAIN);
970 if (current == io && IO_READING(io) && SSL_pending(io->tls))
979 io_dispatch_write_tls(int fd, short event, void *humppa)
981 struct io *io = humppa;
985 io_frame_enter("io_dispatch_write_tls", io, event);
987 if (event == EV_TIMEOUT) {
988 io_callback(io, IO_TIMEOUT);
993 switch ((n = iobuf_write_tls(&io->iobuf, (SSL*)io->tls))) {
994 case IOBUF_WANT_READ:
995 io_reset(io, EV_READ, io_dispatch_write_tls);
997 case IOBUF_WANT_WRITE:
998 io_reset(io, EV_WRITE, io_dispatch_write_tls);
1001 io_callback(io, IO_DISCONNECTED);
1004 saved_errno = errno;
1005 io->error = strerror(errno);
1006 errno = saved_errno;
1007 io_callback(io, IO_ERROR);
1009 case IOBUF_TLSERROR:
1010 io->error = io_tls_error();
1011 ssl_error("io_dispatch_write_tls:SSL_write");
1012 io_callback(io, IO_ERROR);
1015 io_debug("io_dispatch_write_tls(...) -> w=%d\n", n);
1017 if (w > io->lowat && w2 <= io->lowat)
1018 io_callback(io, IO_LOWAT);
1027 io_reload_tls(struct io *io)
1030 void (*dispatch)(int, short, void*) = NULL;
1032 switch (io->state) {
1033 case IO_STATE_CONNECT_TLS:
1035 dispatch = io_dispatch_connect_tls;
1037 case IO_STATE_ACCEPT_TLS:
1039 dispatch = io_dispatch_accept_tls;
1043 if (IO_READING(io) && !(io->flags & IO_PAUSE_IN)) {
1045 dispatch = io_dispatch_read_tls;
1047 else if (IO_WRITING(io) && !(io->flags & IO_PAUSE_OUT) &&
1050 dispatch = io_dispatch_write_tls;
1053 return; /* paused */
1056 errx(1, "io_reload_tls(): bad state");
1059 io_reset(io, ev, dispatch);