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"
83 #define UDPTL_MTU 1200
92 #define LOG_TAG(u) S_OR(u->tag, "no tag")
94 #define DEFAULT_UDPTLSTART 4000
95 #define DEFAULT_UDPTLEND 4999
97 static int udptldebug; /*!< Are we debugging? */
98 static struct ast_sockaddr udptldebugaddr; /*!< Debug packets to/from this host */
100 #define LOCAL_FAX_MAX_DATAGRAM 1400
101 #define DEFAULT_FAX_MAX_DATAGRAM 400
102 #define FAX_MAX_DATAGRAM_LIMIT 1400
103 #define MAX_FEC_ENTRIES 5
104 #define MAX_FEC_SPAN 5
106 #define UDPTL_BUF_MASK 15
110 uint8_t buf[LOCAL_FAX_MAX_DATAGRAM];
111 } udptl_fec_tx_buffer_t;
115 uint8_t buf[LOCAL_FAX_MAX_DATAGRAM];
116 unsigned int fec_len[MAX_FEC_ENTRIES];
117 uint8_t fec[MAX_FEC_ENTRIES][LOCAL_FAX_MAX_DATAGRAM];
118 unsigned int fec_span;
119 unsigned int fec_entries;
120 } udptl_fec_rx_buffer_t;
122 /*! \brief Structure for an UDPTL session */
126 struct ast_frame f[16];
127 unsigned char rawdata[8192 + AST_FRIENDLY_OFFSET];
128 unsigned int lasteventseqn;
131 struct ast_sockaddr us;
132 struct ast_sockaddr them;
134 struct ast_sched_context *sched;
135 struct io_context *io;
138 ast_udptl_callback callback;
140 /*! This option indicates the error correction scheme used in transmitted UDPTL
141 * packets and expected in received UDPTL packets.
143 enum ast_t38_ec_modes error_correction_scheme;
145 /*! This option indicates the number of error correction entries transmitted in
146 * UDPTL packets and expected in received UDPTL packets.
148 unsigned int error_correction_entries;
150 /*! This option indicates the span of the error correction entries in transmitted
151 * UDPTL packets (FEC only).
153 unsigned int error_correction_span;
155 /*! The maximum size UDPTL packet that can be accepted by
158 int far_max_datagram;
160 /*! The maximum size UDPTL packet that we are prepared to
161 * accept, or -1 if it hasn't been calculated since the last
162 * changes were applied to the UDPTL structure.
164 int local_max_datagram;
166 /*! The maximum IFP that can be submitted for sending
167 * to the remote device. Calculated from far_max_datagram,
168 * error_correction_scheme and error_correction_entries,
169 * or -1 if it hasn't been calculated since the last
170 * changes were applied to the UDPTL structure.
174 /*! The maximum IFP that the local endpoint is prepared
175 * to accept. Along with error_correction_scheme and
176 * error_correction_entries, used to calculate local_max_datagram.
180 unsigned int tx_seq_no;
181 unsigned int rx_seq_no;
183 udptl_fec_tx_buffer_t tx[UDPTL_BUF_MASK + 1];
184 udptl_fec_rx_buffer_t rx[UDPTL_BUF_MASK + 1];
187 static AST_RWLIST_HEAD_STATIC(protos, ast_udptl_protocol);
189 struct udptl_global_options {
190 unsigned int start; /*< The UDPTL start port */
191 unsigned int end; /*< The UDPTL end port */
192 unsigned int fecentries;
193 unsigned int fecspan;
194 unsigned int nochecksums;
195 unsigned int use_even_ports;
198 static AO2_GLOBAL_OBJ_STATIC(globals);
200 struct udptl_config {
201 struct udptl_global_options *general;
204 static void *udptl_snapshot_alloc(void);
205 static int udptl_pre_apply_config(void);
207 static struct aco_type general_option = {
209 .category_match = ACO_WHITELIST,
210 .item_offset = offsetof(struct udptl_config, general),
211 .category = "^general$",
214 static struct aco_type *general_options[] = ACO_TYPES(&general_option);
216 static struct aco_file udptl_conf = {
217 .filename = "udptl.conf",
218 .types = ACO_TYPES(&general_option),
221 CONFIG_INFO_STANDARD(cfg_info, globals, udptl_snapshot_alloc,
222 .files = ACO_FILES(&udptl_conf),
223 .pre_apply_config = udptl_pre_apply_config,
226 static inline int udptl_debug_test_addr(const struct ast_sockaddr *addr)
231 if (ast_sockaddr_isnull(&udptldebugaddr)) {
235 if (ast_sockaddr_port(&udptldebugaddr)) {
236 return !ast_sockaddr_cmp(&udptldebugaddr, addr);
238 return !ast_sockaddr_cmp_addr(&udptldebugaddr, addr);
242 static int decode_length(uint8_t *buf, unsigned int limit, unsigned int *len, unsigned int *pvalue)
246 if ((buf[*len] & 0x80) == 0) {
251 if ((buf[*len] & 0x40) == 0) {
252 if (*len == limit - 1)
254 *pvalue = (buf[*len] & 0x3F) << 8;
256 *pvalue |= buf[*len];
260 *pvalue = (buf[*len] & 0x3F) << 14;
262 /* We have a fragment. Currently we don't process fragments. */
263 ast_debug(1, "UDPTL packet with length greater than 16K received, decoding will fail\n");
266 /*- End of function --------------------------------------------------------*/
268 static int decode_open_type(uint8_t *buf, unsigned int limit, unsigned int *len, const uint8_t **p_object, unsigned int *p_num_octets)
270 unsigned int octet_cnt = 0;
272 if (decode_length(buf, limit, len, &octet_cnt) != 0)
276 /* Make sure the buffer contains at least the number of bits requested */
277 if ((*len + octet_cnt) > limit)
280 *p_num_octets = octet_cnt;
281 *p_object = &buf[*len];
287 /*- End of function --------------------------------------------------------*/
289 static unsigned int encode_length(uint8_t *buf, unsigned int *len, unsigned int value)
291 unsigned int multiplier;
299 if (value < 0x4000) {
301 /* Set the first bit of the first octet */
302 buf[*len] = ((0x8000 | value) >> 8) & 0xFF;
304 buf[*len] = value & 0xFF;
309 multiplier = (value < 0x10000) ? (value >> 14) : 4;
310 /* Set the first 2 bits of the octet */
311 buf[*len] = 0xC0 | multiplier;
313 return multiplier << 14;
315 /*- End of function --------------------------------------------------------*/
317 static int encode_open_type(const struct ast_udptl *udptl, uint8_t *buf, unsigned int buflen,
318 unsigned int *len, const uint8_t *data, unsigned int num_octets)
321 unsigned int octet_idx;
324 /* If open type is of zero length, add a single zero byte (10.1) */
325 if (num_octets == 0) {
330 /* Encode the open type */
331 for (octet_idx = 0; ; num_octets -= enclen, octet_idx += enclen) {
332 if ((enclen = encode_length(buf, len, num_octets)) < 0)
334 if (enclen + *len > buflen) {
335 ast_log(LOG_ERROR, "UDPTL (%s): Buffer overflow detected (%d + %d > %d)\n",
336 LOG_TAG(udptl), enclen, *len, buflen);
340 memcpy(&buf[*len], &data[octet_idx], enclen);
343 if (enclen >= num_octets)
349 /*- End of function --------------------------------------------------------*/
351 static int udptl_rx_packet(struct ast_udptl *s, uint8_t *buf, unsigned int len)
356 unsigned int ptr; /* an index that keeps track of how much of the UDPTL packet has been processed */
358 const uint8_t *ifp = NULL;
359 const uint8_t *data = NULL;
360 unsigned int ifp_len = 0;
362 const uint8_t *bufs[ARRAY_LEN(s->f) - 1];
363 unsigned int lengths[ARRAY_LEN(s->f) - 1];
370 memset(&s->f[0], 0, sizeof(s->f[0]));
372 /* Decode seq_number */
375 seq_no = (buf[0] << 8) | buf[1];
378 /* Break out the primary packet */
379 if ((stat1 = decode_open_type(buf, len, &ptr, &ifp, &ifp_len)) != 0)
381 /* Decode error_recovery */
384 if ((buf[ptr++] & 0x80) == 0) {
385 /* Secondary packet mode for error recovery */
386 if (seq_no > s->rx_seq_no) {
387 /* We received a later packet than we expected, so we need to check if we can fill in the gap from the
388 secondary packets. */
392 if ((stat2 = decode_length(buf, len, &ptr, &count)) < 0)
394 for (i = 0; i < count && total_count + i < ARRAY_LEN(bufs); i++) {
395 if ((stat1 = decode_open_type(buf, len, &ptr, &bufs[total_count + i], &lengths[total_count + i])) != 0) {
398 /* valid secondaries can contain zero-length packets that should be ignored */
399 if (!bufs[total_count + i] || !lengths[total_count + i]) {
400 /* drop the count of items to process and reuse the buffers that were just set */
407 while (stat2 > 0 && total_count < ARRAY_LEN(bufs));
408 /* Step through in reverse order, so we go oldest to newest */
409 for (i = total_count; i > 0; i--) {
410 if (seq_no - i >= s->rx_seq_no) {
411 /* This one wasn't seen before */
412 /* Decode the secondary IFP packet */
413 ast_debug(3, "Recovering lost packet via secondary %d, len %d\n", seq_no - i, lengths[i - 1]);
414 s->f[ifp_no].frametype = AST_FRAME_MODEM;
415 s->f[ifp_no].subclass.integer = AST_MODEM_T38;
417 s->f[ifp_no].mallocd = 0;
418 s->f[ifp_no].seqno = seq_no - i;
419 s->f[ifp_no].datalen = lengths[i - 1];
420 s->f[ifp_no].data.ptr = (uint8_t *) bufs[i - 1];
421 s->f[ifp_no].offset = 0;
422 s->f[ifp_no].src = "UDPTL";
424 AST_LIST_NEXT(&s->f[ifp_no - 1], frame_list) = &s->f[ifp_no];
425 AST_LIST_NEXT(&s->f[ifp_no], frame_list) = NULL;
436 /* FEC mode for error recovery */
437 /* Our buffers cannot tolerate overlength IFP packets in FEC mode */
438 if (ifp_len > LOCAL_FAX_MAX_DATAGRAM)
440 /* Update any missed slots in the buffer */
441 for ( ; seq_no > s->rx_seq_no; s->rx_seq_no++) {
442 x = s->rx_seq_no & UDPTL_BUF_MASK;
443 s->rx[x].buf_len = -1;
444 s->rx[x].fec_len[0] = 0;
445 s->rx[x].fec_span = 0;
446 s->rx[x].fec_entries = 0;
449 x = seq_no & UDPTL_BUF_MASK;
451 memset(repaired, 0, sizeof(repaired));
453 /* Save the new IFP packet */
454 memcpy(s->rx[x].buf, ifp, ifp_len);
455 s->rx[x].buf_len = ifp_len;
458 /* Decode the FEC packets */
459 /* The span is defined as an unconstrained integer, but will never be more
460 than a small value. */
466 s->rx[x].fec_span = span;
468 /* The number of entries is defined as a length, but will only ever be a small
469 value. Treat it as such. */
472 entries = buf[ptr++];
473 if (entries > MAX_FEC_ENTRIES) {
476 s->rx[x].fec_entries = entries;
478 /* Decode the elements */
479 for (i = 0; i < entries; i++) {
480 if ((stat1 = decode_open_type(buf, len, &ptr, &data, &s->rx[x].fec_len[i])) != 0)
482 if (s->rx[x].fec_len[i] > LOCAL_FAX_MAX_DATAGRAM)
485 /* Save the new FEC data */
486 memcpy(s->rx[x].fec[i], data, s->rx[x].fec_len[i]);
488 fprintf(stderr, "FEC: ");
489 for (j = 0; j < s->rx[x].fec_len[i]; j++)
490 fprintf(stderr, "%02X ", data[j]);
491 fprintf(stderr, "\n");
495 /* See if we can reconstruct anything which is missing */
496 /* TODO: this does not comprehensively hunt back and repair everything that is possible */
497 for (l = x; l != ((x - (16 - span*entries)) & UDPTL_BUF_MASK); l = (l - 1) & UDPTL_BUF_MASK) {
499 if (s->rx[l].fec_len[0] <= 0)
501 for (m = 0; m < s->rx[l].fec_entries; m++) {
504 int limit = (l + m) & UDPTL_BUF_MASK;
505 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) {
506 if (s->rx[k].buf_len <= 0)
507 which = (which == -1) ? k : -2;
511 for (j = 0; j < s->rx[l].fec_len[m]; j++) {
512 s->rx[which].buf[j] = s->rx[l].fec[m][j];
513 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)
514 s->rx[which].buf[j] ^= (s->rx[k].buf_len > j) ? s->rx[k].buf[j] : 0;
516 s->rx[which].buf_len = s->rx[l].fec_len[m];
517 repaired[which] = TRUE;
521 /* Now play any new packets forwards in time */
522 for (l = (x + 1) & UDPTL_BUF_MASK, j = seq_no - UDPTL_BUF_MASK; l != x; l = (l + 1) & UDPTL_BUF_MASK, j++) {
524 //fprintf(stderr, "Fixed packet %d, len %d\n", j, l);
525 s->f[ifp_no].frametype = AST_FRAME_MODEM;
526 s->f[ifp_no].subclass.integer = AST_MODEM_T38;
528 s->f[ifp_no].mallocd = 0;
529 s->f[ifp_no].seqno = j;
530 s->f[ifp_no].datalen = s->rx[l].buf_len;
531 s->f[ifp_no].data.ptr = s->rx[l].buf;
532 s->f[ifp_no].offset = 0;
533 s->f[ifp_no].src = "UDPTL";
535 AST_LIST_NEXT(&s->f[ifp_no - 1], frame_list) = &s->f[ifp_no];
536 AST_LIST_NEXT(&s->f[ifp_no], frame_list) = NULL;
542 /* If packets are received out of sequence, we may have already processed this packet from the error
543 recovery information in a packet already received. */
544 if (seq_no >= s->rx_seq_no) {
545 /* Decode the primary IFP packet */
546 s->f[ifp_no].frametype = AST_FRAME_MODEM;
547 s->f[ifp_no].subclass.integer = AST_MODEM_T38;
549 s->f[ifp_no].mallocd = 0;
550 s->f[ifp_no].seqno = seq_no;
551 s->f[ifp_no].datalen = ifp_len;
552 s->f[ifp_no].data.ptr = (uint8_t *) ifp;
553 s->f[ifp_no].offset = 0;
554 s->f[ifp_no].src = "UDPTL";
556 AST_LIST_NEXT(&s->f[ifp_no - 1], frame_list) = &s->f[ifp_no];
557 AST_LIST_NEXT(&s->f[ifp_no], frame_list) = NULL;
562 s->rx_seq_no = seq_no + 1;
565 /*- End of function --------------------------------------------------------*/
567 static int udptl_build_packet(struct ast_udptl *s, uint8_t *buf, unsigned int buflen, uint8_t *ifp, unsigned int ifp_len)
569 uint8_t fec[LOCAL_FAX_MAX_DATAGRAM * 2] = { 0, };
581 seq = s->tx_seq_no & 0xFFFF;
583 /* Map the sequence number to an entry in the circular buffer */
584 entry = seq & UDPTL_BUF_MASK;
586 /* We save the message in a circular buffer, for generating FEC or
587 redundancy sets later on. */
588 s->tx[entry].buf_len = ifp_len;
589 memcpy(s->tx[entry].buf, ifp, ifp_len);
591 /* Build the UDPTLPacket */
594 /* Encode the sequence number */
595 buf[len++] = (seq >> 8) & 0xFF;
596 buf[len++] = seq & 0xFF;
598 /* Encode the primary IFP packet */
599 if (encode_open_type(s, buf, buflen, &len, ifp, ifp_len) < 0)
602 /* Encode the appropriate type of error recovery information */
603 switch (s->error_correction_scheme)
605 case UDPTL_ERROR_CORRECTION_NONE:
606 /* Encode the error recovery type */
608 /* The number of entries will always be zero, so it is pointless allowing
609 for the fragmented case here. */
610 if (encode_length(buf, &len, 0) < 0)
613 case UDPTL_ERROR_CORRECTION_REDUNDANCY:
614 /* Encode the error recovery type */
616 if (s->tx_seq_no > s->error_correction_entries)
617 entries = s->error_correction_entries;
619 entries = s->tx_seq_no;
620 /* The number of entries will always be small, so it is pointless allowing
621 for the fragmented case here. */
622 if (encode_length(buf, &len, entries) < 0)
624 /* Encode the elements */
625 for (i = 0; i < entries; i++) {
626 j = (entry - i - 1) & UDPTL_BUF_MASK;
627 if (encode_open_type(s, buf, buflen, &len, s->tx[j].buf, s->tx[j].buf_len) < 0) {
628 ast_debug(1, "UDPTL (%s): Encoding failed at i=%d, j=%d\n",
634 case UDPTL_ERROR_CORRECTION_FEC:
635 span = s->error_correction_span;
636 entries = s->error_correction_entries;
637 if (seq < s->error_correction_span*s->error_correction_entries) {
638 /* In the initial stages, wind up the FEC smoothly */
639 entries = seq/s->error_correction_span;
640 if (seq < s->error_correction_span)
643 /* Encode the error recovery type */
645 /* Span is defined as an inconstrained integer, which it dumb. It will only
646 ever be a small value. Treat it as such. */
649 /* The number of entries is defined as a length, but will only ever be a small
650 value. Treat it as such. */
651 buf[len++] = entries;
652 for (m = 0; m < entries; m++) {
653 /* Make an XOR'ed entry the maximum length */
654 limit = (entry + m) & UDPTL_BUF_MASK;
656 for (i = (limit - span*entries) & UDPTL_BUF_MASK; i != limit; i = (i + entries) & UDPTL_BUF_MASK) {
657 if (high_tide < s->tx[i].buf_len) {
658 for (j = 0; j < high_tide; j++)
659 fec[j] ^= s->tx[i].buf[j];
660 for ( ; j < s->tx[i].buf_len; j++)
661 fec[j] = s->tx[i].buf[j];
662 high_tide = s->tx[i].buf_len;
664 for (j = 0; j < s->tx[i].buf_len; j++)
665 fec[j] ^= s->tx[i].buf[j];
668 if (encode_open_type(s, buf, buflen, &len, fec, high_tide) < 0)
678 int ast_udptl_fd(const struct ast_udptl *udptl)
683 void ast_udptl_set_data(struct ast_udptl *udptl, void *data)
688 void ast_udptl_set_callback(struct ast_udptl *udptl, ast_udptl_callback callback)
690 udptl->callback = callback;
693 void ast_udptl_setnat(struct ast_udptl *udptl, int nat)
698 static int udptlread(int *id, int fd, short events, void *cbdata)
700 struct ast_udptl *udptl = cbdata;
703 if ((f = ast_udptl_read(udptl))) {
705 udptl->callback(udptl, f, udptl->data);
710 struct ast_frame *ast_udptl_read(struct ast_udptl *udptl)
713 struct ast_sockaddr addr;
716 buf = udptl->rawdata + AST_FRIENDLY_OFFSET;
718 /* Cache where the header will go */
719 res = ast_recvfrom(udptl->fd,
721 sizeof(udptl->rawdata) - AST_FRIENDLY_OFFSET,
726 ast_log(LOG_WARNING, "UDPTL (%s): read error: %s\n",
727 LOG_TAG(udptl), strerror(errno));
728 ast_assert(errno != EBADF);
729 return &ast_null_frame;
732 /* Ignore if the other side hasn't been given an address yet. */
733 if (ast_sockaddr_isnull(&udptl->them)) {
734 return &ast_null_frame;
738 /* Send to whoever sent to us */
739 if (ast_sockaddr_cmp(&udptl->them, &addr)) {
740 ast_sockaddr_copy(&udptl->them, &addr);
741 ast_debug(1, "UDPTL (%s): NAT, Using address %s\n",
742 LOG_TAG(udptl), ast_sockaddr_stringify(&udptl->them));
746 if (udptl_debug_test_addr(&addr)) {
749 /* Decode sequence number just for verbose message. */
754 seq_no = (buf[0] << 8) | buf[1];
757 ast_verb(1, "UDPTL (%s): packet from %s (seq %d, len %d)\n",
758 LOG_TAG(udptl), ast_sockaddr_stringify(&addr), seq_no, res);
760 if (udptl_rx_packet(udptl, buf, res) < 1) {
761 return &ast_null_frame;
767 static void calculate_local_max_datagram(struct ast_udptl *udptl)
769 unsigned int new_max = 0;
771 if (udptl->local_max_ifp == -1) {
772 ast_log(LOG_WARNING, "UDPTL (%s): Cannot calculate local_max_datagram before local_max_ifp has been set.\n",
774 udptl->local_max_datagram = -1;
778 /* calculate the amount of space required to receive an IFP
779 * of the maximum size supported by the application/endpoint
780 * that we are delivering them to (local endpoint), and add
781 * the amount of space required to support the selected
782 * error correction mode
784 switch (udptl->error_correction_scheme) {
785 case UDPTL_ERROR_CORRECTION_NONE:
786 /* need room for sequence number, length indicator, redundancy
787 * indicator and following length indicator
789 new_max = 5 + udptl->local_max_ifp;
791 case UDPTL_ERROR_CORRECTION_REDUNDANCY:
792 /* need room for sequence number, length indicators, plus
793 * room for up to 3 redundancy packets
795 new_max = 5 + udptl->local_max_ifp + 2 + (3 * udptl->local_max_ifp);
797 case UDPTL_ERROR_CORRECTION_FEC:
798 /* need room for sequence number, length indicators and a
799 * a single IFP of the maximum size expected
801 new_max = 5 + udptl->local_max_ifp + 4 + udptl->local_max_ifp;
804 /* add 5% extra space for insurance, but no larger than LOCAL_FAX_MAX_DATAGRAM */
805 udptl->local_max_datagram = MIN(new_max * 1.05, LOCAL_FAX_MAX_DATAGRAM);
808 static void calculate_far_max_ifp(struct ast_udptl *udptl)
810 unsigned new_max = 0;
812 if (udptl->far_max_datagram == -1) {
813 ast_log(LOG_WARNING, "UDPTL (%s): Cannot calculate far_max_ifp before far_max_datagram has been set.\n",
815 udptl->far_max_ifp = -1;
819 /* the goal here is to supply the local endpoint (application
820 * or bridged channel) a maximum IFP value that will allow it
821 * to effectively and efficiently transfer image data at its
822 * selected bit rate, taking into account the selected error
823 * correction mode, but without overrunning the far endpoint's
824 * datagram buffer. this is complicated by the fact that some
825 * far endpoints send us bogus (small) max datagram values,
826 * which would result in either buffer overrun or no error
827 * correction. we try to accomodate those, but if the supplied
828 * value is too small to do so, we'll emit warning messages and
829 * the user will have to use configuration options to override
830 * the max datagram value supplied by the far endpoint.
832 switch (udptl->error_correction_scheme) {
833 case UDPTL_ERROR_CORRECTION_NONE:
834 /* need room for sequence number, length indicator, redundancy
835 * indicator and following length indicator
837 new_max = udptl->far_max_datagram - 5;
839 case UDPTL_ERROR_CORRECTION_REDUNDANCY:
840 /* for this case, we'd like to send as many error correction entries
841 * as possible (up to the number we're configured for), but we'll settle
842 * for sending fewer if the configured number would cause the
843 * calculated max IFP to be too small for effective operation
845 * need room for sequence number, length indicators and the
846 * configured number of redundant packets
848 * note: we purposely don't allow error_correction_entries to drop to
849 * zero in this loop; we'd rather send smaller IFPs (and thus reduce
850 * the image data transfer rate) than sacrifice redundancy completely
853 new_max = (udptl->far_max_datagram - 8) / (udptl->error_correction_entries + 1);
855 if ((new_max < 80) && (udptl->error_correction_entries > 1)) {
856 /* the max ifp is not large enough, subtract an
857 * error correction entry and calculate again
859 --udptl->error_correction_entries;
865 case UDPTL_ERROR_CORRECTION_FEC:
866 /* need room for sequence number, length indicators and a
867 * a single IFP of the maximum size expected
869 new_max = (udptl->far_max_datagram - 10) / 2;
872 /* subtract 5% of space for insurance */
873 udptl->far_max_ifp = new_max * 0.95;
876 enum ast_t38_ec_modes ast_udptl_get_error_correction_scheme(const struct ast_udptl *udptl)
878 return udptl->error_correction_scheme;
881 void ast_udptl_set_error_correction_scheme(struct ast_udptl *udptl, enum ast_t38_ec_modes ec)
883 udptl->error_correction_scheme = ec;
885 case UDPTL_ERROR_CORRECTION_FEC:
886 udptl->error_correction_scheme = UDPTL_ERROR_CORRECTION_FEC;
887 if (udptl->error_correction_entries == 0) {
888 udptl->error_correction_entries = 3;
890 if (udptl->error_correction_span == 0) {
891 udptl->error_correction_span = 3;
894 case UDPTL_ERROR_CORRECTION_REDUNDANCY:
895 udptl->error_correction_scheme = UDPTL_ERROR_CORRECTION_REDUNDANCY;
896 if (udptl->error_correction_entries == 0) {
897 udptl->error_correction_entries = 3;
904 /* reset calculated values so they'll be computed again */
905 udptl->local_max_datagram = -1;
906 udptl->far_max_ifp = -1;
909 void ast_udptl_set_local_max_ifp(struct ast_udptl *udptl, unsigned int max_ifp)
911 /* make sure max_ifp is a positive value since a cast will take place when
912 * when setting local_max_ifp */
913 if ((signed int) max_ifp > 0) {
914 udptl->local_max_ifp = max_ifp;
915 /* reset calculated values so they'll be computed again */
916 udptl->local_max_datagram = -1;
920 unsigned int ast_udptl_get_local_max_datagram(struct ast_udptl *udptl)
922 if (udptl->local_max_datagram == -1) {
923 calculate_local_max_datagram(udptl);
926 /* this function expects a unsigned value in return. */
927 if (udptl->local_max_datagram < 0) {
930 return udptl->local_max_datagram;
933 void ast_udptl_set_far_max_datagram(struct ast_udptl *udptl, unsigned int max_datagram)
935 if (!max_datagram || (max_datagram > FAX_MAX_DATAGRAM_LIMIT)) {
936 udptl->far_max_datagram = DEFAULT_FAX_MAX_DATAGRAM;
938 udptl->far_max_datagram = max_datagram;
940 /* reset calculated values so they'll be computed again */
941 udptl->far_max_ifp = -1;
944 unsigned int ast_udptl_get_far_max_datagram(const struct ast_udptl *udptl)
946 if (udptl->far_max_datagram < 0) {
949 return udptl->far_max_datagram;
952 unsigned int ast_udptl_get_far_max_ifp(struct ast_udptl *udptl)
954 if (udptl->far_max_ifp == -1) {
955 calculate_far_max_ifp(udptl);
958 if (udptl->far_max_ifp < 0) {
961 return udptl->far_max_ifp;
964 struct ast_udptl *ast_udptl_new_with_bindaddr(struct ast_sched_context *sched, struct io_context *io, int callbackmode, struct ast_sockaddr *addr)
966 struct ast_udptl *udptl;
971 RAII_VAR(struct udptl_config *, cfg, ao2_global_obj_ref(globals), ao2_cleanup);
973 if (!cfg || !cfg->general) {
974 ast_log(LOG_ERROR, "Could not access global udptl options!\n");
978 if (!(udptl = ast_calloc(1, sizeof(*udptl)))) {
982 udptl->error_correction_span = cfg->general->fecspan;
983 udptl->error_correction_entries = cfg->general->fecentries;
985 udptl->far_max_datagram = -1;
986 udptl->far_max_ifp = -1;
987 udptl->local_max_ifp = -1;
988 udptl->local_max_datagram = -1;
990 for (i = 0; i <= UDPTL_BUF_MASK; i++) {
991 udptl->rx[i].buf_len = -1;
992 udptl->tx[i].buf_len = -1;
995 if ((udptl->fd = socket(ast_sockaddr_is_ipv6(addr) ?
996 AF_INET6 : AF_INET, SOCK_DGRAM, 0)) < 0) {
998 ast_log(LOG_WARNING, "Unable to allocate socket: %s\n", strerror(errno));
1001 flags = fcntl(udptl->fd, F_GETFL);
1002 fcntl(udptl->fd, F_SETFL, flags | O_NONBLOCK);
1005 if (cfg->general->nochecksums)
1006 setsockopt(udptl->fd, SOL_SOCKET, SO_NO_CHECK, &cfg->general->nochecksums, sizeof(cfg->general->nochecksums));
1009 /* Find us a place */
1010 x = (cfg->general->start == cfg->general->end) ? cfg->general->start : (ast_random() % (cfg->general->end - cfg->general->start)) + cfg->general->start;
1011 if (cfg->general->use_even_ports && (x & 1)) {
1016 ast_sockaddr_copy(&udptl->us, addr);
1017 ast_sockaddr_set_port(&udptl->us, x);
1018 if (ast_bind(udptl->fd, &udptl->us) == 0) {
1021 if (errno != EADDRINUSE) {
1022 ast_log(LOG_WARNING, "Unexpected bind error: %s\n", strerror(errno));
1027 if (cfg->general->use_even_ports) {
1032 if (x > cfg->general->end)
1033 x = cfg->general->start;
1034 if (x == startplace) {
1035 ast_log(LOG_WARNING, "No UDPTL ports remaining\n");
1041 if (io && sched && callbackmode) {
1042 /* Operate this one in a callback mode */
1043 udptl->sched = sched;
1045 udptl->ioid = ast_io_add(udptl->io, udptl->fd, udptlread, AST_IO_IN, udptl);
1051 void ast_udptl_set_tag(struct ast_udptl *udptl, const char *format, ...)
1055 ast_free(udptl->tag);
1057 va_start(ap, format);
1058 if (ast_vasprintf(&udptl->tag, format, ap) == -1) {
1064 int ast_udptl_setqos(struct ast_udptl *udptl, unsigned int tos, unsigned int cos)
1066 return ast_set_qos(udptl->fd, tos, cos, "UDPTL");
1069 void ast_udptl_set_peer(struct ast_udptl *udptl, const struct ast_sockaddr *them)
1071 ast_sockaddr_copy(&udptl->them, them);
1074 void ast_udptl_get_peer(const struct ast_udptl *udptl, struct ast_sockaddr *them)
1076 ast_sockaddr_copy(them, &udptl->them);
1079 void ast_udptl_get_us(const struct ast_udptl *udptl, struct ast_sockaddr *us)
1081 ast_sockaddr_copy(us, &udptl->us);
1084 void ast_udptl_stop(struct ast_udptl *udptl)
1086 ast_sockaddr_setnull(&udptl->them);
1089 void ast_udptl_destroy(struct ast_udptl *udptl)
1092 ast_io_remove(udptl->io, udptl->ioid);
1096 ast_free(udptl->tag);
1100 int ast_udptl_write(struct ast_udptl *s, struct ast_frame *f)
1103 unsigned int len = f->datalen;
1104 /* if no max datagram size is provided, use default value */
1105 const int bufsize = (s->far_max_datagram > 0) ? s->far_max_datagram : DEFAULT_FAX_MAX_DATAGRAM;
1106 uint8_t buf[bufsize];
1108 memset(buf, 0, sizeof(buf));
1110 /* If we have no peer, return immediately */
1111 if (ast_sockaddr_isnull(&s->them)) {
1115 /* If there is no data length, return immediately */
1116 if (f->datalen == 0)
1119 if ((f->frametype != AST_FRAME_MODEM) ||
1120 (f->subclass.integer != AST_MODEM_T38)) {
1121 ast_log(LOG_WARNING, "UDPTL (%s): UDPTL can only send T.38 data.\n",
1126 if (len > s->far_max_ifp) {
1127 ast_log(LOG_WARNING,
1128 "UDPTL (%s): UDPTL asked to send %d bytes of IFP when far end only prepared to accept %d bytes; data loss will occur."
1129 "You may need to override the T38FaxMaxDatagram value for this endpoint in the channel driver configuration.\n",
1130 LOG_TAG(s), len, s->far_max_ifp);
1131 len = s->far_max_ifp;
1134 /* Save seq_no for debug output because udptl_build_packet increments it */
1135 seq = s->tx_seq_no & 0xFFFF;
1137 /* Cook up the UDPTL packet, with the relevant EC info. */
1138 len = udptl_build_packet(s, buf, sizeof(buf), f->data.ptr, len);
1140 if ((signed int) len > 0 && !ast_sockaddr_isnull(&s->them)) {
1141 if (ast_sendto(s->fd, buf, len, 0, &s->them) < 0) {
1142 ast_log(LOG_NOTICE, "UDPTL (%s): Transmission error to %s: %s\n",
1143 LOG_TAG(s), ast_sockaddr_stringify(&s->them), strerror(errno));
1145 if (udptl_debug_test_addr(&s->them)) {
1146 ast_verb(1, "UDPTL (%s): packet to %s (seq %d, len %d)\n",
1147 LOG_TAG(s), ast_sockaddr_stringify(&s->them), seq, len);
1154 void ast_udptl_proto_unregister(struct ast_udptl_protocol *proto)
1156 AST_RWLIST_WRLOCK(&protos);
1157 AST_RWLIST_REMOVE(&protos, proto, list);
1158 AST_RWLIST_UNLOCK(&protos);
1161 int ast_udptl_proto_register(struct ast_udptl_protocol *proto)
1163 struct ast_udptl_protocol *cur;
1165 AST_RWLIST_WRLOCK(&protos);
1166 AST_RWLIST_TRAVERSE(&protos, cur, list) {
1167 if (cur->type == proto->type) {
1168 ast_log(LOG_WARNING, "Tried to register same protocol '%s' twice\n", cur->type);
1169 AST_RWLIST_UNLOCK(&protos);
1173 AST_RWLIST_INSERT_TAIL(&protos, proto, list);
1174 AST_RWLIST_UNLOCK(&protos);
1178 static struct ast_udptl_protocol *get_proto(struct ast_channel *chan)
1180 struct ast_udptl_protocol *cur = NULL;
1182 AST_RWLIST_RDLOCK(&protos);
1183 AST_RWLIST_TRAVERSE(&protos, cur, list) {
1184 if (cur->type == ast_channel_tech(chan)->type)
1187 AST_RWLIST_UNLOCK(&protos);
1192 int ast_udptl_bridge(struct ast_channel *c0, struct ast_channel *c1, int flags, struct ast_frame **fo, struct ast_channel **rc)
1194 struct ast_frame *f;
1195 struct ast_channel *who;
1196 struct ast_channel *cs[3];
1197 struct ast_udptl *p0;
1198 struct ast_udptl *p1;
1199 struct ast_udptl_protocol *pr0;
1200 struct ast_udptl_protocol *pr1;
1201 struct ast_sockaddr ac0;
1202 struct ast_sockaddr ac1;
1203 struct ast_sockaddr t0;
1204 struct ast_sockaddr t1;
1209 ast_channel_lock(c0);
1210 while (ast_channel_trylock(c1)) {
1211 ast_channel_unlock(c0);
1213 ast_channel_lock(c0);
1215 pr0 = get_proto(c0);
1216 pr1 = get_proto(c1);
1218 ast_log(LOG_WARNING, "Can't find native functions for channel '%s'\n", ast_channel_name(c0));
1219 ast_channel_unlock(c0);
1220 ast_channel_unlock(c1);
1224 ast_log(LOG_WARNING, "Can't find native functions for channel '%s'\n", ast_channel_name(c1));
1225 ast_channel_unlock(c0);
1226 ast_channel_unlock(c1);
1229 pvt0 = ast_channel_tech_pvt(c0);
1230 pvt1 = ast_channel_tech_pvt(c1);
1231 p0 = pr0->get_udptl_info(c0);
1232 p1 = pr1->get_udptl_info(c1);
1234 /* Somebody doesn't want to play... */
1235 ast_channel_unlock(c0);
1236 ast_channel_unlock(c1);
1239 if (pr0->set_udptl_peer(c0, p1)) {
1240 ast_log(LOG_WARNING, "Channel '%s' failed to talk to '%s'\n", ast_channel_name(c0), ast_channel_name(c1));
1241 memset(&ac1, 0, sizeof(ac1));
1243 /* Store UDPTL peer */
1244 ast_udptl_get_peer(p1, &ac1);
1246 if (pr1->set_udptl_peer(c1, p0)) {
1247 ast_log(LOG_WARNING, "Channel '%s' failed to talk back to '%s'\n", ast_channel_name(c1), ast_channel_name(c0));
1248 memset(&ac0, 0, sizeof(ac0));
1250 /* Store UDPTL peer */
1251 ast_udptl_get_peer(p0, &ac0);
1253 ast_channel_unlock(c0);
1254 ast_channel_unlock(c1);
1259 if ((ast_channel_tech_pvt(c0) != pvt0) ||
1260 (ast_channel_tech_pvt(c1) != pvt1) ||
1261 (ast_channel_masq(c0) || ast_channel_masqr(c0) || ast_channel_masq(c1) || ast_channel_masqr(c1))) {
1262 ast_debug(1, "Oooh, something is weird, backing out\n");
1263 /* Tell it to try again later */
1267 ast_udptl_get_peer(p1, &t1);
1268 ast_udptl_get_peer(p0, &t0);
1269 if (ast_sockaddr_cmp(&t1, &ac1)) {
1270 ast_debug(1, "Oooh, '%s' changed end address to %s\n",
1271 ast_channel_name(c1), ast_sockaddr_stringify(&t1));
1272 ast_debug(1, "Oooh, '%s' was %s\n",
1273 ast_channel_name(c1), ast_sockaddr_stringify(&ac1));
1274 ast_sockaddr_copy(&ac1, &t1);
1276 if (ast_sockaddr_cmp(&t0, &ac0)) {
1277 ast_debug(1, "Oooh, '%s' changed end address to %s\n",
1278 ast_channel_name(c0), ast_sockaddr_stringify(&t0));
1279 ast_debug(1, "Oooh, '%s' was %s\n",
1280 ast_channel_name(c0), ast_sockaddr_stringify(&ac0));
1281 ast_sockaddr_copy(&ac0, &t0);
1283 who = ast_waitfor_n(cs, 2, &to);
1285 ast_debug(1, "Ooh, empty read...\n");
1286 /* check for hangup / whentohangup */
1287 if (ast_check_hangup(c0) || ast_check_hangup(c1))
1295 ast_debug(1, "Oooh, got a %s\n", f ? "digit" : "hangup");
1296 /* That's all we needed */
1299 if (f->frametype == AST_FRAME_MODEM) {
1300 /* Forward T.38 frames if they happen upon us */
1303 } else if (who == c1) {
1309 /* Swap priority. Not that it's a big deal at this point */
1317 static char *handle_cli_udptl_set_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1321 e->command = "udptl set debug {on|off|ip}";
1323 "Usage: udptl set debug {on|off|ip host[:port]}\n"
1324 " Enable or disable dumping of UDPTL packets.\n"
1325 " If ip is specified, limit the dumped packets to those to and from\n"
1326 " the specified 'host' with optional port.\n";
1332 if (a->argc < 4 || a->argc > 5)
1333 return CLI_SHOWUSAGE;
1336 if (!strncasecmp(a->argv[3], "on", 2)) {
1338 memset(&udptldebugaddr, 0, sizeof(udptldebugaddr));
1339 ast_cli(a->fd, "UDPTL Debugging Enabled\n");
1340 } else if (!strncasecmp(a->argv[3], "off", 3)) {
1342 ast_cli(a->fd, "UDPTL Debugging Disabled\n");
1344 return CLI_SHOWUSAGE;
1347 struct ast_sockaddr *addrs;
1348 if (strncasecmp(a->argv[3], "ip", 2))
1349 return CLI_SHOWUSAGE;
1350 if (!ast_sockaddr_resolve(&addrs, a->argv[4], 0, 0)) {
1351 return CLI_SHOWUSAGE;
1353 ast_sockaddr_copy(&udptldebugaddr, &addrs[0]);
1354 ast_cli(a->fd, "UDPTL Debugging Enabled for IP: %s\n", ast_sockaddr_stringify(&udptldebugaddr));
1362 static char *handle_cli_show_config(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1364 RAII_VAR(struct udptl_config *, cfg, NULL, ao2_cleanup);
1368 e->command = "udptl show config";
1370 "Usage: udptl show config\n"
1371 " Display UDPTL configuration options\n";
1377 if (!(cfg = ao2_global_obj_ref(globals))) {
1381 ast_cli(a->fd, "UDPTL Global options\n");
1382 ast_cli(a->fd, "--------------------\n");
1383 ast_cli(a->fd, "udptlstart: %u\n", cfg->general->start);
1384 ast_cli(a->fd, "udptlend: %u\n", cfg->general->end);
1385 ast_cli(a->fd, "udptlfecentries: %u\n", cfg->general->fecentries);
1386 ast_cli(a->fd, "udptlfecspan: %u\n", cfg->general->fecspan);
1387 ast_cli(a->fd, "use_even_ports: %s\n", AST_CLI_YESNO(cfg->general->use_even_ports));
1388 ast_cli(a->fd, "udptlchecksums: %s\n", AST_CLI_YESNO(!cfg->general->nochecksums));
1393 static struct ast_cli_entry cli_udptl[] = {
1394 AST_CLI_DEFINE(handle_cli_udptl_set_debug, "Enable/Disable UDPTL debugging"),
1395 AST_CLI_DEFINE(handle_cli_show_config, "Show UDPTL config options"),
1398 static void udptl_config_destructor(void *obj)
1400 struct udptl_config *cfg = obj;
1401 ao2_cleanup(cfg->general);
1404 static void *udptl_snapshot_alloc(void)
1406 struct udptl_config *cfg;
1408 if (!(cfg = ao2_alloc(sizeof(*cfg), udptl_config_destructor))) {
1411 if (!(cfg->general = ao2_alloc(sizeof(*cfg->general), NULL))) {
1419 static int removed_options_handler(const struct aco_option *opt, struct ast_variable *var, void *obj)
1421 if (!strcasecmp(var->name, "t38faxudpec")) {
1422 ast_log(LOG_WARNING, "t38faxudpec in udptl.conf is no longer supported; use the t38pt_udptl configuration option in sip.conf instead.\n");
1423 } else if (!strcasecmp(var->name, "t38faxmaxdatagram")) {
1424 ast_log(LOG_WARNING, "t38faxmaxdatagram in udptl.conf is no longer supported; value is now supplied by T.38 applications.\n");
1429 static void __ast_udptl_reload(int reload)
1431 if (aco_process_config(&cfg_info, reload) == ACO_PROCESS_ERROR) {
1432 ast_log(LOG_WARNING, "Could not reload udptl config\n");
1436 static int udptl_pre_apply_config(void) {
1437 struct udptl_config *cfg = aco_pending_config(&cfg_info);
1439 if (!cfg->general) {
1444 if (cfg->general->nochecksums) {
1445 ast_log(LOG_WARNING, "Disabling UDPTL checksums is not supported on this operating system!\n");
1446 cfg->general->nochecksums = 0;
1450 /* Fix up any global config values that we can handle before replacing the config */
1451 if (cfg->general->use_even_ports && (cfg->general->start & 1)) {
1452 ++cfg->general->start;
1453 ast_log(LOG_NOTICE, "Odd numbered udptlstart specified but use_even_ports enabled. udptlstart is now %d\n", cfg->general->start);
1455 if (cfg->general->start > cfg->general->end) {
1456 ast_log(LOG_WARNING, "Unreasonable values for UDPTL start/end ports; defaulting to %s-%s.\n", __stringify(DEFAULT_UDPTLSTART), __stringify(DEFAULT_UDPTLEND));
1457 cfg->general->start = DEFAULT_UDPTLSTART;
1458 cfg->general->end = DEFAULT_UDPTLEND;
1460 if (cfg->general->use_even_ports && (cfg->general->end & 1)) {
1461 --cfg->general->end;
1462 ast_log(LOG_NOTICE, "Odd numbered udptlend specified but use_even_ports enabled. udptlend is now %d\n", cfg->general->end);
1468 int ast_udptl_reload(void)
1470 __ast_udptl_reload(1);
1476 * \brief Clean up resources on Asterisk shutdown
1478 static void udptl_shutdown(void)
1480 ast_cli_unregister_multiple(cli_udptl, ARRAY_LEN(cli_udptl));
1481 ao2_t_global_obj_release(globals, "Unref udptl global container in shutdown");
1482 aco_info_destroy(&cfg_info);
1485 void ast_udptl_init(void)
1487 if (aco_info_init(&cfg_info)) {
1491 aco_option_register(&cfg_info, "udptlstart", ACO_EXACT, general_options, __stringify(DEFAULT_UDPTLSTART),
1492 OPT_UINT_T, PARSE_IN_RANGE | PARSE_DEFAULT,
1493 FLDSET(struct udptl_global_options, start), DEFAULT_UDPTLSTART, 1024, 65535);
1495 aco_option_register(&cfg_info, "udptlend", ACO_EXACT, general_options, __stringify(DEFAULT_UDPTLEND),
1496 OPT_UINT_T, PARSE_IN_RANGE | PARSE_DEFAULT,
1497 FLDSET(struct udptl_global_options, end), DEFAULT_UDPTLEND, 1024, 65535);
1499 aco_option_register(&cfg_info, "udptlfecentries", ACO_EXACT, general_options, NULL,
1500 OPT_UINT_T, PARSE_IN_RANGE | PARSE_RANGE_DEFAULTS,
1501 FLDSET(struct udptl_global_options, fecentries), 1, MAX_FEC_ENTRIES);
1503 aco_option_register(&cfg_info, "udptlfecspan", ACO_EXACT, general_options, NULL,
1504 OPT_UINT_T, PARSE_IN_RANGE | PARSE_RANGE_DEFAULTS,
1505 FLDSET(struct udptl_global_options, fecspan), 1, MAX_FEC_SPAN);
1507 aco_option_register(&cfg_info, "udptlchecksums", ACO_EXACT, general_options, "yes",
1508 OPT_BOOL_T, 0, FLDSET(struct udptl_global_options, nochecksums));
1510 aco_option_register(&cfg_info, "use_even_ports", ACO_EXACT, general_options, "no",
1511 OPT_BOOL_T, 1, FLDSET(struct udptl_global_options, use_even_ports));
1513 aco_option_register_custom(&cfg_info, "t38faxudpec", ACO_EXACT, general_options, NULL, removed_options_handler, 0);
1514 aco_option_register_custom(&cfg_info, "t38faxmaxdatagram", ACO_EXACT, general_options, NULL, removed_options_handler, 0);
1516 __ast_udptl_reload(0);
1518 ast_cli_register_multiple(cli_udptl, ARRAY_LEN(cli_udptl));
1520 ast_register_atexit(udptl_shutdown);