Minor formatting change to test a mantis change ...
[asterisk-bristuff.git] / main / udptl.c
blob8d6d62c1a56f78703e88854260e8382943ce283c
1 /*
2 * Asterisk -- A telephony toolkit for Linux.
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.
9 * Steve Underwood <steveu@coppice.org>
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.
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.
21 * A license has been granted to Digium (via disclaimer) for the use of
22 * this code.
25 /*!
26 * \file
28 * \brief UDPTL support for T.38 faxing
31 * \author Mark Spencer <markster@digium.com>, Steve Underwood <steveu@coppice.org>
33 * \page T38fax_udptl T38 fax passhtrough :: UDPTL
35 * Asterisk supports T.38 fax passthrough. Asterisk will not be a client, server
36 * or any form of gateway. Currently fax passthrough is only implemented in the
37 * SIP channel for strict SIP to SIP calls. If you are using chan_local or chan_agent
38 * as a proxy channel, T.38 passthrough will not work.
40 * UDPTL is handled very much like RTP. It can be reinvited to go directly between
41 * the endpoints, without involving Asterisk in the media stream.
43 * \b References:
44 * - chan_sip.c
45 * - udptl.c
49 #include "asterisk.h"
51 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
53 #include <sys/time.h>
54 #include <signal.h>
55 #include <fcntl.h>
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"
68 #define UDPTL_MTU 1200
70 #if !defined(FALSE)
71 #define FALSE 0
72 #endif
73 #if !defined(TRUE)
74 #define TRUE (!FALSE)
75 #endif
77 static int udptlstart;
78 static int udptlend;
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 int udptlfectype;
85 static int udptlfecentries;
86 static int udptlfecspan;
87 static int udptlmaxdatagram;
89 #define LOCAL_FAX_MAX_DATAGRAM 400
90 #define MAX_FEC_ENTRIES 5
91 #define MAX_FEC_SPAN 5
93 #define UDPTL_BUF_MASK 15
95 typedef struct {
96 int buf_len;
97 uint8_t buf[LOCAL_FAX_MAX_DATAGRAM];
98 } udptl_fec_tx_buffer_t;
100 typedef struct {
101 int buf_len;
102 uint8_t buf[LOCAL_FAX_MAX_DATAGRAM];
103 int fec_len[MAX_FEC_ENTRIES];
104 uint8_t fec[MAX_FEC_ENTRIES][LOCAL_FAX_MAX_DATAGRAM];
105 int fec_span;
106 int fec_entries;
107 } udptl_fec_rx_buffer_t;
109 /*! \brief Structure for an UDPTL session */
110 struct ast_udptl {
111 int fd;
112 char resp;
113 struct ast_frame f[16];
114 unsigned char rawdata[8192 + AST_FRIENDLY_OFFSET];
115 unsigned int lasteventseqn;
116 int nat;
117 int flags;
118 struct sockaddr_in us;
119 struct sockaddr_in them;
120 int *ioid;
121 struct sched_context *sched;
122 struct io_context *io;
123 void *data;
124 ast_udptl_callback callback;
125 int udptl_offered_from_local;
127 /*! This option indicates the error correction scheme used in transmitted UDPTL
128 packets. */
129 int error_correction_scheme;
131 /*! This option indicates the number of error correction entries transmitted in
132 UDPTL packets. */
133 int error_correction_entries;
135 /*! This option indicates the span of the error correction entries in transmitted
136 UDPTL packets (FEC only). */
137 int error_correction_span;
139 /*! This option indicates the maximum size of a UDPTL packet that can be accepted by
140 the remote device. */
141 int far_max_datagram_size;
143 /*! This option indicates the maximum size of a UDPTL packet that we are prepared to
144 accept. */
145 int local_max_datagram_size;
147 int verbose;
149 struct sockaddr_in far;
151 int tx_seq_no;
152 int rx_seq_no;
153 int rx_expected_seq_no;
155 udptl_fec_tx_buffer_t tx[UDPTL_BUF_MASK + 1];
156 udptl_fec_rx_buffer_t rx[UDPTL_BUF_MASK + 1];
159 static AST_RWLIST_HEAD_STATIC(protos, ast_udptl_protocol);
161 static int udptl_rx_packet(struct ast_udptl *s, uint8_t *buf, int len);
162 static int udptl_build_packet(struct ast_udptl *s, uint8_t *buf, uint8_t *ifp, int ifp_len);
164 static inline int udptl_debug_test_addr(struct sockaddr_in *addr)
166 if (udptldebug == 0)
167 return 0;
168 if (udptldebugaddr.sin_addr.s_addr) {
169 if (((ntohs(udptldebugaddr.sin_port) != 0)
170 && (udptldebugaddr.sin_port != addr->sin_port))
171 || (udptldebugaddr.sin_addr.s_addr != addr->sin_addr.s_addr))
172 return 0;
174 return 1;
177 static int decode_length(uint8_t *buf, int limit, int *len, int *pvalue)
179 if ((buf[*len] & 0x80) == 0) {
180 if (*len >= limit)
181 return -1;
182 *pvalue = buf[*len];
183 (*len)++;
184 return 0;
186 if ((buf[*len] & 0x40) == 0) {
187 if (*len >= limit - 1)
188 return -1;
189 *pvalue = (buf[*len] & 0x3F) << 8;
190 (*len)++;
191 *pvalue |= buf[*len];
192 (*len)++;
193 return 0;
195 if (*len >= limit)
196 return -1;
197 *pvalue = (buf[*len] & 0x3F) << 14;
198 (*len)++;
199 /* Indicate we have a fragment */
200 return 1;
202 /*- End of function --------------------------------------------------------*/
204 static int decode_open_type(uint8_t *buf, int limit, int *len, const uint8_t **p_object, int *p_num_octets)
206 int octet_cnt;
207 int octet_idx;
208 int stat;
209 int i;
210 const uint8_t **pbuf;
212 for (octet_idx = 0, *p_num_octets = 0; ; octet_idx += octet_cnt) {
213 if ((stat = decode_length(buf, limit, len, &octet_cnt)) < 0)
214 return -1;
215 if (octet_cnt > 0) {
216 *p_num_octets += octet_cnt;
218 pbuf = &p_object[octet_idx];
219 i = 0;
220 /* Make sure the buffer contains at least the number of bits requested */
221 if ((*len + octet_cnt) > limit)
222 return -1;
224 *pbuf = &buf[*len];
225 *len += octet_cnt;
227 if (stat == 0)
228 break;
230 return 0;
232 /*- End of function --------------------------------------------------------*/
234 static int encode_length(uint8_t *buf, int *len, int value)
236 int multiplier;
238 if (value < 0x80) {
239 /* 1 octet */
240 buf[*len] = value;
241 (*len)++;
242 return value;
244 if (value < 0x4000) {
245 /* 2 octets */
246 /* Set the first bit of the first octet */
247 buf[*len] = ((0x8000 | value) >> 8) & 0xFF;
248 (*len)++;
249 buf[*len] = value & 0xFF;
250 (*len)++;
251 return value;
253 /* Fragmentation */
254 multiplier = (value < 0x10000) ? (value >> 14) : 4;
255 /* Set the first 2 bits of the octet */
256 buf[*len] = 0xC0 | multiplier;
257 (*len)++;
258 return multiplier << 14;
260 /*- End of function --------------------------------------------------------*/
262 static int encode_open_type(uint8_t *buf, int *len, const uint8_t *data, int num_octets)
264 int enclen;
265 int octet_idx;
266 uint8_t zero_byte;
268 /* If open type is of zero length, add a single zero byte (10.1) */
269 if (num_octets == 0) {
270 zero_byte = 0;
271 data = &zero_byte;
272 num_octets = 1;
274 /* Encode the open type */
275 for (octet_idx = 0; ; num_octets -= enclen, octet_idx += enclen) {
276 if ((enclen = encode_length(buf, len, num_octets)) < 0)
277 return -1;
278 if (enclen > 0) {
279 memcpy(&buf[*len], &data[octet_idx], enclen);
280 *len += enclen;
282 if (enclen >= num_octets)
283 break;
286 return 0;
288 /*- End of function --------------------------------------------------------*/
290 static int udptl_rx_packet(struct ast_udptl *s, uint8_t *buf, int len)
292 int stat;
293 int stat2;
294 int i;
295 int j;
296 int k;
297 int l;
298 int m;
299 int x;
300 int limit;
301 int which;
302 int ptr;
303 int count;
304 int total_count;
305 int seq_no;
306 const uint8_t *ifp;
307 const uint8_t *data;
308 int ifp_len;
309 int repaired[16];
310 const uint8_t *bufs[16];
311 int lengths[16];
312 int span;
313 int entries;
314 int ifp_no;
316 ptr = 0;
317 ifp_no = 0;
318 memset(&s->f[0], 0, sizeof(s->f[0]));
320 /* Decode seq_number */
321 if (ptr + 2 > len)
322 return -1;
323 seq_no = (buf[0] << 8) | buf[1];
324 ptr += 2;
326 /* Break out the primary packet */
327 if ((stat = decode_open_type(buf, len, &ptr, &ifp, &ifp_len)) != 0)
328 return -1;
329 /* Decode error_recovery */
330 if (ptr + 1 > len)
331 return -1;
332 if ((buf[ptr++] & 0x80) == 0) {
333 /* Secondary packet mode for error recovery */
334 if (seq_no > s->rx_seq_no) {
335 /* We received a later packet than we expected, so we need to check if we can fill in the gap from the
336 secondary packets. */
337 total_count = 0;
338 do {
339 if ((stat2 = decode_length(buf, len, &ptr, &count)) < 0)
340 return -1;
341 for (i = 0; i < count; i++) {
342 if ((stat = decode_open_type(buf, len, &ptr, &bufs[total_count + i], &lengths[total_count + i])) != 0)
343 return -1;
345 total_count += count;
347 while (stat2 > 0);
348 /* Step through in reverse order, so we go oldest to newest */
349 for (i = total_count; i > 0; i--) {
350 if (seq_no - i >= s->rx_seq_no) {
351 /* This one wasn't seen before */
352 /* Decode the secondary IFP packet */
353 //fprintf(stderr, "Secondary %d, len %d\n", seq_no - i, lengths[i - 1]);
354 s->f[ifp_no].frametype = AST_FRAME_MODEM;
355 s->f[ifp_no].subclass = AST_MODEM_T38;
357 s->f[ifp_no].mallocd = 0;
358 s->f[ifp_no].seqno = seq_no - i;
359 s->f[ifp_no].datalen = lengths[i - 1];
360 s->f[ifp_no].data.ptr = (uint8_t *) bufs[i - 1];
361 s->f[ifp_no].offset = 0;
362 s->f[ifp_no].src = "UDPTL";
363 if (ifp_no > 0)
364 AST_LIST_NEXT(&s->f[ifp_no - 1], frame_list) = &s->f[ifp_no];
365 AST_LIST_NEXT(&s->f[ifp_no], frame_list) = NULL;
366 ifp_no++;
371 else
373 /* FEC mode for error recovery */
374 /* Our buffers cannot tolerate overlength IFP packets in FEC mode */
375 if (ifp_len > LOCAL_FAX_MAX_DATAGRAM)
376 return -1;
377 /* Update any missed slots in the buffer */
378 for ( ; seq_no > s->rx_seq_no; s->rx_seq_no++) {
379 x = s->rx_seq_no & UDPTL_BUF_MASK;
380 s->rx[x].buf_len = -1;
381 s->rx[x].fec_len[0] = 0;
382 s->rx[x].fec_span = 0;
383 s->rx[x].fec_entries = 0;
386 x = seq_no & UDPTL_BUF_MASK;
388 memset(repaired, 0, sizeof(repaired));
390 /* Save the new IFP packet */
391 memcpy(s->rx[x].buf, ifp, ifp_len);
392 s->rx[x].buf_len = ifp_len;
393 repaired[x] = TRUE;
395 /* Decode the FEC packets */
396 /* The span is defined as an unconstrained integer, but will never be more
397 than a small value. */
398 if (ptr + 2 > len)
399 return -1;
400 if (buf[ptr++] != 1)
401 return -1;
402 span = buf[ptr++];
403 s->rx[x].fec_span = span;
405 /* The number of entries is defined as a length, but will only ever be a small
406 value. Treat it as such. */
407 if (ptr + 1 > len)
408 return -1;
409 entries = buf[ptr++];
410 s->rx[x].fec_entries = entries;
412 /* Decode the elements */
413 for (i = 0; i < entries; i++) {
414 if ((stat = decode_open_type(buf, len, &ptr, &data, &s->rx[x].fec_len[i])) != 0)
415 return -1;
416 if (s->rx[x].fec_len[i] > LOCAL_FAX_MAX_DATAGRAM)
417 return -1;
419 /* Save the new FEC data */
420 memcpy(s->rx[x].fec[i], data, s->rx[x].fec_len[i]);
421 #if 0
422 fprintf(stderr, "FEC: ");
423 for (j = 0; j < s->rx[x].fec_len[i]; j++)
424 fprintf(stderr, "%02X ", data[j]);
425 fprintf(stderr, "\n");
426 #endif
429 /* See if we can reconstruct anything which is missing */
430 /* TODO: this does not comprehensively hunt back and repair everything that is possible */
431 for (l = x; l != ((x - (16 - span*entries)) & UDPTL_BUF_MASK); l = (l - 1) & UDPTL_BUF_MASK) {
432 if (s->rx[l].fec_len[0] <= 0)
433 continue;
434 for (m = 0; m < s->rx[l].fec_entries; m++) {
435 limit = (l + m) & UDPTL_BUF_MASK;
436 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) {
437 if (s->rx[k].buf_len <= 0)
438 which = (which == -1) ? k : -2;
440 if (which >= 0) {
441 /* Repairable */
442 for (j = 0; j < s->rx[l].fec_len[m]; j++) {
443 s->rx[which].buf[j] = s->rx[l].fec[m][j];
444 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)
445 s->rx[which].buf[j] ^= (s->rx[k].buf_len > j) ? s->rx[k].buf[j] : 0;
447 s->rx[which].buf_len = s->rx[l].fec_len[m];
448 repaired[which] = TRUE;
452 /* Now play any new packets forwards in time */
453 for (l = (x + 1) & UDPTL_BUF_MASK, j = seq_no - UDPTL_BUF_MASK; l != x; l = (l + 1) & UDPTL_BUF_MASK, j++) {
454 if (repaired[l]) {
455 //fprintf(stderr, "Fixed packet %d, len %d\n", j, l);
456 s->f[ifp_no].frametype = AST_FRAME_MODEM;
457 s->f[ifp_no].subclass = AST_MODEM_T38;
459 s->f[ifp_no].mallocd = 0;
460 s->f[ifp_no].seqno = j;
461 s->f[ifp_no].datalen = s->rx[l].buf_len;
462 s->f[ifp_no].data.ptr = s->rx[l].buf;
463 s->f[ifp_no].offset = 0;
464 s->f[ifp_no].src = "UDPTL";
465 if (ifp_no > 0)
466 AST_LIST_NEXT(&s->f[ifp_no - 1], frame_list) = &s->f[ifp_no];
467 AST_LIST_NEXT(&s->f[ifp_no], frame_list) = NULL;
468 ifp_no++;
473 /* If packets are received out of sequence, we may have already processed this packet from the error
474 recovery information in a packet already received. */
475 if (seq_no >= s->rx_seq_no) {
476 /* Decode the primary IFP packet */
477 s->f[ifp_no].frametype = AST_FRAME_MODEM;
478 s->f[ifp_no].subclass = AST_MODEM_T38;
480 s->f[ifp_no].mallocd = 0;
481 s->f[ifp_no].seqno = seq_no;
482 s->f[ifp_no].datalen = ifp_len;
483 s->f[ifp_no].data.ptr = (uint8_t *) ifp;
484 s->f[ifp_no].offset = 0;
485 s->f[ifp_no].src = "UDPTL";
486 if (ifp_no > 0)
487 AST_LIST_NEXT(&s->f[ifp_no - 1], frame_list) = &s->f[ifp_no];
488 AST_LIST_NEXT(&s->f[ifp_no], frame_list) = NULL;
490 ifp_no++;
493 s->rx_seq_no = seq_no + 1;
494 return ifp_no;
496 /*- End of function --------------------------------------------------------*/
498 static int udptl_build_packet(struct ast_udptl *s, uint8_t *buf, uint8_t *ifp, int ifp_len)
500 uint8_t fec[LOCAL_FAX_MAX_DATAGRAM];
501 int i;
502 int j;
503 int seq;
504 int entry;
505 int entries;
506 int span;
507 int m;
508 int len;
509 int limit;
510 int high_tide;
512 seq = s->tx_seq_no & 0xFFFF;
514 /* Map the sequence number to an entry in the circular buffer */
515 entry = seq & UDPTL_BUF_MASK;
517 /* We save the message in a circular buffer, for generating FEC or
518 redundancy sets later on. */
519 s->tx[entry].buf_len = ifp_len;
520 memcpy(s->tx[entry].buf, ifp, ifp_len);
522 /* Build the UDPTLPacket */
524 len = 0;
525 /* Encode the sequence number */
526 buf[len++] = (seq >> 8) & 0xFF;
527 buf[len++] = seq & 0xFF;
529 /* Encode the primary IFP packet */
530 if (encode_open_type(buf, &len, ifp, ifp_len) < 0)
531 return -1;
533 /* Encode the appropriate type of error recovery information */
534 switch (s->error_correction_scheme)
536 case UDPTL_ERROR_CORRECTION_NONE:
537 /* Encode the error recovery type */
538 buf[len++] = 0x00;
539 /* The number of entries will always be zero, so it is pointless allowing
540 for the fragmented case here. */
541 if (encode_length(buf, &len, 0) < 0)
542 return -1;
543 break;
544 case UDPTL_ERROR_CORRECTION_REDUNDANCY:
545 /* Encode the error recovery type */
546 buf[len++] = 0x00;
547 if (s->tx_seq_no > s->error_correction_entries)
548 entries = s->error_correction_entries;
549 else
550 entries = s->tx_seq_no;
551 /* The number of entries will always be small, so it is pointless allowing
552 for the fragmented case here. */
553 if (encode_length(buf, &len, entries) < 0)
554 return -1;
555 /* Encode the elements */
556 for (i = 0; i < entries; i++) {
557 j = (entry - i - 1) & UDPTL_BUF_MASK;
558 if (encode_open_type(buf, &len, s->tx[j].buf, s->tx[j].buf_len) < 0)
559 return -1;
561 break;
562 case UDPTL_ERROR_CORRECTION_FEC:
563 span = s->error_correction_span;
564 entries = s->error_correction_entries;
565 if (seq < s->error_correction_span*s->error_correction_entries) {
566 /* In the initial stages, wind up the FEC smoothly */
567 entries = seq/s->error_correction_span;
568 if (seq < s->error_correction_span)
569 span = 0;
571 /* Encode the error recovery type */
572 buf[len++] = 0x80;
573 /* Span is defined as an inconstrained integer, which it dumb. It will only
574 ever be a small value. Treat it as such. */
575 buf[len++] = 1;
576 buf[len++] = span;
577 /* The number of entries is defined as a length, but will only ever be a small
578 value. Treat it as such. */
579 buf[len++] = entries;
580 for (m = 0; m < entries; m++) {
581 /* Make an XOR'ed entry the maximum length */
582 limit = (entry + m) & UDPTL_BUF_MASK;
583 high_tide = 0;
584 for (i = (limit - span*entries) & UDPTL_BUF_MASK; i != limit; i = (i + entries) & UDPTL_BUF_MASK) {
585 if (high_tide < s->tx[i].buf_len) {
586 for (j = 0; j < high_tide; j++)
587 fec[j] ^= s->tx[i].buf[j];
588 for ( ; j < s->tx[i].buf_len; j++)
589 fec[j] = s->tx[i].buf[j];
590 high_tide = s->tx[i].buf_len;
591 } else {
592 for (j = 0; j < s->tx[i].buf_len; j++)
593 fec[j] ^= s->tx[i].buf[j];
596 if (encode_open_type(buf, &len, fec, high_tide) < 0)
597 return -1;
599 break;
602 if (s->verbose)
603 fprintf(stderr, "\n");
605 s->tx_seq_no++;
606 return len;
609 int ast_udptl_fd(struct ast_udptl *udptl)
611 return udptl->fd;
614 void ast_udptl_set_data(struct ast_udptl *udptl, void *data)
616 udptl->data = data;
619 void ast_udptl_set_callback(struct ast_udptl *udptl, ast_udptl_callback callback)
621 udptl->callback = callback;
624 void ast_udptl_setnat(struct ast_udptl *udptl, int nat)
626 udptl->nat = nat;
629 static int udptlread(int *id, int fd, short events, void *cbdata)
631 struct ast_udptl *udptl = cbdata;
632 struct ast_frame *f;
634 if ((f = ast_udptl_read(udptl))) {
635 if (udptl->callback)
636 udptl->callback(udptl, f, udptl->data);
638 return 1;
641 struct ast_frame *ast_udptl_read(struct ast_udptl *udptl)
643 int res;
644 struct sockaddr_in sin;
645 socklen_t len;
646 uint16_t seqno = 0;
647 uint16_t *udptlheader;
649 len = sizeof(sin);
651 /* Cache where the header will go */
652 res = recvfrom(udptl->fd,
653 udptl->rawdata + AST_FRIENDLY_OFFSET,
654 sizeof(udptl->rawdata) - AST_FRIENDLY_OFFSET,
656 (struct sockaddr *) &sin,
657 &len);
658 udptlheader = (uint16_t *)(udptl->rawdata + AST_FRIENDLY_OFFSET);
659 if (res < 0) {
660 if (errno != EAGAIN)
661 ast_log(LOG_WARNING, "UDPTL read error: %s\n", strerror(errno));
662 ast_assert(errno != EBADF);
663 return &ast_null_frame;
666 /* Ignore if the other side hasn't been given an address yet. */
667 if (!udptl->them.sin_addr.s_addr || !udptl->them.sin_port)
668 return &ast_null_frame;
670 if (udptl->nat) {
671 /* Send to whoever sent to us */
672 if ((udptl->them.sin_addr.s_addr != sin.sin_addr.s_addr) ||
673 (udptl->them.sin_port != sin.sin_port)) {
674 memcpy(&udptl->them, &sin, sizeof(udptl->them));
675 ast_debug(1, "UDPTL NAT: Using address %s:%d\n", ast_inet_ntoa(udptl->them.sin_addr), ntohs(udptl->them.sin_port));
679 if (udptl_debug_test_addr(&sin)) {
680 ast_verb(1, "Got UDPTL packet from %s:%d (type %d, seq %d, len %d)\n",
681 ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port), 0, seqno, res);
683 #if 0
684 printf("Got UDPTL packet from %s:%d (seq %d, len = %d)\n", ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port), seqno, res);
685 #endif
686 if (udptl_rx_packet(udptl, udptl->rawdata + AST_FRIENDLY_OFFSET, res) < 1)
687 return &ast_null_frame;
689 return &udptl->f[0];
692 void ast_udptl_offered_from_local(struct ast_udptl* udptl, int local)
694 if (udptl)
695 udptl->udptl_offered_from_local = local;
696 else
697 ast_log(LOG_WARNING, "udptl structure is null\n");
700 int ast_udptl_get_error_correction_scheme(struct ast_udptl* udptl)
702 if (udptl)
703 return udptl->error_correction_scheme;
704 else {
705 ast_log(LOG_WARNING, "udptl structure is null\n");
706 return -1;
710 void ast_udptl_set_error_correction_scheme(struct ast_udptl* udptl, int ec)
712 if (udptl) {
713 switch (ec) {
714 case UDPTL_ERROR_CORRECTION_FEC:
715 udptl->error_correction_scheme = UDPTL_ERROR_CORRECTION_FEC;
716 break;
717 case UDPTL_ERROR_CORRECTION_REDUNDANCY:
718 udptl->error_correction_scheme = UDPTL_ERROR_CORRECTION_REDUNDANCY;
719 break;
720 case UDPTL_ERROR_CORRECTION_NONE:
721 udptl->error_correction_scheme = UDPTL_ERROR_CORRECTION_NONE;
722 break;
723 default:
724 ast_log(LOG_WARNING, "error correction parameter invalid\n");
726 } else
727 ast_log(LOG_WARNING, "udptl structure is null\n");
730 int ast_udptl_get_local_max_datagram(struct ast_udptl* udptl)
732 if (udptl)
733 return udptl->local_max_datagram_size;
734 else {
735 ast_log(LOG_WARNING, "udptl structure is null\n");
736 return -1;
740 int ast_udptl_get_far_max_datagram(struct ast_udptl* udptl)
742 if (udptl)
743 return udptl->far_max_datagram_size;
744 else {
745 ast_log(LOG_WARNING, "udptl structure is null\n");
746 return -1;
750 void ast_udptl_set_local_max_datagram(struct ast_udptl* udptl, int max_datagram)
752 if (udptl)
753 udptl->local_max_datagram_size = max_datagram;
754 else
755 ast_log(LOG_WARNING, "udptl structure is null\n");
758 void ast_udptl_set_far_max_datagram(struct ast_udptl* udptl, int max_datagram)
760 if (udptl)
761 udptl->far_max_datagram_size = max_datagram;
762 else
763 ast_log(LOG_WARNING, "udptl structure is null\n");
766 struct ast_udptl *ast_udptl_new_with_bindaddr(struct sched_context *sched, struct io_context *io, int callbackmode, struct in_addr addr)
768 struct ast_udptl *udptl;
769 int x;
770 int startplace;
771 int i;
772 long int flags;
774 if (!(udptl = ast_calloc(1, sizeof(*udptl))))
775 return NULL;
777 if (udptlfectype == 2)
778 udptl->error_correction_scheme = UDPTL_ERROR_CORRECTION_FEC;
779 else if (udptlfectype == 1)
780 udptl->error_correction_scheme = UDPTL_ERROR_CORRECTION_REDUNDANCY;
781 else
782 udptl->error_correction_scheme = UDPTL_ERROR_CORRECTION_NONE;
783 udptl->error_correction_span = udptlfecspan;
784 udptl->error_correction_entries = udptlfecentries;
786 udptl->far_max_datagram_size = udptlmaxdatagram;
787 udptl->local_max_datagram_size = udptlmaxdatagram;
789 memset(&udptl->rx, 0, sizeof(udptl->rx));
790 memset(&udptl->tx, 0, sizeof(udptl->tx));
791 for (i = 0; i <= UDPTL_BUF_MASK; i++) {
792 udptl->rx[i].buf_len = -1;
793 udptl->tx[i].buf_len = -1;
796 udptl->them.sin_family = AF_INET;
797 udptl->us.sin_family = AF_INET;
799 if ((udptl->fd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
800 ast_free(udptl);
801 ast_log(LOG_WARNING, "Unable to allocate socket: %s\n", strerror(errno));
802 return NULL;
804 flags = fcntl(udptl->fd, F_GETFL);
805 fcntl(udptl->fd, F_SETFL, flags | O_NONBLOCK);
806 #ifdef SO_NO_CHECK
807 if (nochecksums)
808 setsockopt(udptl->fd, SOL_SOCKET, SO_NO_CHECK, &nochecksums, sizeof(nochecksums));
809 #endif
810 /* Find us a place */
811 x = (ast_random() % (udptlend - udptlstart)) + udptlstart;
812 startplace = x;
813 for (;;) {
814 udptl->us.sin_port = htons(x);
815 udptl->us.sin_addr = addr;
816 if (bind(udptl->fd, (struct sockaddr *) &udptl->us, sizeof(udptl->us)) == 0)
817 break;
818 if (errno != EADDRINUSE) {
819 ast_log(LOG_WARNING, "Unexpected bind error: %s\n", strerror(errno));
820 close(udptl->fd);
821 ast_free(udptl);
822 return NULL;
824 if (++x > udptlend)
825 x = udptlstart;
826 if (x == startplace) {
827 ast_log(LOG_WARNING, "No UDPTL ports remaining\n");
828 close(udptl->fd);
829 ast_free(udptl);
830 return NULL;
833 if (io && sched && callbackmode) {
834 /* Operate this one in a callback mode */
835 udptl->sched = sched;
836 udptl->io = io;
837 udptl->ioid = ast_io_add(udptl->io, udptl->fd, udptlread, AST_IO_IN, udptl);
839 return udptl;
842 struct ast_udptl *ast_udptl_new(struct sched_context *sched, struct io_context *io, int callbackmode)
844 struct in_addr ia;
845 memset(&ia, 0, sizeof(ia));
846 return ast_udptl_new_with_bindaddr(sched, io, callbackmode, ia);
849 int ast_udptl_setqos(struct ast_udptl *udptl, int tos, int cos)
851 return ast_netsock_set_qos(udptl->fd, tos, cos, "UDPTL");
854 void ast_udptl_set_peer(struct ast_udptl *udptl, struct sockaddr_in *them)
856 udptl->them.sin_port = them->sin_port;
857 udptl->them.sin_addr = them->sin_addr;
860 void ast_udptl_get_peer(struct ast_udptl *udptl, struct sockaddr_in *them)
862 memset(them, 0, sizeof(*them));
863 them->sin_family = AF_INET;
864 them->sin_port = udptl->them.sin_port;
865 them->sin_addr = udptl->them.sin_addr;
868 void ast_udptl_get_us(struct ast_udptl *udptl, struct sockaddr_in *us)
870 memcpy(us, &udptl->us, sizeof(udptl->us));
873 void ast_udptl_stop(struct ast_udptl *udptl)
875 memset(&udptl->them.sin_addr, 0, sizeof(udptl->them.sin_addr));
876 memset(&udptl->them.sin_port, 0, sizeof(udptl->them.sin_port));
879 void ast_udptl_destroy(struct ast_udptl *udptl)
881 if (udptl->ioid)
882 ast_io_remove(udptl->io, udptl->ioid);
883 if (udptl->fd > -1)
884 close(udptl->fd);
885 ast_free(udptl);
888 int ast_udptl_write(struct ast_udptl *s, struct ast_frame *f)
890 int seq;
891 int len;
892 int res;
893 uint8_t buf[LOCAL_FAX_MAX_DATAGRAM];
895 /* If we have no peer, return immediately */
896 if (s->them.sin_addr.s_addr == INADDR_ANY)
897 return 0;
899 /* If there is no data length, return immediately */
900 if (f->datalen == 0)
901 return 0;
903 if (f->frametype != AST_FRAME_MODEM) {
904 ast_log(LOG_WARNING, "UDPTL can only send T.38 data\n");
905 return -1;
908 /* Save seq_no for debug output because udptl_build_packet increments it */
909 seq = s->tx_seq_no & 0xFFFF;
911 /* Cook up the UDPTL packet, with the relevant EC info. */
912 len = udptl_build_packet(s, buf, f->data.ptr, f->datalen);
914 if (len > 0 && s->them.sin_port && s->them.sin_addr.s_addr) {
915 if ((res = sendto(s->fd, buf, len, 0, (struct sockaddr *) &s->them, sizeof(s->them))) < 0)
916 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));
917 #if 0
918 printf("Sent %d bytes of UDPTL data to %s:%d\n", res, ast_inet_ntoa(udptl->them.sin_addr), ntohs(udptl->them.sin_port));
919 #endif
920 if (udptl_debug_test_addr(&s->them))
921 ast_verb(1, "Sent UDPTL packet to %s:%d (type %d, seq %d, len %d)\n",
922 ast_inet_ntoa(s->them.sin_addr),
923 ntohs(s->them.sin_port), 0, seq, len);
926 return 0;
929 void ast_udptl_proto_unregister(struct ast_udptl_protocol *proto)
931 AST_RWLIST_WRLOCK(&protos);
932 AST_RWLIST_REMOVE(&protos, proto, list);
933 AST_RWLIST_UNLOCK(&protos);
936 int ast_udptl_proto_register(struct ast_udptl_protocol *proto)
938 struct ast_udptl_protocol *cur;
940 AST_RWLIST_WRLOCK(&protos);
941 AST_RWLIST_TRAVERSE(&protos, cur, list) {
942 if (cur->type == proto->type) {
943 ast_log(LOG_WARNING, "Tried to register same protocol '%s' twice\n", cur->type);
944 AST_RWLIST_UNLOCK(&protos);
945 return -1;
948 AST_RWLIST_INSERT_TAIL(&protos, proto, list);
949 AST_RWLIST_UNLOCK(&protos);
950 return 0;
953 static struct ast_udptl_protocol *get_proto(struct ast_channel *chan)
955 struct ast_udptl_protocol *cur = NULL;
957 AST_RWLIST_RDLOCK(&protos);
958 AST_RWLIST_TRAVERSE(&protos, cur, list) {
959 if (cur->type == chan->tech->type)
960 break;
962 AST_RWLIST_UNLOCK(&protos);
964 return cur;
967 int ast_udptl_bridge(struct ast_channel *c0, struct ast_channel *c1, int flags, struct ast_frame **fo, struct ast_channel **rc)
969 struct ast_frame *f;
970 struct ast_channel *who;
971 struct ast_channel *cs[3];
972 struct ast_udptl *p0;
973 struct ast_udptl *p1;
974 struct ast_udptl_protocol *pr0;
975 struct ast_udptl_protocol *pr1;
976 struct sockaddr_in ac0;
977 struct sockaddr_in ac1;
978 struct sockaddr_in t0;
979 struct sockaddr_in t1;
980 void *pvt0;
981 void *pvt1;
982 int to;
984 ast_channel_lock(c0);
985 while (ast_channel_trylock(c1)) {
986 ast_channel_unlock(c0);
987 usleep(1);
988 ast_channel_lock(c0);
990 pr0 = get_proto(c0);
991 pr1 = get_proto(c1);
992 if (!pr0) {
993 ast_log(LOG_WARNING, "Can't find native functions for channel '%s'\n", c0->name);
994 ast_channel_unlock(c0);
995 ast_channel_unlock(c1);
996 return -1;
998 if (!pr1) {
999 ast_log(LOG_WARNING, "Can't find native functions for channel '%s'\n", c1->name);
1000 ast_channel_unlock(c0);
1001 ast_channel_unlock(c1);
1002 return -1;
1004 pvt0 = c0->tech_pvt;
1005 pvt1 = c1->tech_pvt;
1006 p0 = pr0->get_udptl_info(c0);
1007 p1 = pr1->get_udptl_info(c1);
1008 if (!p0 || !p1) {
1009 /* Somebody doesn't want to play... */
1010 ast_channel_unlock(c0);
1011 ast_channel_unlock(c1);
1012 return -2;
1014 if (pr0->set_udptl_peer(c0, p1)) {
1015 ast_log(LOG_WARNING, "Channel '%s' failed to talk to '%s'\n", c0->name, c1->name);
1016 memset(&ac1, 0, sizeof(ac1));
1017 } else {
1018 /* Store UDPTL peer */
1019 ast_udptl_get_peer(p1, &ac1);
1021 if (pr1->set_udptl_peer(c1, p0)) {
1022 ast_log(LOG_WARNING, "Channel '%s' failed to talk back to '%s'\n", c1->name, c0->name);
1023 memset(&ac0, 0, sizeof(ac0));
1024 } else {
1025 /* Store UDPTL peer */
1026 ast_udptl_get_peer(p0, &ac0);
1028 ast_channel_unlock(c0);
1029 ast_channel_unlock(c1);
1030 cs[0] = c0;
1031 cs[1] = c1;
1032 cs[2] = NULL;
1033 for (;;) {
1034 if ((c0->tech_pvt != pvt0) ||
1035 (c1->tech_pvt != pvt1) ||
1036 (c0->masq || c0->masqr || c1->masq || c1->masqr)) {
1037 ast_debug(1, "Oooh, something is weird, backing out\n");
1038 /* Tell it to try again later */
1039 return -3;
1041 to = -1;
1042 ast_udptl_get_peer(p1, &t1);
1043 ast_udptl_get_peer(p0, &t0);
1044 if (inaddrcmp(&t1, &ac1)) {
1045 ast_debug(1, "Oooh, '%s' changed end address to %s:%d\n",
1046 c1->name, ast_inet_ntoa(t1.sin_addr), ntohs(t1.sin_port));
1047 ast_debug(1, "Oooh, '%s' was %s:%d\n",
1048 c1->name, ast_inet_ntoa(ac1.sin_addr), ntohs(ac1.sin_port));
1049 memcpy(&ac1, &t1, sizeof(ac1));
1051 if (inaddrcmp(&t0, &ac0)) {
1052 ast_debug(1, "Oooh, '%s' changed end address to %s:%d\n",
1053 c0->name, ast_inet_ntoa(t0.sin_addr), ntohs(t0.sin_port));
1054 ast_debug(1, "Oooh, '%s' was %s:%d\n",
1055 c0->name, ast_inet_ntoa(ac0.sin_addr), ntohs(ac0.sin_port));
1056 memcpy(&ac0, &t0, sizeof(ac0));
1058 who = ast_waitfor_n(cs, 2, &to);
1059 if (!who) {
1060 ast_debug(1, "Ooh, empty read...\n");
1061 /* check for hangup / whentohangup */
1062 if (ast_check_hangup(c0) || ast_check_hangup(c1))
1063 break;
1064 continue;
1066 f = ast_read(who);
1067 if (!f) {
1068 *fo = f;
1069 *rc = who;
1070 ast_debug(1, "Oooh, got a %s\n", f ? "digit" : "hangup");
1071 /* That's all we needed */
1072 return 0;
1073 } else {
1074 if (f->frametype == AST_FRAME_MODEM) {
1075 /* Forward T.38 frames if they happen upon us */
1076 if (who == c0) {
1077 ast_write(c1, f);
1078 } else if (who == c1) {
1079 ast_write(c0, f);
1082 ast_frfree(f);
1084 /* Swap priority. Not that it's a big deal at this point */
1085 cs[2] = cs[0];
1086 cs[0] = cs[1];
1087 cs[1] = cs[2];
1089 return -1;
1092 static char *handle_cli_udptl_debug_deprecated(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1094 struct hostent *hp;
1095 struct ast_hostent ahp;
1096 int port;
1097 char *p;
1098 char *arg;
1100 switch (cmd) {
1101 case CLI_INIT:
1102 e->command = "udptl debug [off|ip]";
1103 e->usage =
1104 "Usage: udptl debug [off]|[ip host[:port]]\n"
1105 " Enable or disable dumping of UDPTL packets.\n"
1106 " If ip is specified, limit the dumped packets to those to and from\n"
1107 " the specified 'host' with optional port.\n";
1108 return NULL;
1109 case CLI_GENERATE:
1110 return NULL;
1113 if (a->argc < 2 || a->argc > 4)
1114 return CLI_SHOWUSAGE;
1116 if (a->argc == 2) {
1117 udptldebug = 1;
1118 memset(&udptldebugaddr, 0, sizeof(udptldebugaddr));
1119 ast_cli(a->fd, "UDPTL Debugging Enabled\n");
1120 } else if (a->argc == 3) {
1121 if (strncasecmp(a->argv[2], "off", 3))
1122 return CLI_SHOWUSAGE;
1123 udptldebug = 0;
1124 ast_cli(a->fd, "UDPTL Debugging Disabled\n");
1125 } else {
1126 if (strncasecmp(a->argv[2], "ip", 2))
1127 return CLI_SHOWUSAGE;
1128 port = 0;
1129 arg = a->argv[3];
1130 p = strstr(arg, ":");
1131 if (p) {
1132 *p = '\0';
1133 p++;
1134 port = atoi(p);
1136 hp = ast_gethostbyname(arg, &ahp);
1137 if (hp == NULL)
1138 return CLI_SHOWUSAGE;
1139 udptldebugaddr.sin_family = AF_INET;
1140 memcpy(&udptldebugaddr.sin_addr, hp->h_addr, sizeof(udptldebugaddr.sin_addr));
1141 udptldebugaddr.sin_port = htons(port);
1142 if (port == 0)
1143 ast_cli(a->fd, "UDPTL Debugging Enabled for IP: %s\n", ast_inet_ntoa(udptldebugaddr.sin_addr));
1144 else
1145 ast_cli(a->fd, "UDPTL Debugging Enabled for IP: %s:%d\n", ast_inet_ntoa(udptldebugaddr.sin_addr), port);
1146 udptldebug = 1;
1149 return CLI_SUCCESS;
1152 static char *handle_cli_udptl_set_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1154 struct hostent *hp;
1155 struct ast_hostent ahp;
1156 int port;
1157 char *p;
1158 char *arg;
1160 switch (cmd) {
1161 case CLI_INIT:
1162 e->command = "udptl set debug {on|off|ip}";
1163 e->usage =
1164 "Usage: udptl set debug {on|off|ip host[:port]}\n"
1165 " Enable or disable dumping of UDPTL packets.\n"
1166 " If ip is specified, limit the dumped packets to those to and from\n"
1167 " the specified 'host' with optional port.\n";
1168 return NULL;
1169 case CLI_GENERATE:
1170 return NULL;
1173 if (a->argc < 4 || a->argc > 5)
1174 return CLI_SHOWUSAGE;
1176 if (a->argc == 4) {
1177 if (!strncasecmp(a->argv[3], "on", 2)) {
1178 udptldebug = 1;
1179 memset(&udptldebugaddr, 0, sizeof(udptldebugaddr));
1180 ast_cli(a->fd, "UDPTL Debugging Enabled\n");
1181 } else if (!strncasecmp(a->argv[3], "off", 3)) {
1182 udptldebug = 0;
1183 ast_cli(a->fd, "UDPTL Debugging Disabled\n");
1184 } else {
1185 return CLI_SHOWUSAGE;
1187 } else {
1188 if (strncasecmp(a->argv[3], "ip", 2))
1189 return CLI_SHOWUSAGE;
1190 port = 0;
1191 arg = a->argv[4];
1192 p = strstr(arg, ":");
1193 if (p) {
1194 *p = '\0';
1195 p++;
1196 port = atoi(p);
1198 hp = ast_gethostbyname(arg, &ahp);
1199 if (hp == NULL)
1200 return CLI_SHOWUSAGE;
1201 udptldebugaddr.sin_family = AF_INET;
1202 memcpy(&udptldebugaddr.sin_addr, hp->h_addr, sizeof(udptldebugaddr.sin_addr));
1203 udptldebugaddr.sin_port = htons(port);
1204 if (port == 0)
1205 ast_cli(a->fd, "UDPTL Debugging Enabled for IP: %s\n", ast_inet_ntoa(udptldebugaddr.sin_addr));
1206 else
1207 ast_cli(a->fd, "UDPTL Debugging Enabled for IP: %s:%d\n", ast_inet_ntoa(udptldebugaddr.sin_addr), port);
1208 udptldebug = 1;
1211 return CLI_SUCCESS;
1214 static struct ast_cli_entry cli_handle_udptl_debug_deprecated = AST_CLI_DEFINE(handle_cli_udptl_debug_deprecated, "Enable/Disable UDPTL debugging");
1216 static struct ast_cli_entry cli_udptl[] = {
1217 AST_CLI_DEFINE(handle_cli_udptl_set_debug, "Enable/Disable UDPTL debugging", .deprecate_cmd = &cli_handle_udptl_debug_deprecated)
1220 static void __ast_udptl_reload(int reload)
1222 struct ast_config *cfg;
1223 const char *s;
1224 struct ast_flags config_flags = { reload ? CONFIG_FLAG_FILEUNCHANGED : 0 };
1226 if ((cfg = ast_config_load2("udptl.conf", "udptl", config_flags)) == CONFIG_STATUS_FILEUNCHANGED)
1227 return;
1229 udptlstart = 4500;
1230 udptlend = 4999;
1231 udptlfectype = 0;
1232 udptlfecentries = 0;
1233 udptlfecspan = 0;
1234 udptlmaxdatagram = 0;
1236 if (cfg) {
1237 if ((s = ast_variable_retrieve(cfg, "general", "udptlstart"))) {
1238 udptlstart = atoi(s);
1239 if (udptlstart < 1024)
1240 udptlstart = 1024;
1241 if (udptlstart > 65535)
1242 udptlstart = 65535;
1244 if ((s = ast_variable_retrieve(cfg, "general", "udptlend"))) {
1245 udptlend = atoi(s);
1246 if (udptlend < 1024)
1247 udptlend = 1024;
1248 if (udptlend > 65535)
1249 udptlend = 65535;
1251 if ((s = ast_variable_retrieve(cfg, "general", "udptlchecksums"))) {
1252 #ifdef SO_NO_CHECK
1253 if (ast_false(s))
1254 nochecksums = 1;
1255 else
1256 nochecksums = 0;
1257 #else
1258 if (ast_false(s))
1259 ast_log(LOG_WARNING, "Disabling UDPTL checksums is not supported on this operating system!\n");
1260 #endif
1262 if ((s = ast_variable_retrieve(cfg, "general", "T38FaxUdpEC"))) {
1263 if (strcmp(s, "t38UDPFEC") == 0)
1264 udptlfectype = 2;
1265 else if (strcmp(s, "t38UDPRedundancy") == 0)
1266 udptlfectype = 1;
1268 if ((s = ast_variable_retrieve(cfg, "general", "T38FaxMaxDatagram"))) {
1269 udptlmaxdatagram = atoi(s);
1270 if (udptlmaxdatagram < 0)
1271 udptlmaxdatagram = 0;
1272 if (udptlmaxdatagram > LOCAL_FAX_MAX_DATAGRAM)
1273 udptlmaxdatagram = LOCAL_FAX_MAX_DATAGRAM;
1275 if ((s = ast_variable_retrieve(cfg, "general", "UDPTLFECentries"))) {
1276 udptlfecentries = atoi(s);
1277 if (udptlfecentries < 0)
1278 udptlfecentries = 0;
1279 if (udptlfecentries > MAX_FEC_ENTRIES)
1280 udptlfecentries = MAX_FEC_ENTRIES;
1282 if ((s = ast_variable_retrieve(cfg, "general", "UDPTLFECspan"))) {
1283 udptlfecspan = atoi(s);
1284 if (udptlfecspan < 0)
1285 udptlfecspan = 0;
1286 if (udptlfecspan > MAX_FEC_SPAN)
1287 udptlfecspan = MAX_FEC_SPAN;
1289 ast_config_destroy(cfg);
1291 if (udptlstart >= udptlend) {
1292 ast_log(LOG_WARNING, "Unreasonable values for UDPTL start/end\n");
1293 udptlstart = 4500;
1294 udptlend = 4999;
1296 ast_verb(2, "UDPTL allocating from port range %d -> %d\n", udptlstart, udptlend);
1299 int ast_udptl_reload(void)
1301 __ast_udptl_reload(1);
1302 return 0;
1305 void ast_udptl_init(void)
1307 ast_cli_register_multiple(cli_udptl, sizeof(cli_udptl) / sizeof(struct ast_cli_entry));
1308 __ast_udptl_reload(0);