BuildSystem: Remove unused variables.
[asterisk/asterisk.git] / main / udptl.c
index a90e899..5a491e6 100644 (file)
@@ -1,8 +1,8 @@
 /*
- * Asterisk -- A telephony toolkit for Linux.
+ * Asterisk -- An open source telephony toolkit.
  *
  * UDPTL support for T.38
- * 
+ *
  * Copyright (C) 2005, Steve Underwood, partly based on RTP code which is
  * Copyright (C) 1999-2009, Digium, Inc.
  *
  * this code.
  */
 
-/*! 
- * \file 
+/*!
+ * \file
  *
  * \brief UDPTL support for T.38 faxing
- * 
+ *
  *
  * \author Mark Spencer <markster@digium.com>
  * \author Steve Underwood <steveu@coppice.org>
  * \author Kevin P. Fleming <kpfleming@digium.com>
- * 
+ *
  * \page T38fax_udptl T.38 support :: UDPTL
  *
  * Asterisk supports T.38 fax passthrough, origination and termination. It does
  *
  * UDPTL is handled very much like RTP. It can be reinvited to go directly between
  * the endpoints, without involving Asterisk in the media stream.
- * 
+ *
  * \b References:
  * - chan_sip.c
  * - udptl.c
  * - app_fax.c
  */
 
+/*! \li \ref udptl.c uses the configuration file \ref udptl.conf
+ * \addtogroup configuration_file Configuration Files
+ */
 
-#include "asterisk.h"
+/*!
+ * \page udptl.conf udptl.conf
+ * \verbinclude udptl.conf.sample
+ */
+
+/*** MODULEINFO
+       <support_level>core</support_level>
+ ***/
 
-ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
+#include "asterisk.h"
 
 #include <sys/time.h>
 #include <signal.h>
@@ -61,13 +71,47 @@ ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
 #include "asterisk/frame.h"
 #include "asterisk/channel.h"
 #include "asterisk/acl.h"
-#include "asterisk/config.h"
+#include "asterisk/config_options.h"
 #include "asterisk/lock.h"
 #include "asterisk/utils.h"
-#include "asterisk/netsock.h"
+#include "asterisk/netsock2.h"
 #include "asterisk/cli.h"
 #include "asterisk/unaligned.h"
 
+/*** DOCUMENTATION
+       <configInfo name="udptl" language="en_US">
+               <configFile name="udptl.conf">
+                       <configObject name="global">
+                               <synopsis>Global options for configuring UDPTL</synopsis>
+                               <configOption name="udptlstart">
+                                       <synopsis>The start of the UDPTL port range</synopsis>
+                               </configOption>
+                               <configOption name="udptlend">
+                                       <synopsis>The end of the UDPTL port range</synopsis>
+                               </configOption>
+                               <configOption name="udptlchecksums">
+                                       <synopsis>Whether to enable or disable UDP checksums on UDPTL traffic</synopsis>
+                               </configOption>
+                               <configOption name="udptlfecentries">
+                                       <synopsis>The number of error correction entries in a UDPTL packet</synopsis>
+                               </configOption>
+                               <configOption name="udptlfecspan">
+                                       <synopsis>The span over which parity is calculated for FEC in a UDPTL packet</synopsis>
+                               </configOption>
+                               <configOption name="use_even_ports">
+                                       <synopsis>Whether to only use even-numbered UDPTL ports</synopsis>
+                               </configOption>
+                               <configOption name="t38faxudpec">
+                                       <synopsis>Removed</synopsis>
+                               </configOption>
+                               <configOption name="t38faxmaxdatagram">
+                                       <synopsis>Removed</synopsis>
+                               </configOption>
+                       </configObject>
+               </configFile>
+       </configInfo>
+***/
+
 #define UDPTL_MTU              1200
 
 #if !defined(FALSE)
@@ -79,16 +123,11 @@ ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
 
 #define LOG_TAG(u) S_OR(u->tag, "no tag")
 
-static int udptlstart = 4500;
-static int udptlend = 4599;
+#define DEFAULT_UDPTLSTART 4000
+#define DEFAULT_UDPTLEND 4999
+
 static int udptldebug;                     /*!< Are we debugging? */
 static struct ast_sockaddr udptldebugaddr;   /*!< Debug packets to/from this host */
-#ifdef SO_NO_CHECK
-static int nochecksums;
-#endif
-static int udptlfecentries;
-static int udptlfecspan;
-static int use_even_ports;
 
 #define LOCAL_FAX_MAX_DATAGRAM      1400
 #define DEFAULT_FAX_MAX_DATAGRAM    400
@@ -172,13 +211,48 @@ struct ast_udptl {
 
        unsigned int tx_seq_no;
        unsigned int rx_seq_no;
-       unsigned int rx_expected_seq_no;
 
        udptl_fec_tx_buffer_t tx[UDPTL_BUF_MASK + 1];
        udptl_fec_rx_buffer_t rx[UDPTL_BUF_MASK + 1];
 };
 
