res_rtp_asterisk.c: Fix rtp source address learning for broken clients
[asterisk/asterisk.git] / main / iostream.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 1999 - 2015, Digium, Inc.
5  *
6  * Timo Teräs <timo.teras@iki.fi>
7  *
8  * See http://www.asterisk.org for more information about
9  * the Asterisk project. Please do not directly contact
10  * any of the maintainers of this project for assistance;
11  * the project provides a web site, mailing lists and IRC
12  * channels for your use.
13  *
14  * This program is free software, distributed under the terms of
15  * the GNU General Public License Version 2. See the LICENSE file
16  * at the top of the source tree.
17  */
18
19 #include "asterisk.h"
20
21 #include <fcntl.h>
22 #include <stdarg.h>
23
24 #include "asterisk/utils.h"
25 #include "asterisk/astobj2.h"
26 #include "asterisk/iostream.h"
27
28 struct ast_iostream {
29         SSL *ssl;
30         struct timeval start;
31         int fd;
32         int timeout;
33         int timeout_reset;
34         int exclusive_input;
35         int rbuflen;
36         char *rbufhead;
37         char rbuf[2048];
38 };
39
40 #if defined(DO_SSL)
41 AST_THREADSTORAGE(err2str_threadbuf);
42 #define ERR2STR_BUFSIZE   128
43
44 static const char *ssl_error_to_string(int sslerr, int ret)
45 {
46         switch (sslerr) {
47         case SSL_ERROR_SSL:
48                 return "Internal SSL error";
49         case SSL_ERROR_SYSCALL:
50                 if (!ret) {
51                         return "System call EOF";
52                 } else if (ret == -1) {
53                         char *buf;
54
55                         buf = ast_threadstorage_get(&err2str_threadbuf, ERR2STR_BUFSIZE);
56                         if (!buf) {
57                                 return "Unknown";
58                         }
59
60                         snprintf(buf, ERR2STR_BUFSIZE, "Underlying BIO error: %s", strerror(errno));
61                         return buf;
62                 } else {
63                         return "System call other";
64                 }
65         default:
66                 break;
67         }
68
69         return "Unknown";
70 }
71 #endif
72
73 int ast_iostream_get_fd(struct ast_iostream *stream)
74 {
75         return stream->fd;
76 }
77
78 void ast_iostream_nonblock(struct ast_iostream *stream)
79 {
80         fcntl(stream->fd, F_SETFL, fcntl(stream->fd, F_GETFL) | O_NONBLOCK);
81 }
82
83 SSL *ast_iostream_get_ssl(struct ast_iostream *stream)
84 {
85         return stream->ssl;
86 }
87
88 void ast_iostream_set_timeout_disable(struct ast_iostream *stream)
89 {
90         ast_assert(stream != NULL);
91
92         stream->timeout = -1;
93         stream->timeout_reset = -1;
94 }
95
96 void ast_iostream_set_timeout_inactivity(struct ast_iostream *stream, int timeout)
97 {
98         ast_assert(stream != NULL);
99
100         stream->start.tv_sec = 0;
101         stream->timeout = timeout;
102         stream->timeout_reset = timeout;
103 }
104
105 void ast_iostream_set_timeout_idle_inactivity(struct ast_iostream *stream, int timeout, int timeout_reset)
106 {
107         ast_assert(stream != NULL);
108
109         stream->start.tv_sec = 0;
110         stream->timeout = timeout;
111         stream->timeout_reset = timeout_reset;
112 }
113
114 void ast_iostream_set_timeout_sequence(struct ast_iostream *stream, struct timeval start, int timeout)
115 {
116         ast_assert(stream != NULL);
117
118         stream->start = start;
119         stream->timeout = timeout;
120         stream->timeout_reset = timeout;
121 }
122
123 void ast_iostream_set_exclusive_input(struct ast_iostream *stream, int exclusive_input)
124 {
125         ast_assert(stream != NULL);
126
127         stream->exclusive_input = exclusive_input;
128 }
129
130 static ssize_t iostream_read(struct ast_iostream *stream, void *buf, size_t size)
131 {
132         struct timeval start;
133         int ms;
134         int res;
135
136         if (stream->start.tv_sec) {
137                 start = stream->start;
138         } else {
139                 start = ast_tvnow();
140         }
141
142 #if defined(DO_SSL)
143         if (stream->ssl) {
144                 for (;;) {
145                         int sslerr;
146                         char err[256];
147                         res = SSL_read(stream->ssl, buf, size);
148                         if (0 < res) {
149                                 /* We read some payload data. */
150                                 stream->timeout = stream->timeout_reset;
151                                 return res;
152                         }
153                         sslerr = SSL_get_error(stream->ssl, res);
154                         switch (sslerr) {
155                         case SSL_ERROR_ZERO_RETURN:
156                                 /* Report EOF for a shutdown */
157                                 ast_debug(1, "TLS clean shutdown alert reading data\n");
158                                 return 0;
159                         case SSL_ERROR_WANT_READ:
160                                 if (!stream->exclusive_input) {
161                                         /* We cannot wait for data now. */
162                                         errno = EAGAIN;
163                                         return -1;
164                                 }
165                                 while ((ms = ast_remaining_ms(start, stream->timeout))) {
166                                         res = ast_wait_for_input(stream->fd, ms);
167                                         if (0 < res) {
168                                                 /* Socket is ready to be read. */
169                                                 break;
170                                         }
171                                         if (res < 0) {
172                                                 if (errno == EINTR || errno == EAGAIN) {
173                                                         /* Try again. */
174                                                         continue;
175                                                 }
176                                                 ast_debug(1, "TLS socket error waiting for read data: %s\n",
177                                                         strerror(errno));
178                                                 return -1;
179                                         }
180                                 }
181                                 break;
182                         case SSL_ERROR_WANT_WRITE:
183                                 while ((ms = ast_remaining_ms(start, stream->timeout))) {
184                                         res = ast_wait_for_output(stream->fd, ms);
185                                         if (0 < res) {
186                                                 /* Socket is ready to be written. */
187                                                 break;
188                                         }
189                                         if (res < 0) {
190                                                 if (errno == EINTR || errno == EAGAIN) {
191                                                         /* Try again. */
192                                                         continue;
193                                                 }
194                                                 ast_debug(1, "TLS socket error waiting for write space: %s\n",
195                                                         strerror(errno));
196                                                 return -1;
197                                         }
198                                 }
199                                 break;
200                         default:
201                                 /* Report EOF for an undecoded SSL or transport error. */
202                                 ast_debug(1, "TLS transport or SSL error reading data:  %s, %s\n", ERR_error_string(sslerr, err),
203                                         ssl_error_to_string(sslerr, res));
204                                 return 0;
205                         }
206                         if (!ms) {
207                                 /* Report EOF for a timeout */
208                                 ast_debug(1, "TLS timeout reading data\n");
209                                 return 0;
210                         }
211                 }
212         }
213 #endif  /* defined(DO_SSL) */
214
215         for (;;) {
216                 res = read(stream->fd, buf, size);
217                 if (0 <= res) {
218                         /* Got data or we cannot wait for it. */
219                         stream->timeout = stream->timeout_reset;
220                         return res;
221                 }
222                 if (!stream->exclusive_input) {
223                         return res;
224                 }
225                 if (errno != EINTR && errno != EAGAIN) {
226                         /* Not a retryable error. */
227                         ast_debug(1, "TCP socket error reading data: %s\n",
228                                 strerror(errno));
229                         return -1;
230                 }
231                 ms = ast_remaining_ms(start, stream->timeout);
232                 if (!ms) {
233                         /* Report EOF for a timeout */
234                         ast_debug(1, "TCP timeout reading data\n");
235                         return 0;
236                 }
237                 ast_wait_for_input(stream->fd, ms);
238         }
239 }
240
241 ssize_t ast_iostream_read(struct ast_iostream *stream, void *buf, size_t size)
242 {
243         if (!size) {
244                 /* You asked for no data you got no data. */
245                 return 0;
246         }
247
248         if (!stream || stream->fd == -1) {
249                 errno = EBADF;
250                 return -1;
251         }
252
253         /* Get any remains from the read buffer */
254         if (stream->rbuflen) {
255                 size_t r = size;
256                 if (r > stream->rbuflen) {
257                         r = stream->rbuflen;
258                 }
259                 memcpy(buf, stream->rbufhead, r);
260                 stream->rbuflen -= r;
261                 stream->rbufhead += r;
262                 return r;
263         }
264
265         return iostream_read(stream, buf, size);
266 }
267
268 ssize_t ast_iostream_gets(struct ast_iostream *stream, char *buf, size_t count)
269 {
270         ssize_t r;
271         char *newline;
272
273         do {
274                 /* Search for newline */
275                 newline = memchr(stream->rbufhead, '\n', stream->rbuflen);
276                 if (newline) {
277                         r = newline - stream->rbufhead + 1;
278                         if (r > count-1) {
279                                 r = count-1;
280                         }
281                         break;
282                 }
283
284                 /* Enough data? */
285                 if (stream->rbuflen >= count - 1) {
286                         r = count - 1;
287                         break;
288                 }
289
290                 /* Try to fill in line buffer */
291                 if (stream->rbuflen && stream->rbuf != stream->rbufhead) {
292                         memmove(&stream->rbuf, stream->rbufhead, stream->rbuflen);
293                 }
294                 stream->rbufhead = stream->rbuf;
295
296                 r = iostream_read(stream, stream->rbufhead + stream->rbuflen, sizeof(stream->rbuf) - stream->rbuflen);
297                 if (r <= 0) {
298                         return r;
299                 }
300                 stream->rbuflen += r;
301         } while (1);
302
303         /* Return r bytes with termination byte */
304         memcpy(buf, stream->rbufhead, r);
305         buf[r] = 0;
306         stream->rbuflen -= r;
307         stream->rbufhead += r;
308
309         return r;
310 }
311
312 ssize_t ast_iostream_discard(struct ast_iostream *stream, size_t size)
313 {
314         char buf[1024];
315         size_t remaining = size;
316         ssize_t ret;
317
318         while (remaining) {
319                 ret = ast_iostream_read(stream, buf, remaining > sizeof(buf) ? sizeof(buf) : remaining);
320                 if (ret < 0) {
321                         return ret;
322                 }
323                 remaining -= ret;
324         }
325
326         return size;
327 }
328
329 ssize_t ast_iostream_write(struct ast_iostream *stream, const void *buf, size_t size)
330 {
331         struct timeval start;
332         int ms;
333         int res;
334         int written;
335         int remaining;
336
337         if (!size) {
338                 /* You asked to write no data you wrote no data. */
339                 return 0;
340         }
341
342         if (!stream || stream->fd == -1) {
343                 errno = EBADF;
344                 return -1;
345         }
346
347         if (stream->start.tv_sec) {
348                 start = stream->start;
349         } else {
350                 start = ast_tvnow();
351         }
352
353 #if defined(DO_SSL)
354         if (stream->ssl) {
355                 written = 0;
356                 remaining = size;
357                 for (;;) {
358                         int sslerr;
359                         char err[256];
360                         res = SSL_write(stream->ssl, buf + written, remaining);
361                         if (res == remaining) {
362                                 /* Everything was written. */
363                                 return size;
364                         }
365                         if (0 < res) {
366                                 /* Successfully wrote part of the buffer.  Try to write the rest. */
367                                 written += res;
368                                 remaining -= res;
369                                 continue;
370                         }
371                         sslerr = SSL_get_error(stream->ssl, res);
372                         switch (sslerr) {
373                         case SSL_ERROR_ZERO_RETURN:
374                                 ast_debug(1, "TLS clean shutdown alert writing data\n");
375                                 if (written) {
376                                         /* Report partial write. */
377                                         return written;
378                                 }
379                                 errno = EBADF;
380                                 return -1;
381                         case SSL_ERROR_WANT_READ:
382                                 ms = ast_remaining_ms(start, stream->timeout);
383                                 if (!ms) {
384                                         /* Report partial write. */
385                                         ast_debug(1, "TLS timeout writing data (want read)\n");
386                                         return written;
387                                 }
388                                 ast_wait_for_input(stream->fd, ms);
389                                 break;
390                         case SSL_ERROR_WANT_WRITE:
391                                 ms = ast_remaining_ms(start, stream->timeout);
392                                 if (!ms) {
393                                         /* Report partial write. */
394                                         ast_debug(1, "TLS timeout writing data (want write)\n");
395                                         return written;
396                                 }
397                                 ast_wait_for_output(stream->fd, ms);
398                                 break;
399                         default:
400                                 /* Undecoded SSL or transport error. */
401                                 ast_debug(1, "TLS transport or SSL error writing data: %s, %s\n", ERR_error_string(sslerr, err),
402                                         ssl_error_to_string(sslerr, res));
403                                 if (written) {
404                                         /* Report partial write. */
405                                         return written;
406                                 }
407                                 errno = EBADF;
408                                 return -1;
409                         }
410                 }
411         }
412 #endif  /* defined(DO_SSL) */
413
414         written = 0;
415         remaining = size;
416         for (;;) {
417                 res = write(stream->fd, buf + written, remaining);
418                 if (res == remaining) {
419                         /* Yay everything was written. */
420                         return size;
421                 }
422                 if (0 < res) {
423                         /* Successfully wrote part of the buffer.  Try to write the rest. */
424                         written += res;
425                         remaining -= res;
426                         continue;
427                 }
428                 if (errno != EINTR && errno != EAGAIN) {
429                         /* Not a retryable error. */
430                         ast_debug(1, "TCP socket error writing: %s\n", strerror(errno));
431                         if (written) {
432                                 return written;
433                         }
434                         return -1;
435                 }
436                 ms = ast_remaining_ms(start, stream->timeout);
437                 if (!ms) {
438                         /* Report partial write. */
439                         ast_debug(1, "TCP timeout writing data\n");
440                         return written;
441                 }
442                 ast_wait_for_output(stream->fd, ms);
443         }
444 }
445
446 ssize_t ast_iostream_printf(struct ast_iostream *stream, const void *fmt, ...)
447 {
448         char sbuf[512], *buf = sbuf;
449         int len, len2, ret = -1;
450         va_list va;
451
452         va_start(va, fmt);
453         len = vsnprintf(buf, sizeof(sbuf), fmt, va);
454         va_end(va);
455
456         if (len > sizeof(sbuf) - 1) {
457                 /* Add one to the string length to accommodate the NULL byte */
458                 size_t buf_len = len + 1;
459
460                 buf = ast_malloc(buf_len);
461                 if (!buf) {
462                         return -1;
463                 }
464                 va_start(va, fmt);
465                 len2 = vsnprintf(buf, buf_len, fmt, va);
466                 va_end(va);
467                 if (len2 != len) {
468                         goto error;
469                 }
470         }
471
472         if (ast_iostream_write(stream, buf, len) == len)
473                 ret = len;
474
475 error:
476         if (buf != sbuf) {
477                 ast_free(buf);
478         }
479
480         return ret;
481 }
482
483 int ast_iostream_close(struct ast_iostream *stream)
484 {
485         if (!stream) {
486                 errno = EBADF;
487                 return -1;
488         }
489
490         if (stream->fd != -1) {
491 #if defined(DO_SSL)
492                 if (stream->ssl) {
493                         int res;
494
495                         /*
496                          * According to the TLS standard, it is acceptable for an
497                          * application to only send its shutdown alert and then
498                          * close the underlying connection without waiting for
499                          * the peer's response (this way resources can be saved,
500                          * as the process can already terminate or serve another
501                          * connection).
502                          */
503                         res = SSL_shutdown(stream->ssl);
504                         if (res < 0) {
505                                 int sslerr = SSL_get_error(stream->ssl, res);
506                                 char err[256];
507                                 ast_log(LOG_ERROR, "SSL_shutdown() failed: %s, %s\n",
508                                         ERR_error_string(sslerr, err), ssl_error_to_string(sslerr, res));
509                         }
510
511 #if defined(OPENSSL_VERSION_NUMBER) && OPENSSL_VERSION_NUMBER >= 0x10100000L && !defined(LIBRESSL_VERSION_NUMBER)
512                         if (!SSL_is_server(stream->ssl)) {
513 #else
514                         if (!stream->ssl->server) {
515 #endif
516                                 /* For client threads, ensure that the error stack is cleared */
517 #if !defined(OPENSSL_VERSION_NUMBER) || OPENSSL_VERSION_NUMBER < 0x10100000L || defined(LIBRESSL_VERSION_NUMBER)
518 #if OPENSSL_VERSION_NUMBER >= 0x10000000L
519                                 ERR_remove_thread_state(NULL);
520 #else
521                                 ERR_remove_state(0);
522 #endif  /* OPENSSL_VERSION_NUMBER >= 0x10000000L */
523 #endif  /* !defined(OPENSSL_VERSION_NUMBER) || OPENSSL_VERSION_NUMBER < 0x10100000L */
524                         }
525
526                         SSL_free(stream->ssl);
527                         stream->ssl = NULL;
528                 }
529 #endif  /* defined(DO_SSL) */
530
531                 /*
532                  * Issuing shutdown() is necessary here to avoid a race
533                  * condition where the last data written may not appear
534                  * in the TCP stream.  See ASTERISK-23548
535                  */
536                 shutdown(stream->fd, SHUT_RDWR);
537                 if (close(stream->fd)) {
538                         ast_log(LOG_ERROR, "close() failed: %s\n", strerror(errno));
539                 }
540                 stream->fd = -1;
541         }
542         ao2_t_ref(stream, -1, "Closed ast_iostream");
543
544         return 0;
545 }
546
547 static void iostream_dtor(void *cookie)
548 {
549 #ifdef AST_DEVMODE
550         /* Since the ast_assert below is the only one using stream,
551          * and ast_assert is only available with AST_DEVMODE, we
552          * put this in a conditional to avoid compiler warnings. */
553         struct ast_iostream *stream = cookie;
554 #endif
555
556         ast_assert(stream->fd == -1);
557 }
558
559 struct ast_iostream *ast_iostream_from_fd(int *fd)
560 {
561         struct ast_iostream *stream;
562
563         stream = ao2_alloc_options(sizeof(*stream), iostream_dtor,
564                 AO2_ALLOC_OPT_LOCK_NOLOCK);
565         if (stream) {
566                 stream->timeout = -1;
567                 stream->timeout_reset = -1;
568                 stream->fd = *fd;
569                 *fd = -1;
570         }
571
572         return stream;
573 }
574
575 int ast_iostream_start_tls(struct ast_iostream **pstream, SSL_CTX *ssl_ctx, int client)
576 {
577 #ifdef DO_SSL
578         struct ast_iostream *stream = *pstream;
579         int (*ssl_setup)(SSL *) = client ? SSL_connect : SSL_accept;
580         int res;
581
582         stream->ssl = SSL_new(ssl_ctx);
583         if (!stream->ssl) {
584                 ast_log(LOG_ERROR, "Unable to create new SSL connection\n");
585                 errno = ENOMEM;
586                 return -1;
587         }
588
589         /*
590          * This function takes struct ast_iostream **, so it can chain
591          * SSL over any ast_iostream. For now we assume it's a file descriptor.
592          * But later this should instead use BIO wrapper to tie SSL to another
593          * ast_iostream.
594          */
595         SSL_set_fd(stream->ssl, stream->fd);
596
597         res = ssl_setup(stream->ssl);
598         if (res <= 0) {
599                 int sslerr = SSL_get_error(stream->ssl, res);
600                 char err[256];
601
602                 ast_log(LOG_ERROR, "Problem setting up ssl connection: %s, %s\n",
603                         ERR_error_string(sslerr, err), ssl_error_to_string(sslerr, res));
604                 errno = EIO;
605                 return -1;
606         }
607
608         return 0;
609 #else
610         ast_log(LOG_ERROR, "SSL not enabled in this build\n");
611         errno = ENOTSUP;
612         return -1;
613 #endif
614 }