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