2 * Asterisk -- An open source telephony toolkit.
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.
51 /*! \li \ref udptl.c uses the configuration file \ref udptl.conf
52 * \addtogroup configuration_file Configuration Files
56 * \page udptl.conf udptl.conf
57 * \verbinclude udptl.conf.sample
61 <support_level>core</support_level>
66 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
72 #include "asterisk/udptl.h"
73 #include "asterisk/frame.h"
74 #include "asterisk/channel.h"
75 #include "asterisk/acl.h"
76 #include "asterisk/config_options.h"
77 #include "asterisk/lock.h"
78 #include "asterisk/utils.h"
79 #include "asterisk/netsock2.h"
80 #include "asterisk/cli.h"
81 #include "asterisk/unaligned.h"
84 <configInfo name="udptl" language="en_US">
85 <configFile name="udptl.conf">
86 <configObject name="global">
87 <synopsis>Global options for configuring UDPTL</synopsis>
88 <configOption name="udptlstart">
89 <synopsis>The start of the UDPTL port range</synopsis>
91 <configOption name="udptlend">
92 <synopsis>The end of the UDPTL port range</synopsis>
94 <configOption name="udptlchecksums">
95 <synopsis>Whether to enable or disable UDP checksums on UDPTL traffic</synopsis>
97 <configOption name="udptlfecentries">
98 <synopsis>The number of error correction entries in a UDPTL packet</synopsis>
100 <configOption name="udptlfecspan">
101 <synopsis>The span over which parity is calculated for FEC in a UDPTL packet</synopsis>
103 <configOption name="use_even_ports">
104 <synopsis>Whether to only use even-numbered UDPTL ports</synopsis>
106 <configOption name="t38faxudpec">
107 <synopsis>Removed</synopsis>
109 <configOption name="t38faxmaxdatagram">
110 <synopsis>Removed</synopsis>
117 #define UDPTL_MTU 1200
123 #define TRUE (!FALSE)
126 #define LOG_TAG(u) S_OR(u->tag, "no tag")
128 #define DEFAULT_UDPTLSTART 4000
129 #define DEFAULT_UDPTLEND 4999
131 static int udptldebug; /*!< Are we debugging? */
132 static struct ast_sockaddr udptldebugaddr; /*!< Debug packets to/from this host */
134 #define LOCAL_FAX_MAX_DATAGRAM 1400
135 #define DEFAULT_FAX_MAX_DATAGRAM 400
136 #define FAX_MAX_DATAGRAM_LIMIT 1400
137 #define MAX_FEC_ENTRIES 5
138 #define MAX_FEC_SPAN 5
140 #define UDPTL_BUF_MASK 15
144 uint8_t buf[LOCAL_FAX_MAX_DATAGRAM];
145 } udptl_fec_tx_buffer_t;
149 uint8_t buf[LOCAL_FAX_MAX_DATAGRAM];
150 unsigned int fec_len[MAX_FEC_ENTRIES];
151 uint8_t fec[MAX_FEC_ENTRIES][LOCAL_FAX_MAX_DATAGRAM];
152 unsigned int fec_span;
153 unsigned int fec_entries;
154 } udptl_fec_rx_buffer_t;
156 /*! \brief Structure for an UDPTL session */
160 struct ast_frame f[16];
161 unsigned char rawdata[8192 + AST_FRIENDLY_OFFSET];
162 unsigned int lasteventseqn;
165 struct ast_sockaddr us;
166 struct ast_sockaddr them;
168 struct ast_sched_context *sched;
169 struct io_context *io;
172 ast_udptl_callback callback;
174 /*! This option indicates the error correction scheme used in transmitted UDPTL
175 * packets and expected in received UDPTL packets.
177 enum ast_t38_ec_modes error_correction_scheme;
179 /*! This option indicates the number of error correction entries transmitted in
180 * UDPTL packets and expected in received UDPTL packets.
182 unsigned int error_correction_entries;
184 /*! This option indicates the span of the error correction entries in transmitted
185 * UDPTL packets (FEC only).
187 unsigned int error_correction_span;
189 /*! The maximum size UDPTL packet that can be accepted by
192 int far_max_datagram;
194 /*! The maximum size UDPTL packet that we are prepared to
195 * accept, or -1 if it hasn't been calculated since the last
196 * changes were applied to the UDPTL structure.
198 int local_max_datagram;
200 /*! The maximum IFP that can be submitted for sending
201 * to the remote device. Calculated from far_max_datagram,
202 * error_correction_scheme and error_correction_entries,
203 * or -1 if it hasn't been calculated since the last
204 * changes were applied to the UDPTL structure.
208 /*! The maximum IFP that the local endpoint is prepared
209 * to accept. Along with error_correction_scheme and
210 * error_correction_entries, used to calculate local_max_datagram.
214 unsigned int tx_seq_no;
215 unsigned int rx_seq_no;
217 udptl_fec_tx_buffer_t tx[UDPTL_BUF_MASK + 1];
218 udptl_fec_rx_buffer_t rx[UDPTL_BUF_MASK + 1];
221 struct udptl_global_options {
222 unsigned int start; /*< The UDPTL start port */
223 unsigned int end; /*< The UDPTL end port */
224 unsigned int fecentries;
225 unsigned int fecspan;
226 unsigned int nochecksums;
227 unsigned int use_even_ports;
230 static AO2_GLOBAL_OBJ_STATIC(globals);
232 struct udptl_config {
233 struct udptl_global_options *general;
236 static void *udptl_snapshot_alloc(void);
237 static int udptl_pre_apply_config(void);
239 static struct aco_type general_option = {
242 .category_match = ACO_WHITELIST,
243 .item_offset = offsetof(struct udptl_config, general),
244 .category = "^general$",
247 static struct aco_type *general_options[] = ACO_TYPES(&general_option);
249 static struct aco_file udptl_conf = {
250 .filename = "udptl.conf",
251 .types = ACO_TYPES(&general_option),
254 CONFIG_INFO_CORE("udptl", cfg_info, globals, udptl_snapshot_alloc,
255 .files = ACO_FILES(&udptl_conf),
256 .pre_apply_config = udptl_pre_apply_config,
259 static inline int udptl_debug_test_addr(const struct ast_sockaddr *addr)
264 if (ast_sockaddr_isnull(&udptldebugaddr)) {
268 if (ast_sockaddr_port(&udptldebugaddr)) {
269 return !ast_sockaddr_cmp(&udptldebugaddr, addr);
271 return !ast_sockaddr_cmp_addr(&udptldebugaddr, addr);
275 static int decode_length(uint8_t *buf, unsigned int limit, unsigned int *len, unsigned int *pvalue)
279 if ((buf[*len] & 0x80) == 0) {
284 if ((buf[*len] & 0x40) == 0) {
285 if (*len == limit - 1)
287 *pvalue = (buf[*len] & 0x3F) << 8;
289 *pvalue |= buf[*len];
293 *pvalue = (buf[*len] & 0x3F) << 14;
295 /* We have a fragment. Currently we don't process fragments. */
296 ast_debug(1, "UDPTL packet with length greater than 16K received, decoding will fail\n");
299 /*- End of function --------------------------------------------------------*/
301 static int decode_open_type(uint8_t *buf, unsigned int limit, unsigned int *len, const uint8_t **p_object, unsigned int *p_num_octets)
303 unsigned int octet_cnt = 0;
305 if (decode_length(buf, limit, len, &octet_cnt) != 0)
309 /* Make sure the buffer contains at least the number of bits requested */
310 if ((*len + octet_cnt) > limit)
313 *p_num_octets = octet_cnt;
314 *p_object = &buf[*len];
320 /*- End of function --------------------------------------------------------*/
322 static unsigned int encode_length(uint8_t *buf, unsigned int *len, unsigned int value)
324 unsigned int multiplier;
332 if (value < 0x4000) {
334 /* Set the first bit of the first octet */
335 buf[*len] = ((0x8000 | value) >> 8) & 0xFF;
337 buf[*len] = value & 0xFF;
342 multiplier = (value < 0x10000) ? (value >> 14) : 4;
343 /* Set the first 2 bits of the octet */
344 buf[*len] = 0xC0 | multiplier;
346 return multiplier << 14;
348 /*- End of function --------------------------------------------------------*/
350 static int encode_open_type(const struct ast_udptl *udptl, uint8_t *buf, unsigned int buflen,
351 unsigned int *len, const uint8_t *data, unsigned int num_octets)
354 unsigned int octet_idx;
357 /* If open type is of zero length, add a single zero byte (10.1) */
358 if (num_octets == 0) {
363 /* Encode the open type */
364 for (octet_idx = 0; ; num_octets -= enclen, octet_idx += enclen) {
365 if ((enclen = encode_length(buf, len, num_octets)) < 0)
367 if (enclen + *len > buflen) {
368 ast_log(LOG_ERROR, "UDPTL (%s): Buffer overflow detected (%d + %d > %d)\n",
369 LOG_TAG(udptl), enclen, *len, buflen);
373 memcpy(&buf[*len], &data[octet_idx], enclen);
376 if (enclen >= num_octets)
382 /*- End of function --------------------------------------------------------*/
384 static int udptl_rx_packet(struct ast_udptl *s, uint8_t *buf, unsigned int len)
389 unsigned int ptr; /* an index that keeps track of how much of the UDPTL packet has been processed */
391 const uint8_t *ifp = NULL;
392 const uint8_t *data = NULL;
393 unsigned int ifp_len = 0;
395 const uint8_t *bufs[ARRAY_LEN(s->f) - 1];
396 unsigned int lengths[ARRAY_LEN(s->f) - 1];
403 memset(&s->f[0], 0, sizeof(s->f[0]));
405 /* Decode seq_number */
408 seq_no = (buf[0] << 8) | buf[1];
411 /* Break out the primary packet */
412 if ((stat1 = decode_open_type(buf, len, &ptr, &ifp, &ifp_len)) != 0)
414 /* Decode error_recovery */
417 if ((buf[ptr++] & 0x80) == 0) {
418 /* Secondary packet mode for error recovery */
419 if (seq_no > s->rx_seq_no) {
420 /* We received a later packet than we expected, so we need to check if we can fill in the gap from the
421 secondary packets. */
425 if ((stat2 = decode_length(buf, len, &ptr, &count)) < 0)
427 for (i = 0; i < count && total_count + i < ARRAY_LEN(bufs); i++) {
428 if ((stat1 = decode_open_type(buf, len, &ptr, &bufs[total_count + i], &lengths[total_count + i])) != 0) {
431 /* valid secondaries can contain zero-length packets that should be ignored */
432 if (!bufs[total_count + i] || !lengths[total_count + i]) {
433 /* drop the count of items to process and reuse the buffers that were just set */
440 while (stat2 > 0 && total_count < ARRAY_LEN(bufs));
441 /* Step through in reverse order, so we go oldest to newest */
442 for (i = total_count; i > 0; i--) {
443 if (seq_no - i >= s->rx_seq_no) {
444 /* This one wasn't seen before */
445 /* Decode the secondary IFP packet */
446 ast_debug(3, "Recovering lost packet via secondary %d, len %d\n", seq_no - i, lengths[i - 1]);
447 s->f[ifp_no].frametype = AST_FRAME_MODEM;
448 s->f[ifp_no].subclass.integer = AST_MODEM_T38;
450 s->f[ifp_no].mallocd = 0;
451 s->f[ifp_no].seqno = seq_no - i;
452 s->f[ifp_no].datalen = lengths[i - 1];
453 s->f[ifp_no].data.ptr = (uint8_t *) bufs[i - 1];
454 s->f[ifp_no].offset = 0;
455 s->f[ifp_no].src = "UDPTL";
457 AST_LIST_NEXT(&s->f[ifp_no - 1], frame_list) = &s->f[ifp_no];
458 AST_LIST_NEXT(&s->f[ifp_no], frame_list) = NULL;
469 /* FEC mode for error recovery */
470 /* Our buffers cannot tolerate overlength IFP packets in FEC mode */
471 if (ifp_len > LOCAL_FAX_MAX_DATAGRAM)
473 /* Update any missed slots in the buffer */
474 for ( ; seq_no > s->rx_seq_no; s->rx_seq_no++) {
475 x = s->rx_seq_no & UDPTL_BUF_MASK;
476 s->rx[x].buf_len = -1;
477 s->rx[x].fec_len[0] = 0;
478 s->rx[x].fec_span = 0;
479 s->rx[x].fec_entries = 0;
482 x = seq_no & UDPTL_BUF_MASK;
484 memset(repaired, 0, sizeof(repaired));
486 /* Save the new IFP packet */
487 memcpy(s->rx[x].buf, ifp, ifp_len);
488 s->rx[x].buf_len = ifp_len;
491 /* Decode the FEC packets */
492 /* The span is defined as an unconstrained integer, but will never be more
493 than a small value. */
499 s->rx[x].fec_span = span;
501 /* The number of entries is defined as a length, but will only ever be a small
502 value. Treat it as such. */
505 entries = buf[ptr++];
506 if (entries > MAX_FEC_ENTRIES) {
509 s->rx[x].fec_entries = entries;
511 /* Decode the elements */
512 for (i = 0; i < entries; i++) {
513 if ((stat1 = decode_open_type(buf, len, &ptr, &data, &s->rx[x].fec_len[i])) != 0)
515 if (s->rx[x].fec_len[i] > LOCAL_FAX_MAX_DATAGRAM)
518 /* Save the new FEC data */
519 memcpy(s->rx[x].fec[i], data, s->rx[x].fec_len[i]);
521 fprintf(stderr, "FEC: ");
522 for (j = 0; j < s->rx[x].fec_len[i]; j++)
523 fprintf(stderr, "%02X ", data[j]);
524 fprintf(stderr, "\n");
528 /* See if we can reconstruct anything which is missing */
529 /* TODO: this does not comprehensively hunt back and repair everything that is possible */
530 for (l = x; l != ((x - (16 - span*entries)) & UDPTL_BUF_MASK); l = (l - 1) & UDPTL_BUF_MASK) {
532 if (s->rx[l].fec_len[0] <= 0)
534 for (m = 0; m < s->rx[l].fec_entries; m++) {
537 int limit = (l + m) & UDPTL_BUF_MASK;
538 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) {
539 if (s->rx[k].buf_len <= 0)
540 which = (which == -1) ? k : -2;
544 for (j = 0; j < s->rx[l].fec_len[m]; j++) {
545 s->rx[which].buf[j] = s->rx[l].fec[m][j];
546 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)
547 s->rx[which].buf[j] ^= (s->rx[k].buf_len > j) ? s->rx[k].buf[j] : 0;
549 s->rx[which].buf_len = s->rx[l].fec_len[m];
550 repaired[which] = TRUE;
554 /* Now play any new packets forwards in time */
555 for (l = (x + 1) & UDPTL_BUF_MASK, j = seq_no - UDPTL_BUF_MASK; l != x; l = (l + 1) & UDPTL_BUF_MASK, j++) {
557 //fprintf(stderr, "Fixed packet %d, len %d\n", j, l);
558 s->f[ifp_no].frametype = AST_FRAME_MODEM;
559 s->f[ifp_no].subclass.integer = AST_MODEM_T38;
561 s->f[ifp_no].mallocd = 0;
562 s->f[ifp_no].seqno = j;
563 s->f[ifp_no].datalen = s->rx[l].buf_len;
564 s->f[ifp_no].data.ptr = s->rx[l].buf;
565 s->f[ifp_no].offset = 0;
566 s->f[ifp_no].src = "UDPTL";
568 AST_LIST_NEXT(&s->f[ifp_no - 1], frame_list) = &s->f[ifp_no];
569 AST_LIST_NEXT(&s->f[ifp_no], frame_list) = NULL;
575 /* If packets are received out of sequence, we may have already processed this packet from the error
576 recovery information in a packet already received. */
577 if (seq_no >= s->rx_seq_no) {
578 /* Decode the primary IFP packet */
579 s->f[ifp_no].frametype = AST_FRAME_MODEM;
580 s->f[ifp_no].subclass.integer = AST_MODEM_T38;
582 s->f[ifp_no].mallocd = 0;
583 s->f[ifp_no].seqno = seq_no;
584 s->f[ifp_no].datalen = ifp_len;
585 s->f[ifp_no].data.ptr = (uint8_t *) ifp;
586 s->f[ifp_no].offset = 0;
587 s->f[ifp_no].src = "UDPTL";
589 AST_LIST_NEXT(&s->f[ifp_no - 1], frame_list) = &s->f[ifp_no];
590 AST_LIST_NEXT(&s->f[ifp_no], frame_list) = NULL;
595 s->rx_seq_no = seq_no + 1;
598 /*- End of function --------------------------------------------------------*/
600 static int udptl_build_packet(struct ast_udptl *s, uint8_t *buf, unsigned int buflen, uint8_t *ifp, unsigned int ifp_len)
602 uint8_t fec[LOCAL_FAX_MAX_DATAGRAM * 2] = { 0, };
614 seq = s->tx_seq_no & 0xFFFF;
616 /* Map the sequence number to an entry in the circular buffer */
617 entry = seq & UDPTL_BUF_MASK;
619 /* We save the message in a circular buffer, for generating FEC or
620 redundancy sets later on. */
621 s->tx[entry].buf_len = ifp_len;
622 memcpy(s->tx[entry].buf, ifp, ifp_len);
624 /* Build the UDPTLPacket */
627 /* Encode the sequence number */
628 buf[len++] = (seq >> 8) & 0xFF;
629 buf[len++] = seq & 0xFF;
631 /* Encode the primary IFP packet */
632 if (encode_open_type(s, buf, buflen, &len, ifp, ifp_len) < 0)
635 /* Encode the appropriate type of error recovery information */
636 switch (s->error_correction_scheme)
638 case UDPTL_ERROR_CORRECTION_NONE:
639 /* Encode the error recovery type */
641 /* The number of entries will always be zero, so it is pointless allowing
642 for the fragmented case here. */
643 if (encode_length(buf, &len, 0) < 0)
646 case UDPTL_ERROR_CORRECTION_REDUNDANCY:
647 /* Encode the error recovery type */
649 if (s->tx_seq_no > s->error_correction_entries)
650 entries = s->error_correction_entries;
652 entries = s->tx_seq_no;
653 /* The number of entries will always be small, so it is pointless allowing
654 for the fragmented case here. */
655 if (encode_length(buf, &len, entries) < 0)
657 /* Encode the elements */
658 for (i = 0; i < entries; i++) {
659 j = (entry - i - 1) & UDPTL_BUF_MASK;
660 if (encode_open_type(s, buf, buflen, &len, s->tx[j].buf, s->tx[j].buf_len) < 0) {
661 ast_debug(1, "UDPTL (%s): Encoding failed at i=%d, j=%d\n",
667 case UDPTL_ERROR_CORRECTION_FEC:
668 span = s->error_correction_span;
669 entries = s->error_correction_entries;
670 if (seq < s->error_correction_span*s->error_correction_entries) {
671 /* In the initial stages, wind up the FEC smoothly */
672 entries = seq/s->error_correction_span;
673 if (seq < s->error_correction_span)
676 /* Encode the error recovery type */
678 /* Span is defined as an inconstrained integer, which it dumb. It will only
679 ever be a small value. Treat it as such. */
682 /* The number of entries is defined as a length, but will only ever be a small
683 value. Treat it as such. */
684 buf[len++] = entries;
685 for (m = 0; m < entries; m++) {
686 /* Make an XOR'ed entry the maximum length */
687 limit = (entry + m) & UDPTL_BUF_MASK;
689 for (i = (limit - span*entries) & UDPTL_BUF_MASK; i != limit; i = (i + entries) & UDPTL_BUF_MASK) {
690 if (high_tide < s->tx[i].buf_len) {
691 for (j = 0; j < high_tide; j++)
692 fec[j] ^= s->tx[i].buf[j];
693 for ( ; j < s->tx[i].buf_len; j++)
694 fec[j] = s->tx[i].buf[j];
695 high_tide = s->tx[i].buf_len;
697 for (j = 0; j < s->tx[i].buf_len; j++)
698 fec[j] ^= s->tx[i].buf[j];
701 if (encode_open_type(s, buf, buflen, &len, fec, high_tide) < 0)
711 int ast_udptl_fd(const struct ast_udptl *udptl)
716 void ast_udptl_set_data(struct ast_udptl *udptl, void *data)
721 void ast_udptl_set_callback(struct ast_udptl *udptl, ast_udptl_callback callback)
723 udptl->callback = callback;
726 void ast_udptl_setnat(struct ast_udptl *udptl, int nat)
731 static int udptlread(int *id, int fd, short events, void *cbdata)
733 struct ast_udptl *udptl = cbdata;
736 if ((f = ast_udptl_read(udptl))) {
738 udptl->callback(udptl, f, udptl->data);
743 struct ast_frame *ast_udptl_read(struct ast_udptl *udptl)
746 struct ast_sockaddr addr;
749 buf = udptl->rawdata + AST_FRIENDLY_OFFSET;
751 /* Cache where the header will go */
752 res = ast_recvfrom(udptl->fd,
754 sizeof(udptl->rawdata) - AST_FRIENDLY_OFFSET,
759 ast_log(LOG_WARNING, "UDPTL (%s): read error: %s\n",
760 LOG_TAG(udptl), strerror(errno));
761 ast_assert(errno != EBADF);
762 return &ast_null_frame;
765 /* Ignore if the other side hasn't been given an address yet. */
766 if (ast_sockaddr_isnull(&udptl->them)) {
767 return &ast_null_frame;
771 /* Send to whoever sent to us */
772 if (ast_sockaddr_cmp(&udptl->them, &addr)) {
773 ast_sockaddr_copy(&udptl->them, &addr);
774 ast_debug(1, "UDPTL (%s): NAT, Using address %s\n",
775 LOG_TAG(udptl), ast_sockaddr_stringify(&udptl->them));
779 if (udptl_debug_test_addr(&addr)) {
782 /* Decode sequence number just for verbose message. */
787 seq_no = (buf[0] << 8) | buf[1];
790 ast_verb(1, "UDPTL (%s): packet from %s (seq %d, len %d)\n",
791 LOG_TAG(udptl), ast_sockaddr_stringify(&addr), seq_no, res);
793 if (udptl_rx_packet(udptl, buf, res) < 1) {
794 return &ast_null_frame;
800 static void calculate_local_max_datagram(struct ast_udptl *udptl)
802 unsigned int new_max = 0;
804 if (udptl->local_max_ifp == -1) {
805 ast_log(LOG_WARNING, "UDPTL (%s): Cannot calculate local_max_datagram before local_max_ifp has been set.\n",
807 udptl->local_max_datagram = -1;
811 /* calculate the amount of space required to receive an IFP
812 * of the maximum size supported by the application/endpoint
813 * that we are delivering them to (local endpoint), and add
814 * the amount of space required to support the selected
815 * error correction mode
817 switch (udptl->error_correction_scheme) {
818 case UDPTL_ERROR_CORRECTION_NONE:
819 /* need room for sequence number, length indicator, redundancy
820 * indicator and following length indicator
822 new_max = 5 + udptl->local_max_ifp;
824 case UDPTL_ERROR_CORRECTION_REDUNDANCY:
825 /* need room for sequence number, length indicators, plus
826 * room for up to 3 redundancy packets
828 new_max = 5 + udptl->local_max_ifp + 2 + (3 * udptl->local_max_ifp);
830 case UDPTL_ERROR_CORRECTION_FEC:
831 /* need room for sequence number, length indicators and a
832 * a single IFP of the maximum size expected
834 new_max = 5 + udptl->local_max_ifp + 4 + udptl->local_max_ifp;
837 /* add 5% extra space for insurance, but no larger than LOCAL_FAX_MAX_DATAGRAM */
838 udptl->local_max_datagram = MIN(new_max * 1.05, LOCAL_FAX_MAX_DATAGRAM);
841 static void calculate_far_max_ifp(struct ast_udptl *udptl)
843 unsigned new_max = 0;
845 if (udptl->far_max_datagram == -1) {
846 ast_log(LOG_WARNING, "UDPTL (%s): Cannot calculate far_max_ifp before far_max_datagram has been set.\n",
848 udptl->far_max_ifp = -1;
852 /* the goal here is to supply the local endpoint (application
853 * or bridged channel) a maximum IFP value that will allow it
854 * to effectively and efficiently transfer image data at its
855 * selected bit rate, taking into account the selected error
856 * correction mode, but without overrunning the far endpoint's
857 * datagram buffer. this is complicated by the fact that some
858 * far endpoints send us bogus (small) max datagram values,
859 * which would result in either buffer overrun or no error
860 * correction. we try to accomodate those, but if the supplied
861 * value is too small to do so, we'll emit warning messages and
862 * the user will have to use configuration options to override
863 * the max datagram value supplied by the far endpoint.
865 switch (udptl->error_correction_scheme) {
866 case UDPTL_ERROR_CORRECTION_NONE:
867 /* need room for sequence number, length indicator, redundancy
868 * indicator and following length indicator
870 new_max = udptl->far_max_datagram - 5;
872 case UDPTL_ERROR_CORRECTION_REDUNDANCY:
873 /* for this case, we'd like to send as many error correction entries
874 * as possible (up to the number we're configured for), but we'll settle
875 * for sending fewer if the configured number would cause the
876 * calculated max IFP to be too small for effective operation
878 * need room for sequence number, length indicators and the
879 * configured number of redundant packets
881 * note: we purposely don't allow error_correction_entries to drop to
882 * zero in this loop; we'd rather send smaller IFPs (and thus reduce
883 * the image data transfer rate) than sacrifice redundancy completely
886 new_max = (udptl->far_max_datagram - 8) / (udptl->error_correction_entries + 1);
888 if ((new_max < 80) && (udptl->error_correction_entries > 1)) {
889 /* the max ifp is not large enough, subtract an
890 * error correction entry and calculate again
892 --udptl->error_correction_entries;
898 case UDPTL_ERROR_CORRECTION_FEC:
899 /* need room for sequence number, length indicators and a
900 * a single IFP of the maximum size expected
902 new_max = (udptl->far_max_datagram - 10) / 2;
905 /* subtract 5% of space for insurance */
906 udptl->far_max_ifp = new_max * 0.95;
909 enum ast_t38_ec_modes ast_udptl_get_error_correction_scheme(const struct ast_udptl *udptl)
911 return udptl->error_correction_scheme;
914 void ast_udptl_set_error_correction_scheme(struct ast_udptl *udptl, enum ast_t38_ec_modes ec)
916 udptl->error_correction_scheme = ec;
918 case UDPTL_ERROR_CORRECTION_FEC:
919 udptl->error_correction_scheme = UDPTL_ERROR_CORRECTION_FEC;
920 if (udptl->error_correction_entries == 0) {
921 udptl->error_correction_entries = 3;
923 if (udptl->error_correction_span == 0) {
924 udptl->error_correction_span = 3;
927 case UDPTL_ERROR_CORRECTION_REDUNDANCY:
928 udptl->error_correction_scheme = UDPTL_ERROR_CORRECTION_REDUNDANCY;
929 if (udptl->error_correction_entries == 0) {
930 udptl->error_correction_entries = 3;
937 /* reset calculated values so they'll be computed again */
938 udptl->local_max_datagram = -1;
939 udptl->far_max_ifp = -1;
942 void ast_udptl_set_local_max_ifp(struct ast_udptl *udptl, unsigned int max_ifp)
944 /* make sure max_ifp is a positive value since a cast will take place when
945 * when setting local_max_ifp */
946 if ((signed int) max_ifp > 0) {
947 udptl->local_max_ifp = max_ifp;
948 /* reset calculated values so they'll be computed again */
949 udptl->local_max_datagram = -1;
953 unsigned int ast_udptl_get_local_max_datagram(struct ast_udptl *udptl)
955 if (udptl->local_max_datagram == -1) {
956 calculate_local_max_datagram(udptl);
959 /* this function expects a unsigned value in return. */
960 if (udptl->local_max_datagram < 0) {
963 return udptl->local_max_datagram;
966 void ast_udptl_set_far_max_datagram(struct ast_udptl *udptl, unsigned int max_datagram)
968 if (!max_datagram || (max_datagram > FAX_MAX_DATAGRAM_LIMIT)) {
969 udptl->far_max_datagram = DEFAULT_FAX_MAX_DATAGRAM;
971 udptl->far_max_datagram = max_datagram;
973 /* reset calculated values so they'll be computed again */
974 udptl->far_max_ifp = -1;
977 unsigned int ast_udptl_get_far_max_datagram(const struct ast_udptl *udptl)
979 if (udptl->far_max_datagram < 0) {
982 return udptl->far_max_datagram;
985 unsigned int ast_udptl_get_far_max_ifp(struct ast_udptl *udptl)
987 if (udptl->far_max_ifp == -1) {
988 calculate_far_max_ifp(udptl);
991 if (udptl->far_max_ifp < 0) {
994 return udptl->far_max_ifp;
997 struct ast_udptl *ast_udptl_new_with_bindaddr(struct ast_sched_context *sched, struct io_context *io, int callbackmode, struct ast_sockaddr *addr)
999 struct ast_udptl *udptl;
1004 RAII_VAR(struct udptl_config *, cfg, ao2_global_obj_ref(globals), ao2_cleanup);
1006 if (!cfg || !cfg->general) {
1007 ast_log(LOG_ERROR, "Could not access global udptl options!\n");
1011 if (!(udptl = ast_calloc(1, sizeof(*udptl)))) {
1015 udptl->error_correction_span = cfg->general->fecspan;
1016 udptl->error_correction_entries = cfg->general->fecentries;
1018 udptl->far_max_datagram = -1;
1019 udptl->far_max_ifp = -1;
1020 udptl->local_max_ifp = -1;
1021 udptl->local_max_datagram = -1;
1023 for (i = 0; i <= UDPTL_BUF_MASK; i++) {
1024 udptl->rx[i].buf_len = -1;
1025 udptl->tx[i].buf_len = -1;
1028 if ((udptl->fd = socket(ast_sockaddr_is_ipv6(addr) ?
1029 AF_INET6 : AF_INET, SOCK_DGRAM, 0)) < 0) {
1031 ast_log(LOG_WARNING, "Unable to allocate socket: %s\n", strerror(errno));
1034 flags = fcntl(udptl->fd, F_GETFL);
1035 fcntl(udptl->fd, F_SETFL, flags | O_NONBLOCK);
1038 if (cfg->general->nochecksums)
1039 setsockopt(udptl->fd, SOL_SOCKET, SO_NO_CHECK, &cfg->general->nochecksums, sizeof(cfg->general->nochecksums));
1042 /* Find us a place */
1043 x = (cfg->general->start == cfg->general->end) ? cfg->general->start : (ast_random() % (cfg->general->end - cfg->general->start)) + cfg->general->start;
1044 if (cfg->general->use_even_ports && (x & 1)) {
1049 ast_sockaddr_copy(&udptl->us, addr);
1050 ast_sockaddr_set_port(&udptl->us, x);
1051 if (ast_bind(udptl->fd, &udptl->us) == 0) {
1054 if (errno != EADDRINUSE) {
1055 ast_log(LOG_WARNING, "Unexpected bind error: %s\n", strerror(errno));
1060 if (cfg->general->use_even_ports) {
1065 if (x > cfg->general->end)
1066 x = cfg->general->start;
1067 if (x == startplace) {
1068 ast_log(LOG_WARNING, "No UDPTL ports remaining\n");
1074 if (io && sched && callbackmode) {
1075 /* Operate this one in a callback mode */
1076 udptl->sched = sched;
1078 udptl->ioid = ast_io_add(udptl->io, udptl->fd, udptlread, AST_IO_IN, udptl);
1084 void ast_udptl_set_tag(struct ast_udptl *udptl, const char *format, ...)
1088 ast_free(udptl->tag);
1090 va_start(ap, format);
1091 if (ast_vasprintf(&udptl->tag, format, ap) == -1) {
1097 int ast_udptl_setqos(struct ast_udptl *udptl, unsigned int tos, unsigned int cos)
1099 return ast_set_qos(udptl->fd, tos, cos, "UDPTL");
1102 void ast_udptl_set_peer(struct ast_udptl *udptl, const struct ast_sockaddr *them)
1104 ast_sockaddr_copy(&udptl->them, them);
1107 void ast_udptl_get_peer(const struct ast_udptl *udptl, struct ast_sockaddr *them)
1109 ast_sockaddr_copy(them, &udptl->them);
1112 void ast_udptl_get_us(const struct ast_udptl *udptl, struct ast_sockaddr *us)
1114 ast_sockaddr_copy(us, &udptl->us);
1117 void ast_udptl_stop(struct ast_udptl *udptl)
1119 ast_sockaddr_setnull(&udptl->them);
1122 void ast_udptl_destroy(struct ast_udptl *udptl)
1125 ast_io_remove(udptl->io, udptl->ioid);
1129 ast_free(udptl->tag);
1133 int ast_udptl_write(struct ast_udptl *s, struct ast_frame *f)
1136 unsigned int len = f->datalen;
1137 /* if no max datagram size is provided, use default value */
1138 const int bufsize = (s->far_max_datagram > 0) ? s->far_max_datagram : DEFAULT_FAX_MAX_DATAGRAM;
1139 uint8_t buf[bufsize];
1141 memset(buf, 0, sizeof(buf));
1143 /* If we have no peer, return immediately */
1144 if (ast_sockaddr_isnull(&s->them)) {
1148 /* If there is no data length, return immediately */
1149 if (f->datalen == 0)
1152 if ((f->frametype != AST_FRAME_MODEM) ||
1153 (f->subclass.integer != AST_MODEM_T38)) {
1154 ast_log(LOG_WARNING, "UDPTL (%s): UDPTL can only send T.38 data.\n",
1159 if (len > s->far_max_ifp) {
1160 ast_log(LOG_WARNING,
1161 "UDPTL (%s): UDPTL asked to send %d bytes of IFP when far end only prepared to accept %d bytes; data loss will occur."
1162 "You may need to override the T38FaxMaxDatagram value for this endpoint in the channel driver configuration.\n",
1163 LOG_TAG(s), len, s->far_max_ifp);
1164 len = s->far_max_ifp;
1167 /* Save seq_no for debug output because udptl_build_packet increments it */
1168 seq = s->tx_seq_no & 0xFFFF;
1170 /* Cook up the UDPTL packet, with the relevant EC info. */
1171 len = udptl_build_packet(s, buf, sizeof(buf), f->data.ptr, len);
1173 if ((signed int) len > 0 && !ast_sockaddr_isnull(&s->them)) {
1174 if (ast_sendto(s->fd, buf, len, 0, &s->them) < 0) {
1175 ast_log(LOG_NOTICE, "UDPTL (%s): Transmission error to %s: %s\n",
1176 LOG_TAG(s), ast_sockaddr_stringify(&s->them), strerror(errno));
1178 if (udptl_debug_test_addr(&s->them)) {
1179 ast_verb(1, "UDPTL (%s): packet to %s (seq %d, len %d)\n",
1180 LOG_TAG(s), ast_sockaddr_stringify(&s->them), seq, len);
1187 static char *handle_cli_udptl_set_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1191 e->command = "udptl set debug {on|off|ip}";
1193 "Usage: udptl set debug {on|off|ip host[:port]}\n"
1194 " Enable or disable dumping of UDPTL packets.\n"
1195 " If ip is specified, limit the dumped packets to those to and from\n"
1196 " the specified 'host' with optional port.\n";
1202 if (a->argc < 4 || a->argc > 5)
1203 return CLI_SHOWUSAGE;
1206 if (!strncasecmp(a->argv[3], "on", 2)) {
1208 memset(&udptldebugaddr, 0, sizeof(udptldebugaddr));
1209 ast_cli(a->fd, "UDPTL Debugging Enabled\n");
1210 } else if (!strncasecmp(a->argv[3], "off", 3)) {
1212 ast_cli(a->fd, "UDPTL Debugging Disabled\n");
1214 return CLI_SHOWUSAGE;
1217 struct ast_sockaddr *addrs;
1218 if (strncasecmp(a->argv[3], "ip", 2))
1219 return CLI_SHOWUSAGE;
1220 if (!ast_sockaddr_resolve(&addrs, a->argv[4], 0, 0)) {
1221 return CLI_SHOWUSAGE;
1223 ast_sockaddr_copy(&udptldebugaddr, &addrs[0]);
1224 ast_cli(a->fd, "UDPTL Debugging Enabled for IP: %s\n", ast_sockaddr_stringify(&udptldebugaddr));
1232 static char *handle_cli_show_config(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1234 RAII_VAR(struct udptl_config *, cfg, NULL, ao2_cleanup);
1238 e->command = "udptl show config";
1240 "Usage: udptl show config\n"
1241 " Display UDPTL configuration options\n";
1247 if (!(cfg = ao2_global_obj_ref(globals))) {
1251 ast_cli(a->fd, "UDPTL Global options\n");
1252 ast_cli(a->fd, "--------------------\n");
1253 ast_cli(a->fd, "udptlstart: %u\n", cfg->general->start);
1254 ast_cli(a->fd, "udptlend: %u\n", cfg->general->end);
1255 ast_cli(a->fd, "udptlfecentries: %u\n", cfg->general->fecentries);
1256 ast_cli(a->fd, "udptlfecspan: %u\n", cfg->general->fecspan);
1257 ast_cli(a->fd, "use_even_ports: %s\n", AST_CLI_YESNO(cfg->general->use_even_ports));
1258 ast_cli(a->fd, "udptlchecksums: %s\n", AST_CLI_YESNO(!cfg->general->nochecksums));
1263 static struct ast_cli_entry cli_udptl[] = {
1264 AST_CLI_DEFINE(handle_cli_udptl_set_debug, "Enable/Disable UDPTL debugging"),
1265 AST_CLI_DEFINE(handle_cli_show_config, "Show UDPTL config options"),
1268 static void udptl_config_destructor(void *obj)
1270 struct udptl_config *cfg = obj;
1271 ao2_cleanup(cfg->general);
1274 static void *udptl_snapshot_alloc(void)
1276 struct udptl_config *cfg;
1278 if (!(cfg = ao2_alloc(sizeof(*cfg), udptl_config_destructor))) {
1281 if (!(cfg->general = ao2_alloc(sizeof(*cfg->general), NULL))) {
1289 static int removed_options_handler(const struct aco_option *opt, struct ast_variable *var, void *obj)
1291 if (!strcasecmp(var->name, "t38faxudpec")) {
1292 ast_log(LOG_WARNING, "t38faxudpec in udptl.conf is no longer supported; use the t38pt_udptl configuration option in sip.conf instead.\n");
1293 } else if (!strcasecmp(var->name, "t38faxmaxdatagram")) {
1294 ast_log(LOG_WARNING, "t38faxmaxdatagram in udptl.conf is no longer supported; value is now supplied by T.38 applications.\n");
1299 static void __ast_udptl_reload(int reload)
1301 if (aco_process_config(&cfg_info, reload) == ACO_PROCESS_ERROR) {
1303 RAII_VAR(struct udptl_config *, udptl_cfg, udptl_snapshot_alloc(), ao2_cleanup);
1305 if (aco_set_defaults(&general_option, "general", udptl_cfg->general)) {
1306 ast_log(LOG_ERROR, "Failed to load udptl.conf and failed to initialize defaults.\n");
1310 ast_log(LOG_NOTICE, "Could not load udptl config; using defaults\n");
1311 ao2_global_obj_replace_unref(globals, udptl_cfg);
1316 static int udptl_pre_apply_config(void) {
1317 struct udptl_config *cfg = aco_pending_config(&cfg_info);
1319 if (!cfg->general) {
1324 if (cfg->general->nochecksums) {
1325 ast_log(LOG_WARNING, "Disabling UDPTL checksums is not supported on this operating system!\n");
1326 cfg->general->nochecksums = 0;
1330 /* Fix up any global config values that we can handle before replacing the config */
1331 if (cfg->general->use_even_ports && (cfg->general->start & 1)) {
1332 ++cfg->general->start;
1333 ast_log(LOG_NOTICE, "Odd numbered udptlstart specified but use_even_ports enabled. udptlstart is now %d\n", cfg->general->start);
1335 if (cfg->general->start > cfg->general->end) {
1336 ast_log(LOG_WARNING, "Unreasonable values for UDPTL start/end ports; defaulting to %s-%s.\n", __stringify(DEFAULT_UDPTLSTART), __stringify(DEFAULT_UDPTLEND));
1337 cfg->general->start = DEFAULT_UDPTLSTART;
1338 cfg->general->end = DEFAULT_UDPTLEND;
1340 if (cfg->general->use_even_ports && (cfg->general->end & 1)) {
1341 --cfg->general->end;
1342 ast_log(LOG_NOTICE, "Odd numbered udptlend specified but use_even_ports enabled. udptlend is now %d\n", cfg->general->end);
1348 int ast_udptl_reload(void)
1350 __ast_udptl_reload(1);
1356 * \brief Clean up resources on Asterisk shutdown
1358 static void udptl_shutdown(void)
1360 ast_cli_unregister_multiple(cli_udptl, ARRAY_LEN(cli_udptl));
1361 ao2_t_global_obj_release(globals, "Unref udptl global container in shutdown");
1362 aco_info_destroy(&cfg_info);
1365 void ast_udptl_init(void)
1367 if (aco_info_init(&cfg_info)) {
1371 aco_option_register(&cfg_info, "udptlstart", ACO_EXACT, general_options, __stringify(DEFAULT_UDPTLSTART),
1372 OPT_UINT_T, PARSE_IN_RANGE | PARSE_DEFAULT,
1373 FLDSET(struct udptl_global_options, start), DEFAULT_UDPTLSTART, 1024, 65535);
1375 aco_option_register(&cfg_info, "udptlend", ACO_EXACT, general_options, __stringify(DEFAULT_UDPTLEND),
1376 OPT_UINT_T, PARSE_IN_RANGE | PARSE_DEFAULT,
1377 FLDSET(struct udptl_global_options, end), DEFAULT_UDPTLEND, 1024, 65535);
1379 aco_option_register(&cfg_info, "udptlfecentries", ACO_EXACT, general_options, NULL,
1380 OPT_UINT_T, PARSE_IN_RANGE | PARSE_RANGE_DEFAULTS,
1381 FLDSET(struct udptl_global_options, fecentries), 1, MAX_FEC_ENTRIES);
1383 aco_option_register(&cfg_info, "udptlfecspan", ACO_EXACT, general_options, NULL,
1384 OPT_UINT_T, PARSE_IN_RANGE | PARSE_RANGE_DEFAULTS,
1385 FLDSET(struct udptl_global_options, fecspan), 1, MAX_FEC_SPAN);
1387 aco_option_register(&cfg_info, "udptlchecksums", ACO_EXACT, general_options, "yes",
1388 OPT_BOOL_T, 0, FLDSET(struct udptl_global_options, nochecksums));
1390 aco_option_register(&cfg_info, "use_even_ports", ACO_EXACT, general_options, "no",
1391 OPT_BOOL_T, 1, FLDSET(struct udptl_global_options, use_even_ports));
1393 aco_option_register_custom(&cfg_info, "t38faxudpec", ACO_EXACT, general_options, NULL, removed_options_handler, 0);
1394 aco_option_register_custom(&cfg_info, "t38faxmaxdatagram", ACO_EXACT, general_options, NULL, removed_options_handler, 0);
1396 __ast_udptl_reload(0);
1398 ast_cli_register_multiple(cli_udptl, ARRAY_LEN(cli_udptl));
1400 ast_register_atexit(udptl_shutdown);