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