Sat Mar 26 11:08:22 2011

Asterisk developer's documentation


udptl.c

Go to the documentation of this file.
00001 /*
00002  * Asterisk -- A telephony toolkit for Linux.
00003  *
00004  * UDPTL support for T.38
00005  * 
00006  * Copyright (C) 2005, Steve Underwood, partly based on RTP code which is
00007  * Copyright (C) 1999-2009, Digium, Inc.
00008  *
00009  * Steve Underwood <steveu@coppice.org>
00010  * Kevin P. Fleming <kpfleming@digium.com>
00011  *
00012  * See http://www.asterisk.org for more information about
00013  * the Asterisk project. Please do not directly contact
00014  * any of the maintainers of this project for assistance;
00015  * the project provides a web site, mailing lists and IRC
00016  * channels for your use.
00017  *
00018  * This program is free software, distributed under the terms of
00019  * the GNU General Public License Version 2. See the LICENSE file
00020  * at the top of the source tree.
00021  *
00022  * A license has been granted to Digium (via disclaimer) for the use of
00023  * this code.
00024  */
00025 
00026 /*! 
00027  * \file 
00028  *
00029  * \brief UDPTL support for T.38 faxing
00030  * 
00031  *
00032  * \author Mark Spencer <markster@digium.com>
00033  * \author Steve Underwood <steveu@coppice.org>
00034  * \author Kevin P. Fleming <kpfleming@digium.com>
00035  * 
00036  * \page T38fax_udptl T.38 support :: UDPTL
00037  *
00038  * Asterisk supports T.38 fax passthrough, origination and termination. It does
00039  * not support gateway operation. The only channel driver that supports T.38 at
00040  * this time is chan_sip.
00041  *
00042  * UDPTL is handled very much like RTP. It can be reinvited to go directly between
00043  * the endpoints, without involving Asterisk in the media stream.
00044  * 
00045  * \b References:
00046  * - chan_sip.c
00047  * - udptl.c
00048  * - app_fax.c
00049  */
00050 
00051 
00052 #include "asterisk.h"
00053 
00054 ASTERISK_FILE_VERSION(__FILE__, "$Revision: 278908 $")
00055 
00056 #include <sys/time.h>
00057 #include <signal.h>
00058 #include <fcntl.h>
00059 
00060 #include "asterisk/udptl.h"
00061 #include "asterisk/frame.h"
00062 #include "asterisk/channel.h"
00063 #include "asterisk/acl.h"
00064 #include "asterisk/config.h"
00065 #include "asterisk/lock.h"
00066 #include "asterisk/utils.h"
00067 #include "asterisk/netsock.h"
00068 #include "asterisk/cli.h"
00069 #include "asterisk/unaligned.h"
00070 
00071 #define UDPTL_MTU    1200
00072 
00073 #if !defined(FALSE)
00074 #define FALSE 0
00075 #endif
00076 #if !defined(TRUE)
00077 #define TRUE (!FALSE)
00078 #endif
00079 
00080 #define LOG_TAG(u) S_OR(u->tag, "no tag")
00081 
00082 static int udptlstart = 4500;
00083 static int udptlend = 4599;
00084 static int udptldebug;                      /*!< Are we debugging? */
00085 static struct ast_sockaddr udptldebugaddr;   /*!< Debug packets to/from this host */
00086 #ifdef SO_NO_CHECK
00087 static int nochecksums;
00088 #endif
00089 static int udptlfecentries;
00090 static int udptlfecspan;
00091 static int use_even_ports;
00092 
00093 #define LOCAL_FAX_MAX_DATAGRAM      1400
00094 #define DEFAULT_FAX_MAX_DATAGRAM    400
00095 #define FAX_MAX_DATAGRAM_LIMIT      1400
00096 #define MAX_FEC_ENTRIES             5
00097 #define MAX_FEC_SPAN                5
00098 
00099 #define UDPTL_BUF_MASK              15
00100 
00101 typedef struct {
00102    int buf_len;
00103    uint8_t buf[LOCAL_FAX_MAX_DATAGRAM];
00104 } udptl_fec_tx_buffer_t;
00105 
00106 typedef struct {
00107    int buf_len;
00108    uint8_t buf[LOCAL_FAX_MAX_DATAGRAM];
00109    unsigned int fec_len[MAX_FEC_ENTRIES];
00110    uint8_t fec[MAX_FEC_ENTRIES][LOCAL_FAX_MAX_DATAGRAM];
00111    unsigned int fec_span;
00112    unsigned int fec_entries;
00113 } udptl_fec_rx_buffer_t;
00114 
00115 /*! \brief Structure for an UDPTL session */
00116 struct ast_udptl {
00117    int fd;
00118    char resp;
00119    struct ast_frame f[16];
00120    unsigned char rawdata[8192 + AST_FRIENDLY_OFFSET];
00121    unsigned int lasteventseqn;
00122    int nat;
00123    int flags;
00124    struct ast_sockaddr us;
00125    struct ast_sockaddr them;
00126    int *ioid;
00127    struct sched_context *sched;
00128    struct io_context *io;
00129    void *data;
00130    char *tag;
00131    ast_udptl_callback callback;
00132 
00133    /*! This option indicates the error correction scheme used in transmitted UDPTL
00134     * packets and expected in received UDPTL packets.
00135     */
00136    enum ast_t38_ec_modes error_correction_scheme;
00137 
00138    /*! This option indicates the number of error correction entries transmitted in
00139     * UDPTL packets and expected in received UDPTL packets.
00140     */
00141    unsigned int error_correction_entries;
00142 
00143    /*! This option indicates the span of the error correction entries in transmitted
00144     * UDPTL packets (FEC only).
00145     */
00146    unsigned int error_correction_span;
00147 
00148    /*! The maximum size UDPTL packet that can be accepted by
00149     * the remote device.
00150     */
00151    int far_max_datagram;
00152 
00153    /*! The maximum size UDPTL packet that we are prepared to
00154     * accept, or -1 if it hasn't been calculated since the last
00155     * changes were applied to the UDPTL structure.
00156     */
00157    int local_max_datagram;
00158 
00159    /*! The maximum IFP that can be submitted for sending
00160     * to the remote device. Calculated from far_max_datagram,
00161     * error_correction_scheme and error_correction_entries,
00162     * or -1 if it hasn't been calculated since the last
00163     * changes were applied to the UDPTL structure.
00164     */
00165    int far_max_ifp;
00166 
00167    /*! The maximum IFP that the local endpoint is prepared
00168     * to accept. Along with error_correction_scheme and
00169     * error_correction_entries, used to calculate local_max_datagram.
00170     */
00171    int local_max_ifp;
00172 
00173    int verbose;
00174 
00175    unsigned int tx_seq_no;
00176    unsigned int rx_seq_no;
00177    unsigned int rx_expected_seq_no;
00178 
00179    udptl_fec_tx_buffer_t tx[UDPTL_BUF_MASK + 1];
00180    udptl_fec_rx_buffer_t rx[UDPTL_BUF_MASK + 1];
00181 };
00182 
00183 static AST_RWLIST_HEAD_STATIC(protos, ast_udptl_protocol);
00184 
00185 static inline int udptl_debug_test_addr(const struct ast_sockaddr *addr)
00186 {
00187    if (udptldebug == 0)
00188       return 0;
00189 
00190    if (ast_sockaddr_isnull(&udptldebugaddr)) {
00191       return 1;
00192    }
00193 
00194    if (ast_sockaddr_port(&udptldebugaddr)) {
00195       return !ast_sockaddr_cmp(&udptldebugaddr, addr);
00196    } else {
00197       return !ast_sockaddr_cmp_addr(&udptldebugaddr, addr);
00198    }
00199 }
00200 
00201 static int decode_length(uint8_t *buf, unsigned int limit, unsigned int *len, unsigned int *pvalue)
00202 {
00203    if (*len >= limit)
00204       return -1;
00205    if ((buf[*len] & 0x80) == 0) {
00206       *pvalue = buf[*len];
00207       (*len)++;
00208       return 0;
00209    }
00210    if ((buf[*len] & 0x40) == 0) {
00211       if (*len == limit - 1)
00212          return -1;
00213       *pvalue = (buf[*len] & 0x3F) << 8;
00214       (*len)++;
00215       *pvalue |= buf[*len];
00216       (*len)++;
00217       return 0;
00218    }
00219    *pvalue = (buf[*len] & 0x3F) << 14;
00220    (*len)++;
00221    /* Indicate we have a fragment */
00222    return 1;
00223 }
00224 /*- End of function --------------------------------------------------------*/
00225 
00226 static int decode_open_type(uint8_t *buf, unsigned int limit, unsigned int *len, const uint8_t **p_object, unsigned int *p_num_octets)
00227 {
00228    unsigned int octet_cnt;
00229    unsigned int octet_idx;
00230    unsigned int i;
00231    int length; /* a negative length indicates the limit has been reached in decode_length. */
00232    const uint8_t **pbuf;
00233 
00234    for (octet_idx = 0, *p_num_octets = 0; ; octet_idx += octet_cnt) {
00235       octet_cnt = 0;
00236       if ((length = decode_length(buf, limit, len, &octet_cnt)) < 0)
00237          return -1;
00238       if (octet_cnt > 0) {
00239          *p_num_octets += octet_cnt;
00240 
00241          pbuf = &p_object[octet_idx];
00242          i = 0;
00243          /* Make sure the buffer contains at least the number of bits requested */
00244          if ((*len + octet_cnt) > limit)
00245             return -1;
00246 
00247          *pbuf = &buf[*len];
00248          *len += octet_cnt;
00249       }
00250       if (length == 0)
00251          break;
00252    }
00253    return 0;
00254 }
00255 /*- End of function --------------------------------------------------------*/
00256 
00257 static unsigned int encode_length(uint8_t *buf, unsigned int *len, unsigned int value)
00258 {
00259    unsigned int multiplier;
00260 
00261    if (value < 0x80) {
00262       /* 1 octet */
00263       buf[*len] = value;
00264       (*len)++;
00265       return value;
00266    }
00267    if (value < 0x4000) {
00268       /* 2 octets */
00269       /* Set the first bit of the first octet */
00270       buf[*len] = ((0x8000 | value) >> 8) & 0xFF;
00271       (*len)++;
00272       buf[*len] = value & 0xFF;
00273       (*len)++;
00274       return value;
00275    }
00276    /* Fragmentation */
00277    multiplier = (value < 0x10000) ? (value >> 14) : 4;
00278    /* Set the first 2 bits of the octet */
00279    buf[*len] = 0xC0 | multiplier;
00280    (*len)++;
00281    return multiplier << 14;
00282 }
00283 /*- End of function --------------------------------------------------------*/
00284 
00285 static int encode_open_type(const struct ast_udptl *udptl, uint8_t *buf, unsigned int buflen,
00286              unsigned int *len, const uint8_t *data, unsigned int num_octets)
00287 {
00288    unsigned int enclen;
00289    unsigned int octet_idx;
00290    uint8_t zero_byte;
00291 
00292    /* If open type is of zero length, add a single zero byte (10.1) */
00293    if (num_octets == 0) {
00294       zero_byte = 0;
00295       data = &zero_byte;
00296       num_octets = 1;
00297    }
00298    /* Encode the open type */
00299    for (octet_idx = 0; ; num_octets -= enclen, octet_idx += enclen) {
00300       if ((enclen = encode_length(buf, len, num_octets)) < 0)
00301          return -1;
00302       if (enclen + *len > buflen) {
00303          ast_log(LOG_ERROR, "(%s): Buffer overflow detected (%d + %d > %d)\n",
00304             LOG_TAG(udptl), enclen, *len, buflen);
00305          return -1;
00306       }
00307       if (enclen > 0) {
00308          memcpy(&buf[*len], &data[octet_idx], enclen);
00309          *len += enclen;
00310       }
00311       if (enclen >= num_octets)
00312          break;
00313    }
00314 
00315    return 0;
00316 }
00317 /*- End of function --------------------------------------------------------*/
00318 
00319 static int udptl_rx_packet(struct ast_udptl *s, uint8_t *buf, unsigned int len)
00320 {
00321    int stat1;
00322    int stat2;
00323    int i;
00324    int j;
00325    int k;
00326    int l;
00327    int m;
00328    int x;
00329    int limit;
00330    int which;
00331    unsigned int ptr;
00332    unsigned int count;
00333    int total_count;
00334    int seq_no;
00335    const uint8_t *ifp;
00336    const uint8_t *data;
00337    unsigned int ifp_len;
00338    int repaired[16];
00339    const uint8_t *bufs[16];
00340    unsigned int lengths[16];
00341    int span;
00342    int entries;
00343    int ifp_no;
00344 
00345    ptr = 0;
00346    ifp_no = 0;
00347    memset(&s->f[0], 0, sizeof(s->f[0]));
00348 
00349    /* Decode seq_number */
00350    if (ptr + 2 > len)
00351       return -1;
00352    seq_no = (buf[0] << 8) | buf[1];
00353    ptr += 2;
00354 
00355    /* Break out the primary packet */
00356    if ((stat1 = decode_open_type(buf, len, &ptr, &ifp, &ifp_len)) != 0)
00357       return -1;
00358    /* Decode error_recovery */
00359    if (ptr + 1 > len)
00360       return -1;
00361    if ((buf[ptr++] & 0x80) == 0) {
00362       /* Secondary packet mode for error recovery */
00363       if (seq_no > s->rx_seq_no) {
00364          /* We received a later packet than we expected, so we need to check if we can fill in the gap from the
00365             secondary packets. */
00366          total_count = 0;
00367          do {
00368             if ((stat2 = decode_length(buf, len, &ptr, &count)) < 0)
00369                return -1;
00370             for (i = 0; i < count; i++) {
00371                if ((stat1 = decode_open_type(buf, len, &ptr, &bufs[total_count + i], &lengths[total_count + i])) != 0)
00372                   return -1;
00373             }
00374             total_count += count;
00375          }
00376          while (stat2 > 0);
00377          /* Step through in reverse order, so we go oldest to newest */
00378          for (i = total_count; i > 0; i--) {
00379             if (seq_no - i >= s->rx_seq_no) {
00380                /* This one wasn't seen before */
00381                /* Decode the secondary IFP packet */
00382                //fprintf(stderr, "Secondary %d, len %d\n", seq_no - i, lengths[i - 1]);
00383                s->f[ifp_no].frametype = AST_FRAME_MODEM;
00384                s->f[ifp_no].subclass.codec = AST_MODEM_T38;
00385 
00386                s->f[ifp_no].mallocd = 0;
00387                s->f[ifp_no].seqno = seq_no - i;
00388                s->f[ifp_no].datalen = lengths[i - 1];
00389                s->f[ifp_no].data.ptr = (uint8_t *) bufs[i - 1];
00390                s->f[ifp_no].offset = 0;
00391                s->f[ifp_no].src = "UDPTL";
00392                if (ifp_no > 0)
00393                   AST_LIST_NEXT(&s->f[ifp_no - 1], frame_list) = &s->f[ifp_no];
00394                AST_LIST_NEXT(&s->f[ifp_no], frame_list) = NULL;
00395                ifp_no++;
00396             }
00397          }
00398       }
00399    }
00400    else
00401    {
00402       /* FEC mode for error recovery */
00403       /* Our buffers cannot tolerate overlength IFP packets in FEC mode */
00404       if (ifp_len > LOCAL_FAX_MAX_DATAGRAM)
00405          return -1;
00406       /* Update any missed slots in the buffer */
00407       for ( ; seq_no > s->rx_seq_no; s->rx_seq_no++) {
00408          x = s->rx_seq_no & UDPTL_BUF_MASK;
00409          s->rx[x].buf_len = -1;
00410          s->rx[x].fec_len[0] = 0;
00411          s->rx[x].fec_span = 0;
00412          s->rx[x].fec_entries = 0;
00413       }
00414 
00415       x = seq_no & UDPTL_BUF_MASK;
00416 
00417       memset(repaired, 0, sizeof(repaired));
00418 
00419       /* Save the new IFP packet */
00420       memcpy(s->rx[x].buf, ifp, ifp_len);
00421       s->rx[x].buf_len = ifp_len;
00422       repaired[x] = TRUE;
00423 
00424       /* Decode the FEC packets */
00425       /* The span is defined as an unconstrained integer, but will never be more
00426          than a small value. */
00427       if (ptr + 2 > len)
00428          return -1;
00429       if (buf[ptr++] != 1)
00430          return -1;
00431       span = buf[ptr++];
00432       s->rx[x].fec_span = span;
00433 
00434       /* The number of entries is defined as a length, but will only ever be a small
00435          value. Treat it as such. */
00436       if (ptr + 1 > len)
00437          return -1;
00438       entries = buf[ptr++];
00439       s->rx[x].fec_entries = entries;
00440 
00441       /* Decode the elements */
00442       for (i = 0; i < entries; i++) {
00443          if ((stat1 = decode_open_type(buf, len, &ptr, &data, &s->rx[x].fec_len[i])) != 0)
00444             return -1;
00445          if (s->rx[x].fec_len[i] > LOCAL_FAX_MAX_DATAGRAM)
00446             return -1;
00447 
00448          /* Save the new FEC data */
00449          memcpy(s->rx[x].fec[i], data, s->rx[x].fec_len[i]);
00450 #if 0
00451          fprintf(stderr, "FEC: ");
00452          for (j = 0; j < s->rx[x].fec_len[i]; j++)
00453             fprintf(stderr, "%02X ", data[j]);
00454          fprintf(stderr, "\n");
00455 #endif
00456       }
00457 
00458       /* See if we can reconstruct anything which is missing */
00459       /* TODO: this does not comprehensively hunt back and repair everything that is possible */
00460       for (l = x; l != ((x - (16 - span*entries)) & UDPTL_BUF_MASK); l = (l - 1) & UDPTL_BUF_MASK) {
00461          if (s->rx[l].fec_len[0] <= 0)
00462             continue;
00463          for (m = 0; m < s->rx[l].fec_entries; m++) {
00464             limit = (l + m) & UDPTL_BUF_MASK;
00465             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) {
00466                if (s->rx[k].buf_len <= 0)
00467                   which = (which == -1) ? k : -2;
00468             }
00469             if (which >= 0) {
00470                /* Repairable */
00471                for (j = 0; j < s->rx[l].fec_len[m]; j++) {
00472                   s->rx[which].buf[j] = s->rx[l].fec[m][j];
00473                   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)
00474                      s->rx[which].buf[j] ^= (s->rx[k].buf_len > j) ? s->rx[k].buf[j] : 0;
00475                }
00476                s->rx[which].buf_len = s->rx[l].fec_len[m];
00477                repaired[which] = TRUE;
00478             }
00479          }
00480       }
00481       /* Now play any new packets forwards in time */
00482       for (l = (x + 1) & UDPTL_BUF_MASK, j = seq_no - UDPTL_BUF_MASK; l != x; l = (l + 1) & UDPTL_BUF_MASK, j++) {
00483          if (repaired[l]) {
00484             //fprintf(stderr, "Fixed packet %d, len %d\n", j, l);
00485             s->f[ifp_no].frametype = AST_FRAME_MODEM;
00486             s->f[ifp_no].subclass.codec = AST_MODEM_T38;
00487          
00488             s->f[ifp_no].mallocd = 0;
00489             s->f[ifp_no].seqno = j;
00490             s->f[ifp_no].datalen = s->rx[l].buf_len;
00491             s->f[ifp_no].data.ptr = s->rx[l].buf;
00492             s->f[ifp_no].offset = 0;
00493             s->f[ifp_no].src = "UDPTL";
00494             if (ifp_no > 0)
00495                AST_LIST_NEXT(&s->f[ifp_no - 1], frame_list) = &s->f[ifp_no];
00496             AST_LIST_NEXT(&s->f[ifp_no], frame_list) = NULL;
00497             ifp_no++;
00498          }
00499       }
00500    }
00501 
00502    /* If packets are received out of sequence, we may have already processed this packet from the error
00503       recovery information in a packet already received. */
00504    if (seq_no >= s->rx_seq_no) {
00505       /* Decode the primary IFP packet */
00506       s->f[ifp_no].frametype = AST_FRAME_MODEM;
00507       s->f[ifp_no].subclass.codec = AST_MODEM_T38;
00508       
00509       s->f[ifp_no].mallocd = 0;
00510       s->f[ifp_no].seqno = seq_no;
00511       s->f[ifp_no].datalen = ifp_len;
00512       s->f[ifp_no].data.ptr = (uint8_t *) ifp;
00513       s->f[ifp_no].offset = 0;
00514       s->f[ifp_no].src = "UDPTL";
00515       if (ifp_no > 0)
00516          AST_LIST_NEXT(&s->f[ifp_no - 1], frame_list) = &s->f[ifp_no];
00517       AST_LIST_NEXT(&s->f[ifp_no], frame_list) = NULL;
00518 
00519       ifp_no++;
00520    }
00521 
00522    s->rx_seq_no = seq_no + 1;
00523    return ifp_no;
00524 }
00525 /*- End of function --------------------------------------------------------*/
00526 
00527 static int udptl_build_packet(struct ast_udptl *s, uint8_t *buf, unsigned int buflen, uint8_t *ifp, unsigned int ifp_len)
00528 {
00529    uint8_t fec[LOCAL_FAX_MAX_DATAGRAM * 2];
00530    int i;
00531    int j;
00532    int seq;
00533    int entry;
00534    int entries;
00535    int span;
00536    int m;
00537    unsigned int len;
00538    int limit;
00539    int high_tide;
00540 
00541    seq = s->tx_seq_no & 0xFFFF;
00542 
00543    /* Map the sequence number to an entry in the circular buffer */
00544    entry = seq & UDPTL_BUF_MASK;
00545 
00546    /* We save the message in a circular buffer, for generating FEC or
00547       redundancy sets later on. */
00548    s->tx[entry].buf_len = ifp_len;
00549    memcpy(s->tx[entry].buf, ifp, ifp_len);
00550    
00551    /* Build the UDPTLPacket */
00552 
00553    len = 0;
00554    /* Encode the sequence number */
00555    buf[len++] = (seq >> 8) & 0xFF;
00556    buf[len++] = seq & 0xFF;
00557 
00558    /* Encode the primary IFP packet */
00559    if (encode_open_type(s, buf, buflen, &len, ifp, ifp_len) < 0)
00560       return -1;
00561 
00562    /* Encode the appropriate type of error recovery information */
00563    switch (s->error_correction_scheme)
00564    {
00565    case UDPTL_ERROR_CORRECTION_NONE:
00566       /* Encode the error recovery type */
00567       buf[len++] = 0x00;
00568       /* The number of entries will always be zero, so it is pointless allowing
00569          for the fragmented case here. */
00570       if (encode_length(buf, &len, 0) < 0)
00571          return -1;
00572       break;
00573    case UDPTL_ERROR_CORRECTION_REDUNDANCY:
00574       /* Encode the error recovery type */
00575       buf[len++] = 0x00;
00576       if (s->tx_seq_no > s->error_correction_entries)
00577          entries = s->error_correction_entries;
00578       else
00579          entries = s->tx_seq_no;
00580       /* The number of entries will always be small, so it is pointless allowing
00581          for the fragmented case here. */
00582       if (encode_length(buf, &len, entries) < 0)
00583          return -1;
00584       /* Encode the elements */
00585       for (i = 0; i < entries; i++) {
00586          j = (entry - i - 1) & UDPTL_BUF_MASK;
00587          if (encode_open_type(s, buf, buflen, &len, s->tx[j].buf, s->tx[j].buf_len) < 0) {
00588             ast_debug(1, "(%s): Encoding failed at i=%d, j=%d\n",
00589                  LOG_TAG(s), i, j);
00590             return -1;
00591          }
00592       }
00593       break;
00594    case UDPTL_ERROR_CORRECTION_FEC:
00595       span = s->error_correction_span;
00596       entries = s->error_correction_entries;
00597       if (seq < s->error_correction_span*s->error_correction_entries) {
00598          /* In the initial stages, wind up the FEC smoothly */
00599          entries = seq/s->error_correction_span;
00600          if (seq < s->error_correction_span)
00601             span = 0;
00602       }
00603       /* Encode the error recovery type */
00604       buf[len++] = 0x80;
00605       /* Span is defined as an inconstrained integer, which it dumb. It will only
00606          ever be a small value. Treat it as such. */
00607       buf[len++] = 1;
00608       buf[len++] = span;
00609       /* The number of entries is defined as a length, but will only ever be a small
00610          value. Treat it as such. */
00611       buf[len++] = entries;
00612       for (m = 0; m < entries; m++) {
00613          /* Make an XOR'ed entry the maximum length */
00614          limit = (entry + m) & UDPTL_BUF_MASK;
00615          high_tide = 0;
00616          for (i = (limit - span*entries) & UDPTL_BUF_MASK; i != limit; i = (i + entries) & UDPTL_BUF_MASK) {
00617             if (high_tide < s->tx[i].buf_len) {
00618                for (j = 0; j < high_tide; j++)
00619                   fec[j] ^= s->tx[i].buf[j];
00620                for ( ; j < s->tx[i].buf_len; j++)
00621                   fec[j] = s->tx[i].buf[j];
00622                high_tide = s->tx[i].buf_len;
00623             } else {
00624                for (j = 0; j < s->tx[i].buf_len; j++)
00625                   fec[j] ^= s->tx[i].buf[j];
00626             }
00627          }
00628          if (encode_open_type(s, buf, buflen, &len, fec, high_tide) < 0)
00629             return -1;
00630       }
00631       break;
00632    }
00633 
00634    if (s->verbose)
00635       fprintf(stderr, "\n");
00636 
00637    s->tx_seq_no++;
00638    return len;
00639 }
00640 
00641 int ast_udptl_fd(const struct ast_udptl *udptl)
00642 {
00643    return udptl->fd;
00644 }
00645 
00646 void ast_udptl_set_data(struct ast_udptl *udptl, void *data)
00647 {
00648    udptl->data = data;
00649 }
00650 
00651 void ast_udptl_set_callback(struct ast_udptl *udptl, ast_udptl_callback callback)
00652 {
00653    udptl->callback = callback;
00654 }
00655 
00656 void ast_udptl_setnat(struct ast_udptl *udptl, int nat)
00657 {
00658    udptl->nat = nat;
00659 }
00660 
00661 static int udptlread(int *id, int fd, short events, void *cbdata)
00662 {
00663    struct ast_udptl *udptl = cbdata;
00664    struct ast_frame *f;
00665 
00666    if ((f = ast_udptl_read(udptl))) {
00667       if (udptl->callback)
00668          udptl->callback(udptl, f, udptl->data);
00669    }
00670    return 1;
00671 }
00672 
00673 struct ast_frame *ast_udptl_read(struct ast_udptl *udptl)
00674 {
00675    int res;
00676    struct ast_sockaddr addr;
00677    uint16_t seqno = 0;
00678    uint16_t *udptlheader;
00679    
00680    /* Cache where the header will go */
00681    res = ast_recvfrom(udptl->fd,
00682          udptl->rawdata + AST_FRIENDLY_OFFSET,
00683          sizeof(udptl->rawdata) - AST_FRIENDLY_OFFSET,
00684          0,
00685          &addr);
00686    udptlheader = (uint16_t *)(udptl->rawdata + AST_FRIENDLY_OFFSET);
00687    if (res < 0) {
00688       if (errno != EAGAIN)
00689          ast_log(LOG_WARNING, "(%s): UDPTL read error: %s\n",
00690             LOG_TAG(udptl), strerror(errno));
00691       ast_assert(errno != EBADF);
00692       return &ast_null_frame;
00693    }
00694 
00695    /* Ignore if the other side hasn't been given an address yet. */
00696    if (ast_sockaddr_isnull(&udptl->them)) {
00697       return &ast_null_frame;
00698    }
00699 
00700    if (udptl->nat) {
00701       /* Send to whoever sent to us */
00702       if (ast_sockaddr_cmp(&udptl->them, &addr)) {
00703          ast_sockaddr_copy(&udptl->them, &addr);
00704          ast_debug(1, "UDPTL NAT (%s): Using address %s\n",
00705               LOG_TAG(udptl), ast_sockaddr_stringify(&udptl->them));
00706       }
00707    }
00708 
00709    if (udptl_debug_test_addr(&addr)) {
00710       ast_verb(1, "UDPTL (%s): packet from %s (type %d, seq %d, len %d)\n",
00711           LOG_TAG(udptl), ast_sockaddr_stringify(&addr), 0, seqno, res);
00712    }
00713    if (udptl_rx_packet(udptl, udptl->rawdata + AST_FRIENDLY_OFFSET, res) < 1)
00714       return &ast_null_frame;
00715 
00716    return &udptl->f[0];
00717 }
00718 
00719 static void calculate_local_max_datagram(struct ast_udptl *udptl)
00720 {
00721    unsigned int new_max = 0;
00722 
00723    if (udptl->local_max_ifp == -1) {
00724       ast_log(LOG_WARNING, "(%s): Cannot calculate local_max_datagram before local_max_ifp has been set.\n",
00725          LOG_TAG(udptl));
00726       udptl->local_max_datagram = -1;
00727       return;
00728    }
00729 
00730    /* calculate the amount of space required to receive an IFP
00731     * of the maximum size supported by the application/endpoint
00732     * that we are delivering them to (local endpoint), and add
00733     * the amount of space required to support the selected
00734     * error correction mode
00735     */
00736    switch (udptl->error_correction_scheme) {
00737    case UDPTL_ERROR_CORRECTION_NONE:
00738       /* need room for sequence number, length indicator, redundancy
00739        * indicator and following length indicator
00740        */
00741       new_max = 5 + udptl->local_max_ifp;
00742       break;
00743    case UDPTL_ERROR_CORRECTION_REDUNDANCY:
00744       /* need room for sequence number, length indicators, plus
00745        * room for up to 3 redundancy packets
00746        */
00747       new_max = 5 + udptl->local_max_ifp + 2 + (3 * udptl->local_max_ifp);
00748       break;
00749    case UDPTL_ERROR_CORRECTION_FEC:
00750       /* need room for sequence number, length indicators and a
00751        * a single IFP of the maximum size expected
00752        */
00753       new_max = 5 + udptl->local_max_ifp + 4 + udptl->local_max_ifp;
00754       break;
00755    }
00756    /* add 5% extra space for insurance, but no larger than LOCAL_FAX_MAX_DATAGRAM */
00757    udptl->local_max_datagram = MIN(new_max * 1.05, LOCAL_FAX_MAX_DATAGRAM);
00758 }
00759 
00760 static void calculate_far_max_ifp(struct ast_udptl *udptl)
00761 {
00762    unsigned new_max = 0;
00763 
00764    if (udptl->far_max_datagram == -1) {
00765       ast_log(LOG_WARNING, "(%s): Cannot calculate far_max_ifp before far_max_datagram has been set.\n",
00766          LOG_TAG(udptl));
00767       udptl->far_max_ifp = -1;
00768       return;
00769    }
00770 
00771    /* the goal here is to supply the local endpoint (application
00772     * or bridged channel) a maximum IFP value that will allow it
00773     * to effectively and efficiently transfer image data at its
00774     * selected bit rate, taking into account the selected error
00775     * correction mode, but without overrunning the far endpoint's
00776     * datagram buffer. this is complicated by the fact that some
00777     * far endpoints send us bogus (small) max datagram values,
00778     * which would result in either buffer overrun or no error
00779     * correction. we try to accomodate those, but if the supplied
00780     * value is too small to do so, we'll emit warning messages and
00781     * the user will have to use configuration options to override
00782     * the max datagram value supplied by the far endpoint.
00783     */
00784    switch (udptl->error_correction_scheme) {
00785    case UDPTL_ERROR_CORRECTION_NONE:
00786       /* need room for sequence number, length indicator, redundancy
00787        * indicator and following length indicator
00788        */
00789       new_max = udptl->far_max_datagram - 5;
00790       break;
00791    case UDPTL_ERROR_CORRECTION_REDUNDANCY:
00792       /* for this case, we'd like to send as many error correction entries
00793        * as possible (up to the number we're configured for), but we'll settle
00794        * for sending fewer if the configured number would cause the
00795        * calculated max IFP to be too small for effective operation
00796        *
00797        * need room for sequence number, length indicators and the
00798        * configured number of redundant packets
00799        *
00800        * note: we purposely don't allow error_correction_entries to drop to
00801        * zero in this loop; we'd rather send smaller IFPs (and thus reduce
00802        * the image data transfer rate) than sacrifice redundancy completely
00803        */
00804       for (;;) {
00805          new_max = (udptl->far_max_datagram - 8) / (udptl->error_correction_entries + 1);
00806 
00807          if ((new_max < 80) && (udptl->error_correction_entries > 1)) {
00808             /* the max ifp is not large enough, subtract an
00809              * error correction entry and calculate again
00810              * */
00811             --udptl->error_correction_entries;
00812          } else {
00813             break;
00814          }
00815       }
00816       break;
00817    case UDPTL_ERROR_CORRECTION_FEC:
00818       /* need room for sequence number, length indicators and a
00819        * a single IFP of the maximum size expected
00820        */
00821       new_max = (udptl->far_max_datagram - 10) / 2;
00822       break;
00823    }
00824    /* subtract 5% of space for insurance */
00825    udptl->far_max_ifp = new_max * 0.95;
00826 }
00827 
00828 enum ast_t38_ec_modes ast_udptl_get_error_correction_scheme(const struct ast_udptl *udptl)
00829 {
00830    return udptl->error_correction_scheme;
00831 }
00832 
00833 void ast_udptl_set_error_correction_scheme(struct ast_udptl *udptl, enum ast_t38_ec_modes ec)
00834 {
00835    udptl->error_correction_scheme = ec;
00836    switch (ec) {
00837    case UDPTL_ERROR_CORRECTION_FEC:
00838       udptl->error_correction_scheme = UDPTL_ERROR_CORRECTION_FEC;
00839       if (udptl->error_correction_entries == 0) {
00840          udptl->error_correction_entries = 3;
00841       }
00842       if (udptl->error_correction_span == 0) {
00843          udptl->error_correction_span = 3;
00844       }
00845       break;
00846    case UDPTL_ERROR_CORRECTION_REDUNDANCY:
00847       udptl->error_correction_scheme = UDPTL_ERROR_CORRECTION_REDUNDANCY;
00848       if (udptl->error_correction_entries == 0) {
00849          udptl->error_correction_entries = 3;
00850       }
00851       break;
00852    default:
00853       /* nothing to do */
00854       break;
00855    };
00856    /* reset calculated values so they'll be computed again */
00857    udptl->local_max_datagram = -1;
00858    udptl->far_max_ifp = -1;
00859 }
00860 
00861 void ast_udptl_set_local_max_ifp(struct ast_udptl *udptl, unsigned int max_ifp)
00862 {
00863    /* make sure max_ifp is a positive value since a cast will take place when
00864     * when setting local_max_ifp */
00865    if ((signed int) max_ifp > 0) {
00866       udptl->local_max_ifp = max_ifp;
00867       /* reset calculated values so they'll be computed again */
00868       udptl->local_max_datagram = -1;
00869    }
00870 }
00871 
00872 unsigned int ast_udptl_get_local_max_datagram(struct ast_udptl *udptl)
00873 {
00874    if (udptl->local_max_datagram == -1) {
00875       calculate_local_max_datagram(udptl);
00876    }
00877 
00878    /* this function expects a unsigned value in return. */
00879    if (udptl->local_max_datagram < 0) {
00880       return 0;
00881    }
00882    return udptl->local_max_datagram;
00883 }
00884 
00885 void ast_udptl_set_far_max_datagram(struct ast_udptl *udptl, unsigned int max_datagram)
00886 {
00887    if (!max_datagram || (max_datagram > FAX_MAX_DATAGRAM_LIMIT)) {
00888       udptl->far_max_datagram = DEFAULT_FAX_MAX_DATAGRAM;
00889    } else {
00890       udptl->far_max_datagram = max_datagram;
00891    }
00892    /* reset calculated values so they'll be computed again */
00893    udptl->far_max_ifp = -1;
00894 }
00895 
00896 unsigned int ast_udptl_get_far_max_datagram(const struct ast_udptl *udptl)
00897 {
00898    if (udptl->far_max_datagram < 0) {
00899       return 0;
00900    }
00901    return udptl->far_max_datagram;
00902 }
00903 
00904 unsigned int ast_udptl_get_far_max_ifp(struct ast_udptl *udptl)
00905 {
00906    if (udptl->far_max_ifp == -1) {
00907       calculate_far_max_ifp(udptl);
00908    }
00909 
00910    if (udptl->far_max_ifp < 0) {
00911       return 0;
00912    }
00913    return udptl->far_max_ifp;
00914 }
00915 
00916 struct ast_udptl *ast_udptl_new_with_bindaddr(struct sched_context *sched, struct io_context *io, int callbackmode, struct ast_sockaddr *addr)
00917 {
00918    struct ast_udptl *udptl;
00919    int x;
00920    int startplace;
00921    int i;
00922    long int flags;
00923 
00924    if (!(udptl = ast_calloc(1, sizeof(*udptl))))
00925       return NULL;
00926 
00927    udptl->error_correction_span = udptlfecspan;
00928    udptl->error_correction_entries = udptlfecentries;
00929    
00930    udptl->far_max_datagram = -1;
00931    udptl->far_max_ifp = -1;
00932    udptl->local_max_ifp = -1;
00933    udptl->local_max_datagram = -1;
00934 
00935    for (i = 0; i <= UDPTL_BUF_MASK; i++) {
00936       udptl->rx[i].buf_len = -1;
00937       udptl->tx[i].buf_len = -1;
00938    }
00939 
00940    if ((udptl->fd = socket(ast_sockaddr_is_ipv6(addr) ?
00941                AF_INET6 : AF_INET, SOCK_DGRAM, 0)) < 0) {
00942       ast_free(udptl);
00943       ast_log(LOG_WARNING, "Unable to allocate socket: %s\n", strerror(errno));
00944       return NULL;
00945    }
00946    flags = fcntl(udptl->fd, F_GETFL);
00947    fcntl(udptl->fd, F_SETFL, flags | O_NONBLOCK);
00948 #ifdef SO_NO_CHECK
00949    if (nochecksums)
00950       setsockopt(udptl->fd, SOL_SOCKET, SO_NO_CHECK, &nochecksums, sizeof(nochecksums));
00951 #endif
00952    /* Find us a place */
00953    x = (udptlstart == udptlend) ? udptlstart : (ast_random() % (udptlend - udptlstart)) + udptlstart;
00954    if (use_even_ports && (x & 1)) {
00955       ++x;
00956    }
00957    startplace = x;
00958    for (;;) {
00959       ast_sockaddr_copy(&udptl->us, addr);
00960       ast_sockaddr_set_port(&udptl->us, x);
00961       if (ast_bind(udptl->fd, &udptl->us) == 0) {
00962          break;
00963       }
00964       if (errno != EADDRINUSE) {
00965          ast_log(LOG_WARNING, "Unexpected bind error: %s\n", strerror(errno));
00966          close(udptl->fd);
00967          ast_free(udptl);
00968          return NULL;
00969       }
00970       if (use_even_ports) {
00971          x += 2;
00972       } else {
00973          ++x;
00974       }
00975       if (x > udptlend)
00976          x = udptlstart;
00977       if (x == startplace) {
00978          ast_log(LOG_WARNING, "No UDPTL ports remaining\n");
00979          close(udptl->fd);
00980          ast_free(udptl);
00981          return NULL;
00982       }
00983    }
00984    if (io && sched && callbackmode) {
00985       /* Operate this one in a callback mode */
00986       udptl->sched = sched;
00987       udptl->io = io;
00988       udptl->ioid = ast_io_add(udptl->io, udptl->fd, udptlread, AST_IO_IN, udptl);
00989    }
00990    return udptl;
00991 }
00992 
00993 void ast_udptl_set_tag(struct ast_udptl *udptl, const char *format, ...)
00994 {
00995    va_list ap;
00996 
00997    if (udptl->tag) {
00998       ast_free(udptl->tag);
00999       udptl->tag = NULL;
01000    }
01001    va_start(ap, format);
01002    if (ast_vasprintf(&udptl->tag, format, ap) == -1) {
01003       udptl->tag = NULL;
01004    }
01005    va_end(ap);
01006 }
01007 
01008 int ast_udptl_setqos(struct ast_udptl *udptl, unsigned int tos, unsigned int cos)
01009 {
01010    return ast_netsock_set_qos(udptl->fd, tos, cos, "UDPTL");
01011 }
01012 
01013 void ast_udptl_set_peer(struct ast_udptl *udptl, const struct ast_sockaddr *them)
01014 {
01015    ast_sockaddr_copy(&udptl->them, them);
01016 }
01017 
01018 void ast_udptl_get_peer(const struct ast_udptl *udptl, struct ast_sockaddr *them)
01019 {
01020    ast_sockaddr_copy(them, &udptl->them);
01021 }
01022 
01023 void ast_udptl_get_us(const struct ast_udptl *udptl, struct ast_sockaddr *us)
01024 {
01025    ast_sockaddr_copy(us, &udptl->us);
01026 }
01027 
01028 void ast_udptl_stop(struct ast_udptl *udptl)
01029 {
01030    ast_sockaddr_setnull(&udptl->them);
01031 }
01032 
01033 void ast_udptl_destroy(struct ast_udptl *udptl)
01034 {
01035    if (udptl->ioid)
01036       ast_io_remove(udptl->io, udptl->ioid);
01037    if (udptl->fd > -1)
01038       close(udptl->fd);
01039    if (udptl->tag)
01040       ast_free(udptl->tag);
01041    ast_free(udptl);
01042 }
01043 
01044 int ast_udptl_write(struct ast_udptl *s, struct ast_frame *f)
01045 {
01046    unsigned int seq;
01047    unsigned int len = f->datalen;
01048    int res;
01049    /* if no max datagram size is provided, use default value */
01050    const int bufsize = (s->far_max_datagram > 0) ? s->far_max_datagram : DEFAULT_FAX_MAX_DATAGRAM;
01051    uint8_t buf[bufsize];
01052 
01053    memset(buf, 0, sizeof(buf));
01054 
01055    /* If we have no peer, return immediately */
01056    if (ast_sockaddr_isnull(&s->them)) {
01057       return 0;
01058    }
01059 
01060    /* If there is no data length, return immediately */
01061    if (f->datalen == 0)
01062       return 0;
01063    
01064    if ((f->frametype != AST_FRAME_MODEM) ||
01065        (f->subclass.codec != AST_MODEM_T38)) {
01066       ast_log(LOG_WARNING, "(%s): UDPTL can only send T.38 data.\n",
01067          LOG_TAG(s));
01068       return -1;
01069    }
01070 
01071    if (len > s->far_max_ifp) {
01072       ast_log(LOG_WARNING,
01073          "(%s): UDPTL asked to send %d bytes of IFP when far end only prepared to accept %d bytes; data loss will occur."
01074          "You may need to override the T38FaxMaxDatagram value for this endpoint in the channel driver configuration.\n",
01075          LOG_TAG(s), len, s->far_max_ifp);
01076       len = s->far_max_ifp;
01077    }
01078 
01079    /* Save seq_no for debug output because udptl_build_packet increments it */
01080    seq = s->tx_seq_no & 0xFFFF;
01081 
01082    /* Cook up the UDPTL packet, with the relevant EC info. */
01083    len = udptl_build_packet(s, buf, sizeof(buf), f->data.ptr, len);
01084 
01085    if ((signed int) len > 0 && !ast_sockaddr_isnull(&s->them)) {
01086       if ((res = ast_sendto(s->fd, buf, len, 0, &s->them)) < 0)
01087          ast_log(LOG_NOTICE, "(%s): UDPTL Transmission error to %s: %s\n",
01088             LOG_TAG(s), ast_sockaddr_stringify(&s->them), strerror(errno));
01089       if (udptl_debug_test_addr(&s->them))
01090          ast_verb(1, "UDPTL (%s): packet to %s (type %d, seq %d, len %d)\n",
01091              LOG_TAG(s), ast_sockaddr_stringify(&s->them), 0, seq, len);
01092    }
01093       
01094    return 0;
01095 }
01096 
01097 void ast_udptl_proto_unregister(struct ast_udptl_protocol *proto)
01098 {
01099    AST_RWLIST_WRLOCK(&protos);
01100    AST_RWLIST_REMOVE(&protos, proto, list);
01101    AST_RWLIST_UNLOCK(&protos);
01102 }
01103 
01104 int ast_udptl_proto_register(struct ast_udptl_protocol *proto)
01105 {
01106    struct ast_udptl_protocol *cur;
01107 
01108    AST_RWLIST_WRLOCK(&protos);
01109    AST_RWLIST_TRAVERSE(&protos, cur, list) {
01110       if (cur->type == proto->type) {
01111          ast_log(LOG_WARNING, "Tried to register same protocol '%s' twice\n", cur->type);
01112          AST_RWLIST_UNLOCK(&protos);
01113          return -1;
01114       }
01115    }
01116    AST_RWLIST_INSERT_TAIL(&protos, proto, list);
01117    AST_RWLIST_UNLOCK(&protos);
01118    return 0;
01119 }
01120 
01121 static struct ast_udptl_protocol *get_proto(struct ast_channel *chan)
01122 {
01123    struct ast_udptl_protocol *cur = NULL;
01124 
01125    AST_RWLIST_RDLOCK(&protos);
01126    AST_RWLIST_TRAVERSE(&protos, cur, list) {
01127       if (cur->type == chan->tech->type)
01128          break;
01129    }
01130    AST_RWLIST_UNLOCK(&protos);
01131 
01132    return cur;
01133 }
01134 
01135 int ast_udptl_bridge(struct ast_channel *c0, struct ast_channel *c1, int flags, struct ast_frame **fo, struct ast_channel **rc)
01136 {
01137    struct ast_frame *f;
01138    struct ast_channel *who;
01139    struct ast_channel *cs[3];
01140    struct ast_udptl *p0;
01141    struct ast_udptl *p1;
01142    struct ast_udptl_protocol *pr0;
01143    struct ast_udptl_protocol *pr1;
01144    struct ast_sockaddr ac0;
01145    struct ast_sockaddr ac1;
01146    struct ast_sockaddr t0;
01147    struct ast_sockaddr t1;
01148    void *pvt0;
01149    void *pvt1;
01150    int to;
01151    
01152    ast_channel_lock(c0);
01153    while (ast_channel_trylock(c1)) {
01154       ast_channel_unlock(c0);
01155       usleep(1);
01156       ast_channel_lock(c0);
01157    }
01158    pr0 = get_proto(c0);
01159    pr1 = get_proto(c1);
01160    if (!pr0) {
01161       ast_log(LOG_WARNING, "Can't find native functions for channel '%s'\n", c0->name);
01162       ast_channel_unlock(c0);
01163       ast_channel_unlock(c1);
01164       return -1;
01165    }
01166    if (!pr1) {
01167       ast_log(LOG_WARNING, "Can't find native functions for channel '%s'\n", c1->name);
01168       ast_channel_unlock(c0);
01169       ast_channel_unlock(c1);
01170       return -1;
01171    }
01172    pvt0 = c0->tech_pvt;
01173    pvt1 = c1->tech_pvt;
01174    p0 = pr0->get_udptl_info(c0);
01175    p1 = pr1->get_udptl_info(c1);
01176    if (!p0 || !p1) {
01177       /* Somebody doesn't want to play... */
01178       ast_channel_unlock(c0);
01179       ast_channel_unlock(c1);
01180       return -2;
01181    }
01182    if (pr0->set_udptl_peer(c0, p1)) {
01183       ast_log(LOG_WARNING, "Channel '%s' failed to talk to '%s'\n", c0->name, c1->name);
01184       memset(&ac1, 0, sizeof(ac1));
01185    } else {
01186       /* Store UDPTL peer */
01187       ast_udptl_get_peer(p1, &ac1);
01188    }
01189    if (pr1->set_udptl_peer(c1, p0)) {
01190       ast_log(LOG_WARNING, "Channel '%s' failed to talk back to '%s'\n", c1->name, c0->name);
01191       memset(&ac0, 0, sizeof(ac0));
01192    } else {
01193       /* Store UDPTL peer */
01194       ast_udptl_get_peer(p0, &ac0);
01195    }
01196    ast_channel_unlock(c0);
01197    ast_channel_unlock(c1);
01198    cs[0] = c0;
01199    cs[1] = c1;
01200    cs[2] = NULL;
01201    for (;;) {
01202       if ((c0->tech_pvt != pvt0) ||
01203          (c1->tech_pvt != pvt1) ||
01204          (c0->masq || c0->masqr || c1->masq || c1->masqr)) {
01205             ast_debug(1, "Oooh, something is weird, backing out\n");
01206             /* Tell it to try again later */
01207             return -3;
01208       }
01209       to = -1;
01210       ast_udptl_get_peer(p1, &t1);
01211       ast_udptl_get_peer(p0, &t0);
01212       if (ast_sockaddr_cmp(&t1, &ac1)) {
01213          ast_debug(1, "Oooh, '%s' changed end address to %s\n", 
01214             c1->name, ast_sockaddr_stringify(&t1));
01215          ast_debug(1, "Oooh, '%s' was %s\n", 
01216             c1->name, ast_sockaddr_stringify(&ac1));
01217          ast_sockaddr_copy(&ac1, &t1);
01218       }
01219       if (ast_sockaddr_cmp(&t0, &ac0)) {
01220          ast_debug(1, "Oooh, '%s' changed end address to %s\n", 
01221             c0->name, ast_sockaddr_stringify(&t0));
01222          ast_debug(1, "Oooh, '%s' was %s\n", 
01223             c0->name, ast_sockaddr_stringify(&ac0));
01224          ast_sockaddr_copy(&ac0, &t0);
01225       }
01226       who = ast_waitfor_n(cs, 2, &to);
01227       if (!who) {
01228          ast_debug(1, "Ooh, empty read...\n");
01229          /* check for hangup / whentohangup */
01230          if (ast_check_hangup(c0) || ast_check_hangup(c1))
01231             break;
01232          continue;
01233       }
01234       f = ast_read(who);
01235       if (!f) {
01236          *fo = f;
01237          *rc = who;
01238          ast_debug(1, "Oooh, got a %s\n", f ? "digit" : "hangup");
01239          /* That's all we needed */
01240          return 0;
01241       } else {
01242          if (f->frametype == AST_FRAME_MODEM) {
01243             /* Forward T.38 frames if they happen upon us */
01244             if (who == c0) {
01245                ast_write(c1, f);
01246             } else if (who == c1) {
01247                ast_write(c0, f);
01248             }
01249          }
01250          ast_frfree(f);
01251       }
01252       /* Swap priority. Not that it's a big deal at this point */
01253       cs[2] = cs[0];
01254       cs[0] = cs[1];
01255       cs[1] = cs[2];
01256    }
01257    return -1;
01258 }
01259 
01260 static char *handle_cli_udptl_set_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
01261 {
01262    switch (cmd) {
01263    case CLI_INIT:
01264       e->command = "udptl set debug {on|off|ip}";
01265       e->usage = 
01266          "Usage: udptl set debug {on|off|ip host[:port]}\n"
01267          "       Enable or disable dumping of UDPTL packets.\n"
01268          "       If ip is specified, limit the dumped packets to those to and from\n"
01269          "       the specified 'host' with optional port.\n";
01270       return NULL;
01271    case CLI_GENERATE:
01272       return NULL;
01273    }
01274 
01275    if (a->argc < 4 || a->argc > 5)
01276       return CLI_SHOWUSAGE;
01277 
01278    if (a->argc == 4) {
01279       if (!strncasecmp(a->argv[3], "on", 2)) {
01280          udptldebug = 1;
01281          memset(&udptldebugaddr, 0, sizeof(udptldebugaddr));
01282          ast_cli(a->fd, "UDPTL Debugging Enabled\n");
01283       } else if (!strncasecmp(a->argv[3], "off", 3)) {
01284          udptldebug = 0;
01285          ast_cli(a->fd, "UDPTL Debugging Disabled\n");
01286       } else {
01287          return CLI_SHOWUSAGE;
01288       }
01289    } else {
01290       struct ast_sockaddr *addrs;
01291       if (strncasecmp(a->argv[3], "ip", 2))
01292          return CLI_SHOWUSAGE;
01293       if (!ast_sockaddr_resolve(&addrs, a->argv[4], 0, 0)) {
01294          return CLI_SHOWUSAGE;
01295       }
01296       ast_sockaddr_copy(&udptldebugaddr, &addrs[0]);
01297          ast_cli(a->fd, "UDPTL Debugging Enabled for IP: %s\n", ast_sockaddr_stringify(&udptldebugaddr));
01298       udptldebug = 1;
01299       ast_free(addrs);
01300    }
01301 
01302    return CLI_SUCCESS;
01303 }
01304 
01305 
01306 static struct ast_cli_entry cli_udptl[] = {
01307    AST_CLI_DEFINE(handle_cli_udptl_set_debug, "Enable/Disable UDPTL debugging")
01308 };
01309 
01310 static void __ast_udptl_reload(int reload)
01311 {
01312    struct ast_config *cfg;
01313    const char *s;
01314    struct ast_flags config_flags = { reload ? CONFIG_FLAG_FILEUNCHANGED : 0 };
01315 
01316    cfg = ast_config_load2("udptl.conf", "udptl", config_flags);
01317    if (cfg == CONFIG_STATUS_FILEMISSING || cfg == CONFIG_STATUS_FILEUNCHANGED || cfg == CONFIG_STATUS_FILEINVALID) {
01318       return;
01319    }
01320 
01321    udptlstart = 4500;
01322    udptlend = 4999;
01323    udptlfecentries = 0;
01324    udptlfecspan = 0;
01325    use_even_ports = 0;
01326 
01327    if (cfg) {
01328       if ((s = ast_variable_retrieve(cfg, "general", "udptlstart"))) {
01329          udptlstart = atoi(s);
01330          if (udptlstart < 1024) {
01331             ast_log(LOG_WARNING, "Ports under 1024 are not allowed for T.38.\n");
01332             udptlstart = 1024;
01333          }
01334          if (udptlstart > 65535) {
01335             ast_log(LOG_WARNING, "Ports over 65535 are invalid.\n");
01336             udptlstart = 65535;
01337          }
01338       }
01339       if ((s = ast_variable_retrieve(cfg, "general", "udptlend"))) {
01340          udptlend = atoi(s);
01341          if (udptlend < 1024) {
01342             ast_log(LOG_WARNING, "Ports under 1024 are not allowed for T.38.\n");
01343             udptlend = 1024;
01344          }
01345          if (udptlend > 65535) {
01346             ast_log(LOG_WARNING, "Ports over 65535 are invalid.\n");
01347             udptlend = 65535;
01348          }
01349       }
01350       if ((s = ast_variable_retrieve(cfg, "general", "udptlchecksums"))) {
01351 #ifdef SO_NO_CHECK
01352          if (ast_false(s))
01353             nochecksums = 1;
01354          else
01355             nochecksums = 0;
01356 #else
01357          if (ast_false(s))
01358             ast_log(LOG_WARNING, "Disabling UDPTL checksums is not supported on this operating system!\n");
01359 #endif
01360       }
01361       if ((s = ast_variable_retrieve(cfg, "general", "T38FaxUdpEC"))) {
01362          ast_log(LOG_WARNING, "T38FaxUdpEC in udptl.conf is no longer supported; use the t38pt_udptl configuration option in sip.conf instead.\n");
01363       }
01364       if ((s = ast_variable_retrieve(cfg, "general", "T38FaxMaxDatagram"))) {
01365          ast_log(LOG_WARNING, "T38FaxMaxDatagram in udptl.conf is no longer supported; value is now supplied by T.38 applications.\n");
01366       }
01367       if ((s = ast_variable_retrieve(cfg, "general", "UDPTLFECEntries"))) {
01368          udptlfecentries = atoi(s);
01369          if (udptlfecentries < 1) {
01370             ast_log(LOG_WARNING, "Too small UDPTLFECEntries value.  Defaulting to 1.\n");
01371             udptlfecentries = 1;
01372          }
01373          if (udptlfecentries > MAX_FEC_ENTRIES) {
01374             ast_log(LOG_WARNING, "Too large UDPTLFECEntries value.  Defaulting to %d.\n", MAX_FEC_ENTRIES);
01375             udptlfecentries = MAX_FEC_ENTRIES;
01376          }
01377       }
01378       if ((s = ast_variable_retrieve(cfg, "general", "UDPTLFECSpan"))) {
01379          udptlfecspan = atoi(s);
01380          if (udptlfecspan < 1) {
01381             ast_log(LOG_WARNING, "Too small UDPTLFECSpan value.  Defaulting to 1.\n");
01382             udptlfecspan = 1;
01383          }
01384          if (udptlfecspan > MAX_FEC_SPAN) {
01385             ast_log(LOG_WARNING, "Too large UDPTLFECSpan value.  Defaulting to %d.\n", MAX_FEC_SPAN);
01386             udptlfecspan = MAX_FEC_SPAN;
01387          }
01388       }
01389       if ((s = ast_variable_retrieve(cfg, "general", "use_even_ports"))) {
01390          use_even_ports = ast_true(s);
01391       }
01392       ast_config_destroy(cfg);
01393    }
01394    if (udptlstart >= udptlend) {
01395       ast_log(LOG_WARNING, "Unreasonable values for UDPTL start/end ports; defaulting to 4500-4999.\n");
01396       udptlstart = 4500;
01397       udptlend = 4999;
01398    }
01399    if (use_even_ports && (udptlstart & 1)) {
01400       ++udptlstart;
01401       ast_log(LOG_NOTICE, "Odd numbered udptlstart specified but use_even_ports enabled. udptlstart is now %d\n", udptlstart);
01402    }
01403    if (use_even_ports && (udptlend & 1)) {
01404       --udptlend;
01405       ast_log(LOG_NOTICE, "Odd numbered udptlend specified but use_event_ports enabled. udptlend is now %d\n", udptlend);
01406    }
01407    ast_verb(2, "UDPTL allocating from port range %d -> %d\n", udptlstart, udptlend);
01408 }
01409 
01410 int ast_udptl_reload(void)
01411 {
01412    __ast_udptl_reload(1);
01413    return 0;
01414 }
01415 
01416 void ast_udptl_init(void)
01417 {
01418    ast_cli_register_multiple(cli_udptl, ARRAY_LEN(cli_udptl));
01419    __ast_udptl_reload(0);
01420 }

Generated on Sat Mar 26 11:08:22 2011 for Asterisk - The Open Source Telephony Project by  doxygen 1.5.9