2 * Asterisk -- A telephony toolkit for Linux.
4 * UDPTL support for T.38
6 * Copyright (C) 2005, Steve Underwood, partly based on RTP code which is
7 * Copyright (C) 1999-2009, Digium, Inc.
9 * Steve Underwood <steveu@coppice.org>
10 * Kevin P. Fleming <kpfleming@digium.com>
12 * See http://www.asterisk.org for more information about
13 * the Asterisk project. Please do not directly contact
14 * any of the maintainers of this project for assistance;
15 * the project provides a web site, mailing lists and IRC
16 * channels for your use.
18 * This program is free software, distributed under the terms of
19 * the GNU General Public License Version 2. See the LICENSE file
20 * at the top of the source tree.
22 * A license has been granted to Digium (via disclaimer) for the use of
29 * \brief UDPTL support for T.38 faxing
32 * \author Mark Spencer <markster@digium.com>
33 * \author Steve Underwood <steveu@coppice.org>
34 * \author Kevin P. Fleming <kpfleming@digium.com>
36 * \page T38fax_udptl T.38 support :: UDPTL
38 * Asterisk supports T.38 fax passthrough, origination and termination. It does
39 * not support gateway operation. The only channel driver that supports T.38 at
40 * this time is chan_sip.
42 * UDPTL is handled very much like RTP. It can be reinvited to go directly between
43 * the endpoints, without involving Asterisk in the media stream.
54 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
60 #include "asterisk/udptl.h"
61 #include "asterisk/frame.h"
62 #include "asterisk/channel.h"
63 #include "asterisk/acl.h"
64 #include "asterisk/config.h"
65 #include "asterisk/lock.h"
66 #include "asterisk/utils.h"
67 #include "asterisk/netsock.h"
68 #include "asterisk/cli.h"
69 #include "asterisk/unaligned.h"
71 #define UDPTL_MTU 1200
80 #define LOG_TAG(u) S_OR(u->tag, "no tag")
82 static int udptlstart = 4500;
83 static int udptlend = 4599;
84 static int udptldebug; /*!< Are we debugging? */
85 static struct sockaddr_in udptldebugaddr; /*!< Debug packets to/from this host */
87 static int nochecksums;
89 static int udptlfecentries;
90 static int udptlfecspan;
91 static int use_even_ports;
93 #define LOCAL_FAX_MAX_DATAGRAM 1400
94 #define DEFAULT_FAX_MAX_DATAGRAM 400
95 #define FAX_MAX_DATAGRAM_LIMIT 1400
96 #define MAX_FEC_ENTRIES 5
97 #define MAX_FEC_SPAN 5
99 #define UDPTL_BUF_MASK 15
103 uint8_t buf[LOCAL_FAX_MAX_DATAGRAM];
104 } udptl_fec_tx_buffer_t;
108 uint8_t buf[LOCAL_FAX_MAX_DATAGRAM];
109 unsigned int fec_len[MAX_FEC_ENTRIES];
110 uint8_t fec[MAX_FEC_ENTRIES][LOCAL_FAX_MAX_DATAGRAM];
111 unsigned int fec_span;
112 unsigned int fec_entries;
113 } udptl_fec_rx_buffer_t;
115 /*! \brief Structure for an UDPTL session */
119 struct ast_frame f[16];
120 unsigned char rawdata[8192 + AST_FRIENDLY_OFFSET];
121 unsigned int lasteventseqn;
124 struct sockaddr_in us;
125 struct sockaddr_in them;
127 struct sched_context *sched;
128 struct io_context *io;
131 ast_udptl_callback callback;
133 /*! This option indicates the error correction scheme used in transmitted UDPTL
134 * packets and expected in received UDPTL packets.
136 enum ast_t38_ec_modes error_correction_scheme;
138 /*! This option indicates the number of error correction entries transmitted in
139 * UDPTL packets and expected in received UDPTL packets.
141 unsigned int error_correction_entries;
143 /*! This option indicates the span of the error correction entries in transmitted
144 * UDPTL packets (FEC only).
146 unsigned int error_correction_span;
148 /*! The maximum size UDPTL packet that can be accepted by
151 int far_max_datagram;
153 /*! The maximum size UDPTL packet that we are prepared to
154 * accept, or -1 if it hasn't been calculated since the last
155 * changes were applied to the UDPTL structure.
157 int local_max_datagram;
159 /*! The maximum IFP that can be submitted for sending
160 * to the remote device. Calculated from far_max_datagram,
161 * error_correction_scheme and error_correction_entries,
162 * or -1 if it hasn't been calculated since the last
163 * changes were applied to the UDPTL structure.
167 /*! The maximum IFP that the local endpoint is prepared
168 * to accept. Along with error_correction_scheme and
169 * error_correction_entries, used to calculate local_max_datagram.
175 struct sockaddr_in far;
177 unsigned int tx_seq_no;
178 unsigned int rx_seq_no;
179 unsigned int rx_expected_seq_no;
181 udptl_fec_tx_buffer_t tx[UDPTL_BUF_MASK + 1];
182 udptl_fec_rx_buffer_t rx[UDPTL_BUF_MASK + 1];
185 static AST_RWLIST_HEAD_STATIC(protos, ast_udptl_protocol);
187 static inline int udptl_debug_test_addr(const struct sockaddr_in *addr)
191 if (udptldebugaddr.sin_addr.s_addr) {
192 if (((ntohs(udptldebugaddr.sin_port) != 0) &&
193 (udptldebugaddr.sin_port != addr->sin_port)) ||
194 (udptldebugaddr.sin_addr.s_addr != addr->sin_addr.s_addr))
200 static int decode_length(uint8_t *buf, unsigned int limit, unsigned int *len, unsigned int *pvalue)
204 if ((buf[*len] & 0x80) == 0) {
209 if ((buf[*len] & 0x40) == 0) {
210 if (*len == limit - 1)
212 *pvalue = (buf[*len] & 0x3F) << 8;
214 *pvalue |= buf[*len];
218 *pvalue = (buf[*len] & 0x3F) << 14;
220 /* Indicate we have a fragment */
223 /*- End of function --------------------------------------------------------*/
225 static int decode_open_type(uint8_t *buf, unsigned int limit, unsigned int *len, const uint8_t **p_object, unsigned int *p_num_octets)
227 unsigned int octet_cnt;
228 unsigned int octet_idx;
230 int length; /* a negative length indicates the limit has been reached in decode_length. */
231 const uint8_t **pbuf;
233 for (octet_idx = 0, *p_num_octets = 0; ; octet_idx += octet_cnt) {
235 if ((length = decode_length(buf, limit, len, &octet_cnt)) < 0)
238 *p_num_octets += octet_cnt;
240 pbuf = &p_object[octet_idx];
242 /* Make sure the buffer contains at least the number of bits requested */
243 if ((*len + octet_cnt) > limit)
254 /*- End of function --------------------------------------------------------*/
256 static unsigned int encode_length(uint8_t *buf, unsigned int *len, unsigned int value)
258 unsigned int multiplier;
266 if (value < 0x4000) {
268 /* Set the first bit of the first octet */
269 buf[*len] = ((0x8000 | value) >> 8) & 0xFF;
271 buf[*len] = value & 0xFF;
276 multiplier = (value < 0x10000) ? (value >> 14) : 4;
277 /* Set the first 2 bits of the octet */
278 buf[*len] = 0xC0 | multiplier;
280 return multiplier << 14;
282 /*- End of function --------------------------------------------------------*/
284 static int encode_open_type(const struct ast_udptl *udptl, uint8_t *buf, unsigned int buflen,
285 unsigned int *len, const uint8_t *data, unsigned int num_octets)
288 unsigned int octet_idx;
291 /* If open type is of zero length, add a single zero byte (10.1) */
292 if (num_octets == 0) {
297 /* Encode the open type */
298 for (octet_idx = 0; ; num_octets -= enclen, octet_idx += enclen) {
299 if ((enclen = encode_length(buf, len, num_octets)) < 0)
301 if (enclen + *len > buflen) {
302 ast_log(LOG_ERROR, "(%s): Buffer overflow detected (%d + %d > %d)\n",
303 LOG_TAG(udptl), enclen, *len, buflen);
307 memcpy(&buf[*len], &data[octet_idx], enclen);
310 if (enclen >= num_octets)
316 /*- End of function --------------------------------------------------------*/
318 static int udptl_rx_packet(struct ast_udptl *s, uint8_t *buf, unsigned int len)
336 unsigned int ifp_len;
338 const uint8_t *bufs[16];
339 unsigned int lengths[16];
346 memset(&s->f[0], 0, sizeof(s->f[0]));
348 /* Decode seq_number */
351 seq_no = (buf[0] << 8) | buf[1];
354 /* Break out the primary packet */
355 if ((stat1 = decode_open_type(buf, len, &ptr, &ifp, &ifp_len)) != 0)
357 /* Decode error_recovery */
360 if ((buf[ptr++] & 0x80) == 0) {
361 /* Secondary packet mode for error recovery */
362 if (seq_no > s->rx_seq_no) {
363 /* We received a later packet than we expected, so we need to check if we can fill in the gap from the
364 secondary packets. */
367 if ((stat2 = decode_length(buf, len, &ptr, &count)) < 0)
369 for (i = 0; i < count; i++) {
370 if ((stat1 = decode_open_type(buf, len, &ptr, &bufs[total_count + i], &lengths[total_count + i])) != 0)
373 total_count += count;
376 /* Step through in reverse order, so we go oldest to newest */
377 for (i = total_count; i > 0; i--) {
378 if (seq_no - i >= s->rx_seq_no) {
379 /* This one wasn't seen before */
380 /* Decode the secondary IFP packet */
381 //fprintf(stderr, "Secondary %d, len %d\n", seq_no - i, lengths[i - 1]);
382 s->f[ifp_no].frametype = AST_FRAME_MODEM;
383 s->f[ifp_no].subclass.codec = AST_MODEM_T38;
385 s->f[ifp_no].mallocd = 0;
386 s->f[ifp_no].seqno = seq_no - i;
387 s->f[ifp_no].datalen = lengths[i - 1];
388 s->f[ifp_no].data.ptr = (uint8_t *) bufs[i - 1];
389 s->f[ifp_no].offset = 0;
390 s->f[ifp_no].src = "UDPTL";
392 AST_LIST_NEXT(&s->f[ifp_no - 1], frame_list) = &s->f[ifp_no];
393 AST_LIST_NEXT(&s->f[ifp_no], frame_list) = NULL;
401 /* FEC mode for error recovery */
402 /* Our buffers cannot tolerate overlength IFP packets in FEC mode */
403 if (ifp_len > LOCAL_FAX_MAX_DATAGRAM)
405 /* Update any missed slots in the buffer */
406 for ( ; seq_no > s->rx_seq_no; s->rx_seq_no++) {
407 x = s->rx_seq_no & UDPTL_BUF_MASK;
408 s->rx[x].buf_len = -1;
409 s->rx[x].fec_len[0] = 0;
410 s->rx[x].fec_span = 0;
411 s->rx[x].fec_entries = 0;
414 x = seq_no & UDPTL_BUF_MASK;
416 memset(repaired, 0, sizeof(repaired));
418 /* Save the new IFP packet */
419 memcpy(s->rx[x].buf, ifp, ifp_len);
420 s->rx[x].buf_len = ifp_len;
423 /* Decode the FEC packets */
424 /* The span is defined as an unconstrained integer, but will never be more
425 than a small value. */
431 s->rx[x].fec_span = span;
433 /* The number of entries is defined as a length, but will only ever be a small
434 value. Treat it as such. */
437 entries = buf[ptr++];
438 s->rx[x].fec_entries = entries;
440 /* Decode the elements */
441 for (i = 0; i < entries; i++) {
442 if ((stat1 = decode_open_type(buf, len, &ptr, &data, &s->rx[x].fec_len[i])) != 0)
444 if (s->rx[x].fec_len[i] > LOCAL_FAX_MAX_DATAGRAM)
447 /* Save the new FEC data */
448 memcpy(s->rx[x].fec[i], data, s->rx[x].fec_len[i]);
450 fprintf(stderr, "FEC: ");
451 for (j = 0; j < s->rx[x].fec_len[i]; j++)
452 fprintf(stderr, "%02X ", data[j]);
453 fprintf(stderr, "\n");
457 /* See if we can reconstruct anything which is missing */
458 /* TODO: this does not comprehensively hunt back and repair everything that is possible */
459 for (l = x; l != ((x - (16 - span*entries)) & UDPTL_BUF_MASK); l = (l - 1) & UDPTL_BUF_MASK) {
460 if (s->rx[l].fec_len[0] <= 0)
462 for (m = 0; m < s->rx[l].fec_entries; m++) {
463 limit = (l + m) & UDPTL_BUF_MASK;
464 for (which = -1, k = (limit - s->rx[l].fec_span * s->rx[l].fec_entries) & UDPTL_BUF_MASK; k != limit; k = (k + s->rx[l].fec_entries) & UDPTL_BUF_MASK) {
465 if (s->rx[k].buf_len <= 0)
466 which = (which == -1) ? k : -2;
470 for (j = 0; j < s->rx[l].fec_len[m]; j++) {
471 s->rx[which].buf[j] = s->rx[l].fec[m][j];
472 for (k = (limit - s->rx[l].fec_span * s->rx[l].fec_entries) & UDPTL_BUF_MASK; k != limit; k = (k + s->rx[l].fec_entries) & UDPTL_BUF_MASK)
473 s->rx[which].buf[j] ^= (s->rx[k].buf_len > j) ? s->rx[k].buf[j] : 0;
475 s->rx[which].buf_len = s->rx[l].fec_len[m];
476 repaired[which] = TRUE;
480 /* Now play any new packets forwards in time */
481 for (l = (x + 1) & UDPTL_BUF_MASK, j = seq_no - UDPTL_BUF_MASK; l != x; l = (l + 1) & UDPTL_BUF_MASK, j++) {
483 //fprintf(stderr, "Fixed packet %d, len %d\n", j, l);
484 s->f[ifp_no].frametype = AST_FRAME_MODEM;
485 s->f[ifp_no].subclass.codec = AST_MODEM_T38;
487 s->f[ifp_no].mallocd = 0;
488 s->f[ifp_no].seqno = j;
489 s->f[ifp_no].datalen = s->rx[l].buf_len;
490 s->f[ifp_no].data.ptr = s->rx[l].buf;
491 s->f[ifp_no].offset = 0;
492 s->f[ifp_no].src = "UDPTL";
494 AST_LIST_NEXT(&s->f[ifp_no - 1], frame_list) = &s->f[ifp_no];
495 AST_LIST_NEXT(&s->f[ifp_no], frame_list) = NULL;
501 /* If packets are received out of sequence, we may have already processed this packet from the error
502 recovery information in a packet already received. */
503 if (seq_no >= s->rx_seq_no) {
504 /* Decode the primary IFP packet */
505 s->f[ifp_no].frametype = AST_FRAME_MODEM;
506 s->f[ifp_no].subclass.codec = AST_MODEM_T38;
508 s->f[ifp_no].mallocd = 0;
509 s->f[ifp_no].seqno = seq_no;
510 s->f[ifp_no].datalen = ifp_len;
511 s->f[ifp_no].data.ptr = (uint8_t *) ifp;
512 s->f[ifp_no].offset = 0;
513 s->f[ifp_no].src = "UDPTL";
515 AST_LIST_NEXT(&s->f[ifp_no - 1], frame_list) = &s->f[ifp_no];
516 AST_LIST_NEXT(&s->f[ifp_no], frame_list) = NULL;
521 s->rx_seq_no = seq_no + 1;
524 /*- End of function --------------------------------------------------------*/
526 static int udptl_build_packet(struct ast_udptl *s, uint8_t *buf, unsigned int buflen, uint8_t *ifp, unsigned int ifp_len)
528 uint8_t fec[LOCAL_FAX_MAX_DATAGRAM * 2];
540 seq = s->tx_seq_no & 0xFFFF;
542 /* Map the sequence number to an entry in the circular buffer */
543 entry = seq & UDPTL_BUF_MASK;
545 /* We save the message in a circular buffer, for generating FEC or
546 redundancy sets later on. */
547 s->tx[entry].buf_len = ifp_len;
548 memcpy(s->tx[entry].buf, ifp, ifp_len);
550 /* Build the UDPTLPacket */
553 /* Encode the sequence number */
554 buf[len++] = (seq >> 8) & 0xFF;
555 buf[len++] = seq & 0xFF;
557 /* Encode the primary IFP packet */
558 if (encode_open_type(s, buf, buflen, &len, ifp, ifp_len) < 0)
561 /* Encode the appropriate type of error recovery information */
562 switch (s->error_correction_scheme)
564 case UDPTL_ERROR_CORRECTION_NONE:
565 /* Encode the error recovery type */
567 /* The number of entries will always be zero, so it is pointless allowing
568 for the fragmented case here. */
569 if (encode_length(buf, &len, 0) < 0)
572 case UDPTL_ERROR_CORRECTION_REDUNDANCY:
573 /* Encode the error recovery type */
575 if (s->tx_seq_no > s->error_correction_entries)
576 entries = s->error_correction_entries;
578 entries = s->tx_seq_no;
579 /* The number of entries will always be small, so it is pointless allowing
580 for the fragmented case here. */
581 if (encode_length(buf, &len, entries) < 0)
583 /* Encode the elements */
584 for (i = 0; i < entries; i++) {
585 j = (entry - i - 1) & UDPTL_BUF_MASK;
586 if (encode_open_type(s, buf, buflen, &len, s->tx[j].buf, s->tx[j].buf_len) < 0) {
587 ast_debug(1, "(%s): Encoding failed at i=%d, j=%d\n",
593 case UDPTL_ERROR_CORRECTION_FEC:
594 span = s->error_correction_span;
595 entries = s->error_correction_entries;
596 if (seq < s->error_correction_span*s->error_correction_entries) {
597 /* In the initial stages, wind up the FEC smoothly */
598 entries = seq/s->error_correction_span;
599 if (seq < s->error_correction_span)
602 /* Encode the error recovery type */
604 /* Span is defined as an inconstrained integer, which it dumb. It will only
605 ever be a small value. Treat it as such. */
608 /* The number of entries is defined as a length, but will only ever be a small
609 value. Treat it as such. */
610 buf[len++] = entries;
611 for (m = 0; m < entries; m++) {
612 /* Make an XOR'ed entry the maximum length */
613 limit = (entry + m) & UDPTL_BUF_MASK;
615 for (i = (limit - span*entries) & UDPTL_BUF_MASK; i != limit; i = (i + entries) & UDPTL_BUF_MASK) {
616 if (high_tide < s->tx[i].buf_len) {
617 for (j = 0; j < high_tide; j++)
618 fec[j] ^= s->tx[i].buf[j];
619 for ( ; j < s->tx[i].buf_len; j++)
620 fec[j] = s->tx[i].buf[j];
621 high_tide = s->tx[i].buf_len;
623 for (j = 0; j < s->tx[i].buf_len; j++)
624 fec[j] ^= s->tx[i].buf[j];
627 if (encode_open_type(s, buf, buflen, &len, fec, high_tide) < 0)
634 fprintf(stderr, "\n");
640 int ast_udptl_fd(const struct ast_udptl *udptl)
645 void ast_udptl_set_data(struct ast_udptl *udptl, void *data)
650 void ast_udptl_set_callback(struct ast_udptl *udptl, ast_udptl_callback callback)
652 udptl->callback = callback;
655 void ast_udptl_setnat(struct ast_udptl *udptl, int nat)
660 static int udptlread(int *id, int fd, short events, void *cbdata)
662 struct ast_udptl *udptl = cbdata;
665 if ((f = ast_udptl_read(udptl))) {
667 udptl->callback(udptl, f, udptl->data);
672 struct ast_frame *ast_udptl_read(struct ast_udptl *udptl)
675 struct sockaddr_in sin;
678 uint16_t *udptlheader;
682 /* Cache where the header will go */
683 res = recvfrom(udptl->fd,
684 udptl->rawdata + AST_FRIENDLY_OFFSET,
685 sizeof(udptl->rawdata) - AST_FRIENDLY_OFFSET,
687 (struct sockaddr *) &sin,
689 udptlheader = (uint16_t *)(udptl->rawdata + AST_FRIENDLY_OFFSET);
692 ast_log(LOG_WARNING, "(%s): UDPTL read error: %s\n",
693 LOG_TAG(udptl), strerror(errno));
694 ast_assert(errno != EBADF);
695 return &ast_null_frame;
698 /* Ignore if the other side hasn't been given an address yet. */
699 if (!udptl->them.sin_addr.s_addr || !udptl->them.sin_port)
700 return &ast_null_frame;
703 /* Send to whoever sent to us */
704 if ((udptl->them.sin_addr.s_addr != sin.sin_addr.s_addr) ||
705 (udptl->them.sin_port != sin.sin_port)) {
706 memcpy(&udptl->them, &sin, sizeof(udptl->them));
707 ast_debug(1, "UDPTL NAT (%s): Using address %s:%d\n",
708 LOG_TAG(udptl), ast_inet_ntoa(udptl->them.sin_addr), ntohs(udptl->them.sin_port));
712 if (udptl_debug_test_addr(&sin)) {
713 ast_verb(1, "UDPTL (%s): packet from %s:%d (type %d, seq %d, len %d)\n",
714 LOG_TAG(udptl), ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port), 0, seqno, res);
716 if (udptl_rx_packet(udptl, udptl->rawdata + AST_FRIENDLY_OFFSET, res) < 1)
717 return &ast_null_frame;
722 static void calculate_local_max_datagram(struct ast_udptl *udptl)
724 unsigned int new_max = 0;
726 if (udptl->local_max_ifp == -1) {
727 ast_log(LOG_WARNING, "(%s): Cannot calculate local_max_datagram before local_max_ifp has been set.\n",
729 udptl->local_max_datagram = -1;
733 /* calculate the amount of space required to receive an IFP
734 * of the maximum size supported by the application/endpoint
735 * that we are delivering them to (local endpoint), and add
736 * the amount of space required to support the selected
737 * error correction mode
739 switch (udptl->error_correction_scheme) {
740 case UDPTL_ERROR_CORRECTION_NONE:
741 /* need room for sequence number, length indicator, redundancy
742 * indicator and following length indicator
744 new_max = 5 + udptl->local_max_ifp;
746 case UDPTL_ERROR_CORRECTION_REDUNDANCY:
747 /* need room for sequence number, length indicators, plus
748 * room for up to 3 redundancy packets
750 new_max = 5 + udptl->local_max_ifp + 2 + (3 * udptl->local_max_ifp);
752 case UDPTL_ERROR_CORRECTION_FEC:
753 /* need room for sequence number, length indicators and a
754 * a single IFP of the maximum size expected
756 new_max = 5 + udptl->local_max_ifp + 4 + udptl->local_max_ifp;
759 /* add 5% extra space for insurance, but no larger than LOCAL_FAX_MAX_DATAGRAM */
760 udptl->local_max_datagram = MIN(new_max * 1.05, LOCAL_FAX_MAX_DATAGRAM);
763 static void calculate_far_max_ifp(struct ast_udptl *udptl)
765 unsigned new_max = 0;
767 if (udptl->far_max_datagram == -1) {
768 ast_log(LOG_WARNING, "(%s): Cannot calculate far_max_ifp before far_max_datagram has been set.\n",
770 udptl->far_max_ifp = -1;
774 /* the goal here is to supply the local endpoint (application
775 * or bridged channel) a maximum IFP value that will allow it
776 * to effectively and efficiently transfer image data at its
777 * selected bit rate, taking into account the selected error
778 * correction mode, but without overrunning the far endpoint's
779 * datagram buffer. this is complicated by the fact that some
780 * far endpoints send us bogus (small) max datagram values,
781 * which would result in either buffer overrun or no error
782 * correction. we try to accomodate those, but if the supplied
783 * value is too small to do so, we'll emit warning messages and
784 * the user will have to use configuration options to override
785 * the max datagram value supplied by the far endpoint.
787 switch (udptl->error_correction_scheme) {
788 case UDPTL_ERROR_CORRECTION_NONE:
789 /* need room for sequence number, length indicator, redundancy
790 * indicator and following length indicator
792 new_max = udptl->far_max_datagram - 5;
794 case UDPTL_ERROR_CORRECTION_REDUNDANCY:
795 /* for this case, we'd like to send as many error correction entries
796 * as possible (up to the number we're configured for), but we'll settle
797 * for sending fewer if the configured number would cause the
798 * calculated max IFP to be too small for effective operation
800 * need room for sequence number, length indicators and the
801 * configured number of redundant packets
803 * note: we purposely don't allow error_correction_entries to drop to
804 * zero in this loop; we'd rather send smaller IFPs (and thus reduce
805 * the image data transfer rate) than sacrifice redundancy completely
808 new_max = (udptl->far_max_datagram - 8) / (udptl->error_correction_entries + 1);
810 if ((new_max < 80) && (udptl->error_correction_entries > 1)) {
811 /* the max ifp is not large enough, subtract an
812 * error correction entry and calculate again
814 --udptl->error_correction_entries;
820 case UDPTL_ERROR_CORRECTION_FEC:
821 /* need room for sequence number, length indicators and a
822 * a single IFP of the maximum size expected
824 new_max = (udptl->far_max_datagram - 10) / 2;
827 /* subtract 5% of space for insurance */
828 udptl->far_max_ifp = new_max * 0.95;
831 enum ast_t38_ec_modes ast_udptl_get_error_correction_scheme(const struct ast_udptl *udptl)
833 return udptl->error_correction_scheme;
836 void ast_udptl_set_error_correction_scheme(struct ast_udptl *udptl, enum ast_t38_ec_modes ec)
838 udptl->error_correction_scheme = ec;
840 case UDPTL_ERROR_CORRECTION_FEC:
841 udptl->error_correction_scheme = UDPTL_ERROR_CORRECTION_FEC;
842 if (udptl->error_correction_entries == 0) {
843 udptl->error_correction_entries = 3;
845 if (udptl->error_correction_span == 0) {
846 udptl->error_correction_span = 3;
849 case UDPTL_ERROR_CORRECTION_REDUNDANCY:
850 udptl->error_correction_scheme = UDPTL_ERROR_CORRECTION_REDUNDANCY;
851 if (udptl->error_correction_entries == 0) {
852 udptl->error_correction_entries = 3;
859 /* reset calculated values so they'll be computed again */
860 udptl->local_max_datagram = -1;
861 udptl->far_max_ifp = -1;
864 void ast_udptl_set_local_max_ifp(struct ast_udptl *udptl, unsigned int max_ifp)
866 /* make sure max_ifp is a positive value since a cast will take place when
867 * when setting local_max_ifp */
868 if ((signed int) max_ifp > 0) {
869 udptl->local_max_ifp = max_ifp;
870 /* reset calculated values so they'll be computed again */
871 udptl->local_max_datagram = -1;
875 unsigned int ast_udptl_get_local_max_datagram(struct ast_udptl *udptl)
877 if (udptl->local_max_datagram == -1) {
878 calculate_local_max_datagram(udptl);
881 /* this function expects a unsigned value in return. */
882 if (udptl->local_max_datagram < 0) {
885 return udptl->local_max_datagram;
888 void ast_udptl_set_far_max_datagram(struct ast_udptl *udptl, unsigned int max_datagram)
890 if (!max_datagram || (max_datagram > FAX_MAX_DATAGRAM_LIMIT)) {
891 udptl->far_max_datagram = DEFAULT_FAX_MAX_DATAGRAM;
893 udptl->far_max_datagram = max_datagram;
895 /* reset calculated values so they'll be computed again */
896 udptl->far_max_ifp = -1;
899 unsigned int ast_udptl_get_far_max_datagram(const struct ast_udptl *udptl)
901 if (udptl->far_max_datagram < 0) {
904 return udptl->far_max_datagram;
907 unsigned int ast_udptl_get_far_max_ifp(struct ast_udptl *udptl)
909 if (udptl->far_max_ifp == -1) {
910 calculate_far_max_ifp(udptl);
913 if (udptl->far_max_ifp < 0) {
916 return udptl->far_max_ifp;
919 struct ast_udptl *ast_udptl_new_with_bindaddr(struct sched_context *sched, struct io_context *io, int callbackmode, struct in_addr addr)
921 struct ast_udptl *udptl;
927 if (!(udptl = ast_calloc(1, sizeof(*udptl))))
930 udptl->error_correction_span = udptlfecspan;
931 udptl->error_correction_entries = udptlfecentries;
933 udptl->far_max_datagram = -1;
934 udptl->far_max_ifp = -1;
935 udptl->local_max_ifp = -1;
936 udptl->local_max_datagram = -1;
938 for (i = 0; i <= UDPTL_BUF_MASK; i++) {
939 udptl->rx[i].buf_len = -1;
940 udptl->tx[i].buf_len = -1;
943 udptl->them.sin_family = AF_INET;
944 udptl->us.sin_family = AF_INET;
946 if ((udptl->fd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
948 ast_log(LOG_WARNING, "Unable to allocate socket: %s\n", strerror(errno));
951 flags = fcntl(udptl->fd, F_GETFL);
952 fcntl(udptl->fd, F_SETFL, flags | O_NONBLOCK);
955 setsockopt(udptl->fd, SOL_SOCKET, SO_NO_CHECK, &nochecksums, sizeof(nochecksums));
957 /* Find us a place */
958 x = (udptlstart == udptlend) ? udptlstart : (ast_random() % (udptlend - udptlstart)) + udptlstart;
959 if (use_even_ports && (x & 1)) {
964 udptl->us.sin_port = htons(x);
965 udptl->us.sin_addr = addr;
966 if (bind(udptl->fd, (struct sockaddr *) &udptl->us, sizeof(udptl->us)) == 0)
968 if (errno != EADDRINUSE) {
969 ast_log(LOG_WARNING, "Unexpected bind error: %s\n", strerror(errno));
974 if (use_even_ports) {
981 if (x == startplace) {
982 ast_log(LOG_WARNING, "No UDPTL ports remaining\n");
988 if (io && sched && callbackmode) {
989 /* Operate this one in a callback mode */
990 udptl->sched = sched;
992 udptl->ioid = ast_io_add(udptl->io, udptl->fd, udptlread, AST_IO_IN, udptl);
997 struct ast_udptl *ast_udptl_new(struct sched_context *sched, struct io_context *io, int callbackmode)
1000 memset(&ia, 0, sizeof(ia));
1001 return ast_udptl_new_with_bindaddr(sched, io, callbackmode, ia);
1004 void ast_udptl_set_tag(struct ast_udptl *udptl, const char *format, ...)
1009 ast_free(udptl->tag);
1012 va_start(ap, format);
1013 if (ast_vasprintf(&udptl->tag, format, ap) == -1) {
1019 int ast_udptl_setqos(struct ast_udptl *udptl, unsigned int tos, unsigned int cos)
1021 return ast_netsock_set_qos(udptl->fd, tos, cos, "UDPTL");
1024 void ast_udptl_set_peer(struct ast_udptl *udptl, const struct sockaddr_in *them)
1026 udptl->them.sin_port = them->sin_port;
1027 udptl->them.sin_addr = them->sin_addr;
1030 void ast_udptl_get_peer(const struct ast_udptl *udptl, struct sockaddr_in *them)
1032 memset(them, 0, sizeof(*them));
1033 them->sin_family = AF_INET;
1034 them->sin_port = udptl->them.sin_port;
1035 them->sin_addr = udptl->them.sin_addr;
1038 void ast_udptl_get_us(const struct ast_udptl *udptl, struct sockaddr_in *us)
1040 memcpy(us, &udptl->us, sizeof(udptl->us));
1043 void ast_udptl_stop(struct ast_udptl *udptl)
1045 memset(&udptl->them.sin_addr, 0, sizeof(udptl->them.sin_addr));
1046 memset(&udptl->them.sin_port, 0, sizeof(udptl->them.sin_port));
1049 void ast_udptl_destroy(struct ast_udptl *udptl)
1052 ast_io_remove(udptl->io, udptl->ioid);
1056 ast_free(udptl->tag);
1060 int ast_udptl_write(struct ast_udptl *s, struct ast_frame *f)
1063 unsigned int len = f->datalen;
1065 /* if no max datagram size is provided, use default value */
1066 const int bufsize = (s->far_max_datagram > 0) ? s->far_max_datagram : DEFAULT_FAX_MAX_DATAGRAM;
1067 uint8_t buf[bufsize];
1069 memset(buf, 0, sizeof(buf));
1071 /* If we have no peer, return immediately */
1072 if (s->them.sin_addr.s_addr == INADDR_ANY)
1075 /* If there is no data length, return immediately */
1076 if (f->datalen == 0)
1079 if ((f->frametype != AST_FRAME_MODEM) ||
1080 (f->subclass.codec != AST_MODEM_T38)) {
1081 ast_log(LOG_WARNING, "(%s): UDPTL can only send T.38 data.\n",
1086 if (len > s->far_max_ifp) {
1087 ast_log(LOG_WARNING,
1088 "(%s): UDPTL asked to send %d bytes of IFP when far end only prepared to accept %d bytes; data loss will occur."
1089 "You may need to override the T38FaxMaxDatagram value for this endpoint in the channel driver configuration.\n",
1090 LOG_TAG(s), len, s->far_max_ifp);
1091 len = s->far_max_ifp;
1094 /* Save seq_no for debug output because udptl_build_packet increments it */
1095 seq = s->tx_seq_no & 0xFFFF;
1097 /* Cook up the UDPTL packet, with the relevant EC info. */
1098 len = udptl_build_packet(s, buf, sizeof(buf), f->data.ptr, len);
1100 if ((signed int) len > 0 && s->them.sin_port && s->them.sin_addr.s_addr) {
1101 if ((res = sendto(s->fd, buf, len, 0, (struct sockaddr *) &s->them, sizeof(s->them))) < 0)
1102 ast_log(LOG_NOTICE, "(%s): UDPTL Transmission error to %s:%d: %s\n",
1103 LOG_TAG(s), ast_inet_ntoa(s->them.sin_addr), ntohs(s->them.sin_port), strerror(errno));
1104 if (udptl_debug_test_addr(&s->them))
1105 ast_verb(1, "UDPTL (%s): packet to %s:%d (type %d, seq %d, len %d)\n",
1106 LOG_TAG(s), ast_inet_ntoa(s->them.sin_addr), ntohs(s->them.sin_port), 0, seq, len);
1112 void ast_udptl_proto_unregister(struct ast_udptl_protocol *proto)
1114 AST_RWLIST_WRLOCK(&protos);
1115 AST_RWLIST_REMOVE(&protos, proto, list);
1116 AST_RWLIST_UNLOCK(&protos);
1119 int ast_udptl_proto_register(struct ast_udptl_protocol *proto)
1121 struct ast_udptl_protocol *cur;
1123 AST_RWLIST_WRLOCK(&protos);
1124 AST_RWLIST_TRAVERSE(&protos, cur, list) {
1125 if (cur->type == proto->type) {
1126 ast_log(LOG_WARNING, "Tried to register same protocol '%s' twice\n", cur->type);
1127 AST_RWLIST_UNLOCK(&protos);
1131 AST_RWLIST_INSERT_TAIL(&protos, proto, list);
1132 AST_RWLIST_UNLOCK(&protos);
1136 static struct ast_udptl_protocol *get_proto(struct ast_channel *chan)
1138 struct ast_udptl_protocol *cur = NULL;
1140 AST_RWLIST_RDLOCK(&protos);
1141 AST_RWLIST_TRAVERSE(&protos, cur, list) {
1142 if (cur->type == chan->tech->type)
1145 AST_RWLIST_UNLOCK(&protos);
1150 int ast_udptl_bridge(struct ast_channel *c0, struct ast_channel *c1, int flags, struct ast_frame **fo, struct ast_channel **rc)
1152 struct ast_frame *f;
1153 struct ast_channel *who;
1154 struct ast_channel *cs[3];
1155 struct ast_udptl *p0;
1156 struct ast_udptl *p1;
1157 struct ast_udptl_protocol *pr0;
1158 struct ast_udptl_protocol *pr1;
1159 struct sockaddr_in ac0;
1160 struct sockaddr_in ac1;
1161 struct sockaddr_in t0;
1162 struct sockaddr_in t1;
1167 ast_channel_lock(c0);
1168 while (ast_channel_trylock(c1)) {
1169 ast_channel_unlock(c0);
1171 ast_channel_lock(c0);
1173 pr0 = get_proto(c0);
1174 pr1 = get_proto(c1);
1176 ast_log(LOG_WARNING, "Can't find native functions for channel '%s'\n", c0->name);
1177 ast_channel_unlock(c0);
1178 ast_channel_unlock(c1);
1182 ast_log(LOG_WARNING, "Can't find native functions for channel '%s'\n", c1->name);
1183 ast_channel_unlock(c0);
1184 ast_channel_unlock(c1);
1187 pvt0 = c0->tech_pvt;
1188 pvt1 = c1->tech_pvt;
1189 p0 = pr0->get_udptl_info(c0);
1190 p1 = pr1->get_udptl_info(c1);
1192 /* Somebody doesn't want to play... */
1193 ast_channel_unlock(c0);
1194 ast_channel_unlock(c1);
1197 if (pr0->set_udptl_peer(c0, p1)) {
1198 ast_log(LOG_WARNING, "Channel '%s' failed to talk to '%s'\n", c0->name, c1->name);
1199 memset(&ac1, 0, sizeof(ac1));
1201 /* Store UDPTL peer */
1202 ast_udptl_get_peer(p1, &ac1);
1204 if (pr1->set_udptl_peer(c1, p0)) {
1205 ast_log(LOG_WARNING, "Channel '%s' failed to talk back to '%s'\n", c1->name, c0->name);
1206 memset(&ac0, 0, sizeof(ac0));
1208 /* Store UDPTL peer */
1209 ast_udptl_get_peer(p0, &ac0);
1211 ast_channel_unlock(c0);
1212 ast_channel_unlock(c1);
1217 if ((c0->tech_pvt != pvt0) ||
1218 (c1->tech_pvt != pvt1) ||
1219 (c0->masq || c0->masqr || c1->masq || c1->masqr)) {
1220 ast_debug(1, "Oooh, something is weird, backing out\n");
1221 /* Tell it to try again later */
1225 ast_udptl_get_peer(p1, &t1);
1226 ast_udptl_get_peer(p0, &t0);
1227 if (inaddrcmp(&t1, &ac1)) {
1228 ast_debug(1, "Oooh, '%s' changed end address to %s:%d\n",
1229 c1->name, ast_inet_ntoa(t1.sin_addr), ntohs(t1.sin_port));
1230 ast_debug(1, "Oooh, '%s' was %s:%d\n",
1231 c1->name, ast_inet_ntoa(ac1.sin_addr), ntohs(ac1.sin_port));
1232 memcpy(&ac1, &t1, sizeof(ac1));
1234 if (inaddrcmp(&t0, &ac0)) {
1235 ast_debug(1, "Oooh, '%s' changed end address to %s:%d\n",
1236 c0->name, ast_inet_ntoa(t0.sin_addr), ntohs(t0.sin_port));
1237 ast_debug(1, "Oooh, '%s' was %s:%d\n",
1238 c0->name, ast_inet_ntoa(ac0.sin_addr), ntohs(ac0.sin_port));
1239 memcpy(&ac0, &t0, sizeof(ac0));
1241 who = ast_waitfor_n(cs, 2, &to);
1243 ast_debug(1, "Ooh, empty read...\n");
1244 /* check for hangup / whentohangup */
1245 if (ast_check_hangup(c0) || ast_check_hangup(c1))
1253 ast_debug(1, "Oooh, got a %s\n", f ? "digit" : "hangup");
1254 /* That's all we needed */
1257 if (f->frametype == AST_FRAME_MODEM) {
1258 /* Forward T.38 frames if they happen upon us */
1261 } else if (who == c1) {
1267 /* Swap priority. Not that it's a big deal at this point */
1275 static char *handle_cli_udptl_set_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1278 struct ast_hostent ahp;
1285 e->command = "udptl set debug {on|off|ip}";
1287 "Usage: udptl set debug {on|off|ip host[:port]}\n"
1288 " Enable or disable dumping of UDPTL packets.\n"
1289 " If ip is specified, limit the dumped packets to those to and from\n"
1290 " the specified 'host' with optional port.\n";
1296 if (a->argc < 4 || a->argc > 5)
1297 return CLI_SHOWUSAGE;
1300 if (!strncasecmp(a->argv[3], "on", 2)) {
1302 memset(&udptldebugaddr, 0, sizeof(udptldebugaddr));
1303 ast_cli(a->fd, "UDPTL Debugging Enabled\n");
1304 } else if (!strncasecmp(a->argv[3], "off", 3)) {
1306 ast_cli(a->fd, "UDPTL Debugging Disabled\n");
1308 return CLI_SHOWUSAGE;
1311 if (strncasecmp(a->argv[3], "ip", 2))
1312 return CLI_SHOWUSAGE;
1314 arg = ast_strdupa(a->argv[4]);
1315 p = strstr(arg, ":");
1321 hp = ast_gethostbyname(arg, &ahp);
1323 return CLI_SHOWUSAGE;
1324 udptldebugaddr.sin_family = AF_INET;
1325 memcpy(&udptldebugaddr.sin_addr, hp->h_addr, sizeof(udptldebugaddr.sin_addr));
1326 udptldebugaddr.sin_port = htons(port);
1328 ast_cli(a->fd, "UDPTL Debugging Enabled for IP: %s\n", ast_inet_ntoa(udptldebugaddr.sin_addr));
1330 ast_cli(a->fd, "UDPTL Debugging Enabled for IP: %s:%d\n", ast_inet_ntoa(udptldebugaddr.sin_addr), port);
1338 static struct ast_cli_entry cli_udptl[] = {
1339 AST_CLI_DEFINE(handle_cli_udptl_set_debug, "Enable/Disable UDPTL debugging")
1342 static void __ast_udptl_reload(int reload)
1344 struct ast_config *cfg;
1346 struct ast_flags config_flags = { reload ? CONFIG_FLAG_FILEUNCHANGED : 0 };
1348 cfg = ast_config_load2("udptl.conf", "udptl", config_flags);
1349 if (cfg == CONFIG_STATUS_FILEMISSING || cfg == CONFIG_STATUS_FILEUNCHANGED || cfg == CONFIG_STATUS_FILEINVALID) {
1355 udptlfecentries = 0;
1360 if ((s = ast_variable_retrieve(cfg, "general", "udptlstart"))) {
1361 udptlstart = atoi(s);
1362 if (udptlstart < 1024) {
1363 ast_log(LOG_WARNING, "Ports under 1024 are not allowed for T.38.\n");
1366 if (udptlstart > 65535) {
1367 ast_log(LOG_WARNING, "Ports over 65535 are invalid.\n");
1371 if ((s = ast_variable_retrieve(cfg, "general", "udptlend"))) {
1373 if (udptlend < 1024) {
1374 ast_log(LOG_WARNING, "Ports under 1024 are not allowed for T.38.\n");
1377 if (udptlend > 65535) {
1378 ast_log(LOG_WARNING, "Ports over 65535 are invalid.\n");
1382 if ((s = ast_variable_retrieve(cfg, "general", "udptlchecksums"))) {
1390 ast_log(LOG_WARNING, "Disabling UDPTL checksums is not supported on this operating system!\n");
1393 if ((s = ast_variable_retrieve(cfg, "general", "T38FaxUdpEC"))) {
1394 ast_log(LOG_WARNING, "T38FaxUdpEC in udptl.conf is no longer supported; use the t38pt_udptl configuration option in sip.conf instead.\n");
1396 if ((s = ast_variable_retrieve(cfg, "general", "T38FaxMaxDatagram"))) {
1397 ast_log(LOG_WARNING, "T38FaxMaxDatagram in udptl.conf is no longer supported; value is now supplied by T.38 applications.\n");
1399 if ((s = ast_variable_retrieve(cfg, "general", "UDPTLFECEntries"))) {
1400 udptlfecentries = atoi(s);
1401 if (udptlfecentries < 1) {
1402 ast_log(LOG_WARNING, "Too small UDPTLFECEntries value. Defaulting to 1.\n");
1403 udptlfecentries = 1;
1405 if (udptlfecentries > MAX_FEC_ENTRIES) {
1406 ast_log(LOG_WARNING, "Too large UDPTLFECEntries value. Defaulting to %d.\n", MAX_FEC_ENTRIES);
1407 udptlfecentries = MAX_FEC_ENTRIES;
1410 if ((s = ast_variable_retrieve(cfg, "general", "UDPTLFECSpan"))) {
1411 udptlfecspan = atoi(s);
1412 if (udptlfecspan < 1) {
1413 ast_log(LOG_WARNING, "Too small UDPTLFECSpan value. Defaulting to 1.\n");
1416 if (udptlfecspan > MAX_FEC_SPAN) {
1417 ast_log(LOG_WARNING, "Too large UDPTLFECSpan value. Defaulting to %d.\n", MAX_FEC_SPAN);
1418 udptlfecspan = MAX_FEC_SPAN;
1421 if ((s = ast_variable_retrieve(cfg, "general", "use_even_ports"))) {
1422 use_even_ports = ast_true(s);
1424 ast_config_destroy(cfg);
1426 if (udptlstart >= udptlend) {
1427 ast_log(LOG_WARNING, "Unreasonable values for UDPTL start/end ports; defaulting to 4500-4999.\n");
1431 if (use_even_ports && (udptlstart & 1)) {
1433 ast_log(LOG_NOTICE, "Odd numbered udptlstart specified but use_even_ports enabled. udptlstart is now %d\n", udptlstart);
1435 if (use_even_ports && (udptlend & 1)) {
1437 ast_log(LOG_NOTICE, "Odd numbered udptlend specified but use_event_ports enabled. udptlend is now %d\n", udptlend);
1439 ast_verb(2, "UDPTL allocating from port range %d -> %d\n", udptlstart, udptlend);
1442 int ast_udptl_reload(void)
1444 __ast_udptl_reload(1);
1448 void ast_udptl_init(void)
1450 ast_cli_register_multiple(cli_udptl, ARRAY_LEN(cli_udptl));
1451 __ast_udptl_reload(0);