2 * Asterisk -- An open source telephony toolkit.
4 * Copyright (C) 2007 - 2008, Digium, Inc.
6 * Luigi Rizzo (TCP and TLS server code)
7 * Brett Bryant <brettbryant@gmail.com> (updated for client support)
9 * See http://www.asterisk.org for more information about
10 * the Asterisk project. Please do not directly contact
11 * any of the maintainers of this project for assistance;
12 * the project provides a web site, mailing lists and IRC
13 * channels for your use.
15 * This program is free software, distributed under the terms of
16 * the GNU General Public License Version 2. See the LICENSE file
17 * at the top of the source tree.
22 * \brief Code to support TCP and TLS server/client
25 * \author Brett Bryant <brettbryant@gmail.com>
29 <support_level>core</support_level>
34 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
41 #include <sys/signal.h>
43 #include "asterisk/compat.h"
44 #include "asterisk/tcptls.h"
45 #include "asterisk/http.h"
46 #include "asterisk/utils.h"
47 #include "asterisk/strings.h"
48 #include "asterisk/options.h"
49 #include "asterisk/manager.h"
50 #include "asterisk/astobj2.h"
51 #include "asterisk/pbx.h"
53 /*! ao2 object used for the FILE stream fopencookie()/funopen() cookie. */
54 struct ast_tcptls_stream {
55 /*! SSL state if not NULL */
58 * \brief Start time from when an I/O sequence must complete
59 * by struct ast_tcptls_stream.timeout.
61 * \note If struct ast_tcptls_stream.start.tv_sec is zero then
62 * start time is the current I/O request.
66 * \brief The socket returned by accept().
68 * \note Set to -1 if the stream is closed.
72 * \brief Timeout in ms relative to struct ast_tcptls_stream.start
73 * to wait for an event on struct ast_tcptls_stream.fd.
75 * \note Set to -1 to disable timeout.
76 * \note The socket needs to be set to non-blocking for the timeout
77 * feature to work correctly.
80 /*! TRUE if stream can exclusively wait for fd input. */
84 void ast_tcptls_stream_set_timeout_disable(struct ast_tcptls_stream *stream)
86 ast_assert(stream != NULL);
91 void ast_tcptls_stream_set_timeout_inactivity(struct ast_tcptls_stream *stream, int timeout)
93 ast_assert(stream != NULL);
95 stream->start.tv_sec = 0;
96 stream->timeout = timeout;
99 void ast_tcptls_stream_set_timeout_sequence(struct ast_tcptls_stream *stream, struct timeval start, int timeout)
101 ast_assert(stream != NULL);
103 stream->start = start;
104 stream->timeout = timeout;
107 void ast_tcptls_stream_set_exclusive_input(struct ast_tcptls_stream *stream, int exclusive_input)
109 ast_assert(stream != NULL);
111 stream->exclusive_input = exclusive_input;
116 * \brief fopencookie()/funopen() stream read function.
118 * \param cookie Stream control data.
119 * \param buf Where to put read data.
120 * \param size Size of the buffer.
122 * \retval number of bytes put into buf.
123 * \retval 0 on end of file.
124 * \retval -1 on error.
126 static HOOK_T tcptls_stream_read(void *cookie, char *buf, LEN_T size)
128 struct ast_tcptls_stream *stream = cookie;
129 struct timeval start;
134 /* You asked for no data you got no data. */
138 if (!stream || stream->fd == -1) {
143 if (stream->start.tv_sec) {
144 start = stream->start;
152 res = SSL_read(stream->ssl, buf, size);
154 /* We read some payload data. */
157 switch (SSL_get_error(stream->ssl, res)) {
158 case SSL_ERROR_ZERO_RETURN:
159 /* Report EOF for a shutdown */
160 ast_debug(1, "TLS clean shutdown alert reading data\n");
162 case SSL_ERROR_WANT_READ:
163 if (!stream->exclusive_input) {
164 /* We cannot wait for data now. */
168 while ((ms = ast_remaining_ms(start, stream->timeout))) {
169 res = ast_wait_for_input(stream->fd, ms);
171 /* Socket is ready to be read. */
175 if (errno == EINTR || errno == EAGAIN) {
179 ast_debug(1, "TLS socket error waiting for read data: %s\n",
185 case SSL_ERROR_WANT_WRITE:
186 while ((ms = ast_remaining_ms(start, stream->timeout))) {
187 res = ast_wait_for_output(stream->fd, ms);
189 /* Socket is ready to be written. */
193 if (errno == EINTR || errno == EAGAIN) {
197 ast_debug(1, "TLS socket error waiting for write space: %s\n",
204 /* Report EOF for an undecoded SSL or transport error. */
205 ast_debug(1, "TLS transport or SSL error reading data\n");
209 /* Report EOF for a timeout */
210 ast_debug(1, "TLS timeout reading data\n");
215 #endif /* defined(DO_SSL) */
218 res = read(stream->fd, buf, size);
219 if (0 <= res || !stream->exclusive_input) {
220 /* Got data or we cannot wait for it. */
223 if (errno != EINTR && errno != EAGAIN) {
224 /* Not a retryable error. */
225 ast_debug(1, "TCP socket error reading data: %s\n",
229 ms = ast_remaining_ms(start, stream->timeout);
231 /* Report EOF for a timeout */
232 ast_debug(1, "TCP timeout reading data\n");
235 ast_wait_for_input(stream->fd, ms);
241 * \brief fopencookie()/funopen() stream write function.
243 * \param cookie Stream control data.
244 * \param buf Where to get data to write.
245 * \param size Size of the buffer.
247 * \retval number of bytes written from buf.
248 * \retval -1 on error.
250 static HOOK_T tcptls_stream_write(void *cookie, const char *buf, LEN_T size)
252 struct ast_tcptls_stream *stream = cookie;
253 struct timeval start;
260 /* You asked to write no data you wrote no data. */
264 if (!stream || stream->fd == -1) {
269 if (stream->start.tv_sec) {
270 start = stream->start;
280 res = SSL_write(stream->ssl, buf + written, remaining);
281 if (res == remaining) {
282 /* Everything was written. */
286 /* Successfully wrote part of the buffer. Try to write the rest. */
291 switch (SSL_get_error(stream->ssl, res)) {
292 case SSL_ERROR_ZERO_RETURN:
293 ast_debug(1, "TLS clean shutdown alert writing data\n");
295 /* Report partial write. */
300 case SSL_ERROR_WANT_READ:
301 ms = ast_remaining_ms(start, stream->timeout);
303 /* Report partial write. */
304 ast_debug(1, "TLS timeout writing data (want read)\n");
307 ast_wait_for_input(stream->fd, ms);
309 case SSL_ERROR_WANT_WRITE:
310 ms = ast_remaining_ms(start, stream->timeout);
312 /* Report partial write. */
313 ast_debug(1, "TLS timeout writing data (want write)\n");
316 ast_wait_for_output(stream->fd, ms);
319 /* Undecoded SSL or transport error. */
320 ast_debug(1, "TLS transport or SSL error writing data\n");
322 /* Report partial write. */
330 #endif /* defined(DO_SSL) */
335 res = write(stream->fd, buf + written, remaining);
336 if (res == remaining) {
337 /* Yay everything was written. */
341 /* Successfully wrote part of the buffer. Try to write the rest. */
346 if (errno != EINTR && errno != EAGAIN) {
347 /* Not a retryable error. */
348 ast_debug(1, "TCP socket error writing: %s\n", strerror(errno));
354 ms = ast_remaining_ms(start, stream->timeout);
356 /* Report partial write. */
357 ast_debug(1, "TCP timeout writing data\n");
360 ast_wait_for_output(stream->fd, ms);
366 * \brief fopencookie()/funopen() stream close function.
368 * \param cookie Stream control data.
370 * \retval 0 on success.
371 * \retval -1 on error.
373 static int tcptls_stream_close(void *cookie)
375 struct ast_tcptls_stream *stream = cookie;
382 if (stream->fd != -1) {
388 * According to the TLS standard, it is acceptable for an
389 * application to only send its shutdown alert and then
390 * close the underlying connection without waiting for
391 * the peer's response (this way resources can be saved,
392 * as the process can already terminate or serve another
395 res = SSL_shutdown(stream->ssl);
397 ast_log(LOG_ERROR, "SSL_shutdown() failed: %d\n",
398 SSL_get_error(stream->ssl, res));
401 if (!stream->ssl->server) {
402 /* For client threads, ensure that the error stack is cleared */
406 SSL_free(stream->ssl);
409 #endif /* defined(DO_SSL) */
412 * Issuing shutdown() is necessary here to avoid a race
413 * condition where the last data written may not appear
414 * in the TCP stream. See ASTERISK-23548
416 shutdown(stream->fd, SHUT_RDWR);
417 if (close(stream->fd)) {
418 ast_log(LOG_ERROR, "close() failed: %s\n", strerror(errno));
422 ao2_t_ref(stream, -1, "Closed tcptls stream cookie");
429 * \brief fopencookie()/funopen() stream destructor function.
431 * \param cookie Stream control data.
435 static void tcptls_stream_dtor(void *cookie)
437 struct ast_tcptls_stream *stream = cookie;
439 ast_assert(stream->fd == -1);
444 * \brief fopencookie()/funopen() stream allocation function.
446 * \retval stream_cookie on success.
447 * \retval NULL on error.
449 static struct ast_tcptls_stream *tcptls_stream_alloc(void)
451 struct ast_tcptls_stream *stream;
453 stream = ao2_alloc_options(sizeof(*stream), tcptls_stream_dtor,
454 AO2_ALLOC_OPT_LOCK_NOLOCK);
457 stream->timeout = -1;
464 * \brief Open a custom FILE stream for tcptls.
466 * \param stream Stream cookie control data.
467 * \param ssl SSL state if not NULL.
468 * \param fd Socket file descriptor.
469 * \param timeout ms to wait for an event on fd. -1 if timeout disabled.
471 * \retval fp on success.
472 * \retval NULL on error.
474 static FILE *tcptls_stream_fopen(struct ast_tcptls_stream *stream, SSL *ssl, int fd, int timeout)
478 #if defined(HAVE_FOPENCOOKIE) /* the glibc/linux interface */
479 static const cookie_io_functions_t cookie_funcs = {
485 #endif /* defined(HAVE_FOPENCOOKIE) */
488 /* Socket not open. */
494 stream->timeout = timeout;
495 ao2_t_ref(stream, +1, "Opening tcptls stream cookie");
497 #if defined(HAVE_FUNOPEN) /* the BSD interface */
498 fp = funopen(stream, tcptls_stream_read, tcptls_stream_write, NULL,
499 tcptls_stream_close);
500 #elif defined(HAVE_FOPENCOOKIE) /* the glibc/linux interface */
501 fp = fopencookie(stream, "w+", cookie_funcs);
503 /* could add other methods here */
504 ast_debug(2, "No stream FILE methods attempted!\n");
510 ao2_t_ref(stream, -1, "Failed to open tcptls stream cookie");
515 HOOK_T ast_tcptls_server_read(struct ast_tcptls_session_instance *tcptls_session, void *buf, size_t count)
517 if (!tcptls_session->stream_cookie || tcptls_session->stream_cookie->fd == -1) {
518 ast_log(LOG_ERROR, "TCP/TLS read called on invalid stream.\n");
523 return tcptls_stream_read(tcptls_session->stream_cookie, buf, count);
526 HOOK_T ast_tcptls_server_write(struct ast_tcptls_session_instance *tcptls_session, const void *buf, size_t count)
528 if (!tcptls_session->stream_cookie || tcptls_session->stream_cookie->fd == -1) {
529 ast_log(LOG_ERROR, "TCP/TLS write called on invalid stream.\n");
534 return tcptls_stream_write(tcptls_session->stream_cookie, buf, count);
537 static void session_instance_destructor(void *obj)
539 struct ast_tcptls_session_instance *i = obj;
541 if (i->stream_cookie) {
542 ao2_t_ref(i->stream_cookie, -1, "Destroying tcptls session instance");
543 i->stream_cookie = NULL;
545 ast_free(i->overflow_buf);
549 * creates a FILE * from the fd passed by the accept thread.
550 * This operation is potentially expensive (certificate verification),
551 * so we do it in the child thread context.
553 * \note must decrement ref count before returning NULL on error
555 static void *handle_tcptls_connection(void *data)
557 struct ast_tcptls_session_instance *tcptls_session = data;
559 int (*ssl_setup)(SSL *) = (tcptls_session->client) ? SSL_connect : SSL_accept;
564 /* TCP/TLS connections are associated with external protocols, and
565 * should not be allowed to execute 'dangerous' functions. This may
566 * need to be pushed down into the individual protocol handlers, but
567 * this seems like a good general policy.
569 if (ast_thread_inhibit_escalations()) {
570 ast_log(LOG_ERROR, "Failed to inhibit privilege escalations; killing connection\n");
571 ast_tcptls_close_session_file(tcptls_session);
572 ao2_ref(tcptls_session, -1);
576 tcptls_session->stream_cookie = tcptls_stream_alloc();
577 if (!tcptls_session->stream_cookie) {
578 ast_tcptls_close_session_file(tcptls_session);
579 ao2_ref(tcptls_session, -1);
584 * open a FILE * as appropriate.
586 if (!tcptls_session->parent->tls_cfg) {
587 tcptls_session->f = tcptls_stream_fopen(tcptls_session->stream_cookie, NULL,
588 tcptls_session->fd, -1);
589 if (tcptls_session->f) {
590 if (setvbuf(tcptls_session->f, NULL, _IONBF, 0)) {
591 ast_tcptls_close_session_file(tcptls_session);
596 else if ( (tcptls_session->ssl = SSL_new(tcptls_session->parent->tls_cfg->ssl_ctx)) ) {
597 SSL_set_fd(tcptls_session->ssl, tcptls_session->fd);
598 if ((ret = ssl_setup(tcptls_session->ssl)) <= 0) {
599 ast_log(LOG_ERROR, "Problem setting up ssl connection: %s\n", ERR_error_string(ERR_get_error(), err));
600 } else if ((tcptls_session->f = tcptls_stream_fopen(tcptls_session->stream_cookie,
601 tcptls_session->ssl, tcptls_session->fd, -1))) {
602 if ((tcptls_session->client && !ast_test_flag(&tcptls_session->parent->tls_cfg->flags, AST_SSL_DONT_VERIFY_SERVER))
603 || (!tcptls_session->client && ast_test_flag(&tcptls_session->parent->tls_cfg->flags, AST_SSL_VERIFY_CLIENT))) {
606 peer = SSL_get_peer_certificate(tcptls_session->ssl);
608 ast_log(LOG_ERROR, "No peer SSL certificate to verify\n");
609 ast_tcptls_close_session_file(tcptls_session);
610 ao2_ref(tcptls_session, -1);
614 res = SSL_get_verify_result(tcptls_session->ssl);
615 if (res != X509_V_OK) {
616 ast_log(LOG_ERROR, "Certificate did not verify: %s\n", X509_verify_cert_error_string(res));
618 ast_tcptls_close_session_file(tcptls_session);
619 ao2_ref(tcptls_session, -1);
622 if (!ast_test_flag(&tcptls_session->parent->tls_cfg->flags, AST_SSL_IGNORE_COMMON_NAME)) {
625 X509_NAME *name = X509_get_subject_name(peer);
630 /* Walk the certificate to check all available "Common Name" */
631 /* XXX Probably should do a gethostbyname on the hostname and compare that as well */
632 pos = X509_NAME_get_index_by_NID(name, NID_commonName, pos);
636 str = X509_NAME_ENTRY_get_data(X509_NAME_get_entry(name, pos));
637 ASN1_STRING_to_UTF8(&str2, str);
639 if (!strcasecmp(tcptls_session->parent->hostname, (char *) str2)) {
642 ast_debug(3, "SSL Common Name compare s1='%s' s2='%s'\n", tcptls_session->parent->hostname, str2);
650 ast_log(LOG_ERROR, "Certificate common name did not match (%s)\n", tcptls_session->parent->hostname);
652 ast_tcptls_close_session_file(tcptls_session);
653 ao2_ref(tcptls_session, -1);
660 if (!tcptls_session->f) { /* no success opening descriptor stacking */
661 SSL_free(tcptls_session->ssl);
666 if (!tcptls_session->f) {
667 ast_tcptls_close_session_file(tcptls_session);
668 ast_log(LOG_WARNING, "FILE * open failed!\n");
670 if (tcptls_session->parent->tls_cfg) {
671 ast_log(LOG_ERROR, "Attempted a TLS connection without OpenSSL support. This will not work!\n");
674 ao2_ref(tcptls_session, -1);
678 if (tcptls_session->parent->worker_fn) {
679 return tcptls_session->parent->worker_fn(tcptls_session);
681 return tcptls_session;
685 void *ast_tcptls_server_root(void *data)
687 struct ast_tcptls_session_args *desc = data;
689 struct ast_sockaddr addr;
690 struct ast_tcptls_session_instance *tcptls_session;
696 if (desc->periodic_fn) {
697 desc->periodic_fn(desc);
699 i = ast_wait_for_input(desc->accept_fd, desc->poll_timeout);
703 fd = ast_accept(desc->accept_fd, &addr);
705 if ((errno != EAGAIN) && (errno != EINTR)) {
706 ast_log(LOG_ERROR, "Accept failed: %s\n", strerror(errno));
710 tcptls_session = ao2_alloc(sizeof(*tcptls_session), session_instance_destructor);
711 if (!tcptls_session) {
712 ast_log(LOG_WARNING, "No memory for new session: %s\n", strerror(errno));
714 ast_log(LOG_ERROR, "close() failed: %s\n", strerror(errno));
719 tcptls_session->overflow_buf = ast_str_create(128);
720 flags = fcntl(fd, F_GETFL);
721 fcntl(fd, F_SETFL, flags & ~O_NONBLOCK);
722 tcptls_session->fd = fd;
723 tcptls_session->parent = desc;
724 ast_sockaddr_copy(&tcptls_session->remote_address, &addr);
726 tcptls_session->client = 0;
728 /* This thread is now the only place that controls the single ref to tcptls_session */
729 if (ast_pthread_create_detached_background(&launched, NULL, handle_tcptls_connection, tcptls_session)) {
730 ast_log(LOG_ERROR, "Unable to launch helper thread: %s\n", strerror(errno));
731 ast_tcptls_close_session_file(tcptls_session);
732 ao2_ref(tcptls_session, -1);
738 static int __ssl_setup(struct ast_tls_config *cfg, int client)
748 /* Get rid of an old SSL_CTX since we're about to
752 SSL_CTX_free(cfg->ssl_ctx);
757 #ifndef OPENSSL_NO_SSL2
758 if (ast_test_flag(&cfg->flags, AST_SSL_SSLV2_CLIENT)) {
759 cfg->ssl_ctx = SSL_CTX_new(SSLv2_client_method());
762 if (ast_test_flag(&cfg->flags, AST_SSL_SSLV3_CLIENT)) {
763 cfg->ssl_ctx = SSL_CTX_new(SSLv3_client_method());
764 } else if (ast_test_flag(&cfg->flags, AST_SSL_TLSV1_CLIENT)) {
765 cfg->ssl_ctx = SSL_CTX_new(TLSv1_client_method());
767 /* SSLv23_client_method() sends SSLv2, this was the original
768 * default for ssl clients before the option was given to
769 * pick what protocol a client should use. In order not
770 * to break expected behavior it remains the default. */
771 cfg->ssl_ctx = SSL_CTX_new(SSLv23_client_method());
774 /* SSLv23_server_method() supports TLSv1, SSLv2, and SSLv3 inbound connections. */
775 cfg->ssl_ctx = SSL_CTX_new(SSLv23_server_method());
779 ast_debug(1, "Sorry, SSL_CTX_new call returned null...\n");
784 SSL_CTX_set_verify(cfg->ssl_ctx,
785 ast_test_flag(&cfg->flags, AST_SSL_VERIFY_CLIENT) ? SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT : SSL_VERIFY_NONE,
788 if (!ast_strlen_zero(cfg->certfile)) {
789 char *tmpprivate = ast_strlen_zero(cfg->pvtfile) ? cfg->certfile : cfg->pvtfile;
790 if (SSL_CTX_use_certificate_chain_file(cfg->ssl_ctx, cfg->certfile) == 0) {
792 /* Clients don't need a certificate, but if its setup we can use it */
793 ast_log(LOG_ERROR, "TLS/SSL error loading cert file. <%s>\n", cfg->certfile);
795 SSL_CTX_free(cfg->ssl_ctx);
800 if ((SSL_CTX_use_PrivateKey_file(cfg->ssl_ctx, tmpprivate, SSL_FILETYPE_PEM) == 0) || (SSL_CTX_check_private_key(cfg->ssl_ctx) == 0 )) {
802 /* Clients don't need a private key, but if its setup we can use it */
803 ast_log(LOG_ERROR, "TLS/SSL error loading private key file. <%s>\n", tmpprivate);
805 SSL_CTX_free(cfg->ssl_ctx);
811 if (!ast_strlen_zero(cfg->cipher)) {
812 if (SSL_CTX_set_cipher_list(cfg->ssl_ctx, cfg->cipher) == 0 ) {
814 ast_log(LOG_ERROR, "TLS/SSL cipher error <%s>\n", cfg->cipher);
816 SSL_CTX_free(cfg->ssl_ctx);
822 if (!ast_strlen_zero(cfg->cafile) || !ast_strlen_zero(cfg->capath)) {
823 if (SSL_CTX_load_verify_locations(cfg->ssl_ctx, S_OR(cfg->cafile, NULL), S_OR(cfg->capath,NULL)) == 0) {
824 ast_log(LOG_ERROR, "TLS/SSL CA file(%s)/path(%s) error\n", cfg->cafile, cfg->capath);
828 ast_verb(2, "TLS/SSL certificate ok\n"); /* We should log which one that is ok. This message doesn't really make sense in production use */
833 int ast_ssl_setup(struct ast_tls_config *cfg)
835 return __ssl_setup(cfg, 0);
838 void ast_ssl_teardown(struct ast_tls_config *cfg)
842 SSL_CTX_free(cfg->ssl_ctx);
848 struct ast_tcptls_session_instance *ast_tcptls_client_start(struct ast_tcptls_session_instance *tcptls_session)
850 struct ast_tcptls_session_args *desc;
853 if (!(desc = tcptls_session->parent)) {
854 goto client_start_error;
857 if (ast_connect(desc->accept_fd, &desc->remote_address)) {
858 ast_log(LOG_ERROR, "Unable to connect %s to %s: %s\n",
860 ast_sockaddr_stringify(&desc->remote_address),
862 goto client_start_error;
865 flags = fcntl(desc->accept_fd, F_GETFL);
866 fcntl(desc->accept_fd, F_SETFL, flags & ~O_NONBLOCK);
869 desc->tls_cfg->enabled = 1;
870 __ssl_setup(desc->tls_cfg, 1);
873 return handle_tcptls_connection(tcptls_session);
877 close(desc->accept_fd);
878 desc->accept_fd = -1;
880 ao2_ref(tcptls_session, -1);
885 struct ast_tcptls_session_instance *ast_tcptls_client_create(struct ast_tcptls_session_args *desc)
888 struct ast_tcptls_session_instance *tcptls_session = NULL;
890 /* Do nothing if nothing has changed */
891 if (!ast_sockaddr_cmp(&desc->old_address, &desc->remote_address)) {
892 ast_debug(1, "Nothing changed in %s\n", desc->name);
896 /* If we return early, there is no connection */
897 ast_sockaddr_setnull(&desc->old_address);
899 if (desc->accept_fd != -1) {
900 close(desc->accept_fd);
903 desc->accept_fd = socket(ast_sockaddr_is_ipv6(&desc->remote_address) ?
904 AF_INET6 : AF_INET, SOCK_STREAM, IPPROTO_TCP);
905 if (desc->accept_fd < 0) {
906 ast_log(LOG_ERROR, "Unable to allocate socket for %s: %s\n",
907 desc->name, strerror(errno));
911 /* if a local address was specified, bind to it so the connection will
912 originate from the desired address */
913 if (!ast_sockaddr_isnull(&desc->local_address)) {
914 setsockopt(desc->accept_fd, SOL_SOCKET, SO_REUSEADDR, &x, sizeof(x));
915 if (ast_bind(desc->accept_fd, &desc->local_address)) {
916 ast_log(LOG_ERROR, "Unable to bind %s to %s: %s\n",
918 ast_sockaddr_stringify(&desc->local_address),
924 if (!(tcptls_session = ao2_alloc(sizeof(*tcptls_session), session_instance_destructor))) {
928 tcptls_session->overflow_buf = ast_str_create(128);
929 tcptls_session->client = 1;
930 tcptls_session->fd = desc->accept_fd;
931 tcptls_session->parent = desc;
932 tcptls_session->parent->worker_fn = NULL;
933 ast_sockaddr_copy(&tcptls_session->remote_address,
934 &desc->remote_address);
936 /* Set current info */
937 ast_sockaddr_copy(&desc->old_address, &desc->remote_address);
938 return tcptls_session;
941 close(desc->accept_fd);
942 desc->accept_fd = -1;
943 if (tcptls_session) {
944 ao2_ref(tcptls_session, -1);
949 void ast_tcptls_server_start(struct ast_tcptls_session_args *desc)
954 /* Do nothing if nothing has changed */
955 if (!ast_sockaddr_cmp(&desc->old_address, &desc->local_address)) {
956 ast_debug(1, "Nothing changed in %s\n", desc->name);
960 /* If we return early, there is no one listening */
961 ast_sockaddr_setnull(&desc->old_address);
963 /* Shutdown a running server if there is one */
964 if (desc->master != AST_PTHREADT_NULL) {
965 pthread_cancel(desc->master);
966 pthread_kill(desc->master, SIGURG);
967 pthread_join(desc->master, NULL);
970 if (desc->accept_fd != -1) {
971 close(desc->accept_fd);
974 /* If there's no new server, stop here */
975 if (ast_sockaddr_isnull(&desc->local_address)) {
976 ast_debug(2, "Server disabled: %s\n", desc->name);
980 desc->accept_fd = socket(ast_sockaddr_is_ipv6(&desc->local_address) ?
981 AF_INET6 : AF_INET, SOCK_STREAM, 0);
982 if (desc->accept_fd < 0) {
983 ast_log(LOG_ERROR, "Unable to allocate socket for %s: %s\n", desc->name, strerror(errno));
987 setsockopt(desc->accept_fd, SOL_SOCKET, SO_REUSEADDR, &x, sizeof(x));
988 if (ast_bind(desc->accept_fd, &desc->local_address)) {
989 ast_log(LOG_ERROR, "Unable to bind %s to %s: %s\n",
991 ast_sockaddr_stringify(&desc->local_address),
995 if (listen(desc->accept_fd, 10)) {
996 ast_log(LOG_ERROR, "Unable to listen for %s!\n", desc->name);
999 flags = fcntl(desc->accept_fd, F_GETFL);
1000 fcntl(desc->accept_fd, F_SETFL, flags | O_NONBLOCK);
1001 if (ast_pthread_create_background(&desc->master, NULL, desc->accept_fn, desc)) {
1002 ast_log(LOG_ERROR, "Unable to launch thread for %s on %s: %s\n",
1004 ast_sockaddr_stringify(&desc->local_address),
1009 /* Set current info */
1010 ast_sockaddr_copy(&desc->old_address, &desc->local_address);
1015 close(desc->accept_fd);
1016 desc->accept_fd = -1;
1019 void ast_tcptls_close_session_file(struct ast_tcptls_session_instance *tcptls_session)
1021 if (tcptls_session->f) {
1022 fflush(tcptls_session->f);
1023 if (fclose(tcptls_session->f)) {
1024 ast_log(LOG_ERROR, "fclose() failed: %s\n", strerror(errno));
1026 tcptls_session->f = NULL;
1027 tcptls_session->fd = -1;
1028 } else if (tcptls_session->fd != -1) {
1030 * Issuing shutdown() is necessary here to avoid a race
1031 * condition where the last data written may not appear
1032 * in the TCP stream. See ASTERISK-23548
1034 shutdown(tcptls_session->fd, SHUT_RDWR);
1035 if (close(tcptls_session->fd)) {
1036 ast_log(LOG_ERROR, "close() failed: %s\n", strerror(errno));
1038 tcptls_session->fd = -1;
1040 ast_log(LOG_ERROR, "ast_tcptls_close_session_file invoked on session instance without file or file descriptor\n");
1044 void ast_tcptls_server_stop(struct ast_tcptls_session_args *desc)
1046 if (desc->master != AST_PTHREADT_NULL) {
1047 pthread_cancel(desc->master);
1048 pthread_kill(desc->master, SIGURG);
1049 pthread_join(desc->master, NULL);
1050 desc->master = AST_PTHREADT_NULL;
1052 if (desc->accept_fd != -1) {
1053 close(desc->accept_fd);
1055 desc->accept_fd = -1;
1056 ast_debug(2, "Stopped server :: %s\n", desc->name);
1059 int ast_tls_read_conf(struct ast_tls_config *tls_cfg, struct ast_tcptls_session_args *tls_desc, const char *varname, const char *value)
1061 if (!strcasecmp(varname, "tlsenable") || !strcasecmp(varname, "sslenable")) {
1062 tls_cfg->enabled = ast_true(value) ? 1 : 0;
1063 } else if (!strcasecmp(varname, "tlscertfile") || !strcasecmp(varname, "sslcert") || !strcasecmp(varname, "tlscert")) {
1064 ast_free(tls_cfg->certfile);
1065 tls_cfg->certfile = ast_strdup(value);
1066 } else if (!strcasecmp(varname, "tlsprivatekey") || !strcasecmp(varname, "sslprivatekey")) {
1067 ast_free(tls_cfg->pvtfile);
1068 tls_cfg->pvtfile = ast_strdup(value);
1069 } else if (!strcasecmp(varname, "tlscipher") || !strcasecmp(varname, "sslcipher")) {
1070 ast_free(tls_cfg->cipher);
1071 tls_cfg->cipher = ast_strdup(value);
1072 } else if (!strcasecmp(varname, "tlscafile")) {
1073 ast_free(tls_cfg->cafile);
1074 tls_cfg->cafile = ast_strdup(value);
1075 } else if (!strcasecmp(varname, "tlscapath") || !strcasecmp(varname, "tlscadir")) {
1076 ast_free(tls_cfg->capath);
1077 tls_cfg->capath = ast_strdup(value);
1078 } else if (!strcasecmp(varname, "tlsverifyclient")) {
1079 ast_set2_flag(&tls_cfg->flags, ast_true(value), AST_SSL_VERIFY_CLIENT);
1080 } else if (!strcasecmp(varname, "tlsdontverifyserver")) {
1081 ast_set2_flag(&tls_cfg->flags, ast_true(value), AST_SSL_DONT_VERIFY_SERVER);
1082 } else if (!strcasecmp(varname, "tlsbindaddr") || !strcasecmp(varname, "sslbindaddr")) {
1083 if (ast_parse_arg(value, PARSE_ADDR, &tls_desc->local_address))
1084 ast_log(LOG_ERROR, "Invalid %s '%s'\n", varname, value);
1085 } else if (!strcasecmp(varname, "tlsclientmethod") || !strcasecmp(varname, "sslclientmethod")) {
1086 if (!strcasecmp(value, "tlsv1")) {
1087 ast_set_flag(&tls_cfg->flags, AST_SSL_TLSV1_CLIENT);
1088 ast_clear_flag(&tls_cfg->flags, AST_SSL_SSLV3_CLIENT);
1089 ast_clear_flag(&tls_cfg->flags, AST_SSL_SSLV2_CLIENT);
1090 } else if (!strcasecmp(value, "sslv3")) {
1091 ast_set_flag(&tls_cfg->flags, AST_SSL_SSLV3_CLIENT);
1092 ast_clear_flag(&tls_cfg->flags, AST_SSL_SSLV2_CLIENT);
1093 ast_clear_flag(&tls_cfg->flags, AST_SSL_TLSV1_CLIENT);
1094 } else if (!strcasecmp(value, "sslv2")) {
1095 ast_set_flag(&tls_cfg->flags, AST_SSL_SSLV2_CLIENT);
1096 ast_clear_flag(&tls_cfg->flags, AST_SSL_TLSV1_CLIENT);
1097 ast_clear_flag(&tls_cfg->flags, AST_SSL_SSLV3_CLIENT);