ARI: Add ability to raise arbitrary User Events
[asterisk/asterisk.git] / main / tcptls.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 2007 - 2008, Digium, Inc.
5  *
6  * Luigi Rizzo (TCP and TLS server code)
7  * Brett Bryant <brettbryant@gmail.com> (updated for client support)
8  *
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.
14  *
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.
18  */
19
20 /*!
21  * \file
22  * \brief Code to support TCP and TLS server/client
23  *
24  * \author Luigi Rizzo
25  * \author Brett Bryant <brettbryant@gmail.com>
26  */
27
28 /*** MODULEINFO
29         <support_level>core</support_level>
30  ***/
31
32 #include "asterisk.h"
33
34 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
35
36 #ifdef HAVE_FCNTL_H
37 #include <fcntl.h>
38 #endif
39
40 #include <signal.h>
41 #include <sys/signal.h>
42
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"
52
53 /*! \brief
54  * replacement read/write functions for SSL support.
55  * We use wrappers rather than SSL_read/SSL_write directly so
56  * we can put in some debugging.
57  */
58
59 #ifdef DO_SSL
60 static HOOK_T ssl_read(void *cookie, char *buf, LEN_T len)
61 {
62         int i = SSL_read(cookie, buf, len-1);
63 #if 0
64         if (i >= 0) {
65                 buf[i] = '\0';
66         }
67         ast_verb(0, "ssl read size %d returns %d <%s>\n", (int)len, i, buf);
68 #endif
69         return i;
70 }
71
72 static HOOK_T ssl_write(void *cookie, const char *buf, LEN_T len)
73 {
74 #if 0
75         char *s = ast_alloca(len+1);
76
77         strncpy(s, buf, len);
78         s[len] = '\0';
79         ast_verb(0, "ssl write size %d <%s>\n", (int)len, s);
80 #endif
81         return SSL_write(cookie, buf, len);
82 }
83
84 static int ssl_close(void *cookie)
85 {
86         int cookie_fd = SSL_get_fd(cookie);
87         int ret;
88
89         if (cookie_fd > -1) {
90                 /*
91                  * According to the TLS standard, it is acceptable for an application to only send its shutdown
92                  * alert and then close the underlying connection without waiting for the peer's response (this
93                  * way resources can be saved, as the process can already terminate or serve another connection).
94                  */
95                 if ((ret = SSL_shutdown(cookie)) < 0) {
96                         ast_log(LOG_ERROR, "SSL_shutdown() failed: %d\n", SSL_get_error(cookie, ret));
97                 }
98
99                 if (!((SSL*)cookie)->server) {
100                         /* For client threads, ensure that the error stack is cleared */
101                         ERR_remove_state(0);
102                 }
103
104                 SSL_free(cookie);
105                 /* adding shutdown(2) here has no added benefit */
106                 if (close(cookie_fd)) {
107                         ast_log(LOG_ERROR, "close() failed: %s\n", strerror(errno));
108                 }
109         }
110         return 0;
111 }
112 #endif  /* DO_SSL */
113
114 HOOK_T ast_tcptls_server_read(struct ast_tcptls_session_instance *tcptls_session, void *buf, size_t count)
115 {
116         if (tcptls_session->fd == -1) {
117                 ast_log(LOG_ERROR, "server_read called with an fd of -1\n");
118                 errno = EIO;
119                 return -1;
120         }
121
122 #ifdef DO_SSL
123         if (tcptls_session->ssl) {
124                 return ssl_read(tcptls_session->ssl, buf, count);
125         }
126 #endif
127         return read(tcptls_session->fd, buf, count);
128 }
129
130 HOOK_T ast_tcptls_server_write(struct ast_tcptls_session_instance *tcptls_session, const void *buf, size_t count)
131 {
132         if (tcptls_session->fd == -1) {
133                 ast_log(LOG_ERROR, "server_write called with an fd of -1\n");
134                 errno = EIO;
135                 return -1;
136         }
137
138 #ifdef DO_SSL
139         if (tcptls_session->ssl) {
140                 return ssl_write(tcptls_session->ssl, buf, count);
141         }
142 #endif
143         return write(tcptls_session->fd, buf, count);
144 }
145
146 static void session_instance_destructor(void *obj)
147 {
148         struct ast_tcptls_session_instance *i = obj;
149         ast_free(i->overflow_buf);
150 }
151
152 /*! \brief
153 * creates a FILE * from the fd passed by the accept thread.
154 * This operation is potentially expensive (certificate verification),
155 * so we do it in the child thread context.
156 *
157 * \note must decrement ref count before returning NULL on error
158 */
159 static void *handle_tcptls_connection(void *data)
160 {
161         struct ast_tcptls_session_instance *tcptls_session = data;
162 #ifdef DO_SSL
163         int (*ssl_setup)(SSL *) = (tcptls_session->client) ? SSL_connect : SSL_accept;
164         int ret;
165         char err[256];
166 #endif
167
168         /* TCP/TLS connections are associated with external protocols, and
169          * should not be allowed to execute 'dangerous' functions. This may
170          * need to be pushed down into the individual protocol handlers, but
171          * this seems like a good general policy.
172          */
173         if (ast_thread_inhibit_escalations()) {
174                 ast_log(LOG_ERROR, "Failed to inhibit privilege escalations; killing connection\n");
175                 ast_tcptls_close_session_file(tcptls_session);
176                 ao2_ref(tcptls_session, -1);
177                 return NULL;
178         }
179
180         /*
181         * open a FILE * as appropriate.
182         */
183         if (!tcptls_session->parent->tls_cfg) {
184                 if ((tcptls_session->f = fdopen(tcptls_session->fd, "w+"))) {
185                         if(setvbuf(tcptls_session->f, NULL, _IONBF, 0)) {
186                                 ast_tcptls_close_session_file(tcptls_session);
187                         }
188                 }
189         }
190 #ifdef DO_SSL
191         else if ( (tcptls_session->ssl = SSL_new(tcptls_session->parent->tls_cfg->ssl_ctx)) ) {
192                 SSL_set_fd(tcptls_session->ssl, tcptls_session->fd);
193                 if ((ret = ssl_setup(tcptls_session->ssl)) <= 0) {
194                         ast_log(LOG_ERROR, "Problem setting up ssl connection: %s\n", ERR_error_string(ERR_get_error(), err));
195                 } else {
196 #if defined(HAVE_FUNOPEN)       /* the BSD interface */
197                         tcptls_session->f = funopen(tcptls_session->ssl, ssl_read, ssl_write, NULL, ssl_close);
198
199 #elif defined(HAVE_FOPENCOOKIE) /* the glibc/linux interface */
200                         static const cookie_io_functions_t cookie_funcs = {
201                                 ssl_read, ssl_write, NULL, ssl_close
202                         };
203                         tcptls_session->f = fopencookie(tcptls_session->ssl, "w+", cookie_funcs);
204 #else
205                         /* could add other methods here */
206                         ast_debug(2, "no tcptls_session->f methods attempted!\n");
207 #endif
208                         if ((tcptls_session->client && !ast_test_flag(&tcptls_session->parent->tls_cfg->flags, AST_SSL_DONT_VERIFY_SERVER))
209                                 || (!tcptls_session->client && ast_test_flag(&tcptls_session->parent->tls_cfg->flags, AST_SSL_VERIFY_CLIENT))) {
210                                 X509 *peer;
211                                 long res;
212                                 peer = SSL_get_peer_certificate(tcptls_session->ssl);
213                                 if (!peer) {
214                                         ast_log(LOG_ERROR, "No peer SSL certificate to verify\n");
215                                         ast_tcptls_close_session_file(tcptls_session);
216                                         ao2_ref(tcptls_session, -1);
217                                         return NULL;
218                                 }
219
220                                 res = SSL_get_verify_result(tcptls_session->ssl);
221                                 if (res != X509_V_OK) {
222                                         ast_log(LOG_ERROR, "Certificate did not verify: %s\n", X509_verify_cert_error_string(res));
223                                         X509_free(peer);
224                                         ast_tcptls_close_session_file(tcptls_session);
225                                         ao2_ref(tcptls_session, -1);
226                                         return NULL;
227                                 }
228                                 if (!ast_test_flag(&tcptls_session->parent->tls_cfg->flags, AST_SSL_IGNORE_COMMON_NAME)) {
229                                         ASN1_STRING *str;
230                                         unsigned char *str2;
231                                         X509_NAME *name = X509_get_subject_name(peer);
232                                         int pos = -1;
233                                         int found = 0;
234
235                                         for (;;) {
236                                                 /* Walk the certificate to check all available "Common Name" */
237                                                 /* XXX Probably should do a gethostbyname on the hostname and compare that as well */
238                                                 pos = X509_NAME_get_index_by_NID(name, NID_commonName, pos);
239                                                 if (pos < 0) {
240                                                         break;
241                                                 }
242                                                 str = X509_NAME_ENTRY_get_data(X509_NAME_get_entry(name, pos));
243                                                 ASN1_STRING_to_UTF8(&str2, str);
244                                                 if (str2) {
245                                                         if (!strcasecmp(tcptls_session->parent->hostname, (char *) str2)) {
246                                                                 found = 1;
247                                                         }
248                                                         ast_debug(3, "SSL Common Name compare s1='%s' s2='%s'\n", tcptls_session->parent->hostname, str2);
249                                                         OPENSSL_free(str2);
250                                                 }
251                                                 if (found) {
252                                                         break;
253                                                 }
254                                         }
255                                         if (!found) {
256                                                 ast_log(LOG_ERROR, "Certificate common name did not match (%s)\n", tcptls_session->parent->hostname);
257                                                 X509_free(peer);
258                                                 ast_tcptls_close_session_file(tcptls_session);
259                                                 ao2_ref(tcptls_session, -1);
260                                                 return NULL;
261                                         }
262                                 }
263                                 X509_free(peer);
264                         }
265                 }
266                 if (!tcptls_session->f) {       /* no success opening descriptor stacking */
267                         SSL_free(tcptls_session->ssl);
268                 }
269         }
270 #endif /* DO_SSL */
271
272         if (!tcptls_session->f) {
273                 ast_tcptls_close_session_file(tcptls_session);
274                 ast_log(LOG_WARNING, "FILE * open failed!\n");
275 #ifndef DO_SSL
276                 if (tcptls_session->parent->tls_cfg) {
277                         ast_log(LOG_ERROR, "Attempted a TLS connection without OpenSSL support. This will not work!\n");
278                 }
279 #endif
280                 ao2_ref(tcptls_session, -1);
281                 return NULL;
282         }
283
284         if (tcptls_session->parent->worker_fn) {
285                 return tcptls_session->parent->worker_fn(tcptls_session);
286         } else {
287                 return tcptls_session;
288         }
289 }
290
291 void *ast_tcptls_server_root(void *data)
292 {
293         struct ast_tcptls_session_args *desc = data;
294         int fd;
295         struct ast_sockaddr addr;
296         struct ast_tcptls_session_instance *tcptls_session;
297         pthread_t launched;
298
299         for (;;) {
300                 int i, flags;
301
302                 if (desc->periodic_fn) {
303                         desc->periodic_fn(desc);
304                 }
305                 i = ast_wait_for_input(desc->accept_fd, desc->poll_timeout);
306                 if (i <= 0) {
307                         continue;
308                 }
309                 fd = ast_accept(desc->accept_fd, &addr);
310                 if (fd < 0) {
311                         if ((errno != EAGAIN) && (errno != EINTR)) {
312                                 ast_log(LOG_ERROR, "Accept failed: %s\n", strerror(errno));
313                         }
314                         continue;
315                 }
316                 tcptls_session = ao2_alloc(sizeof(*tcptls_session), session_instance_destructor);
317                 if (!tcptls_session) {
318                         ast_log(LOG_WARNING, "No memory for new session: %s\n", strerror(errno));
319                         if (close(fd)) {
320                                 ast_log(LOG_ERROR, "close() failed: %s\n", strerror(errno));
321                         }
322                         continue;
323                 }
324
325                 tcptls_session->overflow_buf = ast_str_create(128);
326                 flags = fcntl(fd, F_GETFL);
327                 fcntl(fd, F_SETFL, flags & ~O_NONBLOCK);
328                 tcptls_session->fd = fd;
329                 tcptls_session->parent = desc;
330                 ast_sockaddr_copy(&tcptls_session->remote_address, &addr);
331
332                 tcptls_session->client = 0;
333
334                 /* This thread is now the only place that controls the single ref to tcptls_session */
335                 if (ast_pthread_create_detached_background(&launched, NULL, handle_tcptls_connection, tcptls_session)) {
336                         ast_log(LOG_ERROR, "Unable to launch helper thread: %s\n", strerror(errno));
337                         ast_tcptls_close_session_file(tcptls_session);
338                         ao2_ref(tcptls_session, -1);
339                 }
340         }
341         return NULL;
342 }
343
344 static int __ssl_setup(struct ast_tls_config *cfg, int client)
345 {
346 #ifndef DO_SSL
347         cfg->enabled = 0;
348         return 0;
349 #else
350         if (!cfg->enabled) {
351                 return 0;
352         }
353
354         /* Get rid of an old SSL_CTX since we're about to
355          * allocate a new one
356          */
357         if (cfg->ssl_ctx) {
358                 SSL_CTX_free(cfg->ssl_ctx);
359                 cfg->ssl_ctx = NULL;
360         }
361
362         if (client) {
363 #ifndef OPENSSL_NO_SSL2
364                 if (ast_test_flag(&cfg->flags, AST_SSL_SSLV2_CLIENT)) {
365                         cfg->ssl_ctx = SSL_CTX_new(SSLv2_client_method());
366                 } else
367 #endif
368                 if (ast_test_flag(&cfg->flags, AST_SSL_SSLV3_CLIENT)) {
369                         cfg->ssl_ctx = SSL_CTX_new(SSLv3_client_method());
370                 } else if (ast_test_flag(&cfg->flags, AST_SSL_TLSV1_CLIENT)) {
371                         cfg->ssl_ctx = SSL_CTX_new(TLSv1_client_method());
372                 } else {
373                         /* SSLv23_client_method() sends SSLv2, this was the original
374                          * default for ssl clients before the option was given to
375                          * pick what protocol a client should use.  In order not
376                          * to break expected behavior it remains the default. */
377                         cfg->ssl_ctx = SSL_CTX_new(SSLv23_client_method());
378                 }
379         } else {
380                 /* SSLv23_server_method() supports TLSv1, SSLv2, and SSLv3 inbound connections. */
381                 cfg->ssl_ctx = SSL_CTX_new(SSLv23_server_method());
382         }
383
384         if (!cfg->ssl_ctx) {
385                 ast_debug(1, "Sorry, SSL_CTX_new call returned null...\n");
386                 cfg->enabled = 0;
387                 return 0;
388         }
389
390         SSL_CTX_set_verify(cfg->ssl_ctx,
391                 ast_test_flag(&cfg->flags, AST_SSL_VERIFY_CLIENT) ? SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT : SSL_VERIFY_NONE,
392                 NULL);
393
394         if (!ast_strlen_zero(cfg->certfile)) {
395                 char *tmpprivate = ast_strlen_zero(cfg->pvtfile) ? cfg->certfile : cfg->pvtfile;
396                 if (SSL_CTX_use_certificate_chain_file(cfg->ssl_ctx, cfg->certfile) == 0) {
397                         if (!client) {
398                                 /* Clients don't need a certificate, but if its setup we can use it */
399                                 ast_log(LOG_ERROR, "TLS/SSL error loading cert file. <%s>\n", cfg->certfile);
400                                 cfg->enabled = 0;
401                                 SSL_CTX_free(cfg->ssl_ctx);
402                                 cfg->ssl_ctx = NULL;
403                                 return 0;
404                         }
405                 }
406                 if ((SSL_CTX_use_PrivateKey_file(cfg->ssl_ctx, tmpprivate, SSL_FILETYPE_PEM) == 0) || (SSL_CTX_check_private_key(cfg->ssl_ctx) == 0 )) {
407                         if (!client) {
408                                 /* Clients don't need a private key, but if its setup we can use it */
409                                 ast_log(LOG_ERROR, "TLS/SSL error loading private key file. <%s>\n", tmpprivate);
410                                 cfg->enabled = 0;
411                                 SSL_CTX_free(cfg->ssl_ctx);
412                                 cfg->ssl_ctx = NULL;
413                                 return 0;
414                         }
415                 }
416         }
417         if (!ast_strlen_zero(cfg->cipher)) {
418                 if (SSL_CTX_set_cipher_list(cfg->ssl_ctx, cfg->cipher) == 0 ) {
419                         if (!client) {
420                                 ast_log(LOG_ERROR, "TLS/SSL cipher error <%s>\n", cfg->cipher);
421                                 cfg->enabled = 0;
422                                 SSL_CTX_free(cfg->ssl_ctx);
423                                 cfg->ssl_ctx = NULL;
424                                 return 0;
425                         }
426                 }
427         }
428         if (!ast_strlen_zero(cfg->cafile) || !ast_strlen_zero(cfg->capath)) {
429                 if (SSL_CTX_load_verify_locations(cfg->ssl_ctx, S_OR(cfg->cafile, NULL), S_OR(cfg->capath,NULL)) == 0) {
430                         ast_log(LOG_ERROR, "TLS/SSL CA file(%s)/path(%s) error\n", cfg->cafile, cfg->capath);
431                 }
432         }
433
434         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 */
435         return 1;
436 #endif
437 }
438
439 int ast_ssl_setup(struct ast_tls_config *cfg)
440 {
441         return __ssl_setup(cfg, 0);
442 }
443
444 void ast_ssl_teardown(struct ast_tls_config *cfg)
445 {
446 #ifdef DO_SSL
447         if (cfg->ssl_ctx) {
448                 SSL_CTX_free(cfg->ssl_ctx);
449                 cfg->ssl_ctx = NULL;
450         }
451 #endif
452 }
453
454 struct ast_tcptls_session_instance *ast_tcptls_client_start(struct ast_tcptls_session_instance *tcptls_session)
455 {
456         struct ast_tcptls_session_args *desc;
457         int flags;
458
459         if (!(desc = tcptls_session->parent)) {
460                 goto client_start_error;
461         }
462
463         if (ast_connect(desc->accept_fd, &desc->remote_address)) {
464                 ast_log(LOG_ERROR, "Unable to connect %s to %s: %s\n",
465                         desc->name,
466                         ast_sockaddr_stringify(&desc->remote_address),
467                         strerror(errno));
468                 goto client_start_error;
469         }
470
471         flags = fcntl(desc->accept_fd, F_GETFL);
472         fcntl(desc->accept_fd, F_SETFL, flags & ~O_NONBLOCK);
473
474         if (desc->tls_cfg) {
475                 desc->tls_cfg->enabled = 1;
476                 __ssl_setup(desc->tls_cfg, 1);
477         }
478
479         return handle_tcptls_connection(tcptls_session);
480
481 client_start_error:
482         if (desc) {
483                 close(desc->accept_fd);
484                 desc->accept_fd = -1;
485         }
486         ao2_ref(tcptls_session, -1);
487         return NULL;
488
489 }
490
491 struct ast_tcptls_session_instance *ast_tcptls_client_create(struct ast_tcptls_session_args *desc)
492 {
493         int x = 1;
494         struct ast_tcptls_session_instance *tcptls_session = NULL;
495
496         /* Do nothing if nothing has changed */
497         if (!ast_sockaddr_cmp(&desc->old_address, &desc->remote_address)) {
498                 ast_debug(1, "Nothing changed in %s\n", desc->name);
499                 return NULL;
500         }
501
502         /* If we return early, there is no connection */
503         ast_sockaddr_setnull(&desc->old_address);
504
505         if (desc->accept_fd != -1) {
506                 close(desc->accept_fd);
507         }
508
509         desc->accept_fd = socket(ast_sockaddr_is_ipv6(&desc->remote_address) ?
510                                  AF_INET6 : AF_INET, SOCK_STREAM, IPPROTO_TCP);
511         if (desc->accept_fd < 0) {
512                 ast_log(LOG_ERROR, "Unable to allocate socket for %s: %s\n",
513                         desc->name, strerror(errno));
514                 return NULL;
515         }
516
517         /* if a local address was specified, bind to it so the connection will
518            originate from the desired address */
519         if (!ast_sockaddr_isnull(&desc->local_address)) {
520                 setsockopt(desc->accept_fd, SOL_SOCKET, SO_REUSEADDR, &x, sizeof(x));
521                 if (ast_bind(desc->accept_fd, &desc->local_address)) {
522                         ast_log(LOG_ERROR, "Unable to bind %s to %s: %s\n",
523                                 desc->name,
524                                 ast_sockaddr_stringify(&desc->local_address),
525                                 strerror(errno));
526                         goto error;
527                 }
528         }
529
530         if (!(tcptls_session = ao2_alloc(sizeof(*tcptls_session), session_instance_destructor))) {
531                 goto error;
532         }
533
534         tcptls_session->overflow_buf = ast_str_create(128);
535         tcptls_session->client = 1;
536         tcptls_session->fd = desc->accept_fd;
537         tcptls_session->parent = desc;
538         tcptls_session->parent->worker_fn = NULL;
539         ast_sockaddr_copy(&tcptls_session->remote_address,
540                           &desc->remote_address);
541
542         /* Set current info */
543         ast_sockaddr_copy(&desc->old_address, &desc->remote_address);
544         return tcptls_session;
545
546 error:
547         close(desc->accept_fd);
548         desc->accept_fd = -1;
549         if (tcptls_session) {
550                 ao2_ref(tcptls_session, -1);
551         }
552         return NULL;
553 }
554
555 void ast_tcptls_server_start(struct ast_tcptls_session_args *desc)
556 {
557         int flags;
558         int x = 1;
559
560         /* Do nothing if nothing has changed */
561         if (!ast_sockaddr_cmp(&desc->old_address, &desc->local_address)) {
562                 ast_debug(1, "Nothing changed in %s\n", desc->name);
563                 return;
564         }
565
566         /* If we return early, there is no one listening */
567         ast_sockaddr_setnull(&desc->old_address);
568
569         /* Shutdown a running server if there is one */
570         if (desc->master != AST_PTHREADT_NULL) {
571                 pthread_cancel(desc->master);
572                 pthread_kill(desc->master, SIGURG);
573                 pthread_join(desc->master, NULL);
574         }
575
576         if (desc->accept_fd != -1) {
577                 close(desc->accept_fd);
578         }
579
580         /* If there's no new server, stop here */
581         if (ast_sockaddr_isnull(&desc->local_address)) {
582                 ast_debug(2, "Server disabled:  %s\n", desc->name);
583                 return;
584         }
585
586         desc->accept_fd = socket(ast_sockaddr_is_ipv6(&desc->local_address) ?
587                                  AF_INET6 : AF_INET, SOCK_STREAM, 0);
588         if (desc->accept_fd < 0) {
589                 ast_log(LOG_ERROR, "Unable to allocate socket for %s: %s\n", desc->name, strerror(errno));
590                 return;
591         }
592
593         setsockopt(desc->accept_fd, SOL_SOCKET, SO_REUSEADDR, &x, sizeof(x));
594         if (ast_bind(desc->accept_fd, &desc->local_address)) {
595                 ast_log(LOG_ERROR, "Unable to bind %s to %s: %s\n",
596                         desc->name,
597                         ast_sockaddr_stringify(&desc->local_address),
598                         strerror(errno));
599                 goto error;
600         }
601         if (listen(desc->accept_fd, 10)) {
602                 ast_log(LOG_ERROR, "Unable to listen for %s!\n", desc->name);
603                 goto error;
604         }
605         flags = fcntl(desc->accept_fd, F_GETFL);
606         fcntl(desc->accept_fd, F_SETFL, flags | O_NONBLOCK);
607         if (ast_pthread_create_background(&desc->master, NULL, desc->accept_fn, desc)) {
608                 ast_log(LOG_ERROR, "Unable to launch thread for %s on %s: %s\n",
609                         desc->name,
610                         ast_sockaddr_stringify(&desc->local_address),
611                         strerror(errno));
612                 goto error;
613         }
614
615         /* Set current info */
616         ast_sockaddr_copy(&desc->old_address, &desc->local_address);
617
618         return;
619
620 error:
621         close(desc->accept_fd);
622         desc->accept_fd = -1;
623 }
624
625 void ast_tcptls_close_session_file(struct ast_tcptls_session_instance *tcptls_session)
626 {
627         if (tcptls_session->f) {
628                 /*
629                  * Issuing shutdown() is necessary here to avoid a race
630                  * condition where the last data written may not appear
631                  * in the TCP stream.  See ASTERISK-23548
632                 */
633                 fflush(tcptls_session->f);
634                 if (tcptls_session->fd != -1) {
635                         shutdown(tcptls_session->fd, SHUT_RDWR);
636                 }
637                 if (fclose(tcptls_session->f)) {
638                         ast_log(LOG_ERROR, "fclose() failed: %s\n", strerror(errno));
639                 }
640                 tcptls_session->f = NULL;
641                 tcptls_session->fd = -1;
642         } else if (tcptls_session->fd != -1) {
643                 shutdown(tcptls_session->fd, SHUT_RDWR);
644                 if (close(tcptls_session->fd)) {
645                         ast_log(LOG_ERROR, "close() failed: %s\n", strerror(errno));
646                 }
647                 tcptls_session->fd = -1;
648         } else {
649                 ast_log(LOG_ERROR, "ast_tcptls_close_session_file invoked on session instance without file or file descriptor\n");
650         }
651 }
652
653 void ast_tcptls_server_stop(struct ast_tcptls_session_args *desc)
654 {
655         if (desc->master != AST_PTHREADT_NULL) {
656                 pthread_cancel(desc->master);
657                 pthread_kill(desc->master, SIGURG);
658                 pthread_join(desc->master, NULL);
659                 desc->master = AST_PTHREADT_NULL;
660         }
661         if (desc->accept_fd != -1) {
662                 close(desc->accept_fd);
663         }
664         desc->accept_fd = -1;
665         ast_debug(2, "Stopped server :: %s\n", desc->name);
666 }
667
668 int ast_tls_read_conf(struct ast_tls_config *tls_cfg, struct ast_tcptls_session_args *tls_desc, const char *varname, const char *value)
669 {
670         if (!strcasecmp(varname, "tlsenable") || !strcasecmp(varname, "sslenable")) {
671                 tls_cfg->enabled = ast_true(value) ? 1 : 0;
672         } else if (!strcasecmp(varname, "tlscertfile") || !strcasecmp(varname, "sslcert") || !strcasecmp(varname, "tlscert")) {
673                 ast_free(tls_cfg->certfile);
674                 tls_cfg->certfile = ast_strdup(value);
675         } else if (!strcasecmp(varname, "tlsprivatekey") || !strcasecmp(varname, "sslprivatekey")) {
676                 ast_free(tls_cfg->pvtfile);
677                 tls_cfg->pvtfile = ast_strdup(value);
678         } else if (!strcasecmp(varname, "tlscipher") || !strcasecmp(varname, "sslcipher")) {
679                 ast_free(tls_cfg->cipher);
680                 tls_cfg->cipher = ast_strdup(value);
681         } else if (!strcasecmp(varname, "tlscafile")) {
682                 ast_free(tls_cfg->cafile);
683                 tls_cfg->cafile = ast_strdup(value);
684         } else if (!strcasecmp(varname, "tlscapath") || !strcasecmp(varname, "tlscadir")) {
685                 ast_free(tls_cfg->capath);
686                 tls_cfg->capath = ast_strdup(value);
687         } else if (!strcasecmp(varname, "tlsverifyclient")) {
688                 ast_set2_flag(&tls_cfg->flags, ast_true(value), AST_SSL_VERIFY_CLIENT);
689         } else if (!strcasecmp(varname, "tlsdontverifyserver")) {
690                 ast_set2_flag(&tls_cfg->flags, ast_true(value), AST_SSL_DONT_VERIFY_SERVER);
691         } else if (!strcasecmp(varname, "tlsbindaddr") || !strcasecmp(varname, "sslbindaddr")) {
692                 if (ast_parse_arg(value, PARSE_ADDR, &tls_desc->local_address))
693                         ast_log(LOG_ERROR, "Invalid %s '%s'\n", varname, value);
694         } else if (!strcasecmp(varname, "tlsclientmethod") || !strcasecmp(varname, "sslclientmethod")) {
695                 if (!strcasecmp(value, "tlsv1")) {
696                         ast_set_flag(&tls_cfg->flags, AST_SSL_TLSV1_CLIENT);
697                         ast_clear_flag(&tls_cfg->flags, AST_SSL_SSLV3_CLIENT);
698                         ast_clear_flag(&tls_cfg->flags, AST_SSL_SSLV2_CLIENT);
699                 } else if (!strcasecmp(value, "sslv3")) {
700                         ast_set_flag(&tls_cfg->flags, AST_SSL_SSLV3_CLIENT);
701                         ast_clear_flag(&tls_cfg->flags, AST_SSL_SSLV2_CLIENT);
702                         ast_clear_flag(&tls_cfg->flags, AST_SSL_TLSV1_CLIENT);
703                 } else if (!strcasecmp(value, "sslv2")) {
704                         ast_set_flag(&tls_cfg->flags, AST_SSL_SSLV2_CLIENT);
705                         ast_clear_flag(&tls_cfg->flags, AST_SSL_TLSV1_CLIENT);
706                         ast_clear_flag(&tls_cfg->flags, AST_SSL_SSLV3_CLIENT);
707                 }
708         } else {
709                 return -1;
710         }
711
712         return 0;
713 }