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 ast_sockaddr 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 ast_sockaddr us;
125 struct ast_sockaddr them;
127 struct ast_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 unsigned int tx_seq_no;
176 unsigned int rx_seq_no;
177 unsigned int rx_expected_seq_no;
179 udptl_fec_tx_buffer_t tx[UDPTL_BUF_MASK + 1];
180 udptl_fec_rx_buffer_t rx[UDPTL_BUF_MASK + 1];
183 static AST_RWLIST_HEAD_STATIC(protos, ast_udptl_protocol);
185 static inline int udptl_debug_test_addr(const struct ast_sockaddr *addr)
190 if (ast_sockaddr_isnull(&udptldebugaddr)) {
194 if (ast_sockaddr_port(&udptldebugaddr)) {
195 return !ast_sockaddr_cmp(&udptldebugaddr, addr);
197 return !ast_sockaddr_cmp_addr(&udptldebugaddr, addr);
201 static int decode_length(uint8_t *buf, unsigned int limit, unsigned int *len, unsigned int *pvalue)
205 if ((buf[*len] & 0x80) == 0) {
210 if ((buf[*len] & 0x40) == 0) {
211 if (*len == limit - 1)
213 *pvalue = (buf[*len] & 0x3F) << 8;
215 *pvalue |= buf[*len];
219 *pvalue = (buf[*len] & 0x3F) << 14;
221 /* Indicate we have a fragment */
224 /*- End of function --------------------------------------------------------*/
226 static int decode_open_type(uint8_t *buf, unsigned int limit, unsigned int *len, const uint8_t **p_object, unsigned int *p_num_octets)
228 unsigned int octet_cnt;
229 unsigned int octet_idx;
231 int length; /* a negative length indicates the limit has been reached in decode_length. */
232 const uint8_t **pbuf;
234 for (octet_idx = 0, *p_num_octets = 0; ; octet_idx += octet_cnt) {
236 if ((length = decode_length(buf, limit, len, &octet_cnt)) < 0)
239 *p_num_octets += octet_cnt;
241 pbuf = &p_object[octet_idx];
243 /* Make sure the buffer contains at least the number of bits requested */
244 if ((*len + octet_cnt) > limit)
255 /*- End of function --------------------------------------------------------*/
257 static unsigned int encode_length(uint8_t *buf, unsigned int *len, unsigned int value)
259 unsigned int multiplier;
267 if (value < 0x4000) {
269 /* Set the first bit of the first octet */
270 buf[*len] = ((0x8000 | value) >> 8) & 0xFF;
272 buf[*len] = value & 0xFF;
277 multiplier = (value < 0x10000) ? (value >> 14) : 4;
278 /* Set the first 2 bits of the octet */
279 buf[*len] = 0xC0 | multiplier;
281 return multiplier << 14;
283 /*- End of function --------------------------------------------------------*/
285 static int encode_open_type(const struct ast_udptl *udptl, uint8_t *buf, unsigned int buflen,
286 unsigned int *len, const uint8_t *data, unsigned int num_octets)
289 unsigned int octet_idx;
292 /* If open type is of zero length, add a single zero byte (10.1) */
293 if (num_octets == 0) {
298 /* Encode the open type */
299 for (octet_idx = 0; ; num_octets -= enclen, octet_idx += enclen) {
300 if ((enclen = encode_length(buf, len, num_octets)) < 0)
302 if (enclen + *len > buflen) {
303 ast_log(LOG_ERROR, "(%s): Buffer overflow detected (%d + %d > %d)\n",
304 LOG_TAG(udptl), enclen, *len, buflen);
308 memcpy(&buf[*len], &data[octet_idx], enclen);
311 if (enclen >= num_octets)
317 /*- End of function --------------------------------------------------------*/
319 static int udptl_rx_packet(struct ast_udptl *s, uint8_t *buf, unsigned int len)
337 unsigned int ifp_len;
339 const uint8_t *bufs[16];
340 unsigned int lengths[16];
347 memset(&s->f[0], 0, sizeof(s->f[0]));
349 /* Decode seq_number */
352 seq_no = (buf[0] << 8) | buf[1];
355 /* Break out the primary packet */
356 if ((stat1 = decode_open_type(buf, len, &ptr, &ifp, &ifp_len)) != 0)
358 /* Decode error_recovery */
361 if ((buf[ptr++] & 0x80) == 0) {
362 /* Secondary packet mode for error recovery */
363 if (seq_no > s->rx_seq_no) {
364 /* We received a later packet than we expected, so we need to check if we can fill in the gap from the
365 secondary packets. */
368 if ((stat2 = decode_length(buf, len, &ptr, &count)) < 0)
370 for (i = 0; i < count; i++) {
371 if ((stat1 = decode_open_type(buf, len, &ptr, &bufs[total_count + i], &lengths[total_count + i])) != 0)
374 total_count += count;
377 /* Step through in reverse order, so we go oldest to newest */
378 for (i = total_count; i > 0; i--) {
379 if (seq_no - i >= s->rx_seq_no) {
380 /* This one wasn't seen before */
381 /* Decode the secondary IFP packet */
382 //fprintf(stderr, "Secondary %d, len %d\n", seq_no - i, lengths[i - 1]);
383 s->f[ifp_no].frametype = AST_FRAME_MODEM;
384 s->f[ifp_no].subclass.codec = AST_MODEM_T38;
386 s->f[ifp_no].mallocd = 0;
387 s->f[ifp_no].seqno = seq_no - i;
388 s->f[ifp_no].datalen = lengths[i - 1];
389 s->f[ifp_no].data.ptr = (uint8_t *) bufs[i - 1];
390 s->f[ifp_no].offset = 0;
391 s->f[ifp_no].src = "UDPTL";
393 AST_LIST_NEXT(&s->f[ifp_no - 1], frame_list) = &s->f[ifp_no];
394 AST_LIST_NEXT(&s->f[ifp_no], frame_list) = NULL;
402 /* FEC mode for error recovery */
403 /* Our buffers cannot tolerate overlength IFP packets in FEC mode */
404 if (ifp_len > LOCAL_FAX_MAX_DATAGRAM)
406 /* Update any missed slots in the buffer */
407 for ( ; seq_no > s->rx_seq_no; s->rx_seq_no++) {
408 x = s->rx_seq_no & UDPTL_BUF_MASK;
409 s->rx[x].buf_len = -1;
410 s->rx[x].fec_len[0] = 0;
411 s->rx[x].fec_span = 0;
412 s->rx[x].fec_entries = 0;
415 x = seq_no & UDPTL_BUF_MASK;
417 memset(repaired, 0, sizeof(repaired));
419 /* Save the new IFP packet */
420 memcpy(s->rx[x].buf, ifp, ifp_len);
421 s->rx[x].buf_len = ifp_len;
424 /* Decode the FEC packets */
425 /* The span is defined as an unconstrained integer, but will never be more
426 than a small value. */
432 s->rx[x].fec_span = span;
434 /* The number of entries is defined as a length, but will only ever be a small
435 value. Treat it as such. */
438 entries = buf[ptr++];
439 s->rx[x].fec_entries = entries;
441 /* Decode the elements */
442 for (i = 0; i < entries; i++) {
443 if ((stat1 = decode_open_type(buf, len, &ptr, &data, &s->rx[x].fec_len[i])) != 0)
445 if (s->rx[x].fec_len[i] > LOCAL_FAX_MAX_DATAGRAM)
448 /* Save the new FEC data */
449 memcpy(s->rx[x].fec[i], data, s->rx[x].fec_len[i]);
451 fprintf(stderr, "FEC: ");
452 for (j = 0; j < s->rx[x].fec_len[i]; j++)
453 fprintf(stderr, "%02X ", data[j]);
454 fprintf(stderr, "\n");
458 /* See if we can reconstruct anything which is missing */
459 /* TODO: this does not comprehensively hunt back and repair everything that is possible */
460 for (l = x; l != ((x - (16 - span*entries)) & UDPTL_BUF_MASK); l = (l - 1) & UDPTL_BUF_MASK) {
461 if (s->rx[l].fec_len[0] <= 0)
463 for (m = 0; m < s->rx[l].fec_entries; m++) {
464 limit = (l + m) & UDPTL_BUF_MASK;
465 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) {
466 if (s->rx[k].buf_len <= 0)
467 which = (which == -1) ? k : -2;
471 for (j = 0; j < s->rx[l].fec_len[m]; j++) {
472 s->rx[which].buf[j] = s->rx[l].fec[m][j];
473 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)
474 s->rx[which].buf[j] ^= (s->rx[k].buf_len > j) ? s->rx[k].buf[j] : 0;
476 s->rx[which].buf_len = s->rx[l].fec_len[m];
477 repaired[which] = TRUE;
481 /* Now play any new packets forwards in time */
482 for (l = (x + 1) & UDPTL_BUF_MASK, j = seq_no - UDPTL_BUF_MASK; l != x; l = (l + 1) & UDPTL_BUF_MASK, j++) {
484 //fprintf(stderr, "Fixed packet %d, len %d\n", j, l);
485 s->f[ifp_no].frametype = AST_FRAME_MODEM;
486 s->f[ifp_no].subclass.codec = AST_MODEM_T38;
488 s->f[ifp_no].mallocd = 0;
489 s->f[ifp_no].seqno = j;
490 s->f[ifp_no].datalen = s->rx[l].buf_len;
491 s->f[ifp_no].data.ptr = s->rx[l].buf;
492 s->f[ifp_no].offset = 0;
493 s->f[ifp_no].src = "UDPTL";
495 AST_LIST_NEXT(&s->f[ifp_no - 1], frame_list) = &s->f[ifp_no];
496 AST_LIST_NEXT(&s->f[ifp_no], frame_list) = NULL;
502 /* If packets are received out of sequence, we may have already processed this packet from the error
503 recovery information in a packet already received. */
504 if (seq_no >= s->rx_seq_no) {
505 /* Decode the primary IFP packet */
506 s->f[ifp_no].frametype = AST_FRAME_MODEM;
507 s->f[ifp_no].subclass.codec = AST_MODEM_T38;
509 s->f[ifp_no].mallocd = 0;
510 s->f[ifp_no].seqno = seq_no;
511 s->f[ifp_no].datalen = ifp_len;
512 s->f[ifp_no].data.ptr = (uint8_t *) ifp;
513 s->f[ifp_no].offset = 0;
514 s->f[ifp_no].src = "UDPTL";
516 AST_LIST_NEXT(&s->f[ifp_no - 1], frame_list) = &s->f[ifp_no];
517 AST_LIST_NEXT(&s->f[ifp_no], frame_list) = NULL;
522 s->rx_seq_no = seq_no + 1;
525 /*- End of function --------------------------------------------------------*/
527 static int udptl_build_packet(struct ast_udptl *s, uint8_t *buf, unsigned int buflen, uint8_t *ifp, unsigned int ifp_len)
529 uint8_t fec[LOCAL_FAX_MAX_DATAGRAM * 2];
541 seq = s->tx_seq_no & 0xFFFF;
543 /* Map the sequence number to an entry in the circular buffer */
544 entry = seq & UDPTL_BUF_MASK;
546 /* We save the message in a circular buffer, for generating FEC or
547 redundancy sets later on. */
548 s->tx[entry].buf_len = ifp_len;
549 memcpy(s->tx[entry].buf, ifp, ifp_len);
551 /* Build the UDPTLPacket */
554 /* Encode the sequence number */
555 buf[len++] = (seq >> 8) & 0xFF;
556 buf[len++] = seq & 0xFF;
558 /* Encode the primary IFP packet */
559 if (encode_open_type(s, buf, buflen, &len, ifp, ifp_len) < 0)
562 /* Encode the appropriate type of error recovery information */
563 switch (s->error_correction_scheme)
565 case UDPTL_ERROR_CORRECTION_NONE:
566 /* Encode the error recovery type */
568 /* The number of entries will always be zero, so it is pointless allowing
569 for the fragmented case here. */
570 if (encode_length(buf, &len, 0) < 0)
573 case UDPTL_ERROR_CORRECTION_REDUNDANCY:
574 /* Encode the error recovery type */
576 if (s->tx_seq_no > s->error_correction_entries)
577 entries = s->error_correction_entries;
579 entries = s->tx_seq_no;
580 /* The number of entries will always be small, so it is pointless allowing
581 for the fragmented case here. */
582 if (encode_length(buf, &len, entries) < 0)
584 /* Encode the elements */
585 for (i = 0; i < entries; i++) {
586 j = (entry - i - 1) & UDPTL_BUF_MASK;
587 if (encode_open_type(s, buf, buflen, &len, s->tx[j].buf, s->tx[j].buf_len) < 0) {
588 ast_debug(1, "(%s): Encoding failed at i=%d, j=%d\n",
594 case UDPTL_ERROR_CORRECTION_FEC:
595 span = s->error_correction_span;
596 entries = s->error_correction_entries;
597 if (seq < s->error_correction_span*s->error_correction_entries) {
598 /* In the initial stages, wind up the FEC smoothly */
599 entries = seq/s->error_correction_span;
600 if (seq < s->error_correction_span)
603 /* Encode the error recovery type */
605 /* Span is defined as an inconstrained integer, which it dumb. It will only
606 ever be a small value. Treat it as such. */
609 /* The number of entries is defined as a length, but will only ever be a small
610 value. Treat it as such. */
611 buf[len++] = entries;
612 for (m = 0; m < entries; m++) {
613 /* Make an XOR'ed entry the maximum length */
614 limit = (entry + m) & UDPTL_BUF_MASK;
616 for (i = (limit - span*entries) & UDPTL_BUF_MASK; i != limit; i = (i + entries) & UDPTL_BUF_MASK) {
617 if (high_tide < s->tx[i].buf_len) {
618 for (j = 0; j < high_tide; j++)
619 fec[j] ^= s->tx[i].buf[j];
620 for ( ; j < s->tx[i].buf_len; j++)
621 fec[j] = s->tx[i].buf[j];
622 high_tide = s->tx[i].buf_len;
624 for (j = 0; j < s->tx[i].buf_len; j++)
625 fec[j] ^= s->tx[i].buf[j];
628 if (encode_open_type(s, buf, buflen, &len, fec, high_tide) < 0)
635 fprintf(stderr, "\n");
641 int ast_udptl_fd(const struct ast_udptl *udptl)
646 void ast_udptl_set_data(struct ast_udptl *udptl, void *data)
651 void ast_udptl_set_callback(struct ast_udptl *udptl, ast_udptl_callback callback)
653 udptl->callback = callback;
656 void ast_udptl_setnat(struct ast_udptl *udptl, int nat)
661 static int udptlread(int *id, int fd, short events, void *cbdata)
663 struct ast_udptl *udptl = cbdata;
666 if ((f = ast_udptl_read(udptl))) {
668 udptl->callback(udptl, f, udptl->data);
673 struct ast_frame *ast_udptl_read(struct ast_udptl *udptl)
676 struct ast_sockaddr addr;
678 uint16_t *udptlheader;
680 /* Cache where the header will go */
681 res = ast_recvfrom(udptl->fd,
682 udptl->rawdata + AST_FRIENDLY_OFFSET,
683 sizeof(udptl->rawdata) - AST_FRIENDLY_OFFSET,
686 udptlheader = (uint16_t *)(udptl->rawdata + AST_FRIENDLY_OFFSET);
689 ast_log(LOG_WARNING, "(%s): UDPTL read error: %s\n",
690 LOG_TAG(udptl), strerror(errno));
691 ast_assert(errno != EBADF);
692 return &ast_null_frame;
695 /* Ignore if the other side hasn't been given an address yet. */
696 if (ast_sockaddr_isnull(&udptl->them)) {
697 return &ast_null_frame;
701 /* Send to whoever sent to us */
702 if (ast_sockaddr_cmp(&udptl->them, &addr)) {
703 ast_sockaddr_copy(&udptl->them, &addr);
704 ast_debug(1, "UDPTL NAT (%s): Using address %s\n",
705 LOG_TAG(udptl), ast_sockaddr_stringify(&udptl->them));
709 if (udptl_debug_test_addr(&addr)) {
710 ast_verb(1, "UDPTL (%s): packet from %s (type %d, seq %d, len %d)\n",
711 LOG_TAG(udptl), ast_sockaddr_stringify(&addr), 0, seqno, res);
713 if (udptl_rx_packet(udptl, udptl->rawdata + AST_FRIENDLY_OFFSET, res) < 1)
714 return &ast_null_frame;
719 static void calculate_local_max_datagram(struct ast_udptl *udptl)
721 unsigned int new_max = 0;
723 if (udptl->local_max_ifp == -1) {
724 ast_log(LOG_WARNING, "(%s): Cannot calculate local_max_datagram before local_max_ifp has been set.\n",
726 udptl->local_max_datagram = -1;
730 /* calculate the amount of space required to receive an IFP
731 * of the maximum size supported by the application/endpoint
732 * that we are delivering them to (local endpoint), and add
733 * the amount of space required to support the selected
734 * error correction mode
736 switch (udptl->error_correction_scheme) {
737 case UDPTL_ERROR_CORRECTION_NONE:
738 /* need room for sequence number, length indicator, redundancy
739 * indicator and following length indicator
741 new_max = 5 + udptl->local_max_ifp;
743 case UDPTL_ERROR_CORRECTION_REDUNDANCY:
744 /* need room for sequence number, length indicators, plus
745 * room for up to 3 redundancy packets
747 new_max = 5 + udptl->local_max_ifp + 2 + (3 * udptl->local_max_ifp);
749 case UDPTL_ERROR_CORRECTION_FEC:
750 /* need room for sequence number, length indicators and a
751 * a single IFP of the maximum size expected
753 new_max = 5 + udptl->local_max_ifp + 4 + udptl->local_max_ifp;
756 /* add 5% extra space for insurance, but no larger than LOCAL_FAX_MAX_DATAGRAM */
757 udptl->local_max_datagram = MIN(new_max * 1.05, LOCAL_FAX_MAX_DATAGRAM);
760 static void calculate_far_max_ifp(struct ast_udptl *udptl)
762 unsigned new_max = 0;
764 if (udptl->far_max_datagram == -1) {
765 ast_log(LOG_WARNING, "(%s): Cannot calculate far_max_ifp before far_max_datagram has been set.\n",
767 udptl->far_max_ifp = -1;
771 /* the goal here is to supply the local endpoint (application
772 * or bridged channel) a maximum IFP value that will allow it
773 * to effectively and efficiently transfer image data at its
774 * selected bit rate, taking into account the selected error
775 * correction mode, but without overrunning the far endpoint's
776 * datagram buffer. this is complicated by the fact that some
777 * far endpoints send us bogus (small) max datagram values,
778 * which would result in either buffer overrun or no error
779 * correction. we try to accomodate those, but if the supplied
780 * value is too small to do so, we'll emit warning messages and
781 * the user will have to use configuration options to override
782 * the max datagram value supplied by the far endpoint.
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 = udptl->far_max_datagram - 5;
791 case UDPTL_ERROR_CORRECTION_REDUNDANCY:
792 /* for this case, we'd like to send as many error correction entries
793 * as possible (up to the number we're configured for), but we'll settle
794 * for sending fewer if the configured number would cause the
795 * calculated max IFP to be too small for effective operation
797 * need room for sequence number, length indicators and the
798 * configured number of redundant packets
800 * note: we purposely don't allow error_correction_entries to drop to
801 * zero in this loop; we'd rather send smaller IFPs (and thus reduce
802 * the image data transfer rate) than sacrifice redundancy completely
805 new_max = (udptl->far_max_datagram - 8) / (udptl->error_correction_entries + 1);
807 if ((new_max < 80) && (udptl->error_correction_entries > 1)) {
808 /* the max ifp is not large enough, subtract an
809 * error correction entry and calculate again
811 --udptl->error_correction_entries;
817 case UDPTL_ERROR_CORRECTION_FEC:
818 /* need room for sequence number, length indicators and a
819 * a single IFP of the maximum size expected
821 new_max = (udptl->far_max_datagram - 10) / 2;
824 /* subtract 5% of space for insurance */
825 udptl->far_max_ifp = new_max * 0.95;
828 enum ast_t38_ec_modes ast_udptl_get_error_correction_scheme(const struct ast_udptl *udptl)
830 return udptl->error_correction_scheme;
833 void ast_udptl_set_error_correction_scheme(struct ast_udptl *udptl, enum ast_t38_ec_modes ec)
835 udptl->error_correction_scheme = ec;
837 case UDPTL_ERROR_CORRECTION_FEC:
838 udptl->error_correction_scheme = UDPTL_ERROR_CORRECTION_FEC;
839 if (udptl->error_correction_entries == 0) {
840 udptl->error_correction_entries = 3;
842 if (udptl->error_correction_span == 0) {
843 udptl->error_correction_span = 3;
846 case UDPTL_ERROR_CORRECTION_REDUNDANCY:
847 udptl->error_correction_scheme = UDPTL_ERROR_CORRECTION_REDUNDANCY;
848 if (udptl->error_correction_entries == 0) {
849 udptl->error_correction_entries = 3;
856 /* reset calculated values so they'll be computed again */
857 udptl->local_max_datagram = -1;
858 udptl->far_max_ifp = -1;
861 void ast_udptl_set_local_max_ifp(struct ast_udptl *udptl, unsigned int max_ifp)
863 /* make sure max_ifp is a positive value since a cast will take place when
864 * when setting local_max_ifp */
865 if ((signed int) max_ifp > 0) {
866 udptl->local_max_ifp = max_ifp;
867 /* reset calculated values so they'll be computed again */
868 udptl->local_max_datagram = -1;
872 unsigned int ast_udptl_get_local_max_datagram(struct ast_udptl *udptl)
874 if (udptl->local_max_datagram == -1) {
875 calculate_local_max_datagram(udptl);
878 /* this function expects a unsigned value in return. */
879 if (udptl->local_max_datagram < 0) {
882 return udptl->local_max_datagram;
885 void ast_udptl_set_far_max_datagram(struct ast_udptl *udptl, unsigned int max_datagram)
887 if (!max_datagram || (max_datagram > FAX_MAX_DATAGRAM_LIMIT)) {
888 udptl->far_max_datagram = DEFAULT_FAX_MAX_DATAGRAM;
890 udptl->far_max_datagram = max_datagram;
892 /* reset calculated values so they'll be computed again */
893 udptl->far_max_ifp = -1;
896 unsigned int ast_udptl_get_far_max_datagram(const struct ast_udptl *udptl)
898 if (udptl->far_max_datagram < 0) {
901 return udptl->far_max_datagram;
904 unsigned int ast_udptl_get_far_max_ifp(struct ast_udptl *udptl)
906 if (udptl->far_max_ifp == -1) {
907 calculate_far_max_ifp(udptl);
910 if (udptl->far_max_ifp < 0) {
913 return udptl->far_max_ifp;
916 struct ast_udptl *ast_udptl_new_with_bindaddr(struct ast_sched_context *sched, struct io_context *io, int callbackmode, struct ast_sockaddr *addr)
918 struct ast_udptl *udptl;
924 if (!(udptl = ast_calloc(1, sizeof(*udptl))))
927 udptl->error_correction_span = udptlfecspan;
928 udptl->error_correction_entries = udptlfecentries;
930 udptl->far_max_datagram = -1;
931 udptl->far_max_ifp = -1;
932 udptl->local_max_ifp = -1;
933 udptl->local_max_datagram = -1;
935 for (i = 0; i <= UDPTL_BUF_MASK; i++) {
936 udptl->rx[i].buf_len = -1;
937 udptl->tx[i].buf_len = -1;
940 if ((udptl->fd = socket(ast_sockaddr_is_ipv6(addr) ?
941 AF_INET6 : AF_INET, SOCK_DGRAM, 0)) < 0) {
943 ast_log(LOG_WARNING, "Unable to allocate socket: %s\n", strerror(errno));
946 flags = fcntl(udptl->fd, F_GETFL);
947 fcntl(udptl->fd, F_SETFL, flags | O_NONBLOCK);
950 setsockopt(udptl->fd, SOL_SOCKET, SO_NO_CHECK, &nochecksums, sizeof(nochecksums));
952 /* Find us a place */
953 x = (udptlstart == udptlend) ? udptlstart : (ast_random() % (udptlend - udptlstart)) + udptlstart;
954 if (use_even_ports && (x & 1)) {
959 ast_sockaddr_copy(&udptl->us, addr);
960 ast_sockaddr_set_port(&udptl->us, x);
961 if (ast_bind(udptl->fd, &udptl->us) == 0) {
964 if (errno != EADDRINUSE) {
965 ast_log(LOG_WARNING, "Unexpected bind error: %s\n", strerror(errno));
970 if (use_even_ports) {
977 if (x == startplace) {
978 ast_log(LOG_WARNING, "No UDPTL ports remaining\n");
984 if (io && sched && callbackmode) {
985 /* Operate this one in a callback mode */
986 udptl->sched = sched;
988 udptl->ioid = ast_io_add(udptl->io, udptl->fd, udptlread, AST_IO_IN, udptl);
993 void ast_udptl_set_tag(struct ast_udptl *udptl, const char *format, ...)
998 ast_free(udptl->tag);
1001 va_start(ap, format);
1002 if (ast_vasprintf(&udptl->tag, format, ap) == -1) {
1008 int ast_udptl_setqos(struct ast_udptl *udptl, unsigned int tos, unsigned int cos)
1010 return ast_netsock_set_qos(udptl->fd, tos, cos, "UDPTL");
1013 void ast_udptl_set_peer(struct ast_udptl *udptl, const struct ast_sockaddr *them)
1015 ast_sockaddr_copy(&udptl->them, them);
1018 void ast_udptl_get_peer(const struct ast_udptl *udptl, struct ast_sockaddr *them)
1020 ast_sockaddr_copy(them, &udptl->them);
1023 void ast_udptl_get_us(const struct ast_udptl *udptl, struct ast_sockaddr *us)
1025 ast_sockaddr_copy(us, &udptl->us);
1028 void ast_udptl_stop(struct ast_udptl *udptl)
1030 ast_sockaddr_setnull(&udptl->them);
1033 void ast_udptl_destroy(struct ast_udptl *udptl)
1036 ast_io_remove(udptl->io, udptl->ioid);
1040 ast_free(udptl->tag);
1044 int ast_udptl_write(struct ast_udptl *s, struct ast_frame *f)
1047 unsigned int len = f->datalen;
1049 /* if no max datagram size is provided, use default value */
1050 const int bufsize = (s->far_max_datagram > 0) ? s->far_max_datagram : DEFAULT_FAX_MAX_DATAGRAM;
1051 uint8_t buf[bufsize];
1053 memset(buf, 0, sizeof(buf));
1055 /* If we have no peer, return immediately */
1056 if (ast_sockaddr_isnull(&s->them)) {
1060 /* If there is no data length, return immediately */
1061 if (f->datalen == 0)
1064 if ((f->frametype != AST_FRAME_MODEM) ||
1065 (f->subclass.codec != AST_MODEM_T38)) {
1066 ast_log(LOG_WARNING, "(%s): UDPTL can only send T.38 data.\n",
1071 if (len > s->far_max_ifp) {
1072 ast_log(LOG_WARNING,
1073 "(%s): UDPTL asked to send %d bytes of IFP when far end only prepared to accept %d bytes; data loss will occur."
1074 "You may need to override the T38FaxMaxDatagram value for this endpoint in the channel driver configuration.\n",
1075 LOG_TAG(s), len, s->far_max_ifp);
1076 len = s->far_max_ifp;
1079 /* Save seq_no for debug output because udptl_build_packet increments it */
1080 seq = s->tx_seq_no & 0xFFFF;
1082 /* Cook up the UDPTL packet, with the relevant EC info. */
1083 len = udptl_build_packet(s, buf, sizeof(buf), f->data.ptr, len);
1085 if ((signed int) len > 0 && !ast_sockaddr_isnull(&s->them)) {
1086 if ((res = ast_sendto(s->fd, buf, len, 0, &s->them)) < 0)
1087 ast_log(LOG_NOTICE, "(%s): UDPTL Transmission error to %s: %s\n",
1088 LOG_TAG(s), ast_sockaddr_stringify(&s->them), strerror(errno));
1089 if (udptl_debug_test_addr(&s->them))
1090 ast_verb(1, "UDPTL (%s): packet to %s (type %d, seq %d, len %d)\n",
1091 LOG_TAG(s), ast_sockaddr_stringify(&s->them), 0, seq, len);
1097 void ast_udptl_proto_unregister(struct ast_udptl_protocol *proto)
1099 AST_RWLIST_WRLOCK(&protos);
1100 AST_RWLIST_REMOVE(&protos, proto, list);
1101 AST_RWLIST_UNLOCK(&protos);
1104 int ast_udptl_proto_register(struct ast_udptl_protocol *proto)
1106 struct ast_udptl_protocol *cur;
1108 AST_RWLIST_WRLOCK(&protos);
1109 AST_RWLIST_TRAVERSE(&protos, cur, list) {
1110 if (cur->type == proto->type) {
1111 ast_log(LOG_WARNING, "Tried to register same protocol '%s' twice\n", cur->type);
1112 AST_RWLIST_UNLOCK(&protos);
1116 AST_RWLIST_INSERT_TAIL(&protos, proto, list);
1117 AST_RWLIST_UNLOCK(&protos);
1121 static struct ast_udptl_protocol *get_proto(struct ast_channel *chan)
1123 struct ast_udptl_protocol *cur = NULL;
1125 AST_RWLIST_RDLOCK(&protos);
1126 AST_RWLIST_TRAVERSE(&protos, cur, list) {
1127 if (cur->type == chan->tech->type)
1130 AST_RWLIST_UNLOCK(&protos);
1135 int ast_udptl_bridge(struct ast_channel *c0, struct ast_channel *c1, int flags, struct ast_frame **fo, struct ast_channel **rc)
1137 struct ast_frame *f;
1138 struct ast_channel *who;
1139 struct ast_channel *cs[3];
1140 struct ast_udptl *p0;
1141 struct ast_udptl *p1;
1142 struct ast_udptl_protocol *pr0;
1143 struct ast_udptl_protocol *pr1;
1144 struct ast_sockaddr ac0;
1145 struct ast_sockaddr ac1;
1146 struct ast_sockaddr t0;
1147 struct ast_sockaddr t1;
1152 ast_channel_lock(c0);
1153 while (ast_channel_trylock(c1)) {
1154 ast_channel_unlock(c0);
1156 ast_channel_lock(c0);
1158 pr0 = get_proto(c0);
1159 pr1 = get_proto(c1);
1161 ast_log(LOG_WARNING, "Can't find native functions for channel '%s'\n", c0->name);
1162 ast_channel_unlock(c0);
1163 ast_channel_unlock(c1);
1167 ast_log(LOG_WARNING, "Can't find native functions for channel '%s'\n", c1->name);
1168 ast_channel_unlock(c0);
1169 ast_channel_unlock(c1);
1172 pvt0 = c0->tech_pvt;
1173 pvt1 = c1->tech_pvt;
1174 p0 = pr0->get_udptl_info(c0);
1175 p1 = pr1->get_udptl_info(c1);
1177 /* Somebody doesn't want to play... */
1178 ast_channel_unlock(c0);
1179 ast_channel_unlock(c1);
1182 if (pr0->set_udptl_peer(c0, p1)) {
1183 ast_log(LOG_WARNING, "Channel '%s' failed to talk to '%s'\n", c0->name, c1->name);
1184 memset(&ac1, 0, sizeof(ac1));
1186 /* Store UDPTL peer */
1187 ast_udptl_get_peer(p1, &ac1);
1189 if (pr1->set_udptl_peer(c1, p0)) {
1190 ast_log(LOG_WARNING, "Channel '%s' failed to talk back to '%s'\n", c1->name, c0->name);
1191 memset(&ac0, 0, sizeof(ac0));
1193 /* Store UDPTL peer */
1194 ast_udptl_get_peer(p0, &ac0);
1196 ast_channel_unlock(c0);
1197 ast_channel_unlock(c1);
1202 if ((c0->tech_pvt != pvt0) ||
1203 (c1->tech_pvt != pvt1) ||
1204 (c0->masq || c0->masqr || c1->masq || c1->masqr)) {
1205 ast_debug(1, "Oooh, something is weird, backing out\n");
1206 /* Tell it to try again later */
1210 ast_udptl_get_peer(p1, &t1);
1211 ast_udptl_get_peer(p0, &t0);
1212 if (ast_sockaddr_cmp(&t1, &ac1)) {
1213 ast_debug(1, "Oooh, '%s' changed end address to %s\n",
1214 c1->name, ast_sockaddr_stringify(&t1));
1215 ast_debug(1, "Oooh, '%s' was %s\n",
1216 c1->name, ast_sockaddr_stringify(&ac1));
1217 ast_sockaddr_copy(&ac1, &t1);
1219 if (ast_sockaddr_cmp(&t0, &ac0)) {
1220 ast_debug(1, "Oooh, '%s' changed end address to %s\n",
1221 c0->name, ast_sockaddr_stringify(&t0));
1222 ast_debug(1, "Oooh, '%s' was %s\n",
1223 c0->name, ast_sockaddr_stringify(&ac0));
1224 ast_sockaddr_copy(&ac0, &t0);
1226 who = ast_waitfor_n(cs, 2, &to);
1228 ast_debug(1, "Ooh, empty read...\n");
1229 /* check for hangup / whentohangup */
1230 if (ast_check_hangup(c0) || ast_check_hangup(c1))
1238 ast_debug(1, "Oooh, got a %s\n", f ? "digit" : "hangup");
1239 /* That's all we needed */
1242 if (f->frametype == AST_FRAME_MODEM) {
1243 /* Forward T.38 frames if they happen upon us */
1246 } else if (who == c1) {
1252 /* Swap priority. Not that it's a big deal at this point */
1260 static char *handle_cli_udptl_set_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1264 e->command = "udptl set debug {on|off|ip}";
1266 "Usage: udptl set debug {on|off|ip host[:port]}\n"
1267 " Enable or disable dumping of UDPTL packets.\n"
1268 " If ip is specified, limit the dumped packets to those to and from\n"
1269 " the specified 'host' with optional port.\n";
1275 if (a->argc < 4 || a->argc > 5)
1276 return CLI_SHOWUSAGE;
1279 if (!strncasecmp(a->argv[3], "on", 2)) {
1281 memset(&udptldebugaddr, 0, sizeof(udptldebugaddr));
1282 ast_cli(a->fd, "UDPTL Debugging Enabled\n");
1283 } else if (!strncasecmp(a->argv[3], "off", 3)) {
1285 ast_cli(a->fd, "UDPTL Debugging Disabled\n");
1287 return CLI_SHOWUSAGE;
1290 struct ast_sockaddr *addrs;
1291 if (strncasecmp(a->argv[3], "ip", 2))
1292 return CLI_SHOWUSAGE;
1293 if (!ast_sockaddr_resolve(&addrs, a->argv[4], 0, 0)) {
1294 return CLI_SHOWUSAGE;
1296 ast_sockaddr_copy(&udptldebugaddr, &addrs[0]);
1297 ast_cli(a->fd, "UDPTL Debugging Enabled for IP: %s\n", ast_sockaddr_stringify(&udptldebugaddr));
1306 static struct ast_cli_entry cli_udptl[] = {
1307 AST_CLI_DEFINE(handle_cli_udptl_set_debug, "Enable/Disable UDPTL debugging")
1310 static void __ast_udptl_reload(int reload)
1312 struct ast_config *cfg;
1314 struct ast_flags config_flags = { reload ? CONFIG_FLAG_FILEUNCHANGED : 0 };
1316 cfg = ast_config_load2("udptl.conf", "udptl", config_flags);
1317 if (cfg == CONFIG_STATUS_FILEMISSING || cfg == CONFIG_STATUS_FILEUNCHANGED || cfg == CONFIG_STATUS_FILEINVALID) {
1323 udptlfecentries = 0;
1328 if ((s = ast_variable_retrieve(cfg, "general", "udptlstart"))) {
1329 udptlstart = atoi(s);
1330 if (udptlstart < 1024) {
1331 ast_log(LOG_WARNING, "Ports under 1024 are not allowed for T.38.\n");
1334 if (udptlstart > 65535) {
1335 ast_log(LOG_WARNING, "Ports over 65535 are invalid.\n");
1339 if ((s = ast_variable_retrieve(cfg, "general", "udptlend"))) {
1341 if (udptlend < 1024) {
1342 ast_log(LOG_WARNING, "Ports under 1024 are not allowed for T.38.\n");
1345 if (udptlend > 65535) {
1346 ast_log(LOG_WARNING, "Ports over 65535 are invalid.\n");
1350 if ((s = ast_variable_retrieve(cfg, "general", "udptlchecksums"))) {
1358 ast_log(LOG_WARNING, "Disabling UDPTL checksums is not supported on this operating system!\n");
1361 if ((s = ast_variable_retrieve(cfg, "general", "T38FaxUdpEC"))) {
1362 ast_log(LOG_WARNING, "T38FaxUdpEC in udptl.conf is no longer supported; use the t38pt_udptl configuration option in sip.conf instead.\n");
1364 if ((s = ast_variable_retrieve(cfg, "general", "T38FaxMaxDatagram"))) {
1365 ast_log(LOG_WARNING, "T38FaxMaxDatagram in udptl.conf is no longer supported; value is now supplied by T.38 applications.\n");
1367 if ((s = ast_variable_retrieve(cfg, "general", "UDPTLFECEntries"))) {
1368 udptlfecentries = atoi(s);
1369 if (udptlfecentries < 1) {
1370 ast_log(LOG_WARNING, "Too small UDPTLFECEntries value. Defaulting to 1.\n");
1371 udptlfecentries = 1;
1373 if (udptlfecentries > MAX_FEC_ENTRIES) {
1374 ast_log(LOG_WARNING, "Too large UDPTLFECEntries value. Defaulting to %d.\n", MAX_FEC_ENTRIES);
1375 udptlfecentries = MAX_FEC_ENTRIES;
1378 if ((s = ast_variable_retrieve(cfg, "general", "UDPTLFECSpan"))) {
1379 udptlfecspan = atoi(s);
1380 if (udptlfecspan < 1) {
1381 ast_log(LOG_WARNING, "Too small UDPTLFECSpan value. Defaulting to 1.\n");
1384 if (udptlfecspan > MAX_FEC_SPAN) {
1385 ast_log(LOG_WARNING, "Too large UDPTLFECSpan value. Defaulting to %d.\n", MAX_FEC_SPAN);
1386 udptlfecspan = MAX_FEC_SPAN;
1389 if ((s = ast_variable_retrieve(cfg, "general", "use_even_ports"))) {
1390 use_even_ports = ast_true(s);
1392 ast_config_destroy(cfg);
1394 if (udptlstart >= udptlend) {
1395 ast_log(LOG_WARNING, "Unreasonable values for UDPTL start/end ports; defaulting to 4500-4999.\n");
1399 if (use_even_ports && (udptlstart & 1)) {
1401 ast_log(LOG_NOTICE, "Odd numbered udptlstart specified but use_even_ports enabled. udptlstart is now %d\n", udptlstart);
1403 if (use_even_ports && (udptlend & 1)) {
1405 ast_log(LOG_NOTICE, "Odd numbered udptlend specified but use_event_ports enabled. udptlend is now %d\n", udptlend);
1407 ast_verb(2, "UDPTL allocating from port range %d -> %d\n", udptlstart, udptlend);
1410 int ast_udptl_reload(void)
1412 __ast_udptl_reload(1);
1416 void ast_udptl_init(void)
1418 ast_cli_register_multiple(cli_udptl, ARRAY_LEN(cli_udptl));
1419 __ast_udptl_reload(0);