-static AST_RWLIST_HEAD_STATIC(protos, ast_udptl_protocol);
+struct udptl_global_options {
+       unsigned int start; /*< The UDPTL start port */
+       unsigned int end;   /*< The UDPTL end port */
+       unsigned int fecentries;
+       unsigned int fecspan;
+       unsigned int nochecksums;
+       unsigned int use_even_ports;
+};
+
+static AO2_GLOBAL_OBJ_STATIC(globals);
+
+struct udptl_config {
+       struct udptl_global_options *general;
+};
+
+static void *udptl_snapshot_alloc(void);
+static int udptl_pre_apply_config(void);
+
+static struct aco_type general_option = {
+       .type = ACO_GLOBAL,
+       .name = "global",
+       .category_match = ACO_WHITELIST_EXACT,
+       .item_offset = offsetof(struct udptl_config, general),
+       .category = "general",
+};
+
+static struct aco_type *general_options[] = ACO_TYPES(&general_option);
+
+static struct aco_file udptl_conf = {
+       .filename = "udptl.conf",
+       .types = ACO_TYPES(&general_option),
+};
+
+CONFIG_INFO_CORE("udptl", cfg_info, globals, udptl_snapshot_alloc,
+       .files = ACO_FILES(&udptl_conf),
+       .pre_apply_config = udptl_pre_apply_config,
+);
 
 static inline int udptl_debug_test_addr(const struct ast_sockaddr *addr)
 {
@@ -229,16 +303,15 @@ static int decode_open_type(uint8_t *buf, unsigned int limit, unsigned int *len,
        if (decode_length(buf, limit, len, &octet_cnt) != 0)
                return -1;
 
-       if (octet_cnt > 0) {
-               /* Make sure the buffer contains at least the number of bits requested */
-               if ((*len + octet_cnt) > limit)
-                       return -1;
-
-               *p_num_octets = octet_cnt;
-               *p_object = &buf[*len];
-               *len += octet_cnt;
+       /* Make sure the buffer contains at least the number of bits requested */
+       if ((*len + octet_cnt) > limit) {
+               return -1;
        }
 
+       *p_num_octets = octet_cnt;
+       *p_object = &buf[*len];
+       *len += octet_cnt;
+
        return 0;
 }
 /*- End of function --------------------------------------------------------*/
@@ -286,10 +359,9 @@ static int encode_open_type(const struct ast_udptl *udptl, uint8_t *buf, unsigne
        }
        /* Encode the open type */
        for (octet_idx = 0; ; num_octets -= enclen, octet_idx += enclen) {
-               if ((enclen = encode_length(buf, len, num_octets)) < 0)
-                       return -1;
+               enclen = encode_length(buf, len, num_octets);
                if (enclen + *len > buflen) {
-                       ast_log(LOG_ERROR, "(%s): Buffer overflow detected (%d + %d > %d)\n",
+                       ast_log(LOG_ERROR, "UDPTL (%s): Buffer overflow detected (%u + %u > %u)\n",
                                LOG_TAG(udptl), enclen, *len, buflen);
                        return -1;
                }
@@ -310,20 +382,11 @@ static int udptl_rx_packet(struct ast_udptl *s, uint8_t *buf, unsigned int len)
        int stat1;
        int stat2;
        int i;
-       int j;
-       int k;
-       int l;
-       int m;
-       int x;
-       int limit;
-       int which;
-       unsigned int ptr;
-       unsigned int count;
-       int total_count;
+       unsigned int ptr;       /* an index that keeps track of how much of the UDPTL packet has been processed */
        int seq_no;
-       const uint8_t *ifp;
-       const uint8_t *data;
-       unsigned int ifp_len;
+       const uint8_t *ifp = NULL;
+       const uint8_t *data = NULL;
+       unsigned int ifp_len = 0;
        int repaired[16];
        const uint8_t *bufs[ARRAY_LEN(s->f) - 1];
        unsigned int lengths[ARRAY_LEN(s->f) - 1];
@@ -352,13 +415,21 @@ static int udptl_rx_packet(struct ast_udptl *s, uint8_t *buf, unsigned int len)
                if (seq_no > s->rx_seq_no) {
                        /* We received a later packet than we expected, so we need to check if we can fill in the gap from the
                           secondary packets. */
-                       total_count = 0;
+                       int total_count = 0;
                        do {
+                               unsigned int count;
                                if ((stat2 = decode_length(buf, len, &ptr, &count)) < 0)
                                        return -1;
                                for (i = 0; i < count && total_count + i < ARRAY_LEN(bufs); i++) {
-                                       if ((stat1 = decode_open_type(buf, len, &ptr, &bufs[total_count + i], &lengths[total_count + i])) != 0)
+                                       if ((stat1 = decode_open_type(buf, len, &ptr, &bufs[total_count + i], &lengths[total_count + i])) != 0) {
                                                return -1;
+                                       }
+                                       /* valid secondaries can contain zero-length packets that should be ignored */
+                                       if (!bufs[total_count + i] || !lengths[total_count + i]) {
+                                               /* drop the count of items to process and reuse the buffers that were just set */
+                                               i--;
+                                               count--;
+                                       }
                                }
                                total_count += i;
                        }
@@ -368,7 +439,7 @@ static int udptl_rx_packet(struct ast_udptl *s, uint8_t *buf, unsigned int len)
                                if (seq_no - i >= s->rx_seq_no) {
                                        /* This one wasn't seen before */
                                        /* Decode the secondary IFP packet */
-                                       //fprintf(stderr, "Secondary %d, len %d\n", seq_no - i, lengths[i - 1]);
+                                       ast_debug(3, "Recovering lost packet via secondary %d, len %u\n", seq_no - i, lengths[i - 1]);
                                        s->f[ifp_no].frametype = AST_FRAME_MODEM;
                                        s->f[ifp_no].subclass.integer = AST_MODEM_T38;
 
@@ -388,6 +459,9 @@ static int udptl_rx_packet(struct ast_udptl *s, uint8_t *buf, unsigned int len)
        }
        else
        {
+               int j;
+               int l;
+               int x;
                /* FEC mode for error recovery */
                /* Our buffers cannot tolerate overlength IFP packets in FEC mode */
                if (ifp_len > LOCAL_FAX_MAX_DATAGRAM)
@@ -442,7 +516,7 @@ static int udptl_rx_packet(struct ast_udptl *s, uint8_t *buf, unsigned int len)
 #if 0
                        fprintf(stderr, "FEC: ");
                        for (j = 0; j < s->rx[x].fec_len[i]; j++)
-                               fprintf(stderr, "%02X ", data[j]);
+                               fprintf(stderr, "%02hhX ", data[j]);
                        fprintf(stderr, "\n");
 #endif
                }
@@ -450,10 +524,19 @@ static int udptl_rx_packet(struct ast_udptl *s, uint8_t *buf, unsigned int len)
                /* See if we can reconstruct anything which is missing */
                /* TODO: this does not comprehensively hunt back and repair everything that is possible */
                for (l = x; l != ((x - (16 - span*entries)) & UDPTL_BUF_MASK); l = (l - 1) & UDPTL_BUF_MASK) {
+                       int m;
                        if (s->rx[l].fec_len[0] <= 0)
                                continue;
                        for (m = 0; m < s->rx[l].fec_entries; m++) {
-                               limit = (l + m) & UDPTL_BUF_MASK;
+                               int k;
+                               int which;
+                               int limit = (l + m) & UDPTL_BUF_MASK;
+
+                               /* only repair buffers that actually exist! */
+                               if (seq_no <= (s->rx[l].fec_span * s->rx[l].fec_entries) - m) {
+                                       continue;
+                               }
+
                                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) {
                                        if (s->rx[k].buf_len <= 0)
                                                which = (which == -1) ? k : -2;
@@ -476,7 +559,7 @@ static int udptl_rx_packet(struct ast_udptl *s, uint8_t *buf, unsigned int len)
                                //fprintf(stderr, "Fixed packet %d, len %d\n", j, l);
                                s->f[ifp_no].frametype = AST_FRAME_MODEM;
                                s->f[ifp_no].subclass.integer = AST_MODEM_T38;
-                       
+
                                s->f[ifp_no].mallocd = 0;
                                s->f[ifp_no].seqno = j;
                                s->f[ifp_no].datalen = s->rx[l].buf_len;
@@ -497,7 +580,7 @@ static int udptl_rx_packet(struct ast_udptl *s, uint8_t *buf, unsigned int len)
                /* Decode the primary IFP packet */
                s->f[ifp_no].frametype = AST_FRAME_MODEM;
                s->f[ifp_no].subclass.integer = AST_MODEM_T38;
-               
+
                s->f[ifp_no].mallocd = 0;
                s->f[ifp_no].seqno = seq_no;
                s->f[ifp_no].datalen = ifp_len;
@@ -518,7 +601,7 @@ static int udptl_rx_packet(struct ast_udptl *s, uint8_t *buf, unsigned int len)
 
 static int udptl_build_packet(struct ast_udptl *s, uint8_t *buf, unsigned int buflen, uint8_t *ifp, unsigned int ifp_len)
 {
-       uint8_t fec[LOCAL_FAX_MAX_DATAGRAM * 2];
+       uint8_t fec[LOCAL_FAX_MAX_DATAGRAM * 2] = { 0, };
        int i;
        int j;
        int seq;
@@ -539,7 +622,7 @@ static int udptl_build_packet(struct ast_udptl *s, uint8_t *buf, unsigned int bu
           redundancy sets later on. */
        s->tx[entry].buf_len = ifp_len;
        memcpy(s->tx[entry].buf, ifp, ifp_len);
-       
+
        /* Build the UDPTLPacket */
 
        len = 0;
@@ -559,8 +642,7 @@ static int udptl_build_packet(struct ast_udptl *s, uint8_t *buf, unsigned int bu
                buf[len++] = 0x00;
                /* The number of entries will always be zero, so it is pointless allowing
                   for the fragmented case here. */
-               if (encode_length(buf, &len, 0) < 0)
-                       return -1;
+               encode_length(buf, &len, 0);
                break;
        case UDPTL_ERROR_CORRECTION_REDUNDANCY:
                /* Encode the error recovery type */
@@ -571,13 +653,12 @@ static int udptl_build_packet(struct ast_udptl *s, uint8_t *buf, unsigned int bu
                        entries = s->tx_seq_no;
                /* The number of entries will always be small, so it is pointless allowing
                   for the fragmented case here. */
-               if (encode_length(buf, &len, entries) < 0)
-                       return -1;
+               encode_length(buf, &len, entries);
                /* Encode the elements */
                for (i = 0; i < entries; i++) {
                        j = (entry - i - 1) & UDPTL_BUF_MASK;
                        if (encode_open_type(s, buf, buflen, &len, s->tx[j].buf, s->tx[j].buf_len) < 0) {
-                               ast_debug(1, "(%s): Encoding failed at i=%d, j=%d\n",
+                               ast_debug(1, "UDPTL (%s): Encoding failed at i=%d, j=%d\n",
                                          LOG_TAG(s), i, j);
                                return -1;
                        }
@@ -663,19 +744,19 @@ struct ast_frame *ast_udptl_read(struct ast_udptl *udptl)
 {
        int res;
        struct ast_sockaddr addr;
-       uint16_t seqno = 0;
-       uint16_t *udptlheader;
-       
+       uint8_t *buf;
+
+       buf = udptl->rawdata + AST_FRIENDLY_OFFSET;
+
        /* Cache where the header will go */
        res = ast_recvfrom(udptl->fd,
-                       udptl->rawdata + AST_FRIENDLY_OFFSET,
+                       buf,
                        sizeof(udptl->rawdata) - AST_FRIENDLY_OFFSET,
                        0,
                        &addr);
-       udptlheader = (uint16_t *)(udptl->rawdata + AST_FRIENDLY_OFFSET);
        if (res < 0) {
                if (errno != EAGAIN)
-                       ast_log(LOG_WARNING, "(%s): UDPTL read error: %s\n",
+                       ast_log(LOG_WARNING, "UDPTL (%s): read error: %s\n",
                                LOG_TAG(udptl), strerror(errno));
                ast_assert(errno != EBADF);
                return &ast_null_frame;
@@ -686,21 +767,44 @@ struct ast_frame *ast_udptl_read(struct ast_udptl *udptl)
                return &ast_null_frame;
        }
 
+       /*
+        * If early media isn't turned on for the channel driver, it's going to
+        * drop this frame.  By that time though, udptl has already incremented
+        * the expected sequence number so if the CPE re-sends, the second frame
+        * will be dropped as a dup even though the first frame never went through.
+        * So we drop the frame here if the channel isn't up. 'tag' is set by the
+        * channel drivers on T38_ENABLED or T38_PEER_REINVITE.
+        */
+       if (udptl->tag == NULL) {
+               return &ast_null_frame;
+       }
+
        if (udptl->nat) {
                /* Send to whoever sent to us */
                if (ast_sockaddr_cmp(&udptl->them, &addr)) {
                        ast_sockaddr_copy(&udptl->them, &addr);
-                       ast_debug(1, "UDPTL NAT (%s): Using address %s\n",
+                       ast_debug(1, "UDPTL (%s): NAT, Using address %s\n",
                                  LOG_TAG(udptl), ast_sockaddr_stringify(&udptl->them));
                }
        }
 
        if (udptl_debug_test_addr(&addr)) {
-               ast_verb(1, "UDPTL (%s): packet from %s (type %d, seq %d, len %d)\n",
-                        LOG_TAG(udptl), ast_sockaddr_stringify(&addr), 0, seqno, res);
+               int seq_no;
+
+               /* Decode sequence number just for verbose message. */
+               if (res < 2) {
+                       /* Short packet. */
+                       seq_no = -1;
+               } else {
+                       seq_no = (buf[0] << 8) | buf[1];
+               }
+
+               ast_verb(1, "UDPTL (%s): packet from %s (seq %d, len %d)\n",
+                       LOG_TAG(udptl), ast_sockaddr_stringify(&addr), seq_no, res);
        }
-       if (udptl_rx_packet(udptl, udptl->rawdata + AST_FRIENDLY_OFFSET, res) < 1)
+       if (udptl_rx_packet(udptl, buf, res) < 1) {
                return &ast_null_frame;
+       }
 
        return &udptl->f[0];
 }
@@ -710,7 +814,7 @@ static void calculate_local_max_datagram(struct ast_udptl *udptl)
        unsigned int new_max = 0;
 
        if (udptl->local_max_ifp == -1) {
-               ast_log(LOG_WARNING, "(%s): Cannot calculate local_max_datagram before local_max_ifp has been set.\n",
+               ast_log(LOG_WARNING, "UDPTL (%s): Cannot calculate local_max_datagram before local_max_ifp has been set.\n",
                        LOG_TAG(udptl));
                udptl->local_max_datagram = -1;
                return;
@@ -751,7 +855,7 @@ static void calculate_far_max_ifp(struct ast_udptl *udptl)
        unsigned new_max = 0;
 
        if (udptl->far_max_datagram == -1) {
-               ast_log(LOG_WARNING, "(%s): Cannot calculate far_max_ifp before far_max_datagram has been set.\n",
+               ast_log(LOG_WARNING, "UDPTL (%s): Cannot calculate far_max_ifp before far_max_datagram has been set.\n",
                        LOG_TAG(udptl));
                udptl->far_max_ifp = -1;
                return;
@@ -908,14 +1012,20 @@ struct ast_udptl *ast_udptl_new_with_bindaddr(struct ast_sched_context *sched, s
        int x;
        int startplace;
        int i;
-       long int flags;
+       RAII_VAR(struct udptl_config *, cfg, ao2_global_obj_ref(globals), ao2_cleanup);
 
-       if (!(udptl = ast_calloc(1, sizeof(*udptl))))
+       if (!cfg || !cfg->general) {
+               ast_log(LOG_ERROR, "Could not access global udptl options!\n");
                return NULL;
+       }
+
+       if (!(udptl = ast_calloc(1, sizeof(*udptl)))) {
+               return NULL;
+       }
+
+       udptl->error_correction_span = cfg->general->fecspan;
+       udptl->error_correction_entries = cfg->general->fecentries;
 
-       udptl->error_correction_span = udptlfecspan;
-       udptl->error_correction_entries = udptlfecentries;
-       
        udptl->far_max_datagram = -1;
        udptl->far_max_ifp = -1;
        udptl->local_max_ifp = -1;
@@ -932,15 +1042,16 @@ struct ast_udptl *ast_udptl_new_with_bindaddr(struct ast_sched_context *sched, s
                ast_log(LOG_WARNING, "Unable to allocate socket: %s\n", strerror(errno));
                return NULL;
        }
-       flags = fcntl(udptl->fd, F_GETFL);
-       fcntl(udptl->fd, F_SETFL, flags | O_NONBLOCK);
+       ast_fd_set_flags(udptl->fd, O_NONBLOCK);
+
 #ifdef SO_NO_CHECK
-       if (nochecksums)
-               setsockopt(udptl->fd, SOL_SOCKET, SO_NO_CHECK, &nochecksums, sizeof(nochecksums));
+       if (cfg->general->nochecksums)
+               setsockopt(udptl->fd, SOL_SOCKET, SO_NO_CHECK, &cfg->general->nochecksums, sizeof(cfg->general->nochecksums));
 #endif
+
        /* Find us a place */
-       x = (udptlstart == udptlend) ? udptlstart : (ast_random() % (udptlend - udptlstart)) + udptlstart;
-       if (use_even_ports && (x & 1)) {
+       x = (cfg->general->start == cfg->general->end) ? cfg->general->start : (ast_random() % (cfg->general->end - cfg->general->start)) + cfg->general->start;
+       if (cfg->general->use_even_ports && (x & 1)) {
                ++x;
        }
        startplace = x;
@@ -950,19 +1061,19 @@ struct ast_udptl *ast_udptl_new_with_bindaddr(struct ast_sched_context *sched, s
                if (ast_bind(udptl->fd, &udptl->us) == 0) {
                        break;
                }
-               if (errno != EADDRINUSE) {
+               if (errno != EADDRINUSE && errno != EACCES) {
                        ast_log(LOG_WARNING, "Unexpected bind error: %s\n", strerror(errno));
                        close(udptl->fd);
                        ast_free(udptl);
                        return NULL;
                }
-               if (use_even_ports) {
+               if (cfg->general->use_even_ports) {
                        x += 2;
                } else {
                        ++x;
                }
-               if (x > udptlend)
-                       x = udptlstart;
+               if (x > cfg->general->end)
+                       x = cfg->general->start;
                if (x == startplace) {
                        ast_log(LOG_WARNING, "No UDPTL ports remaining\n");
                        close(udptl->fd);
@@ -976,6 +1087,7 @@ struct ast_udptl *ast_udptl_new_with_bindaddr(struct ast_sched_context *sched, s
                udptl->io = io;
                udptl->ioid = ast_io_add(udptl->io, udptl->fd, udptlread, AST_IO_IN, udptl);
        }
+
        return udptl;
 }
 
@@ -983,10 +1095,8 @@ void ast_udptl_set_tag(struct ast_udptl *udptl, const char *format, ...)
 {
        va_list ap;
 
-       if (udptl->tag) {
-               ast_free(udptl->tag);
-               udptl->tag = NULL;
-       }
+       ast_free(udptl->tag);
+       udptl->tag = NULL;
        va_start(ap, format);
        if (ast_vasprintf(&udptl->tag, format, ap) == -1) {
                udptl->tag = NULL;
@@ -996,7 +1106,7 @@ void ast_udptl_set_tag(struct ast_udptl *udptl, const char *format, ...)
 
 int ast_udptl_setqos(struct ast_udptl *udptl, unsigned int tos, unsigned int cos)
 {
-       return ast_netsock_set_qos(udptl->fd, tos, cos, "UDPTL");
+       return ast_set_qos(udptl->fd, tos, cos, "UDPTL");
 }
 
 void ast_udptl_set_peer(struct ast_udptl *udptl, const struct ast_sockaddr *them)
@@ -1034,7 +1144,6 @@ int ast_udptl_write(struct ast_udptl *s, struct ast_frame *f)
 {
        unsigned int seq;
        unsigned int len = f->datalen;
-       int res;
        /* if no max datagram size is provided, use default value */
        const int bufsize = (s->far_max_datagram > 0) ? s->far_max_datagram : DEFAULT_FAX_MAX_DATAGRAM;
        uint8_t buf[bufsize];
@@ -1049,17 +1158,17 @@ int ast_udptl_write(struct ast_udptl *s, struct ast_frame *f)
        /* If there is no data length, return immediately */
        if (f->datalen == 0)
                return 0;
-       
+
        if ((f->frametype != AST_FRAME_MODEM) ||
            (f->subclass.integer != AST_MODEM_T38)) {
-               ast_log(LOG_WARNING, "(%s): UDPTL can only send T.38 data.\n",
+               ast_log(LOG_WARNING, "UDPTL (%s): UDPTL can only send T.38 data.\n",
                        LOG_TAG(s));
                return -1;
        }
 
        if (len > s->far_max_ifp) {
                ast_log(LOG_WARNING,
-                       "(%s): UDPTL asked to send %d bytes of IFP when far end only prepared to accept %d bytes; data loss will occur."
+                       "UDPTL (%s): UDPTL asked to send %u bytes of IFP when far end only prepared to accept %d bytes; data loss will occur."
                        "You may need to override the T38FaxMaxDatagram value for this endpoint in the channel driver configuration.\n",
                        LOG_TAG(s), len, s->far_max_ifp);
                len = s->far_max_ifp;
@@ -1072,178 +1181,17 @@ int ast_udptl_write(struct ast_udptl *s, struct ast_frame *f)
        len = udptl_build_packet(s, buf, sizeof(buf), f->data.ptr, len);
 
        if ((signed int) len > 0 && !ast_sockaddr_isnull(&s->them)) {
-               if ((res = ast_sendto(s->fd, buf, len, 0, &s->them)) < 0)
-                       ast_log(LOG_NOTICE, "(%s): UDPTL Transmission error to %s: %s\n",
+               if (ast_sendto(s->fd, buf, len, 0, &s->them) < 0) {
+                       ast_log(LOG_NOTICE, "UDPTL (%s): Transmission error to %s: %s\n",
                                LOG_TAG(s), ast_sockaddr_stringify(&s->them), strerror(errno));
-               if (udptl_debug_test_addr(&s->them))
-                       ast_verb(1, "UDPTL (%s): packet to %s (type %d, seq %d, len %d)\n",
-                                LOG_TAG(s), ast_sockaddr_stringify(&s->them), 0, seq, len);
-       }
-               
-       return 0;
-}
-
-void ast_udptl_proto_unregister(struct ast_udptl_protocol *proto)
-{
-       AST_RWLIST_WRLOCK(&protos);
-       AST_RWLIST_REMOVE(&protos, proto, list);
-       AST_RWLIST_UNLOCK(&protos);
-}
-
-int ast_udptl_proto_register(struct ast_udptl_protocol *proto)
-{
-       struct ast_udptl_protocol *cur;
-
-       AST_RWLIST_WRLOCK(&protos);
-       AST_RWLIST_TRAVERSE(&protos, cur, list) {
-               if (cur->type == proto->type) {
-                       ast_log(LOG_WARNING, "Tried to register same protocol '%s' twice\n", cur->type);
-                       AST_RWLIST_UNLOCK(&protos);
-                       return -1;
                }
-       }
-       AST_RWLIST_INSERT_TAIL(&protos, proto, list);
-       AST_RWLIST_UNLOCK(&protos);
-       return 0;
-}
-
-static struct ast_udptl_protocol *get_proto(struct ast_channel *chan)
-{
-       struct ast_udptl_protocol *cur = NULL;
-
-       AST_RWLIST_RDLOCK(&protos);
-       AST_RWLIST_TRAVERSE(&protos, cur, list) {
-               if (cur->type == chan->tech->type)
-                       break;
-       }
-       AST_RWLIST_UNLOCK(&protos);
-
-       return cur;
-}
-
-int ast_udptl_bridge(struct ast_channel *c0, struct ast_channel *c1, int flags, struct ast_frame **fo, struct ast_channel **rc)
-{
-       struct ast_frame *f;
-       struct ast_channel *who;
-       struct ast_channel *cs[3];
-       struct ast_udptl *p0;
-       struct ast_udptl *p1;
-       struct ast_udptl_protocol *pr0;
-       struct ast_udptl_protocol *pr1;
-       struct ast_sockaddr ac0;
-       struct ast_sockaddr ac1;
-       struct ast_sockaddr t0;
-       struct ast_sockaddr t1;
-       void *pvt0;
-       void *pvt1;
-       int to;
-       
-       ast_channel_lock(c0);
-       while (ast_channel_trylock(c1)) {
-               ast_channel_unlock(c0);
-               usleep(1);
-               ast_channel_lock(c0);
-       }
-       pr0 = get_proto(c0);
-       pr1 = get_proto(c1);
-       if (!pr0) {
-               ast_log(LOG_WARNING, "Can't find native functions for channel '%s'\n", c0->name);
-               ast_channel_unlock(c0);
-               ast_channel_unlock(c1);
-               return -1;
-       }
-       if (!pr1) {
-               ast_log(LOG_WARNING, "Can't find native functions for channel '%s'\n", c1->name);
-               ast_channel_unlock(c0);
-               ast_channel_unlock(c1);
-               return -1;
-       }
-       pvt0 = c0->tech_pvt;
-       pvt1 = c1->tech_pvt;
-       p0 = pr0->get_udptl_info(c0);
-       p1 = pr1->get_udptl_info(c1);
-       if (!p0 || !p1) {
-               /* Somebody doesn't want to play... */
-               ast_channel_unlock(c0);
-               ast_channel_unlock(c1);
-               return -2;
-       }
-       if (pr0->set_udptl_peer(c0, p1)) {
-               ast_log(LOG_WARNING, "Channel '%s' failed to talk to '%s'\n", c0->name, c1->name);
-               memset(&ac1, 0, sizeof(ac1));
-       } else {
-               /* Store UDPTL peer */
-               ast_udptl_get_peer(p1, &ac1);
-       }
-       if (pr1->set_udptl_peer(c1, p0)) {
-               ast_log(LOG_WARNING, "Channel '%s' failed to talk back to '%s'\n", c1->name, c0->name);
-               memset(&ac0, 0, sizeof(ac0));
-       } else {
-               /* Store UDPTL peer */
-               ast_udptl_get_peer(p0, &ac0);
-       }
-       ast_channel_unlock(c0);
-       ast_channel_unlock(c1);
-       cs[0] = c0;
-       cs[1] = c1;
-       cs[2] = NULL;
-       for (;;) {
-               if ((c0->tech_pvt != pvt0) ||
-                       (c1->tech_pvt != pvt1) ||
-                       (c0->masq || c0->masqr || c1->masq || c1->masqr)) {
-                               ast_debug(1, "Oooh, something is weird, backing out\n");
-                               /* Tell it to try again later */
-                               return -3;
-               }
-               to = -1;
-               ast_udptl_get_peer(p1, &t1);
-               ast_udptl_get_peer(p0, &t0);
-               if (ast_sockaddr_cmp(&t1, &ac1)) {
-                       ast_debug(1, "Oooh, '%s' changed end address to %s\n", 
-                               c1->name, ast_sockaddr_stringify(&t1));
-                       ast_debug(1, "Oooh, '%s' was %s\n", 
-                               c1->name, ast_sockaddr_stringify(&ac1));
-                       ast_sockaddr_copy(&ac1, &t1);
-               }
-               if (ast_sockaddr_cmp(&t0, &ac0)) {
-                       ast_debug(1, "Oooh, '%s' changed end address to %s\n", 
-                               c0->name, ast_sockaddr_stringify(&t0));
-                       ast_debug(1, "Oooh, '%s' was %s\n", 
-                               c0->name, ast_sockaddr_stringify(&ac0));
-                       ast_sockaddr_copy(&ac0, &t0);
-               }
-               who = ast_waitfor_n(cs, 2, &to);
-               if (!who) {
-                       ast_debug(1, "Ooh, empty read...\n");
-                       /* check for hangup / whentohangup */
-                       if (ast_check_hangup(c0) || ast_check_hangup(c1))
-                               break;
-                       continue;
-               }
-               f = ast_read(who);
-               if (!f) {
-                       *fo = f;
-                       *rc = who;
-                       ast_debug(1, "Oooh, got a %s\n", f ? "digit" : "hangup");
-                       /* That's all we needed */
-                       return 0;
-               } else {
-                       if (f->frametype == AST_FRAME_MODEM) {
-                               /* Forward T.38 frames if they happen upon us */
-                               if (who == c0) {
-                                       ast_write(c1, f);
-                               } else if (who == c1) {
-                                       ast_write(c0, f);
-                               }
-                       }
-                       ast_frfree(f);
+               if (udptl_debug_test_addr(&s->them)) {
+                       ast_verb(1, "UDPTL (%s): packet to %s (seq %u, len %u)\n",
+                               LOG_TAG(s), ast_sockaddr_stringify(&s->them), seq, len);
                }
-               /* Swap priority. Not that it's a big deal at this point */
-               cs[2] = cs[0];
-               cs[0] = cs[1];
-               cs[1] = cs[2];
        }
-       return -1;
+
+       return 0;
 }
 
 static char *handle_cli_udptl_set_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
@@ -1251,7 +1199,7 @@ static char *handle_cli_udptl_set_debug(struct ast_cli_entry *e, int cmd, struct
        switch (cmd) {
        case CLI_INIT:
                e->command = "udptl set debug {on|off|ip}";
-               e->usage = 
+               e->usage =
                        "Usage: udptl set debug {on|off|ip host[:port]}\n"
                        "       Enable or disable dumping of UDPTL packets.\n"
                        "       If ip is specified, limit the dumped packets to those to and from\n"
@@ -1291,109 +1239,120 @@ static char *handle_cli_udptl_set_debug(struct ast_cli_entry *e, int cmd, struct
        return CLI_SUCCESS;
 }
 
+static char *handle_cli_show_config(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
+{
+       RAII_VAR(struct udptl_config *, cfg, NULL, ao2_cleanup);
+
+       switch (cmd) {
+       case CLI_INIT:
+               e->command = "udptl show config";
+               e->usage =
+                       "Usage: udptl show config\n"
+                       "       Display UDPTL configuration options\n";
+               return NULL;
+       case CLI_GENERATE:
+               return NULL;
+       }
+
+       if (!(cfg = ao2_global_obj_ref(globals))) {
+               return CLI_FAILURE;
+       }
+
+       ast_cli(a->fd, "UDPTL Global options\n");
+       ast_cli(a->fd, "--------------------\n");
+       ast_cli(a->fd, "udptlstart:      %u\n", cfg->general->start);
+       ast_cli(a->fd, "udptlend:        %u\n", cfg->general->end);
+       ast_cli(a->fd, "udptlfecentries: %u\n", cfg->general->fecentries);
+       ast_cli(a->fd, "udptlfecspan:    %u\n", cfg->general->fecspan);
+       ast_cli(a->fd, "use_even_ports:  %s\n", AST_CLI_YESNO(cfg->general->use_even_ports));
+       ast_cli(a->fd, "udptlchecksums: %s\n", AST_CLI_YESNO(!cfg->general->nochecksums));
+
+       return CLI_SUCCESS;
+}
 
 static struct ast_cli_entry cli_udptl[] = {
-       AST_CLI_DEFINE(handle_cli_udptl_set_debug, "Enable/Disable UDPTL debugging")
+       AST_CLI_DEFINE(handle_cli_udptl_set_debug, "Enable/Disable UDPTL debugging"),
+       AST_CLI_DEFINE(handle_cli_show_config, "Show UDPTL config options"),
 };
 
-static void __ast_udptl_reload(int reload)
+static void udptl_config_destructor(void *obj)
 {
-       struct ast_config *cfg;
-       const char *s;
-       struct ast_flags config_flags = { reload ? CONFIG_FLAG_FILEUNCHANGED : 0 };
+       struct udptl_config *cfg = obj;
+       ao2_cleanup(cfg->general);
+}
 
-       cfg = ast_config_load2("udptl.conf", "udptl", config_flags);
-       if (cfg == CONFIG_STATUS_FILEMISSING || cfg == CONFIG_STATUS_FILEUNCHANGED || cfg == CONFIG_STATUS_FILEINVALID) {
-               return;
+static void *udptl_snapshot_alloc(void)
+{
+       struct udptl_config *cfg;
+
+       if (!(cfg = ao2_alloc(sizeof(*cfg), udptl_config_destructor))) {
+               return NULL;
+       }
+       if (!(cfg->general = ao2_alloc(sizeof(*cfg->general), NULL))) {
+               ao2_ref(cfg, -1);
+               return NULL;
        }
 
-       udptlstart = 4500;
-       udptlend = 4999;
-       udptlfecentries = 0;
-       udptlfecspan = 0;
-       use_even_ports = 0;
-
-       if (cfg) {
-               if ((s = ast_variable_retrieve(cfg, "general", "udptlstart"))) {
-                       udptlstart = atoi(s);
-                       if (udptlstart < 1024) {
-                               ast_log(LOG_WARNING, "Ports under 1024 are not allowed for T.38.\n");
-                               udptlstart = 1024;
-                       }
-                       if (udptlstart > 65535) {
-                               ast_log(LOG_WARNING, "Ports over 65535 are invalid.\n");
-                               udptlstart = 65535;
-                       }
-               }
-               if ((s = ast_variable_retrieve(cfg, "general", "udptlend"))) {
-                       udptlend = atoi(s);
-                       if (udptlend < 1024) {
-                               ast_log(LOG_WARNING, "Ports under 1024 are not allowed for T.38.\n");
-                               udptlend = 1024;
-                       }
-                       if (udptlend > 65535) {
-                               ast_log(LOG_WARNING, "Ports over 65535 are invalid.\n");
-                               udptlend = 65535;
-                       }
-               }
-               if ((s = ast_variable_retrieve(cfg, "general", "udptlchecksums"))) {
-#ifdef SO_NO_CHECK
-                       if (ast_false(s))
-                               nochecksums = 1;
-                       else
-                               nochecksums = 0;
-#else
-                       if (ast_false(s))
-                               ast_log(LOG_WARNING, "Disabling UDPTL checksums is not supported on this operating system!\n");
-#endif
-               }
-               if ((s = ast_variable_retrieve(cfg, "general", "T38FaxUdpEC"))) {
-                       ast_log(LOG_WARNING, "T38FaxUdpEC in udptl.conf is no longer supported; use the t38pt_udptl configuration option in sip.conf instead.\n");
-               }
-               if ((s = ast_variable_retrieve(cfg, "general", "T38FaxMaxDatagram"))) {
-                       ast_log(LOG_WARNING, "T38FaxMaxDatagram in udptl.conf is no longer supported; value is now supplied by T.38 applications.\n");
-               }
-               if ((s = ast_variable_retrieve(cfg, "general", "UDPTLFECEntries"))) {
-                       udptlfecentries = atoi(s);
-                       if (udptlfecentries < 1) {
-                               ast_log(LOG_WARNING, "Too small UDPTLFECEntries value.  Defaulting to 1.\n");
-                               udptlfecentries = 1;
-                       }
-                       if (udptlfecentries > MAX_FEC_ENTRIES) {
-                               ast_log(LOG_WARNING, "Too large UDPTLFECEntries value.  Defaulting to %d.\n", MAX_FEC_ENTRIES);
-                               udptlfecentries = MAX_FEC_ENTRIES;
-                       }
-               }
-               if ((s = ast_variable_retrieve(cfg, "general", "UDPTLFECSpan"))) {
-                       udptlfecspan = atoi(s);
-                       if (udptlfecspan < 1) {
-                               ast_log(LOG_WARNING, "Too small UDPTLFECSpan value.  Defaulting to 1.\n");
-                               udptlfecspan = 1;
-                       }
-                       if (udptlfecspan > MAX_FEC_SPAN) {
-                               ast_log(LOG_WARNING, "Too large UDPTLFECSpan value.  Defaulting to %d.\n", MAX_FEC_SPAN);
-                               udptlfecspan = MAX_FEC_SPAN;
+       return cfg;
+}
+
+static int removed_options_handler(const struct aco_option *opt, struct ast_variable *var, void *obj)
+{
+       if (!strcasecmp(var->name, "t38faxudpec")) {
+               ast_log(LOG_WARNING, "t38faxudpec in udptl.conf is no longer supported; use the t38pt_udptl configuration option in sip.conf instead.\n");
+       } else if (!strcasecmp(var->name, "t38faxmaxdatagram")) {
+               ast_log(LOG_WARNING, "t38faxmaxdatagram in udptl.conf is no longer supported; value is now supplied by T.38 applications.\n");
+       }
+       return 0;
+}
+
+static void __ast_udptl_reload(int reload)
+{
+       if (aco_process_config(&cfg_info, reload) == ACO_PROCESS_ERROR) {
+               if (!reload) {
+                       RAII_VAR(struct udptl_config *, udptl_cfg, udptl_snapshot_alloc(), ao2_cleanup);
+
+                       if (aco_set_defaults(&general_option, "general", udptl_cfg->general)) {
+                               ast_log(LOG_ERROR, "Failed to load udptl.conf and failed to initialize defaults.\n");
+                               return;
                        }
+
+                       ast_log(LOG_NOTICE, "Could not load udptl config; using defaults\n");
+                       ao2_global_obj_replace_unref(globals, udptl_cfg);
                }
-               if ((s = ast_variable_retrieve(cfg, "general", "use_even_ports"))) {
-                       use_even_ports = ast_true(s);
-               }
-               ast_config_destroy(cfg);
        }
-       if (udptlstart >= udptlend) {
-               ast_log(LOG_WARNING, "Unreasonable values for UDPTL start/end ports; defaulting to 4500-4999.\n");
-               udptlstart = 4500;
-               udptlend = 4999;
+}
+
+static int udptl_pre_apply_config(void) {
+       struct udptl_config *cfg = aco_pending_config(&cfg_info);
+
+       if (!cfg->general) {
+               return -1;
        }
-       if (use_even_ports && (udptlstart & 1)) {
-               ++udptlstart;
-               ast_log(LOG_NOTICE, "Odd numbered udptlstart specified but use_even_ports enabled. udptlstart is now %d\n", udptlstart);
+
+#ifndef SO_NO_CHECK
+       if (cfg->general->nochecksums) {
+               ast_log(LOG_WARNING, "Disabling UDPTL checksums is not supported on this operating system!\n");
+               cfg->general->nochecksums = 0;
        }
-       if (use_even_ports && (udptlend & 1)) {
-               --udptlend;
-               ast_log(LOG_NOTICE, "Odd numbered udptlend specified but use_event_ports enabled. udptlend is now %d\n", udptlend);
+#endif
+
+       /* Fix up any global config values that we can handle before replacing the config */
+       if (cfg->general->use_even_ports && (cfg->general->start & 1)) {
+               ++cfg->general->start;
+               ast_log(LOG_NOTICE, "Odd numbered udptlstart specified but use_even_ports enabled. udptlstart is now %u\n", cfg->general->start);
+       }
+       if (cfg->general->start > cfg->general->end) {
+               ast_log(LOG_WARNING, "Unreasonable values for UDPTL start/end ports; defaulting to %s-%s.\n", __stringify(DEFAULT_UDPTLSTART), __stringify(DEFAULT_UDPTLEND));
+               cfg->general->start = DEFAULT_UDPTLSTART;
+               cfg->general->end = DEFAULT_UDPTLEND;
+       }
+       if (cfg->general->use_even_ports && (cfg->general->end & 1)) {
+               --cfg->general->end;
+               ast_log(LOG_NOTICE, "Odd numbered udptlend specified but use_even_ports enabled. udptlend is now %u\n", cfg->general->end);
        }
-       ast_verb(2, "UDPTL allocating from port range %d -> %d\n", udptlstart, udptlend);
+
+       return 0;
 }
 
 int ast_udptl_reload(void)
@@ -1402,8 +1361,51 @@ int ast_udptl_reload(void)
        return 0;
 }
 
+/*!
+ * \internal
+ * \brief Clean up resources on Asterisk shutdown
+ */
+static void udptl_shutdown(void)
+{
+       ast_cli_unregister_multiple(cli_udptl, ARRAY_LEN(cli_udptl));
+       ao2_t_global_obj_release(globals, "Unref udptl global container in shutdown");
+       aco_info_destroy(&cfg_info);
+}
+
 void ast_udptl_init(void)
 {
-       ast_cli_register_multiple(cli_udptl, ARRAY_LEN(cli_udptl));
+       if (aco_info_init(&cfg_info)) {
+               return;
+       }
+
+       aco_option_register(&cfg_info, "udptlstart", ACO_EXACT, general_options, __stringify(DEFAULT_UDPTLSTART),
+               OPT_UINT_T, PARSE_IN_RANGE | PARSE_DEFAULT,
+               FLDSET(struct udptl_global_options, start), DEFAULT_UDPTLSTART, 1024, 65535);
+
+       aco_option_register(&cfg_info, "udptlend", ACO_EXACT, general_options, __stringify(DEFAULT_UDPTLEND),
+               OPT_UINT_T, PARSE_IN_RANGE | PARSE_DEFAULT,
+               FLDSET(struct udptl_global_options, end), DEFAULT_UDPTLEND, 1024, 65535);
+
+       aco_option_register(&cfg_info, "udptlfecentries", ACO_EXACT, general_options, NULL,
+               OPT_UINT_T, PARSE_IN_RANGE | PARSE_RANGE_DEFAULTS,
+               FLDSET(struct udptl_global_options, fecentries), 1, MAX_FEC_ENTRIES);
+
+       aco_option_register(&cfg_info, "udptlfecspan", ACO_EXACT, general_options, NULL,
+               OPT_UINT_T, PARSE_IN_RANGE | PARSE_RANGE_DEFAULTS,
+               FLDSET(struct udptl_global_options, fecspan), 1, MAX_FEC_SPAN);
+
+       aco_option_register(&cfg_info, "udptlchecksums", ACO_EXACT, general_options, "yes",
+               OPT_BOOL_T, 0, FLDSET(struct udptl_global_options, nochecksums));
+
+       aco_option_register(&cfg_info, "use_even_ports", ACO_EXACT, general_options, "no",
+               OPT_BOOL_T, 1, FLDSET(struct udptl_global_options, use_even_ports));
+
+       aco_option_register_custom(&cfg_info, "t38faxudpec", ACO_EXACT, general_options, NULL, removed_options_handler, 0);
+       aco_option_register_custom(&cfg_info, "t38faxmaxdatagram", ACO_EXACT, general_options, NULL, removed_options_handler, 0);
+
        __ast_udptl_reload(0);
+
+       ast_cli_register_multiple(cli_udptl, ARRAY_LEN(cli_udptl));
+
+       ast_register_cleanup(udptl_shutdown);
 }