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