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.
82 void ast_tcptls_stream_set_timeout_disable(struct ast_tcptls_stream *stream)
84 ast_assert(stream != NULL);
89 void ast_tcptls_stream_set_timeout_inactivity(struct ast_tcptls_stream *stream, int timeout)
91 ast_assert(stream != NULL);
93 stream->start.tv_sec = 0;
94 stream->timeout = timeout;
97 void ast_tcptls_stream_set_timeout_sequence(struct ast_tcptls_stream *stream, struct timeval start, int timeout)
99 ast_assert(stream != NULL);
101 stream->start = start;
102 stream->timeout = timeout;
107 * \brief fopencookie()/funopen() stream read function.
109 * \param cookie Stream control data.
110 * \param buf Where to put read data.
111 * \param size Size of the buffer.
113 * \retval number of bytes put into buf.
114 * \retval 0 on end of file.
115 * \retval -1 on error.
117 static HOOK_T tcptls_stream_read(void *cookie, char *buf, LEN_T size)
119 struct ast_tcptls_stream *stream = cookie;
120 struct timeval start;
125 /* You asked for no data you got no data. */
129 if (!stream || stream->fd == -1) {
134 if (stream->start.tv_sec) {
135 start = stream->start;
143 res = SSL_read(stream->ssl, buf, size);
145 /* We read some payload data. */
148 switch (SSL_get_error(stream->ssl, res)) {
149 case SSL_ERROR_ZERO_RETURN:
150 /* Report EOF for a shutdown */
151 ast_debug(1, "TLS clean shutdown alert reading data\n");
153 case SSL_ERROR_WANT_READ:
154 while ((ms = ast_remaining_ms(start, stream->timeout))) {
155 res = ast_wait_for_input(stream->fd, ms);
157 /* Socket is ready to be read. */
161 if (errno == EINTR || errno == EAGAIN) {
165 ast_debug(1, "TLS socket error waiting for read data: %s\n",
171 case SSL_ERROR_WANT_WRITE:
172 while ((ms = ast_remaining_ms(start, stream->timeout))) {
173 res = ast_wait_for_output(stream->fd, ms);
175 /* Socket is ready to be written. */
179 if (errno == EINTR || errno == EAGAIN) {
183 ast_debug(1, "TLS socket error waiting for write space: %s\n",
190 /* Report EOF for an undecoded SSL or transport error. */
191 ast_debug(1, "TLS transport or SSL error reading data\n");
195 /* Report EOF for a timeout */
196 ast_debug(1, "TLS timeout reading data\n");
201 #endif /* defined(DO_SSL) */
204 res = read(stream->fd, buf, size);
208 if (errno != EINTR && errno != EAGAIN) {
209 /* Not a retryable error. */
210 ast_debug(1, "TCP socket error reading data: %s\n",
214 ms = ast_remaining_ms(start, stream->timeout);
216 /* Report EOF for a timeout */
217 ast_debug(1, "TCP timeout reading data\n");
220 ast_wait_for_input(stream->fd, ms);
226 * \brief fopencookie()/funopen() stream write function.
228 * \param cookie Stream control data.
229 * \param buf Where to get data to write.
230 * \param size Size of the buffer.
232 * \retval number of bytes written from buf.
233 * \retval -1 on error.
235 static HOOK_T tcptls_stream_write(void *cookie, const char *buf, LEN_T size)
237 struct ast_tcptls_stream *stream = cookie;
238 struct timeval start;
245 /* You asked to write no data you wrote no data. */
249 if (!stream || stream->fd == -1) {
254 if (stream->start.tv_sec) {
255 start = stream->start;
265 res = SSL_write(stream->ssl, buf + written, remaining);
266 if (res == remaining) {
267 /* Everything was written. */
271 /* Successfully wrote part of the buffer. Try to write the rest. */
276 switch (SSL_get_error(stream->ssl, res)) {
277 case SSL_ERROR_ZERO_RETURN:
278 ast_debug(1, "TLS clean shutdown alert writing data\n");
280 /* Report partial write. */
285 case SSL_ERROR_WANT_READ:
286 ms = ast_remaining_ms(start, stream->timeout);
288 /* Report partial write. */
289 ast_debug(1, "TLS timeout writing data (want read)\n");
292 ast_wait_for_input(stream->fd, ms);
294 case SSL_ERROR_WANT_WRITE:
295 ms = ast_remaining_ms(start, stream->timeout);
297 /* Report partial write. */
298 ast_debug(1, "TLS timeout writing data (want write)\n");
301 ast_wait_for_output(stream->fd, ms);
304 /* Undecoded SSL or transport error. */
305 ast_debug(1, "TLS transport or SSL error writing data\n");
307 /* Report partial write. */
315 #endif /* defined(DO_SSL) */
320 res = write(stream->fd, buf + written, remaining);
321 if (res == remaining) {
322 /* Yay everything was written. */
326 /* Successfully wrote part of the buffer. Try to write the rest. */
331 if (errno != EINTR && errno != EAGAIN) {
332 /* Not a retryable error. */
333 ast_debug(1, "TCP socket error writing: %s\n", strerror(errno));
339 ms = ast_remaining_ms(start, stream->timeout);
341 /* Report partial write. */
342 ast_debug(1, "TCP timeout writing data\n");
345 ast_wait_for_output(stream->fd, ms);
351 * \brief fopencookie()/funopen() stream close function.
353 * \param cookie Stream control data.
355 * \retval 0 on success.
356 * \retval -1 on error.
358 static int tcptls_stream_close(void *cookie)
360 struct ast_tcptls_stream *stream = cookie;
367 if (stream->fd != -1) {
373 * According to the TLS standard, it is acceptable for an
374 * application to only send its shutdown alert and then
375 * close the underlying connection without waiting for
376 * the peer's response (this way resources can be saved,
377 * as the process can already terminate or serve another
380 res = SSL_shutdown(stream->ssl);
382 ast_log(LOG_ERROR, "SSL_shutdown() failed: %d\n",
383 SSL_get_error(stream->ssl, res));
386 if (!stream->ssl->server) {
387 /* For client threads, ensure that the error stack is cleared */
391 SSL_free(stream->ssl);
394 #endif /* defined(DO_SSL) */
397 * Issuing shutdown() is necessary here to avoid a race
398 * condition where the last data written may not appear
399 * in the TCP stream. See ASTERISK-23548
401 shutdown(stream->fd, SHUT_RDWR);
402 if (close(stream->fd)) {
403 ast_log(LOG_ERROR, "close() failed: %s\n", strerror(errno));
407 ao2_t_ref(stream, -1, "Closed tcptls stream cookie");
414 * \brief fopencookie()/funopen() stream destructor function.
416 * \param cookie Stream control data.
420 static void tcptls_stream_dtor(void *cookie)
422 struct ast_tcptls_stream *stream = cookie;
424 ast_assert(stream->fd == -1);
429 * \brief fopencookie()/funopen() stream allocation function.
431 * \retval stream_cookie on success.
432 * \retval NULL on error.
434 static struct ast_tcptls_stream *tcptls_stream_alloc(void)
436 struct ast_tcptls_stream *stream;
438 stream = ao2_alloc_options(sizeof(*stream), tcptls_stream_dtor,
439 AO2_ALLOC_OPT_LOCK_NOLOCK);
442 stream->timeout = -1;
449 * \brief Open a custom FILE stream for tcptls.
451 * \param stream Stream cookie control data.
452 * \param ssl SSL state if not NULL.
453 * \param fd Socket file descriptor.
454 * \param timeout ms to wait for an event on fd. -1 if timeout disabled.
456 * \retval fp on success.
457 * \retval NULL on error.
459 static FILE *tcptls_stream_fopen(struct ast_tcptls_stream *stream, SSL *ssl, int fd, int timeout)
463 #if defined(HAVE_FOPENCOOKIE) /* the glibc/linux interface */
464 static const cookie_io_functions_t cookie_funcs = {
470 #endif /* defined(HAVE_FOPENCOOKIE) */
473 /* Socket not open. */
479 stream->timeout = timeout;
480 ao2_t_ref(stream, +1, "Opening tcptls stream cookie");
482 #if defined(HAVE_FUNOPEN) /* the BSD interface */
483 fp = funopen(stream, tcptls_stream_read, tcptls_stream_write, NULL,
484 tcptls_stream_close);
485 #elif defined(HAVE_FOPENCOOKIE) /* the glibc/linux interface */
486 fp = fopencookie(stream, "w+", cookie_funcs);
488 /* could add other methods here */
489 ast_debug(2, "No stream FILE methods attempted!\n");
495 ao2_t_ref(stream, -1, "Failed to open tcptls stream cookie");
500 HOOK_T ast_tcptls_server_read(struct ast_tcptls_session_instance *tcptls_session, void *buf, size_t count)
502 if (!tcptls_session->stream_cookie || tcptls_session->stream_cookie->fd == -1) {
503 ast_log(LOG_ERROR, "TCP/TLS read called on invalid stream.\n");
508 return tcptls_stream_read(tcptls_session->stream_cookie, buf, count);
511 HOOK_T ast_tcptls_server_write(struct ast_tcptls_session_instance *tcptls_session, const void *buf, size_t count)
513 if (!tcptls_session->stream_cookie || tcptls_session->stream_cookie->fd == -1) {
514 ast_log(LOG_ERROR, "TCP/TLS write called on invalid stream.\n");
519 return tcptls_stream_write(tcptls_session->stream_cookie, buf, count);
522 static void session_instance_destructor(void *obj)
524 struct ast_tcptls_session_instance *i = obj;
526 if (i->stream_cookie) {
527 ao2_t_ref(i->stream_cookie, -1, "Destroying tcptls session instance");
528 i->stream_cookie = NULL;
530 ast_free(i->overflow_buf);
534 * creates a FILE * from the fd passed by the accept thread.
535 * This operation is potentially expensive (certificate verification),
536 * so we do it in the child thread context.
538 * \note must decrement ref count before returning NULL on error
540 static void *handle_tcptls_connection(void *data)
542 struct ast_tcptls_session_instance *tcptls_session = data;
544 int (*ssl_setup)(SSL *) = (tcptls_session->client) ? SSL_connect : SSL_accept;
549 /* TCP/TLS connections are associated with external protocols, and
550 * should not be allowed to execute 'dangerous' functions. This may
551 * need to be pushed down into the individual protocol handlers, but
552 * this seems like a good general policy.
554 if (ast_thread_inhibit_escalations()) {
555 ast_log(LOG_ERROR, "Failed to inhibit privilege escalations; killing connection\n");
556 ast_tcptls_close_session_file(tcptls_session);
557 ao2_ref(tcptls_session, -1);
561 tcptls_session->stream_cookie = tcptls_stream_alloc();
562 if (!tcptls_session->stream_cookie) {
563 ast_tcptls_close_session_file(tcptls_session);
564 ao2_ref(tcptls_session, -1);
569 * open a FILE * as appropriate.
571 if (!tcptls_session->parent->tls_cfg) {
572 tcptls_session->f = tcptls_stream_fopen(tcptls_session->stream_cookie, NULL,
573 tcptls_session->fd, -1);
574 if (tcptls_session->f) {
575 if (setvbuf(tcptls_session->f, NULL, _IONBF, 0)) {
576 ast_tcptls_close_session_file(tcptls_session);
581 else if ( (tcptls_session->ssl = SSL_new(tcptls_session->parent->tls_cfg->ssl_ctx)) ) {
582 SSL_set_fd(tcptls_session->ssl, tcptls_session->fd);
583 if ((ret = ssl_setup(tcptls_session->ssl)) <= 0) {
584 ast_log(LOG_ERROR, "Problem setting up ssl connection: %s\n", ERR_error_string(ERR_get_error(), err));
585 } else if ((tcptls_session->f = tcptls_stream_fopen(tcptls_session->stream_cookie,
586 tcptls_session->ssl, tcptls_session->fd, -1))) {
587 if ((tcptls_session->client && !ast_test_flag(&tcptls_session->parent->tls_cfg->flags, AST_SSL_DONT_VERIFY_SERVER))
588 || (!tcptls_session->client && ast_test_flag(&tcptls_session->parent->tls_cfg->flags, AST_SSL_VERIFY_CLIENT))) {
591 peer = SSL_get_peer_certificate(tcptls_session->ssl);
593 ast_log(LOG_ERROR, "No peer SSL certificate to verify\n");
594 ast_tcptls_close_session_file(tcptls_session);
595 ao2_ref(tcptls_session, -1);
599 res = SSL_get_verify_result(tcptls_session->ssl);
600 if (res != X509_V_OK) {
601 ast_log(LOG_ERROR, "Certificate did not verify: %s\n", X509_verify_cert_error_string(res));
603 ast_tcptls_close_session_file(tcptls_session);
604 ao2_ref(tcptls_session, -1);
607 if (!ast_test_flag(&tcptls_session->parent->tls_cfg->flags, AST_SSL_IGNORE_COMMON_NAME)) {
610 X509_NAME *name = X509_get_subject_name(peer);
615 /* Walk the certificate to check all available "Common Name" */
616 /* XXX Probably should do a gethostbyname on the hostname and compare that as well */
617 pos = X509_NAME_get_index_by_NID(name, NID_commonName, pos);
621 str = X509_NAME_ENTRY_get_data(X509_NAME_get_entry(name, pos));
622 ASN1_STRING_to_UTF8(&str2, str);
624 if (!strcasecmp(tcptls_session->parent->hostname, (char *) str2)) {
627 ast_debug(3, "SSL Common Name compare s1='%s' s2='%s'\n", tcptls_session->parent->hostname, str2);
635 ast_log(LOG_ERROR, "Certificate common name did not match (%s)\n", tcptls_session->parent->hostname);
637 ast_tcptls_close_session_file(tcptls_session);
638 ao2_ref(tcptls_session, -1);
645 if (!tcptls_session->f) { /* no success opening descriptor stacking */
646 SSL_free(tcptls_session->ssl);
651 if (!tcptls_session->f) {
652 ast_tcptls_close_session_file(tcptls_session);
653 ast_log(LOG_WARNING, "FILE * open failed!\n");
655 if (tcptls_session->parent->tls_cfg) {
656 ast_log(LOG_ERROR, "Attempted a TLS connection without OpenSSL support. This will not work!\n");
659 ao2_ref(tcptls_session, -1);
663 if (tcptls_session->parent->worker_fn) {
664 return tcptls_session->parent->worker_fn(tcptls_session);
666 return tcptls_session;
670 void *ast_tcptls_server_root(void *data)
672 struct ast_tcptls_session_args *desc = data;
674 struct ast_sockaddr addr;
675 struct ast_tcptls_session_instance *tcptls_session;
681 if (desc->periodic_fn) {
682 desc->periodic_fn(desc);
684 i = ast_wait_for_input(desc->accept_fd, desc->poll_timeout);
688 fd = ast_accept(desc->accept_fd, &addr);
690 if ((errno != EAGAIN) && (errno != EINTR)) {
691 ast_log(LOG_ERROR, "Accept failed: %s\n", strerror(errno));
695 tcptls_session = ao2_alloc(sizeof(*tcptls_session), session_instance_destructor);
696 if (!tcptls_session) {
697 ast_log(LOG_WARNING, "No memory for new session: %s\n", strerror(errno));
699 ast_log(LOG_ERROR, "close() failed: %s\n", strerror(errno));
704 tcptls_session->overflow_buf = ast_str_create(128);
705 flags = fcntl(fd, F_GETFL);
706 fcntl(fd, F_SETFL, flags & ~O_NONBLOCK);
707 tcptls_session->fd = fd;
708 tcptls_session->parent = desc;
709 ast_sockaddr_copy(&tcptls_session->remote_address, &addr);
711 tcptls_session->client = 0;
713 /* This thread is now the only place that controls the single ref to tcptls_session */
714 if (ast_pthread_create_detached_background(&launched, NULL, handle_tcptls_connection, tcptls_session)) {
715 ast_log(LOG_ERROR, "Unable to launch helper thread: %s\n", strerror(errno));
716 ast_tcptls_close_session_file(tcptls_session);
717 ao2_ref(tcptls_session, -1);
723 static int __ssl_setup(struct ast_tls_config *cfg, int client)
733 /* Get rid of an old SSL_CTX since we're about to
737 SSL_CTX_free(cfg->ssl_ctx);
742 #ifndef OPENSSL_NO_SSL2
743 if (ast_test_flag(&cfg->flags, AST_SSL_SSLV2_CLIENT)) {
744 cfg->ssl_ctx = SSL_CTX_new(SSLv2_client_method());
747 if (ast_test_flag(&cfg->flags, AST_SSL_SSLV3_CLIENT)) {
748 cfg->ssl_ctx = SSL_CTX_new(SSLv3_client_method());
749 } else if (ast_test_flag(&cfg->flags, AST_SSL_TLSV1_CLIENT)) {
750 cfg->ssl_ctx = SSL_CTX_new(TLSv1_client_method());
752 /* SSLv23_client_method() sends SSLv2, this was the original
753 * default for ssl clients before the option was given to
754 * pick what protocol a client should use. In order not
755 * to break expected behavior it remains the default. */
756 cfg->ssl_ctx = SSL_CTX_new(SSLv23_client_method());
759 /* SSLv23_server_method() supports TLSv1, SSLv2, and SSLv3 inbound connections. */
760 cfg->ssl_ctx = SSL_CTX_new(SSLv23_server_method());
764 ast_debug(1, "Sorry, SSL_CTX_new call returned null...\n");
769 SSL_CTX_set_verify(cfg->ssl_ctx,
770 ast_test_flag(&cfg->flags, AST_SSL_VERIFY_CLIENT) ? SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT : SSL_VERIFY_NONE,
773 if (!ast_strlen_zero(cfg->certfile)) {
774 char *tmpprivate = ast_strlen_zero(cfg->pvtfile) ? cfg->certfile : cfg->pvtfile;
775 if (SSL_CTX_use_certificate_chain_file(cfg->ssl_ctx, cfg->certfile) == 0) {
777 /* Clients don't need a certificate, but if its setup we can use it */
778 ast_log(LOG_ERROR, "TLS/SSL error loading cert file. <%s>\n", cfg->certfile);
780 SSL_CTX_free(cfg->ssl_ctx);
785 if ((SSL_CTX_use_PrivateKey_file(cfg->ssl_ctx, tmpprivate, SSL_FILETYPE_PEM) == 0) || (SSL_CTX_check_private_key(cfg->ssl_ctx) == 0 )) {
787 /* Clients don't need a private key, but if its setup we can use it */
788 ast_log(LOG_ERROR, "TLS/SSL error loading private key file. <%s>\n", tmpprivate);
790 SSL_CTX_free(cfg->ssl_ctx);
796 if (!ast_strlen_zero(cfg->cipher)) {
797 if (SSL_CTX_set_cipher_list(cfg->ssl_ctx, cfg->cipher) == 0 ) {
799 ast_log(LOG_ERROR, "TLS/SSL cipher error <%s>\n", cfg->cipher);
801 SSL_CTX_free(cfg->ssl_ctx);
807 if (!ast_strlen_zero(cfg->cafile) || !ast_strlen_zero(cfg->capath)) {
808 if (SSL_CTX_load_verify_locations(cfg->ssl_ctx, S_OR(cfg->cafile, NULL), S_OR(cfg->capath,NULL)) == 0) {
809 ast_log(LOG_ERROR, "TLS/SSL CA file(%s)/path(%s) error\n", cfg->cafile, cfg->capath);
813 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 */
818 int ast_ssl_setup(struct ast_tls_config *cfg)
820 return __ssl_setup(cfg, 0);
823 void ast_ssl_teardown(struct ast_tls_config *cfg)
827 SSL_CTX_free(cfg->ssl_ctx);
833 struct ast_tcptls_session_instance *ast_tcptls_client_start(struct ast_tcptls_session_instance *tcptls_session)
835 struct ast_tcptls_session_args *desc;
838 if (!(desc = tcptls_session->parent)) {
839 goto client_start_error;
842 if (ast_connect(desc->accept_fd, &desc->remote_address)) {
843 ast_log(LOG_ERROR, "Unable to connect %s to %s: %s\n",
845 ast_sockaddr_stringify(&desc->remote_address),
847 goto client_start_error;
850 flags = fcntl(desc->accept_fd, F_GETFL);
851 fcntl(desc->accept_fd, F_SETFL, flags & ~O_NONBLOCK);
854 desc->tls_cfg->enabled = 1;
855 __ssl_setup(desc->tls_cfg, 1);
858 return handle_tcptls_connection(tcptls_session);
862 close(desc->accept_fd);
863 desc->accept_fd = -1;
865 ao2_ref(tcptls_session, -1);
870 struct ast_tcptls_session_instance *ast_tcptls_client_create(struct ast_tcptls_session_args *desc)
873 struct ast_tcptls_session_instance *tcptls_session = NULL;
875 /* Do nothing if nothing has changed */
876 if (!ast_sockaddr_cmp(&desc->old_address, &desc->remote_address)) {
877 ast_debug(1, "Nothing changed in %s\n", desc->name);
881 /* If we return early, there is no connection */
882 ast_sockaddr_setnull(&desc->old_address);
884 if (desc->accept_fd != -1) {
885 close(desc->accept_fd);
888 desc->accept_fd = socket(ast_sockaddr_is_ipv6(&desc->remote_address) ?
889 AF_INET6 : AF_INET, SOCK_STREAM, IPPROTO_TCP);
890 if (desc->accept_fd < 0) {
891 ast_log(LOG_ERROR, "Unable to allocate socket for %s: %s\n",
892 desc->name, strerror(errno));
896 /* if a local address was specified, bind to it so the connection will
897 originate from the desired address */
898 if (!ast_sockaddr_isnull(&desc->local_address)) {
899 setsockopt(desc->accept_fd, SOL_SOCKET, SO_REUSEADDR, &x, sizeof(x));
900 if (ast_bind(desc->accept_fd, &desc->local_address)) {
901 ast_log(LOG_ERROR, "Unable to bind %s to %s: %s\n",
903 ast_sockaddr_stringify(&desc->local_address),
909 if (!(tcptls_session = ao2_alloc(sizeof(*tcptls_session), session_instance_destructor))) {
913 tcptls_session->overflow_buf = ast_str_create(128);
914 tcptls_session->client = 1;
915 tcptls_session->fd = desc->accept_fd;
916 tcptls_session->parent = desc;
917 tcptls_session->parent->worker_fn = NULL;
918 ast_sockaddr_copy(&tcptls_session->remote_address,
919 &desc->remote_address);
921 /* Set current info */
922 ast_sockaddr_copy(&desc->old_address, &desc->remote_address);
923 return tcptls_session;
926 close(desc->accept_fd);
927 desc->accept_fd = -1;
928 if (tcptls_session) {
929 ao2_ref(tcptls_session, -1);
934 void ast_tcptls_server_start(struct ast_tcptls_session_args *desc)
939 /* Do nothing if nothing has changed */
940 if (!ast_sockaddr_cmp(&desc->old_address, &desc->local_address)) {
941 ast_debug(1, "Nothing changed in %s\n", desc->name);
945 /* If we return early, there is no one listening */
946 ast_sockaddr_setnull(&desc->old_address);
948 /* Shutdown a running server if there is one */
949 if (desc->master != AST_PTHREADT_NULL) {
950 pthread_cancel(desc->master);
951 pthread_kill(desc->master, SIGURG);
952 pthread_join(desc->master, NULL);
955 if (desc->accept_fd != -1) {
956 close(desc->accept_fd);
959 /* If there's no new server, stop here */
960 if (ast_sockaddr_isnull(&desc->local_address)) {
961 ast_debug(2, "Server disabled: %s\n", desc->name);
965 desc->accept_fd = socket(ast_sockaddr_is_ipv6(&desc->local_address) ?
966 AF_INET6 : AF_INET, SOCK_STREAM, 0);
967 if (desc->accept_fd < 0) {
968 ast_log(LOG_ERROR, "Unable to allocate socket for %s: %s\n", desc->name, strerror(errno));
972 setsockopt(desc->accept_fd, SOL_SOCKET, SO_REUSEADDR, &x, sizeof(x));
973 if (ast_bind(desc->accept_fd, &desc->local_address)) {
974 ast_log(LOG_ERROR, "Unable to bind %s to %s: %s\n",
976 ast_sockaddr_stringify(&desc->local_address),
980 if (listen(desc->accept_fd, 10)) {
981 ast_log(LOG_ERROR, "Unable to listen for %s!\n", desc->name);
984 flags = fcntl(desc->accept_fd, F_GETFL);
985 fcntl(desc->accept_fd, F_SETFL, flags | O_NONBLOCK);
986 if (ast_pthread_create_background(&desc->master, NULL, desc->accept_fn, desc)) {
987 ast_log(LOG_ERROR, "Unable to launch thread for %s on %s: %s\n",
989 ast_sockaddr_stringify(&desc->local_address),
994 /* Set current info */
995 ast_sockaddr_copy(&desc->old_address, &desc->local_address);
1000 close(desc->accept_fd);
1001 desc->accept_fd = -1;
1004 void ast_tcptls_close_session_file(struct ast_tcptls_session_instance *tcptls_session)
1006 if (tcptls_session->f) {
1007 fflush(tcptls_session->f);
1008 if (fclose(tcptls_session->f)) {
1009 ast_log(LOG_ERROR, "fclose() failed: %s\n", strerror(errno));
1011 tcptls_session->f = NULL;
1012 tcptls_session->fd = -1;
1013 } else if (tcptls_session->fd != -1) {
1015 * Issuing shutdown() is necessary here to avoid a race
1016 * condition where the last data written may not appear
1017 * in the TCP stream. See ASTERISK-23548
1019 shutdown(tcptls_session->fd, SHUT_RDWR);
1020 if (close(tcptls_session->fd)) {
1021 ast_log(LOG_ERROR, "close() failed: %s\n", strerror(errno));
1023 tcptls_session->fd = -1;
1025 ast_log(LOG_ERROR, "ast_tcptls_close_session_file invoked on session instance without file or file descriptor\n");
1029 void ast_tcptls_server_stop(struct ast_tcptls_session_args *desc)
1031 if (desc->master != AST_PTHREADT_NULL) {
1032 pthread_cancel(desc->master);
1033 pthread_kill(desc->master, SIGURG);
1034 pthread_join(desc->master, NULL);
1035 desc->master = AST_PTHREADT_NULL;
1037 if (desc->accept_fd != -1) {
1038 close(desc->accept_fd);
1040 desc->accept_fd = -1;
1041 ast_debug(2, "Stopped server :: %s\n", desc->name);
1044 int ast_tls_read_conf(struct ast_tls_config *tls_cfg, struct ast_tcptls_session_args *tls_desc, const char *varname, const char *value)
1046 if (!strcasecmp(varname, "tlsenable") || !strcasecmp(varname, "sslenable")) {
1047 tls_cfg->enabled = ast_true(value) ? 1 : 0;
1048 } else if (!strcasecmp(varname, "tlscertfile") || !strcasecmp(varname, "sslcert") || !strcasecmp(varname, "tlscert")) {
1049 ast_free(tls_cfg->certfile);
1050 tls_cfg->certfile = ast_strdup(value);
1051 } else if (!strcasecmp(varname, "tlsprivatekey") || !strcasecmp(varname, "sslprivatekey")) {
1052 ast_free(tls_cfg->pvtfile);
1053 tls_cfg->pvtfile = ast_strdup(value);
1054 } else if (!strcasecmp(varname, "tlscipher") || !strcasecmp(varname, "sslcipher")) {
1055 ast_free(tls_cfg->cipher);
1056 tls_cfg->cipher = ast_strdup(value);
1057 } else if (!strcasecmp(varname, "tlscafile")) {
1058 ast_free(tls_cfg->cafile);
1059 tls_cfg->cafile = ast_strdup(value);
1060 } else if (!strcasecmp(varname, "tlscapath") || !strcasecmp(varname, "tlscadir")) {
1061 ast_free(tls_cfg->capath);
1062 tls_cfg->capath = ast_strdup(value);
1063 } else if (!strcasecmp(varname, "tlsverifyclient")) {
1064 ast_set2_flag(&tls_cfg->flags, ast_true(value), AST_SSL_VERIFY_CLIENT);
1065 } else if (!strcasecmp(varname, "tlsdontverifyserver")) {
1066 ast_set2_flag(&tls_cfg->flags, ast_true(value), AST_SSL_DONT_VERIFY_SERVER);
1067 } else if (!strcasecmp(varname, "tlsbindaddr") || !strcasecmp(varname, "sslbindaddr")) {
1068 if (ast_parse_arg(value, PARSE_ADDR, &tls_desc->local_address))
1069 ast_log(LOG_ERROR, "Invalid %s '%s'\n", varname, value);
1070 } else if (!strcasecmp(varname, "tlsclientmethod") || !strcasecmp(varname, "sslclientmethod")) {
1071 if (!strcasecmp(value, "tlsv1")) {
1072 ast_set_flag(&tls_cfg->flags, AST_SSL_TLSV1_CLIENT);
1073 ast_clear_flag(&tls_cfg->flags, AST_SSL_SSLV3_CLIENT);
1074 ast_clear_flag(&tls_cfg->flags, AST_SSL_SSLV2_CLIENT);
1075 } else if (!strcasecmp(value, "sslv3")) {
1076 ast_set_flag(&tls_cfg->flags, AST_SSL_SSLV3_CLIENT);
1077 ast_clear_flag(&tls_cfg->flags, AST_SSL_SSLV2_CLIENT);
1078 ast_clear_flag(&tls_cfg->flags, AST_SSL_TLSV1_CLIENT);
1079 } else if (!strcasecmp(value, "sslv2")) {
1080 ast_set_flag(&tls_cfg->flags, AST_SSL_SSLV2_CLIENT);
1081 ast_clear_flag(&tls_cfg->flags, AST_SSL_TLSV1_CLIENT);
1082 ast_clear_flag(&tls_cfg->flags, AST_SSL_SSLV3_CLIENT);