Cleanup udptl on exit.
[asterisk/asterisk.git] / main / udptl.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * UDPTL support for T.38
5  *
6  * Copyright (C) 2005, Steve Underwood, partly based on RTP code which is
7  * Copyright (C) 1999-2009, Digium, Inc.
8  *
9  * Steve Underwood <steveu@coppice.org>
10  * Kevin P. Fleming <kpfleming@digium.com>
11  *
12  * See http://www.asterisk.org for more information about
13  * the Asterisk project. Please do not directly contact
14  * any of the maintainers of this project for assistance;
15  * the project provides a web site, mailing lists and IRC
16  * channels for your use.
17  *
18  * This program is free software, distributed under the terms of
19  * the GNU General Public License Version 2. See the LICENSE file
20  * at the top of the source tree.
21  *
22  * A license has been granted to Digium (via disclaimer) for the use of
23  * this code.
24  */
25
26 /*!
27  * \file
28  *
29  * \brief UDPTL support for T.38 faxing
30  *
31  *
32  * \author Mark Spencer <markster@digium.com>
33  * \author Steve Underwood <steveu@coppice.org>
34  * \author Kevin P. Fleming <kpfleming@digium.com>
35  *
36  * \page T38fax_udptl T.38 support :: UDPTL
37  *
38  * Asterisk supports T.38 fax passthrough, origination and termination. It does
39  * not support gateway operation. The only channel driver that supports T.38 at
40  * this time is chan_sip.
41  *
42  * UDPTL is handled very much like RTP. It can be reinvited to go directly between
43  * the endpoints, without involving Asterisk in the media stream.
44  *
45  * \b References:
46  * - chan_sip.c
47  * - udptl.c
48  * - app_fax.c
49  */
50
51 /*! \li \ref udptl.c uses the configuration file \ref udptl.conf
52  * \addtogroup configuration_file Configuration Files
53  */
54
55 /*!
56  * \page udptl.conf udptl.conf
57  * \verbinclude udptl.conf.sample
58  */
59
60 /*** MODULEINFO
61         <support_level>core</support_level>
62  ***/
63
64 #include "asterisk.h"
65
66 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
67
68 #include <sys/time.h>
69 #include <signal.h>
70 #include <fcntl.h>
71
72 #include "asterisk/udptl.h"
73 #include "asterisk/frame.h"
74 #include "asterisk/channel.h"
75 #include "asterisk/acl.h"
76 #include "asterisk/config_options.h"
77 #include "asterisk/lock.h"
78 #include "asterisk/utils.h"
79 #include "asterisk/netsock2.h"
80 #include "asterisk/cli.h"
81 #include "asterisk/unaligned.h"
82
83 #define UDPTL_MTU               1200
84
85 #if !defined(FALSE)
86 #define FALSE 0
87 #endif
88 #if !defined(TRUE)
89 #define TRUE (!FALSE)
90 #endif
91
92 #define LOG_TAG(u) S_OR(u->tag, "no tag")
93
94 #define DEFAULT_UDPTLSTART 4000
95 #define DEFAULT_UDPTLEND 4999
96
97 static int udptldebug;                      /*!< Are we debugging? */
98 static struct ast_sockaddr udptldebugaddr;   /*!< Debug packets to/from this host */
99
100 #define LOCAL_FAX_MAX_DATAGRAM      1400
101 #define DEFAULT_FAX_MAX_DATAGRAM    400
102 #define FAX_MAX_DATAGRAM_LIMIT      1400
103 #define MAX_FEC_ENTRIES             5
104 #define MAX_FEC_SPAN                5
105
106 #define UDPTL_BUF_MASK              15
107
108 typedef struct {
109         int buf_len;
110         uint8_t buf[LOCAL_FAX_MAX_DATAGRAM];
111 } udptl_fec_tx_buffer_t;
112
113 typedef struct {
114         int buf_len;
115         uint8_t buf[LOCAL_FAX_MAX_DATAGRAM];
116         unsigned int fec_len[MAX_FEC_ENTRIES];
117         uint8_t fec[MAX_FEC_ENTRIES][LOCAL_FAX_MAX_DATAGRAM];
118         unsigned int fec_span;
119         unsigned int fec_entries;
120 } udptl_fec_rx_buffer_t;
121
122 /*! \brief Structure for an UDPTL session */
123 struct ast_udptl {
124         int fd;
125         char resp;
126         struct ast_frame f[16];
127         unsigned char rawdata[8192 + AST_FRIENDLY_OFFSET];
128         unsigned int lasteventseqn;
129         int nat;
130         int flags;
131         struct ast_sockaddr us;
132         struct ast_sockaddr them;
133         int *ioid;
134         struct ast_sched_context *sched;
135         struct io_context *io;
136         void *data;
137         char *tag;
138         ast_udptl_callback callback;
139
140         /*! This option indicates the error correction scheme used in transmitted UDPTL
141          * packets and expected in received UDPTL packets.
142          */
143         enum ast_t38_ec_modes error_correction_scheme;
144
145         /*! This option indicates the number of error correction entries transmitted in
146          * UDPTL packets and expected in received UDPTL packets.
147          */
148         unsigned int error_correction_entries;
149
150         /*! This option indicates the span of the error correction entries in transmitted
151          * UDPTL packets (FEC only).
152          */
153         unsigned int error_correction_span;
154
155         /*! The maximum size UDPTL packet that can be accepted by
156          * the remote device.
157          */
158         int far_max_datagram;
159
160         /*! The maximum size UDPTL packet that we are prepared to
161          * accept, or -1 if it hasn't been calculated since the last
162          * changes were applied to the UDPTL structure.
163          */
164         int local_max_datagram;
165
166         /*! The maximum IFP that can be submitted for sending
167          * to the remote device. Calculated from far_max_datagram,
168          * error_correction_scheme and error_correction_entries,
169          * or -1 if it hasn't been calculated since the last
170          * changes were applied to the UDPTL structure.
171          */
172         int far_max_ifp;
173
174         /*! The maximum IFP that the local endpoint is prepared
175          * to accept. Along with error_correction_scheme and
176          * error_correction_entries, used to calculate local_max_datagram.
177          */
178         int local_max_ifp;
179
180         unsigned int tx_seq_no;
181         unsigned int rx_seq_no;
182
183         udptl_fec_tx_buffer_t tx[UDPTL_BUF_MASK + 1];
184         udptl_fec_rx_buffer_t rx[UDPTL_BUF_MASK + 1];
185 };
186
187 static AST_RWLIST_HEAD_STATIC(protos, ast_udptl_protocol);
188
189 struct udptl_global_options {
190         unsigned int start; /*< The UDPTL start port */
191         unsigned int end;   /*< The UDPTL end port */
192         unsigned int fecentries;
193         unsigned int fecspan;
194         unsigned int nochecksums;
195         unsigned int use_even_ports;
196 };
197
198 static AO2_GLOBAL_OBJ_STATIC(globals);
199
200 struct udptl_config {
201         struct udptl_global_options *general;
202 };
203
204 static void *udptl_snapshot_alloc(void);
205 static int udptl_pre_apply_config(void);
206
207 static struct aco_type general_option = {
208         .type = ACO_GLOBAL,
209         .category_match = ACO_WHITELIST,
210         .item_offset = offsetof(struct udptl_config, general),
211         .category = "^general$",
212 };
213
214 static struct aco_type *general_options[] = ACO_TYPES(&general_option);
215
216 static struct aco_file udptl_conf = {
217         .filename = "udptl.conf",
218         .types = ACO_TYPES(&general_option),
219 };
220
221 CONFIG_INFO_STANDARD(cfg_info, globals, udptl_snapshot_alloc,
222         .files = ACO_FILES(&udptl_conf),
223         .pre_apply_config = udptl_pre_apply_config,
224 );
225
226 static inline int udptl_debug_test_addr(const struct ast_sockaddr *addr)
227 {
228         if (udptldebug == 0)
229                 return 0;
230
231         if (ast_sockaddr_isnull(&udptldebugaddr)) {
232                 return 1;
233         }
234
235         if (ast_sockaddr_port(&udptldebugaddr)) {
236                 return !ast_sockaddr_cmp(&udptldebugaddr, addr);
237         } else {
238                 return !ast_sockaddr_cmp_addr(&udptldebugaddr, addr);
239         }
240 }
241
242 static int decode_length(uint8_t *buf, unsigned int limit, unsigned int *len, unsigned int *pvalue)
243 {
244         if (*len >= limit)
245                 return -1;
246         if ((buf[*len] & 0x80) == 0) {
247                 *pvalue = buf[*len];
248                 (*len)++;
249                 return 0;
250         }
251         if ((buf[*len] & 0x40) == 0) {
252                 if (*len == limit - 1)
253                         return -1;
254                 *pvalue = (buf[*len] & 0x3F) << 8;
255                 (*len)++;
256                 *pvalue |= buf[*len];
257                 (*len)++;
258                 return 0;
259         }
260         *pvalue = (buf[*len] & 0x3F) << 14;
261         (*len)++;
262         /* We have a fragment.  Currently we don't process fragments. */
263         ast_debug(1, "UDPTL packet with length greater than 16K received, decoding will fail\n");
264         return 1;
265 }
266 /*- End of function --------------------------------------------------------*/
267
268 static int decode_open_type(uint8_t *buf, unsigned int limit, unsigned int *len, const uint8_t **p_object, unsigned int *p_num_octets)
269 {
270         unsigned int octet_cnt = 0;
271
272         if (decode_length(buf, limit, len, &octet_cnt) != 0)
273                 return -1;
274
275         if (octet_cnt > 0) {
276                 /* Make sure the buffer contains at least the number of bits requested */
277                 if ((*len + octet_cnt) > limit)
278                         return -1;
279
280                 *p_num_octets = octet_cnt;
281                 *p_object = &buf[*len];
282                 *len += octet_cnt;
283         }
284
285         return 0;
286 }
287 /*- End of function --------------------------------------------------------*/
288
289 static unsigned int encode_length(uint8_t *buf, unsigned int *len, unsigned int value)
290 {
291         unsigned int multiplier;
292
293         if (value < 0x80) {
294                 /* 1 octet */
295                 buf[*len] = value;
296                 (*len)++;
297                 return value;
298         }
299         if (value < 0x4000) {
300                 /* 2 octets */
301                 /* Set the first bit of the first octet */
302                 buf[*len] = ((0x8000 | value) >> 8) & 0xFF;
303                 (*len)++;
304                 buf[*len] = value & 0xFF;
305                 (*len)++;
306                 return value;
307         }
308         /* Fragmentation */
309         multiplier = (value < 0x10000) ? (value >> 14) : 4;
310         /* Set the first 2 bits of the octet */
311         buf[*len] = 0xC0 | multiplier;
312         (*len)++;
313         return multiplier << 14;
314 }
315 /*- End of function --------------------------------------------------------*/
316
317 static int encode_open_type(const struct ast_udptl *udptl, uint8_t *buf, unsigned int buflen,
318                             unsigned int *len, const uint8_t *data, unsigned int num_octets)
319 {
320         unsigned int enclen;
321         unsigned int octet_idx;
322         uint8_t zero_byte;
323
324         /* If open type is of zero length, add a single zero byte (10.1) */
325         if (num_octets == 0) {
326                 zero_byte = 0;
327                 data = &zero_byte;
328                 num_octets = 1;
329         }
330         /* Encode the open type */
331         for (octet_idx = 0; ; num_octets -= enclen, octet_idx += enclen) {
332                 if ((enclen = encode_length(buf, len, num_octets)) < 0)
333                         return -1;
334                 if (enclen + *len > buflen) {
335                         ast_log(LOG_ERROR, "UDPTL (%s): Buffer overflow detected (%d + %d > %d)\n",
336                                 LOG_TAG(udptl), enclen, *len, buflen);
337                         return -1;
338                 }
339                 if (enclen > 0) {
340                         memcpy(&buf[*len], &data[octet_idx], enclen);
341                         *len += enclen;
342                 }
343                 if (enclen >= num_octets)
344                         break;
345         }
346
347         return 0;
348 }
349 /*- End of function --------------------------------------------------------*/
350
351 static int udptl_rx_packet(struct ast_udptl *s, uint8_t *buf, unsigned int len)
352 {
353         int stat1;
354         int stat2;
355         int i;
356         unsigned int ptr;       /* an index that keeps track of how much of the UDPTL packet has been processed */
357         int seq_no;
358         const uint8_t *ifp = NULL;
359         const uint8_t *data = NULL;
360         unsigned int ifp_len = 0;
361         int repaired[16];
362         const uint8_t *bufs[ARRAY_LEN(s->f) - 1];
363         unsigned int lengths[ARRAY_LEN(s->f) - 1];
364         int span;
365         int entries;
366         int ifp_no;
367
368         ptr = 0;
369         ifp_no = 0;
370         memset(&s->f[0], 0, sizeof(s->f[0]));
371
372         /* Decode seq_number */
373         if (ptr + 2 > len)
374                 return -1;
375         seq_no = (buf[0] << 8) | buf[1];
376         ptr += 2;
377
378         /* Break out the primary packet */
379         if ((stat1 = decode_open_type(buf, len, &ptr, &ifp, &ifp_len)) != 0)
380                 return -1;
381         /* Decode error_recovery */
382         if (ptr + 1 > len)
383                 return -1;
384         if ((buf[ptr++] & 0x80) == 0) {
385                 /* Secondary packet mode for error recovery */
386                 if (seq_no > s->rx_seq_no) {
387                         /* We received a later packet than we expected, so we need to check if we can fill in the gap from the
388                            secondary packets. */
389                         int total_count = 0;
390                         do {
391                                 unsigned int count;
392                                 if ((stat2 = decode_length(buf, len, &ptr, &count)) < 0)
393                                         return -1;
394                                 for (i = 0; i < count && total_count + i < ARRAY_LEN(bufs); i++) {
395                                         if ((stat1 = decode_open_type(buf, len, &ptr, &bufs[total_count + i], &lengths[total_count + i])) != 0) {
396                                                 return -1;
397                                         }
398                                         /* valid secondaries can contain zero-length packets that should be ignored */
399                                         if (!bufs[total_count + i] || !lengths[total_count + i]) {
400                                                 /* drop the count of items to process and reuse the buffers that were just set */
401                                                 i--;
402                                                 count--;
403                                         }
404                                 }
405                                 total_count += i;
406                         }
407                         while (stat2 > 0 && total_count < ARRAY_LEN(bufs));
408                         /* Step through in reverse order, so we go oldest to newest */
409                         for (i = total_count; i > 0; i--) {
410                                 if (seq_no - i >= s->rx_seq_no) {
411                                         /* This one wasn't seen before */
412                                         /* Decode the secondary IFP packet */
413                                         ast_debug(3, "Recovering lost packet via secondary %d, len %d\n", seq_no - i, lengths[i - 1]);
414                                         s->f[ifp_no].frametype = AST_FRAME_MODEM;
415                                         s->f[ifp_no].subclass.integer = AST_MODEM_T38;
416
417                                         s->f[ifp_no].mallocd = 0;
418                                         s->f[ifp_no].seqno = seq_no - i;
419                                         s->f[ifp_no].datalen = lengths[i - 1];
420                                         s->f[ifp_no].data.ptr = (uint8_t *) bufs[i - 1];
421                                         s->f[ifp_no].offset = 0;
422                                         s->f[ifp_no].src = "UDPTL";
423                                         if (ifp_no > 0)
424                                                 AST_LIST_NEXT(&s->f[ifp_no - 1], frame_list) = &s->f[ifp_no];
425                                         AST_LIST_NEXT(&s->f[ifp_no], frame_list) = NULL;
426                                         ifp_no++;
427                                 }
428                         }
429                 }
430         }
431         else
432         {
433                 int j;
434                 int l;
435                 int x;
436                 /* FEC mode for error recovery */
437                 /* Our buffers cannot tolerate overlength IFP packets in FEC mode */
438                 if (ifp_len > LOCAL_FAX_MAX_DATAGRAM)
439                         return -1;
440                 /* Update any missed slots in the buffer */
441                 for ( ; seq_no > s->rx_seq_no; s->rx_seq_no++) {
442                         x = s->rx_seq_no & UDPTL_BUF_MASK;
443                         s->rx[x].buf_len = -1;
444                         s->rx[x].fec_len[0] = 0;
445                         s->rx[x].fec_span = 0;
446                         s->rx[x].fec_entries = 0;
447                 }
448
449                 x = seq_no & UDPTL_BUF_MASK;
450
451                 memset(repaired, 0, sizeof(repaired));
452
453                 /* Save the new IFP packet */
454                 memcpy(s->rx[x].buf, ifp, ifp_len);
455                 s->rx[x].buf_len = ifp_len;
456                 repaired[x] = TRUE;
457
458                 /* Decode the FEC packets */
459                 /* The span is defined as an unconstrained integer, but will never be more
460                    than a small value. */
461                 if (ptr + 2 > len)
462                         return -1;
463                 if (buf[ptr++] != 1)
464                         return -1;
465                 span = buf[ptr++];
466                 s->rx[x].fec_span = span;
467
468                 /* The number of entries is defined as a length, but will only ever be a small
469                    value. Treat it as such. */
470                 if (ptr + 1 > len)
471                         return -1;
472                 entries = buf[ptr++];
473                 if (entries > MAX_FEC_ENTRIES) {
474                         return -1;
475                 }
476                 s->rx[x].fec_entries = entries;
477
478                 /* Decode the elements */
479                 for (i = 0; i < entries; i++) {
480                         if ((stat1 = decode_open_type(buf, len, &ptr, &data, &s->rx[x].fec_len[i])) != 0)
481                                 return -1;
482                         if (s->rx[x].fec_len[i] > LOCAL_FAX_MAX_DATAGRAM)
483                                 return -1;
484
485                         /* Save the new FEC data */
486                         memcpy(s->rx[x].fec[i], data, s->rx[x].fec_len[i]);
487 #if 0
488                         fprintf(stderr, "FEC: ");
489                         for (j = 0; j < s->rx[x].fec_len[i]; j++)
490                                 fprintf(stderr, "%02X ", data[j]);
491                         fprintf(stderr, "\n");
492 #endif
493                 }
494
495                 /* See if we can reconstruct anything which is missing */
496                 /* TODO: this does not comprehensively hunt back and repair everything that is possible */
497                 for (l = x; l != ((x - (16 - span*entries)) & UDPTL_BUF_MASK); l = (l - 1) & UDPTL_BUF_MASK) {
498                         int m;
499                         if (s->rx[l].fec_len[0] <= 0)
500                                 continue;
501                         for (m = 0; m < s->rx[l].fec_entries; m++) {
502                                 int k;
503                                 int which;
504                                 int limit = (l + m) & UDPTL_BUF_MASK;
505                                 for (which = -1, k = (limit - s->rx[l].fec_span * s->rx[l].fec_entries) & UDPTL_BUF_MASK; k != limit; k = (k + s->rx[l].fec_entries) & UDPTL_BUF_MASK) {
506                                         if (s->rx[k].buf_len <= 0)
507                                                 which = (which == -1) ? k : -2;
508                                 }
509                                 if (which >= 0) {
510                                         /* Repairable */
511                                         for (j = 0; j < s->rx[l].fec_len[m]; j++) {
512                                                 s->rx[which].buf[j] = s->rx[l].fec[m][j];
513                                                 for (k = (limit - s->rx[l].fec_span * s->rx[l].fec_entries) & UDPTL_BUF_MASK; k != limit; k = (k + s->rx[l].fec_entries) & UDPTL_BUF_MASK)
514                                                         s->rx[which].buf[j] ^= (s->rx[k].buf_len > j) ? s->rx[k].buf[j] : 0;
515                                         }
516                                         s->rx[which].buf_len = s->rx[l].fec_len[m];
517                                         repaired[which] = TRUE;
518                                 }
519                         }
520                 }
521                 /* Now play any new packets forwards in time */
522                 for (l = (x + 1) & UDPTL_BUF_MASK, j = seq_no - UDPTL_BUF_MASK; l != x; l = (l + 1) & UDPTL_BUF_MASK, j++) {
523                         if (repaired[l]) {
524                                 //fprintf(stderr, "Fixed packet %d, len %d\n", j, l);
525                                 s->f[ifp_no].frametype = AST_FRAME_MODEM;
526                                 s->f[ifp_no].subclass.integer = AST_MODEM_T38;
527
528                                 s->f[ifp_no].mallocd = 0;
529                                 s->f[ifp_no].seqno = j;
530                                 s->f[ifp_no].datalen = s->rx[l].buf_len;
531                                 s->f[ifp_no].data.ptr = s->rx[l].buf;
532                                 s->f[ifp_no].offset = 0;
533                                 s->f[ifp_no].src = "UDPTL";
534                                 if (ifp_no > 0)
535                                         AST_LIST_NEXT(&s->f[ifp_no - 1], frame_list) = &s->f[ifp_no];
536                                 AST_LIST_NEXT(&s->f[ifp_no], frame_list) = NULL;
537                                 ifp_no++;
538                         }
539                 }
540         }
541
542         /* If packets are received out of sequence, we may have already processed this packet from the error
543            recovery information in a packet already received. */
544         if (seq_no >= s->rx_seq_no) {
545                 /* Decode the primary IFP packet */
546                 s->f[ifp_no].frametype = AST_FRAME_MODEM;
547                 s->f[ifp_no].subclass.integer = AST_MODEM_T38;
548
549                 s->f[ifp_no].mallocd = 0;
550                 s->f[ifp_no].seqno = seq_no;
551                 s->f[ifp_no].datalen = ifp_len;
552                 s->f[ifp_no].data.ptr = (uint8_t *) ifp;
553                 s->f[ifp_no].offset = 0;
554                 s->f[ifp_no].src = "UDPTL";
555                 if (ifp_no > 0)
556                         AST_LIST_NEXT(&s->f[ifp_no - 1], frame_list) = &s->f[ifp_no];
557                 AST_LIST_NEXT(&s->f[ifp_no], frame_list) = NULL;
558
559                 ifp_no++;
560         }
561
562         s->rx_seq_no = seq_no + 1;
563         return ifp_no;
564 }
565 /*- End of function --------------------------------------------------------*/
566
567 static int udptl_build_packet(struct ast_udptl *s, uint8_t *buf, unsigned int buflen, uint8_t *ifp, unsigned int ifp_len)
568 {
569         uint8_t fec[LOCAL_FAX_MAX_DATAGRAM * 2] = { 0, };
570         int i;
571         int j;
572         int seq;
573         int entry;
574         int entries;
575         int span;
576         int m;
577         unsigned int len;
578         int limit;
579         int high_tide;
580
581         seq = s->tx_seq_no & 0xFFFF;
582
583         /* Map the sequence number to an entry in the circular buffer */
584         entry = seq & UDPTL_BUF_MASK;
585
586         /* We save the message in a circular buffer, for generating FEC or
587            redundancy sets later on. */
588         s->tx[entry].buf_len = ifp_len;
589         memcpy(s->tx[entry].buf, ifp, ifp_len);
590
591         /* Build the UDPTLPacket */
592
593         len = 0;
594         /* Encode the sequence number */
595         buf[len++] = (seq >> 8) & 0xFF;
596         buf[len++] = seq & 0xFF;
597
598         /* Encode the primary IFP packet */
599         if (encode_open_type(s, buf, buflen, &len, ifp, ifp_len) < 0)
600                 return -1;
601
602         /* Encode the appropriate type of error recovery information */
603         switch (s->error_correction_scheme)
604         {
605         case UDPTL_ERROR_CORRECTION_NONE:
606                 /* Encode the error recovery type */
607                 buf[len++] = 0x00;
608                 /* The number of entries will always be zero, so it is pointless allowing
609                    for the fragmented case here. */
610                 if (encode_length(buf, &len, 0) < 0)
611                         return -1;
612                 break;
613         case UDPTL_ERROR_CORRECTION_REDUNDANCY:
614                 /* Encode the error recovery type */
615                 buf[len++] = 0x00;
616                 if (s->tx_seq_no > s->error_correction_entries)
617                         entries = s->error_correction_entries;
618                 else
619                         entries = s->tx_seq_no;
620                 /* The number of entries will always be small, so it is pointless allowing
621                    for the fragmented case here. */
622                 if (encode_length(buf, &len, entries) < 0)
623                         return -1;
624                 /* Encode the elements */
625                 for (i = 0; i < entries; i++) {
626                         j = (entry - i - 1) & UDPTL_BUF_MASK;
627                         if (encode_open_type(s, buf, buflen, &len, s->tx[j].buf, s->tx[j].buf_len) < 0) {
628                                 ast_debug(1, "UDPTL (%s): Encoding failed at i=%d, j=%d\n",
629                                           LOG_TAG(s), i, j);
630                                 return -1;
631                         }
632                 }
633                 break;
634         case UDPTL_ERROR_CORRECTION_FEC:
635                 span = s->error_correction_span;
636                 entries = s->error_correction_entries;
637                 if (seq < s->error_correction_span*s->error_correction_entries) {
638                         /* In the initial stages, wind up the FEC smoothly */
639                         entries = seq/s->error_correction_span;
640                         if (seq < s->error_correction_span)
641                                 span = 0;
642                 }
643                 /* Encode the error recovery type */
644                 buf[len++] = 0x80;
645                 /* Span is defined as an inconstrained integer, which it dumb. It will only
646                    ever be a small value. Treat it as such. */
647                 buf[len++] = 1;
648                 buf[len++] = span;
649                 /* The number of entries is defined as a length, but will only ever be a small
650                    value. Treat it as such. */
651                 buf[len++] = entries;
652                 for (m = 0; m < entries; m++) {
653                         /* Make an XOR'ed entry the maximum length */
654                         limit = (entry + m) & UDPTL_BUF_MASK;
655                         high_tide = 0;
656                         for (i = (limit - span*entries) & UDPTL_BUF_MASK; i != limit; i = (i + entries) & UDPTL_BUF_MASK) {
657                                 if (high_tide < s->tx[i].buf_len) {
658                                         for (j = 0; j < high_tide; j++)
659                                                 fec[j] ^= s->tx[i].buf[j];
660                                         for ( ; j < s->tx[i].buf_len; j++)
661                                                 fec[j] = s->tx[i].buf[j];
662                                         high_tide = s->tx[i].buf_len;
663                                 } else {
664                                         for (j = 0; j < s->tx[i].buf_len; j++)
665                                                 fec[j] ^= s->tx[i].buf[j];
666                                 }
667                         }
668                         if (encode_open_type(s, buf, buflen, &len, fec, high_tide) < 0)
669                                 return -1;
670                 }
671                 break;
672         }
673
674         s->tx_seq_no++;
675         return len;
676 }
677
678 int ast_udptl_fd(const struct ast_udptl *udptl)
679 {
680         return udptl->fd;
681 }
682
683 void ast_udptl_set_data(struct ast_udptl *udptl, void *data)
684 {
685         udptl->data = data;
686 }
687
688 void ast_udptl_set_callback(struct ast_udptl *udptl, ast_udptl_callback callback)
689 {
690         udptl->callback = callback;
691 }
692
693 void ast_udptl_setnat(struct ast_udptl *udptl, int nat)
694 {
695         udptl->nat = nat;
696 }
697
698 static int udptlread(int *id, int fd, short events, void *cbdata)
699 {
700         struct ast_udptl *udptl = cbdata;
701         struct ast_frame *f;
702
703         if ((f = ast_udptl_read(udptl))) {
704                 if (udptl->callback)
705                         udptl->callback(udptl, f, udptl->data);
706         }
707         return 1;
708 }
709
710 struct ast_frame *ast_udptl_read(struct ast_udptl *udptl)
711 {
712         int res;
713         struct ast_sockaddr addr;
714         uint8_t *buf;
715
716         buf = udptl->rawdata + AST_FRIENDLY_OFFSET;
717
718         /* Cache where the header will go */
719         res = ast_recvfrom(udptl->fd,
720                         buf,
721                         sizeof(udptl->rawdata) - AST_FRIENDLY_OFFSET,
722                         0,
723                         &addr);
724         if (res < 0) {
725                 if (errno != EAGAIN)
726                         ast_log(LOG_WARNING, "UDPTL (%s): read error: %s\n",
727                                 LOG_TAG(udptl), strerror(errno));
728                 ast_assert(errno != EBADF);
729                 return &ast_null_frame;
730         }
731
732         /* Ignore if the other side hasn't been given an address yet. */
733         if (ast_sockaddr_isnull(&udptl->them)) {
734                 return &ast_null_frame;
735         }
736
737         if (udptl->nat) {
738                 /* Send to whoever sent to us */
739                 if (ast_sockaddr_cmp(&udptl->them, &addr)) {
740                         ast_sockaddr_copy(&udptl->them, &addr);
741                         ast_debug(1, "UDPTL (%s): NAT, Using address %s\n",
742                                   LOG_TAG(udptl), ast_sockaddr_stringify(&udptl->them));
743                 }
744         }
745
746         if (udptl_debug_test_addr(&addr)) {
747                 int seq_no;
748
749                 /* Decode sequence number just for verbose message. */
750                 if (res < 2) {
751                         /* Short packet. */
752                         seq_no = -1;
753                 } else {
754                         seq_no = (buf[0] << 8) | buf[1];
755                 }
756
757                 ast_verb(1, "UDPTL (%s): packet from %s (seq %d, len %d)\n",
758                         LOG_TAG(udptl), ast_sockaddr_stringify(&addr), seq_no, res);
759         }
760         if (udptl_rx_packet(udptl, buf, res) < 1) {
761                 return &ast_null_frame;
762         }
763
764         return &udptl->f[0];
765 }
766
767 static void calculate_local_max_datagram(struct ast_udptl *udptl)
768 {
769         unsigned int new_max = 0;
770
771         if (udptl->local_max_ifp == -1) {
772                 ast_log(LOG_WARNING, "UDPTL (%s): Cannot calculate local_max_datagram before local_max_ifp has been set.\n",
773                         LOG_TAG(udptl));
774                 udptl->local_max_datagram = -1;
775                 return;
776         }
777
778         /* calculate the amount of space required to receive an IFP
779          * of the maximum size supported by the application/endpoint
780          * that we are delivering them to (local endpoint), and add
781          * the amount of space required to support the selected
782          * error correction mode
783          */
784         switch (udptl->error_correction_scheme) {
785         case UDPTL_ERROR_CORRECTION_NONE:
786                 /* need room for sequence number, length indicator, redundancy
787                  * indicator and following length indicator
788                  */
789                 new_max = 5 + udptl->local_max_ifp;
790                 break;
791         case UDPTL_ERROR_CORRECTION_REDUNDANCY:
792                 /* need room for sequence number, length indicators, plus
793                  * room for up to 3 redundancy packets
794                  */
795                 new_max = 5 + udptl->local_max_ifp + 2 + (3 * udptl->local_max_ifp);
796                 break;
797         case UDPTL_ERROR_CORRECTION_FEC:
798                 /* need room for sequence number, length indicators and a
799                  * a single IFP of the maximum size expected
800                  */
801                 new_max = 5 + udptl->local_max_ifp + 4 + udptl->local_max_ifp;
802                 break;
803         }
804         /* add 5% extra space for insurance, but no larger than LOCAL_FAX_MAX_DATAGRAM */
805         udptl->local_max_datagram = MIN(new_max * 1.05, LOCAL_FAX_MAX_DATAGRAM);
806 }
807
808 static void calculate_far_max_ifp(struct ast_udptl *udptl)
809 {
810         unsigned new_max = 0;
811
812         if (udptl->far_max_datagram == -1) {
813                 ast_log(LOG_WARNING, "UDPTL (%s): Cannot calculate far_max_ifp before far_max_datagram has been set.\n",
814                         LOG_TAG(udptl));
815                 udptl->far_max_ifp = -1;
816                 return;
817         }
818
819         /* the goal here is to supply the local endpoint (application
820          * or bridged channel) a maximum IFP value that will allow it
821          * to effectively and efficiently transfer image data at its
822          * selected bit rate, taking into account the selected error
823          * correction mode, but without overrunning the far endpoint's
824          * datagram buffer. this is complicated by the fact that some
825          * far endpoints send us bogus (small) max datagram values,
826          * which would result in either buffer overrun or no error
827          * correction. we try to accomodate those, but if the supplied
828          * value is too small to do so, we'll emit warning messages and
829          * the user will have to use configuration options to override
830          * the max datagram value supplied by the far endpoint.
831          */
832         switch (udptl->error_correction_scheme) {
833         case UDPTL_ERROR_CORRECTION_NONE:
834                 /* need room for sequence number, length indicator, redundancy
835                  * indicator and following length indicator
836                  */
837                 new_max = udptl->far_max_datagram - 5;
838                 break;
839         case UDPTL_ERROR_CORRECTION_REDUNDANCY:
840                 /* for this case, we'd like to send as many error correction entries
841                  * as possible (up to the number we're configured for), but we'll settle
842                  * for sending fewer if the configured number would cause the
843                  * calculated max IFP to be too small for effective operation
844                  *
845                  * need room for sequence number, length indicators and the
846                  * configured number of redundant packets
847                  *
848                  * note: we purposely don't allow error_correction_entries to drop to
849                  * zero in this loop; we'd rather send smaller IFPs (and thus reduce
850                  * the image data transfer rate) than sacrifice redundancy completely
851                  */
852                 for (;;) {
853                         new_max = (udptl->far_max_datagram - 8) / (udptl->error_correction_entries + 1);
854
855                         if ((new_max < 80) && (udptl->error_correction_entries > 1)) {
856                                 /* the max ifp is not large enough, subtract an
857                                  * error correction entry and calculate again
858                                  * */
859                                 --udptl->error_correction_entries;
860                         } else {
861                                 break;
862                         }
863                 }
864                 break;
865         case UDPTL_ERROR_CORRECTION_FEC:
866                 /* need room for sequence number, length indicators and a
867                  * a single IFP of the maximum size expected
868                  */
869                 new_max = (udptl->far_max_datagram - 10) / 2;
870                 break;
871         }
872         /* subtract 5% of space for insurance */
873         udptl->far_max_ifp = new_max * 0.95;
874 }
875
876 enum ast_t38_ec_modes ast_udptl_get_error_correction_scheme(const struct ast_udptl *udptl)
877 {
878         return udptl->error_correction_scheme;
879 }
880
881 void ast_udptl_set_error_correction_scheme(struct ast_udptl *udptl, enum ast_t38_ec_modes ec)
882 {
883         udptl->error_correction_scheme = ec;
884         switch (ec) {
885         case UDPTL_ERROR_CORRECTION_FEC:
886                 udptl->error_correction_scheme = UDPTL_ERROR_CORRECTION_FEC;
887                 if (udptl->error_correction_entries == 0) {
888                         udptl->error_correction_entries = 3;
889                 }
890                 if (udptl->error_correction_span == 0) {
891                         udptl->error_correction_span = 3;
892                 }
893                 break;
894         case UDPTL_ERROR_CORRECTION_REDUNDANCY:
895                 udptl->error_correction_scheme = UDPTL_ERROR_CORRECTION_REDUNDANCY;
896                 if (udptl->error_correction_entries == 0) {
897                         udptl->error_correction_entries = 3;
898                 }
899                 break;
900         default:
901                 /* nothing to do */
902                 break;
903         };
904         /* reset calculated values so they'll be computed again */
905         udptl->local_max_datagram = -1;
906         udptl->far_max_ifp = -1;
907 }
908
909 void ast_udptl_set_local_max_ifp(struct ast_udptl *udptl, unsigned int max_ifp)
910 {
911         /* make sure max_ifp is a positive value since a cast will take place when
912          * when setting local_max_ifp */
913         if ((signed int) max_ifp > 0) {
914                 udptl->local_max_ifp = max_ifp;
915                 /* reset calculated values so they'll be computed again */
916                 udptl->local_max_datagram = -1;
917         }
918 }
919
920 unsigned int ast_udptl_get_local_max_datagram(struct ast_udptl *udptl)
921 {
922         if (udptl->local_max_datagram == -1) {
923                 calculate_local_max_datagram(udptl);
924         }
925
926         /* this function expects a unsigned value in return. */
927         if (udptl->local_max_datagram < 0) {
928                 return 0;
929         }
930         return udptl->local_max_datagram;
931 }
932
933 void ast_udptl_set_far_max_datagram(struct ast_udptl *udptl, unsigned int max_datagram)
934 {
935         if (!max_datagram || (max_datagram > FAX_MAX_DATAGRAM_LIMIT)) {
936                 udptl->far_max_datagram = DEFAULT_FAX_MAX_DATAGRAM;
937         } else {
938                 udptl->far_max_datagram = max_datagram;
939         }
940         /* reset calculated values so they'll be computed again */
941         udptl->far_max_ifp = -1;
942 }
943
944 unsigned int ast_udptl_get_far_max_datagram(const struct ast_udptl *udptl)
945 {
946         if (udptl->far_max_datagram < 0) {
947                 return 0;
948         }
949         return udptl->far_max_datagram;
950 }
951
952 unsigned int ast_udptl_get_far_max_ifp(struct ast_udptl *udptl)
953 {
954         if (udptl->far_max_ifp == -1) {
955                 calculate_far_max_ifp(udptl);
956         }
957
958         if (udptl->far_max_ifp < 0) {
959                 return 0;
960         }
961         return udptl->far_max_ifp;
962 }
963
964 struct ast_udptl *ast_udptl_new_with_bindaddr(struct ast_sched_context *sched, struct io_context *io, int callbackmode, struct ast_sockaddr *addr)
965 {
966         struct ast_udptl *udptl;
967         int x;
968         int startplace;
969         int i;
970         long int flags;
971         RAII_VAR(struct udptl_config *, cfg, ao2_global_obj_ref(globals), ao2_cleanup);
972
973         if (!cfg || !cfg->general) {
974                 ast_log(LOG_ERROR, "Could not access global udptl options!\n");
975                 return NULL;
976         }
977
978         if (!(udptl = ast_calloc(1, sizeof(*udptl)))) {
979                 return NULL;
980         }
981
982         udptl->error_correction_span = cfg->general->fecspan;
983         udptl->error_correction_entries = cfg->general->fecentries;
984
985         udptl->far_max_datagram = -1;
986         udptl->far_max_ifp = -1;
987         udptl->local_max_ifp = -1;
988         udptl->local_max_datagram = -1;
989
990         for (i = 0; i <= UDPTL_BUF_MASK; i++) {
991                 udptl->rx[i].buf_len = -1;
992                 udptl->tx[i].buf_len = -1;
993         }
994
995         if ((udptl->fd = socket(ast_sockaddr_is_ipv6(addr) ?
996                                         AF_INET6 : AF_INET, SOCK_DGRAM, 0)) < 0) {
997                 ast_free(udptl);
998                 ast_log(LOG_WARNING, "Unable to allocate socket: %s\n", strerror(errno));
999                 return NULL;
1000         }
1001         flags = fcntl(udptl->fd, F_GETFL);
1002         fcntl(udptl->fd, F_SETFL, flags | O_NONBLOCK);
1003
1004 #ifdef SO_NO_CHECK
1005         if (cfg->general->nochecksums)
1006                 setsockopt(udptl->fd, SOL_SOCKET, SO_NO_CHECK, &cfg->general->nochecksums, sizeof(cfg->general->nochecksums));
1007 #endif
1008
1009         /* Find us a place */
1010         x = (cfg->general->start == cfg->general->end) ? cfg->general->start : (ast_random() % (cfg->general->end - cfg->general->start)) + cfg->general->start;
1011         if (cfg->general->use_even_ports && (x & 1)) {
1012                 ++x;
1013         }
1014         startplace = x;
1015         for (;;) {
1016                 ast_sockaddr_copy(&udptl->us, addr);
1017                 ast_sockaddr_set_port(&udptl->us, x);
1018                 if (ast_bind(udptl->fd, &udptl->us) == 0) {
1019                         break;
1020                 }
1021                 if (errno != EADDRINUSE) {
1022                         ast_log(LOG_WARNING, "Unexpected bind error: %s\n", strerror(errno));
1023                         close(udptl->fd);
1024                         ast_free(udptl);
1025                         return NULL;
1026                 }
1027                 if (cfg->general->use_even_ports) {
1028                         x += 2;
1029                 } else {
1030                         ++x;
1031                 }
1032                 if (x > cfg->general->end)
1033                         x = cfg->general->start;
1034                 if (x == startplace) {
1035                         ast_log(LOG_WARNING, "No UDPTL ports remaining\n");
1036                         close(udptl->fd);
1037                         ast_free(udptl);
1038                         return NULL;
1039                 }
1040         }
1041         if (io && sched && callbackmode) {
1042                 /* Operate this one in a callback mode */
1043                 udptl->sched = sched;
1044                 udptl->io = io;
1045                 udptl->ioid = ast_io_add(udptl->io, udptl->fd, udptlread, AST_IO_IN, udptl);
1046         }
1047
1048         return udptl;
1049 }
1050
1051 void ast_udptl_set_tag(struct ast_udptl *udptl, const char *format, ...)
1052 {
1053         va_list ap;
1054
1055         ast_free(udptl->tag);
1056         udptl->tag = NULL;
1057         va_start(ap, format);
1058         if (ast_vasprintf(&udptl->tag, format, ap) == -1) {
1059                 udptl->tag = NULL;
1060         }
1061         va_end(ap);
1062 }
1063
1064 int ast_udptl_setqos(struct ast_udptl *udptl, unsigned int tos, unsigned int cos)
1065 {
1066         return ast_set_qos(udptl->fd, tos, cos, "UDPTL");
1067 }
1068
1069 void ast_udptl_set_peer(struct ast_udptl *udptl, const struct ast_sockaddr *them)
1070 {
1071         ast_sockaddr_copy(&udptl->them, them);
1072 }
1073
1074 void ast_udptl_get_peer(const struct ast_udptl *udptl, struct ast_sockaddr *them)
1075 {
1076         ast_sockaddr_copy(them, &udptl->them);
1077 }
1078
1079 void ast_udptl_get_us(const struct ast_udptl *udptl, struct ast_sockaddr *us)
1080 {
1081         ast_sockaddr_copy(us, &udptl->us);
1082 }
1083
1084 void ast_udptl_stop(struct ast_udptl *udptl)
1085 {
1086         ast_sockaddr_setnull(&udptl->them);
1087 }
1088
1089 void ast_udptl_destroy(struct ast_udptl *udptl)
1090 {
1091         if (udptl->ioid)
1092                 ast_io_remove(udptl->io, udptl->ioid);
1093         if (udptl->fd > -1)
1094                 close(udptl->fd);
1095         if (udptl->tag)
1096                 ast_free(udptl->tag);
1097         ast_free(udptl);
1098 }
1099
1100 int ast_udptl_write(struct ast_udptl *s, struct ast_frame *f)
1101 {
1102         unsigned int seq;
1103         unsigned int len = f->datalen;
1104         /* if no max datagram size is provided, use default value */
1105         const int bufsize = (s->far_max_datagram > 0) ? s->far_max_datagram : DEFAULT_FAX_MAX_DATAGRAM;
1106         uint8_t buf[bufsize];
1107
1108         memset(buf, 0, sizeof(buf));
1109
1110         /* If we have no peer, return immediately */
1111         if (ast_sockaddr_isnull(&s->them)) {
1112                 return 0;
1113         }
1114
1115         /* If there is no data length, return immediately */
1116         if (f->datalen == 0)
1117                 return 0;
1118
1119         if ((f->frametype != AST_FRAME_MODEM) ||
1120             (f->subclass.integer != AST_MODEM_T38)) {
1121                 ast_log(LOG_WARNING, "UDPTL (%s): UDPTL can only send T.38 data.\n",
1122                         LOG_TAG(s));
1123                 return -1;
1124         }
1125
1126         if (len > s->far_max_ifp) {
1127                 ast_log(LOG_WARNING,
1128                         "UDPTL (%s): UDPTL asked to send %d bytes of IFP when far end only prepared to accept %d bytes; data loss will occur."
1129                         "You may need to override the T38FaxMaxDatagram value for this endpoint in the channel driver configuration.\n",
1130                         LOG_TAG(s), len, s->far_max_ifp);
1131                 len = s->far_max_ifp;
1132         }
1133
1134         /* Save seq_no for debug output because udptl_build_packet increments it */
1135         seq = s->tx_seq_no & 0xFFFF;
1136
1137         /* Cook up the UDPTL packet, with the relevant EC info. */
1138         len = udptl_build_packet(s, buf, sizeof(buf), f->data.ptr, len);
1139
1140         if ((signed int) len > 0 && !ast_sockaddr_isnull(&s->them)) {
1141                 if (ast_sendto(s->fd, buf, len, 0, &s->them) < 0) {
1142                         ast_log(LOG_NOTICE, "UDPTL (%s): Transmission error to %s: %s\n",
1143                                 LOG_TAG(s), ast_sockaddr_stringify(&s->them), strerror(errno));
1144                 }
1145                 if (udptl_debug_test_addr(&s->them)) {
1146                         ast_verb(1, "UDPTL (%s): packet to %s (seq %d, len %d)\n",
1147                                 LOG_TAG(s), ast_sockaddr_stringify(&s->them), seq, len);
1148                 }
1149         }
1150
1151         return 0;
1152 }
1153
1154 void ast_udptl_proto_unregister(struct ast_udptl_protocol *proto)
1155 {
1156         AST_RWLIST_WRLOCK(&protos);
1157         AST_RWLIST_REMOVE(&protos, proto, list);
1158         AST_RWLIST_UNLOCK(&protos);
1159 }
1160
1161 int ast_udptl_proto_register(struct ast_udptl_protocol *proto)
1162 {
1163         struct ast_udptl_protocol *cur;
1164
1165         AST_RWLIST_WRLOCK(&protos);
1166         AST_RWLIST_TRAVERSE(&protos, cur, list) {
1167                 if (cur->type == proto->type) {
1168                         ast_log(LOG_WARNING, "Tried to register same protocol '%s' twice\n", cur->type);
1169                         AST_RWLIST_UNLOCK(&protos);
1170                         return -1;
1171                 }
1172         }
1173         AST_RWLIST_INSERT_TAIL(&protos, proto, list);
1174         AST_RWLIST_UNLOCK(&protos);
1175         return 0;
1176 }
1177
1178 static struct ast_udptl_protocol *get_proto(struct ast_channel *chan)
1179 {
1180         struct ast_udptl_protocol *cur = NULL;
1181
1182         AST_RWLIST_RDLOCK(&protos);
1183         AST_RWLIST_TRAVERSE(&protos, cur, list) {
1184                 if (cur->type == ast_channel_tech(chan)->type)
1185                         break;
1186         }
1187         AST_RWLIST_UNLOCK(&protos);
1188
1189         return cur;
1190 }
1191
1192 int ast_udptl_bridge(struct ast_channel *c0, struct ast_channel *c1, int flags, struct ast_frame **fo, struct ast_channel **rc)
1193 {
1194         struct ast_frame *f;
1195         struct ast_channel *who;
1196         struct ast_channel *cs[3];
1197         struct ast_udptl *p0;
1198         struct ast_udptl *p1;
1199         struct ast_udptl_protocol *pr0;
1200         struct ast_udptl_protocol *pr1;
1201         struct ast_sockaddr ac0;
1202         struct ast_sockaddr ac1;
1203         struct ast_sockaddr t0;
1204         struct ast_sockaddr t1;
1205         void *pvt0;
1206         void *pvt1;
1207         int to;
1208
1209         ast_channel_lock(c0);
1210         while (ast_channel_trylock(c1)) {
1211                 ast_channel_unlock(c0);
1212                 usleep(1);
1213                 ast_channel_lock(c0);
1214         }
1215         pr0 = get_proto(c0);
1216         pr1 = get_proto(c1);
1217         if (!pr0) {
1218                 ast_log(LOG_WARNING, "Can't find native functions for channel '%s'\n", ast_channel_name(c0));
1219                 ast_channel_unlock(c0);
1220                 ast_channel_unlock(c1);
1221                 return -1;
1222         }
1223         if (!pr1) {
1224                 ast_log(LOG_WARNING, "Can't find native functions for channel '%s'\n", ast_channel_name(c1));
1225                 ast_channel_unlock(c0);
1226                 ast_channel_unlock(c1);
1227                 return -1;
1228         }
1229         pvt0 = ast_channel_tech_pvt(c0);
1230         pvt1 = ast_channel_tech_pvt(c1);
1231         p0 = pr0->get_udptl_info(c0);
1232         p1 = pr1->get_udptl_info(c1);
1233         if (!p0 || !p1) {
1234                 /* Somebody doesn't want to play... */
1235                 ast_channel_unlock(c0);
1236                 ast_channel_unlock(c1);
1237                 return -2;
1238         }
1239         if (pr0->set_udptl_peer(c0, p1)) {
1240                 ast_log(LOG_WARNING, "Channel '%s' failed to talk to '%s'\n", ast_channel_name(c0), ast_channel_name(c1));
1241                 memset(&ac1, 0, sizeof(ac1));
1242         } else {
1243                 /* Store UDPTL peer */
1244                 ast_udptl_get_peer(p1, &ac1);
1245         }
1246         if (pr1->set_udptl_peer(c1, p0)) {
1247                 ast_log(LOG_WARNING, "Channel '%s' failed to talk back to '%s'\n", ast_channel_name(c1), ast_channel_name(c0));
1248                 memset(&ac0, 0, sizeof(ac0));
1249         } else {
1250                 /* Store UDPTL peer */
1251                 ast_udptl_get_peer(p0, &ac0);
1252         }
1253         ast_channel_unlock(c0);
1254         ast_channel_unlock(c1);
1255         cs[0] = c0;
1256         cs[1] = c1;
1257         cs[2] = NULL;
1258         for (;;) {
1259                 if ((ast_channel_tech_pvt(c0) != pvt0) ||
1260                         (ast_channel_tech_pvt(c1) != pvt1) ||
1261                         (ast_channel_masq(c0) || ast_channel_masqr(c0) || ast_channel_masq(c1) || ast_channel_masqr(c1))) {
1262                                 ast_debug(1, "Oooh, something is weird, backing out\n");
1263                                 /* Tell it to try again later */
1264                                 return -3;
1265                 }
1266                 to = -1;
1267                 ast_udptl_get_peer(p1, &t1);
1268                 ast_udptl_get_peer(p0, &t0);
1269                 if (ast_sockaddr_cmp(&t1, &ac1)) {
1270                         ast_debug(1, "Oooh, '%s' changed end address to %s\n",
1271                                 ast_channel_name(c1), ast_sockaddr_stringify(&t1));
1272                         ast_debug(1, "Oooh, '%s' was %s\n",
1273                                 ast_channel_name(c1), ast_sockaddr_stringify(&ac1));
1274                         ast_sockaddr_copy(&ac1, &t1);
1275                 }
1276                 if (ast_sockaddr_cmp(&t0, &ac0)) {
1277                         ast_debug(1, "Oooh, '%s' changed end address to %s\n",
1278                                 ast_channel_name(c0), ast_sockaddr_stringify(&t0));
1279                         ast_debug(1, "Oooh, '%s' was %s\n",
1280                                 ast_channel_name(c0), ast_sockaddr_stringify(&ac0));
1281                         ast_sockaddr_copy(&ac0, &t0);
1282                 }
1283                 who = ast_waitfor_n(cs, 2, &to);
1284                 if (!who) {
1285                         ast_debug(1, "Ooh, empty read...\n");
1286                         /* check for hangup / whentohangup */
1287                         if (ast_check_hangup(c0) || ast_check_hangup(c1))
1288                                 break;
1289                         continue;
1290                 }
1291                 f = ast_read(who);
1292                 if (!f) {
1293                         *fo = f;
1294                         *rc = who;
1295                         ast_debug(1, "Oooh, got a %s\n", f ? "digit" : "hangup");
1296                         /* That's all we needed */
1297                         return 0;
1298                 } else {
1299                         if (f->frametype == AST_FRAME_MODEM) {
1300                                 /* Forward T.38 frames if they happen upon us */
1301                                 if (who == c0) {
1302                                         ast_write(c1, f);
1303                                 } else if (who == c1) {
1304                                         ast_write(c0, f);
1305                                 }
1306                         }
1307                         ast_frfree(f);
1308                 }
1309                 /* Swap priority. Not that it's a big deal at this point */
1310                 cs[2] = cs[0];
1311                 cs[0] = cs[1];
1312                 cs[1] = cs[2];
1313         }
1314         return -1;
1315 }
1316
1317 static char *handle_cli_udptl_set_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1318 {
1319         switch (cmd) {
1320         case CLI_INIT:
1321                 e->command = "udptl set debug {on|off|ip}";
1322                 e->usage =
1323                         "Usage: udptl set debug {on|off|ip host[:port]}\n"
1324                         "       Enable or disable dumping of UDPTL packets.\n"
1325                         "       If ip is specified, limit the dumped packets to those to and from\n"
1326                         "       the specified 'host' with optional port.\n";
1327                 return NULL;
1328         case CLI_GENERATE:
1329                 return NULL;
1330         }
1331
1332         if (a->argc < 4 || a->argc > 5)
1333                 return CLI_SHOWUSAGE;
1334
1335         if (a->argc == 4) {
1336                 if (!strncasecmp(a->argv[3], "on", 2)) {
1337                         udptldebug = 1;
1338                         memset(&udptldebugaddr, 0, sizeof(udptldebugaddr));
1339                         ast_cli(a->fd, "UDPTL Debugging Enabled\n");
1340                 } else if (!strncasecmp(a->argv[3], "off", 3)) {
1341                         udptldebug = 0;
1342                         ast_cli(a->fd, "UDPTL Debugging Disabled\n");
1343                 } else {
1344                         return CLI_SHOWUSAGE;
1345                 }
1346         } else {
1347                 struct ast_sockaddr *addrs;
1348                 if (strncasecmp(a->argv[3], "ip", 2))
1349                         return CLI_SHOWUSAGE;
1350                 if (!ast_sockaddr_resolve(&addrs, a->argv[4], 0, 0)) {
1351                         return CLI_SHOWUSAGE;
1352                 }
1353                 ast_sockaddr_copy(&udptldebugaddr, &addrs[0]);
1354                         ast_cli(a->fd, "UDPTL Debugging Enabled for IP: %s\n", ast_sockaddr_stringify(&udptldebugaddr));
1355                 udptldebug = 1;
1356                 ast_free(addrs);
1357         }
1358
1359         return CLI_SUCCESS;
1360 }
1361
1362 static char *handle_cli_show_config(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1363 {
1364         RAII_VAR(struct udptl_config *, cfg, NULL, ao2_cleanup);
1365
1366         switch (cmd) {
1367         case CLI_INIT:
1368                 e->command = "udptl show config";
1369                 e->usage =
1370                         "Usage: udptl show config\n"
1371                         "       Display UDPTL configuration options\n";
1372                 return NULL;
1373         case CLI_GENERATE:
1374                 return NULL;
1375         }
1376
1377         if (!(cfg = ao2_global_obj_ref(globals))) {
1378                 return CLI_FAILURE;
1379         }
1380
1381         ast_cli(a->fd, "UDPTL Global options\n");
1382         ast_cli(a->fd, "--------------------\n");
1383         ast_cli(a->fd, "udptlstart:      %u\n", cfg->general->start);
1384         ast_cli(a->fd, "udptlend:        %u\n", cfg->general->end);
1385         ast_cli(a->fd, "udptlfecentries: %u\n", cfg->general->fecentries);
1386         ast_cli(a->fd, "udptlfecspan:    %u\n", cfg->general->fecspan);
1387         ast_cli(a->fd, "use_even_ports:  %s\n", AST_CLI_YESNO(cfg->general->use_even_ports));
1388         ast_cli(a->fd, "udptlchecksums: %s\n", AST_CLI_YESNO(!cfg->general->nochecksums));
1389
1390         return CLI_SUCCESS;
1391 }
1392
1393 static struct ast_cli_entry cli_udptl[] = {
1394         AST_CLI_DEFINE(handle_cli_udptl_set_debug, "Enable/Disable UDPTL debugging"),
1395         AST_CLI_DEFINE(handle_cli_show_config, "Show UDPTL config options"),
1396 };
1397
1398 static void udptl_config_destructor(void *obj)
1399 {
1400         struct udptl_config *cfg = obj;
1401         ao2_cleanup(cfg->general);
1402 }
1403
1404 static void *udptl_snapshot_alloc(void)
1405 {
1406         struct udptl_config *cfg;
1407
1408         if (!(cfg = ao2_alloc(sizeof(*cfg), udptl_config_destructor))) {
1409                 return NULL;
1410         }
1411         if (!(cfg->general = ao2_alloc(sizeof(*cfg->general), NULL))) {
1412                 ao2_ref(cfg, -1);
1413                 return NULL;
1414         }
1415
1416         return cfg;
1417 }
1418
1419 static int removed_options_handler(const struct aco_option *opt, struct ast_variable *var, void *obj)
1420 {
1421         if (!strcasecmp(var->name, "t38faxudpec")) {
1422                 ast_log(LOG_WARNING, "t38faxudpec in udptl.conf is no longer supported; use the t38pt_udptl configuration option in sip.conf instead.\n");
1423         } else if (!strcasecmp(var->name, "t38faxmaxdatagram")) {
1424                 ast_log(LOG_WARNING, "t38faxmaxdatagram in udptl.conf is no longer supported; value is now supplied by T.38 applications.\n");
1425         }
1426         return 0;
1427 }
1428
1429 static void __ast_udptl_reload(int reload)
1430 {
1431         if (aco_process_config(&cfg_info, reload) == ACO_PROCESS_ERROR) {
1432                 ast_log(LOG_WARNING, "Could not reload udptl config\n");
1433         }
1434 }
1435
1436 static int udptl_pre_apply_config(void) {
1437         struct udptl_config *cfg = aco_pending_config(&cfg_info);
1438
1439         if (!cfg->general) {
1440                 return -1;
1441         }
1442
1443 #ifndef SO_NO_CHECK
1444         if (cfg->general->nochecksums) {
1445                 ast_log(LOG_WARNING, "Disabling UDPTL checksums is not supported on this operating system!\n");
1446                 cfg->general->nochecksums = 0;
1447         }
1448 #endif
1449
1450         /* Fix up any global config values that we can handle before replacing the config */
1451         if (cfg->general->use_even_ports && (cfg->general->start & 1)) {
1452                 ++cfg->general->start;
1453                 ast_log(LOG_NOTICE, "Odd numbered udptlstart specified but use_even_ports enabled. udptlstart is now %d\n", cfg->general->start);
1454         }
1455         if (cfg->general->start > cfg->general->end) {
1456                 ast_log(LOG_WARNING, "Unreasonable values for UDPTL start/end ports; defaulting to %s-%s.\n", __stringify(DEFAULT_UDPTLSTART), __stringify(DEFAULT_UDPTLEND));
1457                 cfg->general->start = DEFAULT_UDPTLSTART;
1458                 cfg->general->end = DEFAULT_UDPTLEND;
1459         }
1460         if (cfg->general->use_even_ports && (cfg->general->end & 1)) {
1461                 --cfg->general->end;
1462                 ast_log(LOG_NOTICE, "Odd numbered udptlend specified but use_even_ports enabled. udptlend is now %d\n", cfg->general->end);
1463         }
1464
1465         return 0;
1466 }
1467
1468 int ast_udptl_reload(void)
1469 {
1470         __ast_udptl_reload(1);
1471         return 0;
1472 }
1473
1474 /*!
1475  * \internal
1476  * \brief Clean up resources on Asterisk shutdown
1477  */
1478 static void udptl_shutdown(void)
1479 {
1480         ast_cli_unregister_multiple(cli_udptl, ARRAY_LEN(cli_udptl));
1481         ao2_t_global_obj_release(globals, "Unref udptl global container in shutdown");
1482         aco_info_destroy(&cfg_info);
1483 }
1484
1485 void ast_udptl_init(void)
1486 {
1487         if (aco_info_init(&cfg_info)) {
1488                 return;
1489         }
1490
1491         aco_option_register(&cfg_info, "udptlstart", ACO_EXACT, general_options, __stringify(DEFAULT_UDPTLSTART),
1492                 OPT_UINT_T, PARSE_IN_RANGE | PARSE_DEFAULT,
1493                 FLDSET(struct udptl_global_options, start), DEFAULT_UDPTLSTART, 1024, 65535);
1494
1495         aco_option_register(&cfg_info, "udptlend", ACO_EXACT, general_options, __stringify(DEFAULT_UDPTLEND),
1496                 OPT_UINT_T, PARSE_IN_RANGE | PARSE_DEFAULT,
1497                 FLDSET(struct udptl_global_options, end), DEFAULT_UDPTLEND, 1024, 65535);
1498
1499         aco_option_register(&cfg_info, "udptlfecentries", ACO_EXACT, general_options, NULL,
1500                 OPT_UINT_T, PARSE_IN_RANGE | PARSE_RANGE_DEFAULTS,
1501                 FLDSET(struct udptl_global_options, fecentries), 1, MAX_FEC_ENTRIES);
1502
1503         aco_option_register(&cfg_info, "udptlfecspan", ACO_EXACT, general_options, NULL,
1504                 OPT_UINT_T, PARSE_IN_RANGE | PARSE_RANGE_DEFAULTS,
1505                 FLDSET(struct udptl_global_options, fecspan), 1, MAX_FEC_SPAN);
1506
1507         aco_option_register(&cfg_info, "udptlchecksums", ACO_EXACT, general_options, "yes",
1508                 OPT_BOOL_T, 0, FLDSET(struct udptl_global_options, nochecksums));
1509
1510         aco_option_register(&cfg_info, "use_even_ports", ACO_EXACT, general_options, "no",
1511                 OPT_BOOL_T, 1, FLDSET(struct udptl_global_options, use_even_ports));
1512
1513         aco_option_register_custom(&cfg_info, "t38faxudpec", ACO_EXACT, general_options, NULL, removed_options_handler, 0);
1514         aco_option_register_custom(&cfg_info, "t38faxmaxdatagram", ACO_EXACT, general_options, NULL, removed_options_handler, 0);
1515
1516         __ast_udptl_reload(0);
1517
1518         ast_cli_register_multiple(cli_udptl, ARRAY_LEN(cli_udptl));
1519
1520         ast_register_atexit(udptl_shutdown);
1521 }