Thu Oct 11 06:47:09 2012

Asterisk developer's documentation


chan_iax2.c

Go to the documentation of this file.
00001 /*
00002  * Asterisk -- An open source telephony toolkit.
00003  *
00004  * Copyright (C) 1999 - 2006, Digium, Inc.
00005  *
00006  * Mark Spencer <markster@digium.com>
00007  *
00008  * See http://www.asterisk.org for more information about
00009  * the Asterisk project. Please do not directly contact
00010  * any of the maintainers of this project for assistance;
00011  * the project provides a web site, mailing lists and IRC
00012  * channels for your use.
00013  *
00014  * This program is free software, distributed under the terms of
00015  * the GNU General Public License Version 2. See the LICENSE file
00016  * at the top of the source tree.
00017  */
00018 
00019 /*! \file
00020  *
00021  * \brief Implementation of Inter-Asterisk eXchange Version 2
00022  *        as specified in RFC 5456
00023  *
00024  * \author Mark Spencer <markster@digium.com>
00025  *
00026  * \par See also
00027  * \arg \ref Config_iax
00028  *
00029  * \ingroup channel_drivers
00030  * 
00031  * \todo Implement musicclass settings for IAX2 devices
00032  */
00033 
00034 /*** MODULEINFO
00035    <use>crypto</use>
00036  ***/
00037 
00038 #include "asterisk.h"
00039 
00040 ASTERISK_FILE_VERSION(__FILE__, "$Revision: 324634 $")
00041 
00042 #include <sys/mman.h>
00043 #include <dirent.h>
00044 #include <sys/socket.h>
00045 #include <netinet/in.h>
00046 #include <arpa/inet.h>
00047 #include <netinet/in_systm.h>
00048 #include <netinet/ip.h>
00049 #include <sys/time.h>
00050 #include <sys/signal.h>
00051 #include <signal.h>
00052 #include <strings.h>
00053 #include <netdb.h>
00054 #include <fcntl.h>
00055 #include <sys/stat.h>
00056 #include <regex.h>
00057 
00058 #include "asterisk/paths.h"   /* need ast_config_AST_DATA_DIR for firmware */
00059 
00060 #include "asterisk/lock.h"
00061 #include "asterisk/frame.h" 
00062 #include "asterisk/channel.h"
00063 #include "asterisk/module.h"
00064 #include "asterisk/pbx.h"
00065 #include "asterisk/sched.h"
00066 #include "asterisk/io.h"
00067 #include "asterisk/config.h"
00068 #include "asterisk/cli.h"
00069 #include "asterisk/translate.h"
00070 #include "asterisk/md5.h"
00071 #include "asterisk/cdr.h"
00072 #include "asterisk/crypto.h"
00073 #include "asterisk/acl.h"
00074 #include "asterisk/manager.h"
00075 #include "asterisk/callerid.h"
00076 #include "asterisk/app.h"
00077 #include "asterisk/astdb.h"
00078 #include "asterisk/musiconhold.h"
00079 #include "asterisk/features.h"
00080 #include "asterisk/utils.h"
00081 #include "asterisk/causes.h"
00082 #include "asterisk/localtime.h"
00083 #include "asterisk/aes.h"
00084 #include "asterisk/dnsmgr.h"
00085 #include "asterisk/devicestate.h"
00086 #include "asterisk/netsock.h"
00087 #include "asterisk/stringfields.h"
00088 #include "asterisk/linkedlists.h"
00089 #include "asterisk/event.h"
00090 #include "asterisk/astobj2.h"
00091 #include "asterisk/timing.h"
00092 
00093 #include "iax2.h"
00094 #include "iax2-parser.h"
00095 #include "iax2-provision.h"
00096 #include "jitterbuf.h"
00097 
00098 /*** DOCUMENTATION
00099    <application name="IAX2Provision" language="en_US">
00100       <synopsis>
00101          Provision a calling IAXy with a given template.
00102       </synopsis>
00103       <syntax>
00104          <parameter name="template">
00105             <para>If not specified, defaults to <literal>default</literal>.</para>
00106          </parameter>
00107       </syntax>
00108       <description>
00109          <para>Provisions the calling IAXy (assuming the calling entity is in fact an IAXy) with the
00110          given <replaceable>template</replaceable>. Returns <literal>-1</literal> on error
00111          or <literal>0</literal> on success.</para>
00112       </description>
00113    </application>
00114    <function name="IAXPEER" language="en_US">
00115       <synopsis>
00116          Gets IAX peer information.
00117       </synopsis>
00118       <syntax>
00119          <parameter name="peername" required="true">
00120             <enumlist>
00121                <enum name="CURRENTCHANNEL">
00122                   <para>If <replaceable>peername</replaceable> is specified to this value, return the IP address of the
00123                   endpoint of the current channel</para>
00124                </enum>
00125             </enumlist>
00126          </parameter>
00127          <parameter name="item">
00128             <para>If <replaceable>peername</replaceable> is specified, valid items are:</para>
00129             <enumlist>
00130                <enum name="ip">
00131                   <para>(default) The IP address.</para>
00132                </enum>
00133                <enum name="status">
00134                   <para>The peer's status (if <literal>qualify=yes</literal>)</para>
00135                </enum>
00136                <enum name="mailbox">
00137                   <para>The configured mailbox.</para>
00138                </enum>
00139                <enum name="context">
00140                   <para>The configured context.</para>
00141                </enum>
00142                <enum name="expire">
00143                   <para>The epoch time of the next expire.</para>
00144                </enum>
00145                <enum name="dynamic">
00146                   <para>Is it dynamic? (yes/no).</para>
00147                </enum>
00148                <enum name="callerid_name">
00149                   <para>The configured Caller ID name.</para>
00150                </enum>
00151                <enum name="callerid_num">
00152                   <para>The configured Caller ID number.</para>
00153                </enum>
00154                <enum name="codecs">
00155                   <para>The configured codecs.</para>
00156                </enum>
00157                <enum name="codec[x]">
00158                   <para>Preferred codec index number <replaceable>x</replaceable> (beginning
00159                   with <literal>0</literal>)</para>
00160                </enum>
00161             </enumlist>
00162          </parameter>
00163       </syntax>
00164       <description></description>
00165       <see-also>
00166          <ref type="function">SIPPEER</ref>
00167       </see-also>
00168    </function>
00169    <function name="IAXVAR" language="en_US">
00170       <synopsis>
00171          Sets or retrieves a remote variable.
00172       </synopsis>
00173       <syntax>
00174          <parameter name="varname" required="true" />
00175       </syntax>
00176       <description></description>
00177    </function>
00178  ***/
00179 
00180 /* Define SCHED_MULTITHREADED to run the scheduler in a special
00181    multithreaded mode. */
00182 #define SCHED_MULTITHREADED
00183 
00184 /* Define DEBUG_SCHED_MULTITHREADED to keep track of where each
00185    thread is actually doing. */
00186 #define DEBUG_SCHED_MULTITHREAD
00187 
00188 
00189 #ifdef SO_NO_CHECK
00190 static int nochecksums = 0;
00191 #endif
00192 
00193 #define PTR_TO_CALLNO(a) ((unsigned short)(unsigned long)(a))
00194 #define CALLNO_TO_PTR(a) ((void *)(unsigned long)(a))
00195 
00196 #define DEFAULT_THREAD_COUNT 10
00197 #define DEFAULT_MAX_THREAD_COUNT 100
00198 #define DEFAULT_RETRY_TIME 1000
00199 #define MEMORY_SIZE 100
00200 #define DEFAULT_DROP 3
00201 
00202 #define DEBUG_SUPPORT
00203 
00204 #define MIN_REUSE_TIME     60 /* Don't reuse a call number within 60 seconds */
00205 
00206 /* Sample over last 100 units to determine historic jitter */
00207 #define GAMMA (0.01)
00208 
00209 static struct ast_codec_pref prefs;
00210 
00211 static const char tdesc[] = "Inter Asterisk eXchange Driver (Ver 2)";
00212 
00213 
00214 /*! \brief Maximum transmission unit for the UDP packet in the trunk not to be
00215     fragmented. This is based on 1516 - ethernet - ip - udp - iax minus one g711 frame = 1240 */
00216 #define MAX_TRUNK_MTU 1240 
00217 
00218 static int global_max_trunk_mtu;    /*!< Maximum MTU, 0 if not used */
00219 static int trunk_timed, trunk_untimed, trunk_maxmtu, trunk_nmaxmtu ;    /*!< Trunk MTU statistics */
00220 
00221 #define DEFAULT_CONTEXT "default"
00222 
00223 static char default_parkinglot[AST_MAX_CONTEXT];
00224 
00225 static char language[MAX_LANGUAGE] = "";
00226 static char regcontext[AST_MAX_CONTEXT] = "";
00227 
00228 static int maxauthreq = 3;
00229 static int max_retries = 4;
00230 static int ping_time = 21;
00231 static int lagrq_time = 10;
00232 static int maxjitterbuffer=1000;
00233 static int resyncthreshold=1000;
00234 static int maxjitterinterps=10;
00235 static int jittertargetextra = 40; /* number of milliseconds the new jitter buffer adds on to its size */
00236 
00237 #define MAX_TRUNKDATA           640 * 200       /*!< 40ms, uncompressed linear * 200 channels */
00238 
00239 static int trunkfreq = 20;
00240 static int trunkmaxsize = MAX_TRUNKDATA;
00241 
00242 static int authdebug = 1;
00243 static int autokill = 0;
00244 static int iaxcompat = 0;
00245 static int last_authmethod = 0;
00246 
00247 static int iaxdefaultdpcache=10 * 60;  /* Cache dialplan entries for 10 minutes by default */
00248 
00249 static int iaxdefaulttimeout = 5;      /* Default to wait no more than 5 seconds for a reply to come back */
00250 
00251 static struct {
00252    unsigned int tos;
00253    unsigned int cos;
00254 } qos = { 0, 0 };
00255 
00256 static int min_reg_expire;
00257 static int max_reg_expire;
00258 
00259 static int srvlookup = 0;
00260 
00261 static struct ast_timer *timer;           /* Timer for trunking */
00262 
00263 static struct ast_netsock_list *netsock;
00264 static struct ast_netsock_list *outsock;     /*!< used if sourceaddress specified and bindaddr == INADDR_ANY */
00265 static int defaultsockfd = -1;
00266 
00267 int (*iax2_regfunk)(const char *username, int onoff) = NULL;
00268 
00269 /* Ethernet, etc */
00270 #define IAX_CAPABILITY_FULLBANDWIDTH   0xFFFF
00271 /* T1, maybe ISDN */
00272 #define IAX_CAPABILITY_MEDBANDWIDTH    (IAX_CAPABILITY_FULLBANDWIDTH &  \
00273                 ~AST_FORMAT_SLINEAR &        \
00274                 ~AST_FORMAT_SLINEAR16 &         \
00275                 ~AST_FORMAT_SIREN7 &         \
00276                 ~AST_FORMAT_SIREN14 &        \
00277                 ~AST_FORMAT_ULAW &        \
00278                 ~AST_FORMAT_ALAW &        \
00279                 ~AST_FORMAT_G722) 
00280 /* A modem */
00281 #define IAX_CAPABILITY_LOWBANDWIDTH (IAX_CAPABILITY_MEDBANDWIDTH &      \
00282                 ~AST_FORMAT_G726 &        \
00283                 ~AST_FORMAT_G726_AAL2 &      \
00284                 ~AST_FORMAT_ADPCM)
00285 
00286 #define IAX_CAPABILITY_LOWFREE      (IAX_CAPABILITY_LOWBANDWIDTH &      \
00287                 ~AST_FORMAT_G723_1)
00288 
00289 
00290 #define DEFAULT_MAXMS      2000     /* Must be faster than 2 seconds by default */
00291 #define DEFAULT_FREQ_OK    60 * 1000   /* How often to check for the host to be up */
00292 #define DEFAULT_FREQ_NOTOK 10 * 1000   /* How often to check, if the host is down... */
00293 
00294 /* if a pvt has encryption setup done and is running on the call */
00295 #define IAX_CALLENCRYPTED(pvt) \
00296    (ast_test_flag(pvt, IAX_ENCRYPTED) && ast_test_flag(pvt, IAX_KEYPOPULATED))
00297 
00298 #define IAX_DEBUGDIGEST(msg, key) do { \
00299       int idx; \
00300       char digest[33] = ""; \
00301       \
00302       if (!iaxdebug) \
00303          break; \
00304       \
00305       for (idx = 0; idx < 16; idx++) \
00306          sprintf(digest + (idx << 1), "%2.2x", (unsigned char) key[idx]); \
00307       \
00308       ast_log(LOG_NOTICE, msg " IAX_COMMAND_RTKEY to rotate key to '%s'\n", digest); \
00309    } while(0)
00310 
00311 static   struct io_context *io;
00312 static   struct ast_sched_thread *sched;
00313 
00314 static int iax2_capability = IAX_CAPABILITY_FULLBANDWIDTH;
00315 
00316 static int iaxdebug = 0;
00317 
00318 static int iaxtrunkdebug = 0;
00319 
00320 static int test_losspct = 0;
00321 #ifdef IAXTESTS
00322 static int test_late = 0;
00323 static int test_resync = 0;
00324 static int test_jit = 0;
00325 static int test_jitpct = 0;
00326 #endif /* IAXTESTS */
00327 
00328 static char accountcode[AST_MAX_ACCOUNT_CODE];
00329 static char mohinterpret[MAX_MUSICCLASS];
00330 static char mohsuggest[MAX_MUSICCLASS];
00331 static int amaflags = 0;
00332 static int adsi = 0;
00333 static int delayreject = 0;
00334 static int iax2_encryption = 0;
00335 
00336 static struct ast_flags globalflags = { 0 };
00337 
00338 static pthread_t netthreadid = AST_PTHREADT_NULL;
00339 
00340 enum iax2_state {
00341    IAX_STATE_STARTED =        (1 << 0),
00342    IAX_STATE_AUTHENTICATED =  (1 << 1),
00343    IAX_STATE_TBD =            (1 << 2),
00344 };
00345 
00346 struct iax2_context {
00347    char context[AST_MAX_CONTEXT];
00348    struct iax2_context *next;
00349 };
00350 
00351 enum iax2_flags {
00352    IAX_HASCALLERID =    (1 << 0),   /*!< CallerID has been specified */
00353    IAX_DELME =    (1 << 1),   /*!< Needs to be deleted */
00354    IAX_TEMPONLY =    (1 << 2),   /*!< Temporary (realtime) */
00355    IAX_TRUNK =    (1 << 3),   /*!< Treat as a trunk */
00356    IAX_NOTRANSFER =  (1 << 4),   /*!< Don't native bridge */
00357    IAX_USEJITTERBUF =   (1 << 5),   /*!< Use jitter buffer */
00358    IAX_DYNAMIC =     (1 << 6),   /*!< dynamic peer */
00359    IAX_SENDANI =     (1 << 7),   /*!< Send ANI along with CallerID */
00360         /* (1 << 8) is currently unused due to the deprecation of an old option. Go ahead, take it! */
00361    IAX_ALREADYGONE = (1 << 9),   /*!< Already disconnected */
00362    IAX_PROVISION =      (1 << 10),  /*!< This is a provisioning request */
00363    IAX_QUELCH =      (1 << 11),  /*!< Whether or not we quelch audio */
00364    IAX_ENCRYPTED =      (1 << 12),  /*!< Whether we should assume encrypted tx/rx */
00365    IAX_KEYPOPULATED =   (1 << 13),  /*!< Whether we have a key populated */
00366    IAX_CODEC_USER_FIRST =  (1 << 14),  /*!< are we willing to let the other guy choose the codec? */
00367    IAX_CODEC_NOPREFS =     (1 << 15),  /*!< Force old behaviour by turning off prefs */
00368    IAX_CODEC_NOCAP =    (1 << 16),  /*!< only consider requested format and ignore capabilities*/
00369    IAX_RTCACHEFRIENDS =    (1 << 17),  /*!< let realtime stay till your reload */
00370    IAX_RTUPDATE =       (1 << 18),  /*!< Send a realtime update */
00371    IAX_RTAUTOCLEAR =    (1 << 19),  /*!< erase me on expire */ 
00372    IAX_FORCEJITTERBUF = (1 << 20),  /*!< Force jitterbuffer, even when bridged to a channel that can take jitter */ 
00373    IAX_RTIGNOREREGEXPIRE = (1 << 21),  /*!< When using realtime, ignore registration expiration */
00374    IAX_TRUNKTIMESTAMPS =   (1 << 22),  /*!< Send trunk timestamps */
00375    IAX_TRANSFERMEDIA =     (1 << 23),      /*!< When doing IAX2 transfers, transfer media only */
00376    IAX_MAXAUTHREQ =        (1 << 24),      /*!< Maximum outstanding AUTHREQ restriction is in place */
00377    IAX_DELAYPBXSTART =  (1 << 25),  /*!< Don't start a PBX on the channel until the peer sends us a
00378                        response, so that we've achieved a three-way handshake with
00379                        them before sending voice or anything else*/
00380    IAX_ALLOWFWDOWNLOAD =   (1 << 26),  /*!< Allow the FWDOWNL command? */
00381    IAX_IMMEDIATE =      (1 << 27),      /*!< Allow immediate off-hook to extension s */
00382    IAX_FORCE_ENCRYPT =  (1 << 28),      /*!< Forces call encryption, if encryption not possible hangup */
00383    IAX_SHRINKCALLERID = (1 << 29),   /*!< Turn on and off caller id shrinking */
00384 };
00385 
00386 static int global_rtautoclear = 120;
00387 
00388 static int reload_config(void);
00389 
00390 /*!
00391  * \brief Call token validation settings.
00392  */
00393 enum calltoken_peer_enum {
00394    /*! \brief Default calltoken required unless the ip is in the ignorelist */
00395    CALLTOKEN_DEFAULT = 0,
00396    /*! \brief Require call token validation. */
00397    CALLTOKEN_YES = 1,
00398    /*! \brief Require call token validation after a successful registration
00399     *         using call token validation occurs. */
00400    CALLTOKEN_AUTO = 2,
00401    /*! \brief Do not require call token validation. */
00402    CALLTOKEN_NO = 3,
00403 };
00404 
00405 struct iax2_user {
00406    AST_DECLARE_STRING_FIELDS(
00407       AST_STRING_FIELD(name);
00408       AST_STRING_FIELD(secret);
00409       AST_STRING_FIELD(dbsecret);
00410       AST_STRING_FIELD(accountcode);
00411       AST_STRING_FIELD(mohinterpret);
00412       AST_STRING_FIELD(mohsuggest);
00413       AST_STRING_FIELD(inkeys);               /*!< Key(s) this user can use to authenticate to us */
00414       AST_STRING_FIELD(language);
00415       AST_STRING_FIELD(cid_num);
00416       AST_STRING_FIELD(cid_name);
00417       AST_STRING_FIELD(parkinglot);           /*!< Default parkinglot for device */
00418    );
00419    
00420    int authmethods;
00421    int encmethods;
00422    int amaflags;
00423    int adsi;
00424    unsigned int flags;
00425    int capability;
00426    int maxauthreq; /*!< Maximum allowed outstanding AUTHREQs */
00427    int curauthreq; /*!< Current number of outstanding AUTHREQs */
00428    struct ast_codec_pref prefs;
00429    struct ast_ha *ha;
00430    struct iax2_context *contexts;
00431    struct ast_variable *vars;
00432    enum calltoken_peer_enum calltoken_required;        /*!< Is calltoken validation required or not, can be YES, NO, or AUTO */
00433 };
00434 
00435 struct iax2_peer {
00436    AST_DECLARE_STRING_FIELDS(
00437       AST_STRING_FIELD(name);
00438       AST_STRING_FIELD(username);
00439       AST_STRING_FIELD(secret);
00440       AST_STRING_FIELD(dbsecret);
00441       AST_STRING_FIELD(outkey);      /*!< What key we use to talk to this peer */
00442 
00443       AST_STRING_FIELD(regexten);     /*!< Extension to register (if regcontext is used) */
00444       AST_STRING_FIELD(context);      /*!< For transfers only */
00445       AST_STRING_FIELD(peercontext);  /*!< Context to pass to peer */
00446       AST_STRING_FIELD(mailbox);     /*!< Mailbox */
00447       AST_STRING_FIELD(mohinterpret);
00448       AST_STRING_FIELD(mohsuggest);
00449       AST_STRING_FIELD(inkeys);     /*!< Key(s) this peer can use to authenticate to us */
00450       /* Suggested caller id if registering */
00451       AST_STRING_FIELD(cid_num);    /*!< Default context (for transfer really) */
00452       AST_STRING_FIELD(cid_name);      /*!< Default context (for transfer really) */
00453       AST_STRING_FIELD(zonetag);    /*!< Time Zone */
00454       AST_STRING_FIELD(parkinglot);   /*!< Default parkinglot for device */
00455    );
00456    struct ast_codec_pref prefs;
00457    struct ast_dnsmgr_entry *dnsmgr;    /*!< DNS refresh manager */
00458    struct sockaddr_in addr;
00459    int formats;
00460    int sockfd;             /*!< Socket to use for transmission */
00461    struct in_addr mask;
00462    int adsi;
00463    unsigned int flags;
00464 
00465    /* Dynamic Registration fields */
00466    struct sockaddr_in defaddr;         /*!< Default address if there is one */
00467    int authmethods;           /*!< Authentication methods (IAX_AUTH_*) */
00468    int encmethods;               /*!< Encryption methods (IAX_ENCRYPT_*) */
00469 
00470    int expire;             /*!< Schedule entry for expiry */
00471    int expiry;             /*!< How soon to expire */
00472    int capability;               /*!< Capability */
00473 
00474    /* Qualification */
00475    int callno;             /*!< Call number of POKE request */
00476    int pokeexpire;               /*!< Scheduled qualification-related task (ie iax2_poke_peer_s or iax2_poke_noanswer) */
00477    int lastms;             /*!< How long last response took (in ms), or -1 for no response */
00478    int maxms;              /*!< Max ms we will accept for the host to be up, 0 to not monitor */
00479 
00480    int pokefreqok;               /*!< How often to check if the host is up */
00481    int pokefreqnotok;            /*!< How often to check when the host has been determined to be down */
00482    int historicms;               /*!< How long recent average responses took */
00483    int smoothing;             /*!< Sample over how many units to determine historic ms */
00484    uint16_t maxcallno;              /*!< Max call number limit for this peer.  Set on registration */
00485 
00486    struct ast_event_sub *mwi_event_sub;
00487 
00488    struct ast_ha *ha;
00489    enum calltoken_peer_enum calltoken_required;        /*!< Is calltoken validation required or not, can be YES, NO, or AUTO */
00490 };
00491 
00492 #define IAX2_TRUNK_PREFACE (sizeof(struct iax_frame) + sizeof(struct ast_iax2_meta_hdr) + sizeof(struct ast_iax2_meta_trunk_hdr))
00493 
00494 struct iax2_trunk_peer {
00495    ast_mutex_t lock;
00496    int sockfd;
00497    struct sockaddr_in addr;
00498    struct timeval txtrunktime;      /*!< Transmit trunktime */
00499    struct timeval rxtrunktime;      /*!< Receive trunktime */
00500    struct timeval lasttxtime;    /*!< Last transmitted trunktime */
00501    struct timeval trunkact;      /*!< Last trunk activity */
00502    unsigned int lastsent;        /*!< Last sent time */
00503    /* Trunk data and length */
00504    unsigned char *trunkdata;
00505    unsigned int trunkdatalen;
00506    unsigned int trunkdataalloc;
00507    int trunkmaxmtu;
00508    int trunkerror;
00509    int calls;
00510    AST_LIST_ENTRY(iax2_trunk_peer) list;
00511 };
00512 
00513 static AST_LIST_HEAD_STATIC(tpeers, iax2_trunk_peer);
00514 
00515 struct iax_firmware {
00516    AST_LIST_ENTRY(iax_firmware) list;
00517    int fd;
00518    int mmaplen;
00519    int dead;
00520    struct ast_iax2_firmware_header *fwh;
00521    unsigned char *buf;
00522 };
00523 
00524 enum iax_reg_state {
00525    REG_STATE_UNREGISTERED = 0,
00526    REG_STATE_REGSENT,
00527    REG_STATE_AUTHSENT,
00528    REG_STATE_REGISTERED,
00529    REG_STATE_REJECTED,
00530    REG_STATE_TIMEOUT,
00531    REG_STATE_NOAUTH
00532 };
00533 
00534 enum iax_transfer_state {
00535    TRANSFER_NONE = 0,
00536    TRANSFER_BEGIN,
00537    TRANSFER_READY,
00538    TRANSFER_RELEASED,
00539    TRANSFER_PASSTHROUGH,
00540    TRANSFER_MBEGIN,
00541    TRANSFER_MREADY,
00542    TRANSFER_MRELEASED,
00543    TRANSFER_MPASSTHROUGH,
00544    TRANSFER_MEDIA,
00545    TRANSFER_MEDIAPASS
00546 };
00547 
00548 struct iax2_registry {
00549    struct sockaddr_in addr;      /*!< Who we connect to for registration purposes */
00550    char username[80];
00551    char secret[80];        /*!< Password or key name in []'s */
00552    int expire;          /*!< Sched ID of expiration */
00553    int refresh;            /*!< How often to refresh */
00554    enum iax_reg_state regstate;
00555    int messages;           /*!< Message count, low 8 bits = new, high 8 bits = old */
00556    int callno;          /*!< Associated call number if applicable */
00557    struct sockaddr_in us;        /*!< Who the server thinks we are */
00558    struct ast_dnsmgr_entry *dnsmgr; /*!< DNS refresh manager */
00559    AST_LIST_ENTRY(iax2_registry) entry;
00560 };
00561 
00562 static AST_LIST_HEAD_STATIC(registrations, iax2_registry);
00563 
00564 /* Don't retry more frequently than every 10 ms, or less frequently than every 5 seconds */
00565 #define MIN_RETRY_TIME     100
00566 #define MAX_RETRY_TIME     10000
00567 
00568 #define MAX_JITTER_BUFFER  50
00569 #define MIN_JITTER_BUFFER  10
00570 
00571 #define DEFAULT_TRUNKDATA  640 * 10 /*!< 40ms, uncompressed linear * 10 channels */
00572 
00573 #define MAX_TIMESTAMP_SKEW 160      /*!< maximum difference between actual and predicted ts for sending */
00574 
00575 /* If consecutive voice frame timestamps jump by more than this many milliseconds, then jitter buffer will resync */
00576 #define TS_GAP_FOR_JB_RESYNC  5000
00577 
00578 /* used for first_iax_message and last_iax_message.  If this bit is set it was TX, else RX */
00579 #define MARK_IAX_SUBCLASS_TX  0x8000
00580 
00581 static int iaxthreadcount = DEFAULT_THREAD_COUNT;
00582 static int iaxmaxthreadcount = DEFAULT_MAX_THREAD_COUNT;
00583 static int iaxdynamicthreadcount = 0;
00584 static int iaxdynamicthreadnum = 0;
00585 static int iaxactivethreadcount = 0;
00586 
00587 struct iax_rr {
00588    int jitter;
00589    int losspct;
00590    int losscnt;
00591    int packets;
00592    int delay;
00593    int dropped;
00594    int ooo;
00595 };
00596 
00597 struct iax2_pvt_ref;
00598 
00599 struct chan_iax2_pvt {
00600    /*! Socket to send/receive on for this call */
00601    int sockfd;
00602    /*! Last received voice format */
00603    int voiceformat;
00604    /*! Last received video format */
00605    int videoformat;
00606    /*! Last sent voice format */
00607    int svoiceformat;
00608    /*! Last sent video format */
00609    int svideoformat;
00610    /*! What we are capable of sending */
00611    int capability;
00612    /*! Last received timestamp */
00613    unsigned int last;
00614    /*! Last sent timestamp - never send the same timestamp twice in a single call */
00615    unsigned int lastsent;
00616    /*! Timestamp of the last video frame sent */
00617    unsigned int lastvsent;
00618    /*! Next outgoing timestamp if everything is good */
00619    unsigned int nextpred;
00620    /*! iax frame subclass that began iax2_pvt entry. 0x8000 bit is set on TX */
00621    int first_iax_message;
00622    /*! Last iax frame subclass sent or received for a iax2_pvt. 0x8000 bit is set on TX */
00623    int last_iax_message;
00624    /*! True if the last voice we transmitted was not silence/CNG */
00625    unsigned int notsilenttx:1;
00626    /*! Ping time */
00627    unsigned int pingtime;
00628    /*! Max time for initial response */
00629    int maxtime;
00630    /*! Peer Address */
00631    struct sockaddr_in addr;
00632    /*! Actual used codec preferences */
00633    struct ast_codec_pref prefs;
00634    /*! Requested codec preferences */
00635    struct ast_codec_pref rprefs;
00636    /*! Our call number */
00637    unsigned short callno;
00638    /*! Our callno_entry entry */
00639    struct callno_entry *callno_entry;
00640    /*! Peer callno */
00641    unsigned short peercallno;
00642    /*! Negotiated format, this is only used to remember what format was
00643        chosen for an unauthenticated call so that the channel can get
00644        created later using the right format */
00645    int chosenformat;
00646    /*! Peer selected format */
00647    int peerformat;
00648    /*! Peer capability */
00649    int peercapability;
00650    /*! timeval that we base our transmission on */
00651    struct timeval offset;
00652    /*! timeval that we base our delivery on */
00653    struct timeval rxcore;
00654    /*! The jitterbuffer */
00655    jitterbuf *jb;
00656    /*! active jb read scheduler id */
00657    int jbid;                       
00658    /*! LAG */
00659    int lag;
00660    /*! Error, as discovered by the manager */
00661    int error;
00662    /*! Owner if we have one */
00663    struct ast_channel *owner;
00664    /*! What's our state? */
00665    struct ast_flags state;
00666    /*! Expiry (optional) */
00667    int expiry;
00668    /*! Next outgoing sequence number */
00669    unsigned char oseqno;
00670    /*! Next sequence number they have not yet acknowledged */
00671    unsigned char rseqno;
00672    /*! Next incoming sequence number */
00673    unsigned char iseqno;
00674    /*! Last incoming sequence number we have acknowledged */
00675    unsigned char aseqno;
00676 
00677    AST_DECLARE_STRING_FIELDS(
00678       /*! Peer name */
00679       AST_STRING_FIELD(peer);
00680       /*! Default Context */
00681       AST_STRING_FIELD(context);
00682       /*! Caller ID if available */
00683       AST_STRING_FIELD(cid_num);
00684       AST_STRING_FIELD(cid_name);
00685       /*! Hidden Caller ID (i.e. ANI) if appropriate */
00686       AST_STRING_FIELD(ani);
00687       /*! DNID */
00688       AST_STRING_FIELD(dnid);
00689       /*! RDNIS */
00690       AST_STRING_FIELD(rdnis);
00691       /*! Requested Extension */
00692       AST_STRING_FIELD(exten);
00693       /*! Expected Username */
00694       AST_STRING_FIELD(username);
00695       /*! Expected Secret */
00696       AST_STRING_FIELD(secret);
00697       /*! MD5 challenge */
00698       AST_STRING_FIELD(challenge);
00699       /*! Public keys permitted keys for incoming authentication */
00700       AST_STRING_FIELD(inkeys);
00701       /*! Private key for outgoing authentication */
00702       AST_STRING_FIELD(outkey);
00703       /*! Preferred language */
00704       AST_STRING_FIELD(language);
00705       /*! Hostname/peername for naming purposes */
00706       AST_STRING_FIELD(host);
00707 
00708       AST_STRING_FIELD(dproot);
00709       AST_STRING_FIELD(accountcode);
00710       AST_STRING_FIELD(mohinterpret);
00711       AST_STRING_FIELD(mohsuggest);
00712       /*! received OSP token */
00713       AST_STRING_FIELD(osptoken);
00714       /*! Default parkinglot */
00715       AST_STRING_FIELD(parkinglot);
00716    );
00717    /*! AUTHREJ all AUTHREP frames */
00718    int authrej;
00719    /*! permitted authentication methods */
00720    int authmethods;
00721    /*! permitted encryption methods */
00722    int encmethods;
00723    /*! Encryption AES-128 Key */
00724    ast_aes_encrypt_key ecx;
00725    /*! Decryption AES-128 Key corresponding to ecx */
00726    ast_aes_decrypt_key mydcx;
00727    /*! Decryption AES-128 Key used to decrypt peer frames */
00728    ast_aes_decrypt_key dcx;
00729    /*! scheduler id associated with iax_key_rotate 
00730     * for encrypted calls*/
00731    int keyrotateid;
00732    /*! 32 bytes of semi-random data */
00733    unsigned char semirand[32];
00734    /*! Associated registry */
00735    struct iax2_registry *reg;
00736    /*! Associated peer for poking */
00737    struct iax2_peer *peerpoke;
00738    /*! IAX_ flags */
00739    unsigned int flags;
00740    int adsi;
00741 
00742    /*! Transferring status */
00743    enum iax_transfer_state transferring;
00744    /*! Transfer identifier */
00745    int transferid;
00746    /*! Who we are IAX transferring to */
00747    struct sockaddr_in transfer;
00748    /*! What's the new call number for the transfer */
00749    unsigned short transfercallno;
00750    /*! Transfer encrypt AES-128 Key */
00751    ast_aes_encrypt_key tdcx;
00752 
00753    /*! Status of knowledge of peer ADSI capability */
00754    int peeradsicpe;
00755 
00756    /*! Who we are bridged to */
00757    unsigned short bridgecallno;
00758    
00759    int pingid;       /*!< Transmit PING request */
00760    int lagid;        /*!< Retransmit lag request */
00761    int autoid;       /*!< Auto hangup for Dialplan requestor */
00762    int authid;       /*!< Authentication rejection ID */
00763    int authfail;        /*!< Reason to report failure */
00764    int initid;       /*!< Initial peer auto-congest ID (based on qualified peers) */
00765    int calling_ton;
00766    int calling_tns;
00767    int calling_pres;
00768    int amaflags;
00769    AST_LIST_HEAD_NOLOCK(, iax2_dpcache) dpentries;
00770    /*! variables inherited from the user definition */
00771    struct ast_variable *vars;
00772    /*! variables transmitted in a NEW packet */
00773    struct ast_variable *iaxvars;
00774    /*! last received remote rr */
00775    struct iax_rr remote_rr;
00776    /*! Current base time: (just for stats) */
00777    int min;
00778    /*! Dropped frame count: (just for stats) */
00779    int frames_dropped;
00780    /*! received frame count: (just for stats) */
00781    int frames_received;
00782    /*! num bytes used for calltoken ie, even an empty ie should contain 2 */
00783    unsigned char calltoken_ie_len;
00784    /*! hold all signaling frames from the pbx thread until we have a destination callno */
00785    char hold_signaling;
00786    /*! frame queue for signaling frames from pbx thread waiting for destination callno */
00787    AST_LIST_HEAD_NOLOCK(signaling_queue, signaling_queue_entry) signaling_queue;
00788 };
00789 
00790 struct signaling_queue_entry {
00791    struct ast_frame f;
00792    AST_LIST_ENTRY(signaling_queue_entry) next;
00793 };
00794 
00795 /*! table of available call numbers */
00796 static struct ao2_container *callno_pool;
00797 
00798 /*! table of available trunk call numbers */
00799 static struct ao2_container *callno_pool_trunk;
00800 
00801 static const unsigned int CALLNO_POOL_BUCKETS = 2699;
00802 
00803 /*!
00804  * \brief a list of frames that may need to be retransmitted
00805  *
00806  * \note The contents of this list do not need to be explicitly destroyed
00807  * on module unload.  This is because all active calls are destroyed, and
00808  * all frames in this queue will get destroyed as a part of that process.
00809  */
00810 static AST_LIST_HEAD_STATIC(frame_queue, iax_frame);
00811 
00812 static int randomcalltokendata;
00813 
00814 static const time_t MAX_CALLTOKEN_DELAY = 10;
00815 
00816 /*!
00817  * This module will get much higher performance when doing a lot of
00818  * user and peer lookups if the number of buckets is increased from 1.
00819  * However, to maintain old behavior for Asterisk 1.4, these are set to
00820  * 1 by default.  When using multiple buckets, search order through these
00821  * containers is considered random, so you will not be able to depend on
00822  * the order the entires are specified in iax.conf for matching order. */
00823 #ifdef LOW_MEMORY
00824 #define MAX_PEER_BUCKETS 17
00825 #else
00826 #define MAX_PEER_BUCKETS 563
00827 #endif
00828 static struct ao2_container *peers;
00829 
00830 #define MAX_USER_BUCKETS MAX_PEER_BUCKETS
00831 static struct ao2_container *users;
00832 
00833 /*! Table containing peercnt objects for every ip address consuming a callno */
00834 static struct ao2_container *peercnts;
00835 
00836 /*! Table containing custom callno limit rules for a range of ip addresses. */
00837 static struct ao2_container *callno_limits;
00838 
00839 /*! Table containing ip addresses not requiring calltoken validation */
00840 static struct ao2_container *calltoken_ignores;
00841 
00842 static uint16_t DEFAULT_MAXCALLNO_LIMIT = 2048;
00843 
00844 static uint16_t DEFAULT_MAXCALLNO_LIMIT_NONVAL = 8192;
00845 
00846 static uint16_t global_maxcallno;
00847 
00848 /*! Total num of call numbers allowed to be allocated without calltoken validation */
00849 static uint16_t global_maxcallno_nonval;
00850 
00851 static uint16_t total_nonval_callno_used = 0;
00852 
00853 /*! peer connection private, keeps track of all the call numbers
00854  *  consumed by a single ip address */
00855 struct peercnt {
00856    /*! ip address consuming call numbers */
00857    unsigned long addr;
00858    /*! Number of call numbers currently used by this ip address */
00859    uint16_t cur;
00860    /*! Max call numbers allowed for this ip address */
00861    uint16_t limit;
00862    /*! Specifies whether limit is set by a registration or not, if so normal
00863     *  limit setting rules do not apply to this address. */
00864    unsigned char reg;
00865 };
00866 
00867 /*! used by both callno_limits and calltoken_ignores containers */
00868 struct addr_range {
00869    /*! ip address range for custom callno limit rule */
00870    struct ast_ha ha;
00871    /*! callno limit for this ip address range, only used in callno_limits container */
00872    uint16_t limit;
00873    /*! delete me marker for reloads */
00874    unsigned char delme;
00875 };
00876 
00877 struct callno_entry {
00878    /*! callno used for this entry */
00879    uint16_t callno;
00880    /*! was this callno calltoken validated or not */
00881    unsigned char validated;
00882 };
00883 
00884 static AST_LIST_HEAD_STATIC(firmwares, iax_firmware);
00885 
00886 enum {
00887    /*! Extension exists */
00888    CACHE_FLAG_EXISTS      = (1 << 0),
00889    /*! Extension is nonexistent */
00890    CACHE_FLAG_NONEXISTENT = (1 << 1),
00891    /*! Extension can exist */
00892    CACHE_FLAG_CANEXIST    = (1 << 2),
00893    /*! Waiting to hear back response */
00894    CACHE_FLAG_PENDING     = (1 << 3),
00895    /*! Timed out */
00896    CACHE_FLAG_TIMEOUT     = (1 << 4),
00897    /*! Request transmitted */
00898    CACHE_FLAG_TRANSMITTED = (1 << 5),
00899    /*! Timeout */
00900    CACHE_FLAG_UNKNOWN     = (1 << 6),
00901    /*! Matchmore */
00902    CACHE_FLAG_MATCHMORE   = (1 << 7),
00903 };
00904 
00905 struct iax2_dpcache {
00906    char peercontext[AST_MAX_CONTEXT];
00907    char exten[AST_MAX_EXTENSION];
00908    struct timeval orig;
00909    struct timeval expiry;
00910    int flags;
00911    unsigned short callno;
00912    int waiters[256];
00913    AST_LIST_ENTRY(iax2_dpcache) cache_list;
00914    AST_LIST_ENTRY(iax2_dpcache) peer_list;
00915 };
00916 
00917 static AST_LIST_HEAD_STATIC(dpcache, iax2_dpcache);
00918 
00919 static void reg_source_db(struct iax2_peer *p);
00920 static struct iax2_peer *realtime_peer(const char *peername, struct sockaddr_in *sin);
00921 static struct iax2_user *realtime_user(const char *username, struct sockaddr_in *sin);
00922 
00923 static int ast_cli_netstats(struct mansession *s, int fd, int limit_fmt);
00924 static char *complete_iax2_peers(const char *line, const char *word, int pos, int state, int flags);
00925 static char *complete_iax2_unregister(const char *line, const char *word, int pos, int state);
00926 
00927 enum iax2_thread_iostate {
00928    IAX_IOSTATE_IDLE,
00929    IAX_IOSTATE_READY,
00930    IAX_IOSTATE_PROCESSING,
00931    IAX_IOSTATE_SCHEDREADY,
00932 };
00933 
00934 enum iax2_thread_type {
00935    IAX_THREAD_TYPE_POOL,
00936    IAX_THREAD_TYPE_DYNAMIC,
00937 };
00938 
00939 struct iax2_pkt_buf {
00940    AST_LIST_ENTRY(iax2_pkt_buf) entry;
00941    size_t len;
00942    unsigned char buf[1];
00943 };
00944 
00945 struct iax2_thread {
00946    AST_LIST_ENTRY(iax2_thread) list;
00947    enum iax2_thread_type type;
00948    enum iax2_thread_iostate iostate;
00949 #ifdef SCHED_MULTITHREADED
00950    void (*schedfunc)(const void *);
00951    const void *scheddata;
00952 #endif
00953 #ifdef DEBUG_SCHED_MULTITHREAD
00954    char curfunc[80];
00955 #endif   
00956    int actions;
00957    pthread_t threadid;
00958    int threadnum;
00959    struct sockaddr_in iosin;
00960    unsigned char readbuf[4096]; 
00961    unsigned char *buf;
00962    ssize_t buf_len;
00963    size_t buf_size;
00964    int iofd;
00965    time_t checktime;
00966    ast_mutex_t lock;
00967    ast_cond_t cond;
00968    ast_mutex_t init_lock;
00969    ast_cond_t init_cond;
00970    /*! if this thread is processing a full frame,
00971      some information about that frame will be stored
00972      here, so we can avoid dispatching any more full
00973      frames for that callno to other threads */
00974    struct {
00975       unsigned short callno;
00976       struct sockaddr_in sin;
00977       unsigned char type;
00978       unsigned char csub;
00979    } ffinfo;
00980    /*! Queued up full frames for processing.  If more full frames arrive for
00981     *  a call which this thread is already processing a full frame for, they
00982     *  are queued up here. */
00983    AST_LIST_HEAD_NOLOCK(, iax2_pkt_buf) full_frames;
00984    unsigned char stop;
00985 };
00986 
00987 /* Thread lists */
00988 static AST_LIST_HEAD_STATIC(idle_list, iax2_thread);
00989 static AST_LIST_HEAD_STATIC(active_list, iax2_thread);
00990 static AST_LIST_HEAD_STATIC(dynamic_list, iax2_thread);
00991 
00992 static void *iax2_process_thread(void *data);
00993 static void iax2_destroy(int callno);
00994 
00995 static void signal_condition(ast_mutex_t *lock, ast_cond_t *cond)
00996 {
00997    ast_mutex_lock(lock);
00998    ast_cond_signal(cond);
00999    ast_mutex_unlock(lock);
01000 }
01001 
01002 /*!
01003  * \brief an array of iax2 pvt structures
01004  *
01005  * The container for active chan_iax2_pvt structures is implemented as an
01006  * array for extremely quick direct access to the correct pvt structure
01007  * based on the local call number.  The local call number is used as the
01008  * index into the array where the associated pvt structure is stored.
01009  */
01010 static struct chan_iax2_pvt *iaxs[IAX_MAX_CALLS + 1];
01011 
01012 /*!
01013  * \brief Another container of iax2_pvt structures
01014  *
01015  * Active IAX2 pvt structs are also stored in this container, if they are a part
01016  * of an active call where we know the remote side's call number.  The reason
01017  * for this is that incoming media frames do not contain our call number.  So,
01018  * instead of having to iterate the entire iaxs array, we use this container to
01019  * look up calls where the remote side is using a given call number.
01020  */
01021 static struct ao2_container *iax_peercallno_pvts;
01022 
01023 /*!
01024  * \brief chan_iax2_pvt structure locks
01025  *
01026  * These locks are used when accessing a pvt structure in the iaxs array.
01027  * The index used here is the same as used in the iaxs array.  It is the
01028  * local call number for the associated pvt struct.
01029  */
01030 static ast_mutex_t iaxsl[ARRAY_LEN(iaxs)];
01031 
01032 /*!
01033  *  * \brief Another container of iax2_pvt structures
01034  *  
01035  *  Active IAX2 pvt stucts used during transfering a call are stored here.  
01036  */
01037 static struct ao2_container *iax_transfercallno_pvts;
01038 
01039 /* Flag to use with trunk calls, keeping these calls high up.  It halves our effective use
01040    but keeps the division between trunked and non-trunked better. */
01041 #define TRUNK_CALL_START   IAX_MAX_CALLS / 2
01042 
01043 /* Debug routines... */
01044 static struct sockaddr_in debugaddr;
01045 
01046 static void iax_outputframe(struct iax_frame *f, struct ast_iax2_full_hdr *fhi, int rx, struct sockaddr_in *sin, int datalen)
01047 {
01048    if (iaxdebug ||
01049        (sin && debugaddr.sin_addr.s_addr && 
01050         (!ntohs(debugaddr.sin_port) ||
01051          debugaddr.sin_port == sin->sin_port) &&
01052         debugaddr.sin_addr.s_addr == sin->sin_addr.s_addr)) {
01053       if (iaxdebug) {
01054          iax_showframe(f, fhi, rx, sin, datalen);
01055       } else {
01056          iaxdebug = 1;
01057          iax_showframe(f, fhi, rx, sin, datalen);
01058          iaxdebug = 0;
01059       }
01060    }
01061 }
01062 
01063 static void iax_debug_output(const char *data)
01064 {
01065    if (iaxdebug)
01066       ast_verbose("%s", data);
01067 }
01068 
01069 static void iax_error_output(const char *data)
01070 {
01071    ast_log(LOG_WARNING, "%s", data);
01072 }
01073 
01074 static void __attribute__((format(printf, 1, 2))) jb_error_output(const char *fmt, ...)
01075 {
01076    va_list args;
01077    char buf[1024];
01078 
01079    va_start(args, fmt);
01080    vsnprintf(buf, sizeof(buf), fmt, args);
01081    va_end(args);
01082 
01083    ast_log(LOG_ERROR, "%s", buf);
01084 }
01085 
01086 static void __attribute__((format(printf, 1, 2))) jb_warning_output(const char *fmt, ...)
01087 {
01088    va_list args;
01089    char buf[1024];
01090 
01091    va_start(args, fmt);
01092    vsnprintf(buf, sizeof(buf), fmt, args);
01093    va_end(args);
01094 
01095    ast_log(LOG_WARNING, "%s", buf);
01096 }
01097 
01098 static void __attribute__((format(printf, 1, 2))) jb_debug_output(const char *fmt, ...)
01099 {
01100    va_list args;
01101    char buf[1024];
01102 
01103    va_start(args, fmt);
01104    vsnprintf(buf, sizeof(buf), fmt, args);
01105    va_end(args);
01106 
01107    ast_verbose("%s", buf);
01108 }
01109 
01110 static int maxtrunkcall = TRUNK_CALL_START;
01111 static int maxnontrunkcall = 1;
01112 
01113 static enum ast_bridge_result iax2_bridge(struct ast_channel *c0, struct ast_channel *c1, int flags, struct ast_frame **fo, struct ast_channel **rc, int timeoutms);
01114 static int expire_registry(const void *data);
01115 static int iax2_answer(struct ast_channel *c);
01116 static int iax2_call(struct ast_channel *c, char *dest, int timeout);
01117 static int iax2_devicestate(void *data);
01118 static int iax2_digit_begin(struct ast_channel *c, char digit);
01119 static int iax2_digit_end(struct ast_channel *c, char digit, unsigned int duration);
01120 static int iax2_do_register(struct iax2_registry *reg);
01121 static int iax2_fixup(struct ast_channel *oldchannel, struct ast_channel *newchan);
01122 static int iax2_hangup(struct ast_channel *c);
01123 static int iax2_indicate(struct ast_channel *c, int condition, const void *data, size_t datalen);
01124 static int iax2_poke_peer(struct iax2_peer *peer, int heldcall);
01125 static int iax2_provision(struct sockaddr_in *end, int sockfd, char *dest, const char *template, int force);
01126 static int iax2_send(struct chan_iax2_pvt *pvt, struct ast_frame *f, unsigned int ts, int seqno, int now, int transfer, int final);
01127 static int iax2_sendhtml(struct ast_channel *c, int subclass, const char *data, int datalen);
01128 static int iax2_sendimage(struct ast_channel *c, struct ast_frame *img);
01129 static int iax2_sendtext(struct ast_channel *c, const char *text);
01130 static int iax2_setoption(struct ast_channel *c, int option, void *data, int datalen);
01131 static int iax2_transfer(struct ast_channel *c, const char *dest);
01132 static int iax2_write(struct ast_channel *c, struct ast_frame *f);
01133 static int send_trunk(struct iax2_trunk_peer *tpeer, struct timeval *now);
01134 static int send_command(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
01135 static int send_command_final(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
01136 static int send_command_immediate(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
01137 static int send_command_locked(unsigned short callno, char, int, unsigned int, const unsigned char *, int, int);
01138 static int send_command_transfer(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int);
01139 static struct ast_channel *iax2_request(const char *type, int format, void *data, int *cause);
01140 static struct ast_frame *iax2_read(struct ast_channel *c);
01141 static struct iax2_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly);
01142 static struct iax2_user *build_user(const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly);
01143 static void realtime_update_peer(const char *peername, struct sockaddr_in *sin, time_t regtime);
01144 static void *iax2_dup_variable_datastore(void *);
01145 static void prune_peers(void);
01146 static void prune_users(void);
01147 static void iax2_free_variable_datastore(void *);
01148 
01149 static int acf_channel_read(struct ast_channel *chan, const char *funcname, char *preparse, char *buf, size_t buflen);
01150 static int decode_frame(ast_aes_decrypt_key *dcx, struct ast_iax2_full_hdr *fh, struct ast_frame *f, int *datalen);
01151 static int encrypt_frame(ast_aes_encrypt_key *ecx, struct ast_iax2_full_hdr *fh, unsigned char *poo, int *datalen);
01152 static void build_ecx_key(const unsigned char *digest, struct chan_iax2_pvt *pvt);
01153 static void build_rand_pad(unsigned char *buf, ssize_t len);
01154 static struct callno_entry *get_unused_callno(int trunk, int validated);
01155 static int replace_callno(const void *obj);
01156 static void sched_delay_remove(struct sockaddr_in *sin, struct callno_entry *callno_entry);
01157 
01158 static const struct ast_channel_tech iax2_tech = {
01159    .type = "IAX2",
01160    .description = tdesc,
01161    .capabilities = IAX_CAPABILITY_FULLBANDWIDTH,
01162    .properties = AST_CHAN_TP_WANTSJITTER,
01163    .requester = iax2_request,
01164    .devicestate = iax2_devicestate,
01165    .send_digit_begin = iax2_digit_begin,
01166    .send_digit_end = iax2_digit_end,
01167    .send_text = iax2_sendtext,
01168    .send_image = iax2_sendimage,
01169    .send_html = iax2_sendhtml,
01170    .call = iax2_call,
01171    .hangup = iax2_hangup,
01172    .answer = iax2_answer,
01173    .read = iax2_read,
01174    .write = iax2_write,
01175    .write_video = iax2_write,
01176    .indicate = iax2_indicate,
01177    .setoption = iax2_setoption,
01178    .bridge = iax2_bridge,
01179    .transfer = iax2_transfer,
01180    .fixup = iax2_fixup,
01181    .func_channel_read = acf_channel_read,
01182 };
01183 
01184 /*!
01185  * \internal
01186  * \brief Obtain the owner channel lock if the owner exists.
01187  *
01188  * \param callno IAX2 call id.
01189  *
01190  * \note Assumes the iaxsl[callno] lock is already obtained.
01191  *
01192  * \note
01193  * IMPORTANT NOTE!!!  Any time this function is used, even if
01194  * iaxs[callno] was valid before calling it, it may no longer be
01195  * valid after calling it.  This function may unlock and lock
01196  * the mutex associated with this callno, meaning that another
01197  * thread may grab it and destroy the call.
01198  *
01199  * \return Nothing
01200  */
01201 static void iax2_lock_owner(int callno)
01202 {
01203    for (;;) {
01204       if (!iaxs[callno] || !iaxs[callno]->owner) {
01205          /* There is no owner lock to get. */
01206          break;
01207       }
01208       if (!ast_channel_trylock(iaxs[callno]->owner)) {
01209          /* We got the lock */
01210          break;
01211       }
01212       /* Avoid deadlock by pausing and trying again */
01213       DEADLOCK_AVOIDANCE(&iaxsl[callno]);
01214    }
01215 }
01216 
01217 static void mwi_event_cb(const struct ast_event *event, void *userdata)
01218 {
01219    /* The MWI subscriptions exist just so the core knows we care about those
01220     * mailboxes.  However, we just grab the events out of the cache when it
01221     * is time to send MWI, since it is only sent with a REGACK. */
01222 }
01223 
01224 /*! \brief Send manager event at call setup to link between Asterisk channel name
01225    and IAX2 call identifiers */
01226 static void iax2_ami_channelupdate(struct chan_iax2_pvt *pvt) 
01227 {
01228    manager_event(EVENT_FLAG_SYSTEM, "ChannelUpdate",
01229       "Channel: %s\r\nChanneltype: IAX2\r\nIAX2-callno-local: %d\r\nIAX2-callno-remote: %d\r\nIAX2-peer: %s\r\n",
01230       pvt->owner ? pvt->owner->name : "",
01231       pvt->callno, pvt->peercallno, pvt->peer ? pvt->peer : "");
01232 }
01233 
01234 
01235 static struct ast_datastore_info iax2_variable_datastore_info = {
01236    .type = "IAX2_VARIABLE",
01237    .duplicate = iax2_dup_variable_datastore,
01238    .destroy = iax2_free_variable_datastore,
01239 };
01240 
01241 static void *iax2_dup_variable_datastore(void *old)
01242 {
01243    AST_LIST_HEAD(, ast_var_t) *oldlist = old, *newlist;
01244    struct ast_var_t *oldvar, *newvar;
01245 
01246    newlist = ast_calloc(sizeof(*newlist), 1);
01247    if (!newlist) {
01248       ast_log(LOG_ERROR, "Unable to duplicate iax2 variables\n");
01249       return NULL;
01250    }
01251 
01252    AST_LIST_HEAD_INIT(newlist);
01253    AST_LIST_LOCK(oldlist);
01254    AST_LIST_TRAVERSE(oldlist, oldvar, entries) {
01255       newvar = ast_var_assign(ast_var_name(oldvar), ast_var_value(oldvar));
01256       if (newvar)
01257          AST_LIST_INSERT_TAIL(newlist, newvar, entries);
01258       else
01259          ast_log(LOG_ERROR, "Unable to duplicate iax2 variable '%s'\n", ast_var_name(oldvar));
01260    }
01261    AST_LIST_UNLOCK(oldlist);
01262    return newlist;
01263 }
01264 
01265 static void iax2_free_variable_datastore(void *old)
01266 {
01267    AST_LIST_HEAD(, ast_var_t) *oldlist = old;
01268    struct ast_var_t *oldvar;
01269 
01270    AST_LIST_LOCK(oldlist);
01271    while ((oldvar = AST_LIST_REMOVE_HEAD(oldlist, entries))) {
01272       ast_free(oldvar);
01273    }
01274    AST_LIST_UNLOCK(oldlist);
01275    AST_LIST_HEAD_DESTROY(oldlist);
01276    ast_free(oldlist);
01277 }
01278 
01279 
01280 /* WARNING: insert_idle_thread should only ever be called within the
01281  * context of an iax2_process_thread() thread.
01282  */
01283 static void insert_idle_thread(struct iax2_thread *thread)
01284 {
01285    if (thread->type == IAX_THREAD_TYPE_DYNAMIC) {
01286       AST_LIST_LOCK(&dynamic_list);
01287       AST_LIST_INSERT_TAIL(&dynamic_list, thread, list);
01288       AST_LIST_UNLOCK(&dynamic_list);
01289    } else {
01290       AST_LIST_LOCK(&idle_list);
01291       AST_LIST_INSERT_TAIL(&idle_list, thread, list);
01292       AST_LIST_UNLOCK(&idle_list);
01293    }
01294 
01295    return;
01296 }
01297 
01298 static struct iax2_thread *find_idle_thread(void)
01299 {
01300    struct iax2_thread *thread = NULL;
01301 
01302    /* Pop the head of the idle list off */
01303    AST_LIST_LOCK(&idle_list);
01304    thread = AST_LIST_REMOVE_HEAD(&idle_list, list);
01305    AST_LIST_UNLOCK(&idle_list);
01306 
01307    /* If we popped a thread off the idle list, just return it */
01308    if (thread) {
01309       memset(&thread->ffinfo, 0, sizeof(thread->ffinfo));
01310       return thread;
01311    }
01312 
01313    /* Pop the head of the dynamic list off */
01314    AST_LIST_LOCK(&dynamic_list);
01315    thread = AST_LIST_REMOVE_HEAD(&dynamic_list, list);
01316    AST_LIST_UNLOCK(&dynamic_list);
01317 
01318    /* If we popped a thread off the dynamic list, just return it */
01319    if (thread) {
01320       memset(&thread->ffinfo, 0, sizeof(thread->ffinfo));
01321       return thread;
01322    }
01323 
01324    /* If we can't create a new dynamic thread for any reason, return no thread at all */
01325    if (iaxdynamicthreadcount >= iaxmaxthreadcount || !(thread = ast_calloc(1, sizeof(*thread))))
01326       return NULL;
01327 
01328    /* Set default values */
01329    ast_atomic_fetchadd_int(&iaxdynamicthreadcount, 1);
01330    thread->threadnum = ast_atomic_fetchadd_int(&iaxdynamicthreadnum, 1);
01331    thread->type = IAX_THREAD_TYPE_DYNAMIC;
01332 
01333    /* Initialize lock and condition */
01334    ast_mutex_init(&thread->lock);
01335    ast_cond_init(&thread->cond, NULL);
01336    ast_mutex_init(&thread->init_lock);
01337    ast_cond_init(&thread->init_cond, NULL);
01338    ast_mutex_lock(&thread->init_lock);
01339 
01340    /* Create thread and send it on it's way */
01341    if (ast_pthread_create_background(&thread->threadid, NULL, iax2_process_thread, thread)) {
01342       ast_cond_destroy(&thread->cond);
01343       ast_mutex_destroy(&thread->lock);
01344       ast_mutex_unlock(&thread->init_lock);
01345       ast_cond_destroy(&thread->init_cond);
01346       ast_mutex_destroy(&thread->init_lock);
01347       ast_free(thread);
01348       return NULL;
01349    }
01350 
01351    /* this thread is not processing a full frame (since it is idle),
01352       so ensure that the field for the full frame call number is empty */
01353    memset(&thread->ffinfo, 0, sizeof(thread->ffinfo));
01354 
01355    /* Wait for the thread to be ready before returning it to the caller */
01356    ast_cond_wait(&thread->init_cond, &thread->init_lock);
01357 
01358    /* Done with init_lock */
01359    ast_mutex_unlock(&thread->init_lock);
01360 
01361    return thread;
01362 }
01363 
01364 #ifdef SCHED_MULTITHREADED
01365 static int __schedule_action(void (*func)(const void *data), const void *data, const char *funcname)
01366 {
01367    struct iax2_thread *thread = NULL;
01368    static time_t lasterror;
01369    static time_t t;
01370 
01371    thread = find_idle_thread();
01372 
01373    if (thread != NULL) {
01374       thread->schedfunc = func;
01375       thread->scheddata = data;
01376       thread->iostate = IAX_IOSTATE_SCHEDREADY;
01377 #ifdef DEBUG_SCHED_MULTITHREAD
01378       ast_copy_string(thread->curfunc, funcname, sizeof(thread->curfunc));
01379 #endif
01380       signal_condition(&thread->lock, &thread->cond);
01381       return 0;
01382    }
01383    time(&t);
01384    if (t != lasterror) 
01385       ast_debug(1, "Out of idle IAX2 threads for scheduling!\n");
01386    lasterror = t;
01387 
01388    return -1;
01389 }
01390 #define schedule_action(func, data) __schedule_action(func, data, __PRETTY_FUNCTION__)
01391 #endif
01392 
01393 static int iax2_sched_replace(int id, struct ast_sched_thread *st, int when, 
01394       ast_sched_cb callback, const void *data)
01395 {
01396    ast_sched_thread_del(st, id);
01397 
01398    return ast_sched_thread_add(st, when, callback, data);
01399 }
01400 
01401 static int iax2_sched_add(struct ast_sched_thread *st, int when, 
01402       ast_sched_cb callback, const void *data)
01403 {
01404    return ast_sched_thread_add(st, when, callback, data);
01405 }
01406 
01407 static int send_ping(const void *data);
01408 
01409 static void __send_ping(const void *data)
01410 {
01411    int callno = (long) data;
01412 
01413    ast_mutex_lock(&iaxsl[callno]);
01414 
01415    if (iaxs[callno]) {
01416       if (iaxs[callno]->peercallno) {
01417          send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_PING, 0, NULL, 0, -1);
01418          iaxs[callno]->pingid = iax2_sched_add(sched, ping_time * 1000, send_ping, data);
01419       } else {
01420          /* I am the schedule, so I'm allowed to do this */
01421          iaxs[callno]->pingid = -1;
01422       }
01423    } else {
01424       ast_debug(1, "I was supposed to send a PING with callno %d, but no such call exists.\n", callno);
01425    }
01426 
01427    ast_mutex_unlock(&iaxsl[callno]);
01428 }
01429 
01430 static int send_ping(const void *data)
01431 {
01432 #ifdef SCHED_MULTITHREADED
01433    if (schedule_action(__send_ping, data))
01434 #endif      
01435       __send_ping(data);
01436 
01437    return 0;
01438 }
01439 
01440 static void encmethods_to_str(int e, struct ast_str *buf)
01441 {
01442    ast_str_set(&buf, 0, "(");
01443    if (e & IAX_ENCRYPT_AES128) {
01444       ast_str_append(&buf, 0, "aes128");
01445    }
01446    if (e & IAX_ENCRYPT_KEYROTATE) {
01447       ast_str_append(&buf, 0, ",keyrotate");
01448    }
01449    if (ast_str_strlen(buf) > 1) {
01450       ast_str_append(&buf, 0, ")");
01451    } else {
01452       ast_str_set(&buf, 0, "No");
01453    }
01454 }
01455 
01456 static int get_encrypt_methods(const char *s)
01457 {
01458    int e;
01459    if (!strcasecmp(s, "aes128"))
01460       e = IAX_ENCRYPT_AES128 | IAX_ENCRYPT_KEYROTATE;
01461    else if (ast_true(s))
01462       e = IAX_ENCRYPT_AES128 | IAX_ENCRYPT_KEYROTATE;
01463    else
01464       e = 0;
01465    return e;
01466 }
01467 
01468 static int send_lagrq(const void *data);
01469 
01470 static void __send_lagrq(const void *data)
01471 {
01472    int callno = (long) data;
01473 
01474    ast_mutex_lock(&iaxsl[callno]);
01475 
01476    if (iaxs[callno]) {
01477       if (iaxs[callno]->peercallno) {
01478          send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_LAGRQ, 0, NULL, 0, -1);
01479          iaxs[callno]->lagid = iax2_sched_add(sched, lagrq_time * 1000, send_lagrq, data);
01480       } else {
01481          /* I am the schedule, so I'm allowed to do this */
01482          iaxs[callno]->lagid = -1;
01483       }
01484    } else {
01485       ast_debug(1, "I was supposed to send a LAGRQ with callno %d, but no such call exists.\n", callno);
01486    }
01487 
01488    ast_mutex_unlock(&iaxsl[callno]);
01489 }
01490 
01491 static int send_lagrq(const void *data)
01492 {
01493 #ifdef SCHED_MULTITHREADED
01494    if (schedule_action(__send_lagrq, data))
01495 #endif      
01496       __send_lagrq(data);
01497    
01498    return 0;
01499 }
01500 
01501 static unsigned char compress_subclass(int subclass)
01502 {
01503    int x;
01504    int power=-1;
01505    /* If it's 128 or smaller, just return it */
01506    if (subclass < IAX_FLAG_SC_LOG)
01507       return subclass;
01508    /* Otherwise find its power */
01509    for (x = 0; x < IAX_MAX_SHIFT; x++) {
01510       if (subclass & (1 << x)) {
01511          if (power > -1) {
01512             ast_log(LOG_WARNING, "Can't compress subclass %d\n", subclass);
01513             return 0;
01514          } else
01515             power = x;
01516       }
01517    }
01518    return power | IAX_FLAG_SC_LOG;
01519 }
01520 
01521 static int uncompress_subclass(unsigned char csub)
01522 {
01523    /* If the SC_LOG flag is set, return 2^csub otherwise csub */
01524    if (csub & IAX_FLAG_SC_LOG) {
01525       /* special case for 'compressed' -1 */
01526       if (csub == 0xff)
01527          return -1;
01528       else
01529          return 1 << (csub & ~IAX_FLAG_SC_LOG & IAX_MAX_SHIFT);
01530    }
01531    else
01532       return csub;
01533 }
01534 
01535 /*!
01536  * \note The only member of the peer passed here guaranteed to be set is the name field
01537  */
01538 static int peer_hash_cb(const void *obj, const int flags)
01539 {
01540    const struct iax2_peer *peer = obj;
01541 
01542    return ast_str_hash(peer->name);
01543 }
01544 
01545 /*!
01546  * \note The only member of the peer passed here guaranteed to be set is the name field
01547  */
01548 static int peer_cmp_cb(void *obj, void *arg, int flags)
01549 {
01550    struct iax2_peer *peer = obj, *peer2 = arg;
01551 
01552    return !strcmp(peer->name, peer2->name) ? CMP_MATCH | CMP_STOP : 0;
01553 }
01554 
01555 /*!
01556  * \note The only member of the user passed here guaranteed to be set is the name field
01557  */
01558 static int user_hash_cb(const void *obj, const int flags)
01559 {
01560    const struct iax2_user *user = obj;
01561 
01562    return ast_str_hash(user->name);
01563 }
01564 
01565 /*!
01566  * \note The only member of the user passed here guaranteed to be set is the name field
01567  */
01568 static int user_cmp_cb(void *obj, void *arg, int flags)
01569 {
01570    struct iax2_user *user = obj, *user2 = arg;
01571 
01572    return !strcmp(user->name, user2->name) ? CMP_MATCH | CMP_STOP : 0;
01573 }
01574 
01575 /*!
01576  * \note This funtion calls realtime_peer -> reg_source_db -> iax2_poke_peer -> find_callno,
01577  *       so do not call it with a pvt lock held.
01578  */
01579 static struct iax2_peer *find_peer(const char *name, int realtime) 
01580 {
01581    struct iax2_peer *peer = NULL;
01582    struct iax2_peer tmp_peer = {
01583       .name = name,
01584    };
01585 
01586    peer = ao2_find(peers, &tmp_peer, OBJ_POINTER);
01587 
01588    /* Now go for realtime if applicable */
01589    if(!peer && realtime)
01590       peer = realtime_peer(name, NULL);
01591 
01592    return peer;
01593 }
01594 
01595 static struct iax2_peer *peer_ref(struct iax2_peer *peer)
01596 {
01597    ao2_ref(peer, +1);
01598    return peer;
01599 }
01600 
01601 static inline struct iax2_peer *peer_unref(struct iax2_peer *peer)
01602 {
01603    ao2_ref(peer, -1);
01604    return NULL;
01605 }
01606 
01607 static struct iax2_user *find_user(const char *name)
01608 {
01609    struct iax2_user tmp_user = {
01610       .name = name,
01611    };
01612 
01613    return ao2_find(users, &tmp_user, OBJ_POINTER);
01614 }
01615 static inline struct iax2_user *user_ref(struct iax2_user *user)
01616 {
01617    ao2_ref(user, +1);
01618    return user;
01619 }
01620 
01621 static inline struct iax2_user *user_unref(struct iax2_user *user)
01622 {
01623    ao2_ref(user, -1);
01624    return NULL;
01625 }
01626 
01627 static int iax2_getpeername(struct sockaddr_in sin, char *host, int len)
01628 {
01629    struct iax2_peer *peer = NULL;
01630    int res = 0;
01631    struct ao2_iterator i;
01632 
01633    i = ao2_iterator_init(peers, 0);
01634    while ((peer = ao2_iterator_next(&i))) {
01635       if ((peer->addr.sin_addr.s_addr == sin.sin_addr.s_addr) &&
01636           (peer->addr.sin_port == sin.sin_port)) {
01637          ast_copy_string(host, peer->name, len);
01638          peer_unref(peer);
01639          res = 1;
01640          break;
01641       }
01642       peer_unref(peer);
01643    }
01644    ao2_iterator_destroy(&i);
01645 
01646    if (!peer) {
01647       peer = realtime_peer(NULL, &sin);
01648       if (peer) {
01649          ast_copy_string(host, peer->name, len);
01650          peer_unref(peer);
01651          res = 1;
01652       }
01653    }
01654 
01655    return res;
01656 }
01657 
01658 /*!\note Assumes the lock on the pvt is already held, when
01659  * iax2_destroy_helper() is called. */
01660 static void iax2_destroy_helper(struct chan_iax2_pvt *pvt)
01661 {
01662    /* Decrement AUTHREQ count if needed */
01663    if (ast_test_flag(pvt, IAX_MAXAUTHREQ)) {
01664       struct iax2_user *user;
01665       struct iax2_user tmp_user = {
01666          .name = pvt->username,
01667       };
01668 
01669       user = ao2_find(users, &tmp_user, OBJ_POINTER);
01670       if (user) {
01671          ast_atomic_fetchadd_int(&user->curauthreq, -1);
01672          user_unref(user); 
01673       }
01674 
01675       ast_clear_flag(pvt, IAX_MAXAUTHREQ);
01676    }
01677    /* No more pings or lagrq's */
01678    AST_SCHED_DEL_SPINLOCK(ast_sched_thread_get_context(sched), pvt->pingid, &iaxsl[pvt->callno]);
01679    AST_SCHED_DEL_SPINLOCK(ast_sched_thread_get_context(sched), pvt->lagid, &iaxsl[pvt->callno]);
01680    ast_sched_thread_del(sched, pvt->autoid);
01681    ast_sched_thread_del(sched, pvt->authid);
01682    ast_sched_thread_del(sched, pvt->initid);
01683    ast_sched_thread_del(sched, pvt->jbid);
01684    ast_sched_thread_del(sched, pvt->keyrotateid);
01685 }
01686 
01687 static void iax2_frame_free(struct iax_frame *fr)
01688 {
01689    ast_sched_thread_del(sched, fr->retrans);
01690    iax_frame_free(fr);
01691 }
01692 
01693 static int scheduled_destroy(const void *vid)
01694 {
01695    unsigned short callno = PTR_TO_CALLNO(vid);
01696    ast_mutex_lock(&iaxsl[callno]);
01697    if (iaxs[callno]) {
01698       if (option_debug) {
01699          ast_log(LOG_DEBUG, "Really destroying %d now...\n", callno);
01700       }
01701       iax2_destroy(callno);
01702    }
01703    ast_mutex_unlock(&iaxsl[callno]);
01704    return 0;
01705 }
01706 
01707 static void free_signaling_queue_entry(struct signaling_queue_entry *s)
01708 {
01709    ast_free(s->f.data.ptr);
01710    ast_free(s);
01711 }
01712 
01713 /*! \brief This function must be called once we are sure the other side has
01714  *  given us a call number.  All signaling is held here until that point. */
01715 static void send_signaling(struct chan_iax2_pvt *pvt)
01716 {
01717    struct signaling_queue_entry *s = NULL;
01718 
01719    while ((s = AST_LIST_REMOVE_HEAD(&pvt->signaling_queue, next))) {
01720       iax2_send(pvt, &s->f, 0, -1, 0, 0, 0);
01721       free_signaling_queue_entry(s);
01722    }
01723    pvt->hold_signaling = 0;
01724 }
01725 
01726 /*! \brief All frames other than that of type AST_FRAME_IAX must be held until
01727  *  we have received a destination call number. */
01728 static int queue_signalling(struct chan_iax2_pvt *pvt, struct ast_frame *f)
01729 {
01730    struct signaling_queue_entry *new;
01731 
01732    if (f->frametype == AST_FRAME_IAX || !pvt->hold_signaling) {
01733       return 1; /* do not queue this frame */
01734    } else if (!(new = ast_calloc(1, sizeof(struct signaling_queue_entry)))) {
01735       return -1;  /* out of memory */
01736    }
01737 
01738    memcpy(&new->f, f, sizeof(new->f)); /* copy ast_frame into our queue entry */
01739 
01740    if (new->f.datalen) { /* if there is data in this frame copy it over as well */
01741       if (!(new->f.data.ptr = ast_calloc(1, new->f.datalen))) {
01742          free_signaling_queue_entry(new);
01743          return -1;
01744       }
01745       memcpy(new->f.data.ptr, f->data.ptr, sizeof(*new->f.data.ptr));
01746    }
01747    AST_LIST_INSERT_TAIL(&pvt->signaling_queue, new, next);
01748 
01749    return 0;
01750 }
01751 
01752 static void pvt_destructor(void *obj)
01753 {
01754    struct chan_iax2_pvt *pvt = obj;
01755    struct iax_frame *cur = NULL;
01756    struct signaling_queue_entry *s = NULL;
01757 
01758    ast_mutex_lock(&iaxsl[pvt->callno]);
01759    iax2_destroy_helper(pvt);
01760    sched_delay_remove(&pvt->addr, pvt->callno_entry);
01761    pvt->callno_entry = NULL;
01762    ast_mutex_unlock(&iaxsl[pvt->callno]);
01763 
01764    /* Already gone */
01765    ast_set_flag(pvt, IAX_ALREADYGONE); 
01766 
01767    AST_LIST_LOCK(&frame_queue);
01768    AST_LIST_TRAVERSE(&frame_queue, cur, list) {
01769       /* Cancel any pending transmissions */
01770       if (cur->callno == pvt->callno) { 
01771          cur->retries = -1;
01772       }
01773    }
01774    AST_LIST_UNLOCK(&frame_queue);
01775 
01776    while ((s = AST_LIST_REMOVE_HEAD(&pvt->signaling_queue, next))) {
01777       free_signaling_queue_entry(s);
01778    }
01779 
01780    if (pvt->reg) {
01781       pvt->reg->callno = 0;
01782    }
01783 
01784    if (!pvt->owner) {
01785       jb_frame frame;
01786       if (pvt->vars) {
01787           ast_variables_destroy(pvt->vars);
01788           pvt->vars = NULL;
01789       }
01790 
01791       while (jb_getall(pvt->jb, &frame) == JB_OK) {
01792          iax2_frame_free(frame.data);
01793       }
01794 
01795       jb_destroy(pvt->jb);
01796       ast_string_field_free_memory(pvt);
01797    }
01798 }
01799 
01800 static struct chan_iax2_pvt *new_iax(struct sockaddr_in *sin, const char *host)
01801 {
01802    struct chan_iax2_pvt *tmp;
01803    jb_conf jbconf;
01804 
01805    if (!(tmp = ao2_alloc(sizeof(*tmp), pvt_destructor))) {
01806       return NULL;
01807    }
01808 
01809    if (ast_string_field_init(tmp, 32)) {
01810       ao2_ref(tmp, -1);
01811       tmp = NULL;
01812       return NULL;
01813    }
01814       
01815    tmp->prefs = prefs;
01816    tmp->pingid = -1;
01817    tmp->lagid = -1;
01818    tmp->autoid = -1;
01819    tmp->authid = -1;
01820    tmp->initid = -1;
01821    tmp->keyrotateid = -1;
01822 
01823    ast_string_field_set(tmp,exten, "s");
01824    ast_string_field_set(tmp,host, host);
01825 
01826    tmp->jb = jb_new();
01827    tmp->jbid = -1;
01828    jbconf.max_jitterbuf = maxjitterbuffer;
01829    jbconf.resync_threshold = resyncthreshold;
01830    jbconf.max_contig_interp = maxjitterinterps;
01831    jbconf.target_extra = jittertargetextra;
01832    jb_setconf(tmp->jb,&jbconf);
01833 
01834    AST_LIST_HEAD_INIT_NOLOCK(&tmp->dpentries);
01835 
01836    tmp->hold_signaling = 1;
01837    AST_LIST_HEAD_INIT_NOLOCK(&tmp->signaling_queue);
01838 
01839    return tmp;
01840 }
01841 
01842 static struct iax_frame *iaxfrdup2(struct iax_frame *fr)
01843 {
01844    struct iax_frame *new = iax_frame_new(DIRECTION_INGRESS, fr->af.datalen, fr->cacheable);
01845    if (new) {
01846       size_t afdatalen = new->afdatalen;
01847       memcpy(new, fr, sizeof(*new));
01848       iax_frame_wrap(new, &fr->af);
01849       new->afdatalen = afdatalen;
01850       new->data = NULL;
01851       new->datalen = 0;
01852       new->direction = DIRECTION_INGRESS;
01853       new->retrans = -1;
01854    }
01855    return new;
01856 }
01857 /* keep these defined in this order.  They are used in find_callno to
01858  * determine whether or not a new call number should be allowed. */
01859 enum {
01860    /* do not allow a new call number, only search ones in use for match */
01861    NEW_PREVENT = 0,
01862    /* search for match first, then allow a new one to be allocated */
01863    NEW_ALLOW = 1,
01864    /* do not search for match, force a new call number */
01865    NEW_FORCE = 2,
01866    /* do not search for match, force a new call number.  Signifies call number
01867     * has been calltoken validated */
01868    NEW_ALLOW_CALLTOKEN_VALIDATED = 3,
01869 };
01870 
01871 static int match(struct sockaddr_in *sin, unsigned short callno, unsigned short dcallno, const struct chan_iax2_pvt *cur, int check_dcallno)
01872 {
01873    if ((cur->addr.sin_addr.s_addr == sin->sin_addr.s_addr) &&
01874       (cur->addr.sin_port == sin->sin_port)) {
01875       /* This is the main host */
01876       if ( (cur->peercallno == 0 || cur->peercallno == callno) &&
01877           (check_dcallno ? dcallno == cur->callno : 1) ) {
01878          /* That's us.  Be sure we keep track of the peer call number */
01879          return 1;
01880       }
01881    }
01882    if ((cur->transfer.sin_addr.s_addr == sin->sin_addr.s_addr) &&
01883        (cur->transfer.sin_port == sin->sin_port) && (cur->transferring)) {
01884       /* We're transferring */
01885       if ((dcallno == cur->callno) || (cur->transferring == TRANSFER_MEDIAPASS && cur->transfercallno == callno))
01886          return 1;
01887    }
01888    return 0;
01889 }
01890 
01891 static void update_max_trunk(void)
01892 {
01893    int max = TRUNK_CALL_START;
01894    int x;
01895 
01896    /* XXX Prolly don't need locks here XXX */
01897    for (x = TRUNK_CALL_START; x < ARRAY_LEN(iaxs) - 1; x++) {
01898       if (iaxs[x]) {
01899          max = x + 1;
01900       }
01901    }
01902 
01903    maxtrunkcall = max;
01904    if (iaxdebug)
01905       ast_debug(1, "New max trunk callno is %d\n", max);
01906 }
01907 
01908 static void update_max_nontrunk(void)
01909 {
01910    int max = 1;
01911    int x;
01912    /* XXX Prolly don't need locks here XXX */
01913    for (x=1;x<TRUNK_CALL_START - 1; x++) {
01914       if (iaxs[x])
01915          max = x + 1;
01916    }
01917    maxnontrunkcall = max;
01918    if (iaxdebug)
01919       ast_debug(1, "New max nontrunk callno is %d\n", max);
01920 }
01921 
01922 static int make_trunk(unsigned short callno, int locked)
01923 {
01924    int x;
01925    int res= 0;
01926    struct callno_entry *callno_entry;
01927    if (iaxs[callno]->oseqno) {
01928       ast_log(LOG_WARNING, "Can't make trunk once a call has started!\n");
01929       return -1;
01930    }
01931    if (callno & TRUNK_CALL_START) {
01932       ast_log(LOG_WARNING, "Call %d is already a trunk\n", callno);
01933       return -1;
01934    }
01935 
01936    if (!(callno_entry = get_unused_callno(1, iaxs[callno]->callno_entry->validated))) {
01937       ast_log(LOG_WARNING, "Unable to trunk call: Insufficient space\n");
01938       return -1;
01939    }
01940 
01941    x = callno_entry->callno;
01942    ast_mutex_lock(&iaxsl[x]);
01943 
01944    /*!
01945     * \note We delete these before switching the slot, because if
01946     * they fire in the meantime, they will generate a warning.
01947     */
01948    ast_sched_thread_del(sched, iaxs[callno]->pingid);
01949    ast_sched_thread_del(sched, iaxs[callno]->lagid);
01950    iaxs[x] = iaxs[callno];
01951    iaxs[x]->callno = x;
01952 
01953    /* since we copied over the pvt from a different callno, make sure the old entry is replaced
01954     * before assigning the new one */
01955    if (iaxs[x]->callno_entry) {
01956       iax2_sched_add(sched, MIN_REUSE_TIME * 1000, replace_callno, iaxs[x]->callno_entry);
01957    }
01958    iaxs[x]->callno_entry = callno_entry;
01959 
01960    iaxs[callno] = NULL;
01961    /* Update the two timers that should have been started */
01962    iaxs[x]->pingid = iax2_sched_add(sched, 
01963       ping_time * 1000, send_ping, (void *)(long)x);
01964    iaxs[x]->lagid = iax2_sched_add(sched, 
01965       lagrq_time * 1000, send_lagrq, (void *)(long)x);
01966 
01967    if (locked)
01968       ast_mutex_unlock(&iaxsl[callno]);
01969    res = x;
01970    if (!locked)
01971       ast_mutex_unlock(&iaxsl[x]);
01972 
01973    ast_debug(1, "Made call %d into trunk call %d\n", callno, x);
01974    /* We move this call from a non-trunked to a trunked call */
01975    update_max_trunk();
01976    update_max_nontrunk();
01977    return res;
01978 }
01979 
01980 static void store_by_transfercallno(struct chan_iax2_pvt *pvt)
01981 {
01982    if (!pvt->transfercallno) {
01983       ast_log(LOG_ERROR, "This should not be called without a transfer call number.\n");
01984       return;
01985    }
01986 
01987    ao2_link(iax_transfercallno_pvts, pvt);
01988 }
01989 
01990 static void remove_by_transfercallno(struct chan_iax2_pvt *pvt)
01991 {
01992    if (!pvt->transfercallno) {
01993       ast_log(LOG_ERROR, "This should not be called without a transfer call number.\n");
01994       return;
01995    }
01996 
01997    ao2_unlink(iax_transfercallno_pvts, pvt);
01998 }
01999 static void store_by_peercallno(struct chan_iax2_pvt *pvt)
02000 {
02001    if (!pvt->peercallno) {
02002       ast_log(LOG_ERROR, "This should not be called without a peer call number.\n");
02003       return;
02004    }
02005 
02006    ao2_link(iax_peercallno_pvts, pvt);
02007 }
02008 
02009 static void remove_by_peercallno(struct chan_iax2_pvt *pvt)
02010 {
02011    if (!pvt->peercallno) {
02012       ast_log(LOG_ERROR, "This should not be called without a peer call number.\n");
02013       return;
02014    }
02015 
02016    ao2_unlink(iax_peercallno_pvts, pvt);
02017 }
02018 
02019 static int addr_range_delme_cb(void *obj, void *arg, int flags)
02020 {
02021    struct addr_range *lim = obj;
02022    lim->delme = 1;
02023    return 0;
02024 }
02025 
02026 static int addr_range_hash_cb(const void *obj, const int flags)
02027 {
02028    const struct addr_range *lim = obj;
02029    return abs((int) lim->ha.netaddr.s_addr);
02030 }
02031 
02032 static int addr_range_cmp_cb(void *obj, void *arg, int flags)
02033 {
02034    struct addr_range *lim1 = obj, *lim2 = arg;
02035    return ((lim1->ha.netaddr.s_addr == lim2->ha.netaddr.s_addr) &&
02036       (lim1->ha.netmask.s_addr == lim2->ha.netmask.s_addr)) ?
02037       CMP_MATCH | CMP_STOP : 0;
02038 }
02039 
02040 static int peercnt_hash_cb(const void *obj, const int flags)
02041 {
02042    const struct peercnt *peercnt = obj;
02043    return abs((int) peercnt->addr);
02044 }
02045 
02046 static int peercnt_cmp_cb(void *obj, void *arg, int flags)
02047 {
02048    struct peercnt *peercnt1 = obj, *peercnt2 = arg;
02049    return (peercnt1->addr == peercnt2->addr) ? CMP_MATCH | CMP_STOP : 0;
02050 }
02051 
02052 static int addr_range_match_address_cb(void *obj, void *arg, int flags)
02053 {
02054    struct addr_range *addr_range = obj;
02055    struct sockaddr_in *sin = arg;
02056 
02057    if ((sin->sin_addr.s_addr & addr_range->ha.netmask.s_addr) == addr_range->ha.netaddr.s_addr) {
02058       return CMP_MATCH | CMP_STOP;
02059    }
02060    return 0;
02061 }
02062 
02063 /*! 
02064  * \internal
02065  *
02066  * \brief compares sin to calltoken_ignores table to determine if validation is required.
02067  */
02068 static int calltoken_required(struct sockaddr_in *sin, const char *name, int subclass)
02069 {
02070    struct addr_range *addr_range;
02071    struct iax2_peer *peer = NULL;
02072    struct iax2_user *user = NULL;
02073    /* if no username is given, check for guest accounts */
02074    const char *find = S_OR(name, "guest");
02075    int res = 1;  /* required by default */
02076    int optional = 0;
02077    enum calltoken_peer_enum calltoken_required = CALLTOKEN_DEFAULT;
02078    /* There are only two cases in which calltoken validation is not required.
02079     * Case 1. sin falls within the list of address ranges specified in the calltoken optional table and
02080     *         the peer definition has not set the requirecalltoken option.
02081     * Case 2. Username is a valid peer/user, and that peer has requirecalltoken set either auto or no.
02082     */
02083 
02084    /* ----- Case 1 ----- */
02085    if ((addr_range = ao2_callback(calltoken_ignores, 0, addr_range_match_address_cb, sin))) {
02086       ao2_ref(addr_range, -1);
02087       optional = 1;
02088    }
02089 
02090    /* ----- Case 2 ----- */
02091    if ((subclass == IAX_COMMAND_NEW) && (user = find_user(find))) {
02092       calltoken_required = user->calltoken_required;
02093    } else if ((subclass == IAX_COMMAND_NEW) && (user = realtime_user(find, sin))) {
02094       calltoken_required = user->calltoken_required;
02095    } else if ((subclass != IAX_COMMAND_NEW) && (peer = find_peer(find, 0))) {
02096       calltoken_required = peer->calltoken_required;
02097    } else if ((subclass != IAX_COMMAND_NEW) && (peer = realtime_peer(find, sin))) {
02098       calltoken_required = peer->calltoken_required;
02099    }
02100 
02101    if (peer) {
02102       peer_unref(peer);
02103    }
02104    if (user) {
02105       user_unref(user);
02106    }
02107 
02108    ast_debug(1, "Determining if address %s with username %s requires calltoken validation.  Optional = %d  calltoken_required = %d \n", ast_inet_ntoa(sin->sin_addr), name, optional, calltoken_required);
02109    if (((calltoken_required == CALLTOKEN_NO) || (calltoken_required == CALLTOKEN_AUTO)) ||
02110       (optional && (calltoken_required == CALLTOKEN_DEFAULT))) {
02111       res = 0;
02112    }
02113 
02114    return res;
02115 }
02116 
02117 /*! 
02118  * \internal
02119  *
02120  * \brief set peercnt callno limit.
02121  *
02122  * \details 
02123  * First looks in custom definitions. If not found, global limit
02124  * is used.  Entries marked as reg already have
02125  * a custom limit set by a registration and are not modified.
02126  */
02127 static void set_peercnt_limit(struct peercnt *peercnt)
02128 {
02129    uint16_t limit = global_maxcallno;
02130    struct addr_range *addr_range;
02131    struct sockaddr_in sin = {
02132       .sin_addr.s_addr = peercnt->addr,
02133    };
02134 
02135 
02136    if (peercnt->reg && peercnt->limit) {
02137       return; /* this peercnt has a custom limit set by a registration */
02138    }
02139 
02140    if ((addr_range = ao2_callback(callno_limits, 0, addr_range_match_address_cb, &sin))) {
02141       limit = addr_range->limit;
02142       ast_debug(1, "custom addr_range %d found for %s\n", limit, ast_inet_ntoa(sin.sin_addr));
02143       ao2_ref(addr_range, -1);
02144    }
02145 
02146    peercnt->limit = limit;
02147 }
02148 
02149 /*! 
02150  * \internal
02151  * \brief sets limits for all peercnts in table. done on reload to reflect changes in conf.
02152  */
02153 static int set_peercnt_limit_all_cb(void *obj, void *arg, int flags)
02154 {
02155    struct peercnt *peercnt = obj;
02156 
02157    set_peercnt_limit(peercnt);
02158    ast_debug(1, "Reset limits for peercnts table\n");
02159 
02160    return 0;
02161 }
02162 
02163 /*! 
02164  * \internal
02165  * \brief returns match if delme is set. 
02166  */
02167 static int prune_addr_range_cb(void *obj, void *arg, int flags)
02168 {
02169    struct addr_range *addr_range = obj;
02170 
02171    return addr_range->delme ? CMP_MATCH : 0;
02172 }
02173 
02174 /*! 
02175  * \internal
02176  * \brief modifies peercnt entry in peercnts table. Used to set custom limit or mark a registered ip
02177  */
02178 static void peercnt_modify(unsigned char reg, uint16_t limit, struct sockaddr_in *sin)
02179 {
02180    /* this function turns off and on custom callno limits set by peer registration */
02181    struct peercnt *peercnt;
02182    struct peercnt tmp = {
02183       .addr = sin->sin_addr.s_addr,
02184    };
02185 
02186    if ((peercnt = ao2_find(peercnts, &tmp, OBJ_POINTER))) {
02187       peercnt->reg = reg;
02188       if (limit) {
02189          peercnt->limit = limit;
02190       } else {
02191          set_peercnt_limit(peercnt);
02192       }
02193       ast_debug(1, "peercnt entry %s modified limit:%d registered:%d", ast_inet_ntoa(sin->sin_addr), peercnt->limit, peercnt->reg);
02194       ao2_ref(peercnt, -1); /* decrement ref from find */
02195    }
02196 }
02197 
02198 /*! 
02199  * \internal
02200  * \brief adds an ip to the peercnts table, increments connection count if it already exists
02201  *
02202  * \details First searches for the address in the peercnts table.  If found
02203  * the current count is incremented.  If not found a new peercnt is allocated
02204  * and linked into the peercnts table with a call number count of 1.
02205  */
02206 static int peercnt_add(struct sockaddr_in *sin)
02207 {
02208    struct peercnt *peercnt;
02209    unsigned long addr = sin->sin_addr.s_addr;
02210    int res = 0;
02211    struct peercnt tmp = {
02212       .addr = addr,
02213    };
02214 
02215    /* Reasoning for peercnts container lock:  Two identical ip addresses
02216     * could be added by different threads at the "same time". Without the container
02217     * lock, both threads could alloc space for the same object and attempt
02218     * to link to table.  With the lock, one would create the object and link
02219     * to table while the other would find the already created peercnt object
02220     * rather than creating a new one. */
02221    ao2_lock(peercnts);
02222    if ((peercnt = ao2_find(peercnts, &tmp, OBJ_POINTER))) {
02223       ao2_lock(peercnt);
02224    } else if ((peercnt = ao2_alloc(sizeof(*peercnt), NULL))) {
02225       ao2_lock(peercnt);
02226       /* create and set defaults */
02227       peercnt->addr = addr;
02228       set_peercnt_limit(peercnt);
02229       /* guarantees it does not go away after unlocking table
02230        * ao2_find automatically adds this */
02231       ao2_link(peercnts, peercnt);
02232    } else {
02233       ao2_unlock(peercnts);
02234       return -1;
02235    }
02236 
02237    /* check to see if the address has hit its callno limit.  If not increment cur. */
02238    if (peercnt->limit > peercnt->cur) {
02239       peercnt->cur++;
02240       ast_debug(1, "ip callno count incremented to %d for %s\n", peercnt->cur, ast_inet_ntoa(sin->sin_addr));
02241    } else { /* max num call numbers for this peer has been reached! */
02242       ast_log(LOG_ERROR, "maxcallnumber limit of %d for %s has been reached!\n", peercnt->limit, ast_inet_ntoa(sin->sin_addr));
02243       res = -1;
02244    }
02245 
02246    /* clean up locks and ref count */
02247    ao2_unlock(peercnt);
02248    ao2_unlock(peercnts);
02249    ao2_ref(peercnt, -1); /* decrement ref from find/alloc, only the container ref remains. */
02250 
02251    return res;
02252 }
02253 
02254 /*! 
02255  * \internal
02256  * \brief decrements a peercnts table entry
02257  */
02258 static void peercnt_remove(struct peercnt *peercnt)
02259 {
02260    struct sockaddr_in sin = {
02261       .sin_addr.s_addr = peercnt->addr,
02262    };
02263 
02264    if (peercnt) {
02265       /* Container locked here since peercnt may be unlinked from list.  If left unlocked,
02266        * peercnt_add could try and grab this entry from the table and modify it at the
02267        * "same time" this thread attemps to unlink it.*/
02268       ao2_lock(peercnts);
02269       peercnt->cur--;
02270       ast_debug(1, "ip callno count decremented to %d for %s\n", peercnt->cur, ast_inet_ntoa(sin.sin_addr));
02271       /* if this was the last connection from the peer remove it from table */
02272       if (peercnt->cur == 0) {
02273          ao2_unlink(peercnts, peercnt);/* decrements ref from table, last ref is left to scheduler */
02274       }
02275       ao2_unlock(peercnts);
02276    }
02277 }
02278 
02279 /*! 
02280  * \internal
02281  * \brief called by scheduler to decrement object
02282  */
02283 static int peercnt_remove_cb(const void *obj)
02284 {
02285    struct peercnt *peercnt = (struct peercnt *) obj;
02286 
02287    peercnt_remove(peercnt);
02288    ao2_ref(peercnt, -1); /* decrement ref from scheduler */
02289 
02290    return 0;
02291 }
02292 
02293 /*! 
02294  * \internal
02295  * \brief decrements peercnts connection count, finds by addr
02296  */
02297 static int peercnt_remove_by_addr(struct sockaddr_in *sin)
02298 {
02299    struct peercnt *peercnt;
02300    struct peercnt tmp = {
02301       .addr = sin->sin_addr.s_addr,
02302    };
02303 
02304    if ((peercnt = ao2_find(peercnts, &tmp, OBJ_POINTER))) {
02305       peercnt_remove(peercnt);
02306       ao2_ref(peercnt, -1); /* decrement ref from find */
02307    }
02308    return 0;
02309 }
02310 
02311 /*! 
02312  * \internal
02313  * \brief Create callno_limit entry based on configuration
02314  */
02315 static void build_callno_limits(struct ast_variable *v)
02316 {
02317    struct addr_range *addr_range = NULL;
02318    struct addr_range tmp;
02319    struct ast_ha *ha;
02320    int limit;
02321    int error;
02322    int found;
02323 
02324    for (; v; v = v->next) {
02325       limit = -1;
02326       error = 0;
02327       found = 0;
02328       ha = ast_append_ha("permit", v->name, NULL, &error);
02329 
02330       /* check for valid config information */
02331       if (error) {
02332          ast_log(LOG_ERROR, "Call number limit for %s could not be added, Invalid address range\n.", v->name);
02333          continue;
02334       } else if ((sscanf(v->value, "%d", &limit) != 1) || (limit < 0)) {
02335          ast_log(LOG_ERROR, "Call number limit for %s could not be added. Invalid limit %s\n.", v->name, v->value);
02336          ast_free_ha(ha);
02337          continue;
02338       }
02339 
02340       ast_copy_ha(ha, &tmp.ha);
02341       /* find or create the addr_range */
02342       if ((addr_range = ao2_find(callno_limits, &tmp, OBJ_POINTER))) {
02343          ao2_lock(addr_range);
02344          found = 1;
02345       } else if (!(addr_range = ao2_alloc(sizeof(*addr_range), NULL))) {
02346          ast_free_ha(ha);
02347          return; /* out of memory */
02348       }
02349 
02350       /* copy over config data into addr_range object */
02351       ast_copy_ha(ha, &addr_range->ha); /* this is safe because only one ha is possible for each limit */
02352       ast_free_ha(ha); /* cleanup the tmp ha */
02353       addr_range->limit = limit;
02354       addr_range->delme = 0;
02355 
02356       /* cleanup */
02357       if (found) {
02358          ao2_unlock(addr_range);
02359       } else {
02360          ao2_link(callno_limits, addr_range);
02361       }
02362       ao2_ref(addr_range, -1); /* decrement ref from ao2_find and ao2_alloc, only container ref remains */
02363    }
02364 }
02365 
02366 /*! 
02367  * \internal
02368  * \brief Create calltoken_ignores entry based on configuration
02369  */
02370 static int add_calltoken_ignore(const char *addr)
02371 {
02372    struct addr_range tmp;
02373    struct addr_range *addr_range = NULL;
02374    struct ast_ha *ha = NULL;
02375    int error = 0;
02376 
02377    if (ast_strlen_zero(addr)) {
02378       ast_log(LOG_WARNING, "invalid calltokenoptional %s\n", addr);
02379       return -1;
02380    }
02381 
02382    ha = ast_append_ha("permit", addr, NULL, &error);
02383 
02384    /* check for valid config information */
02385    if (error) {
02386       ast_log(LOG_WARNING, "Error %d creating calltokenoptional entry %s\n", error, addr);
02387       return -1;
02388    }
02389 
02390    ast_copy_ha(ha, &tmp.ha);
02391    /* find or create the addr_range */
02392    if ((addr_range = ao2_find(calltoken_ignores, &tmp, OBJ_POINTER))) {
02393       ao2_lock(addr_range);
02394       addr_range->delme = 0;
02395       ao2_unlock(addr_range);
02396    } else if ((addr_range = ao2_alloc(sizeof(*addr_range), NULL))) {
02397       /* copy over config data into addr_range object */
02398       ast_copy_ha(ha, &addr_range->ha); /* this is safe because only one ha is possible */
02399       ao2_link(calltoken_ignores, addr_range);
02400    } else {
02401       ast_free_ha(ha);
02402       return -1;
02403    }
02404 
02405    ast_free_ha(ha);
02406    ao2_ref(addr_range, -1); /* decrement ref from ao2_find and ao2_alloc, only container ref remains */
02407 
02408    return 0;
02409 }
02410 
02411 static char *handle_cli_iax2_show_callno_limits(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
02412 {
02413    struct ao2_iterator i;
02414    struct peercnt *peercnt;
02415    struct sockaddr_in sin;
02416    int found = 0;
02417 
02418    switch (cmd) {
02419    case CLI_INIT:
02420       e->command = "iax2 show callnumber usage";
02421       e->usage =
02422          "Usage: iax2 show callnumber usage <ip address (optional)>\n"
02423          "       Shows current ip addresses which are consuming iax2 call numbers\n";
02424       return NULL;
02425    case CLI_GENERATE:
02426       return NULL;
02427    case CLI_HANDLER:
02428       if (a->argc < 4 || a->argc > 5)
02429          return CLI_SHOWUSAGE;
02430 
02431       ast_cli(a->fd, "%-15s %-12s %-12s\n", "Address", "Callno Usage", "Callno Limit");
02432       i = ao2_iterator_init(peercnts, 0);
02433       while ((peercnt = ao2_iterator_next(&i))) {
02434          sin.sin_addr.s_addr = peercnt->addr;
02435          if (a->argc == 5 && (!strcasecmp(a->argv[4], ast_inet_ntoa(sin.sin_addr)))) {
02436                ast_cli(a->fd, "%-15s %-12d %-12d\n", ast_inet_ntoa(sin.sin_addr), peercnt->cur, peercnt->limit);
02437                found = 1;
02438                break;
02439          } else {
02440             ast_cli(a->fd, "%-15s %-12d %-12d\n", ast_inet_ntoa(sin.sin_addr), peercnt->cur, peercnt->limit);
02441          }
02442          ao2_ref(peercnt, -1);
02443       }
02444       ao2_iterator_destroy(&i);
02445 
02446       if (a->argc == 4) {
02447          ast_cli(a->fd, "\nNon-CallToken Validation Limit: %d\nNon-CallToken Validated: %d\n", global_maxcallno_nonval, total_nonval_callno_used);
02448       } else if (a->argc == 5 && !found) {
02449          ast_cli(a->fd, "No callnumber table entries for %s found\n", a->argv[4] );
02450       }
02451 
02452       return CLI_SUCCESS;
02453    default:
02454       return NULL;
02455    }
02456 }
02457 
02458 static struct callno_entry *get_unused_callno(int trunk, int validated)
02459 {
02460    struct callno_entry *callno_entry = NULL;
02461    if ((!ao2_container_count(callno_pool) && !trunk) || (!ao2_container_count(callno_pool_trunk) && trunk)) {
02462       ast_log(LOG_WARNING, "Out of CallNumbers\n");
02463       /* Minor optimization for the extreme case. */
02464       return NULL;
02465    }
02466 
02467    /* the callno_pool container is locked here primarily to ensure thread
02468     * safety of the total_nonval_callno_used check and increment */
02469    ao2_lock(callno_pool);
02470 
02471    /* only a certain number of nonvalidated call numbers should be allocated.
02472     * If there ever is an attack, this separates the calltoken validating
02473     * users from the non calltoken validating users. */
02474    if (!validated && (total_nonval_callno_used >= global_maxcallno_nonval)) {
02475       ast_log(LOG_WARNING, "NON-CallToken callnumber limit is reached. Current:%d Max:%d\n", total_nonval_callno_used, global_maxcallno_nonval);
02476       ao2_unlock(callno_pool);
02477       return NULL;
02478    }
02479 
02480    /* unlink the object from the container, taking over ownership
02481     * of the reference the container had to the object */
02482    callno_entry = ao2_find((trunk ? callno_pool_trunk : callno_pool), NULL, OBJ_POINTER | OBJ_UNLINK | OBJ_CONTINUE);
02483 
02484    if (callno_entry) {
02485       callno_entry->validated = validated;
02486       if (!validated) {
02487          total_nonval_callno_used++;
02488       }
02489    }
02490 
02491    ao2_unlock(callno_pool);
02492    return callno_entry;
02493 }
02494 
02495 static int replace_callno(const void *obj)
02496 {
02497    struct callno_entry *callno_entry = (struct callno_entry *) obj;
02498 
02499    /* the callno_pool container is locked here primarily to ensure thread
02500     * safety of the total_nonval_callno_used check and decrement */
02501    ao2_lock(callno_pool);
02502 
02503    if (!callno_entry->validated && (total_nonval_callno_used != 0)) {
02504       total_nonval_callno_used--;
02505    } else if (!callno_entry->validated && (total_nonval_callno_used == 0)) {
02506       ast_log(LOG_ERROR, "Attempted to decrement total non calltoken validated callnumbers below zero... Callno is:%d \n", callno_entry->callno);
02507    }
02508 
02509    if (callno_entry->callno < TRUNK_CALL_START) {
02510       ao2_link(callno_pool, callno_entry);
02511    } else {
02512       ao2_link(callno_pool_trunk, callno_entry);
02513    }
02514    ao2_ref(callno_entry, -1); /* only container ref remains */
02515 
02516    ao2_unlock(callno_pool);
02517    return 0;
02518 }
02519 
02520 static int callno_hash(const void *obj, const int flags)
02521 {
02522    return abs(ast_random());
02523 }
02524 
02525 static int create_callno_pools(void)
02526 {
02527    uint16_t i;
02528 
02529    if (!(callno_pool = ao2_container_alloc(CALLNO_POOL_BUCKETS, callno_hash, NULL))) {
02530       return -1;
02531    }
02532 
02533    if (!(callno_pool_trunk = ao2_container_alloc(CALLNO_POOL_BUCKETS, callno_hash, NULL))) {
02534       return -1;
02535    }
02536 
02537    /* start at 2, 0 and 1 are reserved */
02538    for (i = 2; i <= IAX_MAX_CALLS; i++) {
02539       struct callno_entry *callno_entry;
02540 
02541       if (!(callno_entry = ao2_alloc(sizeof(*callno_entry), NULL))) {
02542          return -1;
02543       }
02544 
02545       callno_entry->callno = i;
02546 
02547       if (i < TRUNK_CALL_START) {
02548          ao2_link(callno_pool, callno_entry);
02549       } else {
02550          ao2_link(callno_pool_trunk, callno_entry);
02551       }
02552 
02553       ao2_ref(callno_entry, -1);
02554    }
02555 
02556    return 0;
02557 }
02558 
02559 /*!
02560  * \internal
02561  * \brief Schedules delayed removal of iax2_pvt call number data
02562  *
02563  * \note After MIN_REUSE_TIME has passed for a destroyed iax2_pvt, the callno is
02564  * avaliable again, and the address from the previous connection must be decremented
02565  * from the peercnts table.  This function schedules these operations to take place.
02566  */
02567 static void sched_delay_remove(struct sockaddr_in *sin, struct callno_entry *callno_entry)
02568 {
02569    int i;
02570    struct peercnt *peercnt;
02571    struct peercnt tmp = {
02572       .addr = sin->sin_addr.s_addr,
02573    };
02574 
02575    if ((peercnt = ao2_find(peercnts, &tmp, OBJ_POINTER))) {
02576       /* refcount is incremented with ao2_find.  keep that ref for the scheduler */
02577       ast_debug(1, "schedule decrement of callno used for %s in %d seconds\n", ast_inet_ntoa(sin->sin_addr), MIN_REUSE_TIME);
02578       i = iax2_sched_add(sched, MIN_REUSE_TIME * 1000, peercnt_remove_cb, peercnt);
02579       if (i == -1) {
02580          ao2_ref(peercnt, -1);
02581       }
02582    }
02583 
02584    iax2_sched_add(sched, MIN_REUSE_TIME * 1000, replace_callno, callno_entry);
02585 }
02586 
02587 /*! 
02588  * \internal
02589  * \brief returns whether or not a frame is capable of starting a new IAX2 dialog. 
02590  *
02591  * \note For this implementation, inbound pokes should _NOT_ be capable of allocating
02592  * a new callno.
02593  */
02594 static inline int attribute_pure iax2_allow_new(int frametype, int subclass, int inbound)
02595 {
02596    if (frametype != AST_FRAME_IAX) {
02597       return 0;
02598    }
02599    switch (subclass) {
02600    case IAX_COMMAND_NEW:
02601    case IAX_COMMAND_REGREQ:
02602    case IAX_COMMAND_FWDOWNL:
02603    case IAX_COMMAND_REGREL:
02604       return 1;
02605    case IAX_COMMAND_POKE:
02606       if (!inbound) {
02607          return 1;
02608       }
02609       break;
02610    }
02611    return 0;
02612 }
02613 
02614 /*
02615  * \note Calling this function while holding another pvt lock can cause a deadlock.
02616  */
02617 static int __find_callno(unsigned short callno, unsigned short dcallno, struct sockaddr_in *sin, int new, int sockfd, int return_locked, int check_dcallno)
02618 {
02619    int res = 0;
02620    int x;
02621    /* this call is calltoken validated as long as it is either NEW_FORCE
02622     * or NEW_ALLOW_CALLTOKEN_VALIDATED */
02623    int validated = (new > NEW_ALLOW) ? 1 : 0;
02624    char host[80];
02625 
02626    if (new <= NEW_ALLOW) {
02627       if (callno) {
02628          struct chan_iax2_pvt *pvt;
02629          struct chan_iax2_pvt tmp_pvt = {
02630             .callno = dcallno,
02631             .peercallno = callno,
02632             .transfercallno = callno,
02633             /* hack!! */
02634             .frames_received = check_dcallno,
02635          };
02636 
02637          memcpy(&tmp_pvt.addr, sin, sizeof(tmp_pvt.addr));
02638          /* this works for finding normal call numbers not involving transfering */ 
02639          if ((pvt = ao2_find(iax_peercallno_pvts, &tmp_pvt, OBJ_POINTER))) {
02640             if (return_locked) {
02641                ast_mutex_lock(&iaxsl[pvt->callno]);
02642             }
02643             res = pvt->callno;
02644             ao2_ref(pvt, -1);
02645             pvt = NULL;
02646             return res;
02647          }
02648          /* this searches for transfer call numbers that might not get caught otherwise */
02649          memset(&tmp_pvt.addr, 0, sizeof(tmp_pvt.addr));
02650          memcpy(&tmp_pvt.transfer, sin, sizeof(tmp_pvt.transfer));
02651          if ((pvt = ao2_find(iax_transfercallno_pvts, &tmp_pvt, OBJ_POINTER))) {
02652             if (return_locked) {
02653                ast_mutex_lock(&iaxsl[pvt->callno]);
02654             }
02655             res = pvt->callno;
02656             ao2_ref(pvt, -1);
02657             pvt = NULL;
02658             return res;
02659          }
02660       }
02661          /* This will occur on the first response to a message that we initiated,
02662        * such as a PING. */
02663       if (dcallno) {
02664          ast_mutex_lock(&iaxsl[dcallno]);
02665       }
02666       if (callno && dcallno && iaxs[dcallno] && !iaxs[dcallno]->peercallno && match(sin, callno, dcallno, iaxs[dcallno], check_dcallno)) {
02667          iaxs[dcallno]->peercallno = callno;
02668          res = dcallno;
02669          store_by_peercallno(iaxs[dcallno]);
02670          if (!res || !return_locked) {
02671             ast_mutex_unlock(&iaxsl[dcallno]);
02672          }
02673          return res;
02674       }
02675       if (dcallno) {
02676          ast_mutex_unlock(&iaxsl[dcallno]);
02677       }
02678 #ifdef IAX_OLD_FIND
02679       /* If we get here, we SHOULD NOT find a call structure for this
02680          callno; if we do, it means that there is a call structure that
02681          has a peer callno but did NOT get entered into the hash table,
02682          which is bad.
02683 
02684          If we find a call structure using this old, slow method, output a log
02685          message so we'll know about it. After a few months of leaving this in
02686          place, if we don't hear about people seeing these messages, we can
02687          remove this code for good.
02688       */
02689 
02690       for (x = 1; !res && x < maxnontrunkcall; x++) {
02691          ast_mutex_lock(&iaxsl[x]);
02692          if (iaxs[x]) {
02693             /* Look for an exact match */
02694             if (match(sin, callno, dcallno, iaxs[x], check_dcallno)) {
02695                res = x;
02696             }
02697          }
02698          if (!res || !return_locked)
02699             ast_mutex_unlock(&iaxsl[x]);
02700       }
02701       for (x = TRUNK_CALL_START; !res && x < maxtrunkcall; x++) {
02702          ast_mutex_lock(&iaxsl[x]);
02703          if (iaxs[x]) {
02704             /* Look for an exact match */
02705             if (match(sin, callno, dcallno, iaxs[x], check_dcallno)) {
02706                res = x;
02707             }
02708          }
02709          if (!res || !return_locked)
02710             ast_mutex_unlock(&iaxsl[x]);
02711       }
02712 #endif
02713    }
02714    if (!res && (new >= NEW_ALLOW)) {
02715       struct callno_entry *callno_entry;
02716       /* It may seem odd that we look through the peer list for a name for
02717        * this *incoming* call.  Well, it is weird.  However, users don't
02718        * have an IP address/port number that we can match against.  So,
02719        * this is just checking for a peer that has that IP/port and
02720        * assuming that we have a user of the same name.  This isn't always
02721        * correct, but it will be changed if needed after authentication. */
02722       if (!iax2_getpeername(*sin, host, sizeof(host)))
02723          snprintf(host, sizeof(host), "%s:%d", ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
02724 
02725       if (peercnt_add(sin)) {
02726          /* This address has hit its callnumber limit.  When the limit
02727           * is reached, the connection is not added to the peercnts table.*/
02728          return 0;
02729       }
02730 
02731       if (!(callno_entry = get_unused_callno(0, validated))) {
02732          /* since we ran out of space, remove the peercnt
02733           * entry we added earlier */
02734          peercnt_remove_by_addr(sin);
02735          ast_log(LOG_WARNING, "No more space\n");
02736          return 0;
02737       }
02738       x = callno_entry->callno;
02739       ast_mutex_lock(&iaxsl[x]);
02740 
02741       iaxs[x] = new_iax(sin, host);
02742       update_max_nontrunk();
02743       if (iaxs[x]) {
02744          if (iaxdebug)
02745             ast_debug(1, "Creating new call structure %d\n", x);
02746          iaxs[x]->callno_entry = callno_entry;
02747          iaxs[x]->sockfd = sockfd;
02748          iaxs[x]->addr.sin_port = sin->sin_port;
02749          iaxs[x]->addr.sin_family = sin->sin_family;
02750          iaxs[x]->addr.sin_addr.s_addr = sin->sin_addr.s_addr;
02751          iaxs[x]->peercallno = callno;
02752          iaxs[x]->callno = x;
02753          iaxs[x]->pingtime = DEFAULT_RETRY_TIME;
02754          iaxs[x]->expiry = min_reg_expire;
02755          iaxs[x]->pingid = iax2_sched_add(sched, ping_time * 1000, send_ping, (void *)(long)x);
02756          iaxs[x]->lagid = iax2_sched_add(sched, lagrq_time * 1000, send_lagrq, (void *)(long)x);
02757          iaxs[x]->amaflags = amaflags;
02758          ast_copy_flags(iaxs[x], &globalflags, IAX_NOTRANSFER | IAX_TRANSFERMEDIA | IAX_USEJITTERBUF | IAX_FORCEJITTERBUF | IAX_FORCE_ENCRYPT); 
02759          ast_string_field_set(iaxs[x], accountcode, accountcode);
02760          ast_string_field_set(iaxs[x], mohinterpret, mohinterpret);
02761          ast_string_field_set(iaxs[x], mohsuggest, mohsuggest);
02762          ast_string_field_set(iaxs[x], parkinglot, default_parkinglot);
02763 
02764          if (iaxs[x]->peercallno) {
02765             store_by_peercallno(iaxs[x]);
02766          }
02767       } else {
02768          ast_log(LOG_WARNING, "Out of resources\n");
02769          ast_mutex_unlock(&iaxsl[x]);
02770          replace_callno(callno_entry);
02771          return 0;
02772       }
02773       if (!return_locked)
02774          ast_mutex_unlock(&iaxsl[x]);
02775       res = x;
02776    }
02777    return res;
02778 }
02779 
02780 static int find_callno(unsigned short callno, unsigned short dcallno, struct sockaddr_in *sin, int new, int sockfd, int full_frame) {
02781 
02782    return __find_callno(callno, dcallno, sin, new, sockfd, 0, full_frame);
02783 }
02784 
02785 static int find_callno_locked(unsigned short callno, unsigned short dcallno, struct sockaddr_in *sin, int new, int sockfd, int full_frame) {
02786 
02787    return __find_callno(callno, dcallno, sin, new, sockfd, 1, full_frame);
02788 }
02789 
02790 /*!
02791  * \brief Queue a frame to a call's owning asterisk channel
02792  *
02793  * \pre This function assumes that iaxsl[callno] is locked when called.
02794  *
02795  * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
02796  * was valid before calling it, it may no longer be valid after calling it.
02797  * This function may unlock and lock the mutex associated with this callno,
02798  * meaning that another thread may grab it and destroy the call.
02799  */
02800 static int iax2_queue_frame(int callno, struct ast_frame *f)
02801 {
02802    iax2_lock_owner(callno);
02803    if (iaxs[callno] && iaxs[callno]->owner) {
02804       ast_queue_frame(iaxs[callno]->owner, f);
02805       ast_channel_unlock(iaxs[callno]->owner);
02806    }
02807    return 0;
02808 }
02809 
02810 /*!
02811  * \brief Queue a hangup frame on the ast_channel owner
02812  *
02813  * This function queues a hangup frame on the owner of the IAX2 pvt struct that
02814  * is active for the given call number.
02815  *
02816  * \pre Assumes lock for callno is already held.
02817  *
02818  * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
02819  * was valid before calling it, it may no longer be valid after calling it.
02820  * This function may unlock and lock the mutex associated with this callno,
02821  * meaning that another thread may grab it and destroy the call.
02822  */
02823 static int iax2_queue_hangup(int callno)
02824 {
02825    iax2_lock_owner(callno);
02826    if (iaxs[callno] && iaxs[callno]->owner) {
02827       ast_queue_hangup(iaxs[callno]->owner);
02828       ast_channel_unlock(iaxs[callno]->owner);
02829    }
02830    return 0;
02831 }
02832 
02833 /*!
02834  * \brief Queue a control frame on the ast_channel owner
02835  *
02836  * This function queues a control frame on the owner of the IAX2 pvt struct that
02837  * is active for the given call number.
02838  *
02839  * \pre Assumes lock for callno is already held.
02840  *
02841  * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
02842  * was valid before calling it, it may no longer be valid after calling it.
02843  * This function may unlock and lock the mutex associated with this callno,
02844  * meaning that another thread may grab it and destroy the call.
02845  */
02846 static int iax2_queue_control_data(int callno, 
02847    enum ast_control_frame_type control, const void *data, size_t datalen)
02848 {
02849    iax2_lock_owner(callno);
02850    if (iaxs[callno] && iaxs[callno]->owner) {
02851       ast_queue_control_data(iaxs[callno]->owner, control, data, datalen);
02852       ast_channel_unlock(iaxs[callno]->owner);
02853    }
02854    return 0;
02855 }
02856 static void destroy_firmware(struct iax_firmware *cur)
02857 {
02858    /* Close firmware */
02859    if (cur->fwh) {
02860       munmap((void*)cur->fwh, ntohl(cur->fwh->datalen) + sizeof(*(cur->fwh)));
02861    }
02862    close(cur->fd);
02863    ast_free(cur);
02864 }
02865 
02866 static int try_firmware(char *s)
02867 {
02868    struct stat stbuf;
02869    struct iax_firmware *cur = NULL;
02870    int ifd, fd, res, len, chunk;
02871    struct ast_iax2_firmware_header *fwh, fwh2;
02872    struct MD5Context md5;
02873    unsigned char sum[16], buf[1024];
02874    char *s2, *last;
02875 
02876    if (!(s2 = alloca(strlen(s) + 100))) {
02877       ast_log(LOG_WARNING, "Alloca failed!\n");
02878       return -1;
02879    }
02880 
02881    last = strrchr(s, '/');
02882    if (last)
02883       last++;
02884    else
02885       last = s;
02886 
02887    snprintf(s2, strlen(s) + 100, "/var/tmp/%s-%ld", last, (unsigned long)ast_random());
02888 
02889    if ((res = stat(s, &stbuf) < 0)) {
02890       ast_log(LOG_WARNING, "Failed to stat '%s': %s\n", s, strerror(errno));
02891       return -1;
02892    }
02893 
02894    /* Make sure it's not a directory */
02895    if (S_ISDIR(stbuf.st_mode))
02896       return -1;
02897    ifd = open(s, O_RDONLY);
02898    if (ifd < 0) {
02899       ast_log(LOG_WARNING, "Cannot open '%s': %s\n", s, strerror(errno));
02900       return -1;
02901    }
02902    fd = open(s2, O_RDWR | O_CREAT | O_EXCL, AST_FILE_MODE);
02903    if (fd < 0) {
02904       ast_log(LOG_WARNING, "Cannot open '%s' for writing: %s\n", s2, strerror(errno));
02905       close(ifd);
02906       return -1;
02907    }
02908    /* Unlink our newly created file */
02909    unlink(s2);
02910    
02911    /* Now copy the firmware into it */
02912    len = stbuf.st_size;
02913    while(len) {
02914       chunk = len;
02915       if (chunk > sizeof(buf))
02916          chunk = sizeof(buf);
02917       res = read(ifd, buf, chunk);
02918       if (res != chunk) {
02919          ast_log(LOG_WARNING, "Only read %d of %d bytes of data :(: %s\n", res, chunk, strerror(errno));
02920          close(ifd);
02921          close(fd);
02922          return -1;
02923       }
02924       res = write(fd, buf, chunk);
02925       if (res != chunk) {
02926          ast_log(LOG_WARNING, "Only write %d of %d bytes of data :(: %s\n", res, chunk, strerror(errno));
02927          close(ifd);
02928          close(fd);
02929          return -1;
02930       }
02931       len -= chunk;
02932    }
02933    close(ifd);
02934    /* Return to the beginning */
02935    lseek(fd, 0, SEEK_SET);
02936    if ((res = read(fd, &fwh2, sizeof(fwh2))) != sizeof(fwh2)) {
02937       ast_log(LOG_WARNING, "Unable to read firmware header in '%s'\n", s);
02938       close(fd);
02939       return -1;
02940    }
02941    if (ntohl(fwh2.magic) != IAX_FIRMWARE_MAGIC) {
02942       ast_log(LOG_WARNING, "'%s' is not a valid firmware file\n", s);
02943       close(fd);
02944       return -1;
02945    }
02946    if (ntohl(fwh2.datalen) != (stbuf.st_size - sizeof(fwh2))) {
02947       ast_log(LOG_WARNING, "Invalid data length in firmware '%s'\n", s);
02948       close(fd);
02949       return -1;
02950    }
02951    if (fwh2.devname[sizeof(fwh2.devname) - 1] || ast_strlen_zero((char *)fwh2.devname)) {
02952       ast_log(LOG_WARNING, "No or invalid device type specified for '%s'\n", s);
02953       close(fd);
02954       return -1;
02955    }
02956    fwh = (struct ast_iax2_firmware_header*)mmap(NULL, stbuf.st_size, PROT_READ, MAP_PRIVATE, fd, 0); 
02957    if (fwh == (void *) -1) {
02958       ast_log(LOG_WARNING, "mmap failed: %s\n", strerror(errno));
02959       close(fd);
02960       return -1;
02961    }
02962    MD5Init(&md5);
02963    MD5Update(&md5, fwh->data, ntohl(fwh->datalen));
02964    MD5Final(sum, &md5);
02965    if (memcmp(sum, fwh->chksum, sizeof(sum))) {
02966       ast_log(LOG_WARNING, "Firmware file '%s' fails checksum\n", s);
02967       munmap((void*)fwh, stbuf.st_size);
02968       close(fd);
02969       return -1;
02970    }
02971 
02972    AST_LIST_TRAVERSE(&firmwares, cur, list) {
02973       if (!strcmp((char *)cur->fwh->devname, (char *)fwh->devname)) {
02974          /* Found a candidate */
02975          if (cur->dead || (ntohs(cur->fwh->version) < ntohs(fwh->version)))
02976             /* The version we have on loaded is older, load this one instead */
02977             break;
02978          /* This version is no newer than what we have.  Don't worry about it.
02979             We'll consider it a proper load anyhow though */
02980          munmap((void*)fwh, stbuf.st_size);
02981          close(fd);
02982          return 0;
02983       }
02984    }
02985    
02986    if (!cur && ((cur = ast_calloc(1, sizeof(*cur))))) {
02987       cur->fd = -1;
02988       AST_LIST_INSERT_TAIL(&firmwares, cur, list);
02989    }
02990    
02991    if (cur) {
02992       if (cur->fwh)
02993          munmap((void*)cur->fwh, cur->mmaplen);
02994       if (cur->fd > -1)
02995          close(cur->fd);
02996       cur->fwh = fwh;
02997       cur->fd = fd;
02998       cur->mmaplen = stbuf.st_size;
02999       cur->dead = 0;
03000    }
03001    
03002    return 0;
03003 }
03004 
03005 static int iax_check_version(char *dev)
03006 {
03007    int res = 0;
03008    struct iax_firmware *cur = NULL;
03009 
03010    if (ast_strlen_zero(dev))
03011       return 0;
03012 
03013    AST_LIST_LOCK(&firmwares);
03014    AST_LIST_TRAVERSE(&firmwares, cur, list) {
03015       if (!strcmp(dev, (char *)cur->fwh->devname)) {
03016          res = ntohs(cur->fwh->version);
03017          break;
03018       }
03019    }
03020    AST_LIST_UNLOCK(&firmwares);
03021 
03022    return res;
03023 }
03024 
03025 static int iax_firmware_append(struct iax_ie_data *ied, const unsigned char *dev, unsigned int desc)
03026 {
03027    int res = -1;
03028    unsigned int bs = desc & 0xff;
03029    unsigned int start = (desc >> 8) & 0xffffff;
03030    unsigned int bytes;
03031    struct iax_firmware *cur;
03032 
03033    if (ast_strlen_zero((char *)dev) || !bs)
03034       return -1;
03035 
03036    start *= bs;
03037    
03038    AST_LIST_LOCK(&firmwares);
03039    AST_LIST_TRAVERSE(&firmwares, cur, list) {
03040       if (strcmp((char *)dev, (char *)cur->fwh->devname))
03041          continue;
03042       iax_ie_append_int(ied, IAX_IE_FWBLOCKDESC, desc);
03043       if (start < ntohl(cur->fwh->datalen)) {
03044          bytes = ntohl(cur->fwh->datalen) - start;
03045          if (bytes > bs)
03046             bytes = bs;
03047          iax_ie_append_raw(ied, IAX_IE_FWBLOCKDATA, cur->fwh->data + start, bytes);
03048       } else {
03049          bytes = 0;
03050          iax_ie_append(ied, IAX_IE_FWBLOCKDATA);
03051       }
03052       if (bytes == bs)
03053          res = 0;
03054       else
03055          res = 1;
03056       break;
03057    }
03058    AST_LIST_UNLOCK(&firmwares);
03059 
03060    return res;
03061 }
03062 
03063 
03064 static void reload_firmware(int unload)
03065 {
03066    struct iax_firmware *cur = NULL;
03067    DIR *fwd;
03068    struct dirent *de;
03069    char dir[256], fn[256];
03070 
03071    AST_LIST_LOCK(&firmwares);
03072 
03073    /* Mark all as dead */
03074    AST_LIST_TRAVERSE(&firmwares, cur, list)
03075       cur->dead = 1;
03076 
03077    /* Now that we have marked them dead... load new ones */
03078    if (!unload) {
03079       snprintf(dir, sizeof(dir), "%s/firmware/iax", ast_config_AST_DATA_DIR);
03080       fwd = opendir(dir);
03081       if (fwd) {
03082          while((de = readdir(fwd))) {
03083             if (de->d_name[0] != '.') {
03084                snprintf(fn, sizeof(fn), "%s/%s", dir, de->d_name);
03085                if (!try_firmware(fn)) {
03086                   ast_verb(2, "Loaded firmware '%s'\n", de->d_name);
03087                }
03088             }
03089          }
03090          closedir(fwd);
03091       } else 
03092          ast_log(LOG_WARNING, "Error opening firmware directory '%s': %s\n", dir, strerror(errno));
03093    }
03094 
03095    /* Clean up leftovers */
03096    AST_LIST_TRAVERSE_SAFE_BEGIN(&firmwares, cur, list) {
03097       if (!cur->dead)
03098          continue;
03099       AST_LIST_REMOVE_CURRENT(list);
03100       destroy_firmware(cur);
03101    }
03102    AST_LIST_TRAVERSE_SAFE_END;
03103 
03104    AST_LIST_UNLOCK(&firmwares);
03105 }
03106 
03107 /*!
03108  * \note This function assumes that iaxsl[callno] is locked when called.
03109  *
03110  * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
03111  * was valid before calling it, it may no longer be valid after calling it.
03112  * This function calls iax2_queue_frame(), which may unlock and lock the mutex 
03113  * associated with this callno, meaning that another thread may grab it and destroy the call.
03114  */
03115 static int __do_deliver(void *data)
03116 {
03117    /* Just deliver the packet by using queueing.  This is called by
03118      the IAX thread with the iaxsl lock held. */
03119    struct iax_frame *fr = data;
03120    fr->retrans = -1;
03121    ast_clear_flag(&fr->af, AST_FRFLAG_HAS_TIMING_INFO);
03122    if (iaxs[fr->callno] && !ast_test_flag(iaxs[fr->callno], IAX_ALREADYGONE))
03123       iax2_queue_frame(fr->callno, &fr->af);
03124    /* Free our iax frame */
03125    iax2_frame_free(fr);
03126    /* And don't run again */
03127    return 0;
03128 }
03129 
03130 static int handle_error(void)
03131 {
03132    /* XXX Ideally we should figure out why an error occurred and then abort those
03133       rather than continuing to try.  Unfortunately, the published interface does
03134       not seem to work XXX */
03135 #if 0
03136    struct sockaddr_in *sin;
03137    int res;
03138    struct msghdr m;
03139    struct sock_extended_err e;
03140    m.msg_name = NULL;
03141    m.msg_namelen = 0;
03142    m.msg_iov = NULL;
03143    m.msg_control = &e;
03144    m.msg_controllen = sizeof(e);
03145    m.msg_flags = 0;
03146    res = recvmsg(netsocket, &m, MSG_ERRQUEUE);
03147    if (res < 0)
03148       ast_log(LOG_WARNING, "Error detected, but unable to read error: %s\n", strerror(errno));
03149    else {
03150       if (m.msg_controllen) {
03151          sin = (struct sockaddr_in *)SO_EE_OFFENDER(&e);
03152          if (sin) 
03153             ast_log(LOG_WARNING, "Receive error from %s\n", ast_inet_ntoa(sin->sin_addr));
03154          else
03155             ast_log(LOG_WARNING, "No address detected??\n");
03156       } else {
03157          ast_log(LOG_WARNING, "Local error: %s\n", strerror(e.ee_errno));
03158       }
03159    }
03160 #endif
03161    return 0;
03162 }
03163 
03164 static int transmit_trunk(struct iax_frame *f, struct sockaddr_in *sin, int sockfd)
03165 {
03166    int res;
03167    res = sendto(sockfd, f->data, f->datalen, 0,(struct sockaddr *)sin,
03168                sizeof(*sin));
03169    if (res < 0) {
03170       ast_debug(1, "Received error: %s\n", strerror(errno));
03171       handle_error();
03172    } else
03173       res = 0;
03174    return res;
03175 }
03176 
03177 static int send_packet(struct iax_frame *f)
03178 {
03179    int res;
03180    int callno = f->callno;
03181 
03182    /* Don't send if there was an error, but return error instead */
03183    if (!callno || !iaxs[callno] || iaxs[callno]->error)
03184        return -1;
03185    
03186    /* Called with iaxsl held */
03187    if (iaxdebug)
03188       ast_debug(3, "Sending %d on %d/%d to %s:%d\n", f->ts, callno, iaxs[callno]->peercallno, ast_inet_ntoa(iaxs[callno]->addr.sin_addr), ntohs(iaxs[callno]->addr.sin_port));
03189    
03190    if (f->transfer) {
03191       if (iaxdebug)
03192          iax_showframe(f, NULL, 0, &iaxs[callno]->transfer, f->datalen - sizeof(struct ast_iax2_full_hdr));
03193       res = sendto(iaxs[callno]->sockfd, f->data, f->datalen, 0,(struct sockaddr *)&iaxs[callno]->transfer, sizeof(iaxs[callno]->transfer));
03194    } else {
03195       if (iaxdebug)
03196          iax_showframe(f, NULL, 0, &iaxs[callno]->addr, f->datalen - sizeof(struct ast_iax2_full_hdr));
03197       res = sendto(iaxs[callno]->sockfd, f->data, f->datalen, 0,(struct sockaddr *)&iaxs[callno]->addr, sizeof(iaxs[callno]->addr));
03198    }
03199    if (res < 0) {
03200       if (iaxdebug)
03201          ast_debug(1, "Received error: %s\n", strerror(errno));
03202       handle_error();
03203    } else
03204       res = 0;
03205 
03206    return res;
03207 }
03208 
03209 /*!
03210  * \note Since this function calls iax2_queue_hangup(), the pvt struct
03211  *       for the given call number may disappear during its execution.
03212  */
03213 static int iax2_predestroy(int callno)
03214 {
03215    struct ast_channel *c = NULL;
03216    struct chan_iax2_pvt *pvt = iaxs[callno];
03217 
03218    if (!pvt)
03219       return -1;
03220 
03221    if (!ast_test_flag(pvt, IAX_ALREADYGONE)) {
03222       iax2_destroy_helper(pvt);
03223       ast_set_flag(pvt, IAX_ALREADYGONE); 
03224    }
03225 
03226    if ((c = pvt->owner)) {
03227       c->tech_pvt = NULL;
03228       iax2_queue_hangup(callno);
03229       pvt->owner = NULL;
03230       ast_module_unref(ast_module_info->self);
03231    }
03232 
03233    return 0;
03234 }
03235 
03236 static void iax2_destroy(int callno)
03237 {
03238    struct chan_iax2_pvt *pvt = NULL;
03239    struct ast_channel *owner = NULL;
03240 
03241 retry:
03242    if ((pvt = iaxs[callno])) {
03243 #if 0
03244       /* iax2_destroy_helper gets called from this function later on.  When
03245        * called twice, we get the (previously) familiar FRACK! errors in
03246        * devmode, from the scheduler.  An alternative to this approach is to
03247        * reset the scheduler entries to -1 when they're deleted in
03248        * iax2_destroy_helper().  That approach was previously decided to be
03249        * "wrong" because "the memory is going to be deallocated anyway.  Why
03250        * should we be resetting those values?" */
03251       iax2_destroy_helper(pvt);
03252 #endif
03253    }
03254 
03255    owner = pvt ? pvt->owner : NULL;
03256 
03257    if (owner) {
03258       if (ast_channel_trylock(owner)) {
03259          ast_debug(3, "Avoiding IAX destroy deadlock\n");
03260          DEADLOCK_AVOIDANCE(&iaxsl[callno]);
03261          goto retry;
03262       }
03263    }
03264 
03265    if (!owner) {
03266       iaxs[callno] = NULL;
03267    }
03268 
03269    if (pvt) {
03270       if (!owner) {
03271          pvt->owner = NULL;
03272       } else {
03273          /* If there's an owner, prod it to give up */
03274          /* It is ok to use ast_queue_hangup() here instead of iax2_queue_hangup()
03275           * because we already hold the owner channel lock. */
03276          ast_queue_hangup(owner);
03277       }
03278 
03279       if (pvt->peercallno) {
03280          remove_by_peercallno(pvt);
03281       }
03282 
03283       if (pvt->transfercallno) {
03284          remove_by_transfercallno(pvt);
03285       }
03286 
03287       if (!owner) {
03288          ao2_ref(pvt, -1);
03289          pvt = NULL;
03290       }
03291    }
03292 
03293    if (owner) {
03294       ast_channel_unlock(owner);
03295    }
03296 
03297    if (callno & 0x4000) {
03298       update_max_trunk();
03299    }
03300 }
03301 
03302 static int update_packet(struct iax_frame *f)
03303 {
03304    /* Called with iaxsl lock held, and iaxs[callno] non-NULL */
03305    struct ast_iax2_full_hdr *fh = f->data;
03306    struct ast_frame af;
03307 
03308    /* if frame is encrypted. decrypt before updating it. */
03309    if (f->encmethods) {
03310       decode_frame(&f->mydcx, fh, &af, &f->datalen);
03311    }
03312    /* Mark this as a retransmission */
03313    fh->dcallno = ntohs(IAX_FLAG_RETRANS | f->dcallno);
03314    /* Update iseqno */
03315    f->iseqno = iaxs[f->callno]->iseqno;
03316    fh->iseqno = f->iseqno;
03317 
03318    /* Now re-encrypt the frame */
03319    if (f->encmethods) {
03320    /* since this is a retransmit frame, create a new random padding
03321     * before re-encrypting. */
03322       build_rand_pad(f->semirand, sizeof(f->semirand));
03323       encrypt_frame(&f->ecx, fh, f->semirand, &f->datalen);
03324    }
03325    return 0;
03326 }
03327 
03328 static int attempt_transmit(const void *data);
03329 static void __attempt_transmit(const void *data)
03330 {
03331    /* Attempt to transmit the frame to the remote peer...
03332       Called without iaxsl held. */
03333    struct iax_frame *f = (struct iax_frame *)data;
03334    int freeme = 0;
03335    int callno = f->callno;
03336    /* Make sure this call is still active */
03337    if (callno) 
03338       ast_mutex_lock(&iaxsl[callno]);
03339    if (callno && iaxs[callno]) {
03340       if ((f->retries < 0) /* Already ACK'd */ ||
03341           (f->retries >= max_retries) /* Too many attempts */) {
03342             /* Record an error if we've transmitted too many times */
03343             if (f->retries >= max_retries) {
03344                if (f->transfer) {
03345                   /* Transfer timeout */
03346                   send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_TXREJ, 0, NULL, 0, -1);
03347                } else if (f->final) {
03348                   iax2_destroy(callno);
03349                } else {
03350                   if (iaxs[callno]->owner)
03351                      ast_log(LOG_WARNING, "Max retries exceeded to host %s on %s (type = %d, subclass = %d, ts=%d, seqno=%d)\n", ast_inet_ntoa(iaxs[f->callno]->addr.sin_addr),iaxs[f->callno]->owner->name , f->af.frametype, f->af.subclass, f->ts, f->oseqno);
03352                   iaxs[callno]->error = ETIMEDOUT;
03353                   if (iaxs[callno]->owner) {
03354                      struct ast_frame fr = { AST_FRAME_CONTROL, AST_CONTROL_HANGUP, .data.uint32 = AST_CAUSE_DESTINATION_OUT_OF_ORDER };
03355                      /* Hangup the fd */
03356                      iax2_queue_frame(callno, &fr); /* XXX */
03357                      /* Remember, owner could disappear */
03358                      if (iaxs[callno] && iaxs[callno]->owner)
03359                         iaxs[callno]->owner->hangupcause = AST_CAUSE_DESTINATION_OUT_OF_ORDER;
03360                   } else {
03361                      if (iaxs[callno]->reg) {
03362                         memset(&iaxs[callno]->reg->us, 0, sizeof(iaxs[callno]->reg->us));
03363                         iaxs[callno]->reg->regstate = REG_STATE_TIMEOUT;
03364                         iaxs[callno]->reg->refresh = IAX_DEFAULT_REG_EXPIRE;
03365                      }
03366                      iax2_destroy(callno);
03367                   }
03368                }
03369 
03370             }
03371             freeme = 1;
03372       } else {
03373          /* Update it if it needs it */
03374          update_packet(f);
03375          /* Attempt transmission */
03376          send_packet(f);
03377          f->retries++;
03378          /* Try again later after 10 times as long */
03379          f->retrytime *= 10;
03380          if (f->retrytime > MAX_RETRY_TIME)
03381             f->retrytime = MAX_RETRY_TIME;
03382          /* Transfer messages max out at one second */
03383          if (f->transfer && (f->retrytime > 1000))
03384             f->retrytime = 1000;
03385          f->retrans = iax2_sched_add(sched, f->retrytime, attempt_transmit, f);
03386       }
03387    } else {
03388       /* Make sure it gets freed */
03389       f->retries = -1;
03390       freeme = 1;
03391    }
03392    if (callno)
03393       ast_mutex_unlock(&iaxsl[callno]);
03394    /* Do not try again */
03395    if (freeme) {
03396       /* Don't attempt delivery, just remove it from the queue */
03397       AST_LIST_LOCK(&frame_queue);
03398       AST_LIST_REMOVE(&frame_queue, f, list);
03399       AST_LIST_UNLOCK(&frame_queue);
03400       f->retrans = -1; /* this is safe because this is the scheduled function */
03401       /* Free the IAX frame */
03402       iax2_frame_free(f);
03403    }
03404 }
03405 
03406 static int attempt_transmit(const void *data)
03407 {
03408 #ifdef SCHED_MULTITHREADED
03409    if (schedule_action(__attempt_transmit, data))
03410 #endif      
03411       __attempt_transmit(data);
03412    return 0;
03413 }
03414 
03415 static char *handle_cli_iax2_prune_realtime(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
03416 {
03417    struct iax2_peer *peer = NULL;
03418    struct iax2_user *user = NULL;
03419    static char *choices[] = { "all", NULL };
03420    char *cmplt;
03421 
03422    switch (cmd) {
03423    case CLI_INIT:
03424       e->command = "iax2 prune realtime";
03425       e->usage =
03426          "Usage: iax2 prune realtime [<peername>|all]\n"
03427          "       Prunes object(s) from the cache\n";
03428       return NULL;
03429    case CLI_GENERATE:
03430       if (a->pos == 3) {
03431          cmplt = ast_cli_complete(a->word, choices, a->n);
03432          if (!cmplt)
03433             cmplt = complete_iax2_peers(a->line, a->word, a->pos, a->n - sizeof(choices), IAX_RTCACHEFRIENDS);
03434          return cmplt;
03435       }
03436       return NULL;
03437    }
03438    if (a->argc != 4)
03439       return CLI_SHOWUSAGE;
03440    if (!strcmp(a->argv[3], "all")) {
03441       prune_users();
03442       prune_peers();
03443       ast_cli(a->fd, "Cache flushed successfully.\n");
03444       return CLI_SUCCESS;
03445    }
03446    peer = find_peer(a->argv[3], 0);
03447    user = find_user(a->argv[3]);
03448    if (peer || user) {
03449       if (peer) {
03450          if (ast_test_flag(peer, IAX_RTCACHEFRIENDS)) {
03451             ast_set_flag(peer, IAX_RTAUTOCLEAR);
03452             expire_registry(peer_ref(peer));
03453             ast_cli(a->fd, "Peer %s was removed from the cache.\n", a->argv[3]);
03454          } else {
03455             ast_cli(a->fd, "Peer %s is not eligible for this operation.\n", a->argv[3]);
03456          }
03457          peer_unref(peer);
03458       }
03459       if (user) {
03460          if (ast_test_flag(user, IAX_RTCACHEFRIENDS)) {
03461             ast_set_flag(user, IAX_RTAUTOCLEAR);
03462             ast_cli(a->fd, "User %s was removed from the cache.\n", a->argv[3]);
03463          } else {
03464             ast_cli(a->fd, "User %s is not eligible for this operation.\n", a->argv[3]);
03465          }
03466          ao2_unlink(users,user);
03467          user_unref(user);
03468       }
03469    } else {
03470       ast_cli(a->fd, "%s was not found in the cache.\n", a->argv[3]);
03471    }
03472 
03473    return CLI_SUCCESS;
03474 }
03475 
03476 static char *handle_cli_iax2_test_losspct(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
03477 {
03478    switch (cmd) {
03479    case CLI_INIT:
03480       e->command = "iax2 test losspct";
03481       e->usage =
03482          "Usage: iax2 test losspct <percentage>\n"
03483          "       For testing, throws away <percentage> percent of incoming packets\n";
03484       return NULL;
03485    case CLI_GENERATE:
03486       return NULL;
03487    }
03488    if (a->argc != 4)
03489       return CLI_SHOWUSAGE;
03490 
03491    test_losspct = atoi(a->argv[3]);
03492 
03493    return CLI_SUCCESS;
03494 }
03495 
03496 #ifdef IAXTESTS
03497 static char *handle_cli_iax2_test_late(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
03498 {
03499    switch (cmd) {
03500    case CLI_INIT:
03501       e->command = "iax2 test late";
03502       e->usage =
03503          "Usage: iax2 test late <ms>\n"
03504          "       For testing, count the next frame as <ms> ms late\n";
03505       return NULL;
03506    case CLI_GENERATE:
03507       return NULL;
03508    }
03509 
03510    if (a->argc != 4)
03511       return CLI_SHOWUSAGE;
03512 
03513    test_late = atoi(a->argv[3]);
03514 
03515    return CLI_SUCCESS;
03516 }
03517 
03518 static char *handle_cli_iax2_test_resync(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
03519 {
03520    switch (cmd) {
03521    case CLI_INIT:
03522       e->command = "iax2 test resync";
03523       e->usage =
03524          "Usage: iax2 test resync <ms>\n"
03525          "       For testing, adjust all future frames by <ms> ms\n";
03526       return NULL;
03527    case CLI_GENERATE:
03528       return NULL;
03529    }
03530 
03531    if (a->argc != 4)
03532       return CLI_SHOWUSAGE;
03533 
03534    test_resync = atoi(a->argv[3]);
03535 
03536    return CLI_SUCCESS;
03537 }
03538 
03539 static char *handle_cli_iax2_test_jitter(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
03540 {
03541    switch (cmd) {
03542    case CLI_INIT:
03543       e->command = "iax2 test jitter";
03544       e->usage =
03545          "Usage: iax2 test jitter <ms> <pct>\n"
03546          "       For testing, simulate maximum jitter of +/- <ms> on <pct>\n"
03547          "       percentage of packets. If <pct> is not specified, adds\n"
03548          "       jitter to all packets.\n";
03549       return NULL;
03550    case CLI_GENERATE:
03551       return NULL;
03552    }
03553 
03554    if (a->argc < 4 || a->argc > 5)
03555       return CLI_SHOWUSAGE;
03556 
03557    test_jit = atoi(a->argv[3]);
03558    if (a->argc == 5)
03559       test_jitpct = atoi(a->argv[4]);
03560 
03561    return CLI_SUCCESS;
03562 }
03563 #endif /* IAXTESTS */
03564 
03565 /*! \brief  peer_status: Report Peer status in character string */
03566 /*    returns 1 if peer is online, -1 if unmonitored */
03567 static int peer_status(struct iax2_peer *peer, char *status, int statuslen)
03568 {
03569    int res = 0;
03570    if (peer->maxms) {
03571       if (peer->lastms < 0) {
03572          ast_copy_string(status, "UNREACHABLE", statuslen);
03573       } else if (peer->lastms > peer->maxms) {
03574          snprintf(status, statuslen, "LAGGED (%d ms)", peer->lastms);
03575          res = 1;
03576       } else if (peer->lastms) {
03577          snprintf(status, statuslen, "OK (%d ms)", peer->lastms);
03578          res = 1;
03579       } else {
03580          ast_copy_string(status, "UNKNOWN", statuslen);
03581       }
03582    } else { 
03583       ast_copy_string(status, "Unmonitored", statuslen);
03584       res = -1;
03585    }
03586    return res;
03587 }
03588 
03589 /*! \brief Show one peer in detail */
03590 static char *handle_cli_iax2_show_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
03591 {
03592    char status[30];
03593    char cbuf[256];
03594    struct iax2_peer *peer;
03595    char codec_buf[512];
03596    struct ast_str *encmethods = ast_str_alloca(256);
03597    int x = 0, codec = 0, load_realtime = 0;
03598 
03599    switch (cmd) {
03600    case CLI_INIT:
03601       e->command = "iax2 show peer";
03602       e->usage =
03603          "Usage: iax2 show peer <name>\n"
03604          "       Display details on specific IAX peer\n";
03605       return NULL;
03606    case CLI_GENERATE:
03607       if (a->pos == 3)
03608          return complete_iax2_peers(a->line, a->word, a->pos, a->n, 0);
03609       return NULL;
03610    }
03611 
03612    if (a->argc < 4)
03613       return CLI_SHOWUSAGE;
03614 
03615    load_realtime = (a->argc == 5 && !strcmp(a->argv[4], "load")) ? 1 : 0;
03616 
03617    peer = find_peer(a->argv[3], load_realtime);
03618    if (peer) {
03619       encmethods_to_str(peer->encmethods, encmethods);
03620       ast_cli(a->fd, "\n\n");
03621       ast_cli(a->fd, "  * Name       : %s\n", peer->name);
03622       ast_cli(a->fd, "  Secret       : %s\n", ast_strlen_zero(peer->secret) ? "<Not set>" : "<Set>");
03623       ast_cli(a->fd, "  Context      : %s\n", peer->context);
03624       ast_cli(a->fd, "  Parking lot  : %s\n", peer->parkinglot);
03625       ast_cli(a->fd, "  Mailbox      : %s\n", peer->mailbox);
03626       ast_cli(a->fd, "  Dynamic      : %s\n", ast_test_flag(peer, IAX_DYNAMIC) ? "Yes" : "No");
03627       ast_cli(a->fd, "  Callnum limit: %d\n", peer->maxcallno);
03628       ast_cli(a->fd, "  Calltoken req: %s\n", (peer->calltoken_required == CALLTOKEN_YES) ? "Yes" : ((peer->calltoken_required == CALLTOKEN_AUTO) ? "Auto" : "No"));
03629       ast_cli(a->fd, "  Trunk        : %s\n", ast_test_flag(peer, IAX_TRUNK) ? "Yes" : "No");
03630       ast_cli(a->fd, "  Encryption   : %s\n", peer->encmethods ? ast_str_buffer(encmethods) : "No");
03631       ast_cli(a->fd, "  Callerid     : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, "<unspecified>"));
03632       ast_cli(a->fd, "  Expire       : %d\n", peer->expire);
03633       ast_cli(a->fd, "  ACL          : %s\n", (peer->ha ? "Yes" : "No"));
03634       ast_cli(a->fd, "  Addr->IP     : %s Port %d\n",  peer->addr.sin_addr.s_addr ? ast_inet_ntoa(peer->addr.sin_addr) : "(Unspecified)", ntohs(peer->addr.sin_port));
03635       ast_cli(a->fd, "  Defaddr->IP  : %s Port %d\n", ast_inet_ntoa(peer->defaddr.sin_addr), ntohs(peer->defaddr.sin_port));
03636       ast_cli(a->fd, "  Username     : %s\n", peer->username);
03637       ast_cli(a->fd, "  Codecs       : ");
03638       ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, peer->capability);
03639       ast_cli(a->fd, "%s\n", codec_buf);
03640 
03641       ast_cli(a->fd, "  Codec Order  : (");
03642       for(x = 0; x < 32 ; x++) {
03643          codec = ast_codec_pref_index(&peer->prefs,x);
03644          if(!codec)
03645             break;
03646          ast_cli(a->fd, "%s", ast_getformatname(codec));
03647          if(x < 31 && ast_codec_pref_index(&peer->prefs,x+1))
03648             ast_cli(a->fd, "|");
03649       }
03650 
03651       if (!x)
03652          ast_cli(a->fd, "none");
03653       ast_cli(a->fd, ")\n");
03654 
03655       ast_cli(a->fd, "  Status       : ");
03656       peer_status(peer, status, sizeof(status));   
03657       ast_cli(a->fd, "%s\n",status);
03658       ast_cli(a->fd, "  Qualify      : every %dms when OK, every %dms when UNREACHABLE (sample smoothing %s)\n", peer->pokefreqok, peer->pokefreqnotok, peer->smoothing ? "On" : "Off");
03659       ast_cli(a->fd, "\n");
03660       peer_unref(peer);
03661    } else {
03662       ast_cli(a->fd, "Peer %s not found.\n", a->argv[3]);
03663       ast_cli(a->fd, "\n");
03664    }
03665 
03666    return CLI_SUCCESS;
03667 }
03668 
03669 static char *complete_iax2_peers(const char *line, const char *word, int pos, int state, int flags)
03670 {
03671    int which = 0;
03672    struct iax2_peer *peer;
03673    char *res = NULL;
03674    int wordlen = strlen(word);
03675    struct ao2_iterator i;
03676 
03677    i = ao2_iterator_init(peers, 0);
03678    while ((peer = ao2_iterator_next(&i))) {
03679       if (!strncasecmp(peer->name, word, wordlen) && ++which > state
03680          && (!flags || ast_test_flag(peer, flags))) {
03681          res = ast_strdup(peer->name);
03682          peer_unref(peer);
03683          break;
03684       }
03685       peer_unref(peer);
03686    }
03687    ao2_iterator_destroy(&i);
03688 
03689    return res;
03690 }
03691 
03692 static char *handle_cli_iax2_show_stats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
03693 {
03694    struct iax_frame *cur;
03695    int cnt = 0, dead = 0, final = 0;
03696 
03697    switch (cmd) {
03698    case CLI_INIT:
03699       e->command = "iax2 show stats";
03700       e->usage =
03701          "Usage: iax2 show stats\n"
03702          "       Display statistics on IAX channel driver.\n";
03703       return NULL;
03704    case CLI_GENERATE:
03705       return NULL;
03706    }
03707 
03708    if (a->argc != 3)
03709       return CLI_SHOWUSAGE;
03710 
03711    AST_LIST_LOCK(&frame_queue);
03712    AST_LIST_TRAVERSE(&frame_queue, cur, list) {
03713       if (cur->retries < 0)
03714          dead++;
03715       if (cur->final)
03716          final++;
03717       cnt++;
03718    }
03719    AST_LIST_UNLOCK(&frame_queue);
03720 
03721    ast_cli(a->fd, "    IAX Statistics\n");
03722    ast_cli(a->fd, "---------------------\n");
03723    ast_cli(a->fd, "Outstanding frames: %d (%d ingress, %d egress)\n", iax_get_frames(), iax_get_iframes(), iax_get_oframes());
03724    ast_cli(a->fd, "%d timed and %d untimed transmits; MTU %d/%d/%d\n", trunk_timed, trunk_untimed,
03725       trunk_maxmtu, trunk_nmaxmtu, global_max_trunk_mtu);
03726    ast_cli(a->fd, "Packets in transmit queue: %d dead, %d final, %d total\n\n", dead, final, cnt);
03727 
03728    trunk_timed = trunk_untimed = 0;
03729    if (trunk_maxmtu > trunk_nmaxmtu)
03730       trunk_nmaxmtu = trunk_maxmtu;
03731 
03732    return CLI_SUCCESS;
03733 }
03734 
03735 /*! \brief Set trunk MTU from CLI */
03736 static char *handle_cli_iax2_set_mtu(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
03737 {
03738    int mtuv;
03739 
03740    switch (cmd) {
03741    case CLI_INIT:
03742       e->command = "iax2 set mtu";
03743       e->usage =
03744          "Usage: iax2 set mtu <value>\n"
03745          "       Set the system-wide IAX IP mtu to <value> bytes net or\n"
03746          "       zero to disable. Disabling means that the operating system\n"
03747          "       must handle fragmentation of UDP packets when the IAX2 trunk\n"
03748          "       packet exceeds the UDP payload size. This is substantially\n"
03749          "       below the IP mtu. Try 1240 on ethernets. Must be 172 or\n"
03750          "       greater for G.711 samples.\n";
03751       return NULL;
03752    case CLI_GENERATE:
03753       return NULL;
03754    }
03755 
03756    if (a->argc != 4)
03757       return CLI_SHOWUSAGE; 
03758    if (strncasecmp(a->argv[3], "default", strlen(a->argv[3])) == 0)
03759       mtuv = MAX_TRUNK_MTU;
03760    else
03761       mtuv = atoi(a->argv[3]);
03762 
03763    if (mtuv == 0) {
03764       ast_cli(a->fd, "Trunk MTU control disabled (mtu was %d)\n", global_max_trunk_mtu); 
03765       global_max_trunk_mtu = 0; 
03766       return CLI_SUCCESS; 
03767    }
03768    if (mtuv < 172 || mtuv > 4000) {
03769       ast_cli(a->fd, "Trunk MTU must be between 172 and 4000\n"); 
03770       return CLI_SHOWUSAGE; 
03771    }
03772    ast_cli(a->fd, "Trunk MTU changed from %d to %d\n", global_max_trunk_mtu, mtuv); 
03773    global_max_trunk_mtu = mtuv; 
03774    return CLI_SUCCESS;
03775 }
03776 
03777 static char *handle_cli_iax2_show_cache(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
03778 {
03779    struct iax2_dpcache *dp = NULL;
03780    char tmp[1024], *pc = NULL;
03781    int s, x, y;
03782    struct timeval now = ast_tvnow();
03783 
03784    switch (cmd) {
03785    case CLI_INIT:
03786       e->command = "iax2 show cache";
03787       e->usage =
03788          "Usage: iax2 show cache\n"
03789          "       Display currently cached IAX Dialplan results.\n";
03790       return NULL;
03791    case CLI_GENERATE:
03792       return NULL;
03793    }
03794 
03795    AST_LIST_LOCK(&dpcache);
03796 
03797    ast_cli(a->fd, "%-20.20s %-12.12s %-9.9s %-8.8s %s\n", "Peer/Context", "Exten", "Exp.", "Wait.", "Flags");
03798 
03799    AST_LIST_TRAVERSE(&dpcache, dp, cache_list) {
03800       s = dp->expiry.tv_sec - now.tv_sec;
03801       tmp[0] = '\0';
03802       if (dp->flags & CACHE_FLAG_EXISTS)
03803          strncat(tmp, "EXISTS|", sizeof(tmp) - strlen(tmp) - 1);
03804       if (dp->flags & CACHE_FLAG_NONEXISTENT)
03805          strncat(tmp, "NONEXISTENT|", sizeof(tmp) - strlen(tmp) - 1);
03806       if (dp->flags & CACHE_FLAG_CANEXIST)
03807          strncat(tmp, "CANEXIST|", sizeof(tmp) - strlen(tmp) - 1);
03808       if (dp->flags & CACHE_FLAG_PENDING)
03809          strncat(tmp, "PENDING|", sizeof(tmp) - strlen(tmp) - 1);
03810       if (dp->flags & CACHE_FLAG_TIMEOUT)
03811          strncat(tmp, "TIMEOUT|", sizeof(tmp) - strlen(tmp) - 1);
03812       if (dp->flags & CACHE_FLAG_TRANSMITTED)
03813          strncat(tmp, "TRANSMITTED|", sizeof(tmp) - strlen(tmp) - 1);
03814       if (dp->flags & CACHE_FLAG_MATCHMORE)
03815          strncat(tmp, "MATCHMORE|", sizeof(tmp) - strlen(tmp) - 1);
03816       if (dp->flags & CACHE_FLAG_UNKNOWN)
03817          strncat(tmp, "UNKNOWN|", sizeof(tmp) - strlen(tmp) - 1);
03818       /* Trim trailing pipe */
03819       if (!ast_strlen_zero(tmp)) {
03820          tmp[strlen(tmp) - 1] = '\0';
03821       } else {
03822          ast_copy_string(tmp, "(none)", sizeof(tmp));
03823       }
03824       y = 0;
03825       pc = strchr(dp->peercontext, '@');
03826       if (!pc) {
03827          pc = dp->peercontext;
03828       } else {
03829          pc++;
03830       }
03831       for (x = 0; x < ARRAY_LEN(dp->waiters); x++) {
03832          if (dp->waiters[x] > -1)
03833             y++;
03834       }
03835       if (s > 0) {
03836          ast_cli(a->fd, "%-20.20s %-12.12s %-9d %-8d %s\n", pc, dp->exten, s, y, tmp);
03837       } else {
03838          ast_cli(a->fd, "%-20.20s %-12.12s %-9.9s %-8d %s\n", pc, dp->exten, "(expired)", y, tmp);
03839       }
03840    }
03841 
03842    AST_LIST_UNLOCK(&dpcache);
03843 
03844    return CLI_SUCCESS;
03845 }
03846 
03847 static unsigned int calc_rxstamp(struct chan_iax2_pvt *p, unsigned int offset);
03848 
03849 static void unwrap_timestamp(struct iax_frame *fr)
03850 {
03851    /* Video mini frames only encode the lower 15 bits of the session
03852     * timestamp, but other frame types (e.g. audio) encode 16 bits. */
03853    const int ts_shift = (fr->af.frametype == AST_FRAME_VIDEO) ? 15 : 16;
03854    const int lower_mask = (1 << ts_shift) - 1;
03855    const int upper_mask = ~lower_mask;
03856    const int last_upper = iaxs[fr->callno]->last & upper_mask;
03857 
03858    if ( (fr->ts & upper_mask) == last_upper ) {
03859       const int x = fr->ts - iaxs[fr->callno]->last;
03860       const int threshold = (ts_shift == 15) ? 25000 : 50000;
03861 
03862       if (x < -threshold) {
03863          /* Sudden big jump backwards in timestamp:
03864             What likely happened here is that miniframe timestamp has circled but we haven't
03865             gotten the update from the main packet.  We'll just pretend that we did, and
03866             update the timestamp appropriately. */
03867          fr->ts = (last_upper + (1 << ts_shift)) | (fr->ts & lower_mask);
03868          if (iaxdebug)
03869             ast_debug(1, "schedule_delivery: pushed forward timestamp\n");
03870       } else if (x > threshold) {
03871          /* Sudden apparent big jump forwards in timestamp:
03872             What's likely happened is this is an old miniframe belonging to the previous
03873             top 15 or 16-bit timestamp that has turned up out of order.
03874             Adjust the timestamp appropriately. */
03875          fr->ts = (last_upper - (1 << ts_shift)) | (fr->ts & lower_mask);
03876          if (iaxdebug)
03877             ast_debug(1, "schedule_delivery: pushed back timestamp\n");
03878       }
03879    }
03880 }
03881 
03882 static int get_from_jb(const void *p);
03883 
03884 static void update_jbsched(struct chan_iax2_pvt *pvt)
03885 {
03886    int when;
03887    
03888    when = ast_tvdiff_ms(ast_tvnow(), pvt->rxcore);
03889    
03890    when = jb_next(pvt->jb) - when;
03891 
03892    if (when <= 0) {
03893       /* XXX should really just empty until when > 0.. */
03894       when = 1;
03895    }
03896    
03897    pvt->jbid = iax2_sched_replace(pvt->jbid, sched, when, get_from_jb, 
03898       CALLNO_TO_PTR(pvt->callno));
03899 }
03900 
03901 static void __get_from_jb(const void *p) 
03902 {
03903    int callno = PTR_TO_CALLNO(p);
03904    struct chan_iax2_pvt *pvt = NULL;
03905    struct iax_frame *fr;
03906    jb_frame frame;
03907    int ret;
03908    long ms;
03909    long next;
03910    struct timeval now = ast_tvnow();
03911    
03912    /* Make sure we have a valid private structure before going on */
03913    ast_mutex_lock(&iaxsl[callno]);
03914    pvt = iaxs[callno];
03915    if (!pvt) {
03916       /* No go! */
03917       ast_mutex_unlock(&iaxsl[callno]);
03918       return;
03919    }
03920 
03921    pvt->jbid = -1;
03922    
03923    /* round up a millisecond since ast_sched_runq does; */
03924    /* prevents us from spinning while waiting for our now */
03925    /* to catch up with runq's now */
03926    now.tv_usec += 1000;
03927    
03928    ms = ast_tvdiff_ms(now, pvt->rxcore);
03929    
03930    if(ms >= (next = jb_next(pvt->jb))) {
03931       ret = jb_get(pvt->jb,&frame,ms,ast_codec_interp_len(pvt->voiceformat));
03932       switch(ret) {
03933       case JB_OK:
03934          fr = frame.data;
03935          __do_deliver(fr);
03936          /* __do_deliver() can cause the call to disappear */
03937          pvt = iaxs[callno];
03938          break;
03939       case JB_INTERP:
03940       {
03941          struct ast_frame af = { 0, };
03942          
03943          /* create an interpolation frame */
03944          af.frametype = AST_FRAME_VOICE;
03945          af.subclass = pvt->voiceformat;
03946          af.samples  = frame.ms * (ast_format_rate(pvt->voiceformat) / 1000);
03947          af.src  = "IAX2 JB interpolation";
03948          af.delivery = ast_tvadd(pvt->rxcore, ast_samp2tv(next, 1000));
03949          af.offset = AST_FRIENDLY_OFFSET;
03950          
03951          /* queue the frame:  For consistency, we would call __do_deliver here, but __do_deliver wants an iax_frame,
03952           * which we'd need to malloc, and then it would free it.  That seems like a drag */
03953          if (!ast_test_flag(iaxs[callno], IAX_ALREADYGONE)) {
03954             iax2_queue_frame(callno, &af);
03955             /* iax2_queue_frame() could cause the call to disappear */
03956             pvt = iaxs[callno];
03957          }
03958       }
03959          break;
03960       case JB_DROP:
03961          iax2_frame_free(frame.data);
03962          break;
03963       case JB_NOFRAME:
03964       case JB_EMPTY:
03965          /* do nothing */
03966          break;
03967       default:
03968          /* shouldn't happen */
03969          break;
03970       }
03971    }
03972    if (pvt)
03973       update_jbsched(pvt);
03974    ast_mutex_unlock(&iaxsl[callno]);
03975 }
03976 
03977 static int get_from_jb(const void *data)
03978 {
03979 #ifdef SCHED_MULTITHREADED
03980    if (schedule_action(__get_from_jb, data))
03981 #endif      
03982       __get_from_jb(data);
03983    return 0;
03984 }
03985 
03986 /*!
03987  * \note This function assumes fr->callno is locked
03988  *
03989  * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
03990  * was valid before calling it, it may no longer be valid after calling it.
03991  */
03992 static int schedule_delivery(struct iax_frame *fr, int updatehistory, int fromtrunk, unsigned int *tsout)
03993 {
03994    int type, len;
03995    int ret;
03996    int needfree = 0;
03997    struct ast_channel *owner = NULL;
03998    struct ast_channel *bridge = NULL;
03999    
04000    /* Attempt to recover wrapped timestamps */
04001    unwrap_timestamp(fr);
04002 
04003    /* delivery time is sender's sent timestamp converted back into absolute time according to our clock */
04004    if ( !fromtrunk && !ast_tvzero(iaxs[fr->callno]->rxcore))
04005       fr->af.delivery = ast_tvadd(iaxs[fr->callno]->rxcore, ast_samp2tv(fr->ts, 1000));
04006    else {
04007 #if 0
04008       ast_debug(1, "schedule_delivery: set delivery to 0 as we don't have an rxcore yet, or frame is from trunk.\n");
04009 #endif
04010       fr->af.delivery = ast_tv(0,0);
04011    }
04012 
04013    type = JB_TYPE_CONTROL;
04014    len = 0;
04015 
04016    if(fr->af.frametype == AST_FRAME_VOICE) {
04017       type = JB_TYPE_VOICE;
04018       len = ast_codec_get_samples(&fr->af) / (ast_format_rate(fr->af.subclass) / 1000);
04019    } else if(fr->af.frametype == AST_FRAME_CNG) {
04020       type = JB_TYPE_SILENCE;
04021    }
04022 
04023    if ( (!ast_test_flag(iaxs[fr->callno], IAX_USEJITTERBUF)) ) {
04024       if (tsout)
04025          *tsout = fr->ts;
04026       __do_deliver(fr);
04027       return -1;
04028    }
04029 
04030    iax2_lock_owner(fr->callno);
04031    if (!iaxs[fr->callno]) {
04032       /* The call dissappeared so discard this frame that we could not send. */
04033       iax2_frame_free(fr);
04034       return -1;
04035    }
04036    if ((owner = iaxs[fr->callno]->owner))
04037       bridge = ast_bridged_channel(owner);
04038 
04039    /* if the user hasn't requested we force the use of the jitterbuffer, and we're bridged to
04040     * a channel that can accept jitter, then flush and suspend the jb, and send this frame straight through */
04041    if ( (!ast_test_flag(iaxs[fr->callno], IAX_FORCEJITTERBUF)) && owner && bridge && (bridge->tech->properties & AST_CHAN_TP_WANTSJITTER) ) {
04042       jb_frame frame;
04043 
04044       ast_channel_unlock(owner);
04045 
04046       /* deliver any frames in the jb */
04047       while (jb_getall(iaxs[fr->callno]->jb, &frame) == JB_OK) {
04048          __do_deliver(frame.data);
04049          /* __do_deliver() can make the call disappear */
04050          if (!iaxs[fr->callno])
04051             return -1;
04052       }
04053 
04054       jb_reset(iaxs[fr->callno]->jb);
04055 
04056       ast_sched_thread_del(sched, iaxs[fr->callno]->jbid);
04057 
04058       /* deliver this frame now */
04059       if (tsout)
04060          *tsout = fr->ts;
04061       __do_deliver(fr);
04062       return -1;
04063    }
04064    if (owner) {
04065       ast_channel_unlock(owner);
04066    }
04067 
04068    /* insert into jitterbuffer */
04069    /* TODO: Perhaps we could act immediately if it's not droppable and late */
04070    ret = jb_put(iaxs[fr->callno]->jb, fr, type, len, fr->ts,
04071          calc_rxstamp(iaxs[fr->callno],fr->ts));
04072    if (ret == JB_DROP) {
04073       needfree++;
04074    } else if (ret == JB_SCHED) {
04075       update_jbsched(iaxs[fr->callno]);
04076    }
04077    if (tsout)
04078       *tsout = fr->ts;
04079    if (needfree) {
04080       /* Free our iax frame */
04081       iax2_frame_free(fr);
04082       return -1;
04083    }
04084    return 0;
04085 }
04086 
04087 static int iax2_transmit(struct iax_frame *fr)
04088 {
04089    /* Lock the queue and place this packet at the end */
04090    /* By setting this to 0, the network thread will send it for us, and
04091       queue retransmission if necessary */
04092    fr->sentyet = 0;
04093    AST_LIST_LOCK(&frame_queue);
04094    AST_LIST_INSERT_TAIL(&frame_queue, fr, list);
04095    AST_LIST_UNLOCK(&frame_queue);
04096    /* Wake up the network and scheduler thread */
04097    if (netthreadid != AST_PTHREADT_NULL)
04098       pthread_kill(netthreadid, SIGURG);
04099    ast_sched_thread_poke(sched);
04100    return 0;
04101 }
04102 
04103 
04104 
04105 static int iax2_digit_begin(struct ast_channel *c, char digit)
04106 {
04107    return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_DTMF_BEGIN, digit, 0, NULL, 0, -1);
04108 }
04109 
04110 static int iax2_digit_end(struct ast_channel *c, char digit, unsigned int duration)
04111 {
04112    return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_DTMF_END, digit, 0, NULL, 0, -1);
04113 }
04114 
04115 static int iax2_sendtext(struct ast_channel *c, const char *text)
04116 {
04117    
04118    return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_TEXT,
04119       0, 0, (unsigned char *)text, strlen(text) + 1, -1);
04120 }
04121 
04122 static int iax2_sendimage(struct ast_channel *c, struct ast_frame *img)
04123 {
04124    return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_IMAGE, img->subclass, 0, img->data.ptr, img->datalen, -1);
04125 }
04126 
04127 static int iax2_sendhtml(struct ast_channel *c, int subclass, const char *data, int datalen)
04128 {
04129    return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_HTML, subclass, 0, (unsigned char *)data, datalen, -1);
04130 }
04131 
04132 static int iax2_fixup(struct ast_channel *oldchannel, struct ast_channel *newchan)
04133 {
04134    unsigned short callno = PTR_TO_CALLNO(newchan->tech_pvt);
04135    ast_mutex_lock(&iaxsl[callno]);
04136    if (iaxs[callno])
04137       iaxs[callno]->owner = newchan;
04138    else
04139       ast_log(LOG_WARNING, "Uh, this isn't a good sign...\n");
04140    ast_mutex_unlock(&iaxsl[callno]);
04141    return 0;
04142 }
04143 
04144 /*!
04145  * \note This function calls reg_source_db -> iax2_poke_peer -> find_callno,
04146  *       so do not call this with a pvt lock held.
04147  */
04148 static struct iax2_peer *realtime_peer(const char *peername, struct sockaddr_in *sin)
04149 {
04150    struct ast_variable *var = NULL;
04151    struct ast_variable *tmp;
04152    struct iax2_peer *peer=NULL;
04153    time_t regseconds = 0, nowtime;
04154    int dynamic=0;
04155 
04156    if (peername) {
04157       var = ast_load_realtime("iaxpeers", "name", peername, "host", "dynamic", SENTINEL);
04158       if (!var && sin)
04159          var = ast_load_realtime("iaxpeers", "name", peername, "host", ast_inet_ntoa(sin->sin_addr), SENTINEL);
04160    } else if (sin) {
04161       char porta[25];
04162       sprintf(porta, "%d", ntohs(sin->sin_port));
04163       var = ast_load_realtime("iaxpeers", "ipaddr", ast_inet_ntoa(sin->sin_addr), "port", porta, SENTINEL);
04164       if (var) {
04165          /* We'll need the peer name in order to build the structure! */
04166          for (tmp = var; tmp; tmp = tmp->next) {
04167             if (!strcasecmp(tmp->name, "name"))
04168                peername = tmp->value;
04169          }
04170       }
04171    }
04172    if (!var && peername) { /* Last ditch effort */
04173       var = ast_load_realtime("iaxpeers", "name", peername, SENTINEL);
04174       /*!\note
04175        * If this one loaded something, then we need to ensure that the host
04176        * field matched.  The only reason why we can't have this as a criteria
04177        * is because we only have the IP address and the host field might be
04178        * set as a name (and the reverse PTR might not match).
04179        */
04180       if (var && sin) {
04181          for (tmp = var; tmp; tmp = tmp->next) {
04182             if (!strcasecmp(tmp->name, "host")) {
04183                struct ast_hostent ahp;
04184                struct hostent *hp;
04185                if (!(hp = ast_gethostbyname(tmp->value, &ahp)) || (memcmp(hp->h_addr, &sin->sin_addr, sizeof(hp->h_addr)))) {
04186                   /* No match */
04187                   ast_variables_destroy(var);
04188                   var = NULL;
04189                }
04190                break;
04191             }
04192          }
04193       }
04194    }
04195    if (!var)
04196       return NULL;
04197 
04198    peer = build_peer(peername, var, NULL, ast_test_flag((&globalflags), IAX_RTCACHEFRIENDS) ? 0 : 1);
04199    
04200    if (!peer) {
04201       ast_variables_destroy(var);
04202       return NULL;
04203    }
04204 
04205    for (tmp = var; tmp; tmp = tmp->next) {
04206       /* Make sure it's not a user only... */
04207       if (!strcasecmp(tmp->name, "type")) {
04208          if (strcasecmp(tmp->value, "friend") &&
04209              strcasecmp(tmp->value, "peer")) {
04210             /* Whoops, we weren't supposed to exist! */
04211             peer = peer_unref(peer);
04212             break;
04213          } 
04214       } else if (!strcasecmp(tmp->name, "regseconds")) {
04215          ast_get_time_t(tmp->value, &regseconds, 0, NULL);
04216       } else if (!strcasecmp(tmp->name, "ipaddr")) {
04217          inet_aton(tmp->value, &(peer->addr.sin_addr));
04218       } else if (!strcasecmp(tmp->name, "port")) {
04219          peer->addr.sin_port = htons(atoi(tmp->value));
04220       } else if (!strcasecmp(tmp->name, "host")) {
04221          if (!strcasecmp(tmp->value, "dynamic"))
04222             dynamic = 1;
04223       }
04224    }
04225 
04226    ast_variables_destroy(var);
04227 
04228    if (!peer)
04229       return NULL;
04230 
04231    if (ast_test_flag((&globalflags), IAX_RTCACHEFRIENDS)) {
04232       ast_copy_flags(peer, &globalflags, IAX_RTAUTOCLEAR|IAX_RTCACHEFRIENDS);
04233       if (ast_test_flag(peer, IAX_RTAUTOCLEAR)) {
04234          if (peer->expire > -1) {
04235             if (!ast_sched_thread_del(sched, peer->expire)) {
04236                peer->expire = -1;
04237                peer_unref(peer);
04238             }
04239          }
04240          peer->expire = iax2_sched_add(sched, (global_rtautoclear) * 1000, expire_registry, peer_ref(peer));
04241          if (peer->expire == -1)
04242             peer_unref(peer);
04243       }
04244       ao2_link(peers, peer);
04245       if (ast_test_flag(peer, IAX_DYNAMIC))
04246          reg_source_db(peer);
04247    } else {
04248       ast_set_flag(peer, IAX_TEMPONLY);   
04249    }
04250 
04251    if (!ast_test_flag(&globalflags, IAX_RTIGNOREREGEXPIRE) && dynamic) {
04252       time(&nowtime);
04253       if ((nowtime - regseconds) > IAX_DEFAULT_REG_EXPIRE) {
04254          memset(&peer->addr, 0, sizeof(peer->addr));
04255          realtime_update_peer(peer->name, &peer->addr, 0);
04256          ast_debug(1, "realtime_peer: Bah, '%s' is expired (%d/%d/%d)!\n",
04257             peername, (int)(nowtime - regseconds), (int)regseconds, (int)nowtime);
04258       }
04259       else {
04260          ast_debug(1, "realtime_peer: Registration for '%s' still active (%d/%d/%d)!\n",
04261             peername, (int)(nowtime - regseconds), (int)regseconds, (int)nowtime);
04262       }
04263    }
04264 
04265    return peer;
04266 }
04267 
04268 static struct iax2_user *realtime_user(const char *username, struct sockaddr_in *sin)
04269 {
04270    struct ast_variable *var;
04271    struct ast_variable *tmp;
04272    struct iax2_user *user=NULL;
04273 
04274    var = ast_load_realtime("iaxusers", "name", username, "host", "dynamic", SENTINEL);
04275    if (!var)
04276       var = ast_load_realtime("iaxusers", "name", username, "host", ast_inet_ntoa(sin->sin_addr), SENTINEL);
04277    if (!var && sin) {
04278       char porta[6];
04279       snprintf(porta, sizeof(porta), "%d", ntohs(sin->sin_port));
04280       var = ast_load_realtime("iaxusers", "name", username, "ipaddr", ast_inet_ntoa(sin->sin_addr), "port", porta, SENTINEL);
04281       if (!var)
04282          var = ast_load_realtime("iaxusers", "ipaddr", ast_inet_ntoa(sin->sin_addr), "port", porta, SENTINEL);
04283    }
04284    if (!var) { /* Last ditch effort */
04285       var = ast_load_realtime("iaxusers", "name", username, SENTINEL);
04286       /*!\note
04287        * If this one loaded something, then we need to ensure that the host
04288        * field matched.  The only reason why we can't have this as a criteria
04289        * is because we only have the IP address and the host field might be
04290        * set as a name (and the reverse PTR might not match).
04291        */
04292       if (var) {
04293          for (tmp = var; tmp; tmp = tmp->next) {
04294             if (!strcasecmp(tmp->name, "host")) {
04295                struct ast_hostent ahp;
04296                struct hostent *hp;
04297                if (!(hp = ast_gethostbyname(tmp->value, &ahp)) || (memcmp(hp->h_addr, &sin->sin_addr, sizeof(hp->h_addr)))) {
04298                   /* No match */
04299                   ast_variables_destroy(var);
04300                   var = NULL;
04301                }
04302                break;
04303             }
04304          }
04305       }
04306    }
04307    if (!var)
04308       return NULL;
04309 
04310    tmp = var;
04311    while(tmp) {
04312       /* Make sure it's not a peer only... */
04313       if (!strcasecmp(tmp->name, "type")) {
04314          if (strcasecmp(tmp->value, "friend") &&
04315              strcasecmp(tmp->value, "user")) {
04316             return NULL;
04317          } 
04318       }
04319       tmp = tmp->next;
04320    }
04321 
04322    user = build_user(username, var, NULL, !ast_test_flag((&globalflags), IAX_RTCACHEFRIENDS));
04323 
04324    ast_variables_destroy(var);
04325 
04326    if (!user)
04327       return NULL;
04328 
04329    if (ast_test_flag((&globalflags), IAX_RTCACHEFRIENDS)) {
04330       ast_set_flag(user, IAX_RTCACHEFRIENDS);
04331       ao2_link(users, user);
04332    } else {
04333       ast_set_flag(user, IAX_TEMPONLY);   
04334    }
04335 
04336    return user;
04337 }
04338 
04339 static void realtime_update_peer(const char *peername, struct sockaddr_in *sin, time_t regtime)
04340 {
04341    char port[10];
04342    char regseconds[20];
04343    
04344    snprintf(regseconds, sizeof(regseconds), "%d", (int)regtime);
04345    snprintf(port, sizeof(port), "%d", ntohs(sin->sin_port));
04346    ast_update_realtime("iaxpeers", "name", peername, 
04347       "ipaddr", ast_inet_ntoa(sin->sin_addr), "port", port, 
04348       "regseconds", regseconds, SENTINEL);
04349 }
04350 
04351 struct create_addr_info {
04352    int capability;
04353    unsigned int flags;
04354    int maxtime;
04355    int encmethods;
04356    int found;
04357    int sockfd;
04358    int adsi;
04359    char username[80];
04360    char secret[80];
04361    char outkey[80];
04362    char timezone[80];
04363    char prefs[32];
04364    char context[AST_MAX_CONTEXT];
04365    char peercontext[AST_MAX_CONTEXT];
04366    char mohinterpret[MAX_MUSICCLASS];
04367    char mohsuggest[MAX_MUSICCLASS];
04368 };
04369 
04370 static int create_addr(const char *peername, struct ast_channel *c, struct sockaddr_in *sin, struct create_addr_info *cai)
04371 {
04372    struct iax2_peer *peer;
04373    int res = -1;
04374    struct ast_codec_pref ourprefs;
04375 
04376    ast_clear_flag(cai, IAX_SENDANI | IAX_TRUNK);
04377    cai->sockfd = defaultsockfd;
04378    cai->maxtime = 0;
04379    sin->sin_family = AF_INET;
04380 
04381    if (!(peer = find_peer(peername, 1))) {
04382       cai->found = 0;
04383       if (ast_get_ip_or_srv(sin, peername, srvlookup ? "_iax._udp" : NULL)) {
04384          ast_log(LOG_WARNING, "No such host: %s\n", peername);
04385          return -1;
04386       }
04387       sin->sin_port = htons(IAX_DEFAULT_PORTNO);
04388       /* use global iax prefs for unknown peer/user */
04389       /* But move the calling channel's native codec to the top of the preference list */
04390       memcpy(&ourprefs, &prefs, sizeof(ourprefs));
04391       if (c)
04392          ast_codec_pref_prepend(&ourprefs, c->nativeformats, 1);
04393       ast_codec_pref_convert(&ourprefs, cai->prefs, sizeof(cai->prefs), 1);
04394       return 0;
04395    }
04396 
04397    cai->found = 1;
04398    
04399    /* if the peer has no address (current or default), return failure */
04400    if (!(peer->addr.sin_addr.s_addr || peer->defaddr.sin_addr.s_addr))
04401       goto return_unref;
04402 
04403    /* if the peer is being monitored and is currently unreachable, return failure */
04404    if (peer->maxms && ((peer->lastms > peer->maxms) || (peer->lastms < 0)))
04405       goto return_unref;
04406 
04407    ast_copy_flags(cai, peer, IAX_SENDANI | IAX_TRUNK | IAX_NOTRANSFER | IAX_TRANSFERMEDIA | IAX_USEJITTERBUF | IAX_FORCEJITTERBUF | IAX_FORCE_ENCRYPT);
04408    cai->maxtime = peer->maxms;
04409    cai->capability = peer->capability;
04410    cai->encmethods = peer->encmethods;
04411    cai->sockfd = peer->sockfd;
04412    cai->adsi = peer->adsi;
04413    memcpy(&ourprefs, &peer->prefs, sizeof(ourprefs));
04414    /* Move the calling channel's native codec to the top of the preference list */
04415    if (c) {
04416       ast_debug(1, "prepending %x to prefs\n", c->nativeformats);
04417       ast_codec_pref_prepend(&ourprefs, c->nativeformats, 1);
04418    }
04419    ast_codec_pref_convert(&ourprefs, cai->prefs, sizeof(cai->prefs), 1);
04420    ast_copy_string(cai->context, peer->context, sizeof(cai->context));
04421    ast_copy_string(cai->peercontext, peer->peercontext, sizeof(cai->peercontext));
04422    ast_copy_string(cai->username, peer->username, sizeof(cai->username));
04423    ast_copy_string(cai->timezone, peer->zonetag, sizeof(cai->timezone));
04424    ast_copy_string(cai->outkey, peer->outkey, sizeof(cai->outkey));
04425    ast_copy_string(cai->mohinterpret, peer->mohinterpret, sizeof(cai->mohinterpret));
04426    ast_copy_string(cai->mohsuggest, peer->mohsuggest, sizeof(cai->mohsuggest));
04427    if (ast_strlen_zero(peer->dbsecret)) {
04428       ast_copy_string(cai->secret, peer->secret, sizeof(cai->secret));
04429    } else {
04430       char *family;
04431       char *key = NULL;
04432 
04433       family = ast_strdupa(peer->dbsecret);
04434       key = strchr(family, '/');
04435       if (key)
04436          *key++ = '\0';
04437       if (!key || ast_db_get(family, key, cai->secret, sizeof(cai->secret))) {
04438          ast_log(LOG_WARNING, "Unable to retrieve database password for family/key '%s'!\n", peer->dbsecret);
04439          goto return_unref;
04440       }
04441    }
04442 
04443    if (peer->addr.sin_addr.s_addr) {
04444       sin->sin_addr = peer->addr.sin_addr;
04445       sin->sin_port = peer->addr.sin_port;
04446    } else {
04447       sin->sin_addr = peer->defaddr.sin_addr;
04448       sin->sin_port = peer->defaddr.sin_port;
04449    }
04450 
04451    res = 0;
04452 
04453 return_unref:
04454    peer_unref(peer);
04455 
04456    return res;
04457 }
04458 
04459 static void __auto_congest(const void *nothing)
04460 {
04461    int callno = PTR_TO_CALLNO(nothing);
04462    struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_CONGESTION };
04463    ast_mutex_lock(&iaxsl[callno]);
04464    if (iaxs[callno]) {
04465       iaxs[callno]->initid = -1;
04466       iax2_queue_frame(callno, &f);
04467       ast_log(LOG_NOTICE, "Auto-congesting call due to slow response\n");
04468    }
04469    ast_mutex_unlock(&iaxsl[callno]);
04470 }
04471 
04472 static int auto_congest(const void *data)
04473 {
04474 #ifdef SCHED_MULTITHREADED
04475    if (schedule_action(__auto_congest, data))
04476 #endif      
04477       __auto_congest(data);
04478    return 0;
04479 }
04480 
04481 static unsigned int iax2_datetime(const char *tz)
04482 {
04483    struct timeval t = ast_tvnow();
04484    struct ast_tm tm;
04485    unsigned int tmp;
04486    ast_localtime(&t, &tm, ast_strlen_zero(tz) ? NULL : tz);
04487    tmp  = (tm.tm_sec >> 1) & 0x1f;        /* 5 bits of seconds */
04488    tmp |= (tm.tm_min & 0x3f) << 5;        /* 6 bits of minutes */
04489    tmp |= (tm.tm_hour & 0x1f) << 11;      /* 5 bits of hours */
04490    tmp |= (tm.tm_mday & 0x1f) << 16;      /* 5 bits of day of month */
04491    tmp |= ((tm.tm_mon + 1) & 0xf) << 21;     /* 4 bits of month */
04492    tmp |= ((tm.tm_year - 100) & 0x7f) << 25; /* 7 bits of year */
04493    return tmp;
04494 }
04495 
04496 struct parsed_dial_string {
04497    char *username;
04498    char *password;
04499    char *key;
04500    char *peer;
04501    char *port;
04502    char *exten;
04503    char *context;
04504    char *options;
04505 };
04506 
04507 static int send_apathetic_reply(unsigned short callno, unsigned short dcallno,
04508       struct sockaddr_in *sin, int command, int ts, unsigned char seqno,
04509       int sockfd, struct iax_ie_data *ied)
04510 {
04511    struct {
04512       struct ast_iax2_full_hdr f;
04513       struct iax_ie_data ied;
04514    } data;
04515    size_t size = sizeof(struct ast_iax2_full_hdr);
04516 
04517    if (ied) {
04518       size += ied->pos;
04519       memcpy(&data.ied, ied->buf, ied->pos);
04520    }
04521 
04522    data.f.scallno = htons(0x8000 | callno);
04523    data.f.dcallno = htons(dcallno);
04524    data.f.ts = htonl(ts);
04525    data.f.iseqno = seqno;
04526    data.f.oseqno = 0;
04527    data.f.type = AST_FRAME_IAX;
04528    data.f.csub = compress_subclass(command);
04529 
04530    return sendto(sockfd, &data, size, 0, (struct sockaddr *)sin, sizeof(*sin));
04531 }
04532 
04533 static void add_empty_calltoken_ie(struct chan_iax2_pvt *pvt, struct iax_ie_data *ied)
04534 {
04535    /* first make sure their are two empty bytes left in ied->buf */
04536    if (pvt && ied && (2 < ((int) sizeof(ied->buf) - ied->pos))) {
04537       ied->buf[ied->pos++] = IAX_IE_CALLTOKEN;  /* type */
04538       ied->buf[ied->pos++] = 0;   /* data size,  ZERO in this case */
04539       pvt->calltoken_ie_len = 2;
04540    }
04541 }
04542 
04543 static void resend_with_token(int callno, struct iax_frame *f, const char *newtoken)
04544 {
04545    struct chan_iax2_pvt *pvt = iaxs[callno];
04546    int frametype = f->af.frametype;
04547    int subclass = f->af.subclass;
04548    struct {
04549       struct ast_iax2_full_hdr fh;
04550       struct iax_ie_data ied;
04551    } data = {
04552       .ied.buf = { 0 },
04553       .ied.pos = 0,
04554    };
04555    /* total len - header len gives us the frame's IE len */
04556    int ie_data_pos = f->datalen - sizeof(struct ast_iax2_full_hdr);
04557 
04558    if (!pvt) {
04559       return;  /* this should not be possible if called from socket_process() */
04560    }
04561 
04562    /* 
04563     * Check to make sure last frame sent is valid for call token resend
04564     * 1. Frame should _NOT_ be encrypted since it starts the IAX dialog 
04565     * 2. Frame should _NOT_ already have a destination callno
04566     * 3. Frame must be a valid iax_frame subclass capable of starting dialog
04567     * 4. Pvt must have a calltoken_ie_len which represents the number of
04568     *    bytes at the end of the frame used for the previous calltoken ie.
04569     * 5. Pvt's calltoken_ie_len must be _LESS_ than the total IE length
04570     * 6. Total length of f->data must be _LESS_ than size of our data struct
04571     *    because f->data must be able to fit within data. 
04572     */
04573    if (f->encmethods || f->dcallno || !iax2_allow_new(frametype, subclass, 0)
04574       || !pvt->calltoken_ie_len || (pvt->calltoken_ie_len > ie_data_pos) ||
04575       (f->datalen > sizeof(data))) {
04576 
04577       return;  /* ignore resend, token was not valid for the dialog */
04578    }
04579 
04580    /* token is valid
04581     * 1. Copy frame data over
04582     * 2. Redo calltoken IE, it will always be the last ie in the frame.
04583     *    NOTE: Having the ie always be last is not protocol specified,
04584     *    it is only an implementation choice.  Since we only expect the ie to
04585     *    be last for frames we have sent, this can no way be affected by
04586     *    another end point.
04587     * 3. Remove frame from queue
04588     * 4. Free old frame
04589     * 5. Clear previous seqnos
04590     * 6. Resend with CALLTOKEN ie.
04591     */
04592 
04593    /* ---1.--- */
04594    memcpy(&data, f->data, f->datalen);
04595    data.ied.pos = ie_data_pos;
04596 
04597    /* ---2.--- */
04598    /* move to the beginning of the calltoken ie so we can write over it */
04599    data.ied.pos -= pvt->calltoken_ie_len;
04600    iax_ie_append_str(&data.ied, IAX_IE_CALLTOKEN, newtoken);
04601 
04602    /* make sure to update token length incase it ever has to be stripped off again */
04603    pvt->calltoken_ie_len = data.ied.pos - ie_data_pos; /* new pos minus old pos tells how big token ie is */
04604 
04605    /* ---3.--- */
04606    AST_LIST_LOCK(&frame_queue);
04607    AST_LIST_REMOVE(&frame_queue, f, list);
04608    AST_LIST_UNLOCK(&frame_queue);
04609 
04610    /* ---4.--- */
04611    iax2_frame_free(f);
04612 
04613    /* ---5.--- */
04614    pvt->oseqno = 0;
04615    pvt->rseqno = 0;
04616    pvt->iseqno = 0;
04617    pvt->aseqno = 0;
04618    if (pvt->peercallno) {
04619       remove_by_peercallno(pvt);
04620       pvt->peercallno = 0;
04621    }
04622 
04623    /* ---6.--- */
04624    send_command(pvt, AST_FRAME_IAX, subclass, 0, data.ied.buf, data.ied.pos, -1);
04625 }
04626 
04627 static void requirecalltoken_mark_auto(const char *name, int subclass)
04628 {
04629    struct iax2_user *user = NULL;
04630    struct iax2_peer *peer = NULL;
04631 
04632    if (ast_strlen_zero(name)) {
04633       return; /* no username given */
04634    }
04635 
04636    if ((subclass == IAX_COMMAND_NEW) && (user = find_user(name)) && (user->calltoken_required == CALLTOKEN_AUTO)) {
04637       user->calltoken_required = CALLTOKEN_YES;
04638    } else if ((subclass != IAX_COMMAND_NEW) && (peer = find_peer(name, 1)) && (peer->calltoken_required == CALLTOKEN_AUTO)) {
04639       peer->calltoken_required = CALLTOKEN_YES;
04640    }
04641 
04642    if (peer) {
04643       peer_unref(peer);
04644    }
04645    if (user) {
04646       user_unref(user);
04647    }
04648 }
04649 
04650 /*!
04651  * \internal
04652  *
04653  * \brief handles calltoken logic for a received iax_frame.
04654  * 
04655  * \note frametype must be AST_FRAME_IAX.
04656  * 
04657  * \note
04658  * Three different cases are possible here.
04659  * Case 1. An empty calltoken is provided. This means the client supports
04660  *         calltokens but has not yet received one from us.  In this case
04661  *         a full calltoken IE is created and sent in a calltoken fullframe.
04662  * Case 2. A full calltoken is received and must be checked for validity.
04663  * Case 3. No calltoken is received indicating that the client does not
04664  *         support calltokens.  In this case it is up to the configuration
04665  *         to decide how this should be handled (reject or permit without calltoken)
04666  */
04667 static int handle_call_token(struct ast_iax2_full_hdr *fh, struct iax_ies *ies,
04668       struct sockaddr_in *sin, int fd)
04669 {
04670 #define CALLTOKEN_HASH_FORMAT "%s%d%u%d"  /* address + port + ts + randomcalldata */
04671 #define CALLTOKEN_IE_FORMAT   "%u?%s"     /* time + ? + (40 char hash) */
04672    struct ast_str *buf = ast_str_alloca(256);
04673    time_t t = time(NULL);
04674    char hash[41]; /* 40 char sha1 hash */
04675    int subclass = uncompress_subclass(fh->csub);
04676 
04677    /* ----- Case 1 ----- */
04678    if (ies->calltoken && !ies->calltokendata) {  /* empty calltoken is provided, client supports calltokens */
04679       struct iax_ie_data ied = {
04680          .buf = { 0 },
04681          .pos = 0,
04682       };
04683 
04684       /* create the hash with their address data and our timestamp */
04685       ast_str_set(&buf, 0, CALLTOKEN_HASH_FORMAT, ast_inet_ntoa(sin->sin_addr), sin->sin_port, (unsigned int) t, randomcalltokendata);
04686       ast_sha1_hash(hash, ast_str_buffer(buf));
04687 
04688       ast_str_set(&buf, 0, CALLTOKEN_IE_FORMAT, (unsigned int) t, hash);
04689       iax_ie_append_str(&ied, IAX_IE_CALLTOKEN, ast_str_buffer(buf));
04690       send_apathetic_reply(1, ntohs(fh->scallno), sin, IAX_COMMAND_CALLTOKEN, ntohl(fh->ts), fh->iseqno + 1, fd, &ied);
04691 
04692       return 1;
04693 
04694    /* ----- Case 2 ----- */
04695    } else if (ies->calltoken && ies->calltokendata) { /* calltoken received, check to see if it is valid */
04696       char *rec_hash = NULL;    /* the received hash, make sure it matches with ours. */
04697       char *rec_ts = NULL;      /* received timestamp */
04698       unsigned int rec_time;  /* received time_t */
04699 
04700       /* split the timestamp from the hash data */
04701       rec_hash = strchr((char *) ies->calltokendata, '?');
04702       if (rec_hash) {
04703          *rec_hash++ = '\0';
04704          rec_ts = (char *) ies->calltokendata;
04705       }
04706 
04707       /* check that we have valid data before we do any comparisons */
04708       if (!rec_hash || !rec_ts) {
04709          goto reject;
04710       } else if (sscanf(rec_ts, "%u", &rec_time) != 1) {
04711          goto reject;
04712       }
04713 
04714       /* create a hash with their address and the _TOKEN'S_ timestamp */
04715       ast_str_set(&buf, 0, CALLTOKEN_HASH_FORMAT, ast_inet_ntoa(sin->sin_addr), sin->sin_port, (unsigned int) rec_time, randomcalltokendata);
04716       ast_sha1_hash(hash, ast_str_buffer(buf));
04717 
04718       /* compare hashes and then check timestamp delay */
04719       if (strcmp(hash, rec_hash)) {
04720          ast_log(LOG_WARNING, "Address %s failed CallToken hash inspection\n", ast_inet_ntoa(sin->sin_addr));
04721          goto reject; /* received hash does not match ours, reject */
04722       } else if ((t < rec_time) || ((t - rec_time) >= MAX_CALLTOKEN_DELAY)) {
04723          ast_log(LOG_WARNING, "Too much delay in IAX2 calltoken timestamp from address %s\n", ast_inet_ntoa(sin->sin_addr));
04724          goto reject; /* too much delay, reject */
04725       }
04726 
04727       /* at this point the call token is valid, returning 0 
04728        * will allow socket_process to continue as usual */
04729       requirecalltoken_mark_auto(ies->username, subclass);
04730       return 0;
04731 
04732    /* ----- Case 3 ----- */
04733    } else { /* calltokens are not supported for this client, how do we respond? */
04734       if (calltoken_required(sin, ies->username, subclass)) {
04735          ast_log(LOG_ERROR, "Call rejected, CallToken Support required. If unexpected, resolve by placing address %s in the calltokenoptional list or setting user %s requirecalltoken=no\n", ast_inet_ntoa(sin->sin_addr), S_OR(ies->username, "guest"));
04736          goto reject;
04737       }
04738       return 0; /* calltoken is not required for this addr, so permit it. */
04739    }
04740 
04741 reject:
04742    /* received frame has failed calltoken inspection, send apathetic reject messages */
04743    if (subclass == IAX_COMMAND_REGREQ || subclass == IAX_COMMAND_REGREL) {
04744       send_apathetic_reply(1, ntohs(fh->scallno), sin, IAX_COMMAND_REGREJ, ntohl(fh->ts), fh->iseqno + 1, fd, NULL);
04745    } else {
04746       send_apathetic_reply(1, ntohs(fh->scallno), sin, IAX_COMMAND_REJECT, ntohl(fh->ts), fh->iseqno + 1, fd, NULL);
04747    }
04748 
04749    return 1;
04750 }
04751 
04752 /*!
04753  * \brief Parses an IAX dial string into its component parts.
04754  * \param data the string to be parsed
04755  * \param pds pointer to a \c struct \c parsed_dial_string to be filled in
04756  * \return nothing
04757  *
04758  * This function parses the string and fills the structure
04759  * with pointers to its component parts. The input string
04760  * will be modified.
04761  *
04762  * \note This function supports both plaintext passwords and RSA
04763  * key names; if the password string is formatted as '[keyname]',
04764  * then the keyname will be placed into the key field, and the
04765  * password field will be set to NULL.
04766  *
04767  * \note The dial string format is:
04768  *       [username[:password]@]peer[:port][/exten[@@context]][/options]
04769  */
04770 static void parse_dial_string(char *data, struct parsed_dial_string *pds)
04771 {
04772    if (ast_strlen_zero(data))
04773       return;
04774 
04775    pds->peer = strsep(&data, "/");
04776    pds->exten = strsep(&data, "/");
04777    pds->options = data;
04778 
04779    if (pds->exten) {
04780       data = pds->exten;
04781       pds->exten = strsep(&data, "@");
04782       pds->context = data;
04783    }
04784 
04785    if (strchr(pds->peer, '@')) {
04786       data = pds->peer;
04787       pds->username = strsep(&data, "@");
04788       pds->peer = data;
04789    }
04790 
04791    if (pds->username) {
04792       data = pds->username;
04793       pds->username = strsep(&data, ":");
04794       pds->password = data;
04795    }
04796 
04797    data = pds->peer;
04798    pds->peer = strsep(&data, ":");
04799    pds->port = data;
04800 
04801    /* check for a key name wrapped in [] in the secret position, if found,
04802       move it to the key field instead
04803    */
04804    if (pds->password && (pds->password[0] == '[')) {
04805       pds->key = ast_strip_quoted(pds->password, "[", "]");
04806       pds->password = NULL;
04807    }
04808 }
04809 
04810 static int iax2_call(struct ast_channel *c, char *dest, int timeout)
04811 {
04812    struct sockaddr_in sin;
04813    char *l=NULL, *n=NULL, *tmpstr;
04814    struct iax_ie_data ied;
04815    char *defaultrdest = "s";
04816    unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
04817    struct parsed_dial_string pds;
04818    struct create_addr_info cai;
04819    struct ast_var_t *var;
04820    struct ast_datastore *variablestore = ast_channel_datastore_find(c, &iax2_variable_datastore_info, NULL);
04821    const char* osp_token_ptr;
04822    unsigned int osp_token_length;
04823    unsigned char osp_block_index;
04824    unsigned int osp_block_length;
04825    unsigned char osp_buffer[256];
04826 
04827    if ((c->_state != AST_STATE_DOWN) && (c->_state != AST_STATE_RESERVED)) {
04828       ast_log(LOG_WARNING, "Channel is already in use (%s)?\n", c->name);
04829       return -1;
04830    }
04831 
04832    memset(&cai, 0, sizeof(cai));
04833    cai.encmethods = iax2_encryption;
04834 
04835    memset(&pds, 0, sizeof(pds));
04836    tmpstr = ast_strdupa(dest);
04837    parse_dial_string(tmpstr, &pds);
04838 
04839    if (ast_strlen_zero(pds.peer)) {
04840       ast_log(LOG_WARNING, "No peer provided in the IAX2 dial string '%s'\n", dest);
04841       return -1;
04842    }
04843    if (!pds.exten) {
04844       pds.exten = defaultrdest;
04845    }
04846    if (create_addr(pds.peer, c, &sin, &cai)) {
04847       ast_log(LOG_WARNING, "No address associated with '%s'\n", pds.peer);
04848       return -1;
04849    }
04850    if (ast_strlen_zero(cai.secret) && ast_test_flag(iaxs[callno], IAX_FORCE_ENCRYPT)) {
04851       ast_log(LOG_WARNING, "Call terminated. No secret given and force encrypt enabled\n");
04852       return -1;
04853    }
04854    if (!pds.username && !ast_strlen_zero(cai.username))
04855       pds.username = cai.username;
04856    if (!pds.password && !ast_strlen_zero(cai.secret))
04857       pds.password = cai.secret;
04858    if (!pds.key && !ast_strlen_zero(cai.outkey))
04859       pds.key = cai.outkey;
04860    if (!pds.context && !ast_strlen_zero(cai.peercontext))
04861       pds.context = cai.peercontext;
04862 
04863    /* Keep track of the context for outgoing calls too */
04864    ast_copy_string(c->context, cai.context, sizeof(c->context));
04865 
04866    if (pds.port)
04867       sin.sin_port = htons(atoi(pds.port));
04868 
04869    l = c->cid.cid_num;
04870    n = c->cid.cid_name;
04871 
04872    /* Now build request */ 
04873    memset(&ied, 0, sizeof(ied));
04874 
04875    /* On new call, first IE MUST be IAX version of caller */
04876    iax_ie_append_short(&ied, IAX_IE_VERSION, IAX_PROTO_VERSION);
04877    iax_ie_append_str(&ied, IAX_IE_CALLED_NUMBER, pds.exten);
04878    if (pds.options && strchr(pds.options, 'a')) {
04879       /* Request auto answer */
04880       iax_ie_append(&ied, IAX_IE_AUTOANSWER);
04881    }
04882 
04883    iax_ie_append_str(&ied, IAX_IE_CODEC_PREFS, cai.prefs);
04884 
04885    if (l) {
04886       iax_ie_append_str(&ied, IAX_IE_CALLING_NUMBER, l);
04887       iax_ie_append_byte(&ied, IAX_IE_CALLINGPRES, c->cid.cid_pres);
04888    } else {
04889       if (n)
04890          iax_ie_append_byte(&ied, IAX_IE_CALLINGPRES, c->cid.cid_pres);
04891       else
04892          iax_ie_append_byte(&ied, IAX_IE_CALLINGPRES, AST_PRES_NUMBER_NOT_AVAILABLE);
04893    }
04894 
04895    iax_ie_append_byte(&ied, IAX_IE_CALLINGTON, c->cid.cid_ton);
04896    iax_ie_append_short(&ied, IAX_IE_CALLINGTNS, c->cid.cid_tns);
04897 
04898    if (n)
04899       iax_ie_append_str(&ied, IAX_IE_CALLING_NAME, n);
04900    if (ast_test_flag(iaxs[callno], IAX_SENDANI) && c->cid.cid_ani)
04901       iax_ie_append_str(&ied, IAX_IE_CALLING_ANI, c->cid.cid_ani);
04902 
04903    if (!ast_strlen_zero(c->language))
04904       iax_ie_append_str(&ied, IAX_IE_LANGUAGE, c->language);
04905    if (!ast_strlen_zero(c->cid.cid_dnid))
04906       iax_ie_append_str(&ied, IAX_IE_DNID, c->cid.cid_dnid);
04907    if (!ast_strlen_zero(c->cid.cid_rdnis))
04908       iax_ie_append_str(&ied, IAX_IE_RDNIS, c->cid.cid_rdnis);
04909 
04910    if (pds.context)
04911       iax_ie_append_str(&ied, IAX_IE_CALLED_CONTEXT, pds.context);
04912 
04913    if (pds.username)
04914       iax_ie_append_str(&ied, IAX_IE_USERNAME, pds.username);
04915 
04916    if (cai.encmethods)
04917       iax_ie_append_short(&ied, IAX_IE_ENCRYPTION, cai.encmethods);
04918 
04919    ast_mutex_lock(&iaxsl[callno]);
04920 
04921    if (!ast_strlen_zero(c->context))
04922       ast_string_field_set(iaxs[callno], context, c->context);
04923 
04924    if (pds.username)
04925       ast_string_field_set(iaxs[callno], username, pds.username);
04926 
04927    iaxs[callno]->encmethods = cai.encmethods;
04928 
04929    iaxs[callno]->adsi = cai.adsi;
04930    
04931    ast_string_field_set(iaxs[callno], mohinterpret, cai.mohinterpret);
04932    ast_string_field_set(iaxs[callno], mohsuggest, cai.mohsuggest);
04933 
04934    if (pds.key)
04935       ast_string_field_set(iaxs[callno], outkey, pds.key);
04936    if (pds.password)
04937       ast_string_field_set(iaxs[callno], secret, pds.password);
04938 
04939    iax_ie_append_int(&ied, IAX_IE_FORMAT, c->nativeformats);
04940    iax_ie_append_int(&ied, IAX_IE_CAPABILITY, iaxs[callno]->capability);
04941    iax_ie_append_short(&ied, IAX_IE_ADSICPE, c->adsicpe);
04942    iax_ie_append_int(&ied, IAX_IE_DATETIME, iax2_datetime(cai.timezone));
04943 
04944    if (iaxs[callno]->maxtime) {
04945       /* Initialize pingtime and auto-congest time */
04946       iaxs[callno]->pingtime = iaxs[callno]->maxtime / 2;
04947       iaxs[callno]->initid = iax2_sched_add(sched, iaxs[callno]->maxtime * 2, auto_congest, CALLNO_TO_PTR(callno));
04948    } else if (autokill) {
04949       iaxs[callno]->pingtime = autokill / 2;
04950       iaxs[callno]->initid = iax2_sched_add(sched, autokill * 2, auto_congest, CALLNO_TO_PTR(callno));
04951    }
04952 
04953    /* Check if there is an OSP token */
04954    osp_token_ptr = pbx_builtin_getvar_helper(c, "IAX2OSPTOKEN");
04955    if (!ast_strlen_zero(osp_token_ptr)) {
04956       if ((osp_token_length = strlen(osp_token_ptr)) <= IAX_MAX_OSPTOKEN_SIZE) {
04957          osp_block_index = 0;
04958          while (osp_token_length > 0) {
04959             osp_block_length = IAX_MAX_OSPBLOCK_SIZE < osp_token_length ? IAX_MAX_OSPBLOCK_SIZE : osp_token_length;
04960             osp_buffer[0] = osp_block_index;
04961             memcpy(osp_buffer + 1, osp_token_ptr, osp_block_length);
04962             iax_ie_append_raw(&ied, IAX_IE_OSPTOKEN, osp_buffer, osp_block_length + 1);
04963             osp_block_index++;
04964             osp_token_ptr += osp_block_length;
04965             osp_token_length -= osp_block_length;
04966          } 
04967       } else
04968          ast_log(LOG_WARNING, "OSP token is too long\n");
04969    } else if (iaxdebug)
04970       ast_debug(1, "OSP token is undefined\n");
04971 
04972    /* send the command using the appropriate socket for this peer */
04973    iaxs[callno]->sockfd = cai.sockfd;
04974 
04975    /* Add remote vars */
04976    if (variablestore) {
04977       AST_LIST_HEAD(, ast_var_t) *variablelist = variablestore->data;
04978       ast_debug(1, "Found an IAX variable store on this channel\n");
04979       AST_LIST_LOCK(variablelist);
04980       AST_LIST_TRAVERSE(variablelist, var, entries) {
04981          char tmp[256];
04982          int i;
04983          ast_debug(1, "Found IAXVAR '%s' with value '%s' (to transmit)\n", ast_var_name(var), ast_var_value(var));
04984          /* Automatically divide the value up into sized chunks */
04985          for (i = 0; i < strlen(ast_var_value(var)); i += 255 - (strlen(ast_var_name(var)) + 1)) {
04986             snprintf(tmp, sizeof(tmp), "%s=%s", ast_var_name(var), ast_var_value(var) + i);
04987             iax_ie_append_str(&ied, IAX_IE_VARIABLE, tmp);
04988          }
04989       }
04990       AST_LIST_UNLOCK(variablelist);
04991    }
04992 
04993    /* Transmit the string in a "NEW" request */
04994    add_empty_calltoken_ie(iaxs[callno], &ied); /* this _MUST_ be the last ie added */
04995    send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_NEW, 0, ied.buf, ied.pos, -1);
04996 
04997    ast_mutex_unlock(&iaxsl[callno]);
04998    ast_setstate(c, AST_STATE_RINGING);
04999 
05000    return 0;
05001 }
05002 
05003 static int iax2_hangup(struct ast_channel *c) 
05004 {
05005    unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
05006    struct iax_ie_data ied;
05007    int alreadygone;
05008    memset(&ied, 0, sizeof(ied));
05009    ast_mutex_lock(&iaxsl[callno]);
05010    if (callno && iaxs[callno]) {
05011       ast_debug(1, "We're hanging up %s now...\n", c->name);
05012       alreadygone = ast_test_flag(iaxs[callno], IAX_ALREADYGONE);
05013       /* Send the hangup unless we have had a transmission error or are already gone */
05014       iax_ie_append_byte(&ied, IAX_IE_CAUSECODE, (unsigned char)c->hangupcause);
05015       if (!iaxs[callno]->error && !alreadygone) {
05016          if (send_command_final(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_HANGUP, 0, ied.buf, ied.pos, -1)) {
05017             ast_log(LOG_WARNING, "No final packet could be sent for callno %d\n", callno);
05018          }
05019          if (!iaxs[callno]) {
05020             ast_mutex_unlock(&iaxsl[callno]);
05021             return 0;
05022          }
05023       }
05024       /* Explicitly predestroy it */
05025       iax2_predestroy(callno);
05026       /* If we were already gone to begin with, destroy us now */
05027       if (iaxs[callno] && alreadygone) {
05028          ast_debug(1, "Really destroying %s now...\n", c->name);
05029          iax2_destroy(callno);
05030       } else if (iaxs[callno]) {
05031          if (ast_sched_thread_add(sched, 10000, scheduled_destroy, CALLNO_TO_PTR(callno)) < 0) {
05032             ast_log(LOG_ERROR, "Unable to schedule iax2 callno %d destruction?!!  Destroying immediately.\n", callno);
05033             iax2_destroy(callno);
05034          }
05035       }
05036    } else if (c->tech_pvt) {
05037       /* If this call no longer exists, but the channel still
05038        * references it we need to set the channel's tech_pvt to null
05039        * to avoid ast_channel_free() trying to free it.
05040        */
05041       c->tech_pvt = NULL;
05042    }
05043    ast_mutex_unlock(&iaxsl[callno]);
05044    ast_verb(3, "Hungup '%s'\n", c->name);
05045    return 0;
05046 }
05047 
05048 /*!
05049  * \note expects the pvt to be locked
05050  */
05051 static int wait_for_peercallno(struct chan_iax2_pvt *pvt)
05052 {
05053    unsigned short callno = pvt->callno;
05054 
05055    if (!pvt->peercallno) {
05056       /* We don't know the remote side's call number, yet.  :( */
05057       int count = 10;
05058       while (count-- && pvt && !pvt->peercallno) {
05059          DEADLOCK_AVOIDANCE(&iaxsl[callno]);
05060          pvt = iaxs[callno];
05061       }
05062       if (!pvt->peercallno) {
05063          return -1;
05064       }
05065    }
05066 
05067    return 0;
05068 }
05069 
05070 static int iax2_setoption(struct ast_channel *c, int option, void *data, int datalen)
05071 {
05072    struct ast_option_header *h;
05073    int res;
05074 
05075    switch (option) {
05076    case AST_OPTION_TXGAIN:
05077    case AST_OPTION_RXGAIN:
05078       /* these two cannot be sent, because they require a result */
05079       errno = ENOSYS;
05080       return -1;
05081    case AST_OPTION_OPRMODE:
05082       errno = EINVAL;
05083       return -1;
05084    /* These options are sent to the other side across the network where
05085     * they will be passed to whatever channel is bridged there. Don't
05086     * do anything silly like pass an option that transmits pointers to
05087     * memory on this machine to a remote machine to use */
05088    case AST_OPTION_TONE_VERIFY:
05089    case AST_OPTION_TDD:
05090    case AST_OPTION_RELAXDTMF:
05091    case AST_OPTION_AUDIO_MODE:
05092    {
05093       unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
05094       struct chan_iax2_pvt *pvt;
05095 
05096       ast_mutex_lock(&iaxsl[callno]);
05097       pvt = iaxs[callno];
05098 
05099       if (wait_for_peercallno(pvt)) {
05100          ast_mutex_unlock(&iaxsl[callno]);
05101          return -1;
05102       }
05103 
05104       ast_mutex_unlock(&iaxsl[callno]);
05105 
05106       if (!(h = ast_malloc(datalen + sizeof(*h)))) {
05107          return -1;
05108       }
05109 
05110       h->flag = AST_OPTION_FLAG_REQUEST;
05111       h->option = htons(option);
05112       memcpy(h->data, data, datalen);
05113       res = send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_CONTROL,
05114                  AST_CONTROL_OPTION, 0, (unsigned char *) h,
05115                  datalen + sizeof(*h), -1);
05116       ast_free(h);
05117       return res;
05118    }
05119    default:
05120       return -1;
05121    }
05122 
05123    /* Just in case someone does a break instead of a return */
05124    return -1;
05125 }
05126 
05127 static struct ast_frame *iax2_read(struct ast_channel *c) 
05128 {
05129    ast_log(LOG_NOTICE, "I should never be called!\n");
05130    return &ast_null_frame;
05131 }
05132 
05133 static int iax2_key_rotate(const void *vpvt)
05134 {
05135    int res = 0;
05136    struct chan_iax2_pvt *pvt = (void *) vpvt;
05137    struct MD5Context md5;
05138    char key[17] = "";
05139    struct iax_ie_data ied = {
05140       .pos = 0,   
05141    };
05142    
05143    ast_mutex_lock(&iaxsl[pvt->callno]);
05144    pvt->keyrotateid = 
05145       ast_sched_thread_add(sched, 120000 + (ast_random() % 180001), iax2_key_rotate, vpvt);
05146 
05147    snprintf(key, sizeof(key), "%lX", ast_random());
05148 
05149    MD5Init(&md5);
05150    MD5Update(&md5, (unsigned char *) key, strlen(key));
05151    MD5Final((unsigned char *) key, &md5);
05152 
05153    IAX_DEBUGDIGEST("Sending", key);
05154 
05155    iax_ie_append_raw(&ied, IAX_IE_CHALLENGE, key, 16);
05156 
05157    res = send_command(pvt, AST_FRAME_IAX, IAX_COMMAND_RTKEY, 0, ied.buf, ied.pos, -1);
05158 
05159    build_ecx_key((unsigned char *) key, pvt);
05160 
05161    ast_mutex_unlock(&iaxsl[pvt->callno]);
05162 
05163    return res;
05164 }
05165 
05166 static int iax2_start_transfer(unsigned short callno0, unsigned short callno1, int mediaonly)
05167 {
05168    int res;
05169    struct iax_ie_data ied0;
05170    struct iax_ie_data ied1;
05171    unsigned int transferid = (unsigned int)ast_random();
05172 
05173    if (IAX_CALLENCRYPTED(iaxs[callno0]) || IAX_CALLENCRYPTED(iaxs[callno1])) {
05174       ast_debug(1, "transfers are not supported for encrypted calls at this time");
05175       ast_set_flag(iaxs[callno0], IAX_NOTRANSFER);
05176       ast_set_flag(iaxs[callno1], IAX_NOTRANSFER);
05177       return 0;
05178    }
05179 
05180    memset(&ied0, 0, sizeof(ied0));
05181    iax_ie_append_addr(&ied0, IAX_IE_APPARENT_ADDR, &iaxs[callno1]->addr);
05182    iax_ie_append_short(&ied0, IAX_IE_CALLNO, iaxs[callno1]->peercallno);
05183    iax_ie_append_int(&ied0, IAX_IE_TRANSFERID, transferid);
05184 
05185    memset(&ied1, 0, sizeof(ied1));
05186    iax_ie_append_addr(&ied1, IAX_IE_APPARENT_ADDR, &iaxs[callno0]->addr);
05187    iax_ie_append_short(&ied1, IAX_IE_CALLNO, iaxs[callno0]->peercallno);
05188    iax_ie_append_int(&ied1, IAX_IE_TRANSFERID, transferid);
05189    
05190    res = send_command(iaxs[callno0], AST_FRAME_IAX, IAX_COMMAND_TXREQ, 0, ied0.buf, ied0.pos, -1);
05191    if (res)
05192       return -1;
05193    res = send_command(iaxs[callno1], AST_FRAME_IAX, IAX_COMMAND_TXREQ, 0, ied1.buf, ied1.pos, -1);
05194    if (res)
05195       return -1;
05196    iaxs[callno0]->transferring = mediaonly ? TRANSFER_MBEGIN : TRANSFER_BEGIN;
05197    iaxs[callno1]->transferring = mediaonly ? TRANSFER_MBEGIN : TRANSFER_BEGIN;
05198    return 0;
05199 }
05200 
05201 static void lock_both(unsigned short callno0, unsigned short callno1)
05202 {
05203    ast_mutex_lock(&iaxsl[callno0]);
05204    while (ast_mutex_trylock(&iaxsl[callno1])) {
05205       DEADLOCK_AVOIDANCE(&iaxsl[callno0]);
05206    }
05207 }
05208 
05209 static void unlock_both(unsigned short callno0, unsigned short callno1)
05210 {
05211    ast_mutex_unlock(&iaxsl[callno1]);
05212    ast_mutex_unlock(&iaxsl[callno0]);
05213 }
05214 
05215 static enum ast_bridge_result iax2_bridge(struct ast_channel *c0, struct ast_channel *c1, int flags, struct ast_frame **fo, struct ast_channel **rc, int timeoutms)
05216 {
05217    struct ast_channel *cs[3];
05218    struct ast_channel *who, *other;
05219    int to = -1;
05220    int res = -1;
05221    int transferstarted=0;
05222    struct ast_frame *f;
05223    unsigned short callno0 = PTR_TO_CALLNO(c0->tech_pvt);
05224    unsigned short callno1 = PTR_TO_CALLNO(c1->tech_pvt);
05225    struct timeval waittimer = {0, 0};
05226 
05227    /* We currently do not support native bridging if a timeoutms value has been provided */
05228    if (timeoutms > 0) {
05229       return AST_BRIDGE_FAILED;
05230    }
05231 
05232    timeoutms = -1;
05233 
05234    lock_both(callno0, callno1);
05235    if (!iaxs[callno0] || !iaxs[callno1]) {
05236       unlock_both(callno0, callno1);
05237       return AST_BRIDGE_FAILED;
05238    }
05239    /* Put them in native bridge mode */
05240    if (!(flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1))) {
05241       iaxs[callno0]->bridgecallno = callno1;
05242       iaxs[callno1]->bridgecallno = callno0;
05243    }
05244    unlock_both(callno0, callno1);
05245 
05246    /* If not, try to bridge until we can execute a transfer, if we can */
05247    cs[0] = c0;
05248    cs[1] = c1;
05249    for (/* ever */;;) {
05250       /* Check in case we got masqueraded into */
05251       if ((c0->tech != &iax2_tech) || (c1->tech != &iax2_tech)) {
05252          ast_verb(3, "Can't masquerade, we're different...\n");
05253          /* Remove from native mode */
05254          if (c0->tech == &iax2_tech) {
05255             ast_mutex_lock(&iaxsl[callno0]);
05256             iaxs[callno0]->bridgecallno = 0;
05257             ast_mutex_unlock(&iaxsl[callno0]);
05258          }
05259          if (c1->tech == &iax2_tech) {
05260             ast_mutex_lock(&iaxsl[callno1]);
05261             iaxs[callno1]->bridgecallno = 0;
05262             ast_mutex_unlock(&iaxsl[callno1]);
05263          }
05264          return AST_BRIDGE_FAILED_NOWARN;
05265       }
05266       if (c0->nativeformats != c1->nativeformats) {
05267             char buf0[255];
05268             char buf1[255];
05269             ast_getformatname_multiple(buf0, sizeof(buf0) -1, c0->nativeformats);
05270             ast_getformatname_multiple(buf1, sizeof(buf1) -1, c1->nativeformats);
05271          ast_verb(3, "Operating with different codecs %d[%s] %d[%s] , can't native bridge...\n", c0->nativeformats, buf0, c1->nativeformats, buf1);
05272          /* Remove from native mode */
05273          lock_both(callno0, callno1);
05274          if (iaxs[callno0])
05275             iaxs[callno0]->bridgecallno = 0;
05276          if (iaxs[callno1])
05277             iaxs[callno1]->bridgecallno = 0;
05278          unlock_both(callno0, callno1);
05279          return AST_BRIDGE_FAILED_NOWARN;
05280       }
05281       /* check if transfered and if we really want native bridging */
05282       if (!transferstarted && !ast_test_flag(iaxs[callno0], IAX_NOTRANSFER) && !ast_test_flag(iaxs[callno1], IAX_NOTRANSFER)) {
05283          /* Try the transfer */
05284          if (iax2_start_transfer(callno0, callno1, (flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1)) ||
05285                      ast_test_flag(iaxs[callno0], IAX_TRANSFERMEDIA) | ast_test_flag(iaxs[callno1], IAX_TRANSFERMEDIA)))
05286             ast_log(LOG_WARNING, "Unable to start the transfer\n");
05287          transferstarted = 1;
05288       }
05289       if ((iaxs[callno0]->transferring == TRANSFER_RELEASED) && (iaxs[callno1]->transferring == TRANSFER_RELEASED)) {
05290          /* Call has been transferred.  We're no longer involved */
05291          struct timeval now = ast_tvnow();
05292          if (ast_tvzero(waittimer)) {
05293             waittimer = now;
05294          } else if (now.tv_sec - waittimer.tv_sec > IAX_LINGER_TIMEOUT) {
05295             c0->_softhangup |= AST_SOFTHANGUP_DEV;
05296             c1->_softhangup |= AST_SOFTHANGUP_DEV;
05297             *fo = NULL;
05298             *rc = c0;
05299             res = AST_BRIDGE_COMPLETE;
05300             break;
05301          }
05302       }
05303       to = 1000;
05304       who = ast_waitfor_n(cs, 2, &to);
05305       if (timeoutms > -1) {
05306          timeoutms -= (1000 - to);
05307          if (timeoutms < 0)
05308             timeoutms = 0;
05309       }
05310       if (!who) {
05311          if (!timeoutms) {
05312             res = AST_BRIDGE_RETRY;
05313             break;
05314          }
05315          if (ast_check_hangup(c0) || ast_check_hangup(c1)) {
05316             res = AST_BRIDGE_FAILED;
05317             break;
05318          }
05319          continue;
05320       }
05321       f = ast_read(who);
05322       if (!f) {
05323          *fo = NULL;
05324          *rc = who;
05325          res = AST_BRIDGE_COMPLETE;
05326          break;
05327       }
05328       if ((f->frametype == AST_FRAME_CONTROL) && !(flags & AST_BRIDGE_IGNORE_SIGS) && (f->subclass != AST_CONTROL_SRCUPDATE)) {
05329          *fo = f;
05330          *rc = who;
05331          res =  AST_BRIDGE_COMPLETE;
05332          break;
05333       }
05334       other = (who == c0) ? c1 : c0;  /* the 'other' channel */
05335       if ((f->frametype == AST_FRAME_VOICE) ||
05336          (f->frametype == AST_FRAME_TEXT) ||
05337          (f->frametype == AST_FRAME_VIDEO) || 
05338          (f->frametype == AST_FRAME_IMAGE) ||
05339          (f->frametype == AST_FRAME_DTMF) ||
05340          (f->frametype == AST_FRAME_CONTROL)) {
05341          /* monitored dtmf take out of the bridge.
05342           * check if we monitor the specific source.
05343           */
05344          int monitored_source = (who == c0) ? AST_BRIDGE_DTMF_CHANNEL_0 : AST_BRIDGE_DTMF_CHANNEL_1;
05345          if (f->frametype == AST_FRAME_DTMF && (flags & monitored_source)) {
05346             *rc = who;
05347             *fo = f;
05348             res = AST_BRIDGE_COMPLETE;
05349             /* Remove from native mode */
05350             break;
05351          }
05352          /* everything else goes to the other side */
05353          ast_write(other, f);
05354       }
05355       ast_frfree(f);
05356       /* Swap who gets priority */
05357       cs[2] = cs[0];
05358       cs[0] = cs[1];
05359       cs[1] = cs[2];
05360    }
05361    lock_both(callno0, callno1);
05362    if(iaxs[callno0])
05363       iaxs[callno0]->bridgecallno = 0;
05364    if(iaxs[callno1])
05365       iaxs[callno1]->bridgecallno = 0;
05366    unlock_both(callno0, callno1);
05367    return res;
05368 }
05369 
05370 static int iax2_answer(struct ast_channel *c)
05371 {
05372    unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
05373    ast_debug(1, "Answering IAX2 call\n");
05374    ast_mutex_lock(&iaxsl[callno]);
05375    if (iaxs[callno])
05376       iax2_ami_channelupdate(iaxs[callno]);
05377    ast_mutex_unlock(&iaxsl[callno]);
05378    return send_command_locked(callno, AST_FRAME_CONTROL, AST_CONTROL_ANSWER, 0, NULL, 0, -1);
05379 }
05380 
05381 static int iax2_indicate(struct ast_channel *c, int condition, const void *data, size_t datalen)
05382 {
05383    unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
05384    struct chan_iax2_pvt *pvt;
05385    int res = 0;
05386 
05387    if (iaxdebug)
05388       ast_debug(1, "Indicating condition %d\n", condition);
05389 
05390    ast_mutex_lock(&iaxsl[callno]);
05391    pvt = iaxs[callno];
05392 
05393    if (wait_for_peercallno(pvt)) {
05394       res = -1;
05395       goto done;
05396    }
05397 
05398    switch (condition) {
05399    case AST_CONTROL_HOLD:
05400       if (strcasecmp(pvt->mohinterpret, "passthrough")) {
05401          ast_moh_start(c, data, pvt->mohinterpret);
05402          goto done;
05403       }
05404       break;
05405    case AST_CONTROL_UNHOLD:
05406       if (strcasecmp(pvt->mohinterpret, "passthrough")) {
05407          ast_moh_stop(c);
05408          goto done;
05409       }
05410    }
05411 
05412    res = send_command(pvt, AST_FRAME_CONTROL, condition, 0, data, datalen, -1);
05413 
05414 done:
05415    ast_mutex_unlock(&iaxsl[callno]);
05416 
05417    return res;
05418 }
05419    
05420 static int iax2_transfer(struct ast_channel *c, const char *dest)
05421 {
05422    unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
05423    struct iax_ie_data ied = { "", };
05424    char tmp[256], *context;
05425    ast_copy_string(tmp, dest, sizeof(tmp));
05426    context = strchr(tmp, '@');
05427    if (context) {
05428       *context = '\0';
05429       context++;
05430    }
05431    iax_ie_append_str(&ied, IAX_IE_CALLED_NUMBER, tmp);
05432    if (context)
05433       iax_ie_append_str(&ied, IAX_IE_CALLED_CONTEXT, context);
05434    ast_debug(1, "Transferring '%s' to '%s'\n", c->name, dest);
05435    return send_command_locked(callno, AST_FRAME_IAX, IAX_COMMAND_TRANSFER, 0, ied.buf, ied.pos, -1);
05436 }
05437    
05438 static int iax2_getpeertrunk(struct sockaddr_in sin)
05439 {
05440    struct iax2_peer *peer;
05441    int res = 0;
05442    struct ao2_iterator i;
05443 
05444    i = ao2_iterator_init(peers, 0);
05445    while ((peer = ao2_iterator_next(&i))) {
05446       if ((peer->addr.sin_addr.s_addr == sin.sin_addr.s_addr) &&
05447           (peer->addr.sin_port == sin.sin_port)) {
05448          res = ast_test_flag(peer, IAX_TRUNK);
05449          peer_unref(peer);
05450          break;
05451       }
05452       peer_unref(peer);
05453    }
05454    ao2_iterator_destroy(&i);
05455 
05456    return res;
05457 }
05458 
05459 /*! \brief  Create new call, interface with the PBX core */
05460 static struct ast_channel *ast_iax2_new(int callno, int state, int capability)
05461 {
05462    struct ast_channel *tmp;
05463    struct chan_iax2_pvt *i;
05464    struct ast_variable *v = NULL;
05465 
05466    if (!(i = iaxs[callno])) {
05467       ast_log(LOG_WARNING, "No IAX2 pvt found for callno '%d' !\n", callno);
05468       return NULL;
05469    }
05470 
05471    /* Don't hold call lock */
05472    ast_mutex_unlock(&iaxsl[callno]);
05473    tmp = ast_channel_alloc(1, state, i->cid_num, i->cid_name, i->accountcode, i->exten, i->context, i->amaflags, "IAX2/%s-%d", i->host, i->callno);
05474    ast_mutex_lock(&iaxsl[callno]);
05475    if (i != iaxs[callno]) {
05476       if (tmp) {
05477          /* unlock and relock iaxsl[callno] to preserve locking order */
05478          ast_mutex_unlock(&iaxsl[callno]);
05479          ast_channel_free(tmp);
05480          ast_mutex_lock(&iaxsl[callno]);
05481       }
05482       return NULL;
05483    }
05484    iax2_ami_channelupdate(i);
05485    if (!tmp)
05486       return NULL;
05487    tmp->tech = &iax2_tech;
05488    /* We can support any format by default, until we get restricted */
05489    tmp->nativeformats = capability;
05490    tmp->readformat = tmp->rawreadformat = ast_best_codec(capability);
05491    tmp->writeformat = tmp->rawwriteformat = ast_best_codec(capability);
05492    tmp->tech_pvt = CALLNO_TO_PTR(i->callno);
05493 
05494    if (!ast_strlen_zero(i->parkinglot))
05495       ast_string_field_set(tmp, parkinglot, i->parkinglot);
05496    /* Don't use ast_set_callerid() here because it will
05497     * generate a NewCallerID event before the NewChannel event */
05498    if (!ast_strlen_zero(i->ani))
05499       tmp->cid.cid_ani = ast_strdup(i->ani);
05500    else
05501       tmp->cid.cid_ani = ast_strdup(i->cid_num);
05502    tmp->cid.cid_dnid = ast_strdup(i->dnid);
05503    tmp->cid.cid_rdnis = ast_strdup(i->rdnis);
05504    tmp->cid.cid_pres = i->calling_pres;
05505    tmp->cid.cid_ton = i->calling_ton;
05506    tmp->cid.cid_tns = i->calling_tns;
05507    if (!ast_strlen_zero(i->language))
05508       ast_string_field_set(tmp, language, i->language);
05509    if (!ast_strlen_zero(i->accountcode))
05510       ast_string_field_set(tmp, accountcode, i->accountcode);
05511    if (i->amaflags)
05512       tmp->amaflags = i->amaflags;
05513    ast_copy_string(tmp->context, i->context, sizeof(tmp->context));
05514    ast_copy_string(tmp->exten, i->exten, sizeof(tmp->exten));
05515    if (i->adsi)
05516       tmp->adsicpe = i->peeradsicpe;
05517    else
05518       tmp->adsicpe = AST_ADSI_UNAVAILABLE;
05519    i->owner = tmp;
05520    i->capability = capability;
05521 
05522    /* Set inherited variables */
05523    if (i->vars) {
05524       for (v = i->vars ; v ; v = v->next)
05525          pbx_builtin_setvar_helper(tmp, v->name, v->value);
05526    }
05527    if (i->iaxvars) {
05528       struct ast_datastore *variablestore;
05529       struct ast_variable *var, *prev = NULL;
05530       AST_LIST_HEAD(, ast_var_t) *varlist;
05531       ast_debug(1, "Loading up the channel with IAXVARs\n");
05532       varlist = ast_calloc(1, sizeof(*varlist));
05533       variablestore = ast_datastore_alloc(&iax2_variable_datastore_info, NULL);
05534       if (variablestore && varlist) {
05535          variablestore->data = varlist;
05536          variablestore->inheritance = DATASTORE_INHERIT_FOREVER;
05537          AST_LIST_HEAD_INIT(varlist);
05538          for (var = i->iaxvars; var; var = var->next) {
05539             struct ast_var_t *newvar = ast_var_assign(var->name, var->value);
05540             if (prev)
05541                ast_free(prev);
05542             prev = var;
05543             if (!newvar) {
05544                /* Don't abort list traversal, as this would leave i->iaxvars in an inconsistent state. */
05545                ast_log(LOG_ERROR, "Memory allocation error while processing IAX2 variables\n");
05546             } else {
05547                AST_LIST_INSERT_TAIL(varlist, newvar, entries);
05548             }
05549          }
05550          if (prev)
05551             ast_free(prev);
05552          i->iaxvars = NULL;
05553          ast_channel_datastore_add(i->owner, variablestore);
05554       } else {
05555          if (variablestore) {
05556             ast_datastore_free(variablestore);
05557          }
05558          if (varlist) {
05559             ast_free(varlist);
05560          }
05561       }
05562    }
05563 
05564    if (state != AST_STATE_DOWN) {
05565       if (ast_pbx_start(tmp)) {
05566          ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
05567          ast_hangup(tmp);
05568          i->owner = NULL;
05569          return NULL;
05570       }
05571    }
05572 
05573    ast_module_ref(ast_module_info->self);
05574    return tmp;
05575 }
05576 
05577 static unsigned int calc_txpeerstamp(struct iax2_trunk_peer *tpeer, int sampms, struct timeval *now)
05578 {
05579    unsigned long int mssincetx; /* unsigned to handle overflows */
05580    long int ms, pred;
05581 
05582    tpeer->trunkact = *now;
05583    mssincetx = ast_tvdiff_ms(*now, tpeer->lasttxtime);
05584    if (mssincetx > 5000 || ast_tvzero(tpeer->txtrunktime)) {
05585       /* If it's been at least 5 seconds since the last time we transmitted on this trunk, reset our timers */
05586       tpeer->txtrunktime = *now;
05587       tpeer->lastsent = 999999;
05588    }
05589    /* Update last transmit time now */
05590    tpeer->lasttxtime = *now;
05591    
05592    /* Calculate ms offset */
05593    ms = ast_tvdiff_ms(*now, tpeer->txtrunktime);
05594    /* Predict from last value */
05595    pred = tpeer->lastsent + sampms;
05596    if (abs(ms - pred) < MAX_TIMESTAMP_SKEW)
05597       ms = pred;
05598    
05599    /* We never send the same timestamp twice, so fudge a little if we must */
05600    if (ms == tpeer->lastsent)
05601       ms = tpeer->lastsent + 1;
05602    tpeer->lastsent = ms;
05603    return ms;
05604 }
05605 
05606 static unsigned int fix_peerts(struct timeval *rxtrunktime, int callno, unsigned int ts)
05607 {
05608    long ms; /* NOT unsigned */
05609    if (ast_tvzero(iaxs[callno]->rxcore)) {
05610       /* Initialize rxcore time if appropriate */
05611       iaxs[callno]->rxcore = ast_tvnow();
05612       /* Round to nearest 20ms so traces look pretty */
05613       iaxs[callno]->rxcore.tv_usec -= iaxs[callno]->rxcore.tv_usec % 20000;
05614    }
05615    /* Calculate difference between trunk and channel */
05616    ms = ast_tvdiff_ms(*rxtrunktime, iaxs[callno]->rxcore);
05617    /* Return as the sum of trunk time and the difference between trunk and real time */
05618    return ms + ts;
05619 }
05620 
05621 static unsigned int calc_timestamp(struct chan_iax2_pvt *p, unsigned int ts, struct ast_frame *f)
05622 {
05623    int ms;
05624    int voice = 0;
05625    int genuine = 0;
05626    int adjust;
05627    int rate = ast_format_rate(f->subclass) / 1000;
05628    struct timeval *delivery = NULL;
05629 
05630 
05631    /* What sort of frame do we have?: voice is self-explanatory
05632       "genuine" means an IAX frame - things like LAGRQ/RP, PING/PONG, ACK
05633       non-genuine frames are CONTROL frames [ringing etc], DTMF
05634       The "genuine" distinction is needed because genuine frames must get a clock-based timestamp,
05635       the others need a timestamp slaved to the voice frames so that they go in sequence
05636    */
05637    if (f) {
05638       if (f->frametype == AST_FRAME_VOICE) {
05639          voice = 1;
05640          delivery = &f->delivery;
05641       } else if (f->frametype == AST_FRAME_IAX) {
05642          genuine = 1;
05643       } else if (f->frametype == AST_FRAME_CNG) {
05644          p->notsilenttx = 0;  
05645       }
05646    }
05647    if (ast_tvzero(p->offset)) {
05648       p->offset = ast_tvnow();
05649       /* Round to nearest 20ms for nice looking traces */
05650       p->offset.tv_usec -= p->offset.tv_usec % 20000;
05651    }
05652    /* If the timestamp is specified, just send it as is */
05653    if (ts)
05654       return ts;
05655    /* If we have a time that the frame arrived, always use it to make our timestamp */
05656    if (delivery && !ast_tvzero(*delivery)) {
05657       ms = ast_tvdiff_ms(*delivery, p->offset);
05658       if (ms < 0) {
05659          ms = 0;
05660       }
05661       if (iaxdebug)
05662          ast_debug(3, "calc_timestamp: call %d/%d: Timestamp slaved to delivery time\n", p->callno, iaxs[p->callno]->peercallno);
05663    } else {
05664       ms = ast_tvdiff_ms(ast_tvnow(), p->offset);
05665       if (ms < 0)
05666          ms = 0;
05667       if (voice) {
05668          /* On a voice frame, use predicted values if appropriate */
05669          if (p->notsilenttx && abs(ms - p->nextpred) <= MAX_TIMESTAMP_SKEW) {
05670             /* Adjust our txcore, keeping voice and non-voice synchronized */
05671             /* AN EXPLANATION:
05672                When we send voice, we usually send "calculated" timestamps worked out
05673                on the basis of the number of samples sent. When we send other frames,
05674                we usually send timestamps worked out from the real clock.
05675                The problem is that they can tend to drift out of step because the 
05676                   source channel's clock and our clock may not be exactly at the same rate.
05677                We fix this by continuously "tweaking" p->offset.  p->offset is "time zero"
05678                for this call.  Moving it adjusts timestamps for non-voice frames.
05679                We make the adjustment in the style of a moving average.  Each time we
05680                adjust p->offset by 10% of the difference between our clock-derived
05681                timestamp and the predicted timestamp.  That's why you see "10000"
05682                below even though IAX2 timestamps are in milliseconds.
05683                The use of a moving average avoids offset moving too radically.
05684                Generally, "adjust" roams back and forth around 0, with offset hardly
05685                changing at all.  But if a consistent different starts to develop it
05686                will be eliminated over the course of 10 frames (200-300msecs) 
05687             */
05688             adjust = (ms - p->nextpred);
05689             if (adjust < 0)
05690                p->offset = ast_tvsub(p->offset, ast_samp2tv(abs(adjust), 10000));
05691             else if (adjust > 0)
05692                p->offset = ast_tvadd(p->offset, ast_samp2tv(adjust, 10000));
05693 
05694             if (!p->nextpred) {
05695                p->nextpred = ms; /*f->samples / rate;*/
05696                if (p->nextpred <= p->lastsent)
05697                   p->nextpred = p->lastsent + 3;
05698             }
05699             ms = p->nextpred;
05700          } else {
05701                 /* in this case, just use the actual
05702             * time, since we're either way off
05703             * (shouldn't happen), or we're  ending a
05704             * silent period -- and seed the next
05705             * predicted time.  Also, round ms to the
05706             * next multiple of frame size (so our
05707             * silent periods are multiples of
05708             * frame size too) */
05709 
05710             if (iaxdebug && abs(ms - p->nextpred) > MAX_TIMESTAMP_SKEW )
05711                ast_debug(1, "predicted timestamp skew (%u) > max (%u), using real ts instead.\n",
05712                   abs(ms - p->nextpred), MAX_TIMESTAMP_SKEW);
05713 
05714             if (f->samples >= rate) /* check to make sure we dont core dump */
05715             {
05716                int diff = ms % (f->samples / rate);
05717                if (diff)
05718                    ms += f->samples/rate - diff;
05719             }
05720 
05721             p->nextpred = ms;
05722             p->notsilenttx = 1;
05723          }
05724       } else if ( f->frametype == AST_FRAME_VIDEO ) {
05725          /*
05726          * IAX2 draft 03 says that timestamps MUST be in order.
05727          * It does not say anything about several frames having the same timestamp
05728          * When transporting video, we can have a frame that spans multiple iax packets
05729          * (so called slices), so it would make sense to use the same timestamp for all of
05730          * them
05731          * We do want to make sure that frames don't go backwards though
05732          */
05733          if ( (unsigned int)ms < p->lastsent )
05734             ms = p->lastsent;
05735       } else {
05736          /* On a dataframe, use last value + 3 (to accomodate jitter buffer shrinking) if appropriate unless
05737             it's a genuine frame */
05738          if (genuine) {
05739             /* genuine (IAX LAGRQ etc) must keep their clock-based stamps */
05740             if (ms <= p->lastsent)
05741                ms = p->lastsent + 3;
05742          } else if (abs(ms - p->lastsent) <= MAX_TIMESTAMP_SKEW) {
05743             /* non-genuine frames (!?) (DTMF, CONTROL) should be pulled into the predicted stream stamps */
05744             ms = p->lastsent + 3;
05745          }
05746       }
05747    }
05748    p->lastsent = ms;
05749    if (voice)
05750       p->nextpred = p->nextpred + f->samples / rate;
05751    return ms;
05752 }
05753 
05754 static unsigned int calc_rxstamp(struct chan_iax2_pvt *p, unsigned int offset)
05755 {
05756    /* Returns where in "receive time" we are.  That is, how many ms
05757       since we received (or would have received) the frame with timestamp 0 */
05758    int ms;
05759 #ifdef IAXTESTS
05760    int jit;
05761 #endif /* IAXTESTS */
05762    /* Setup rxcore if necessary */
05763    if (ast_tvzero(p->rxcore)) {
05764       p->rxcore = ast_tvnow();
05765       if (iaxdebug)
05766          ast_debug(1, "calc_rxstamp: call=%d: rxcore set to %d.%6.6d - %dms\n",
05767                p->callno, (int)(p->rxcore.tv_sec), (int)(p->rxcore.tv_usec), offset);
05768       p->rxcore = ast_tvsub(p->rxcore, ast_samp2tv(offset, 1000));
05769 #if 1
05770       if (iaxdebug)
05771          ast_debug(1, "calc_rxstamp: call=%d: works out as %d.%6.6d\n",
05772                p->callno, (int)(p->rxcore.tv_sec),(int)( p->rxcore.tv_usec));
05773 #endif
05774    }
05775 
05776    ms = ast_tvdiff_ms(ast_tvnow(), p->rxcore);
05777 #ifdef IAXTESTS
05778    if (test_jit) {
05779       if (!test_jitpct || ((100.0 * ast_random() / (RAND_MAX + 1.0)) < test_jitpct)) {
05780          jit = (int)((float)test_jit * ast_random() / (RAND_MAX + 1.0));
05781          if ((int)(2.0 * ast_random() / (RAND_MAX + 1.0)))
05782             jit = -jit;
05783          ms += jit;
05784       }
05785    }
05786    if (test_late) {
05787       ms += test_late;
05788       test_late = 0;
05789    }
05790 #endif /* IAXTESTS */
05791    return ms;
05792 }
05793 
05794 static struct iax2_trunk_peer *find_tpeer(struct sockaddr_in *sin, int fd)
05795 {
05796    struct iax2_trunk_peer *tpeer = NULL;
05797    
05798    /* Finds and locks trunk peer */
05799    AST_LIST_LOCK(&tpeers);
05800 
05801    AST_LIST_TRAVERSE(&tpeers, tpeer, list) {
05802       if (!inaddrcmp(&tpeer->addr, sin)) {
05803          ast_mutex_lock(&tpeer->lock);
05804          break;
05805       }
05806    }
05807 
05808    if (!tpeer) {
05809       if ((tpeer = ast_calloc(1, sizeof(*tpeer)))) {
05810          ast_mutex_init(&tpeer->lock);
05811          tpeer->lastsent = 9999;
05812          memcpy(&tpeer->addr, sin, sizeof(tpeer->addr));
05813          tpeer->trunkact = ast_tvnow();
05814          ast_mutex_lock(&tpeer->lock);
05815          tpeer->sockfd = fd;
05816 #ifdef SO_NO_CHECK
05817          setsockopt(tpeer->sockfd, SOL_SOCKET, SO_NO_CHECK, &nochecksums, sizeof(nochecksums));
05818 #endif
05819          ast_debug(1, "Created trunk peer for '%s:%d'\n", ast_inet_ntoa(tpeer->addr.sin_addr), ntohs(tpeer->addr.sin_port));
05820          AST_LIST_INSERT_TAIL(&tpeers, tpeer, list);
05821       }
05822    }
05823 
05824    AST_LIST_UNLOCK(&tpeers);
05825 
05826    return tpeer;
05827 }
05828 
05829 static int iax2_trunk_queue(struct chan_iax2_pvt *pvt, struct iax_frame *fr)
05830 {
05831    struct ast_frame *f;
05832    struct iax2_trunk_peer *tpeer;
05833    void *tmp, *ptr;
05834    struct timeval now;
05835    int res; 
05836    struct ast_iax2_meta_trunk_entry *met;
05837    struct ast_iax2_meta_trunk_mini *mtm;
05838 
05839    f = &fr->af;
05840    tpeer = find_tpeer(&pvt->addr, pvt->sockfd);
05841    if (tpeer) {
05842       if (tpeer->trunkdatalen + f->datalen + 4 >= tpeer->trunkdataalloc) {
05843          /* Need to reallocate space */
05844          if (tpeer->trunkdataalloc < trunkmaxsize) {
05845             if (!(tmp = ast_realloc(tpeer->trunkdata, tpeer->trunkdataalloc + DEFAULT_TRUNKDATA + IAX2_TRUNK_PREFACE))) {
05846                ast_mutex_unlock(&tpeer->lock);
05847                return -1;
05848             }
05849             
05850             tpeer->trunkdataalloc += DEFAULT_TRUNKDATA;
05851             tpeer->trunkdata = tmp;
05852             ast_debug(1, "Expanded trunk '%s:%d' to %d bytes\n", ast_inet_ntoa(tpeer->addr.sin_addr), ntohs(tpeer->addr.sin_port), tpeer->trunkdataalloc);
05853          } else {
05854             ast_log(LOG_WARNING, "Maximum trunk data space exceeded to %s:%d\n", ast_inet_ntoa(tpeer->addr.sin_addr), ntohs(tpeer->addr.sin_port));
05855             ast_mutex_unlock(&tpeer->lock);
05856             return -1;
05857          }
05858       }
05859 
05860       /* Append to meta frame */
05861       ptr = tpeer->trunkdata + IAX2_TRUNK_PREFACE + tpeer->trunkdatalen;
05862       if (ast_test_flag(&globalflags, IAX_TRUNKTIMESTAMPS)) {
05863          mtm = (struct ast_iax2_meta_trunk_mini *)ptr;
05864          mtm->len = htons(f->datalen);
05865          mtm->mini.callno = htons(pvt->callno);
05866          mtm->mini.ts = htons(0xffff & fr->ts);
05867          ptr += sizeof(struct ast_iax2_meta_trunk_mini);
05868          tpeer->trunkdatalen += sizeof(struct ast_iax2_meta_trunk_mini);
05869       } else {
05870          met = (struct ast_iax2_meta_trunk_entry *)ptr;
05871          /* Store call number and length in meta header */
05872          met->callno = htons(pvt->callno);
05873          met->len = htons(f->datalen);
05874          /* Advance pointers/decrease length past trunk entry header */
05875          ptr += sizeof(struct ast_iax2_meta_trunk_entry);
05876          tpeer->trunkdatalen += sizeof(struct ast_iax2_meta_trunk_entry);
05877       }
05878       /* Copy actual trunk data */
05879       memcpy(ptr, f->data.ptr, f->datalen);
05880       tpeer->trunkdatalen += f->datalen;
05881 
05882       tpeer->calls++;
05883 
05884       /* track the largest mtu we actually have sent */
05885       if (tpeer->trunkdatalen + f->datalen + 4 > trunk_maxmtu) 
05886          trunk_maxmtu = tpeer->trunkdatalen + f->datalen + 4 ; 
05887 
05888       /* if we have enough for a full MTU, ship it now without waiting */
05889       if (global_max_trunk_mtu > 0 && tpeer->trunkdatalen + f->datalen + 4 >= global_max_trunk_mtu) {
05890          now = ast_tvnow();
05891          res = send_trunk(tpeer, &now); 
05892          trunk_untimed ++; 
05893       }
05894 
05895       ast_mutex_unlock(&tpeer->lock);
05896    }
05897    return 0;
05898 }
05899 
05900 /* IAX2 encryption requires 16 to 32 bytes of random padding to be present
05901  * before the encryption data.  This function randomizes that data. */
05902 static void build_rand_pad(unsigned char *buf, ssize_t len)
05903 {
05904    long tmp;
05905    for (tmp = ast_random(); len > 0; tmp = ast_random()) {
05906       memcpy(buf, (unsigned char *) &tmp, (len > sizeof(tmp)) ? sizeof(tmp) : len);
05907       buf += sizeof(tmp);
05908       len -= sizeof(tmp);
05909    }
05910 }
05911 
05912 static void build_encryption_keys(const unsigned char *digest, struct chan_iax2_pvt *pvt)
05913 {
05914    build_ecx_key(digest, pvt);
05915    ast_aes_decrypt_key(digest, &pvt->dcx);
05916 }
05917 
05918 static void build_ecx_key(const unsigned char *digest, struct chan_iax2_pvt *pvt)
05919 {
05920    /* it is required to hold the corresponding decrypt key to our encrypt key
05921     * in the pvt struct because queued frames occasionally need to be decrypted and
05922     * re-encrypted when updated for a retransmission */
05923    build_rand_pad(pvt->semirand, sizeof(pvt->semirand));
05924    ast_aes_encrypt_key(digest, &pvt->ecx);
05925    ast_aes_decrypt_key(digest, &pvt->mydcx);
05926 }
05927 
05928 static void memcpy_decrypt(unsigned char *dst, const unsigned char *src, int len, ast_aes_decrypt_key *dcx)
05929 {
05930 #if 0
05931    /* Debug with "fake encryption" */
05932    int x;
05933    if (len % 16)
05934       ast_log(LOG_WARNING, "len should be multiple of 16, not %d!\n", len);
05935    for (x=0;x<len;x++)
05936       dst[x] = src[x] ^ 0xff;
05937 #else 
05938    unsigned char lastblock[16] = { 0 };
05939    int x;
05940    while(len > 0) {
05941       ast_aes_decrypt(src, dst, dcx);
05942       for (x=0;x<16;x++)
05943          dst[x] ^= lastblock[x];
05944       memcpy(lastblock, src, sizeof(lastblock));
05945       dst += 16;
05946       src += 16;
05947       len -= 16;
05948    }
05949 #endif
05950 }
05951 
05952 static void memcpy_encrypt(unsigned char *dst, const unsigned char *src, int len, ast_aes_encrypt_key *ecx)
05953 {
05954 #if 0
05955    /* Debug with "fake encryption" */
05956    int x;
05957    if (len % 16)
05958       ast_log(LOG_WARNING, "len should be multiple of 16, not %d!\n", len);
05959    for (x=0;x<len;x++)
05960       dst[x] = src[x] ^ 0xff;
05961 #else
05962    unsigned char curblock[16] = { 0 };
05963    int x;
05964    while(len > 0) {
05965       for (x=0;x<16;x++)
05966          curblock[x] ^= src[x];
05967       ast_aes_encrypt(curblock, dst, ecx);
05968       memcpy(curblock, dst, sizeof(curblock)); 
05969       dst += 16;
05970       src += 16;
05971       len -= 16;
05972    }
05973 #endif
05974 }
05975 
05976 static int decode_frame(ast_aes_decrypt_key *dcx, struct ast_iax2_full_hdr *fh, struct ast_frame *f, int *datalen)
05977 {
05978    int padding;
05979    unsigned char *workspace;
05980 
05981    workspace = alloca(*datalen);
05982    memset(f, 0, sizeof(*f));
05983    if (ntohs(fh->scallno) & IAX_FLAG_FULL) {
05984       struct ast_iax2_full_enc_hdr *efh = (struct ast_iax2_full_enc_hdr *)fh;
05985       if (*datalen < 16 + sizeof(struct ast_iax2_full_hdr))
05986          return -1;
05987       /* Decrypt */
05988       memcpy_decrypt(workspace, efh->encdata, *datalen - sizeof(struct ast_iax2_full_enc_hdr), dcx);
05989 
05990       padding = 16 + (workspace[15] & 0x0f);
05991       if (iaxdebug)
05992          ast_debug(1, "Decoding full frame with length %d (padding = %d) (15=%02x)\n", *datalen, padding, workspace[15]);
05993       if (*datalen < padding + sizeof(struct ast_iax2_full_hdr))
05994          return -1;
05995 
05996       *datalen -= padding;
05997       memcpy(efh->encdata, workspace + padding, *datalen - sizeof(struct ast_iax2_full_enc_hdr));
05998       f->frametype = fh->type;
05999       if (f->frametype == AST_FRAME_VIDEO) {
06000          f->subclass = uncompress_subclass(fh->csub & ~0x40) | ((fh->csub >> 6) & 0x1);
06001       } else {
06002          f->subclass = uncompress_subclass(fh->csub);
06003       }
06004    } else {
06005       struct ast_iax2_mini_enc_hdr *efh = (struct ast_iax2_mini_enc_hdr *)fh;
06006       if (iaxdebug)
06007          ast_debug(1, "Decoding mini with length %d\n", *datalen);
06008       if (*datalen < 16 + sizeof(struct ast_iax2_mini_hdr))
06009          return -1;
06010       /* Decrypt */
06011       memcpy_decrypt(workspace, efh->encdata, *datalen - sizeof(struct ast_iax2_mini_enc_hdr), dcx);
06012       padding = 16 + (workspace[15] & 0x0f);
06013       if (*datalen < padding + sizeof(struct ast_iax2_mini_hdr))
06014          return -1;
06015       *datalen -= padding;
06016       memcpy(efh->encdata, workspace + padding, *datalen - sizeof(struct ast_iax2_mini_enc_hdr));
06017    }
06018    return 0;
06019 }
06020 
06021 static int encrypt_frame(ast_aes_encrypt_key *ecx, struct ast_iax2_full_hdr *fh, unsigned char *poo, int *datalen)
06022 {
06023    int padding;
06024    unsigned char *workspace;
06025    workspace = alloca(*datalen + 32);
06026    if (!workspace)
06027       return -1;
06028    if (ntohs(fh->scallno) & IAX_FLAG_FULL) {
06029       struct ast_iax2_full_enc_hdr *efh = (struct ast_iax2_full_enc_hdr *)fh;
06030       if (iaxdebug)
06031          ast_debug(1, "Encoding full frame %d/%d with length %d\n", fh->type, fh->csub, *datalen);
06032       padding = 16 - ((*datalen - sizeof(struct ast_iax2_full_enc_hdr)) % 16);
06033       padding = 16 + (padding & 0xf);
06034       memcpy(workspace, poo, padding);
06035       memcpy(workspace + padding, efh->encdata, *datalen - sizeof(struct ast_iax2_full_enc_hdr));
06036       workspace[15] &= 0xf0;
06037       workspace[15] |= (padding & 0xf);
06038       if (iaxdebug)
06039          ast_debug(1, "Encoding full frame %d/%d with length %d + %d padding (15=%02x)\n", fh->type, fh->csub, *datalen, padding, workspace[15]);
06040       *datalen += padding;
06041       memcpy_encrypt(efh->encdata, workspace, *datalen - sizeof(struct ast_iax2_full_enc_hdr), ecx);
06042       if (*datalen >= 32 + sizeof(struct ast_iax2_full_enc_hdr))
06043          memcpy(poo, workspace + *datalen - 32, 32);
06044    } else {
06045       struct ast_iax2_mini_enc_hdr *efh = (struct ast_iax2_mini_enc_hdr *)fh;
06046       if (iaxdebug)
06047          ast_debug(1, "Encoding mini frame with length %d\n", *datalen);
06048       padding = 16 - ((*datalen - sizeof(struct ast_iax2_mini_enc_hdr)) % 16);
06049       padding = 16 + (padding & 0xf);
06050       memcpy(workspace, poo, padding);
06051       memcpy(workspace + padding, efh->encdata, *datalen - sizeof(struct ast_iax2_mini_enc_hdr));
06052       workspace[15] &= 0xf0;
06053       workspace[15] |= (padding & 0x0f);
06054       *datalen += padding;
06055       memcpy_encrypt(efh->encdata, workspace, *datalen - sizeof(struct ast_iax2_mini_enc_hdr), ecx);
06056       if (*datalen >= 32 + sizeof(struct ast_iax2_mini_enc_hdr))
06057          memcpy(poo, workspace + *datalen - 32, 32);
06058    }
06059    return 0;
06060 }
06061 
06062 static int decrypt_frame(int callno, struct ast_iax2_full_hdr *fh, struct ast_frame *f, int *datalen)
06063 {
06064    int res=-1;
06065    if (!ast_test_flag(iaxs[callno], IAX_KEYPOPULATED)) {
06066       /* Search for possible keys, given secrets */
06067       struct MD5Context md5;
06068       unsigned char digest[16];
06069       char *tmppw, *stringp;
06070       
06071       tmppw = ast_strdupa(iaxs[callno]->secret);
06072       stringp = tmppw;
06073       while ((tmppw = strsep(&stringp, ";"))) {
06074          MD5Init(&md5);
06075          MD5Update(&md5, (unsigned char *)iaxs[callno]->challenge, strlen(iaxs[callno]->challenge));
06076          MD5Update(&md5, (unsigned char *)tmppw, strlen(tmppw));
06077          MD5Final(digest, &md5);
06078          build_encryption_keys(digest, iaxs[callno]);
06079          res = decode_frame(&iaxs[callno]->dcx, fh, f, datalen);
06080          if (!res) {
06081             ast_set_flag(iaxs[callno], IAX_KEYPOPULATED);
06082             break;
06083          }
06084       }
06085    } else 
06086       res = decode_frame(&iaxs[callno]->dcx, fh, f, datalen);
06087    return res;
06088 }
06089 
06090 static int iax2_send(struct chan_iax2_pvt *pvt, struct ast_frame *f, unsigned int ts, int seqno, int now, int transfer, int final)
06091 {
06092    /* Queue a packet for delivery on a given private structure.  Use "ts" for
06093       timestamp, or calculate if ts is 0.  Send immediately without retransmission
06094       or delayed, with retransmission */
06095    struct ast_iax2_full_hdr *fh;
06096    struct ast_iax2_mini_hdr *mh;
06097    struct ast_iax2_video_hdr *vh;
06098    struct {
06099       struct iax_frame fr2;
06100       unsigned char buffer[4096];
06101    } frb;
06102    struct iax_frame *fr;
06103    int res;
06104    int sendmini=0;
06105    unsigned int lastsent;
06106    unsigned int fts;
06107 
06108    frb.fr2.afdatalen = sizeof(frb.buffer);
06109 
06110    if (!pvt) {
06111       ast_log(LOG_WARNING, "No private structure for packet?\n");
06112       return -1;
06113    }
06114    
06115    lastsent = pvt->lastsent;
06116 
06117    /* Calculate actual timestamp */
06118    fts = calc_timestamp(pvt, ts, f);
06119 
06120    /* Bail here if this is an "interp" frame; we don't want or need to send these placeholders out
06121     * (the endpoint should detect the lost packet itself).  But, we want to do this here, so that we
06122     * increment the "predicted timestamps" for voice, if we're predicting */
06123    if(f->frametype == AST_FRAME_VOICE && f->datalen == 0)
06124       return 0;
06125 #if 0
06126    ast_log(LOG_NOTICE, 
06127       "f->frametype %c= AST_FRAME_VOICE, %sencrypted, %srotation scheduled...\n",
06128       *("=!" + (f->frametype == AST_FRAME_VOICE)),
06129       IAX_CALLENCRYPTED(pvt) ? "" : "not ",
06130       pvt->keyrotateid != -1 ? "" : "no "
06131    );
06132 #endif
06133    if (pvt->keyrotateid == -1 && f->frametype == AST_FRAME_VOICE && IAX_CALLENCRYPTED(pvt)) {
06134       iax2_key_rotate(pvt);
06135    }
06136 
06137    if ((ast_test_flag(pvt, IAX_TRUNK) || 
06138          (((fts & 0xFFFF0000L) == (lastsent & 0xFFFF0000L)) ||
06139          ((fts & 0xFFFF0000L) == ((lastsent + 0x10000) & 0xFFFF0000L))))
06140       /* High two bytes are the same on timestamp, or sending on a trunk */ &&
06141        (f->frametype == AST_FRAME_VOICE) 
06142       /* is a voice frame */ &&
06143       (f->subclass == pvt->svoiceformat) 
06144       /* is the same type */ ) {
06145          /* Force immediate rather than delayed transmission */
06146          now = 1;
06147          /* Mark that mini-style frame is appropriate */
06148          sendmini = 1;
06149    }
06150    if ( f->frametype == AST_FRAME_VIDEO ) {
06151       /*
06152        * If the lower 15 bits of the timestamp roll over, or if
06153        * the video format changed then send a full frame.
06154        * Otherwise send a mini video frame
06155        */
06156       if (((fts & 0xFFFF8000L) == (pvt->lastvsent & 0xFFFF8000L)) &&
06157           ((f->subclass & ~0x1) == pvt->svideoformat)
06158          ) {
06159          now = 1;
06160          sendmini = 1;
06161       } else {
06162          now = 0;
06163          sendmini = 0;
06164       }
06165       pvt->lastvsent = fts;
06166    }
06167    if (f->frametype == AST_FRAME_IAX) {
06168       /* 0x8000 marks this message as TX:, this bit will be stripped later */
06169       pvt->last_iax_message = f->subclass | MARK_IAX_SUBCLASS_TX;
06170       if (!pvt->first_iax_message) {
06171          pvt->first_iax_message = pvt->last_iax_message;
06172       }
06173    }
06174    /* Allocate an iax_frame */
06175    if (now) {
06176       fr = &frb.fr2;
06177    } else
06178       fr = iax_frame_new(DIRECTION_OUTGRESS, ast_test_flag(pvt, IAX_ENCRYPTED) ? f->datalen + 32 : f->datalen, (f->frametype == AST_FRAME_VOICE) || (f->frametype == AST_FRAME_VIDEO));
06179    if (!fr) {
06180       ast_log(LOG_WARNING, "Out of memory\n");
06181       return -1;
06182    }
06183    /* Copy our prospective frame into our immediate or retransmitted wrapper */
06184    iax_frame_wrap(fr, f);
06185 
06186    fr->ts = fts;
06187    fr->callno = pvt->callno;
06188    fr->transfer = transfer;
06189    fr->final = final;
06190    fr->encmethods = 0;
06191    if (!sendmini) {
06192       /* We need a full frame */
06193       if (seqno > -1)
06194          fr->oseqno = seqno;
06195       else
06196          fr->oseqno = pvt->oseqno++;
06197       fr->iseqno = pvt->iseqno;
06198       fh = (struct ast_iax2_full_hdr *)(fr->af.data.ptr - sizeof(struct ast_iax2_full_hdr));
06199       fh->scallno = htons(fr->callno | IAX_FLAG_FULL);
06200       fh->ts = htonl(fr->ts);
06201       fh->oseqno = fr->oseqno;
06202       if (transfer) {
06203          fh->iseqno = 0;
06204       } else
06205          fh->iseqno = fr->iseqno;
06206       /* Keep track of the last thing we've acknowledged */
06207       if (!transfer)
06208          pvt->aseqno = fr->iseqno;
06209       fh->type = fr->af.frametype & 0xFF;
06210       if (fr->af.frametype == AST_FRAME_VIDEO)
06211          fh->csub = compress_subclass(fr->af.subclass & ~0x1) | ((fr->af.subclass & 0x1) << 6);
06212       else
06213          fh->csub = compress_subclass(fr->af.subclass);
06214       if (transfer) {
06215          fr->dcallno = pvt->transfercallno;
06216       } else
06217          fr->dcallno = pvt->peercallno;
06218       fh->dcallno = htons(fr->dcallno);
06219       fr->datalen = fr->af.datalen + sizeof(struct ast_iax2_full_hdr);
06220       fr->data = fh;
06221       fr->retries = 0;
06222       /* Retry after 2x the ping time has passed */
06223       fr->retrytime = pvt->pingtime * 2;
06224       if (fr->retrytime < MIN_RETRY_TIME)
06225          fr->retrytime = MIN_RETRY_TIME;
06226       if (fr->retrytime > MAX_RETRY_TIME)
06227          fr->retrytime = MAX_RETRY_TIME;
06228       /* Acks' don't get retried */
06229       if ((f->frametype == AST_FRAME_IAX) && (f->subclass == IAX_COMMAND_ACK))
06230          fr->retries = -1;
06231       else if (f->frametype == AST_FRAME_VOICE)
06232          pvt->svoiceformat = f->subclass;
06233       else if (f->frametype == AST_FRAME_VIDEO)
06234          pvt->svideoformat = f->subclass & ~0x1;
06235       if (ast_test_flag(pvt, IAX_ENCRYPTED)) {
06236          if (ast_test_flag(pvt, IAX_KEYPOPULATED)) {
06237             if (fr->transfer)
06238                iax_outputframe(fr, NULL, 2, &pvt->transfer, fr->datalen - sizeof(struct ast_iax2_full_hdr));
06239             else
06240                iax_outputframe(fr, NULL, 2, &pvt->addr, fr->datalen - sizeof(struct ast_iax2_full_hdr));
06241             encrypt_frame(&pvt->ecx, fh, pvt->semirand, &fr->datalen);
06242             fr->encmethods = pvt->encmethods;
06243             fr->ecx = pvt->ecx;
06244             fr->mydcx = pvt->mydcx;
06245             memcpy(fr->semirand, pvt->semirand, sizeof(fr->semirand));
06246          } else
06247             ast_log(LOG_WARNING, "Supposed to send packet encrypted, but no key?\n");
06248       }
06249 
06250       if (now) {
06251          res = send_packet(fr);
06252       } else
06253          res = iax2_transmit(fr);
06254    } else {
06255       if (ast_test_flag(pvt, IAX_TRUNK)) {
06256          iax2_trunk_queue(pvt, fr);
06257          res = 0;
06258       } else if (fr->af.frametype == AST_FRAME_VIDEO) {
06259          /* Video frame have no sequence number */
06260          fr->oseqno = -1;
06261          fr->iseqno = -1;
06262          vh = (struct ast_iax2_video_hdr *)(fr->af.data.ptr - sizeof(struct ast_iax2_video_hdr));
06263          vh->zeros = 0;
06264          vh->callno = htons(0x8000 | fr->callno);
06265          vh->ts = htons((fr->ts & 0x7FFF) | (fr->af.subclass & 0x1 ? 0x8000 : 0));
06266          fr->datalen = fr->af.datalen + sizeof(struct ast_iax2_video_hdr);
06267          fr->data = vh;
06268          fr->retries = -1;
06269          res = send_packet(fr);        
06270       } else {
06271          /* Mini-frames have no sequence number */
06272          fr->oseqno = -1;
06273          fr->iseqno = -1;
06274          /* Mini frame will do */
06275          mh = (struct ast_iax2_mini_hdr *)(fr->af.data.ptr - sizeof(struct ast_iax2_mini_hdr));
06276          mh->callno = htons(fr->callno);
06277          mh->ts = htons(fr->ts & 0xFFFF);
06278          fr->datalen = fr->af.datalen + sizeof(struct ast_iax2_mini_hdr);
06279          fr->data = mh;
06280          fr->retries = -1;
06281          if (pvt->transferring == TRANSFER_MEDIAPASS)
06282             fr->transfer = 1;
06283          if (ast_test_flag(pvt, IAX_ENCRYPTED)) {
06284             if (ast_test_flag(pvt, IAX_KEYPOPULATED)) {
06285                encrypt_frame(&pvt->ecx, (struct ast_iax2_full_hdr *)mh, pvt->semirand, &fr->datalen);
06286             } else
06287                ast_log(LOG_WARNING, "Supposed to send packet encrypted, but no key?\n");
06288          }
06289          res = send_packet(fr);
06290       }
06291    }
06292    return res;
06293 }
06294 
06295 static char *handle_cli_iax2_show_users(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
06296 {
06297    regex_t regexbuf;
06298    int havepattern = 0;
06299 
06300 #define FORMAT "%-15.15s  %-20.20s  %-15.15s  %-15.15s  %-5.5s  %-5.10s\n"
06301 #define FORMAT2 "%-15.15s  %-20.20s  %-15.15d  %-15.15s  %-5.5s  %-5.10s\n"
06302 
06303    struct iax2_user *user = NULL;
06304    char auth[90];
06305    char *pstr = "";
06306    struct ao2_iterator i;
06307 
06308    switch (cmd) {
06309    case CLI_INIT:
06310       e->command = "iax2 show users [like]";
06311       e->usage =
06312          "Usage: iax2 show users [like <pattern>]\n"
06313          "       Lists all known IAX2 users.\n"
06314          "       Optional regular expression pattern is used to filter the user list.\n";
06315       return NULL;
06316    case CLI_GENERATE:
06317       return NULL;
06318    }
06319 
06320    switch (a->argc) {
06321    case 5:
06322       if (!strcasecmp(a->argv[3], "like")) {
06323          if (regcomp(&regexbuf, a->argv[4], REG_EXTENDED | REG_NOSUB))
06324             return CLI_SHOWUSAGE;
06325          havepattern = 1;
06326       } else
06327          return CLI_SHOWUSAGE;
06328    case 3:
06329       break;
06330    default:
06331       return CLI_SHOWUSAGE;
06332    }
06333 
06334    ast_cli(a->fd, FORMAT, "Username", "Secret", "Authen", "Def.Context", "A/C","Codec Pref");
06335    i = ao2_iterator_init(users, 0);
06336    for (user = ao2_iterator_next(&i); user; 
06337       user_unref(user), user = ao2_iterator_next(&i)) {
06338       if (havepattern && regexec(&regexbuf, user->name, 0, NULL, 0))
06339          continue;
06340       
06341       if (!ast_strlen_zero(user->secret)) {
06342          ast_copy_string(auth,user->secret, sizeof(auth));
06343       } else if (!ast_strlen_zero(user->inkeys)) {
06344          snprintf(auth, sizeof(auth), "Key: %-15.15s ", user->inkeys);
06345       } else
06346          ast_copy_string(auth, "-no secret-", sizeof(auth));
06347       
06348       if(ast_test_flag(user,IAX_CODEC_NOCAP))
06349          pstr = "REQ Only";
06350       else if(ast_test_flag(user,IAX_CODEC_NOPREFS))
06351          pstr = "Disabled";
06352       else
06353          pstr = ast_test_flag(user,IAX_CODEC_USER_FIRST) ? "Caller" : "Host";
06354       
06355       ast_cli(a->fd, FORMAT2, user->name, auth, user->authmethods, 
06356          user->contexts ? user->contexts->context : DEFAULT_CONTEXT,
06357          user->ha ? "Yes" : "No", pstr);
06358    }
06359    ao2_iterator_destroy(&i);
06360 
06361    if (havepattern)
06362       regfree(&regexbuf);
06363 
06364    return CLI_SUCCESS;
06365 #undef FORMAT
06366 #undef FORMAT2
06367 }
06368 
06369 static int __iax2_show_peers(int manager, int fd, struct mansession *s, int argc, char *argv[])
06370 {
06371    regex_t regexbuf;
06372    int havepattern = 0;
06373    int total_peers = 0;
06374    int online_peers = 0;
06375    int offline_peers = 0;
06376    int unmonitored_peers = 0;
06377    struct ao2_iterator i;
06378 
06379 #define FORMAT2 "%-15.15s  %-15.15s %s  %-15.15s  %-8s  %s %-10s%s"
06380 #define FORMAT "%-15.15s  %-15.15s %s  %-15.15s  %-5d%s  %s %-10s%s"
06381 
06382    struct iax2_peer *peer = NULL;
06383    char name[256];
06384    struct ast_str *encmethods = ast_str_alloca(256);
06385    int registeredonly=0;
06386    char *term = manager ? "\r\n" : "\n";
06387    char idtext[256] = "";
06388    switch (argc) {
06389    case 6:
06390       if (!strcasecmp(argv[3], "registered"))
06391          registeredonly = 1;
06392       else
06393          return RESULT_SHOWUSAGE;
06394       if (!strcasecmp(argv[4], "like")) {
06395          if (regcomp(&regexbuf, argv[5], REG_EXTENDED | REG_NOSUB))
06396             return RESULT_SHOWUSAGE;
06397          havepattern = 1;
06398       } else
06399          return RESULT_SHOWUSAGE;
06400       break;
06401    case 5:
06402       if (!strcasecmp(argv[3], "like")) {
06403          if (regcomp(&regexbuf, argv[4], REG_EXTENDED | REG_NOSUB))
06404             return RESULT_SHOWUSAGE;
06405          havepattern = 1;
06406       } else
06407          return RESULT_SHOWUSAGE;
06408       break;
06409    case 4:
06410       if (!strcasecmp(argv[3], "registered"))
06411          registeredonly = 1;
06412       else
06413          return RESULT_SHOWUSAGE;
06414       break;
06415    case 3:
06416       break;
06417    default:
06418       return RESULT_SHOWUSAGE;
06419    }
06420 
06421 
06422    if (!s)
06423       ast_cli(fd, FORMAT2, "Name/Username", "Host", "   ", "Mask", "Port", "   ", "Status", term);
06424 
06425    i = ao2_iterator_init(peers, 0);
06426    for (peer = ao2_iterator_next(&i); peer; 
06427       peer_unref(peer), peer = ao2_iterator_next(&i)) {
06428       char nm[20];
06429       char status[20];
06430       int retstatus;
06431 
06432       if (registeredonly && !peer->addr.sin_addr.s_addr)
06433          continue;
06434       if (havepattern && regexec(&regexbuf, peer->name, 0, NULL, 0))
06435          continue;
06436 
06437       if (!ast_strlen_zero(peer->username))
06438          snprintf(name, sizeof(name), "%s/%s", peer->name, peer->username);
06439       else
06440          ast_copy_string(name, peer->name, sizeof(name));
06441 
06442       encmethods_to_str(peer->encmethods, encmethods);
06443       retstatus = peer_status(peer, status, sizeof(status));
06444       if (retstatus > 0)
06445          online_peers++;
06446       else if (!retstatus)
06447          offline_peers++;
06448       else
06449          unmonitored_peers++;
06450 
06451       ast_copy_string(nm, ast_inet_ntoa(peer->mask), sizeof(nm));
06452 
06453       if (s) {
06454          astman_append(s,
06455             "Event: PeerEntry\r\n%s"
06456             "Channeltype: IAX2\r\n"
06457             "ChanObjectType: peer\r\n"
06458             "ObjectName: %s\r\n"
06459             "IPaddress: %s\r\n"
06460             "IPport: %d\r\n"
06461             "Dynamic: %s\r\n"
06462             "Trunk: %s\r\n"
06463             "Encryption: %s\r\n"
06464             "Status: %s\r\n\r\n",
06465             idtext,
06466             name,
06467             peer->addr.sin_addr.s_addr ? ast_inet_ntoa(peer->addr.sin_addr) : "-none-",
06468             ntohs(peer->addr.sin_port),
06469             ast_test_flag(peer, IAX_DYNAMIC) ? "yes" : "no",
06470             ast_test_flag(peer, IAX_TRUNK) ? "yes" : "no",
06471             peer->encmethods ? ast_str_buffer(encmethods) : "no",
06472             status);
06473       } else {
06474          ast_cli(fd, FORMAT, name,
06475             peer->addr.sin_addr.s_addr ? ast_inet_ntoa(peer->addr.sin_addr) : "(Unspecified)",
06476             ast_test_flag(peer, IAX_DYNAMIC) ? "(D)" : "(S)",
06477             nm,
06478             ntohs(peer->addr.sin_port),
06479             ast_test_flag(peer, IAX_TRUNK) ? "(T)" : "   ",
06480             peer->encmethods ? "(E)" : "   ",
06481             status,
06482             term);
06483       }
06484       total_peers++;
06485    }
06486    ao2_iterator_destroy(&i);
06487 
06488    if (!s)
06489       ast_cli(fd,"%d iax2 peers [%d online, %d offline, %d unmonitored]%s", total_peers, online_peers, offline_peers, unmonitored_peers, term);
06490 
06491    if (havepattern)
06492       regfree(&regexbuf);
06493 
06494    return RESULT_SUCCESS;
06495 #undef FORMAT
06496 #undef FORMAT2
06497 }
06498 
06499 static char *handle_cli_iax2_show_threads(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
06500 {
06501    struct iax2_thread *thread = NULL;
06502    time_t t;
06503    int threadcount = 0, dynamiccount = 0;
06504    char type;
06505 
06506    switch (cmd) {
06507    case CLI_INIT:
06508       e->command = "iax2 show threads";
06509       e->usage =
06510          "Usage: iax2 show threads\n"
06511          "       Lists status of IAX helper threads\n";
06512       return NULL;
06513    case CLI_GENERATE:
06514       return NULL;
06515    }
06516    if (a->argc != 3)
06517       return CLI_SHOWUSAGE;
06518       
06519    ast_cli(a->fd, "IAX2 Thread Information\n");
06520    time(&t);
06521    ast_cli(a->fd, "Idle Threads:\n");
06522    AST_LIST_LOCK(&idle_list);
06523    AST_LIST_TRAVERSE(&idle_list, thread, list) {
06524 #ifdef DEBUG_SCHED_MULTITHREAD
06525       ast_cli(a->fd, "Thread %d: state=%d, update=%d, actions=%d, func='%s'\n", 
06526          thread->threadnum, thread->iostate, (int)(t - thread->checktime), thread->actions, thread->curfunc);
06527 #else
06528       ast_cli(a->fd, "Thread %d: state=%d, update=%d, actions=%d\n", 
06529          thread->threadnum, thread->iostate, (int)(t - thread->checktime), thread->actions);
06530 #endif
06531       threadcount++;
06532    }
06533    AST_LIST_UNLOCK(&idle_list);
06534    ast_cli(a->fd, "Active Threads:\n");
06535    AST_LIST_LOCK(&active_list);
06536    AST_LIST_TRAVERSE(&active_list, thread, list) {
06537       if (thread->type == IAX_THREAD_TYPE_DYNAMIC)
06538          type = 'D';
06539       else
06540          type = 'P';
06541 #ifdef DEBUG_SCHED_MULTITHREAD
06542       ast_cli(a->fd, "Thread %c%d: state=%d, update=%d, actions=%d, func='%s'\n", 
06543          type, thread->threadnum, thread->iostate, (int)(t - thread->checktime), thread->actions, thread->curfunc);
06544 #else
06545       ast_cli(a->fd, "Thread %c%d: state=%d, update=%d, actions=%d\n", 
06546          type, thread->threadnum, thread->iostate, (int)(t - thread->checktime), thread->actions);
06547 #endif
06548       threadcount++;
06549    }
06550    AST_LIST_UNLOCK(&active_list);
06551    ast_cli(a->fd, "Dynamic Threads:\n");
06552    AST_LIST_LOCK(&dynamic_list);
06553    AST_LIST_TRAVERSE(&dynamic_list, thread, list) {
06554 #ifdef DEBUG_SCHED_MULTITHREAD
06555       ast_cli(a->fd, "Thread %d: state=%d, update=%d, actions=%d, func='%s'\n",
06556          thread->threadnum, thread->iostate, (int)(t - thread->checktime), thread->actions, thread->curfunc);
06557 #else
06558       ast_cli(a->fd, "Thread %d: state=%d, update=%d, actions=%d\n",
06559          thread->threadnum, thread->iostate, (int)(t - thread->checktime), thread->actions);
06560 #endif
06561       dynamiccount++;
06562    }
06563    AST_LIST_UNLOCK(&dynamic_list);
06564    ast_cli(a->fd, "%d of %d threads accounted for with %d dynamic threads\n", threadcount, iaxthreadcount, dynamiccount);
06565    return CLI_SUCCESS;
06566 }
06567 
06568 static char *handle_cli_iax2_unregister(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
06569 {
06570    struct iax2_peer *p;
06571 
06572    switch (cmd) {
06573    case CLI_INIT:
06574       e->command = "iax2 unregister";
06575       e->usage =
06576          "Usage: iax2 unregister <peername>\n"
06577          "       Unregister (force expiration) an IAX2 peer from the registry.\n";
06578       return NULL;
06579    case CLI_GENERATE:
06580       return complete_iax2_unregister(a->line, a->word, a->pos, a->n);
06581    }
06582 
06583    if (a->argc != 3)
06584       return CLI_SHOWUSAGE;
06585 
06586    p = find_peer(a->argv[2], 1);
06587    if (p) {
06588       if (p->expire > 0) {
06589          struct iax2_peer tmp_peer = {
06590             .name = a->argv[2],
06591          };
06592          struct iax2_peer *peer;
06593 
06594          peer = ao2_find(peers, &tmp_peer, OBJ_POINTER);
06595          if (peer) {
06596             expire_registry(peer_ref(peer)); /* will release its own reference when done */
06597             peer_unref(peer); /* ref from ao2_find() */
06598             ast_cli(a->fd, "Peer %s unregistered\n", a->argv[2]);
06599          } else {
06600             ast_cli(a->fd, "Peer %s not found\n", a->argv[2]);
06601          }
06602       } else {
06603          ast_cli(a->fd, "Peer %s not registered\n", a->argv[2]);
06604       }
06605    } else {
06606       ast_cli(a->fd, "Peer unknown: %s. Not unregistered\n", a->argv[2]);
06607    }
06608    return CLI_SUCCESS;
06609 }
06610 
06611 static char *complete_iax2_unregister(const char *line, const char *word, int pos, int state)
06612 {
06613    int which = 0;
06614    struct iax2_peer *p = NULL;
06615    char *res = NULL;
06616    int wordlen = strlen(word);
06617 
06618    /* 0 - iax2; 1 - unregister; 2 - <peername> */
06619    if (pos == 2) {
06620       struct ao2_iterator i = ao2_iterator_init(peers, 0);
06621       while ((p = ao2_iterator_next(&i))) {
06622          if (!strncasecmp(p->name, word, wordlen) && 
06623             ++which > state && p->expire > 0) {
06624             res = ast_strdup(p->name);
06625             peer_unref(p);
06626             break;
06627          }
06628          peer_unref(p);
06629       }
06630       ao2_iterator_destroy(&i);
06631    }
06632 
06633    return res;
06634 }
06635 
06636 static char *handle_cli_iax2_show_peers(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
06637 {
06638    switch (cmd) {
06639    case CLI_INIT:
06640       e->command = "iax2 show peers";
06641       e->usage =
06642          "Usage: iax2 show peers [registered] [like <pattern>]\n"
06643          "       Lists all known IAX2 peers.\n"
06644          "       Optional 'registered' argument lists only peers with known addresses.\n"
06645          "       Optional regular expression pattern is used to filter the peer list.\n";
06646       return NULL;
06647    case CLI_GENERATE:
06648       return NULL;
06649    }
06650 
06651    switch (__iax2_show_peers(0, a->fd, NULL, a->argc, a->argv)) {
06652    case RESULT_SHOWUSAGE:
06653       return CLI_SHOWUSAGE;
06654    case RESULT_FAILURE:
06655       return CLI_FAILURE;
06656    default:
06657       return CLI_SUCCESS;
06658    }
06659 }
06660 
06661 static int manager_iax2_show_netstats(struct mansession *s, const struct message *m)
06662 {
06663    ast_cli_netstats(s, -1, 0);
06664    astman_append(s, "\r\n");
06665    return RESULT_SUCCESS;
06666 }
06667 
06668 static char *handle_cli_iax2_show_firmware(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
06669 {
06670    struct iax_firmware *cur = NULL;
06671 
06672    switch (cmd) {
06673    case CLI_INIT:
06674       e->command = "iax2 show firmware";
06675       e->usage =
06676          "Usage: iax2 show firmware\n"
06677          "       Lists all known IAX firmware images.\n";
06678       return NULL;
06679    case CLI_GENERATE:
06680       return NULL;
06681    }
06682 
06683    if (a->argc != 3 && a->argc != 4)
06684       return CLI_SHOWUSAGE;
06685 
06686    ast_cli(a->fd, "%-15.15s  %-15.15s %-15.15s\n", "Device", "Version", "Size");
06687    AST_LIST_LOCK(&firmwares);
06688    AST_LIST_TRAVERSE(&firmwares, cur, list) {
06689       if ((a->argc == 3) || (!strcasecmp(a->argv[3], (char *) cur->fwh->devname)))  {
06690          ast_cli(a->fd, "%-15.15s  %-15d %-15d\n", cur->fwh->devname, 
06691             ntohs(cur->fwh->version), (int)ntohl(cur->fwh->datalen));
06692       }
06693    }
06694    AST_LIST_UNLOCK(&firmwares);
06695 
06696    return CLI_SUCCESS;
06697 }
06698 
06699 /*! \brief callback to display iax peers in manager */
06700 static int manager_iax2_show_peers(struct mansession *s, const struct message *m)
06701 {
06702    char *a[] = { "iax2", "show", "users" };
06703    const char *id = astman_get_header(m,"ActionID");
06704    char idtext[256] = "";
06705 
06706    if (!ast_strlen_zero(id))
06707       snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
06708    astman_send_ack(s, m, "Peer status list will follow");
06709    return __iax2_show_peers(1, -1, s, 3, a );
06710 } 
06711 
06712 /*! \brief callback to display iax peers in manager format */
06713 static int manager_iax2_show_peer_list(struct mansession *s, const struct message *m)
06714 {
06715    struct iax2_peer *peer = NULL;
06716    int peer_count = 0;
06717    char nm[20];
06718    char status[20];
06719    const char *id = astman_get_header(m,"ActionID");
06720    char idtext[256] = "";
06721    struct ast_str *encmethods = ast_str_alloca(256);
06722    struct ao2_iterator i;
06723 
06724    if (!ast_strlen_zero(id))
06725       snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
06726 
06727    astman_append(s, "Response: Success\r\n%sMessage: IAX Peer status list will follow\r\n\r\n", idtext);
06728 
06729 
067