2 * PgBouncer - Lightweight connection pooler for PostgreSQL.
4 * Copyright (c) 2007-2009 Marko Kreen, Skype Technologies OÜ
6 * Permission to use, copy, modify, and/or distribute this software for any
7 * purpose with or without fee is hereby granted, provided that the above
8 * copyright notice and this permission notice appear in all copies.
10 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
22 * The task is to copy data from one socket to another
23 * efficiently, while allowing callbacks to look
29 #ifdef USUAL_LIBSSL_FOR_TLS
33 /* sbuf_main_loop() skip_recv values */
35 #define SKIP_RECV true
44 SBUF_TLS_DO_HANDSHAKE,
45 SBUF_TLS_IN_HANDSHAKE,
57 #define AssertSanity(sbuf) do { \
58 Assert(iobuf_sane((sbuf)->io)); \
61 #define AssertActive(sbuf) do { \
62 Assert((sbuf)->sock > 0); \
66 /* declare static stuff */
67 static bool sbuf_queue_send(SBuf *sbuf) _MUSTCHECK;
68 static bool sbuf_send_pending(SBuf *sbuf) _MUSTCHECK;
69 static bool sbuf_process_pending(SBuf *sbuf) _MUSTCHECK;
70 static void sbuf_connect_cb(evutil_socket_t sock, short flags, void *arg);
71 static void sbuf_recv_cb(evutil_socket_t sock, short flags, void *arg);
72 static void sbuf_send_cb(evutil_socket_t sock, short flags, void *arg);
73 static void sbuf_try_resync(SBuf *sbuf, bool release);
74 static bool sbuf_wait_for_data(SBuf *sbuf) _MUSTCHECK;
75 static void sbuf_main_loop(SBuf *sbuf, bool skip_recv);
76 static bool sbuf_call_proto(SBuf *sbuf, int event) /* _MUSTCHECK */;
77 static bool sbuf_actual_recv(SBuf *sbuf, unsigned len) _MUSTCHECK;
78 static bool sbuf_after_connect_check(SBuf *sbuf) _MUSTCHECK;
79 static bool handle_tls_handshake(SBuf *sbuf) /* _MUSTCHECK */;
82 static int raw_sbufio_recv(struct SBuf *sbuf, void *dst, unsigned int len);
83 static int raw_sbufio_send(struct SBuf *sbuf, const void *data, unsigned int len);
84 static int raw_sbufio_close(struct SBuf *sbuf);
85 static const SBufIO raw_sbufio_ops = {
93 static int tls_sbufio_recv(struct SBuf *sbuf, void *dst, unsigned int len);
94 static int tls_sbufio_send(struct SBuf *sbuf, const void *data, unsigned int len);
95 static int tls_sbufio_close(struct SBuf *sbuf);
96 static const SBufIO tls_sbufio_ops = {
101 static void sbuf_tls_handshake_cb(evutil_socket_t fd, short flags, void *_sbuf);
104 /*********************************
106 *********************************/
108 /* initialize SBuf with proto handler */
109 void sbuf_init(SBuf *sbuf, sbuf_cb_t proto_fn)
111 memset(sbuf, 0, sizeof(SBuf));
112 sbuf->proto_cb = proto_fn;
113 sbuf->ops = &raw_sbufio_ops;
116 /* got new socket from accept() */
117 bool sbuf_accept(SBuf *sbuf, int sock, bool is_unix)
121 Assert(iobuf_empty(sbuf->io) && sbuf->sock == 0);
125 if (!tune_socket(sock, is_unix))
129 res = sbuf_wait_for_data(sbuf);
132 /* socket should already have some data (linux only) */
133 if (cf_tcp_defer_accept && !is_unix) {
134 sbuf_main_loop(sbuf, DO_RECV);
141 sbuf_call_proto(sbuf, SBUF_EV_RECV_FAILED);
145 /* need to connect() to get a socket */
146 bool sbuf_connect(SBuf *sbuf, const struct sockaddr *sa, int sa_len, int timeout_sec)
149 struct timeval timeout;
150 bool is_unix = sa->sa_family == AF_UNIX;
152 Assert(iobuf_empty(sbuf->io) && sbuf->sock == 0);
158 sock = socket(sa->sa_family, SOCK_STREAM, 0);
160 /* probably fd limit */
164 if (!tune_socket(sock, is_unix))
169 timeout.tv_sec = timeout_sec;
172 /* launch connection */
173 res = safe_connect(sock, sa, sa_len);
175 /* unix socket gives connection immediately */
176 sbuf_connect_cb(sock, EV_WRITE, sbuf);
178 } else if (errno == EINPROGRESS || errno == EAGAIN) {
179 /* tcp socket needs waiting */
180 event_set(&sbuf->ev, sock, EV_WRITE, sbuf_connect_cb, sbuf);
181 res = event_add(&sbuf->ev, &timeout);
183 sbuf->wait_type = W_CONNECT;
189 log_warning("sbuf_connect failed: %s", strerror(errno));
194 sbuf_call_proto(sbuf, SBUF_EV_CONNECT_FAILED);
198 /* don't wait for data on this socket */
199 bool sbuf_pause(SBuf *sbuf)
202 Assert(sbuf->wait_type == W_RECV);
204 if (event_del(&sbuf->ev) < 0) {
205 log_warning("event_del: %s", strerror(errno));
208 sbuf->wait_type = W_NONE;
212 /* resume from pause, start waiting for data */
213 void sbuf_continue(SBuf *sbuf)
215 bool do_recv = DO_RECV;
219 res = sbuf_wait_for_data(sbuf);
221 /* drop if problems */
222 sbuf_call_proto(sbuf, SBUF_EV_RECV_FAILED);
227 * It's tempting to try to avoid the recv() but that would
228 * only work if no code wants to see full packet.
230 * This is not true in ServerParameter case.
233 * if (sbuf->recv_pos - sbuf->pkt_pos >= SBUF_SMALL_PKT)
237 sbuf_main_loop(sbuf, do_recv);
241 * Resume from pause and give socket over to external
244 * The callback will be called with arg given to sbuf_init.
246 bool sbuf_continue_with_callback(SBuf *sbuf, sbuf_libevent_cb user_cb)
252 event_set(&sbuf->ev, sbuf->sock, EV_READ | EV_PERSIST,
255 err = event_add(&sbuf->ev, NULL);
257 log_warning("sbuf_continue_with_callback: %s", strerror(errno));
260 sbuf->wait_type = W_RECV;
264 bool sbuf_use_callback_once(SBuf *sbuf, short ev, sbuf_libevent_cb user_cb)
269 if (sbuf->wait_type != W_NONE) {
270 err = event_del(&sbuf->ev);
271 sbuf->wait_type = W_NONE; /* make sure its called only once */
273 log_warning("sbuf_queue_once: event_del failed: %s", strerror(errno));
278 /* setup one one-off event handler */
279 event_set(&sbuf->ev, sbuf->sock, ev, user_cb, sbuf);
280 err = event_add(&sbuf->ev, NULL);
282 log_warning("sbuf_queue_once: event_add failed: %s", strerror(errno));
285 sbuf->wait_type = W_ONCE;
289 /* socket cleanup & close: keeps .handler and .arg values */
290 bool sbuf_close(SBuf *sbuf)
292 if (sbuf->wait_type) {
294 /* event_del() acts funny occasionally, debug it */
296 if (event_del(&sbuf->ev) < 0) {
298 log_warning("event_del: %s", strerror(errno));
300 log_warning("event_del: libevent error");
302 /* we can retry whole sbuf_close() if needed */
303 /* if (errno == ENOMEM) return false; */
309 sbuf->pkt_remain = 0;
310 sbuf->pkt_action = sbuf->wait_type = 0;
312 slab_free(iobuf_cache, sbuf->io);
318 /* proto_fn tells to send some bytes to socket */
319 void sbuf_prepare_send(SBuf *sbuf, SBuf *dst, unsigned amount)
322 Assert(sbuf->pkt_remain == 0);
323 /* Assert(sbuf->pkt_action == ACT_UNSET || sbuf->pkt_action == ACT_SEND || iobuf_amount_pending(&sbuf->io)); */
326 sbuf->pkt_action = ACT_SEND;
327 sbuf->pkt_remain = amount;
331 /* proto_fn tells to skip some amount of bytes */
332 void sbuf_prepare_skip(SBuf *sbuf, unsigned amount)
335 Assert(sbuf->pkt_remain == 0);
336 /* Assert(sbuf->pkt_action == ACT_UNSET || iobuf_send_pending_avail(&sbuf->io)); */
339 sbuf->pkt_action = ACT_SKIP;
340 sbuf->pkt_remain = amount;
343 /* proto_fn tells to skip some amount of bytes */
344 void sbuf_prepare_fetch(SBuf *sbuf, unsigned amount)
347 Assert(sbuf->pkt_remain == 0);
348 /* Assert(sbuf->pkt_action == ACT_UNSET || iobuf_send_pending_avail(&sbuf->io)); */
351 sbuf->pkt_action = ACT_CALL;
352 sbuf->pkt_remain = amount;
353 /* sbuf->dst = NULL; // FIXME ?? */
356 /*************************
358 *************************/
361 * Call proto callback with proper struct MBuf.
363 * If callback returns true it used one of sbuf_prepare_* on sbuf,
364 * and processing can continue.
366 * If it returned false it used sbuf_pause(), sbuf_close() or simply
367 * wants to wait for next event loop (e.g. too few data available).
368 * Callee should not touch sbuf in that case and just return to libevent.
370 static bool sbuf_call_proto(SBuf *sbuf, int event)
373 IOBuf *io = sbuf->io;
377 Assert(event != SBUF_EV_READ || iobuf_amount_parse(io) > 0);
379 /* if pkt callback, limit only with current packet */
380 if (event == SBUF_EV_PKT_CALLBACK) {
381 iobuf_parse_limit(io, &mbuf, sbuf->pkt_remain);
382 } else if (event == SBUF_EV_READ) {
383 iobuf_parse_all(io, &mbuf);
385 memset(&mbuf, 0, sizeof(mbuf));
387 res = sbuf->proto_cb(sbuf, event, &mbuf);
390 Assert(event != SBUF_EV_READ || !res || sbuf->sock > 0);
395 /* let's wait for new data */
396 static bool sbuf_wait_for_data(SBuf *sbuf)
400 event_set(&sbuf->ev, sbuf->sock, EV_READ | EV_PERSIST, sbuf_recv_cb, sbuf);
401 err = event_add(&sbuf->ev, NULL);
403 log_warning("sbuf_wait_for_data: event_add failed: %s", strerror(errno));
406 sbuf->wait_type = W_RECV;
410 static void sbuf_recv_forced_cb(evutil_socket_t sock, short flags, void *arg)
414 sbuf->wait_type = W_NONE;
416 if (sbuf_wait_for_data(sbuf)) {
417 sbuf_recv_cb(sock, flags, arg);
419 sbuf_call_proto(sbuf, SBUF_EV_RECV_FAILED);
423 static bool sbuf_wait_for_data_forced(SBuf *sbuf)
426 struct timeval tv_min;
431 if (sbuf->wait_type != W_NONE) {
432 event_del(&sbuf->ev);
433 sbuf->wait_type = W_NONE;
436 event_set(&sbuf->ev, sbuf->sock, EV_READ, sbuf_recv_forced_cb, sbuf);
437 err = event_add(&sbuf->ev, &tv_min);
439 log_warning("sbuf_wait_for_data: event_add failed: %s", strerror(errno));
442 sbuf->wait_type = W_ONCE;
446 /* libevent EV_WRITE: called when dest socket is writable again */
447 static void sbuf_send_cb(evutil_socket_t sock, short flags, void *arg)
452 /* sbuf was closed before in this loop */
457 Assert(sbuf->wait_type == W_SEND);
459 sbuf->wait_type = W_NONE;
461 /* prepare normal situation for sbuf_main_loop */
462 res = sbuf_wait_for_data(sbuf);
464 /* here we should certainly skip recv() */
465 sbuf_main_loop(sbuf, SKIP_RECV);
467 /* drop if problems */
468 sbuf_call_proto(sbuf, SBUF_EV_SEND_FAILED);
472 /* socket is full, wait until it's writable again */
473 static bool sbuf_queue_send(SBuf *sbuf)
477 Assert(sbuf->wait_type == W_RECV);
479 /* if false is returned, the socket will be closed later */
481 /* stop waiting for read events */
482 err = event_del(&sbuf->ev);
483 sbuf->wait_type = W_NONE; /* make sure its called only once */
485 log_warning("sbuf_queue_send: event_del failed: %s", strerror(errno));
489 /* instead wait for EV_WRITE on destination socket */
490 event_set(&sbuf->ev, sbuf->dst->sock, EV_WRITE, sbuf_send_cb, sbuf);
491 err = event_add(&sbuf->ev, NULL);
493 log_warning("sbuf_queue_send: event_add failed: %s", strerror(errno));
496 sbuf->wait_type = W_SEND;
502 * There's data in buffer to be sent. Returns bool if processing can continue.
504 * Does not look at pkt_pos/remain fields, expects them to be merged to send_*
506 static bool sbuf_send_pending(SBuf *sbuf)
509 IOBuf *io = sbuf->io;
512 Assert(sbuf->dst || iobuf_amount_pending(io) == 0);
515 /* how much data is available for sending */
516 avail = iobuf_amount_pending(io);
520 if (sbuf->dst->sock == 0) {
521 log_error("sbuf_send_pending: no dst sock?");
525 /* actually send it */
526 //res = iobuf_send_pending(io, sbuf->dst->sock);
527 res = sbuf_op_send(sbuf->dst, io->buf + io->done_pos, avail);
530 } else if (res < 0) {
531 if (errno == EAGAIN) {
532 if (!sbuf_queue_send(sbuf))
533 /* drop if queue failed */
534 sbuf_call_proto(sbuf, SBUF_EV_SEND_FAILED);
536 sbuf_call_proto(sbuf, SBUF_EV_SEND_FAILED);
544 * Should do sbuf_queue_send() immediately?
546 * To be sure, let's run into EAGAIN.
551 /* process as much data as possible */
552 static bool sbuf_process_pending(SBuf *sbuf)
555 IOBuf *io = sbuf->io;
556 bool full = iobuf_amount_recv(io) <= 0;
565 * The (avail <= SBUF_SMALL_PKT) check is to avoid partial pkts.
566 * As SBuf should not assume knowledge about packets,
567 * the check is not done in !full case. Packet handler can
568 * then still notify about partial packet by returning false.
570 avail = iobuf_amount_parse(io);
571 if (avail == 0 || (full && avail <= SBUF_SMALL_PKT))
575 * If start of packet, process packet header.
577 if (sbuf->pkt_remain == 0) {
578 res = sbuf_call_proto(sbuf, SBUF_EV_READ);
581 Assert(sbuf->pkt_remain > 0);
584 if (sbuf->pkt_action == ACT_SKIP || sbuf->pkt_action == ACT_CALL) {
585 /* send any pending data before skipping */
586 if (iobuf_amount_pending(io) > 0) {
587 res = sbuf_send_pending(sbuf);
593 if (avail > sbuf->pkt_remain)
594 avail = sbuf->pkt_remain;
596 switch (sbuf->pkt_action) {
598 iobuf_tag_send(io, avail);
601 res = sbuf_call_proto(sbuf, SBUF_EV_PKT_CALLBACK);
605 /* after callback, skip pkt */
607 iobuf_tag_skip(io, avail);
610 sbuf->pkt_remain -= avail;
613 return sbuf_send_pending(sbuf);
616 /* reposition at buffer start again */
617 static void sbuf_try_resync(SBuf *sbuf, bool release)
619 IOBuf *io = sbuf->io;
622 log_noise("resync(%d): done=%d, parse=%d, recv=%d",
624 io->done_pos, io->parse_pos, io->recv_pos);
631 if (release && iobuf_empty(io)) {
632 slab_free(iobuf_cache, io);
635 iobuf_try_resync(io, SBUF_SMALL_PKT);
639 /* actually ask kernel for more data */
640 static bool sbuf_actual_recv(SBuf *sbuf, unsigned len)
643 IOBuf *io = sbuf->io;
644 uint8_t *dst = io->buf + io->recv_pos;
645 unsigned avail = iobuf_amount_recv(io);
648 got = sbuf_op_recv(sbuf, dst, len);
651 } else if (got == 0) {
652 /* eof from socket */
653 sbuf_call_proto(sbuf, SBUF_EV_RECV_FAILED);
655 } else if (got < 0 && errno != EAGAIN) {
656 /* some error occurred */
657 sbuf_call_proto(sbuf, SBUF_EV_RECV_FAILED);
663 /* callback for libevent EV_READ */
664 static void sbuf_recv_cb(evutil_socket_t sock, short flags, void *arg)
667 sbuf_main_loop(sbuf, DO_RECV);
670 static bool allocate_iobuf(SBuf *sbuf)
672 if (sbuf->io == NULL) {
673 sbuf->io = slab_alloc(iobuf_cache);
674 if (sbuf->io == NULL) {
675 sbuf_call_proto(sbuf, SBUF_EV_RECV_FAILED);
678 iobuf_reset(sbuf->io);
684 * Main recv-parse-send-repeat loop.
686 * Reason for skip_recv is to avoid extra recv(). The problem with it
687 * is EOF from socket. Currently that means that the pending data is
688 * dropped. Fortunately server sockets are not paused and dropping
689 * data from client is no problem. So only place where skip_recv is
690 * important is sbuf_send_cb().
692 static void sbuf_main_loop(SBuf *sbuf, bool skip_recv)
697 /* sbuf was closed before in this event loop */
701 /* reading should be disabled when waiting */
702 Assert(sbuf->wait_type == W_RECV);
705 if (!allocate_iobuf(sbuf))
708 /* avoid recv() if asked */
713 /* make room in buffer */
714 sbuf_try_resync(sbuf, false);
716 /* avoid spending too much time on single socket */
717 if (cf_sbuf_loopcnt > 0 && loopcnt >= cf_sbuf_loopcnt) {
720 log_debug("loopcnt full");
722 * sbuf_process_pending() avoids some data if buffer is full,
723 * but as we exit processing loop here, we need to retry
724 * after resync to process all data. (result is ignored)
726 _ignore = sbuf_process_pending(sbuf);
729 sbuf_wait_for_data_forced(sbuf);
735 * here used to be if (free > SBUF_SMALL_PKT) check
736 * but with skip_recv switch its should not be needed anymore.
738 free = iobuf_amount_recv(sbuf->io);
741 * When suspending, try to hit packet boundary ASAP.
743 if (cf_pause_mode == P_SUSPEND
744 && sbuf->pkt_remain > 0
745 && sbuf->pkt_remain < free)
747 free = sbuf->pkt_remain;
750 /* now fetch the data */
751 ok = sbuf_actual_recv(sbuf, free);
758 ok = sbuf_process_pending(sbuf);
762 /* if the buffer is full, there can be more data available */
763 if (iobuf_amount_recv(sbuf->io) <= 0)
767 sbuf_try_resync(sbuf, true);
769 /* notify proto that all is sent */
770 if (sbuf_is_empty(sbuf))
771 sbuf_call_proto(sbuf, SBUF_EV_FLUSH);
773 if (sbuf->tls_state == SBUF_TLS_DO_HANDSHAKE) {
774 sbuf->pkt_action = SBUF_TLS_IN_HANDSHAKE;
775 handle_tls_handshake(sbuf);
779 /* check if there is any error pending on socket */
780 static bool sbuf_after_connect_check(SBuf *sbuf)
783 socklen_t optlen = sizeof(optval);
785 err = getsockopt(sbuf->sock, SOL_SOCKET, SO_ERROR, (void*)&optval, &optlen);
787 log_debug("sbuf_after_connect_check: getsockopt: %s",
792 log_debug("sbuf_after_connect_check: pending error: %s",
799 /* callback for libevent EV_WRITE when connecting */
800 static void sbuf_connect_cb(evutil_socket_t sock, short flags, void *arg)
804 Assert(sbuf->wait_type == W_CONNECT || sbuf->wait_type == W_NONE);
805 sbuf->wait_type = W_NONE;
807 if (flags & EV_WRITE) {
808 if (!sbuf_after_connect_check(sbuf))
810 if (!sbuf_call_proto(sbuf, SBUF_EV_CONNECT_OK))
812 if (!sbuf_wait_for_data(sbuf))
817 sbuf_call_proto(sbuf, SBUF_EV_CONNECT_FAILED);
820 /* send some data to listening socket */
821 bool sbuf_answer(SBuf *sbuf, const void *buf, unsigned len)
826 res = sbuf_op_send(sbuf, buf, len);
828 log_debug("sbuf_answer: error sending: %s", strerror(errno));
829 } else if ((unsigned)res != len) {
830 log_debug("sbuf_answer: partial send: len=%d sent=%d", len, res);
832 return (unsigned)res == len;
839 static int raw_sbufio_recv(struct SBuf *sbuf, void *dst, unsigned int len)
841 return safe_recv(sbuf->sock, dst, len, 0);
844 static int raw_sbufio_send(struct SBuf *sbuf, const void *data, unsigned int len)
846 return safe_send(sbuf->sock, data, len, 0);
849 static int raw_sbufio_close(struct SBuf *sbuf)
851 if (sbuf->sock > 0) {
852 safe_close(sbuf->sock);
864 static struct tls_config *client_accept_conf;
865 static struct tls_config *server_connect_conf;
866 static struct tls *client_accept_base;
872 static void setup_tls(struct tls_config *conf, const char *pfx, int sslmode,
873 const char *protocols, const char *ciphers,
874 const char *keyfile, const char *certfile, const char *cafile,
875 const char *dheparams, const char *ecdhecurve,
880 uint32_t protos = TLS_PROTOCOLS_ALL;
881 err = tls_config_parse_protocols(&protos, protocols);
883 log_error("invalid %s_protocols: %s", pfx, protocols);
885 tls_config_set_protocols(conf, protos);
889 err = tls_config_set_ciphers(conf, ciphers);
891 log_error("invalid %s_ciphers: %s", pfx, ciphers);
894 err = tls_config_set_dheparams(conf, dheparams);
896 log_error("invalid %s_dheparams: %s", pfx, dheparams);
899 err = tls_config_set_ecdhecurve(conf, ecdhecurve);
901 log_error("invalid %s_ecdhecurve: %s", pfx, ecdhecurve);
904 err = tls_config_set_ca_file(conf, cafile);
906 log_error("invalid %s_ca_file: %s", pfx, cafile);
909 err = tls_config_set_key_file(conf, keyfile);
911 log_error("invalid %s_key_file: %s", pfx, keyfile);
914 err = tls_config_set_cert_file(conf, certfile);
916 log_error("invalid %s_cert_file: %s", pfx, certfile);
920 /* TLS client, check server? */
921 if (sslmode == SSLMODE_VERIFY_FULL) {
922 tls_config_verify(conf);
923 } else if (sslmode == SSLMODE_VERIFY_CA) {
924 tls_config_verify(conf);
925 tls_config_insecure_noverifyname(conf);
927 tls_config_insecure_noverifycert(conf);
928 tls_config_insecure_noverifyname(conf);
931 /* TLS server, check client? */
932 if (sslmode == SSLMODE_VERIFY_FULL) {
933 tls_config_verify_client(conf);
934 } else if (sslmode == SSLMODE_VERIFY_CA) {
935 tls_config_verify_client(conf);
937 tls_config_verify_client_optional(conf);
942 void sbuf_tls_setup(void)
946 if (cf_client_tls_sslmode != SSLMODE_DISABLED) {
947 if (!*cf_client_tls_key_file || !*cf_client_tls_cert_file)
948 die("To allow TLS connections from clients, client_tls_key_file and client_tls_cert_file must be set.");
950 if (cf_auth_type == AUTH_CERT) {
951 if (cf_client_tls_sslmode != SSLMODE_VERIFY_FULL)
952 die("auth_type=cert requires client_tls_sslmode=SSLMODE_VERIFY_FULL");
953 if (*cf_client_tls_ca_file == '\0')
954 die("auth_type=cert requires client_tls_ca_file");
955 } else if (cf_client_tls_sslmode > SSLMODE_VERIFY_CA && *cf_client_tls_ca_file == '\0') {
956 die("client_tls_sslmode requires client_tls_ca_file");
961 fatal("tls_init failed");
963 if (cf_server_tls_sslmode != SSLMODE_DISABLED) {
964 server_connect_conf = tls_config_new();
965 if (!server_connect_conf)
966 die("tls_config_new failed 1");
967 setup_tls(server_connect_conf, "server_tls", cf_server_tls_sslmode,
968 cf_server_tls_protocols, cf_server_tls_ciphers,
969 cf_server_tls_key_file, cf_server_tls_cert_file,
970 cf_server_tls_ca_file, "", "", true);
973 if (cf_client_tls_sslmode != SSLMODE_DISABLED) {
974 client_accept_conf = tls_config_new();
975 if (!client_accept_conf)
976 die("tls_config_new failed 2");
977 setup_tls(client_accept_conf, "client_tls", cf_client_tls_sslmode,
978 cf_client_tls_protocols, cf_client_tls_ciphers,
979 cf_client_tls_key_file, cf_client_tls_cert_file,
980 cf_client_tls_ca_file, cf_client_tls_dheparams,
981 cf_client_tls_ecdhecurve, false);
983 client_accept_base = tls_server();
984 if (!client_accept_base)
985 die("server_base failed");
986 err = tls_configure(client_accept_base, client_accept_conf);
988 die("TLS setup failed: %s", tls_error(client_accept_base));
996 static bool handle_tls_handshake(SBuf *sbuf)
1000 err = tls_handshake(sbuf->tls);
1001 log_noise("tls_handshake: err=%d", err);
1002 if (err == TLS_WANT_POLLIN) {
1003 return sbuf_use_callback_once(sbuf, EV_READ, sbuf_tls_handshake_cb);
1004 } else if (err == TLS_WANT_POLLOUT) {
1005 return sbuf_use_callback_once(sbuf, EV_WRITE, sbuf_tls_handshake_cb);
1006 } else if (err == 0) {
1007 sbuf->tls_state = SBUF_TLS_OK;
1008 sbuf_call_proto(sbuf, SBUF_EV_TLS_READY);
1011 log_warning("TLS handshake error: %s", tls_error(sbuf->tls));
1016 static void sbuf_tls_handshake_cb(evutil_socket_t fd, short flags, void *_sbuf)
1019 sbuf->wait_type = W_NONE;
1020 if (!handle_tls_handshake(sbuf))
1021 sbuf_call_proto(sbuf, SBUF_EV_RECV_FAILED);
1025 * Accept TLS connection.
1028 bool sbuf_tls_accept(SBuf *sbuf)
1032 if (!sbuf_pause(sbuf))
1035 sbuf->ops = &tls_sbufio_ops;
1037 err = tls_accept_fds(client_accept_base, &sbuf->tls, sbuf->sock, sbuf->sock);
1038 log_noise("tls_accept_fds: err=%d", err);
1040 log_warning("TLS accept error: %s", tls_error(sbuf->tls));
1044 sbuf->tls_state = SBUF_TLS_DO_HANDSHAKE;
1049 * Connect to remote TLS host.
1052 bool sbuf_tls_connect(SBuf *sbuf, const char *hostname)
1057 if (!sbuf_pause(sbuf))
1060 if (cf_server_tls_sslmode != SSLMODE_VERIFY_FULL)
1063 ctls = tls_client();
1066 err = tls_configure(ctls, server_connect_conf);
1068 log_error("tls client config failed: %s", tls_error(ctls));
1074 sbuf->tls_host = hostname;
1075 sbuf->ops = &tls_sbufio_ops;
1077 err = tls_connect_fds(sbuf->tls, sbuf->sock, sbuf->sock, sbuf->tls_host);
1079 log_warning("TLS connect error: %s", tls_error(sbuf->tls));
1083 sbuf->tls_state = SBUF_TLS_DO_HANDSHAKE;
1091 static int tls_sbufio_recv(struct SBuf *sbuf, void *dst, unsigned int len)
1095 if (sbuf->tls_state != SBUF_TLS_OK) {
1100 out = tls_read(sbuf->tls, dst, len);
1101 log_noise("tls_read: req=%u out=%d", len, (int)out);
1104 } else if (out == TLS_WANT_POLLIN) {
1106 } else if (out == TLS_WANT_POLLOUT) {
1107 log_warning("tls_sbufio_recv: got TLS_WANT_POLLOUT");
1110 log_warning("tls_sbufio_recv: %s", tls_error(sbuf->tls));
1116 static int tls_sbufio_send(struct SBuf *sbuf, const void *data, unsigned int len)
1120 if (sbuf->tls_state != SBUF_TLS_OK) {
1125 out = tls_write(sbuf->tls, data, len);
1126 log_noise("tls_write: req=%u out=%d", len, (int)out);
1129 } else if (out == TLS_WANT_POLLOUT) {
1131 } else if (out == TLS_WANT_POLLIN) {
1132 log_warning("tls_sbufio_send: got TLS_WANT_POLLIN");
1135 log_warning("tls_sbufio_send: %s", tls_error(sbuf->tls));
1141 static int tls_sbufio_close(struct SBuf *sbuf)
1143 log_noise("tls_close");
1145 tls_close(sbuf->tls);
1146 tls_free(sbuf->tls);
1149 if (sbuf->sock > 0) {
1150 safe_close(sbuf->sock);
1156 void sbuf_cleanup(void)
1158 tls_free(client_accept_base);
1159 tls_config_free(client_accept_conf);
1160 tls_config_free(server_connect_conf);
1161 client_accept_conf = NULL;
1162 server_connect_conf = NULL;
1163 client_accept_base = NULL;
1168 void sbuf_tls_setup(void) { }
1169 bool sbuf_tls_accept(SBuf *sbuf) { return false; }
1170 bool sbuf_tls_connect(SBuf *sbuf, const char *hostname) { return false; }
1172 void sbuf_cleanup(void)
1176 static bool handle_tls_handshake(SBuf *sbuf)