Mon May 14 2012 03:42:30

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    <support_level>core</support_level>
00037  ***/
00038 
00039 #include "asterisk.h"
00040 
00041 ASTERISK_FILE_VERSION(__FILE__, "$Revision: 356107 $")
00042 
00043 #include <sys/mman.h>
00044 #include <dirent.h>
00045 #include <sys/socket.h>
00046 #include <netinet/in.h>
00047 #include <arpa/inet.h>
00048 #include <netinet/in_systm.h>
00049 #include <netinet/ip.h>
00050 #include <sys/time.h>
00051 #include <sys/signal.h>
00052 #include <signal.h>
00053 #include <strings.h>
00054 #include <netdb.h>
00055 #include <fcntl.h>
00056 #include <sys/stat.h>
00057 #include <regex.h>
00058 
00059 #include "asterisk/paths.h"   /* need ast_config_AST_DATA_DIR for firmware */
00060 
00061 #include "asterisk/lock.h"
00062 #include "asterisk/frame.h" 
00063 #include "asterisk/channel.h"
00064 #include "asterisk/module.h"
00065 #include "asterisk/pbx.h"
00066 #include "asterisk/sched.h"
00067 #include "asterisk/io.h"
00068 #include "asterisk/config.h"
00069 #include "asterisk/cli.h"
00070 #include "asterisk/translate.h"
00071 #include "asterisk/md5.h"
00072 #include "asterisk/cdr.h"
00073 #include "asterisk/crypto.h"
00074 #include "asterisk/acl.h"
00075 #include "asterisk/manager.h"
00076 #include "asterisk/callerid.h"
00077 #include "asterisk/app.h"
00078 #include "asterisk/astdb.h"
00079 #include "asterisk/musiconhold.h"
00080 #include "asterisk/features.h"
00081 #include "asterisk/utils.h"
00082 #include "asterisk/causes.h"
00083 #include "asterisk/localtime.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 #include "asterisk/taskprocessor.h"
00093 #include "asterisk/test.h"
00094 #include "asterisk/data.h"
00095 #include "asterisk/netsock2.h"
00096 
00097 #include "iax2.h"
00098 #include "iax2-parser.h"
00099 #include "iax2-provision.h"
00100 #include "jitterbuf.h"
00101 
00102 /*** DOCUMENTATION
00103    <application name="IAX2Provision" language="en_US">
00104       <synopsis>
00105          Provision a calling IAXy with a given template.
00106       </synopsis>
00107       <syntax>
00108          <parameter name="template">
00109             <para>If not specified, defaults to <literal>default</literal>.</para>
00110          </parameter>
00111       </syntax>
00112       <description>
00113          <para>Provisions the calling IAXy (assuming the calling entity is in fact an IAXy) with the
00114          given <replaceable>template</replaceable>. Returns <literal>-1</literal> on error
00115          or <literal>0</literal> on success.</para>
00116       </description>
00117    </application>
00118    <function name="IAXPEER" language="en_US">
00119       <synopsis>
00120          Gets IAX peer information.
00121       </synopsis>
00122       <syntax>
00123          <parameter name="peername" required="true">
00124             <enumlist>
00125                <enum name="CURRENTCHANNEL">
00126                   <para>If <replaceable>peername</replaceable> is specified to this value, return the IP address of the
00127                   endpoint of the current channel</para>
00128                </enum>
00129             </enumlist>
00130          </parameter>
00131          <parameter name="item">
00132             <para>If <replaceable>peername</replaceable> is specified, valid items are:</para>
00133             <enumlist>
00134                <enum name="ip">
00135                   <para>(default) The IP address.</para>
00136                </enum>
00137                <enum name="status">
00138                   <para>The peer's status (if <literal>qualify=yes</literal>)</para>
00139                </enum>
00140                <enum name="mailbox">
00141                   <para>The configured mailbox.</para>
00142                </enum>
00143                <enum name="context">
00144                   <para>The configured context.</para>
00145                </enum>
00146                <enum name="expire">
00147                   <para>The epoch time of the next expire.</para>
00148                </enum>
00149                <enum name="dynamic">
00150                   <para>Is it dynamic? (yes/no).</para>
00151                </enum>
00152                <enum name="callerid_name">
00153                   <para>The configured Caller ID name.</para>
00154                </enum>
00155                <enum name="callerid_num">
00156                   <para>The configured Caller ID number.</para>
00157                </enum>
00158                <enum name="codecs">
00159                   <para>The configured codecs.</para>
00160                </enum>
00161                <enum name="codec[x]">
00162                   <para>Preferred codec index number <replaceable>x</replaceable> (beginning
00163                   with <literal>0</literal>)</para>
00164                </enum>
00165             </enumlist>
00166          </parameter>
00167       </syntax>
00168       <description>
00169          <para>Gets information associated with the specified IAX2 peer.</para>
00170       </description>
00171       <see-also>
00172          <ref type="function">SIPPEER</ref>
00173       </see-also>
00174    </function>
00175    <function name="IAXVAR" language="en_US">
00176       <synopsis>
00177          Sets or retrieves a remote variable.
00178       </synopsis>
00179       <syntax>
00180          <parameter name="varname" required="true" />
00181       </syntax>
00182       <description>
00183          <para>Gets or sets a variable that is sent to a remote IAX2 peer during call setup.</para>
00184       </description>
00185    </function>
00186    <manager name="IAXpeers" language="en_US">
00187       <synopsis>
00188          List IAX peers.
00189       </synopsis>
00190       <syntax>
00191          <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
00192       </syntax>
00193       <description>
00194       </description>
00195    </manager>
00196    <manager name="IAXpeerlist" language="en_US">
00197       <synopsis>
00198          List IAX Peers.
00199       </synopsis>
00200       <syntax>
00201          <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
00202       </syntax>
00203       <description>
00204          <para>List all the IAX peers.</para>
00205       </description>
00206    </manager>
00207    <manager name="IAXnetstats" language="en_US">
00208       <synopsis>
00209          Show IAX Netstats.
00210       </synopsis>
00211       <syntax />
00212       <description>
00213          <para>Show IAX channels network statistics.</para>
00214       </description>
00215    </manager>
00216    <manager name="IAXregistry" language="en_US">
00217       <synopsis>
00218          Show IAX registrations.
00219       </synopsis>
00220       <syntax>
00221          <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
00222       </syntax>
00223       <description>
00224          <para>Show IAX registrations.</para>
00225       </description>
00226    </manager>
00227  ***/
00228 
00229 /* Define SCHED_MULTITHREADED to run the scheduler in a special
00230    multithreaded mode. */
00231 #define SCHED_MULTITHREADED
00232 
00233 /* Define DEBUG_SCHED_MULTITHREADED to keep track of where each
00234    thread is actually doing. */
00235 #define DEBUG_SCHED_MULTITHREAD
00236 
00237 
00238 #ifdef SO_NO_CHECK
00239 static int nochecksums = 0;
00240 #endif
00241 
00242 #define PTR_TO_CALLNO(a) ((unsigned short)(unsigned long)(a))
00243 #define CALLNO_TO_PTR(a) ((void *)(unsigned long)(a))
00244 
00245 #define DEFAULT_THREAD_COUNT 10
00246 #define DEFAULT_MAX_THREAD_COUNT 100
00247 #define DEFAULT_RETRY_TIME 1000
00248 #define MEMORY_SIZE 100
00249 #define DEFAULT_DROP 3
00250 
00251 #define DEBUG_SUPPORT
00252 
00253 #define MIN_REUSE_TIME     60 /* Don't reuse a call number within 60 seconds */
00254 
00255 /* Sample over last 100 units to determine historic jitter */
00256 #define GAMMA (0.01)
00257 
00258 static struct ast_codec_pref prefs;
00259 
00260 static const char tdesc[] = "Inter Asterisk eXchange Driver (Ver 2)";
00261 
00262 
00263 /*! \brief Maximum transmission unit for the UDP packet in the trunk not to be
00264     fragmented. This is based on 1516 - ethernet - ip - udp - iax minus one g711 frame = 1240 */
00265 #define MAX_TRUNK_MTU 1240
00266 
00267 static int global_max_trunk_mtu; /*!< Maximum MTU, 0 if not used */
00268 static int trunk_timed, trunk_untimed, trunk_maxmtu, trunk_nmaxmtu ; /*!< Trunk MTU statistics */
00269 
00270 #define DEFAULT_CONTEXT "default"
00271 
00272 static char default_parkinglot[AST_MAX_CONTEXT];
00273 
00274 static char language[MAX_LANGUAGE] = "";
00275 static char regcontext[AST_MAX_CONTEXT] = "";
00276 
00277 static struct ast_event_sub *network_change_event_subscription; /*!< subscription id for network change events */
00278 static int network_change_event_sched_id = -1;
00279 
00280 static int maxauthreq = 3;
00281 static int max_retries = 4;
00282 static int ping_time = 21;
00283 static int lagrq_time = 10;
00284 static int maxjitterbuffer=1000;
00285 static int resyncthreshold=1000;
00286 static int maxjitterinterps=10;
00287 static int jittertargetextra = 40; /* number of milliseconds the new jitter buffer adds on to its size */
00288 
00289 #define MAX_TRUNKDATA           640 * 200       /*!< 40ms, uncompressed linear * 200 channels */
00290 
00291 static int trunkfreq = 20;
00292 static int trunkmaxsize = MAX_TRUNKDATA;
00293 
00294 static int authdebug = 1;
00295 static int autokill = 0;
00296 static int iaxcompat = 0;
00297 static int last_authmethod = 0;
00298 
00299 static int iaxdefaultdpcache=10 * 60;  /* Cache dialplan entries for 10 minutes by default */
00300 
00301 static int iaxdefaulttimeout = 5;      /* Default to wait no more than 5 seconds for a reply to come back */
00302 
00303 static struct {
00304    unsigned int tos;
00305    unsigned int cos;
00306 } qos = { 0, 0 };
00307 
00308 static int min_reg_expire;
00309 static int max_reg_expire;
00310 
00311 static int srvlookup = 0;
00312 
00313 static struct ast_timer *timer;           /* Timer for trunking */
00314 
00315 static struct ast_netsock_list *netsock;
00316 static struct ast_netsock_list *outsock;     /*!< used if sourceaddress specified and bindaddr == INADDR_ANY */
00317 static int defaultsockfd = -1;
00318 
00319 static int (*iax2_regfunk)(const char *username, int onoff) = NULL;
00320 
00321 /* Ethernet, etc */
00322 #define IAX_CAPABILITY_FULLBANDWIDTH   0xFFFF
00323 /* T1, maybe ISDN */
00324 #define IAX_CAPABILITY_MEDBANDWIDTH (IAX_CAPABILITY_FULLBANDWIDTH & \
00325                      ~AST_FORMAT_SLINEAR &      \
00326                      ~AST_FORMAT_SLINEAR16 &    \
00327                      ~AST_FORMAT_SIREN7 &       \
00328                      ~AST_FORMAT_SIREN14 &      \
00329                      ~AST_FORMAT_G719 &         \
00330                      ~AST_FORMAT_ULAW &         \
00331                      ~AST_FORMAT_ALAW &         \
00332                      ~AST_FORMAT_G722)
00333 /* A modem */
00334 #define IAX_CAPABILITY_LOWBANDWIDTH (IAX_CAPABILITY_MEDBANDWIDTH & \
00335                      ~AST_FORMAT_G726 &         \
00336                      ~AST_FORMAT_G726_AAL2 &    \
00337                      ~AST_FORMAT_ADPCM)
00338 
00339 #define IAX_CAPABILITY_LOWFREE      (IAX_CAPABILITY_LOWBANDWIDTH & \
00340                      ~AST_FORMAT_G723_1)
00341 
00342 
00343 #define DEFAULT_MAXMS      2000     /* Must be faster than 2 seconds by default */
00344 #define DEFAULT_FREQ_OK    60 * 1000   /* How often to check for the host to be up */
00345 #define DEFAULT_FREQ_NOTOK 10 * 1000   /* How often to check, if the host is down... */
00346 
00347 /* if a pvt has encryption setup done and is running on the call */
00348 #define IAX_CALLENCRYPTED(pvt) \
00349    (ast_test_flag64(pvt, IAX_ENCRYPTED) && ast_test_flag64(pvt, IAX_KEYPOPULATED))
00350 
00351 #define IAX_DEBUGDIGEST(msg, key) do { \
00352       int idx; \
00353       char digest[33] = ""; \
00354       \
00355       if (!iaxdebug) \
00356          break; \
00357       \
00358       for (idx = 0; idx < 16; idx++) \
00359          sprintf(digest + (idx << 1), "%2.2x", (unsigned char) key[idx]); \
00360       \
00361       ast_log(LOG_NOTICE, msg " IAX_COMMAND_RTKEY to rotate key to '%s'\n", digest); \
00362    } while(0)
00363 
00364 static   struct io_context *io;
00365 static   struct ast_sched_thread *sched;
00366 
00367 #define DONT_RESCHEDULE -2
00368 
00369 static format_t iax2_capability = IAX_CAPABILITY_FULLBANDWIDTH;
00370 
00371 static int iaxdebug = 0;
00372 
00373 static int iaxtrunkdebug = 0;
00374 
00375 static int test_losspct = 0;
00376 #ifdef IAXTESTS
00377 static int test_late = 0;
00378 static int test_resync = 0;
00379 static int test_jit = 0;
00380 static int test_jitpct = 0;
00381 #endif /* IAXTESTS */
00382 
00383 static char accountcode[AST_MAX_ACCOUNT_CODE];
00384 static char mohinterpret[MAX_MUSICCLASS];
00385 static char mohsuggest[MAX_MUSICCLASS];
00386 static int amaflags = 0;
00387 static int adsi = 0;
00388 static int delayreject = 0;
00389 static int iax2_encryption = 0;
00390 
00391 static struct ast_flags64 globalflags = { 0 };
00392 
00393 static pthread_t netthreadid = AST_PTHREADT_NULL;
00394 
00395 enum iax2_state {
00396    IAX_STATE_STARTED =        (1 << 0),
00397    IAX_STATE_AUTHENTICATED =  (1 << 1),
00398    IAX_STATE_TBD =            (1 << 2),
00399 };
00400 
00401 struct iax2_context {
00402    char context[AST_MAX_CONTEXT];
00403    struct iax2_context *next;
00404 };
00405 
00406 
00407 #define  IAX_HASCALLERID         (uint64_t)(1 << 0)    /*!< CallerID has been specified */
00408 #define IAX_DELME               (uint64_t)(1 << 1)    /*!< Needs to be deleted */
00409 #define IAX_TEMPONLY            (uint64_t)(1 << 2)    /*!< Temporary (realtime) */
00410 #define IAX_TRUNK               (uint64_t)(1 << 3)    /*!< Treat as a trunk */
00411 #define IAX_NOTRANSFER          (uint64_t)(1 << 4)    /*!< Don't native bridge */
00412 #define IAX_USEJITTERBUF        (uint64_t)(1 << 5)    /*!< Use jitter buffer */
00413 #define IAX_DYNAMIC             (uint64_t)(1 << 6)    /*!< dynamic peer */
00414 #define IAX_SENDANI             (uint64_t)(1 << 7)    /*!< Send ANI along with CallerID */
00415 #define IAX_RTSAVE_SYSNAME      (uint64_t)(1 << 8)    /*!< Save Systname on Realtime Updates */
00416 #define IAX_ALREADYGONE         (uint64_t)(1 << 9)    /*!< Already disconnected */
00417 #define IAX_PROVISION           (uint64_t)(1 << 10)   /*!< This is a provisioning request */
00418 #define IAX_QUELCH              (uint64_t)(1 << 11)   /*!< Whether or not we quelch audio */
00419 #define IAX_ENCRYPTED           (uint64_t)(1 << 12)   /*!< Whether we should assume encrypted tx/rx */
00420 #define IAX_KEYPOPULATED        (uint64_t)(1 << 13)   /*!< Whether we have a key populated */
00421 #define IAX_CODEC_USER_FIRST    (uint64_t)(1 << 14)   /*!< are we willing to let the other guy choose the codec? */
00422 #define IAX_CODEC_NOPREFS       (uint64_t)(1 << 15)   /*!< Force old behaviour by turning off prefs */
00423 #define IAX_CODEC_NOCAP         (uint64_t)(1 << 16)   /*!< only consider requested format and ignore capabilities*/
00424 #define IAX_RTCACHEFRIENDS      (uint64_t)(1 << 17)   /*!< let realtime stay till your reload */
00425 #define IAX_RTUPDATE            (uint64_t)(1 << 18)   /*!< Send a realtime update */
00426 #define IAX_RTAUTOCLEAR         (uint64_t)(1 << 19)   /*!< erase me on expire */
00427 #define IAX_FORCEJITTERBUF      (uint64_t)(1 << 20)   /*!< Force jitterbuffer, even when bridged to a channel that can take jitter */
00428 #define IAX_RTIGNOREREGEXPIRE   (uint64_t)(1 << 21)   /*!< When using realtime, ignore registration expiration */
00429 #define IAX_TRUNKTIMESTAMPS     (uint64_t)(1 << 22)   /*!< Send trunk timestamps */
00430 #define IAX_TRANSFERMEDIA       (uint64_t)(1 << 23)   /*!< When doing IAX2 transfers, transfer media only */
00431 #define IAX_MAXAUTHREQ          (uint64_t)(1 << 24)   /*!< Maximum outstanding AUTHREQ restriction is in place */
00432 #define IAX_DELAYPBXSTART       (uint64_t)(1 << 25)   /*!< Don't start a PBX on the channel until the peer sends us a response, so that we've achieved a three-way handshake with them before sending voice or anything else */
00433 #define IAX_ALLOWFWDOWNLOAD     (uint64_t)(1 << 26)   /*!< Allow the FWDOWNL command? */
00434 #define IAX_IMMEDIATE           (uint64_t)(1 << 27)   /*!< Allow immediate off-hook to extension s */
00435 #define IAX_SENDCONNECTEDLINE   (uint64_t)(1 << 28)   /*!< Allow sending of connected line updates */
00436 #define IAX_RECVCONNECTEDLINE   (uint64_t)(1 << 29)   /*!< Allow receiving of connected line updates */
00437 #define IAX_FORCE_ENCRYPT       (uint64_t)(1 << 30)   /*!< Forces call encryption, if encryption not possible hangup */
00438 #define IAX_SHRINKCALLERID      (uint64_t)(1 << 31)   /*!< Turn on and off caller id shrinking */
00439 static int global_rtautoclear = 120;
00440 
00441 static int reload_config(void);
00442 
00443 /*!
00444  * \brief Call token validation settings.
00445  */
00446 enum calltoken_peer_enum {
00447    /*! \brief Default calltoken required unless the ip is in the ignorelist */
00448    CALLTOKEN_DEFAULT = 0,
00449    /*! \brief Require call token validation. */
00450    CALLTOKEN_YES = 1,
00451    /*! \brief Require call token validation after a successful registration
00452     *         using call token validation occurs. */
00453    CALLTOKEN_AUTO = 2,
00454    /*! \brief Do not require call token validation. */
00455    CALLTOKEN_NO = 3,
00456 };
00457 
00458 struct iax2_user {
00459    AST_DECLARE_STRING_FIELDS(
00460       AST_STRING_FIELD(name);
00461       AST_STRING_FIELD(secret);
00462       AST_STRING_FIELD(dbsecret);
00463       AST_STRING_FIELD(accountcode);
00464       AST_STRING_FIELD(mohinterpret);
00465       AST_STRING_FIELD(mohsuggest);
00466       AST_STRING_FIELD(inkeys);               /*!< Key(s) this user can use to authenticate to us */
00467       AST_STRING_FIELD(language);
00468       AST_STRING_FIELD(cid_num);
00469       AST_STRING_FIELD(cid_name);
00470       AST_STRING_FIELD(parkinglot);           /*!< Default parkinglot for device */
00471    );
00472 
00473    int authmethods;
00474    int encmethods;
00475    int amaflags;
00476    int adsi;
00477    uint64_t flags;
00478    format_t capability;
00479    int maxauthreq; /*!< Maximum allowed outstanding AUTHREQs */
00480    int curauthreq; /*!< Current number of outstanding AUTHREQs */
00481    struct ast_codec_pref prefs;
00482    struct ast_ha *ha;
00483    struct iax2_context *contexts;
00484    struct ast_variable *vars;
00485    enum calltoken_peer_enum calltoken_required;        /*!< Is calltoken validation required or not, can be YES, NO, or AUTO */
00486 };
00487 
00488 struct iax2_peer {
00489    AST_DECLARE_STRING_FIELDS(
00490       AST_STRING_FIELD(name);
00491       AST_STRING_FIELD(username);
00492       AST_STRING_FIELD(secret);
00493       AST_STRING_FIELD(dbsecret);
00494       AST_STRING_FIELD(outkey);      /*!< What key we use to talk to this peer */
00495 
00496       AST_STRING_FIELD(regexten);     /*!< Extension to register (if regcontext is used) */
00497       AST_STRING_FIELD(context);      /*!< For transfers only */
00498       AST_STRING_FIELD(peercontext);  /*!< Context to pass to peer */
00499       AST_STRING_FIELD(mailbox);     /*!< Mailbox */
00500       AST_STRING_FIELD(mohinterpret);
00501       AST_STRING_FIELD(mohsuggest);
00502       AST_STRING_FIELD(inkeys);     /*!< Key(s) this peer can use to authenticate to us */
00503       /* Suggested caller id if registering */
00504       AST_STRING_FIELD(cid_num);    /*!< Default context (for transfer really) */
00505       AST_STRING_FIELD(cid_name);      /*!< Default context (for transfer really) */
00506       AST_STRING_FIELD(zonetag);    /*!< Time Zone */
00507       AST_STRING_FIELD(parkinglot);   /*!< Default parkinglot for device */
00508    );
00509    struct ast_codec_pref prefs;
00510    struct ast_dnsmgr_entry *dnsmgr;    /*!< DNS refresh manager */
00511    struct ast_sockaddr addr;
00512    int formats;
00513    int sockfd;             /*!< Socket to use for transmission */
00514    struct in_addr mask;
00515    int adsi;
00516    uint64_t flags;
00517 
00518    /* Dynamic Registration fields */
00519    struct sockaddr_in defaddr;         /*!< Default address if there is one */
00520    int authmethods;           /*!< Authentication methods (IAX_AUTH_*) */
00521    int encmethods;               /*!< Encryption methods (IAX_ENCRYPT_*) */
00522 
00523    int expire;             /*!< Schedule entry for expiry */
00524    int expiry;             /*!< How soon to expire */
00525    format_t capability;        /*!< Capability */
00526 
00527    /* Qualification */
00528    int callno;             /*!< Call number of POKE request */
00529    int pokeexpire;               /*!< Scheduled qualification-related task (ie iax2_poke_peer_s or iax2_poke_noanswer) */
00530    int lastms;             /*!< How long last response took (in ms), or -1 for no response */
00531    int maxms;              /*!< Max ms we will accept for the host to be up, 0 to not monitor */
00532 
00533    int pokefreqok;               /*!< How often to check if the host is up */
00534    int pokefreqnotok;            /*!< How often to check when the host has been determined to be down */
00535    int historicms;               /*!< How long recent average responses took */
00536    int smoothing;             /*!< Sample over how many units to determine historic ms */
00537    uint16_t maxcallno;              /*!< Max call number limit for this peer.  Set on registration */
00538 
00539    struct ast_event_sub *mwi_event_sub;
00540 
00541    struct ast_ha *ha;
00542    enum calltoken_peer_enum calltoken_required;        /*!< Is calltoken validation required or not, can be YES, NO, or AUTO */
00543 };
00544 
00545 #define IAX2_TRUNK_PREFACE (sizeof(struct iax_frame) + sizeof(struct ast_iax2_meta_hdr) + sizeof(struct ast_iax2_meta_trunk_hdr))
00546 
00547 struct iax2_trunk_peer {
00548    ast_mutex_t lock;
00549    int sockfd;
00550    struct sockaddr_in addr;
00551    struct timeval txtrunktime;      /*!< Transmit trunktime */
00552    struct timeval rxtrunktime;      /*!< Receive trunktime */
00553    struct timeval lasttxtime;    /*!< Last transmitted trunktime */
00554    struct timeval trunkact;      /*!< Last trunk activity */
00555    unsigned int lastsent;        /*!< Last sent time */
00556    /* Trunk data and length */
00557    unsigned char *trunkdata;
00558    unsigned int trunkdatalen;
00559    unsigned int trunkdataalloc;
00560    int trunkmaxmtu;
00561    int trunkerror;
00562    int calls;
00563    AST_LIST_ENTRY(iax2_trunk_peer) list;
00564 };
00565 
00566 static AST_LIST_HEAD_STATIC(tpeers, iax2_trunk_peer);
00567 
00568 struct iax_firmware {
00569    AST_LIST_ENTRY(iax_firmware) list;
00570    int fd;
00571    int mmaplen;
00572    int dead;
00573    struct ast_iax2_firmware_header *fwh;
00574    unsigned char *buf;
00575 };
00576 
00577 enum iax_reg_state {
00578    REG_STATE_UNREGISTERED = 0,
00579    REG_STATE_REGSENT,
00580    REG_STATE_AUTHSENT,
00581    REG_STATE_REGISTERED,
00582    REG_STATE_REJECTED,
00583    REG_STATE_TIMEOUT,
00584    REG_STATE_NOAUTH
00585 };
00586 
00587 enum iax_transfer_state {
00588    TRANSFER_NONE = 0,
00589    TRANSFER_BEGIN,
00590    TRANSFER_READY,
00591    TRANSFER_RELEASED,
00592    TRANSFER_PASSTHROUGH,
00593    TRANSFER_MBEGIN,
00594    TRANSFER_MREADY,
00595    TRANSFER_MRELEASED,
00596    TRANSFER_MPASSTHROUGH,
00597    TRANSFER_MEDIA,
00598    TRANSFER_MEDIAPASS
00599 };
00600 
00601 struct iax2_registry {
00602    struct ast_sockaddr addr;     /*!< Who we connect to for registration purposes */
00603    char username[80];
00604    char secret[80];        /*!< Password or key name in []'s */
00605    int expire;          /*!< Sched ID of expiration */
00606    int refresh;            /*!< How often to refresh */
00607    enum iax_reg_state regstate;
00608    int messages;           /*!< Message count, low 8 bits = new, high 8 bits = old */
00609    int callno;          /*!< Associated call number if applicable */
00610    struct sockaddr_in us;        /*!< Who the server thinks we are */
00611    struct ast_dnsmgr_entry *dnsmgr; /*!< DNS refresh manager */
00612    AST_LIST_ENTRY(iax2_registry) entry;
00613 };
00614 
00615 static AST_LIST_HEAD_STATIC(registrations, iax2_registry);
00616 
00617 /* Don't retry more frequently than every 10 ms, or less frequently than every 5 seconds */
00618 #define MIN_RETRY_TIME     100
00619 #define MAX_RETRY_TIME     10000
00620 
00621 #define MAX_JITTER_BUFFER  50
00622 #define MIN_JITTER_BUFFER  10
00623 
00624 #define DEFAULT_TRUNKDATA  640 * 10 /*!< 40ms, uncompressed linear * 10 channels */
00625 
00626 #define MAX_TIMESTAMP_SKEW 160      /*!< maximum difference between actual and predicted ts for sending */
00627 
00628 /* If consecutive voice frame timestamps jump by more than this many milliseconds, then jitter buffer will resync */
00629 #define TS_GAP_FOR_JB_RESYNC  5000
00630 
00631 /* used for first_iax_message and last_iax_message.  If this bit is set it was TX, else RX */
00632 #define MARK_IAX_SUBCLASS_TX  0x8000
00633 
00634 static int iaxthreadcount = DEFAULT_THREAD_COUNT;
00635 static int iaxmaxthreadcount = DEFAULT_MAX_THREAD_COUNT;
00636 static int iaxdynamicthreadcount = 0;
00637 static int iaxdynamicthreadnum = 0;
00638 static int iaxactivethreadcount = 0;
00639 
00640 struct iax_rr {
00641    int jitter;
00642    int losspct;
00643    int losscnt;
00644    int packets;
00645    int delay;
00646    int dropped;
00647    int ooo;
00648 };
00649 
00650 struct iax2_pvt_ref;
00651 
00652 struct chan_iax2_pvt {
00653    /*! Socket to send/receive on for this call */
00654    int sockfd;
00655    /*! Last received voice format */
00656    format_t voiceformat;
00657    /*! Last received video format */
00658    format_t videoformat;
00659    /*! Last sent voice format */
00660    format_t svoiceformat;
00661    /*! Last sent video format */
00662    format_t svideoformat;
00663    /*! What we are capable of sending */
00664    format_t capability;
00665    /*! Last received timestamp */
00666    unsigned int last;
00667    /*! Last sent timestamp - never send the same timestamp twice in a single call */
00668    unsigned int lastsent;
00669    /*! Timestamp of the last video frame sent */
00670    unsigned int lastvsent;
00671    /*! Next outgoing timestamp if everything is good */
00672    unsigned int nextpred;
00673    /*! iax frame subclass that began iax2_pvt entry. 0x8000 bit is set on TX */
00674    int first_iax_message;
00675    /*! Last iax frame subclass sent or received for a iax2_pvt. 0x8000 bit is set on TX */
00676    int last_iax_message;
00677    /*! True if the last voice we transmitted was not silence/CNG */
00678    unsigned int notsilenttx:1;
00679    /*! Ping time */
00680    unsigned int pingtime;
00681    /*! Max time for initial response */
00682    int maxtime;
00683    /*! Peer Address */
00684    struct sockaddr_in addr;
00685    /*! Actual used codec preferences */
00686    struct ast_codec_pref prefs;
00687    /*! Requested codec preferences */
00688    struct ast_codec_pref rprefs;
00689    /*! Our call number */
00690    unsigned short callno;
00691    /*! Our callno_entry entry */
00692    struct callno_entry *callno_entry;
00693    /*! Peer callno */
00694    unsigned short peercallno;
00695    /*! Negotiated format, this is only used to remember what format was
00696        chosen for an unauthenticated call so that the channel can get
00697        created later using the right format */
00698    format_t chosenformat;
00699    /*! Peer selected format */
00700    format_t peerformat;
00701    /*! Peer capability */
00702    format_t peercapability;
00703    /*! timeval that we base our transmission on */
00704    struct timeval offset;
00705    /*! timeval that we base our delivery on */
00706    struct timeval rxcore;
00707    /*! The jitterbuffer */
00708    jitterbuf *jb;
00709    /*! active jb read scheduler id */
00710    int jbid;
00711    /*! LAG */
00712    int lag;
00713    /*! Error, as discovered by the manager */
00714    int error;
00715    /*! Owner if we have one */
00716    struct ast_channel *owner;
00717    /*! What's our state? */
00718    struct ast_flags state;
00719    /*! Expiry (optional) */
00720    int expiry;
00721    /*! Next outgoing sequence number */
00722    unsigned char oseqno;
00723    /*! Next sequence number they have not yet acknowledged */
00724    unsigned char rseqno;
00725    /*! Next incoming sequence number */
00726    unsigned char iseqno;
00727    /*! Last incoming sequence number we have acknowledged */
00728    unsigned char aseqno;
00729 
00730    AST_DECLARE_STRING_FIELDS(
00731       /*! Peer name */
00732       AST_STRING_FIELD(peer);
00733       /*! Default Context */
00734       AST_STRING_FIELD(context);
00735       /*! Caller ID if available */
00736       AST_STRING_FIELD(cid_num);
00737       AST_STRING_FIELD(cid_name);
00738       /*! Hidden Caller ID (i.e. ANI) if appropriate */
00739       AST_STRING_FIELD(ani);
00740       /*! DNID */
00741       AST_STRING_FIELD(dnid);
00742       /*! RDNIS */
00743       AST_STRING_FIELD(rdnis);
00744       /*! Requested Extension */
00745       AST_STRING_FIELD(exten);
00746       /*! Expected Username */
00747       AST_STRING_FIELD(username);
00748       /*! Expected Secret */
00749       AST_STRING_FIELD(secret);
00750       /*! MD5 challenge */
00751       AST_STRING_FIELD(challenge);
00752       /*! Public keys permitted keys for incoming authentication */
00753       AST_STRING_FIELD(inkeys);
00754       /*! Private key for outgoing authentication */
00755       AST_STRING_FIELD(outkey);
00756       /*! Preferred language */
00757       AST_STRING_FIELD(language);
00758       /*! Hostname/peername for naming purposes */
00759       AST_STRING_FIELD(host);
00760 
00761       AST_STRING_FIELD(dproot);
00762       AST_STRING_FIELD(accountcode);
00763       AST_STRING_FIELD(mohinterpret);
00764       AST_STRING_FIELD(mohsuggest);
00765       /*! received OSP token */
00766       AST_STRING_FIELD(osptoken);
00767       /*! Default parkinglot */
00768       AST_STRING_FIELD(parkinglot);
00769    );
00770    /*! AUTHREJ all AUTHREP frames */
00771    int authrej;
00772    /*! permitted authentication methods */
00773    int authmethods;
00774    /*! permitted encryption methods */
00775    int encmethods;
00776    /*! Encryption AES-128 Key */
00777    ast_aes_encrypt_key ecx;
00778    /*! Decryption AES-128 Key corresponding to ecx */
00779    ast_aes_decrypt_key mydcx;
00780    /*! Decryption AES-128 Key used to decrypt peer frames */
00781    ast_aes_decrypt_key dcx;
00782    /*! scheduler id associated with iax_key_rotate 
00783     * for encrypted calls*/
00784    int keyrotateid;
00785    /*! 32 bytes of semi-random data */
00786    unsigned char semirand[32];
00787    /*! Associated registry */
00788    struct iax2_registry *reg;
00789    /*! Associated peer for poking */
00790    struct iax2_peer *peerpoke;
00791    /*! IAX_ flags */
00792    uint64_t flags;
00793    int adsi;
00794 
00795    /*! Transferring status */
00796    enum iax_transfer_state transferring;
00797    /*! Transfer identifier */
00798    int transferid;
00799    /*! Who we are IAX transferring to */
00800    struct sockaddr_in transfer;
00801    /*! What's the new call number for the transfer */
00802    unsigned short transfercallno;
00803    /*! Transfer encrypt AES-128 Key */
00804    ast_aes_encrypt_key tdcx;
00805 
00806    /*! Status of knowledge of peer ADSI capability */
00807    int peeradsicpe;
00808 
00809    /*! Who we are bridged to */
00810    unsigned short bridgecallno;
00811 
00812    int pingid;       /*!< Transmit PING request */
00813    int lagid;        /*!< Retransmit lag request */
00814    int autoid;       /*!< Auto hangup for Dialplan requestor */
00815    int authid;       /*!< Authentication rejection ID */
00816    int authfail;        /*!< Reason to report failure */
00817    int initid;       /*!< Initial peer auto-congest ID (based on qualified peers) */
00818    int calling_ton;
00819    int calling_tns;
00820    int calling_pres;
00821    int amaflags;
00822    AST_LIST_HEAD_NOLOCK(, iax2_dpcache) dpentries;
00823    /*! variables inherited from the user definition */
00824    struct ast_variable *vars;
00825    /*! variables transmitted in a NEW packet */
00826    struct ast_variable *iaxvars;
00827    /*! last received remote rr */
00828    struct iax_rr remote_rr;
00829    /*! Current base time: (just for stats) */
00830    int min;
00831    /*! Dropped frame count: (just for stats) */
00832    int frames_dropped;
00833    /*! received frame count: (just for stats) */
00834    int frames_received;
00835    /*! num bytes used for calltoken ie, even an empty ie should contain 2 */
00836    unsigned char calltoken_ie_len;
00837    /*! hold all signaling frames from the pbx thread until we have a destination callno */
00838    char hold_signaling;
00839    /*! frame queue for signaling frames from pbx thread waiting for destination callno */
00840    AST_LIST_HEAD_NOLOCK(signaling_queue, signaling_queue_entry) signaling_queue;
00841 };
00842 
00843 struct signaling_queue_entry {
00844    struct ast_frame f;
00845    AST_LIST_ENTRY(signaling_queue_entry) next;
00846 };
00847 
00848 /*! table of available call numbers */
00849 static struct ao2_container *callno_pool;
00850 
00851 /*! table of available trunk call numbers */
00852 static struct ao2_container *callno_pool_trunk;
00853 
00854 static const unsigned int CALLNO_POOL_BUCKETS = 2699;
00855 
00856 /*!
00857  * \brief a list of frames that may need to be retransmitted
00858  *
00859  * \note The contents of this list do not need to be explicitly destroyed
00860  * on module unload.  This is because all active calls are destroyed, and
00861  * all frames in this queue will get destroyed as a part of that process.
00862  *
00863  * \note Contents protected by the iaxsl[] locks
00864  */
00865 static AST_LIST_HEAD_NOLOCK(, iax_frame) frame_queue[IAX_MAX_CALLS + 1];
00866 
00867 static struct ast_taskprocessor *transmit_processor;
00868 
00869 static int randomcalltokendata;
00870 
00871 static const time_t MAX_CALLTOKEN_DELAY = 10;
00872 
00873 /*!
00874  * This module will get much higher performance when doing a lot of
00875  * user and peer lookups if the number of buckets is increased from 1.
00876  * However, to maintain old behavior for Asterisk 1.4, these are set to
00877  * 1 by default.  When using multiple buckets, search order through these
00878  * containers is considered random, so you will not be able to depend on
00879  * the order the entires are specified in iax.conf for matching order. */
00880 #ifdef LOW_MEMORY
00881 #define MAX_PEER_BUCKETS 17
00882 #else
00883 #define MAX_PEER_BUCKETS 563
00884 #endif
00885 static struct ao2_container *peers;
00886 
00887 #define MAX_USER_BUCKETS MAX_PEER_BUCKETS
00888 static struct ao2_container *users;
00889 
00890 /*! Table containing peercnt objects for every ip address consuming a callno */
00891 static struct ao2_container *peercnts;
00892 
00893 /*! Table containing custom callno limit rules for a range of ip addresses. */
00894 static struct ao2_container *callno_limits;
00895 
00896 /*! Table containing ip addresses not requiring calltoken validation */
00897 static struct ao2_container *calltoken_ignores;
00898 
00899 static uint16_t DEFAULT_MAXCALLNO_LIMIT = 2048;
00900 
00901 static uint16_t DEFAULT_MAXCALLNO_LIMIT_NONVAL = 8192;
00902 
00903 static uint16_t global_maxcallno;
00904 
00905 /*! Total num of call numbers allowed to be allocated without calltoken validation */
00906 static uint16_t global_maxcallno_nonval;
00907 
00908 static uint16_t total_nonval_callno_used = 0;
00909 
00910 /*! peer connection private, keeps track of all the call numbers
00911  *  consumed by a single ip address */
00912 struct peercnt {
00913    /*! ip address consuming call numbers */
00914    unsigned long addr;
00915    /*! Number of call numbers currently used by this ip address */
00916    uint16_t cur;
00917    /*! Max call numbers allowed for this ip address */
00918    uint16_t limit;
00919    /*! Specifies whether limit is set by a registration or not, if so normal
00920     *  limit setting rules do not apply to this address. */
00921    unsigned char reg;
00922 };
00923 
00924 /*! used by both callno_limits and calltoken_ignores containers */
00925 struct addr_range {
00926    /*! ip address range for custom callno limit rule */
00927    struct ast_ha ha;
00928    /*! callno limit for this ip address range, only used in callno_limits container */
00929    uint16_t limit;
00930    /*! delete me marker for reloads */
00931    unsigned char delme;
00932 };
00933 
00934 struct callno_entry {
00935    /*! callno used for this entry */
00936    uint16_t callno;
00937    /*! was this callno calltoken validated or not */
00938    unsigned char validated;
00939 };
00940 
00941 static AST_LIST_HEAD_STATIC(firmwares, iax_firmware);
00942 
00943 enum {
00944    /*! Extension exists */
00945    CACHE_FLAG_EXISTS      = (1 << 0),
00946    /*! Extension is nonexistent */
00947    CACHE_FLAG_NONEXISTENT = (1 << 1),
00948    /*! Extension can exist */
00949    CACHE_FLAG_CANEXIST    = (1 << 2),
00950    /*! Waiting to hear back response */
00951    CACHE_FLAG_PENDING     = (1 << 3),
00952    /*! Timed out */
00953    CACHE_FLAG_TIMEOUT     = (1 << 4),
00954    /*! Request transmitted */
00955    CACHE_FLAG_TRANSMITTED = (1 << 5),
00956    /*! Timeout */
00957    CACHE_FLAG_UNKNOWN     = (1 << 6),
00958    /*! Matchmore */
00959    CACHE_FLAG_MATCHMORE   = (1 << 7),
00960 };
00961 
00962 struct iax2_dpcache {
00963    char peercontext[AST_MAX_CONTEXT];
00964    char exten[AST_MAX_EXTENSION];
00965    struct timeval orig;
00966    struct timeval expiry;
00967    int flags;
00968    unsigned short callno;
00969    int waiters[256];
00970    AST_LIST_ENTRY(iax2_dpcache) cache_list;
00971    AST_LIST_ENTRY(iax2_dpcache) peer_list;
00972 };
00973 
00974 static AST_LIST_HEAD_STATIC(dpcache, iax2_dpcache);
00975 
00976 static void reg_source_db(struct iax2_peer *p);
00977 static struct iax2_peer *realtime_peer(const char *peername, struct sockaddr_in *sin);
00978 static struct iax2_user *realtime_user(const char *username, struct sockaddr_in *sin);
00979 
00980 static int ast_cli_netstats(struct mansession *s, int fd, int limit_fmt);
00981 static char *complete_iax2_peers(const char *line, const char *word, int pos, int state, uint64_t flags);
00982 static char *complete_iax2_unregister(const char *line, const char *word, int pos, int state);
00983 
00984 enum iax2_thread_iostate {
00985    IAX_IOSTATE_IDLE,
00986    IAX_IOSTATE_READY,
00987    IAX_IOSTATE_PROCESSING,
00988    IAX_IOSTATE_SCHEDREADY,
00989 };
00990 
00991 enum iax2_thread_type {
00992    IAX_THREAD_TYPE_POOL,
00993    IAX_THREAD_TYPE_DYNAMIC,
00994 };
00995 
00996 struct iax2_pkt_buf {
00997    AST_LIST_ENTRY(iax2_pkt_buf) entry;
00998    size_t len;
00999    unsigned char buf[1];
01000 };
01001 
01002 struct iax2_thread {
01003    AST_LIST_ENTRY(iax2_thread) list;
01004    enum iax2_thread_type type;
01005    enum iax2_thread_iostate iostate;
01006 #ifdef SCHED_MULTITHREADED
01007    void (*schedfunc)(const void *);
01008    const void *scheddata;
01009 #endif
01010 #ifdef DEBUG_SCHED_MULTITHREAD
01011    char curfunc[80];
01012 #endif   
01013    int actions;
01014    pthread_t threadid;
01015    int threadnum;
01016    struct sockaddr_in iosin;
01017    unsigned char readbuf[4096]; 
01018    unsigned char *buf;
01019    ssize_t buf_len;
01020    size_t buf_size;
01021    int iofd;
01022    time_t checktime;
01023    ast_mutex_t lock;
01024    ast_cond_t cond;
01025    ast_mutex_t init_lock;
01026    ast_cond_t init_cond;
01027    /*! if this thread is processing a full frame,
01028      some information about that frame will be stored
01029      here, so we can avoid dispatching any more full
01030      frames for that callno to other threads */
01031    struct {
01032       unsigned short callno;
01033       struct sockaddr_in sin;
01034       unsigned char type;
01035       unsigned char csub;
01036    } ffinfo;
01037    /*! Queued up full frames for processing.  If more full frames arrive for
01038     *  a call which this thread is already processing a full frame for, they
01039     *  are queued up here. */
01040    AST_LIST_HEAD_NOLOCK(, iax2_pkt_buf) full_frames;
01041    unsigned char stop;
01042 };
01043 
01044 /* Thread lists */
01045 static AST_LIST_HEAD_STATIC(idle_list, iax2_thread);
01046 static AST_LIST_HEAD_STATIC(active_list, iax2_thread);
01047 static AST_LIST_HEAD_STATIC(dynamic_list, iax2_thread);
01048 
01049 static void *iax2_process_thread(void *data);
01050 static void iax2_destroy(int callno);
01051 
01052 static void signal_condition(ast_mutex_t *lock, ast_cond_t *cond)
01053 {
01054    ast_mutex_lock(lock);
01055    ast_cond_signal(cond);
01056    ast_mutex_unlock(lock);
01057 }
01058 
01059 /*!
01060  * \brief an array of iax2 pvt structures
01061  *
01062  * The container for active chan_iax2_pvt structures is implemented as an
01063  * array for extremely quick direct access to the correct pvt structure
01064  * based on the local call number.  The local call number is used as the
01065  * index into the array where the associated pvt structure is stored.
01066  */
01067 static struct chan_iax2_pvt *iaxs[IAX_MAX_CALLS + 1];
01068 
01069 /*!
01070  * \brief Another container of iax2_pvt structures
01071  *
01072  * Active IAX2 pvt structs are also stored in this container, if they are a part
01073  * of an active call where we know the remote side's call number.  The reason
01074  * for this is that incoming media frames do not contain our call number.  So,
01075  * instead of having to iterate the entire iaxs array, we use this container to
01076  * look up calls where the remote side is using a given call number.
01077  */
01078 static struct ao2_container *iax_peercallno_pvts;
01079 
01080 /*!
01081  * \brief chan_iax2_pvt structure locks
01082  *
01083  * These locks are used when accessing a pvt structure in the iaxs array.
01084  * The index used here is the same as used in the iaxs array.  It is the
01085  * local call number for the associated pvt struct.
01086  */
01087 static ast_mutex_t iaxsl[ARRAY_LEN(iaxs)];
01088 
01089 /*!
01090  *  * \brief Another container of iax2_pvt structures
01091  *  
01092  *  Active IAX2 pvt stucts used during transfering a call are stored here.  
01093  */
01094 static struct ao2_container *iax_transfercallno_pvts;
01095 
01096 /* Flag to use with trunk calls, keeping these calls high up.  It halves our effective use
01097    but keeps the division between trunked and non-trunked better. */
01098 #define TRUNK_CALL_START   IAX_MAX_CALLS / 2
01099 
01100 /* Debug routines... */
01101 static struct sockaddr_in debugaddr;
01102 
01103 static void iax_outputframe(struct iax_frame *f, struct ast_iax2_full_hdr *fhi, int rx, struct sockaddr_in *sin, int datalen)
01104 {
01105    if (iaxdebug ||
01106        (sin && debugaddr.sin_addr.s_addr && 
01107         (!ntohs(debugaddr.sin_port) ||
01108          debugaddr.sin_port == sin->sin_port) &&
01109         debugaddr.sin_addr.s_addr == sin->sin_addr.s_addr)) {
01110       if (iaxdebug) {
01111          iax_showframe(f, fhi, rx, sin, datalen);
01112       } else {
01113          iaxdebug = 1;
01114          iax_showframe(f, fhi, rx, sin, datalen);
01115          iaxdebug = 0;
01116       }
01117    }
01118 }
01119 
01120 static void iax_debug_output(const char *data)
01121 {
01122    if (iaxdebug)
01123       ast_verbose("%s", data);
01124 }
01125 
01126 static void iax_error_output(const char *data)
01127 {
01128    ast_log(LOG_WARNING, "%s", data);
01129 }
01130 
01131 static void __attribute__((format(printf, 1, 2))) jb_error_output(const char *fmt, ...)
01132 {
01133    va_list args;
01134    char buf[1024];
01135 
01136    va_start(args, fmt);
01137    vsnprintf(buf, sizeof(buf), fmt, args);
01138    va_end(args);
01139 
01140    ast_log(LOG_ERROR, "%s", buf);
01141 }
01142 
01143 static void __attribute__((format(printf, 1, 2))) jb_warning_output(const char *fmt, ...)
01144 {
01145    va_list args;
01146    char buf[1024];
01147 
01148    va_start(args, fmt);
01149    vsnprintf(buf, sizeof(buf), fmt, args);
01150    va_end(args);
01151 
01152    ast_log(LOG_WARNING, "%s", buf);
01153 }
01154 
01155 static void __attribute__((format(printf, 1, 2))) jb_debug_output(const char *fmt, ...)
01156 {
01157    va_list args;
01158    char buf[1024];
01159 
01160    va_start(args, fmt);
01161    vsnprintf(buf, sizeof(buf), fmt, args);
01162    va_end(args);
01163 
01164    ast_verbose("%s", buf);
01165 }
01166 
01167 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);
01168 static int expire_registry(const void *data);
01169 static int iax2_answer(struct ast_channel *c);
01170 static int iax2_call(struct ast_channel *c, char *dest, int timeout);
01171 static int iax2_devicestate(void *data);
01172 static int iax2_digit_begin(struct ast_channel *c, char digit);
01173 static int iax2_digit_end(struct ast_channel *c, char digit, unsigned int duration);
01174 static int iax2_do_register(struct iax2_registry *reg);
01175 static int iax2_fixup(struct ast_channel *oldchannel, struct ast_channel *newchan);
01176 static int iax2_hangup(struct ast_channel *c);
01177 static int iax2_indicate(struct ast_channel *c, int condition, const void *data, size_t datalen);
01178 static int iax2_poke_peer(struct iax2_peer *peer, int heldcall);
01179 static int iax2_provision(struct sockaddr_in *end, int sockfd, const char *dest, const char *template, int force);
01180 static int iax2_send(struct chan_iax2_pvt *pvt, struct ast_frame *f, unsigned int ts, int seqno, int now, int transfer, int final);
01181 static int iax2_sendhtml(struct ast_channel *c, int subclass, const char *data, int datalen);
01182 static int iax2_sendimage(struct ast_channel *c, struct ast_frame *img);
01183 static int iax2_sendtext(struct ast_channel *c, const char *text);
01184 static int iax2_setoption(struct ast_channel *c, int option, void *data, int datalen);
01185 static int iax2_queryoption(struct ast_channel *c, int option, void *data, int *datalen);
01186 static int iax2_transfer(struct ast_channel *c, const char *dest);
01187 static int iax2_write(struct ast_channel *c, struct ast_frame *f);
01188 static int iax2_sched_add(struct ast_sched_thread *st, int when, ast_sched_cb callback, const void *data);
01189 
01190 static int send_trunk(struct iax2_trunk_peer *tpeer, struct timeval *now);
01191 static int send_command(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
01192 static int send_command_final(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
01193 static int send_command_immediate(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
01194 static int send_command_locked(unsigned short callno, char, int, unsigned int, const unsigned char *, int, int);
01195 static int send_command_transfer(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int);
01196 static struct ast_channel *iax2_request(const char *type, format_t format, const struct ast_channel *requestor, void *data, int *cause);
01197 static struct ast_frame *iax2_read(struct ast_channel *c);
01198 static struct iax2_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly);
01199 static struct iax2_user *build_user(const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly);
01200 static void realtime_update_peer(const char *peername, struct ast_sockaddr *sockaddr, time_t regtime);
01201 static void *iax2_dup_variable_datastore(void *);
01202 static void prune_peers(void);
01203 static void prune_users(void);
01204 static void iax2_free_variable_datastore(void *);
01205 
01206 static int acf_channel_read(struct ast_channel *chan, const char *funcname, char *preparse, char *buf, size_t buflen);
01207 static int decode_frame(ast_aes_decrypt_key *dcx, struct ast_iax2_full_hdr *fh, struct ast_frame *f, int *datalen);
01208 static int encrypt_frame(ast_aes_encrypt_key *ecx, struct ast_iax2_full_hdr *fh, unsigned char *poo, int *datalen);
01209 static void build_ecx_key(const unsigned char *digest, struct chan_iax2_pvt *pvt);
01210 static void build_rand_pad(unsigned char *buf, ssize_t len);
01211 static struct callno_entry *get_unused_callno(int trunk, int validated);
01212 static int replace_callno(const void *obj);
01213 static void sched_delay_remove(struct sockaddr_in *sin, struct callno_entry *callno_entry);
01214 static void network_change_event_cb(const struct ast_event *, void *);
01215 
01216 static const struct ast_channel_tech iax2_tech = {
01217    .type = "IAX2",
01218    .description = tdesc,
01219    .capabilities = IAX_CAPABILITY_FULLBANDWIDTH,
01220    .properties = AST_CHAN_TP_WANTSJITTER,
01221    .requester = iax2_request,
01222    .devicestate = iax2_devicestate,
01223    .send_digit_begin = iax2_digit_begin,
01224    .send_digit_end = iax2_digit_end,
01225    .send_text = iax2_sendtext,
01226    .send_image = iax2_sendimage,
01227    .send_html = iax2_sendhtml,
01228    .call = iax2_call,
01229    .hangup = iax2_hangup,
01230    .answer = iax2_answer,
01231    .read = iax2_read,
01232    .write = iax2_write,
01233    .write_video = iax2_write,
01234    .indicate = iax2_indicate,
01235    .setoption = iax2_setoption,
01236    .queryoption = iax2_queryoption,
01237    .bridge = iax2_bridge,
01238    .transfer = iax2_transfer,
01239    .fixup = iax2_fixup,
01240    .func_channel_read = acf_channel_read,
01241 };
01242 
01243 /*!
01244  * \internal
01245  * \brief Obtain the owner channel lock if the owner exists.
01246  *
01247  * \param callno IAX2 call id.
01248  *
01249  * \note Assumes the iaxsl[callno] lock is already obtained.
01250  *
01251  * \note
01252  * IMPORTANT NOTE!!!  Any time this function is used, even if
01253  * iaxs[callno] was valid before calling it, it may no longer be
01254  * valid after calling it.  This function may unlock and lock
01255  * the mutex associated with this callno, meaning that another
01256  * thread may grab it and destroy the call.
01257  *
01258  * \return Nothing
01259  */
01260 static void iax2_lock_owner(int callno)
01261 {
01262    for (;;) {
01263       if (!iaxs[callno] || !iaxs[callno]->owner) {
01264          /* There is no owner lock to get. */
01265          break;
01266       }
01267       if (!ast_channel_trylock(iaxs[callno]->owner)) {
01268          /* We got the lock */
01269          break;
01270       }
01271       /* Avoid deadlock by pausing and trying again */
01272       DEADLOCK_AVOIDANCE(&iaxsl[callno]);
01273    }
01274 }
01275 
01276 static void mwi_event_cb(const struct ast_event *event, void *userdata)
01277 {
01278    /* The MWI subscriptions exist just so the core knows we care about those
01279     * mailboxes.  However, we just grab the events out of the cache when it
01280     * is time to send MWI, since it is only sent with a REGACK. */
01281 }
01282 
01283 static void network_change_event_subscribe(void)
01284 {
01285    if (!network_change_event_subscription) {
01286       network_change_event_subscription = ast_event_subscribe(AST_EVENT_NETWORK_CHANGE,
01287          network_change_event_cb, "IAX2 Network Change", NULL, AST_EVENT_IE_END);
01288    }
01289 }
01290 
01291 static void network_change_event_unsubscribe(void)
01292 {
01293    if (network_change_event_subscription) {
01294       network_change_event_subscription = ast_event_unsubscribe(network_change_event_subscription);
01295    }
01296 }
01297 
01298 static int network_change_event_sched_cb(const void *data)
01299 {
01300    struct iax2_registry *reg;
01301    network_change_event_sched_id = -1;
01302    AST_LIST_LOCK(&registrations);
01303    AST_LIST_TRAVERSE(&registrations, reg, entry) {
01304       iax2_do_register(reg);
01305    }
01306    AST_LIST_UNLOCK(&registrations);
01307 
01308    return 0;
01309 }
01310 
01311 static void network_change_event_cb(const struct ast_event *event, void *userdata)
01312 {
01313    ast_debug(1, "IAX, got a network change event, renewing all IAX registrations.\n");
01314    if (network_change_event_sched_id == -1) {
01315       network_change_event_sched_id = iax2_sched_add(sched, 1000, network_change_event_sched_cb, NULL);
01316    }
01317 
01318 }
01319 
01320 
01321 /*! \brief Send manager event at call setup to link between Asterisk channel name
01322    and IAX2 call identifiers */
01323 static void iax2_ami_channelupdate(struct chan_iax2_pvt *pvt) 
01324 {
01325    manager_event(EVENT_FLAG_SYSTEM, "ChannelUpdate",
01326       "Channel: %s\r\nChanneltype: IAX2\r\nIAX2-callno-local: %d\r\nIAX2-callno-remote: %d\r\nIAX2-peer: %s\r\n",
01327       pvt->owner ? pvt->owner->name : "",
01328       pvt->callno, pvt->peercallno, pvt->peer ? pvt->peer : "");
01329 }
01330 
01331 static struct ast_datastore_info iax2_variable_datastore_info = {
01332    .type = "IAX2_VARIABLE",
01333    .duplicate = iax2_dup_variable_datastore,
01334    .destroy = iax2_free_variable_datastore,
01335 };
01336 
01337 static void *iax2_dup_variable_datastore(void *old)
01338 {
01339    AST_LIST_HEAD(, ast_var_t) *oldlist = old, *newlist;
01340    struct ast_var_t *oldvar, *newvar;
01341 
01342    newlist = ast_calloc(sizeof(*newlist), 1);
01343    if (!newlist) {
01344       ast_log(LOG_ERROR, "Unable to duplicate iax2 variables\n");
01345       return NULL;
01346    }
01347 
01348    AST_LIST_HEAD_INIT(newlist);
01349    AST_LIST_LOCK(oldlist);
01350    AST_LIST_TRAVERSE(oldlist, oldvar, entries) {
01351       newvar = ast_var_assign(ast_var_name(oldvar), ast_var_value(oldvar));
01352       if (newvar)
01353          AST_LIST_INSERT_TAIL(newlist, newvar, entries);
01354       else
01355          ast_log(LOG_ERROR, "Unable to duplicate iax2 variable '%s'\n", ast_var_name(oldvar));
01356    }
01357    AST_LIST_UNLOCK(oldlist);
01358    return newlist;
01359 }
01360 
01361 static void iax2_free_variable_datastore(void *old)
01362 {
01363    AST_LIST_HEAD(, ast_var_t) *oldlist = old;
01364    struct ast_var_t *oldvar;
01365 
01366    AST_LIST_LOCK(oldlist);
01367    while ((oldvar = AST_LIST_REMOVE_HEAD(oldlist, entries))) {
01368       ast_free(oldvar);
01369    }
01370    AST_LIST_UNLOCK(oldlist);
01371    AST_LIST_HEAD_DESTROY(oldlist);
01372    ast_free(oldlist);
01373 }
01374 
01375 
01376 /* WARNING: insert_idle_thread should only ever be called within the
01377  * context of an iax2_process_thread() thread.
01378  */
01379 static void insert_idle_thread(struct iax2_thread *thread)
01380 {
01381    if (thread->type == IAX_THREAD_TYPE_DYNAMIC) {
01382       AST_LIST_LOCK(&dynamic_list);
01383       AST_LIST_INSERT_TAIL(&dynamic_list, thread, list);
01384       AST_LIST_UNLOCK(&dynamic_list);
01385    } else {
01386       AST_LIST_LOCK(&idle_list);
01387       AST_LIST_INSERT_TAIL(&idle_list, thread, list);
01388       AST_LIST_UNLOCK(&idle_list);
01389    }
01390 
01391    return;
01392 }
01393 
01394 static struct iax2_thread *find_idle_thread(void)
01395 {
01396    struct iax2_thread *thread = NULL;
01397 
01398    /* Pop the head of the idle list off */
01399    AST_LIST_LOCK(&idle_list);
01400    thread = AST_LIST_REMOVE_HEAD(&idle_list, list);
01401    AST_LIST_UNLOCK(&idle_list);
01402 
01403    /* If we popped a thread off the idle list, just return it */
01404    if (thread) {
01405       memset(&thread->ffinfo, 0, sizeof(thread->ffinfo));
01406       return thread;
01407    }
01408 
01409    /* Pop the head of the dynamic list off */
01410    AST_LIST_LOCK(&dynamic_list);
01411    thread = AST_LIST_REMOVE_HEAD(&dynamic_list, list);
01412    AST_LIST_UNLOCK(&dynamic_list);
01413 
01414    /* If we popped a thread off the dynamic list, just return it */
01415    if (thread) {
01416       memset(&thread->ffinfo, 0, sizeof(thread->ffinfo));
01417       return thread;
01418    }
01419 
01420    /* If we can't create a new dynamic thread for any reason, return no thread at all */
01421    if (iaxdynamicthreadcount >= iaxmaxthreadcount || !(thread = ast_calloc(1, sizeof(*thread))))
01422       return NULL;
01423 
01424    /* Set default values */
01425    ast_atomic_fetchadd_int(&iaxdynamicthreadcount, 1);
01426    thread->threadnum = ast_atomic_fetchadd_int(&iaxdynamicthreadnum, 1);
01427    thread->type = IAX_THREAD_TYPE_DYNAMIC;
01428 
01429    /* Initialize lock and condition */
01430    ast_mutex_init(&thread->lock);
01431    ast_cond_init(&thread->cond, NULL);
01432    ast_mutex_init(&thread->init_lock);
01433    ast_cond_init(&thread->init_cond, NULL);
01434    ast_mutex_lock(&thread->init_lock);
01435 
01436    /* Create thread and send it on it's way */
01437    if (ast_pthread_create_background(&thread->threadid, NULL, iax2_process_thread, thread)) {
01438       ast_cond_destroy(&thread->cond);
01439       ast_mutex_destroy(&thread->lock);
01440       ast_mutex_unlock(&thread->init_lock);
01441       ast_cond_destroy(&thread->init_cond);
01442       ast_mutex_destroy(&thread->init_lock);
01443       ast_free(thread);
01444       return NULL;
01445    }
01446 
01447    /* this thread is not processing a full frame (since it is idle),
01448       so ensure that the field for the full frame call number is empty */
01449    memset(&thread->ffinfo, 0, sizeof(thread->ffinfo));
01450 
01451    /* Wait for the thread to be ready before returning it to the caller */
01452    ast_cond_wait(&thread->init_cond, &thread->init_lock);
01453 
01454    /* Done with init_lock */
01455    ast_mutex_unlock(&thread->init_lock);
01456 
01457    return thread;
01458 }
01459 
01460 #ifdef SCHED_MULTITHREADED
01461 static int __schedule_action(void (*func)(const void *data), const void *data, const char *funcname)
01462 {
01463    struct iax2_thread *thread = NULL;
01464    static time_t lasterror;
01465    static time_t t;
01466 
01467    thread = find_idle_thread();
01468 
01469    if (thread != NULL) {
01470       thread->schedfunc = func;
01471       thread->scheddata = data;
01472       thread->iostate = IAX_IOSTATE_SCHEDREADY;
01473 #ifdef DEBUG_SCHED_MULTITHREAD
01474       ast_copy_string(thread->curfunc, funcname, sizeof(thread->curfunc));
01475 #endif
01476       signal_condition(&thread->lock, &thread->cond);
01477       return 0;
01478    }
01479    time(&t);
01480    if (t != lasterror) 
01481       ast_debug(1, "Out of idle IAX2 threads for scheduling!\n");
01482    lasterror = t;
01483 
01484    return -1;
01485 }
01486 #define schedule_action(func, data) __schedule_action(func, data, __PRETTY_FUNCTION__)
01487 #endif
01488 
01489 static int iax2_sched_replace(int id, struct ast_sched_thread *st, int when, 
01490       ast_sched_cb callback, const void *data)
01491 {
01492    ast_sched_thread_del(st, id);
01493 
01494    return ast_sched_thread_add(st, when, callback, data);
01495 }
01496 
01497 static int iax2_sched_add(struct ast_sched_thread *st, int when, 
01498       ast_sched_cb callback, const void *data)
01499 {
01500    return ast_sched_thread_add(st, when, callback, data);
01501 }
01502 
01503 static int send_ping(const void *data);
01504 
01505 static void __send_ping(const void *data)
01506 {
01507    int callno = (long) data;
01508 
01509    ast_mutex_lock(&iaxsl[callno]);
01510 
01511    if (iaxs[callno]) {
01512       if (iaxs[callno]->peercallno) {
01513          send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_PING, 0, NULL, 0, -1);
01514          if (iaxs[callno]->pingid != DONT_RESCHEDULE) {
01515             iaxs[callno]->pingid = iax2_sched_add(sched, ping_time * 1000, send_ping, data);
01516          }
01517       }
01518    } else {
01519       ast_debug(1, "I was supposed to send a PING with callno %d, but no such call exists.\n", callno);
01520    }
01521 
01522    ast_mutex_unlock(&iaxsl[callno]);
01523 }
01524 
01525 static int send_ping(const void *data)
01526 {
01527    int callno = (long) data;
01528    ast_mutex_lock(&iaxsl[callno]);
01529    if (iaxs[callno] && iaxs[callno]->pingid != DONT_RESCHEDULE) {
01530       iaxs[callno]->pingid = -1;
01531    }
01532    ast_mutex_unlock(&iaxsl[callno]);
01533 
01534 #ifdef SCHED_MULTITHREADED
01535    if (schedule_action(__send_ping, data))
01536 #endif
01537       __send_ping(data);
01538 
01539    return 0;
01540 }
01541 
01542 static void encmethods_to_str(int e, struct ast_str *buf)
01543 {
01544    ast_str_set(&buf, 0, "(");
01545    if (e & IAX_ENCRYPT_AES128) {
01546       ast_str_append(&buf, 0, "aes128");
01547    }
01548    if (e & IAX_ENCRYPT_KEYROTATE) {
01549       ast_str_append(&buf, 0, ",keyrotate");
01550    }
01551    if (ast_str_strlen(buf) > 1) {
01552       ast_str_append(&buf, 0, ")");
01553    } else {
01554       ast_str_set(&buf, 0, "No");
01555    }
01556 }
01557 
01558 static int get_encrypt_methods(const char *s)
01559 {
01560    int e;
01561    if (!strcasecmp(s, "aes128"))
01562       e = IAX_ENCRYPT_AES128 | IAX_ENCRYPT_KEYROTATE;
01563    else if (ast_true(s))
01564       e = IAX_ENCRYPT_AES128 | IAX_ENCRYPT_KEYROTATE;
01565    else
01566       e = 0;
01567    return e;
01568 }
01569 
01570 static int send_lagrq(const void *data);
01571 
01572 static void __send_lagrq(const void *data)
01573 {
01574    int callno = (long) data;
01575 
01576    ast_mutex_lock(&iaxsl[callno]);
01577 
01578    if (iaxs[callno]) {
01579       if (iaxs[callno]->peercallno) {
01580          send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_LAGRQ, 0, NULL, 0, -1);
01581          if (iaxs[callno]->lagid != DONT_RESCHEDULE) {
01582             iaxs[callno]->lagid = iax2_sched_add(sched, lagrq_time * 1000, send_lagrq, data);
01583          }
01584       }
01585    } else {
01586       ast_debug(1, "I was supposed to send a LAGRQ with callno %d, but no such call exists.\n", callno);
01587    }
01588 
01589    ast_mutex_unlock(&iaxsl[callno]);
01590 }
01591 
01592 static int send_lagrq(const void *data)
01593 {
01594    int callno = (long) data;
01595    ast_mutex_lock(&iaxsl[callno]);
01596    if (iaxs[callno] && iaxs[callno]->lagid != DONT_RESCHEDULE) {
01597       iaxs[callno]->lagid = -1;
01598    }
01599    ast_mutex_unlock(&iaxsl[callno]);
01600 
01601 #ifdef SCHED_MULTITHREADED
01602    if (schedule_action(__send_lagrq, data))
01603 #endif
01604       __send_lagrq(data);
01605    return 0;
01606 }
01607 
01608 static unsigned char compress_subclass(format_t subclass)
01609 {
01610    int x;
01611    int power=-1;
01612    /* If it's 64 or smaller, just return it */
01613    if (subclass < IAX_FLAG_SC_LOG)
01614       return subclass;
01615    /* Otherwise find its power */
01616    for (x = 0; x < IAX_MAX_SHIFT; x++) {
01617       if (subclass & (1LL << x)) {
01618          if (power > -1) {
01619             ast_log(LOG_WARNING, "Can't compress subclass %lld\n", (long long) subclass);
01620             return 0;
01621          } else
01622             power = x;
01623       }
01624    }
01625    return power | IAX_FLAG_SC_LOG;
01626 }
01627 
01628 static format_t uncompress_subclass(unsigned char csub)
01629 {
01630    /* If the SC_LOG flag is set, return 2^csub otherwise csub */
01631    if (csub & IAX_FLAG_SC_LOG) {
01632       /* special case for 'compressed' -1 */
01633       if (csub == 0xff)
01634          return -1;
01635       else
01636          return 1LL << (csub & ~IAX_FLAG_SC_LOG & IAX_MAX_SHIFT);
01637    }
01638    else
01639       return csub;
01640 }
01641 
01642 /*!
01643  * \note The only member of the peer passed here guaranteed to be set is the name field
01644  */
01645 static int peer_hash_cb(const void *obj, const int flags)
01646 {
01647    const struct iax2_peer *peer = obj;
01648 
01649    return ast_str_hash(peer->name);
01650 }
01651 
01652 /*!
01653  * \note The only member of the peer passed here guaranteed to be set is the name field
01654  */
01655 static int peer_cmp_cb(void *obj, void *arg, int flags)
01656 {
01657    struct iax2_peer *peer = obj, *peer2 = arg;
01658 
01659    return !strcmp(peer->name, peer2->name) ? CMP_MATCH | CMP_STOP : 0;
01660 }
01661 
01662 /*!
01663  * \note The only member of the user passed here guaranteed to be set is the name field
01664  */
01665 static int user_hash_cb(const void *obj, const int flags)
01666 {
01667    const struct iax2_user *user = obj;
01668 
01669    return ast_str_hash(user->name);
01670 }
01671 
01672 /*!
01673  * \note The only member of the user passed here guaranteed to be set is the name field
01674  */
01675 static int user_cmp_cb(void *obj, void *arg, int flags)
01676 {
01677    struct iax2_user *user = obj, *user2 = arg;
01678 
01679    return !strcmp(user->name, user2->name) ? CMP_MATCH | CMP_STOP : 0;
01680 }
01681 
01682 /*!
01683  * \note This funtion calls realtime_peer -> reg_source_db -> iax2_poke_peer -> find_callno,
01684  *       so do not call it with a pvt lock held.
01685  */
01686 static struct iax2_peer *find_peer(const char *name, int realtime) 
01687 {
01688    struct iax2_peer *peer = NULL;
01689    struct iax2_peer tmp_peer = {
01690       .name = name,
01691    };
01692 
01693    peer = ao2_find(peers, &tmp_peer, OBJ_POINTER);
01694 
01695    /* Now go for realtime if applicable */
01696    if(!peer && realtime)
01697       peer = realtime_peer(name, NULL);
01698 
01699    return peer;
01700 }
01701 
01702 static struct iax2_peer *peer_ref(struct iax2_peer *peer)
01703 {
01704    ao2_ref(peer, +1);
01705    return peer;
01706 }
01707 
01708 static inline struct iax2_peer *peer_unref(struct iax2_peer *peer)
01709 {
01710    ao2_ref(peer, -1);
01711    return NULL;
01712 }
01713 
01714 static struct iax2_user *find_user(const char *name)
01715 {
01716    struct iax2_user tmp_user = {
01717       .name = name,
01718    };
01719 
01720    return ao2_find(users, &tmp_user, OBJ_POINTER);
01721 }
01722 static inline struct iax2_user *user_ref(struct iax2_user *user)
01723 {
01724    ao2_ref(user, +1);
01725    return user;
01726 }
01727 
01728 static inline struct iax2_user *user_unref(struct iax2_user *user)
01729 {
01730    ao2_ref(user, -1);
01731    return NULL;
01732 }
01733 
01734 static int iax2_getpeername(struct sockaddr_in sin, char *host, int len)
01735 {
01736    struct iax2_peer *peer = NULL;
01737    int res = 0;
01738    struct ao2_iterator i;
01739 
01740    i = ao2_iterator_init(peers, 0);
01741    while ((peer = ao2_iterator_next(&i))) {
01742       struct sockaddr_in peer_addr;
01743 
01744       ast_sockaddr_to_sin(&peer->addr, &peer_addr);
01745 
01746       if ((peer_addr.sin_addr.s_addr == sin.sin_addr.s_addr) &&
01747           (peer_addr.sin_port == sin.sin_port)) {
01748          ast_copy_string(host, peer->name, len);
01749          peer_unref(peer);
01750          res = 1;
01751          break;
01752       }
01753       peer_unref(peer);
01754    }
01755    ao2_iterator_destroy(&i);
01756 
01757    if (!peer) {
01758       peer = realtime_peer(NULL, &sin);
01759       if (peer) {
01760          ast_copy_string(host, peer->name, len);
01761          peer_unref(peer);
01762          res = 1;
01763       }
01764    }
01765 
01766    return res;
01767 }
01768 
01769 /*!\note Assumes the lock on the pvt is already held, when
01770  * iax2_destroy_helper() is called. */
01771 static void iax2_destroy_helper(struct chan_iax2_pvt *pvt)
01772 {
01773    /* Decrement AUTHREQ count if needed */
01774    if (ast_test_flag64(pvt, IAX_MAXAUTHREQ)) {
01775       struct iax2_user *user;
01776       struct iax2_user tmp_user = {
01777          .name = pvt->username,
01778       };
01779 
01780       user = ao2_find(users, &tmp_user, OBJ_POINTER);
01781       if (user) {
01782          ast_atomic_fetchadd_int(&user->curauthreq, -1);
01783          user_unref(user);
01784       }
01785 
01786       ast_clear_flag64(pvt, IAX_MAXAUTHREQ);
01787    }
01788    /* No more pings or lagrq's */
01789    AST_SCHED_DEL_SPINLOCK(ast_sched_thread_get_context(sched), pvt->pingid, &iaxsl[pvt->callno]);
01790    pvt->pingid = DONT_RESCHEDULE;
01791    AST_SCHED_DEL_SPINLOCK(ast_sched_thread_get_context(sched), pvt->lagid, &iaxsl[pvt->callno]);
01792    pvt->lagid = DONT_RESCHEDULE;
01793    ast_sched_thread_del(sched, pvt->autoid);
01794    ast_sched_thread_del(sched, pvt->authid);
01795    ast_sched_thread_del(sched, pvt->initid);
01796    ast_sched_thread_del(sched, pvt->jbid);
01797    ast_sched_thread_del(sched, pvt->keyrotateid);
01798 }
01799 
01800 static void iax2_frame_free(struct iax_frame *fr)
01801 {
01802    ast_sched_thread_del(sched, fr->retrans);
01803    iax_frame_free(fr);
01804 }
01805 
01806 static int scheduled_destroy(const void *vid)
01807 {
01808    unsigned short callno = PTR_TO_CALLNO(vid);
01809    ast_mutex_lock(&iaxsl[callno]);
01810    if (iaxs[callno]) {
01811       if (option_debug) {
01812          ast_log(LOG_DEBUG, "Really destroying %d now...\n", callno);
01813       }
01814       iax2_destroy(callno);
01815    }
01816    ast_mutex_unlock(&iaxsl[callno]);
01817    return 0;
01818 }
01819 
01820 static void free_signaling_queue_entry(struct signaling_queue_entry *s)
01821 {
01822    if (s->f.datalen) {
01823       ast_free(s->f.data.ptr);
01824    }
01825    ast_free(s);
01826 }
01827 
01828 /*! \brief This function must be called once we are sure the other side has
01829  *  given us a call number.  All signaling is held here until that point. */
01830 static void send_signaling(struct chan_iax2_pvt *pvt)
01831 {
01832    struct signaling_queue_entry *s = NULL;
01833 
01834    while ((s = AST_LIST_REMOVE_HEAD(&pvt->signaling_queue, next))) {
01835       iax2_send(pvt, &s->f, 0, -1, 0, 0, 0);
01836       free_signaling_queue_entry(s);
01837    }
01838    pvt->hold_signaling = 0;
01839 }
01840 
01841 /*! \brief All frames other than that of type AST_FRAME_IAX must be held until
01842  *  we have received a destination call number. */
01843 static int queue_signalling(struct chan_iax2_pvt *pvt, struct ast_frame *f)
01844 {
01845    struct signaling_queue_entry *new;
01846 
01847    if (f->frametype == AST_FRAME_IAX || !pvt->hold_signaling) {
01848       return 1; /* do not queue this frame */
01849    } else if (!(new = ast_calloc(1, sizeof(struct signaling_queue_entry)))) {
01850       return -1;  /* out of memory */
01851    }
01852 
01853    memcpy(&new->f, f, sizeof(new->f)); /* copy ast_frame into our queue entry */
01854 
01855    if (new->f.datalen) { /* if there is data in this frame copy it over as well */
01856       if (!(new->f.data.ptr = ast_calloc(1, new->f.datalen))) {
01857          free_signaling_queue_entry(new);
01858          return -1;
01859       }
01860       memcpy(new->f.data.ptr, f->data.ptr, sizeof(*new->f.data.ptr));
01861    }
01862    AST_LIST_INSERT_TAIL(&pvt->signaling_queue, new, next);
01863 
01864    return 0;
01865 }
01866 
01867 static void pvt_destructor(void *obj)
01868 {
01869    struct chan_iax2_pvt *pvt = obj;
01870    struct iax_frame *cur = NULL;
01871    struct signaling_queue_entry *s = NULL;
01872 
01873    ast_mutex_lock(&iaxsl[pvt->callno]);
01874 
01875    iax2_destroy_helper(pvt);
01876 
01877    sched_delay_remove(&pvt->addr, pvt->callno_entry);
01878    pvt->callno_entry = NULL;
01879 
01880    /* Already gone */
01881    ast_set_flag64(pvt, IAX_ALREADYGONE);
01882 
01883    AST_LIST_TRAVERSE(&frame_queue[pvt->callno], cur, list) {
01884       /* Cancel any pending transmissions */
01885       cur->retries = -1;
01886    }
01887 
01888    ast_mutex_unlock(&iaxsl[pvt->callno]);
01889 
01890    while ((s = AST_LIST_REMOVE_HEAD(&pvt->signaling_queue, next))) {
01891       free_signaling_queue_entry(s);
01892    }
01893 
01894    if (pvt->reg) {
01895       pvt->reg->callno = 0;
01896    }
01897 
01898    if (!pvt->owner) {
01899       jb_frame frame;
01900       if (pvt->vars) {
01901           ast_variables_destroy(pvt->vars);
01902           pvt->vars = NULL;
01903       }
01904 
01905       while (jb_getall(pvt->jb, &frame) == JB_OK) {
01906          iax2_frame_free(frame.data);
01907       }
01908 
01909       jb_destroy(pvt->jb);
01910       ast_string_field_free_memory(pvt);
01911    }
01912 }
01913 
01914 static struct chan_iax2_pvt *new_iax(struct sockaddr_in *sin, const char *host)
01915 {
01916    struct chan_iax2_pvt *tmp;
01917    jb_conf jbconf;
01918 
01919    if (!(tmp = ao2_alloc(sizeof(*tmp), pvt_destructor))) {
01920       return NULL;
01921    }
01922 
01923    if (ast_string_field_init(tmp, 32)) {
01924       ao2_ref(tmp, -1);
01925       tmp = NULL;
01926       return NULL;
01927    }
01928       
01929    tmp->prefs = prefs;
01930    tmp->pingid = -1;
01931    tmp->lagid = -1;
01932    tmp->autoid = -1;
01933    tmp->authid = -1;
01934    tmp->initid = -1;
01935    tmp->keyrotateid = -1;
01936 
01937    ast_string_field_set(tmp,exten, "s");
01938    ast_string_field_set(tmp,host, host);
01939 
01940    tmp->jb = jb_new();
01941    tmp->jbid = -1;
01942    jbconf.max_jitterbuf = maxjitterbuffer;
01943    jbconf.resync_threshold = resyncthreshold;
01944    jbconf.max_contig_interp = maxjitterinterps;
01945    jbconf.target_extra = jittertargetextra;
01946    jb_setconf(tmp->jb,&jbconf);
01947 
01948    AST_LIST_HEAD_INIT_NOLOCK(&tmp->dpentries);
01949 
01950    tmp->hold_signaling = 1;
01951    AST_LIST_HEAD_INIT_NOLOCK(&tmp->signaling_queue);
01952 
01953    return tmp;
01954 }
01955 
01956 static struct iax_frame *iaxfrdup2(struct iax_frame *fr)
01957 {
01958    struct iax_frame *new = iax_frame_new(DIRECTION_INGRESS, fr->af.datalen, fr->cacheable);
01959    if (new) {
01960       size_t afdatalen = new->afdatalen;
01961       memcpy(new, fr, sizeof(*new));
01962       iax_frame_wrap(new, &fr->af);
01963       new->afdatalen = afdatalen;
01964       new->data = NULL;
01965       new->datalen = 0;
01966       new->direction = DIRECTION_INGRESS;
01967       new->retrans = -1;
01968    }
01969    return new;
01970 }
01971 /* keep these defined in this order.  They are used in find_callno to
01972  * determine whether or not a new call number should be allowed. */
01973 enum {
01974    /* do not allow a new call number, only search ones in use for match */
01975    NEW_PREVENT = 0,
01976    /* search for match first, then allow a new one to be allocated */
01977    NEW_ALLOW = 1,
01978    /* do not search for match, force a new call number */
01979    NEW_FORCE = 2,
01980    /* do not search for match, force a new call number.  Signifies call number
01981     * has been calltoken validated */
01982    NEW_ALLOW_CALLTOKEN_VALIDATED = 3,
01983 };
01984 
01985 static int match(struct sockaddr_in *sin, unsigned short callno, unsigned short dcallno, const struct chan_iax2_pvt *cur, int check_dcallno)
01986 {
01987    if ((cur->addr.sin_addr.s_addr == sin->sin_addr.s_addr) &&
01988       (cur->addr.sin_port == sin->sin_port)) {
01989       /* This is the main host */
01990       if ( (cur->peercallno == 0 || cur->peercallno == callno) &&
01991           (check_dcallno ? dcallno == cur->callno : 1) ) {
01992          /* That's us.  Be sure we keep track of the peer call number */
01993          return 1;
01994       }
01995    }
01996    if ((cur->transfer.sin_addr.s_addr == sin->sin_addr.s_addr) &&
01997        (cur->transfer.sin_port == sin->sin_port) && (cur->transferring)) {
01998       /* We're transferring */
01999       if ((dcallno == cur->callno) || (cur->transferring == TRANSFER_MEDIAPASS && cur->transfercallno == callno))
02000          return 1;
02001    }
02002    return 0;
02003 }
02004 
02005 #ifdef IAX_OLD_FIND
02006 
02007 static int maxtrunkcall = TRUNK_CALL_START;
02008 static int maxnontrunkcall = 1;
02009 
02010 #define update_max_trunk() __update_max_trunk()
02011 #define update_max_nontrunk() __update_max_nontrunk()
02012 
02013 static void __update_max_trunk(void)
02014 {
02015    int max = TRUNK_CALL_START;
02016    int x;
02017 
02018    /* XXX Prolly don't need locks here XXX */
02019    for (x = TRUNK_CALL_START; x < ARRAY_LEN(iaxs) - 1; x++) {
02020       if (iaxs[x]) {
02021          max = x + 1;
02022       }
02023    }
02024 
02025    maxtrunkcall = max;
02026    if (iaxdebug)
02027       ast_debug(1, "New max trunk callno is %d\n", max);
02028 }
02029 
02030 static void __update_max_nontrunk(void)
02031 {
02032    int max = 1;
02033    int x;
02034    /* XXX Prolly don't need locks here XXX */
02035    for (x=1;x<TRUNK_CALL_START - 1; x++) {
02036       if (iaxs[x])
02037          max = x + 1;
02038    }
02039    maxnontrunkcall = max;
02040    if (iaxdebug)
02041       ast_debug(1, "New max nontrunk callno is %d\n", max);
02042 }
02043 
02044 #else
02045 
02046 #define update_max_trunk() do { } while (0)
02047 #define update_max_nontrunk() do { } while (0)
02048 
02049 #endif
02050 
02051 static int make_trunk(unsigned short callno, int locked)
02052 {
02053    int x;
02054    int res= 0;
02055    struct callno_entry *callno_entry;
02056    if (iaxs[callno]->oseqno) {
02057       ast_log(LOG_WARNING, "Can't make trunk once a call has started!\n");
02058       return -1;
02059    }
02060    if (callno & TRUNK_CALL_START) {
02061       ast_log(LOG_WARNING, "Call %d is already a trunk\n", callno);
02062       return -1;
02063    }
02064 
02065    if (!(callno_entry = get_unused_callno(1, iaxs[callno]->callno_entry->validated))) {
02066       ast_log(LOG_WARNING, "Unable to trunk call: Insufficient space\n");
02067       return -1;
02068    }
02069 
02070    x = callno_entry->callno;
02071    ast_mutex_lock(&iaxsl[x]);
02072 
02073    /*!
02074     * \note We delete these before switching the slot, because if
02075     * they fire in the meantime, they will generate a warning.
02076     */
02077    ast_sched_thread_del(sched, iaxs[callno]->pingid);
02078    ast_sched_thread_del(sched, iaxs[callno]->lagid);
02079    iaxs[callno]->lagid = iaxs[callno]->pingid = -1;
02080    iaxs[x] = iaxs[callno];
02081    iaxs[x]->callno = x;
02082 
02083    /* since we copied over the pvt from a different callno, make sure the old entry is replaced
02084     * before assigning the new one */
02085    if (iaxs[x]->callno_entry) {
02086       iax2_sched_add(sched, MIN_REUSE_TIME * 1000, replace_callno, iaxs[x]->callno_entry);
02087    }
02088    iaxs[x]->callno_entry = callno_entry;
02089 
02090    iaxs[callno] = NULL;
02091    /* Update the two timers that should have been started */
02092    iaxs[x]->pingid = iax2_sched_add(sched, 
02093       ping_time * 1000, send_ping, (void *)(long)x);
02094    iaxs[x]->lagid = iax2_sched_add(sched, 
02095       lagrq_time * 1000, send_lagrq, (void *)(long)x);
02096 
02097    if (locked)
02098       ast_mutex_unlock(&iaxsl[callno]);
02099    res = x;
02100    if (!locked)
02101       ast_mutex_unlock(&iaxsl[x]);
02102 
02103    ast_debug(1, "Made call %d into trunk call %d\n", callno, x);
02104    /* We move this call from a non-trunked to a trunked call */
02105    update_max_trunk();
02106    update_max_nontrunk();
02107    return res;
02108 }
02109 
02110 static void store_by_transfercallno(struct chan_iax2_pvt *pvt)
02111 {
02112    if (!pvt->transfercallno) {
02113       ast_log(LOG_ERROR, "This should not be called without a transfer call number.\n");
02114       return;
02115    }
02116 
02117    ao2_link(iax_transfercallno_pvts, pvt);
02118 }
02119 
02120 static void remove_by_transfercallno(struct chan_iax2_pvt *pvt)
02121 {
02122    if (!pvt->transfercallno) {
02123       ast_log(LOG_ERROR, "This should not be called without a transfer call number.\n");
02124       return;
02125    }
02126 
02127    ao2_unlink(iax_transfercallno_pvts, pvt);
02128 }
02129 static void store_by_peercallno(struct chan_iax2_pvt *pvt)
02130 {
02131    if (!pvt->peercallno) {
02132       ast_log(LOG_ERROR, "This should not be called without a peer call number.\n");
02133       return;
02134    }
02135 
02136    ao2_link(iax_peercallno_pvts, pvt);
02137 }
02138 
02139 static void remove_by_peercallno(struct chan_iax2_pvt *pvt)
02140 {
02141    if (!pvt->peercallno) {
02142       ast_log(LOG_ERROR, "This should not be called without a peer call number.\n");
02143       return;
02144    }
02145 
02146    ao2_unlink(iax_peercallno_pvts, pvt);
02147 }
02148 
02149 static int addr_range_delme_cb(void *obj, void *arg, int flags)
02150 {
02151    struct addr_range *lim = obj;
02152    lim->delme = 1;
02153    return 0;
02154 }
02155 
02156 static int addr_range_hash_cb(const void *obj, const int flags)
02157 {
02158    const struct addr_range *lim = obj;
02159    struct sockaddr_in sin;
02160    ast_sockaddr_to_sin(&lim->ha.addr, &sin);
02161    return abs((int) sin.sin_addr.s_addr);
02162 }
02163 
02164 static int addr_range_cmp_cb(void *obj, void *arg, int flags)
02165 {
02166    struct addr_range *lim1 = obj, *lim2 = arg;
02167    return (!(ast_sockaddr_cmp_addr(&lim1->ha.addr, &lim2->ha.addr)) &&
02168          !(ast_sockaddr_cmp_addr(&lim1->ha.netmask, &lim2->ha.netmask))) ?
02169          CMP_MATCH | CMP_STOP : 0;
02170 }
02171 
02172 static int peercnt_hash_cb(const void *obj, const int flags)
02173 {
02174    const struct peercnt *peercnt = obj;
02175    return abs((int) peercnt->addr);
02176 }
02177 
02178 static int peercnt_cmp_cb(void *obj, void *arg, int flags)
02179 {
02180    struct peercnt *peercnt1 = obj, *peercnt2 = arg;
02181    return (peercnt1->addr == peercnt2->addr) ? CMP_MATCH | CMP_STOP : 0;
02182 }
02183 
02184 static int addr_range_match_address_cb(void *obj, void *arg, int flags)
02185 {
02186    struct addr_range *addr_range = obj;
02187    struct sockaddr_in *sin = arg;
02188    struct sockaddr_in ha_netmask_sin;
02189    struct sockaddr_in ha_addr_sin;
02190 
02191    ast_sockaddr_to_sin(&addr_range->ha.netmask, &ha_netmask_sin);
02192    ast_sockaddr_to_sin(&addr_range->ha.addr, &ha_addr_sin);
02193 
02194    if ((sin->sin_addr.s_addr & ha_netmask_sin.sin_addr.s_addr) == ha_addr_sin.sin_addr.s_addr) {
02195       return CMP_MATCH | CMP_STOP;
02196    }
02197    return 0;
02198 }
02199 
02200 /*! 
02201  * \internal
02202  *
02203  * \brief compares sin to calltoken_ignores table to determine if validation is required.
02204  */
02205 static int calltoken_required(struct sockaddr_in *sin, const char *name, int subclass)
02206 {
02207    struct addr_range *addr_range;
02208    struct iax2_peer *peer = NULL;
02209    struct iax2_user *user = NULL;
02210    /* if no username is given, check for guest accounts */
02211    const char *find = S_OR(name, "guest");
02212    int res = 1;  /* required by default */
02213    int optional = 0;
02214    enum calltoken_peer_enum calltoken_required = CALLTOKEN_DEFAULT;
02215    /* There are only two cases in which calltoken validation is not required.
02216     * Case 1. sin falls within the list of address ranges specified in the calltoken optional table and
02217     *         the peer definition has not set the requirecalltoken option.
02218     * Case 2. Username is a valid peer/user, and that peer has requirecalltoken set either auto or no.
02219     */
02220 
02221    /* ----- Case 1 ----- */
02222    if ((addr_range = ao2_callback(calltoken_ignores, 0, addr_range_match_address_cb, sin))) {
02223       ao2_ref(addr_range, -1);
02224       optional = 1;
02225    }
02226 
02227    /* ----- Case 2 ----- */
02228    if ((subclass == IAX_COMMAND_NEW) && (user = find_user(find))) {
02229       calltoken_required = user->calltoken_required;
02230    } else if ((subclass == IAX_COMMAND_NEW) && (user = realtime_user(find, sin))) {
02231       calltoken_required = user->calltoken_required;
02232    } else if ((subclass != IAX_COMMAND_NEW) && (peer = find_peer(find, 0))) {
02233       calltoken_required = peer->calltoken_required;
02234    } else if ((subclass != IAX_COMMAND_NEW) && (peer = realtime_peer(find, sin))) {
02235       calltoken_required = peer->calltoken_required;
02236    }
02237 
02238    if (peer) {
02239       peer_unref(peer);
02240    }
02241    if (user) {
02242       user_unref(user);
02243    }
02244 
02245    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);
02246    if (((calltoken_required == CALLTOKEN_NO) || (calltoken_required == CALLTOKEN_AUTO)) ||
02247       (optional && (calltoken_required == CALLTOKEN_DEFAULT))) {
02248       res = 0;
02249    }
02250 
02251    return res;
02252 }
02253 
02254 /*! 
02255  * \internal
02256  *
02257  * \brief set peercnt callno limit.
02258  *
02259  * \details 
02260  * First looks in custom definitions. If not found, global limit
02261  * is used.  Entries marked as reg already have
02262  * a custom limit set by a registration and are not modified.
02263  */
02264 static void set_peercnt_limit(struct peercnt *peercnt)
02265 {
02266    uint16_t limit = global_maxcallno;
02267    struct addr_range *addr_range;
02268    struct sockaddr_in sin = {
02269       .sin_addr.s_addr = peercnt->addr,
02270    };
02271 
02272 
02273    if (peercnt->reg && peercnt->limit) {
02274       return; /* this peercnt has a custom limit set by a registration */
02275    }
02276 
02277    if ((addr_range = ao2_callback(callno_limits, 0, addr_range_match_address_cb, &sin))) {
02278       limit = addr_range->limit;
02279       ast_debug(1, "custom addr_range %d found for %s\n", limit, ast_inet_ntoa(sin.sin_addr));
02280       ao2_ref(addr_range, -1);
02281    }
02282 
02283    peercnt->limit = limit;
02284 }
02285 
02286 /*! 
02287  * \internal
02288  * \brief sets limits for all peercnts in table. done on reload to reflect changes in conf.
02289  */
02290 static int set_peercnt_limit_all_cb(void *obj, void *arg, int flags)
02291 {
02292    struct peercnt *peercnt = obj;
02293 
02294    set_peercnt_limit(peercnt);
02295    ast_debug(1, "Reset limits for peercnts table\n");
02296 
02297    return 0;
02298 }
02299 
02300 /*! 
02301  * \internal
02302  * \brief returns match if delme is set. 
02303  */
02304 static int prune_addr_range_cb(void *obj, void *arg, int flags)
02305 {
02306    struct addr_range *addr_range = obj;
02307 
02308    return addr_range->delme ? CMP_MATCH : 0;
02309 }
02310 
02311 /*! 
02312  * \internal
02313  * \brief modifies peercnt entry in peercnts table. Used to set custom limit or mark a registered ip
02314  */
02315 static void peercnt_modify(unsigned char reg, uint16_t limit, struct ast_sockaddr *sockaddr)
02316 {
02317    /* this function turns off and on custom callno limits set by peer registration */
02318    struct peercnt *peercnt;
02319    struct peercnt tmp = {
02320       .addr = 0,
02321    };
02322    struct sockaddr_in sin;
02323 
02324    ast_sockaddr_to_sin(sockaddr, &sin);
02325 
02326    tmp.addr = sin.sin_addr.s_addr;
02327 
02328    if ((peercnt = ao2_find(peercnts, &tmp, OBJ_POINTER))) {
02329       peercnt->reg = reg;
02330       if (limit) {
02331          peercnt->limit = limit;
02332       } else {
02333          set_peercnt_limit(peercnt);
02334       }
02335       ast_debug(1, "peercnt entry %s modified limit:%d registered:%d", ast_inet_ntoa(sin.sin_addr), peercnt->limit, peercnt->reg);
02336       ao2_ref(peercnt, -1); /* decrement ref from find */
02337    }
02338 }
02339 
02340 /*! 
02341  * \internal
02342  * \brief adds an ip to the peercnts table, increments connection count if it already exists
02343  *
02344  * \details First searches for the address in the peercnts table.  If found
02345  * the current count is incremented.  If not found a new peercnt is allocated
02346  * and linked into the peercnts table with a call number count of 1.
02347  */
02348 static int peercnt_add(struct sockaddr_in *sin)
02349 {
02350    struct peercnt *peercnt;
02351    unsigned long addr = sin->sin_addr.s_addr;
02352    int res = 0;
02353    struct peercnt tmp = {
02354       .addr = addr,
02355    };
02356 
02357    /* Reasoning for peercnts container lock:  Two identical ip addresses
02358     * could be added by different threads at the "same time". Without the container
02359     * lock, both threads could alloc space for the same object and attempt
02360     * to link to table.  With the lock, one would create the object and link
02361     * to table while the other would find the already created peercnt object
02362     * rather than creating a new one. */
02363    ao2_lock(peercnts);
02364    if ((peercnt = ao2_find(peercnts, &tmp, OBJ_POINTER))) {
02365       ao2_lock(peercnt);
02366    } else if ((peercnt = ao2_alloc(sizeof(*peercnt), NULL))) {
02367       ao2_lock(peercnt);
02368       /* create and set defaults */
02369       peercnt->addr = addr;
02370       set_peercnt_limit(peercnt);
02371       /* guarantees it does not go away after unlocking table
02372        * ao2_find automatically adds this */
02373       ao2_link(peercnts, peercnt);
02374    } else {
02375       ao2_unlock(peercnts);
02376       return -1;
02377    }
02378 
02379    /* check to see if the address has hit its callno limit.  If not increment cur. */
02380    if (peercnt->limit > peercnt->cur) {
02381       peercnt->cur++;
02382       ast_debug(1, "ip callno count incremented to %d for %s\n", peercnt->cur, ast_inet_ntoa(sin->sin_addr));
02383    } else { /* max num call numbers for this peer has been reached! */
02384       ast_log(LOG_ERROR, "maxcallnumber limit of %d for %s has been reached!\n", peercnt->limit, ast_inet_ntoa(sin->sin_addr));
02385       res = -1;
02386    }
02387 
02388    /* clean up locks and ref count */
02389    ao2_unlock(peercnt);
02390    ao2_unlock(peercnts);
02391    ao2_ref(peercnt, -1); /* decrement ref from find/alloc, only the container ref remains. */
02392 
02393    return res;
02394 }
02395 
02396 /*! 
02397  * \internal
02398  * \brief decrements a peercnts table entry
02399  */
02400 static void peercnt_remove(struct peercnt *peercnt)
02401 {
02402    struct sockaddr_in sin = {
02403       .sin_addr.s_addr = peercnt->addr,
02404    };
02405 
02406    if (peercnt) {
02407       /* Container locked here since peercnt may be unlinked from list.  If left unlocked,
02408        * peercnt_add could try and grab this entry from the table and modify it at the
02409        * "same time" this thread attemps to unlink it.*/
02410       ao2_lock(peercnts);
02411       peercnt->cur--;
02412       ast_debug(1, "ip callno count decremented to %d for %s\n", peercnt->cur, ast_inet_ntoa(sin.sin_addr));
02413       /* if this was the last connection from the peer remove it from table */
02414       if (peercnt->cur == 0) {
02415          ao2_unlink(peercnts, peercnt);/* decrements ref from table, last ref is left to scheduler */
02416       }
02417       ao2_unlock(peercnts);
02418    }
02419 }
02420 
02421 /*! 
02422  * \internal
02423  * \brief called by scheduler to decrement object
02424  */
02425 static int peercnt_remove_cb(const void *obj)
02426 {
02427    struct peercnt *peercnt = (struct peercnt *) obj;
02428 
02429    peercnt_remove(peercnt);
02430    ao2_ref(peercnt, -1); /* decrement ref from scheduler */
02431 
02432    return 0;
02433 }
02434 
02435 /*! 
02436  * \internal
02437  * \brief decrements peercnts connection count, finds by addr
02438  */
02439 static int peercnt_remove_by_addr(struct sockaddr_in *sin)
02440 {
02441    struct peercnt *peercnt;
02442    struct peercnt tmp = {
02443       .addr = sin->sin_addr.s_addr,
02444    };
02445 
02446    if ((peercnt = ao2_find(peercnts, &tmp, OBJ_POINTER))) {
02447       peercnt_remove(peercnt);
02448       ao2_ref(peercnt, -1); /* decrement ref from find */
02449    }
02450    return 0;
02451 }
02452 
02453 /*! 
02454  * \internal
02455  * \brief Create callno_limit entry based on configuration
02456  */
02457 static void build_callno_limits(struct ast_variable *v)
02458 {
02459    struct addr_range *addr_range = NULL;
02460    struct addr_range tmp;
02461    struct ast_ha *ha;
02462    int limit;
02463    int error;
02464    int found;
02465 
02466    for (; v; v = v->next) {
02467       limit = -1;
02468       error = 0;
02469       found = 0;
02470       ha = ast_append_ha("permit", v->name, NULL, &error);
02471 
02472       /* check for valid config information */
02473       if (error) {
02474          ast_log(LOG_ERROR, "Call number limit for %s could not be added, Invalid address range\n.", v->name);
02475          continue;
02476       } else if ((sscanf(v->value, "%d", &limit) != 1) || (limit < 0)) {
02477          ast_log(LOG_ERROR, "Call number limit for %s could not be added. Invalid limit %s\n.", v->name, v->value);
02478          ast_free_ha(ha);
02479          continue;
02480       }
02481 
02482       ast_copy_ha(ha, &tmp.ha);
02483       /* find or create the addr_range */
02484       if ((addr_range = ao2_find(callno_limits, &tmp, OBJ_POINTER))) {
02485          ao2_lock(addr_range);
02486          found = 1;
02487       } else if (!(addr_range = ao2_alloc(sizeof(*addr_range), NULL))) {
02488          ast_free_ha(ha);
02489          return; /* out of memory */
02490       }
02491 
02492       /* copy over config data into addr_range object */
02493       ast_copy_ha(ha, &addr_range->ha); /* this is safe because only one ha is possible for each limit */
02494       ast_free_ha(ha); /* cleanup the tmp ha */
02495       addr_range->limit = limit;
02496       addr_range->delme = 0;
02497 
02498       /* cleanup */
02499       if (found) {
02500          ao2_unlock(addr_range);
02501       } else {
02502          ao2_link(callno_limits, addr_range);
02503       }
02504       ao2_ref(addr_range, -1); /* decrement ref from ao2_find and ao2_alloc, only container ref remains */
02505    }
02506 }
02507 
02508 /*! 
02509  * \internal
02510  * \brief Create calltoken_ignores entry based on configuration
02511  */
02512 static int add_calltoken_ignore(const char *addr)
02513 {
02514    struct addr_range tmp;
02515    struct addr_range *addr_range = NULL;
02516    struct ast_ha *ha = NULL;
02517    int error = 0;
02518 
02519    if (ast_strlen_zero(addr)) {
02520       ast_log(LOG_WARNING, "invalid calltokenoptional %s\n", addr);
02521       return -1;
02522    }
02523 
02524    ha = ast_append_ha("permit", addr, NULL, &error);
02525 
02526    /* check for valid config information */
02527    if (error) {
02528       ast_log(LOG_WARNING, "Error %d creating calltokenoptional entry %s\n", error, addr);
02529       return -1;
02530    }
02531 
02532    ast_copy_ha(ha, &tmp.ha);
02533    /* find or create the addr_range */
02534    if ((addr_range = ao2_find(calltoken_ignores, &tmp, OBJ_POINTER))) {
02535       ao2_lock(addr_range);
02536       addr_range->delme = 0;
02537       ao2_unlock(addr_range);
02538    } else if ((addr_range = ao2_alloc(sizeof(*addr_range), NULL))) {
02539       /* copy over config data into addr_range object */
02540       ast_copy_ha(ha, &addr_range->ha); /* this is safe because only one ha is possible */
02541       ao2_link(calltoken_ignores, addr_range);
02542    } else {
02543       ast_free_ha(ha);
02544       return -1;
02545    }
02546 
02547    ast_free_ha(ha);
02548    ao2_ref(addr_range, -1); /* decrement ref from ao2_find and ao2_alloc, only container ref remains */
02549 
02550    return 0;
02551 }
02552 
02553 static char *handle_cli_iax2_show_callno_limits(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
02554 {
02555    struct ao2_iterator i;
02556    struct peercnt *peercnt;
02557    struct sockaddr_in sin;
02558    int found = 0;
02559 
02560    switch (cmd) {
02561    case CLI_INIT:
02562       e->command = "iax2 show callnumber usage";
02563       e->usage =
02564          "Usage: iax2 show callnumber usage [IP address]\n"
02565          "       Shows current IP addresses which are consuming iax2 call numbers\n";
02566       return NULL;
02567    case CLI_GENERATE:
02568       return NULL;
02569    case CLI_HANDLER:
02570       if (a->argc < 4 || a->argc > 5)
02571          return CLI_SHOWUSAGE;
02572 
02573       if (a->argc == 4) {
02574          ast_cli(a->fd, "%-15s %-12s %-12s\n", "Address", "Callno Usage", "Callno Limit");
02575       }
02576 
02577       i = ao2_iterator_init(peercnts, 0);
02578       while ((peercnt = ao2_iterator_next(&i))) {
02579          sin.sin_addr.s_addr = peercnt->addr;
02580          if (a->argc == 5) {
02581             if (!strcasecmp(a->argv[4], ast_inet_ntoa(sin.sin_addr))) {
02582                ast_cli(a->fd, "%-15s %-12s %-12s\n", "Address", "Callno Usage", "Callno Limit");
02583                ast_cli(a->fd, "%-15s %-12d %-12d\n", ast_inet_ntoa(sin.sin_addr), peercnt->cur, peercnt->limit);
02584                ao2_ref(peercnt, -1);
02585                found = 1;
02586                break;
02587             }
02588          } else {
02589             ast_cli(a->fd, "%-15s %-12d %-12d\n", ast_inet_ntoa(sin.sin_addr), peercnt->cur, peercnt->limit);
02590          }
02591          ao2_ref(peercnt, -1);
02592       }
02593       ao2_iterator_destroy(&i);
02594 
02595       if (a->argc == 4) {
02596          ast_cli(a->fd, "\nNon-CallToken Validation Callno Limit: %d\n"
02597                           "Non-CallToken Validated Callno Used:   %d\n",
02598             global_maxcallno_nonval,
02599             total_nonval_callno_used);
02600 
02601          ast_cli(a->fd,   "Total Available Callno:                %d\n"
02602                           "Regular Callno Available:              %d\n"
02603                           "Trunk Callno Available:                %d\n",
02604             ao2_container_count(callno_pool) + ao2_container_count(callno_pool_trunk),
02605             ao2_container_count(callno_pool),
02606             ao2_container_count(callno_pool_trunk));
02607       } else if (a->argc == 5 && !found) {
02608          ast_cli(a->fd, "No call number table entries for %s found\n", a->argv[4] );
02609       }
02610 
02611 
02612       return CLI_SUCCESS;
02613    default:
02614       return NULL;
02615    }
02616 }
02617 
02618 static struct callno_entry *get_unused_callno(int trunk, int validated)
02619 {
02620    struct callno_entry *callno_entry = NULL;
02621    if ((!ao2_container_count(callno_pool) && !trunk) || (!ao2_container_count(callno_pool_trunk) && trunk)) {
02622       ast_log(LOG_WARNING, "Out of CallNumbers\n");
02623       /* Minor optimization for the extreme case. */
02624       return NULL;
02625    }
02626 
02627    /* the callno_pool container is locked here primarily to ensure thread
02628     * safety of the total_nonval_callno_used check and increment */
02629    ao2_lock(callno_pool);
02630 
02631    /* only a certain number of nonvalidated call numbers should be allocated.
02632     * If there ever is an attack, this separates the calltoken validating
02633     * users from the non calltoken validating users. */
02634    if (!validated && (total_nonval_callno_used >= global_maxcallno_nonval)) {
02635       ast_log(LOG_WARNING, "NON-CallToken callnumber limit is reached. Current:%d Max:%d\n", total_nonval_callno_used, global_maxcallno_nonval);
02636       ao2_unlock(callno_pool);
02637       return NULL;
02638    }
02639 
02640    /* unlink the object from the container, taking over ownership
02641     * of the reference the container had to the object */
02642    callno_entry = ao2_find((trunk ? callno_pool_trunk : callno_pool), NULL, OBJ_POINTER | OBJ_UNLINK | OBJ_CONTINUE);
02643 
02644    if (callno_entry) {
02645       callno_entry->validated = validated;
02646       if (!validated) {
02647          total_nonval_callno_used++;
02648       }
02649    }
02650 
02651    ao2_unlock(callno_pool);
02652    return callno_entry;
02653 }
02654 
02655 static int replace_callno(const void *obj)
02656 {
02657    struct callno_entry *callno_entry = (struct callno_entry *) obj;
02658 
02659    /* the callno_pool container is locked here primarily to ensure thread
02660     * safety of the total_nonval_callno_used check and decrement */
02661    ao2_lock(callno_pool);
02662 
02663    if (!callno_entry->validated && (total_nonval_callno_used != 0)) {
02664       total_nonval_callno_used--;
02665    } else if (!callno_entry->validated && (total_nonval_callno_used == 0)) {
02666       ast_log(LOG_ERROR, "Attempted to decrement total non calltoken validated callnumbers below zero... Callno is:%d \n", callno_entry->callno);
02667    }
02668 
02669    if (callno_entry->callno < TRUNK_CALL_START) {
02670       ao2_link(callno_pool, callno_entry);
02671    } else {
02672       ao2_link(callno_pool_trunk, callno_entry);
02673    }
02674    ao2_ref(callno_entry, -1); /* only container ref remains */
02675 
02676    ao2_unlock(callno_pool);
02677    return 0;
02678 }
02679 
02680 static int callno_hash(const void *obj, const int flags)
02681 {
02682    return abs(ast_random());
02683 }
02684 
02685 static int create_callno_pools(void)
02686 {
02687    uint16_t i;
02688 
02689    if (!(callno_pool = ao2_container_alloc(CALLNO_POOL_BUCKETS, callno_hash, NULL))) {
02690       return -1;
02691    }
02692 
02693    if (!(callno_pool_trunk = ao2_container_alloc(CALLNO_POOL_BUCKETS, callno_hash, NULL))) {
02694       return -1;
02695    }
02696 
02697    /* start at 2, 0 and 1 are reserved */
02698    for (i = 2; i <= IAX_MAX_CALLS; i++) {
02699       struct callno_entry *callno_entry;
02700 
02701       if (!(callno_entry = ao2_alloc(sizeof(*callno_entry), NULL))) {
02702          return -1;
02703       }
02704 
02705       callno_entry->callno = i;
02706 
02707       if (i < TRUNK_CALL_START) {
02708          ao2_link(callno_pool, callno_entry);
02709       } else {
02710          ao2_link(callno_pool_trunk, callno_entry);
02711       }
02712 
02713       ao2_ref(callno_entry, -1);
02714    }
02715 
02716    return 0;
02717 }
02718 
02719 /*!
02720  * \internal
02721  * \brief Schedules delayed removal of iax2_pvt call number data
02722  *
02723  * \note After MIN_REUSE_TIME has passed for a destroyed iax2_pvt, the callno is
02724  * avaliable again, and the address from the previous connection must be decremented
02725  * from the peercnts table.  This function schedules these operations to take place.
02726  */
02727 static void sched_delay_remove(struct sockaddr_in *sin, struct callno_entry *callno_entry)
02728 {
02729    int i;
02730    struct peercnt *peercnt;
02731    struct peercnt tmp = {
02732       .addr = sin->sin_addr.s_addr,
02733    };
02734 
02735    if ((peercnt = ao2_find(peercnts, &tmp, OBJ_POINTER))) {
02736       /* refcount is incremented with ao2_find.  keep that ref for the scheduler */
02737       ast_debug(1, "schedule decrement of callno used for %s in %d seconds\n", ast_inet_ntoa(sin->sin_addr), MIN_REUSE_TIME);
02738       i = iax2_sched_add(sched, MIN_REUSE_TIME * 1000, peercnt_remove_cb, peercnt);
02739       if (i == -1) {
02740          ao2_ref(peercnt, -1);
02741       }
02742    }
02743 
02744    iax2_sched_add(sched, MIN_REUSE_TIME * 1000, replace_callno, callno_entry);
02745 }
02746 
02747 /*! 
02748  * \internal
02749  * \brief returns whether or not a frame is capable of starting a new IAX2 dialog. 
02750  *
02751  * \note For this implementation, inbound pokes should _NOT_ be capable of allocating
02752  * a new callno.
02753  */
02754 static inline int attribute_pure iax2_allow_new(int frametype, int subclass, int inbound)
02755 {
02756    if (frametype != AST_FRAME_IAX) {
02757       return 0;
02758    }
02759    switch (subclass) {
02760    case IAX_COMMAND_NEW:
02761    case IAX_COMMAND_REGREQ:
02762    case IAX_COMMAND_FWDOWNL:
02763    case IAX_COMMAND_REGREL:
02764       return 1;
02765    case IAX_COMMAND_POKE:
02766       if (!inbound) {
02767          return 1;
02768       }
02769       break;
02770    }
02771    return 0;
02772 }
02773 
02774 /*
02775  * \note Calling this function while holding another pvt lock can cause a deadlock.
02776  */
02777 static int __find_callno(unsigned short callno, unsigned short dcallno, struct sockaddr_in *sin, int new, int sockfd, int return_locked, int check_dcallno)
02778 {
02779    int res = 0;
02780    int x;
02781    /* this call is calltoken validated as long as it is either NEW_FORCE
02782     * or NEW_ALLOW_CALLTOKEN_VALIDATED */
02783    int validated = (new > NEW_ALLOW) ? 1 : 0;
02784    char host[80];
02785 
02786    if (new <= NEW_ALLOW) {
02787       if (callno) {
02788          struct chan_iax2_pvt *pvt;
02789          struct chan_iax2_pvt tmp_pvt = {
02790             .callno = dcallno,
02791             .peercallno = callno,
02792             .transfercallno = callno,
02793             /* hack!! */
02794             .frames_received = check_dcallno,
02795          };
02796 
02797          memcpy(&tmp_pvt.addr, sin, sizeof(tmp_pvt.addr));
02798          /* this works for finding normal call numbers not involving transfering */ 
02799          if ((pvt = ao2_find(iax_peercallno_pvts, &tmp_pvt, OBJ_POINTER))) {
02800             if (return_locked) {
02801                ast_mutex_lock(&iaxsl[pvt->callno]);
02802             }
02803             res = pvt->callno;
02804             ao2_ref(pvt, -1);
02805             pvt = NULL;
02806             return res;
02807          }
02808          /* this searches for transfer call numbers that might not get caught otherwise */
02809          memset(&tmp_pvt.addr, 0, sizeof(tmp_pvt.addr));
02810          memcpy(&tmp_pvt.transfer, sin, sizeof(tmp_pvt.transfer));
02811          if ((pvt = ao2_find(iax_transfercallno_pvts, &tmp_pvt, OBJ_POINTER))) {
02812             if (return_locked) {
02813                ast_mutex_lock(&iaxsl[pvt->callno]);
02814             }
02815             res = pvt->callno;
02816             ao2_ref(pvt, -1);
02817             pvt = NULL;
02818             return res;
02819          }
02820       }
02821          /* This will occur on the first response to a message that we initiated,
02822        * such as a PING. */
02823       if (dcallno) {
02824          ast_mutex_lock(&iaxsl[dcallno]);
02825       }
02826       if (callno && dcallno && iaxs[dcallno] && !iaxs[dcallno]->peercallno && match(sin, callno, dcallno, iaxs[dcallno], check_dcallno)) {
02827          iaxs[dcallno]->peercallno = callno;
02828          res = dcallno;
02829          store_by_peercallno(iaxs[dcallno]);
02830          if (!res || !return_locked) {
02831             ast_mutex_unlock(&iaxsl[dcallno]);
02832          }
02833          return res;
02834       }
02835       if (dcallno) {
02836          ast_mutex_unlock(&iaxsl[dcallno]);
02837       }
02838 #ifdef IAX_OLD_FIND
02839       /* If we get here, we SHOULD NOT find a call structure for this
02840          callno; if we do, it means that there is a call structure that
02841          has a peer callno but did NOT get entered into the hash table,
02842          which is bad.
02843 
02844          If we find a call structure using this old, slow method, output a log
02845          message so we'll know about it. After a few months of leaving this in
02846          place, if we don't hear about people seeing these messages, we can
02847          remove this code for good.
02848       */
02849 
02850       for (x = 1; !res && x < maxnontrunkcall; x++) {
02851          ast_mutex_lock(&iaxsl[x]);
02852          if (iaxs[x]) {
02853             /* Look for an exact match */
02854             if (match(sin, callno, dcallno, iaxs[x], check_dcallno)) {
02855                res = x;
02856             }
02857          }
02858          if (!res || !return_locked)
02859             ast_mutex_unlock(&iaxsl[x]);
02860       }
02861       for (x = TRUNK_CALL_START; !res && x < maxtrunkcall; x++) {
02862          ast_mutex_lock(&iaxsl[x]);
02863          if (iaxs[x]) {
02864             /* Look for an exact match */
02865             if (match(sin, callno, dcallno, iaxs[x], check_dcallno)) {
02866                res = x;
02867             }
02868          }
02869          if (!res || !return_locked)
02870             ast_mutex_unlock(&iaxsl[x]);
02871       }
02872 #endif
02873    }
02874    if (!res && (new >= NEW_ALLOW)) {
02875       struct callno_entry *callno_entry;
02876       /* It may seem odd that we look through the peer list for a name for
02877        * this *incoming* call.  Well, it is weird.  However, users don't
02878        * have an IP address/port number that we can match against.  So,
02879        * this is just checking for a peer that has that IP/port and
02880        * assuming that we have a user of the same name.  This isn't always
02881        * correct, but it will be changed if needed after authentication. */
02882       if (!iax2_getpeername(*sin, host, sizeof(host)))
02883          snprintf(host, sizeof(host), "%s:%d", ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
02884 
02885       if (peercnt_add(sin)) {
02886          /* This address has hit its callnumber limit.  When the limit
02887           * is reached, the connection is not added to the peercnts table.*/
02888          return 0;
02889       }
02890 
02891       if (!(callno_entry = get_unused_callno(0, validated))) {
02892          /* since we ran out of space, remove the peercnt
02893           * entry we added earlier */
02894          peercnt_remove_by_addr(sin);
02895          ast_log(LOG_WARNING, "No more space\n");
02896          return 0;
02897       }
02898       x = callno_entry->callno;
02899       ast_mutex_lock(&iaxsl[x]);
02900 
02901       iaxs[x] = new_iax(sin, host);
02902       update_max_nontrunk();
02903       if (iaxs[x]) {
02904          if (iaxdebug)
02905             ast_debug(1, "Creating new call structure %d\n", x);
02906          iaxs[x]->callno_entry = callno_entry;
02907          iaxs[x]->sockfd = sockfd;
02908          iaxs[x]->addr.sin_port = sin->sin_port;
02909          iaxs[x]->addr.sin_family = sin->sin_family;
02910          iaxs[x]->addr.sin_addr.s_addr = sin->sin_addr.s_addr;
02911          iaxs[x]->peercallno = callno;
02912          iaxs[x]->callno = x;
02913          iaxs[x]->pingtime = DEFAULT_RETRY_TIME;
02914          iaxs[x]->expiry = min_reg_expire;
02915          iaxs[x]->pingid = iax2_sched_add(sched, ping_time * 1000, send_ping, (void *)(long)x);
02916          iaxs[x]->lagid = iax2_sched_add(sched, lagrq_time * 1000, send_lagrq, (void *)(long)x);
02917          iaxs[x]->amaflags = amaflags;
02918          ast_copy_flags64(iaxs[x], &globalflags, IAX_NOTRANSFER | IAX_TRANSFERMEDIA | IAX_USEJITTERBUF | IAX_FORCEJITTERBUF | IAX_SENDCONNECTEDLINE | IAX_RECVCONNECTEDLINE | IAX_FORCE_ENCRYPT);
02919          ast_string_field_set(iaxs[x], accountcode, accountcode);
02920          ast_string_field_set(iaxs[x], mohinterpret, mohinterpret);
02921          ast_string_field_set(iaxs[x], mohsuggest, mohsuggest);
02922          ast_string_field_set(iaxs[x], parkinglot, default_parkinglot);
02923 
02924          if (iaxs[x]->peercallno) {
02925             store_by_peercallno(iaxs[x]);
02926          }
02927       } else {
02928          ast_log(LOG_WARNING, "Out of resources\n");
02929          ast_mutex_unlock(&iaxsl[x]);
02930          replace_callno(callno_entry);
02931          return 0;
02932       }
02933       if (!return_locked)
02934          ast_mutex_unlock(&iaxsl[x]);
02935       res = x;
02936    }
02937    return res;
02938 }
02939 
02940 static int find_callno(unsigned short callno, unsigned short dcallno, struct sockaddr_in *sin, int new, int sockfd, int full_frame) { 
02941    return __find_callno(callno, dcallno, sin, new, sockfd, 0, full_frame);
02942 }
02943 
02944 static int find_callno_locked(unsigned short callno, unsigned short dcallno, struct sockaddr_in *sin, int new, int sockfd, int full_frame) {
02945 
02946    return __find_callno(callno, dcallno, sin, new, sockfd, 1, full_frame);
02947 }
02948 
02949 /*!
02950  * \brief Queue a frame to a call's owning asterisk channel
02951  *
02952  * \pre This function assumes that iaxsl[callno] is locked when called.
02953  *
02954  * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
02955  * was valid before calling it, it may no longer be valid after calling it.
02956  * This function may unlock and lock the mutex associated with this callno,
02957  * meaning that another thread may grab it and destroy the call.
02958  */
02959 static int iax2_queue_frame(int callno, struct ast_frame *f)
02960 {
02961    iax2_lock_owner(callno);
02962    if (iaxs[callno] && iaxs[callno]->owner) {
02963       ast_queue_frame(iaxs[callno]->owner, f);
02964       ast_channel_unlock(iaxs[callno]->owner);
02965    }
02966    return 0;
02967 }
02968 
02969 /*!
02970  * \brief Queue a hangup frame on the ast_channel owner
02971  *
02972  * This function queues a hangup frame on the owner of the IAX2 pvt struct that
02973  * is active for the given call number.
02974  *
02975  * \pre Assumes lock for callno is already held.
02976  *
02977  * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
02978  * was valid before calling it, it may no longer be valid after calling it.
02979  * This function may unlock and lock the mutex associated with this callno,
02980  * meaning that another thread may grab it and destroy the call.
02981  */
02982 static int iax2_queue_hangup(int callno)
02983 {
02984    iax2_lock_owner(callno);
02985    if (iaxs[callno] && iaxs[callno]->owner) {
02986       ast_queue_hangup(iaxs[callno]->owner);
02987       ast_channel_unlock(iaxs[callno]->owner);
02988    }
02989    return 0;
02990 }
02991 
02992 /*!
02993  * \brief Queue a control frame on the ast_channel owner
02994  *
02995  * This function queues a control frame on the owner of the IAX2 pvt struct that
02996  * is active for the given call number.
02997  *
02998  * \pre Assumes lock for callno is already held.
02999  *
03000  * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
03001  * was valid before calling it, it may no longer be valid after calling it.
03002  * This function may unlock and lock the mutex associated with this callno,
03003  * meaning that another thread may grab it and destroy the call.
03004  */
03005 static int iax2_queue_control_data(int callno, 
03006    enum ast_control_frame_type control, const void *data, size_t datalen)
03007 {
03008    iax2_lock_owner(callno);
03009    if (iaxs[callno] && iaxs[callno]->owner) {
03010       ast_queue_control_data(iaxs[callno]->owner, control, data, datalen);
03011       ast_channel_unlock(iaxs[callno]->owner);
03012    }
03013    return 0;
03014 }
03015 static void destroy_firmware(struct iax_firmware *cur)
03016 {
03017    /* Close firmware */
03018    if (cur->fwh) {
03019       munmap((void*)cur->fwh, ntohl(cur->fwh->datalen) + sizeof(*(cur->fwh)));
03020    }
03021    close(cur->fd);
03022    ast_free(cur);
03023 }
03024 
03025 static int try_firmware(char *s)
03026 {
03027    struct stat stbuf;
03028    struct iax_firmware *cur = NULL;
03029    int ifd, fd, res, len, chunk;
03030    struct ast_iax2_firmware_header *fwh, fwh2;
03031    struct MD5Context md5;
03032    unsigned char sum[16], buf[1024];
03033    char *s2, *last;
03034 
03035    if (!(s2 = alloca(strlen(s) + 100))) {
03036       ast_log(LOG_WARNING, "Alloca failed!\n");
03037       return -1;
03038    }
03039 
03040    last = strrchr(s, '/');
03041    if (last)
03042       last++;
03043    else
03044       last = s;
03045 
03046    snprintf(s2, strlen(s) + 100, "/var/tmp/%s-%ld", last, (unsigned long)ast_random());
03047 
03048    if ((res = stat(s, &stbuf) < 0)) {
03049       ast_log(LOG_WARNING, "Failed to stat '%s': %s\n", s, strerror(errno));
03050       return -1;
03051    }
03052 
03053    /* Make sure it's not a directory */
03054    if (S_ISDIR(stbuf.st_mode))
03055       return -1;
03056    ifd = open(s, O_RDONLY);
03057    if (ifd < 0) {
03058       ast_log(LOG_WARNING, "Cannot open '%s': %s\n", s, strerror(errno));
03059       return -1;
03060    }
03061    fd = open(s2, O_RDWR | O_CREAT | O_EXCL, AST_FILE_MODE);
03062    if (fd < 0) {
03063       ast_log(LOG_WARNING, "Cannot open '%s' for writing: %s\n", s2, strerror(errno));
03064       close(ifd);
03065       return -1;
03066    }
03067    /* Unlink our newly created file */
03068    unlink(s2);
03069    
03070    /* Now copy the firmware into it */
03071    len = stbuf.st_size;
03072    while(len) {
03073       chunk = len;
03074       if (chunk > sizeof(buf))
03075          chunk = sizeof(buf);
03076       res = read(ifd, buf, chunk);
03077       if (res != chunk) {
03078          ast_log(LOG_WARNING, "Only read %d of %d bytes of data :(: %s\n", res, chunk, strerror(errno));
03079          close(ifd);
03080          close(fd);
03081          return -1;
03082       }
03083       res = write(fd, buf, chunk);
03084       if (res != chunk) {
03085          ast_log(LOG_WARNING, "Only write %d of %d bytes of data :(: %s\n", res, chunk, strerror(errno));
03086          close(ifd);
03087          close(fd);
03088          return -1;
03089       }
03090       len -= chunk;
03091    }
03092    close(ifd);
03093    /* Return to the beginning */
03094    lseek(fd, 0, SEEK_SET);
03095    if ((res = read(fd, &fwh2, sizeof(fwh2))) != sizeof(fwh2)) {
03096       ast_log(LOG_WARNING, "Unable to read firmware header in '%s'\n", s);
03097       close(fd);
03098       return -1;
03099    }
03100    if (ntohl(fwh2.magic) != IAX_FIRMWARE_MAGIC) {
03101       ast_log(LOG_WARNING, "'%s' is not a valid firmware file\n", s);
03102       close(fd);
03103       return -1;
03104    }
03105    if (ntohl(fwh2.datalen) != (stbuf.st_size - sizeof(fwh2))) {
03106       ast_log(LOG_WARNING, "Invalid data length in firmware '%s'\n", s);
03107       close(fd);
03108       return -1;
03109    }
03110    if (fwh2.devname[sizeof(fwh2.devname) - 1] || ast_strlen_zero((char *)fwh2.devname)) {
03111       ast_log(LOG_WARNING, "No or invalid device type specified for '%s'\n", s);
03112       close(fd);
03113       return -1;
03114    }
03115    fwh = (struct ast_iax2_firmware_header*)mmap(NULL, stbuf.st_size, PROT_READ, MAP_PRIVATE, fd, 0); 
03116    if (fwh == MAP_FAILED) {
03117       ast_log(LOG_WARNING, "mmap failed: %s\n", strerror(errno));
03118       close(fd);
03119       return -1;
03120    }
03121    MD5Init(&md5);
03122    MD5Update(&md5, fwh->data, ntohl(fwh->datalen));
03123    MD5Final(sum, &md5);
03124    if (memcmp(sum, fwh->chksum, sizeof(sum))) {
03125       ast_log(LOG_WARNING, "Firmware file '%s' fails checksum\n", s);
03126       munmap((void*)fwh, stbuf.st_size);
03127       close(fd);
03128       return -1;
03129    }
03130 
03131    AST_LIST_TRAVERSE(&firmwares, cur, list) {
03132       if (!strcmp((char *)cur->fwh->devname, (char *)fwh->devname)) {
03133          /* Found a candidate */
03134          if (cur->dead || (ntohs(cur->fwh->version) < ntohs(fwh->version)))
03135             /* The version we have on loaded is older, load this one instead */
03136             break;
03137          /* This version is no newer than what we have.  Don't worry about it.
03138             We'll consider it a proper load anyhow though */
03139          munmap((void*)fwh, stbuf.st_size);
03140          close(fd);
03141          return 0;
03142       }
03143    }
03144    
03145    if (!cur && ((cur = ast_calloc(1, sizeof(*cur))))) {
03146       cur->fd = -1;
03147       AST_LIST_INSERT_TAIL(&firmwares, cur, list);
03148    }
03149    
03150    if (cur) {
03151       if (cur->fwh)
03152          munmap((void*)cur->fwh, cur->mmaplen);
03153       if (cur->fd > -1)
03154          close(cur->fd);
03155       cur->fwh = fwh;
03156       cur->fd = fd;
03157       cur->mmaplen = stbuf.st_size;
03158       cur->dead = 0;
03159    }
03160    
03161    return 0;
03162 }
03163 
03164 static int iax_check_version(char *dev)
03165 {
03166    int res = 0;
03167    struct iax_firmware *cur = NULL;
03168 
03169    if (ast_strlen_zero(dev))
03170       return 0;
03171 
03172    AST_LIST_LOCK(&firmwares);
03173    AST_LIST_TRAVERSE(&firmwares, cur, list) {
03174       if (!strcmp(dev, (char *)cur->fwh->devname)) {
03175          res = ntohs(cur->fwh->version);
03176          break;
03177       }
03178    }
03179    AST_LIST_UNLOCK(&firmwares);
03180 
03181    return res;
03182 }
03183 
03184 static int iax_firmware_append(struct iax_ie_data *ied, const unsigned char *dev, unsigned int desc)
03185 {
03186    int res = -1;
03187    unsigned int bs = desc & 0xff;
03188    unsigned int start = (desc >> 8) & 0xffffff;
03189    unsigned int bytes;
03190    struct iax_firmware *cur;
03191 
03192    if (ast_strlen_zero((char *)dev) || !bs)
03193       return -1;
03194 
03195    start *= bs;
03196    
03197    AST_LIST_LOCK(&firmwares);
03198    AST_LIST_TRAVERSE(&firmwares, cur, list) {
03199       if (strcmp((char *)dev, (char *)cur->fwh->devname))
03200          continue;
03201       iax_ie_append_int(ied, IAX_IE_FWBLOCKDESC, desc);
03202       if (start < ntohl(cur->fwh->datalen)) {
03203          bytes = ntohl(cur->fwh->datalen) - start;
03204          if (bytes > bs)
03205             bytes = bs;
03206          iax_ie_append_raw(ied, IAX_IE_FWBLOCKDATA, cur->fwh->data + start, bytes);
03207       } else {
03208          bytes = 0;
03209          iax_ie_append(ied, IAX_IE_FWBLOCKDATA);
03210       }
03211       if (bytes == bs)
03212          res = 0;
03213       else
03214          res = 1;
03215       break;
03216    }
03217    AST_LIST_UNLOCK(&firmwares);
03218 
03219    return res;
03220 }
03221 
03222 
03223 static void reload_firmware(int unload)
03224 {
03225    struct iax_firmware *cur = NULL;
03226    DIR *fwd;
03227    struct dirent *de;
03228    char dir[256], fn[256];
03229 
03230    AST_LIST_LOCK(&firmwares);
03231 
03232    /* Mark all as dead */
03233    AST_LIST_TRAVERSE(&firmwares, cur, list)
03234       cur->dead = 1;
03235 
03236    /* Now that we have marked them dead... load new ones */
03237    if (!unload) {
03238       snprintf(dir, sizeof(dir), "%s/firmware/iax", ast_config_AST_DATA_DIR);
03239       fwd = opendir(dir);
03240       if (fwd) {
03241          while((de = readdir(fwd))) {
03242             if (de->d_name[0] != '.') {
03243                snprintf(fn, sizeof(fn), "%s/%s", dir, de->d_name);
03244                if (!try_firmware(fn)) {
03245                   ast_verb(2, "Loaded firmware '%s'\n", de->d_name);
03246                }
03247             }
03248          }
03249          closedir(fwd);
03250       } else 
03251          ast_log(LOG_WARNING, "Error opening firmware directory '%s': %s\n", dir, strerror(errno));
03252    }
03253 
03254    /* Clean up leftovers */
03255    AST_LIST_TRAVERSE_SAFE_BEGIN(&firmwares, cur, list) {
03256       if (!cur->dead)
03257          continue;
03258       AST_LIST_REMOVE_CURRENT(list);
03259       destroy_firmware(cur);
03260    }
03261    AST_LIST_TRAVERSE_SAFE_END;
03262 
03263    AST_LIST_UNLOCK(&firmwares);
03264 }
03265 
03266 /*!
03267  * \note This function assumes that iaxsl[callno] is locked when called.
03268  *
03269  * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
03270  * was valid before calling it, it may no longer be valid after calling it.
03271  * This function calls iax2_queue_frame(), which may unlock and lock the mutex 
03272  * associated with this callno, meaning that another thread may grab it and destroy the call.
03273  */
03274 static int __do_deliver(void *data)
03275 {
03276    /* Just deliver the packet by using queueing.  This is called by
03277      the IAX thread with the iaxsl lock held. */
03278    struct iax_frame *fr = data;
03279    fr->retrans = -1;
03280    ast_clear_flag(&fr->af, AST_FRFLAG_HAS_TIMING_INFO);
03281    if (iaxs[fr->callno] && !ast_test_flag64(iaxs[fr->callno], IAX_ALREADYGONE))
03282       iax2_queue_frame(fr->callno, &fr->af);
03283    /* Free our iax frame */
03284    iax2_frame_free(fr);
03285    /* And don't run again */
03286    return 0;
03287 }
03288 
03289 static int handle_error(void)
03290 {
03291    /* XXX Ideally we should figure out why an error occurred and then abort those
03292       rather than continuing to try.  Unfortunately, the published interface does
03293       not seem to work XXX */
03294 #if 0
03295    struct sockaddr_in *sin;
03296    int res;
03297    struct msghdr m;
03298    struct sock_extended_err e;
03299    m.msg_name = NULL;
03300    m.msg_namelen = 0;
03301    m.msg_iov = NULL;
03302    m.msg_control = &e;
03303    m.msg_controllen = sizeof(e);
03304    m.msg_flags = 0;
03305    res = recvmsg(netsocket, &m, MSG_ERRQUEUE);
03306    if (res < 0)
03307       ast_log(LOG_WARNING, "Error detected, but unable to read error: %s\n", strerror(errno));
03308    else {
03309       if (m.msg_controllen) {
03310          sin = (struct sockaddr_in *)SO_EE_OFFENDER(&e);
03311          if (sin) 
03312             ast_log(LOG_WARNING, "Receive error from %s\n", ast_inet_ntoa(sin->sin_addr));
03313          else
03314             ast_log(LOG_WARNING, "No address detected??\n");
03315       } else {
03316          ast_log(LOG_WARNING, "Local error: %s\n", strerror(e.ee_errno));
03317       }
03318    }
03319 #endif
03320    return 0;
03321 }
03322 
03323 static int transmit_trunk(struct iax_frame *f, struct sockaddr_in *sin, int sockfd)
03324 {
03325    int res;
03326    res = sendto(sockfd, f->data, f->datalen, 0,(struct sockaddr *)sin,
03327                sizeof(*sin));
03328    if (res < 0) {
03329       ast_debug(1, "Received error: %s\n", strerror(errno));
03330       handle_error();
03331    } else
03332       res = 0;
03333    return res;
03334 }
03335 
03336 static int send_packet(struct iax_frame *f)
03337 {
03338    int res;
03339    int callno = f->callno;
03340 
03341    /* Don't send if there was an error, but return error instead */
03342    if (!callno || !iaxs[callno] || iaxs[callno]->error)
03343        return -1;
03344    
03345    /* Called with iaxsl held */
03346    if (iaxdebug)
03347       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));
03348    
03349    if (f->transfer) {
03350       if (iaxdebug)
03351          iax_showframe(f, NULL, 0, &iaxs[callno]->transfer, f->datalen - sizeof(struct ast_iax2_full_hdr));
03352       res = sendto(iaxs[callno]->sockfd, f->data, f->datalen, 0,(struct sockaddr *)&iaxs[callno]->transfer, sizeof(iaxs[callno]->transfer));
03353    } else {
03354       if (iaxdebug)
03355          iax_showframe(f, NULL, 0, &iaxs[callno]->addr, f->datalen - sizeof(struct ast_iax2_full_hdr));
03356       res = sendto(iaxs[callno]->sockfd, f->data, f->datalen, 0,(struct sockaddr *)&iaxs[callno]->addr, sizeof(iaxs[callno]->addr));
03357    }
03358    if (res < 0) {
03359       if (iaxdebug)
03360          ast_debug(1, "Received error: %s\n", strerror(errno));
03361       handle_error();
03362    } else
03363       res = 0;
03364 
03365    return res;
03366 }
03367 
03368 /*!
03369  * \note Since this function calls iax2_queue_hangup(), the pvt struct
03370  *       for the given call number may disappear during its execution.
03371  */
03372 static int iax2_predestroy(int callno)
03373 {
03374    struct ast_channel *c = NULL;
03375    struct chan_iax2_pvt *pvt = iaxs[callno];
03376 
03377    if (!pvt)
03378       return -1;
03379 
03380    if (!ast_test_flag64(pvt, IAX_ALREADYGONE)) {
03381       iax2_destroy_helper(pvt);
03382       ast_set_flag64(pvt, IAX_ALREADYGONE);
03383    }
03384 
03385    if ((c = pvt->owner)) {
03386       c->tech_pvt = NULL;
03387       iax2_queue_hangup(callno);
03388       pvt->owner = NULL;
03389       ast_module_unref(ast_module_info->self);
03390    }
03391 
03392    return 0;
03393 }
03394 
03395 static void iax2_destroy(int callno)
03396 {
03397    struct chan_iax2_pvt *pvt = NULL;
03398    struct ast_channel *owner = NULL;
03399 
03400 retry:
03401    if ((pvt = iaxs[callno])) {
03402 #if 0
03403       /* iax2_destroy_helper gets called from this function later on.  When
03404        * called twice, we get the (previously) familiar FRACK! errors in
03405        * devmode, from the scheduler.  An alternative to this approach is to
03406        * reset the scheduler entries to -1 when they're deleted in
03407        * iax2_destroy_helper().  That approach was previously decided to be
03408        * "wrong" because "the memory is going to be deallocated anyway.  Why
03409        * should we be resetting those values?" */
03410       iax2_destroy_helper(pvt);
03411 #endif
03412    }
03413 
03414    owner = pvt ? pvt->owner : NULL;
03415 
03416    if (owner) {
03417       if (ast_channel_trylock(owner)) {
03418          ast_debug(3, "Avoiding IAX destroy deadlock\n");
03419          DEADLOCK_AVOIDANCE(&iaxsl[callno]);
03420          goto retry;
03421       }
03422    }
03423 
03424    if (!owner) {
03425       iaxs[callno] = NULL;
03426    }
03427 
03428    if (pvt) {
03429       if (!owner) {
03430          pvt->owner = NULL;
03431       } else {
03432          /* If there's an owner, prod it to give up */
03433          /* It is ok to use ast_queue_hangup() here instead of iax2_queue_hangup()
03434           * because we already hold the owner channel lock. */
03435          ast_queue_hangup(owner);
03436       }
03437 
03438       if (pvt->peercallno) {
03439          remove_by_peercallno(pvt);
03440       }
03441 
03442       if (pvt->transfercallno) {
03443          remove_by_transfercallno(pvt);
03444       }
03445 
03446       if (!owner) {
03447          ao2_ref(pvt, -1);
03448          pvt = NULL;
03449       }
03450    }
03451 
03452    if (owner) {
03453       ast_channel_unlock(owner);
03454    }
03455 
03456    if (callno & TRUNK_CALL_START) {
03457       update_max_trunk();
03458    }
03459 }
03460 
03461 static int update_packet(struct iax_frame *f)
03462 {
03463    /* Called with iaxsl lock held, and iaxs[callno] non-NULL */
03464    struct ast_iax2_full_hdr *fh = f->data;
03465    struct ast_frame af;
03466 
03467    /* if frame is encrypted. decrypt before updating it. */
03468    if (f->encmethods) {
03469       decode_frame(&f->mydcx, fh, &af, &f->datalen);
03470    }
03471    /* Mark this as a retransmission */
03472    fh->dcallno = ntohs(IAX_FLAG_RETRANS | f->dcallno);
03473    /* Update iseqno */
03474    f->iseqno = iaxs[f->callno]->iseqno;
03475    fh->iseqno = f->iseqno;
03476 
03477    /* Now re-encrypt the frame */
03478    if (f->encmethods) {
03479    /* since this is a retransmit frame, create a new random padding
03480     * before re-encrypting. */
03481       build_rand_pad(f->semirand, sizeof(f->semirand));
03482       encrypt_frame(&f->ecx, fh, f->semirand, &f->datalen);
03483    }
03484    return 0;
03485 }
03486 
03487 static int attempt_transmit(const void *data);
03488 static void __attempt_transmit(const void *data)
03489 {
03490    /* Attempt to transmit the frame to the remote peer...
03491       Called without iaxsl held. */
03492    struct iax_frame *f = (struct iax_frame *)data;
03493    int freeme = 0;
03494    int callno = f->callno;
03495    /* Make sure this call is still active */
03496    if (callno) 
03497       ast_mutex_lock(&iaxsl[callno]);
03498    if (callno && iaxs[callno]) {
03499       if ((f->retries < 0) /* Already ACK'd */ ||
03500           (f->retries >= max_retries) /* Too many attempts */) {
03501             /* Record an error if we've transmitted too many times */
03502             if (f->retries >= max_retries) {
03503                if (f->transfer) {
03504                   /* Transfer timeout */
03505                   send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_TXREJ, 0, NULL, 0, -1);
03506                } else if (f->final) {
03507                   iax2_destroy(callno);
03508                } else {
03509                   if (iaxs[callno]->owner)
03510                      ast_log(LOG_WARNING, "Max retries exceeded to host %s on %s (type = %d, subclass = %u, 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.integer, f->ts, f->oseqno);
03511                   iaxs[callno]->error = ETIMEDOUT;
03512                   if (iaxs[callno]->owner) {
03513                      struct ast_frame fr = { AST_FRAME_CONTROL, { AST_CONTROL_HANGUP }, .data.uint32 = AST_CAUSE_DESTINATION_OUT_OF_ORDER };
03514                      /* Hangup the fd */
03515                      iax2_queue_frame(callno, &fr); /* XXX */
03516                      /* Remember, owner could disappear */
03517                      if (iaxs[callno] && iaxs[callno]->owner)
03518                         iaxs[callno]->owner->hangupcause = AST_CAUSE_DESTINATION_OUT_OF_ORDER;
03519                   } else {
03520                      if (iaxs[callno]->reg) {
03521                         memset(&iaxs[callno]->reg->us, 0, sizeof(iaxs[callno]->reg->us));
03522                         iaxs[callno]->reg->regstate = REG_STATE_TIMEOUT;
03523                         iaxs[callno]->reg->refresh = IAX_DEFAULT_REG_EXPIRE;
03524                      }
03525                      iax2_destroy(callno);
03526                   }
03527                }
03528 
03529             }
03530             freeme = 1;
03531       } else {
03532          /* Update it if it needs it */
03533          update_packet(f);
03534          /* Attempt transmission */
03535          send_packet(f);
03536          f->retries++;
03537          /* Try again later after 10 times as long */
03538          f->retrytime *= 10;
03539          if (f->retrytime > MAX_RETRY_TIME)
03540             f->retrytime = MAX_RETRY_TIME;
03541          /* Transfer messages max out at one second */
03542          if (f->transfer && (f->retrytime > 1000))
03543             f->retrytime = 1000;
03544          f->retrans = iax2_sched_add(sched, f->retrytime, attempt_transmit, f);
03545       }
03546    } else {
03547       /* Make sure it gets freed */
03548       f->retries = -1;
03549       freeme = 1;
03550    }
03551 
03552    if (freeme) {
03553       /* Don't attempt delivery, just remove it from the queue */
03554       AST_LIST_REMOVE(&frame_queue[callno], f, list);
03555       ast_mutex_unlock(&iaxsl[callno]);
03556       f->retrans = -1; /* this is safe because this is the scheduled function */
03557       /* Free the IAX frame */
03558       iax2_frame_free(f);
03559    } else if (callno) {
03560       ast_mutex_unlock(&iaxsl[callno]);
03561    }
03562 }
03563 
03564 static int attempt_transmit(const void *data)
03565 {
03566 #ifdef SCHED_MULTITHREADED
03567    if (schedule_action(__attempt_transmit, data))
03568 #endif      
03569       __attempt_transmit(data);
03570    return 0;
03571 }
03572 
03573 static char *handle_cli_iax2_prune_realtime(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
03574 {
03575    struct iax2_peer *peer = NULL;
03576    struct iax2_user *user = NULL;
03577    static const char * const choices[] = { "all", NULL };
03578    char *cmplt;
03579 
03580    switch (cmd) {
03581    case CLI_INIT:
03582       e->command = "iax2 prune realtime";
03583       e->usage =
03584          "Usage: iax2 prune realtime [<peername>|all]\n"
03585          "       Prunes object(s) from the cache\n";
03586       return NULL;
03587    case CLI_GENERATE:
03588       if (a->pos == 3) {
03589          cmplt = ast_cli_complete(a->word, choices, a->n);
03590          if (!cmplt)
03591             cmplt = complete_iax2_peers(a->line, a->word, a->pos, a->n - sizeof(choices), IAX_RTCACHEFRIENDS);
03592          return cmplt;
03593       }
03594       return NULL;
03595    }
03596    if (a->argc != 4)
03597       return CLI_SHOWUSAGE;
03598    if (!strcmp(a->argv[3], "all")) {
03599       prune_users();
03600       prune_peers();
03601       ast_cli(a->fd, "Cache flushed successfully.\n");
03602       return CLI_SUCCESS;
03603    }
03604    peer = find_peer(a->argv[3], 0);
03605    user = find_user(a->argv[3]);
03606    if (peer || user) {
03607       if (peer) {
03608          if (ast_test_flag64(peer, IAX_RTCACHEFRIENDS)) {
03609             ast_set_flag64(peer, IAX_RTAUTOCLEAR);
03610             expire_registry(peer_ref(peer));
03611             ast_cli(a->fd, "Peer %s was removed from the cache.\n", a->argv[3]);
03612          } else {
03613             ast_cli(a->fd, "Peer %s is not eligible for this operation.\n", a->argv[3]);
03614          }
03615          peer_unref(peer);
03616       }
03617       if (user) {
03618          if (ast_test_flag64(user, IAX_RTCACHEFRIENDS)) {
03619             ast_set_flag64(user, IAX_RTAUTOCLEAR);
03620             ast_cli(a->fd, "User %s was removed from the cache.\n", a->argv[3]);
03621          } else {
03622             ast_cli(a->fd, "User %s is not eligible for this operation.\n", a->argv[3]);
03623          }
03624          ao2_unlink(users,user);
03625          user_unref(user);
03626       }
03627    } else {
03628       ast_cli(a->fd, "%s was not found in the cache.\n", a->argv[3]);
03629    }
03630 
03631    return CLI_SUCCESS;
03632 }
03633 
03634 static char *handle_cli_iax2_test_losspct(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
03635 {
03636    switch (cmd) {
03637    case CLI_INIT:
03638       e->command = "iax2 test losspct";
03639       e->usage =
03640          "Usage: iax2 test losspct <percentage>\n"
03641          "       For testing, throws away <percentage> percent of incoming packets\n";
03642       return NULL;
03643    case CLI_GENERATE:
03644       return NULL;
03645    }
03646    if (a->argc != 4)
03647       return CLI_SHOWUSAGE;
03648 
03649    test_losspct = atoi(a->argv[3]);
03650 
03651    return CLI_SUCCESS;
03652 }
03653 
03654 #ifdef IAXTESTS
03655 static char *handle_cli_iax2_test_late(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
03656 {
03657    switch (cmd) {
03658    case CLI_INIT:
03659       e->command = "iax2 test late";
03660       e->usage =
03661          "Usage: iax2 test late <ms>\n"
03662          "       For testing, count the next frame as <ms> ms late\n";
03663       return NULL;
03664    case CLI_GENERATE:
03665       return NULL;
03666    }
03667 
03668    if (a->argc != 4)
03669       return CLI_SHOWUSAGE;
03670 
03671    test_late = atoi(a->argv[3]);
03672 
03673    return CLI_SUCCESS;
03674 }
03675 
03676 static char *handle_cli_iax2_test_resync(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
03677 {
03678    switch (cmd) {
03679    case CLI_INIT:
03680       e->command = "iax2 test resync";
03681       e->usage =
03682          "Usage: iax2 test resync <ms>\n"
03683          "       For testing, adjust all future frames by <ms> ms\n";
03684       return NULL;
03685    case CLI_GENERATE:
03686       return NULL;
03687    }
03688 
03689    if (a->argc != 4)
03690       return CLI_SHOWUSAGE;
03691 
03692    test_resync = atoi(a->argv[3]);
03693 
03694    return CLI_SUCCESS;
03695 }
03696 
03697 static char *handle_cli_iax2_test_jitter(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
03698 {
03699    switch (cmd) {
03700    case CLI_INIT:
03701       e->command = "iax2 test jitter";
03702       e->usage =
03703          "Usage: iax2 test jitter <ms> <pct>\n"
03704          "       For testing, simulate maximum jitter of +/- <ms> on <pct>\n"
03705          "       percentage of packets. If <pct> is not specified, adds\n"
03706          "       jitter to all packets.\n";
03707       return NULL;
03708    case CLI_GENERATE:
03709       return NULL;
03710    }
03711 
03712    if (a->argc < 4 || a->argc > 5)
03713       return CLI_SHOWUSAGE;
03714 
03715    test_jit = atoi(a->argv[3]);
03716    if (a->argc == 5)
03717       test_jitpct = atoi(a->argv[4]);
03718 
03719    return CLI_SUCCESS;
03720 }
03721 #endif /* IAXTESTS */
03722 
03723 /*! \brief  peer_status: Report Peer status in character string */
03724 /*    returns 1 if peer is online, -1 if unmonitored */
03725 static int peer_status(struct iax2_peer *peer, char *status, int statuslen)
03726 {
03727    int res = 0;
03728    if (peer->maxms) {
03729       if (peer->lastms < 0) {
03730          ast_copy_string(status, "UNREACHABLE", statuslen);
03731       } else if (peer->lastms > peer->maxms) {
03732          snprintf(status, statuslen, "LAGGED (%d ms)", peer->lastms);
03733          res = 1;
03734       } else if (peer->lastms) {
03735          snprintf(status, statuslen, "OK (%d ms)", peer->lastms);
03736          res = 1;
03737       } else {
03738          ast_copy_string(status, "UNKNOWN", statuslen);
03739       }
03740    } else { 
03741       ast_copy_string(status, "Unmonitored", statuslen);
03742       res = -1;
03743    }
03744    return res;
03745 }
03746 
03747 /*! \brief Show one peer in detail */
03748 static char *handle_cli_iax2_show_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
03749 {
03750    char status[30];
03751    char cbuf[256];
03752    struct iax2_peer *peer;
03753    char codec_buf[512];
03754    struct ast_str *encmethods = ast_str_alloca(256);
03755    int x = 0, codec = 0, load_realtime = 0;
03756 
03757    switch (cmd) {
03758    case CLI_INIT:
03759       e->command = "iax2 show peer";
03760       e->usage =
03761          "Usage: iax2 show peer <name>\n"
03762          "       Display details on specific IAX peer\n";
03763       return NULL;
03764    case CLI_GENERATE:
03765       if (a->pos == 3)
03766          return complete_iax2_peers(a->line, a->word, a->pos, a->n, 0);
03767       return NULL;
03768    }
03769 
03770    if (a->argc < 4)
03771       return CLI_SHOWUSAGE;
03772 
03773    load_realtime = (a->argc == 5 && !strcmp(a->argv[4], "load")) ? 1 : 0;
03774 
03775    peer = find_peer(a->argv[3], load_realtime);
03776    if (peer) {
03777       struct sockaddr_in peer_addr;
03778 
03779       ast_sockaddr_to_sin(&peer->addr, &peer_addr);
03780 
03781       encmethods_to_str(peer->encmethods, encmethods);
03782       ast_cli(a->fd, "\n\n");
03783       ast_cli(a->fd, "  * Name       : %s\n", peer->name);
03784       ast_cli(a->fd, "  Secret       : %s\n", ast_strlen_zero(peer->secret) ? "<Not set>" : "<Set>");
03785       ast_cli(a->fd, "  Context      : %s\n", peer->context);
03786       ast_cli(a->fd, "  Parking lot  : %s\n", peer->parkinglot);
03787       ast_cli(a->fd, "  Mailbox      : %s\n", peer->mailbox);
03788       ast_cli(a->fd, "  Dynamic      : %s\n", ast_test_flag64(peer, IAX_DYNAMIC) ? "Yes" : "No");
03789       ast_cli(a->fd, "  Callnum limit: %d\n", peer->maxcallno);
03790       ast_cli(a->fd, "  Calltoken req: %s\n", (peer->calltoken_required == CALLTOKEN_YES) ? "Yes" : ((peer->calltoken_required == CALLTOKEN_AUTO) ? "Auto" : "No"));
03791       ast_cli(a->fd, "  Trunk        : %s\n", ast_test_flag64(peer, IAX_TRUNK) ? "Yes" : "No");
03792       ast_cli(a->fd, "  Encryption   : %s\n", peer->encmethods ? ast_str_buffer(encmethods) : "No");
03793       ast_cli(a->fd, "  Callerid     : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, "<unspecified>"));
03794       ast_cli(a->fd, "  Expire       : %d\n", peer->expire);
03795       ast_cli(a->fd, "  ACL          : %s\n", (peer->ha ? "Yes" : "No"));
03796       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));
03797       ast_cli(a->fd, "  Defaddr->IP  : %s Port %d\n", ast_inet_ntoa(peer->defaddr.sin_addr), ntohs(peer->defaddr.sin_port));
03798       ast_cli(a->fd, "  Username     : %s\n", peer->username);
03799       ast_cli(a->fd, "  Codecs       : ");
03800       ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, peer->capability);
03801       ast_cli(a->fd, "%s\n", codec_buf);
03802 
03803       ast_cli(a->fd, "  Codec Order  : (");
03804       for(x = 0; x < 32 ; x++) {
03805          codec = ast_codec_pref_index(&peer->prefs,x);
03806          if(!codec)
03807             break;
03808          ast_cli(a->fd, "%s", ast_getformatname(codec));
03809          if(x < 31 && ast_codec_pref_index(&peer->prefs,x+1))
03810             ast_cli(a->fd, "|");
03811       }
03812 
03813       if (!x)
03814          ast_cli(a->fd, "none");
03815       ast_cli(a->fd, ")\n");
03816 
03817       ast_cli(a->fd, "  Status       : ");
03818       peer_status(peer, status, sizeof(status));   
03819       ast_cli(a->fd, "%s\n",status);
03820       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");
03821       ast_cli(a->fd, "\n");
03822       peer_unref(peer);
03823    } else {
03824       ast_cli(a->fd, "Peer %s not found.\n", a->argv[3]);
03825       ast_cli(a->fd, "\n");
03826    }
03827 
03828    return CLI_SUCCESS;
03829 }
03830 
03831 static char *complete_iax2_peers(const char *line, const char *word, int pos, int state, uint64_t flags)
03832 {
03833    int which = 0;
03834    struct iax2_peer *peer;
03835    char *res = NULL;
03836    int wordlen = strlen(word);
03837    struct ao2_iterator i;
03838 
03839    i = ao2_iterator_init(peers, 0);
03840    while ((peer = ao2_iterator_next(&i))) {
03841       if (!strncasecmp(peer->name, word, wordlen) && ++which > state
03842          && (!flags || ast_test_flag64(peer, flags))) {
03843          res = ast_strdup(peer->name);
03844          peer_unref(peer);
03845          break;
03846       }
03847       peer_unref(peer);
03848    }
03849    ao2_iterator_destroy(&i);
03850 
03851    return res;
03852 }
03853 
03854 static char *handle_cli_iax2_show_stats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
03855 {
03856    struct iax_frame *cur;
03857    int cnt = 0, dead = 0, final = 0, i = 0;
03858 
03859    switch (cmd) {
03860    case CLI_INIT:
03861       e->command = "iax2 show stats";
03862       e->usage =
03863          "Usage: iax2 show stats\n"
03864          "       Display statistics on IAX channel driver.\n";
03865       return NULL;
03866    case CLI_GENERATE:
03867       return NULL;
03868    }
03869 
03870    if (a->argc != 3)
03871       return CLI_SHOWUSAGE;
03872 
03873    for (i = 0; i < ARRAY_LEN(frame_queue); i++) {
03874       ast_mutex_lock(&iaxsl[i]);
03875       AST_LIST_TRAVERSE(&frame_queue[i], cur, list) {
03876          if (cur->retries < 0)
03877             dead++;
03878          if (cur->final)
03879             final++;
03880          cnt++;
03881       }
03882       ast_mutex_unlock(&iaxsl[i]);
03883    }
03884 
03885    ast_cli(a->fd, "    IAX Statistics\n");
03886    ast_cli(a->fd, "---------------------\n");
03887    ast_cli(a->fd, "Outstanding frames: %d (%d ingress, %d egress)\n", iax_get_frames(), iax_get_iframes(), iax_get_oframes());
03888    ast_cli(a->fd, "%d timed and %d untimed transmits; MTU %d/%d/%d\n", trunk_timed, trunk_untimed,
03889       trunk_maxmtu, trunk_nmaxmtu, global_max_trunk_mtu);
03890    ast_cli(a->fd, "Packets in transmit queue: %d dead, %d final, %d total\n\n", dead, final, cnt);
03891 
03892    trunk_timed = trunk_untimed = 0;
03893    if (trunk_maxmtu > trunk_nmaxmtu)
03894       trunk_nmaxmtu = trunk_maxmtu;
03895 
03896    return CLI_SUCCESS;
03897 }
03898 
03899 /*! \brief Set trunk MTU from CLI */
03900 static char *handle_cli_iax2_set_mtu(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
03901 {
03902    int mtuv;
03903 
03904    switch (cmd) {
03905    case CLI_INIT:
03906       e->command = "iax2 set mtu";
03907       e->usage =
03908          "Usage: iax2 set mtu <value>\n"
03909          "       Set the system-wide IAX IP mtu to <value> bytes net or\n"
03910          "       zero to disable. Disabling means that the operating system\n"
03911          "       must handle fragmentation of UDP packets when the IAX2 trunk\n"
03912          "       packet exceeds the UDP payload size. This is substantially\n"
03913          "       below the IP mtu. Try 1240 on ethernets. Must be 172 or\n"
03914          "       greater for G.711 samples.\n";
03915       return NULL;
03916    case CLI_GENERATE:
03917       return NULL;
03918    }
03919 
03920    if (a->argc != 4)
03921       return CLI_SHOWUSAGE; 
03922    if (strncasecmp(a->argv[3], "default", strlen(a->argv[3])) == 0)
03923       mtuv = MAX_TRUNK_MTU;
03924    else
03925       mtuv = atoi(a->argv[3]);
03926 
03927    if (mtuv == 0) {
03928       ast_cli(a->fd, "Trunk MTU control disabled (mtu was %d)\n", global_max_trunk_mtu); 
03929       global_max_trunk_mtu = 0; 
03930       return CLI_SUCCESS; 
03931    }
03932    if (mtuv < 172 || mtuv > 4000) {
03933       ast_cli(a->fd, "Trunk MTU must be between 172 and 4000\n"); 
03934       return CLI_SHOWUSAGE; 
03935    }
03936    ast_cli(a->fd, "Trunk MTU changed from %d to %d\n", global_max_trunk_mtu, mtuv); 
03937    global_max_trunk_mtu = mtuv; 
03938    return CLI_SUCCESS;
03939 }
03940 
03941 static char *handle_cli_iax2_show_cache(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
03942 {
03943    struct iax2_dpcache *dp = NULL;
03944    char tmp[1024], *pc = NULL;
03945    int s, x, y;
03946    struct timeval now = ast_tvnow();
03947 
03948    switch (cmd) {
03949    case CLI_INIT:
03950       e->command = "iax2 show cache";
03951       e->usage =
03952          "Usage: iax2 show cache\n"
03953          "       Display currently cached IAX Dialplan results.\n";
03954       return NULL;
03955    case CLI_GENERATE:
03956       return NULL;
03957    }
03958 
03959    AST_LIST_LOCK(&dpcache);
03960 
03961    ast_cli(a->fd, "%-20.20s %-12.12s %-9.9s %-8.8s %s\n", "Peer/Context", "Exten", "Exp.", "Wait.", "Flags");
03962 
03963    AST_LIST_TRAVERSE(&dpcache, dp, cache_list) {
03964       s = dp->expiry.tv_sec - now.tv_sec;
03965       tmp[0] = '\0';
03966       if (dp->flags & CACHE_FLAG_EXISTS)
03967          strncat(tmp, "EXISTS|", sizeof(tmp) - strlen(tmp) - 1);
03968       if (dp->flags & CACHE_FLAG_NONEXISTENT)
03969          strncat(tmp, "NONEXISTENT|", sizeof(tmp) - strlen(tmp) - 1);
03970       if (dp->flags & CACHE_FLAG_CANEXIST)
03971          strncat(tmp, "CANEXIST|", sizeof(tmp) - strlen(tmp) - 1);
03972       if (dp->flags & CACHE_FLAG_PENDING)
03973          strncat(tmp, "PENDING|", sizeof(tmp) - strlen(tmp) - 1);
03974       if (dp->flags & CACHE_FLAG_TIMEOUT)
03975          strncat(tmp, "TIMEOUT|", sizeof(tmp) - strlen(tmp) - 1);
03976       if (dp->flags & CACHE_FLAG_TRANSMITTED)
03977          strncat(tmp, "TRANSMITTED|", sizeof(tmp) - strlen(tmp) - 1);
03978       if (dp->flags & CACHE_FLAG_MATCHMORE)
03979          strncat(tmp, "MATCHMORE|", sizeof(tmp) - strlen(tmp) - 1);
03980       if (dp->flags & CACHE_FLAG_UNKNOWN)
03981          strncat(tmp, "UNKNOWN|", sizeof(tmp) - strlen(tmp) - 1);
03982       /* Trim trailing pipe */
03983       if (!ast_strlen_zero(tmp)) {
03984          tmp[strlen(tmp) - 1] = '\0';
03985       } else {
03986          ast_copy_string(tmp, "(none)", sizeof(tmp));
03987       }
03988       y = 0;
03989       pc = strchr(dp->peercontext, '@');
03990       if (!pc) {
03991          pc = dp->peercontext;
03992       } else {
03993          pc++;
03994       }
03995       for (x = 0; x < ARRAY_LEN(dp->waiters); x++) {
03996          if (dp->waiters[x] > -1)
03997             y++;
03998       }
03999       if (s > 0) {
04000          ast_cli(a->fd, "%-20.20s %-12.12s %-9d %-8d %s\n", pc, dp->exten, s, y, tmp);
04001       } else {
04002          ast_cli(a->fd, "%-20.20s %-12.12s %-9.9s %-8d %s\n", pc, dp->exten, "(expired)", y, tmp);
04003       }
04004    }
04005 
04006    AST_LIST_UNLOCK(&dpcache);
04007 
04008    return CLI_SUCCESS;
04009 }
04010 
04011 static unsigned int calc_rxstamp(struct chan_iax2_pvt *p, unsigned int offset);
04012 
04013 static void unwrap_timestamp(struct iax_frame *fr)
04014 {
04015    /* Video mini frames only encode the lower 15 bits of the session
04016     * timestamp, but other frame types (e.g. audio) encode 16 bits. */
04017    const int ts_shift = (fr->af.frametype == AST_FRAME_VIDEO) ? 15 : 16;
04018    const int lower_mask = (1 << ts_shift) - 1;
04019    const int upper_mask = ~lower_mask;
04020    const int last_upper = iaxs[fr->callno]->last & upper_mask;
04021 
04022    if ( (fr->ts & upper_mask) == last_upper ) {
04023       const int x = fr->ts - iaxs[fr->callno]->last;
04024       const int threshold = (ts_shift == 15) ? 25000 : 50000;
04025 
04026       if (x < -threshold) {
04027          /* Sudden big jump backwards in timestamp:
04028             What likely happened here is that miniframe timestamp has circled but we haven't
04029             gotten the update from the main packet.  We'll just pretend that we did, and
04030             update the timestamp appropriately. */
04031          fr->ts = (last_upper + (1 << ts_shift)) | (fr->ts & lower_mask);
04032          if (iaxdebug)
04033             ast_debug(1, "schedule_delivery: pushed forward timestamp\n");
04034       } else if (x > threshold) {
04035          /* Sudden apparent big jump forwards in timestamp:
04036             What's likely happened is this is an old miniframe belonging to the previous
04037             top 15 or 16-bit timestamp that has turned up out of order.
04038             Adjust the timestamp appropriately. */
04039          fr->ts = (last_upper - (1 << ts_shift)) | (fr->ts & lower_mask);
04040          if (iaxdebug)
04041             ast_debug(1, "schedule_delivery: pushed back timestamp\n");
04042       }
04043    }
04044 }
04045 
04046 static int get_from_jb(const void *p);
04047 
04048 static void update_jbsched(struct chan_iax2_pvt *pvt)
04049 {
04050    int when;
04051    
04052    when = ast_tvdiff_ms(ast_tvnow(), pvt->rxcore);
04053    
04054    when = jb_next(pvt->jb) - when;
04055 
04056    if (when <= 0) {
04057       /* XXX should really just empty until when > 0.. */
04058       when = 1;
04059    }
04060    
04061    pvt->jbid = iax2_sched_replace(pvt->jbid, sched, when, get_from_jb, 
04062       CALLNO_TO_PTR(pvt->callno));
04063 }
04064 
04065 static void __get_from_jb(const void *p) 
04066 {
04067    int callno = PTR_TO_CALLNO(p);
04068    struct chan_iax2_pvt *pvt = NULL;
04069    struct iax_frame *fr;
04070    jb_frame frame;
04071    int ret;
04072    long ms;
04073    long next;
04074    struct timeval now = ast_tvnow();
04075    
04076    /* Make sure we have a valid private structure before going on */
04077    ast_mutex_lock(&iaxsl[callno]);
04078    pvt = iaxs[callno];
04079    if (!pvt) {
04080       /* No go! */
04081       ast_mutex_unlock(&iaxsl[callno]);
04082       return;
04083    }
04084 
04085    pvt->jbid = -1;
04086    
04087    /* round up a millisecond since ast_sched_runq does; */
04088    /* prevents us from spinning while waiting for our now */
04089    /* to catch up with runq's now */
04090    now.tv_usec += 1000;
04091    
04092    ms = ast_tvdiff_ms(now, pvt->rxcore);
04093    
04094    if(ms >= (next = jb_next(pvt->jb))) {
04095       ret = jb_get(pvt->jb,&frame,ms,ast_codec_interp_len(pvt->voiceformat));
04096       switch(ret) {
04097       case JB_OK:
04098          fr = frame.data;
04099          __do_deliver(fr);
04100          /* __do_deliver() can cause the call to disappear */
04101          pvt = iaxs[callno];
04102          break;
04103       case JB_INTERP:
04104       {
04105          struct ast_frame af = { 0, };
04106          
04107          /* create an interpolation frame */
04108          af.frametype = AST_FRAME_VOICE;
04109          af.subclass.codec = pvt->voiceformat;
04110          af.samples  = frame.ms * (ast_format_rate(pvt->voiceformat) / 1000);
04111          af.src  = "IAX2 JB interpolation";
04112          af.delivery = ast_tvadd(pvt->rxcore, ast_samp2tv(next, 1000));
04113          af.offset = AST_FRIENDLY_OFFSET;
04114          
04115          /* queue the frame:  For consistency, we would call __do_deliver here, but __do_deliver wants an iax_frame,
04116           * which we'd need to malloc, and then it would free it.  That seems like a drag */
04117          if (!ast_test_flag64(iaxs[callno], IAX_ALREADYGONE)) {
04118             iax2_queue_frame(callno, &af);
04119             /* iax2_queue_frame() could cause the call to disappear */
04120             pvt = iaxs[callno];
04121          }
04122       }
04123          break;
04124       case JB_DROP:
04125          iax2_frame_free(frame.data);
04126          break;
04127       case JB_NOFRAME:
04128       case JB_EMPTY:
04129          /* do nothing */
04130          break;
04131       default:
04132          /* shouldn't happen */
04133          break;
04134       }
04135    }
04136    if (pvt)
04137       update_jbsched(pvt);
04138    ast_mutex_unlock(&iaxsl[callno]);
04139 }
04140 
04141 static int get_from_jb(const void *data)
04142 {
04143 #ifdef SCHED_MULTITHREADED
04144    if (schedule_action(__get_from_jb, data))
04145 #endif      
04146       __get_from_jb(data);
04147    return 0;
04148 }
04149 
04150 /*!
04151  * \note This function assumes fr->callno is locked
04152  *
04153  * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
04154  * was valid before calling it, it may no longer be valid after calling it.
04155  */
04156 static int schedule_delivery(struct iax_frame *fr, int updatehistory, int fromtrunk, unsigned int *tsout)
04157 {
04158    int type, len;
04159    int ret;
04160    int needfree = 0;
04161    struct ast_channel *owner = NULL;
04162    struct ast_channel *bridge = NULL;
04163    
04164    /* Attempt to recover wrapped timestamps */
04165    unwrap_timestamp(fr);
04166 
04167    /* delivery time is sender's sent timestamp converted back into absolute time according to our clock */
04168    if ( !fromtrunk && !ast_tvzero(iaxs[fr->callno]->rxcore))
04169       fr->af.delivery = ast_tvadd(iaxs[fr->callno]->rxcore, ast_samp2tv(fr->ts, 1000));
04170    else {
04171 #if 0
04172       ast_debug(1, "schedule_delivery: set delivery to 0 as we don't have an rxcore yet, or frame is from trunk.\n");
04173 #endif
04174       fr->af.delivery = ast_tv(0,0);
04175    }
04176 
04177    type = JB_TYPE_CONTROL;
04178    len = 0;
04179 
04180    if(fr->af.frametype == AST_FRAME_VOICE) {
04181       type = JB_TYPE_VOICE;
04182       len = ast_codec_get_samples(&fr->af) / (ast_format_rate(fr->af.subclass.codec) / 1000);
04183    } else if(fr->af.frametype == AST_FRAME_CNG) {
04184       type = JB_TYPE_SILENCE;
04185    }
04186 
04187    if ( (!ast_test_flag64(iaxs[fr->callno], IAX_USEJITTERBUF)) ) {
04188       if (tsout)
04189          *tsout = fr->ts;
04190       __do_deliver(fr);
04191       return -1;
04192    }
04193 
04194    iax2_lock_owner(fr->callno);
04195    if (!iaxs[fr->callno]) {
04196       /* The call dissappeared so discard this frame that we could not send. */
04197       iax2_frame_free(fr);
04198       return -1;
04199    }
04200    if ((owner = iaxs[fr->callno]->owner))
04201       bridge = ast_bridged_channel(owner);
04202 
04203    /* if the user hasn't requested we force the use of the jitterbuffer, and we're bridged to
04204     * a channel that can accept jitter, then flush and suspend the jb, and send this frame straight through */
04205    if ( (!ast_test_flag64(iaxs[fr->callno], IAX_FORCEJITTERBUF)) && owner && bridge && (bridge->tech->properties & AST_CHAN_TP_WANTSJITTER) ) {
04206       jb_frame frame;
04207 
04208       ast_channel_unlock(owner);
04209 
04210       /* deliver any frames in the jb */
04211       while (jb_getall(iaxs[fr->callno]->jb, &frame) == JB_OK) {
04212          __do_deliver(frame.data);
04213          /* __do_deliver() can make the call disappear */
04214          if (!iaxs[fr->callno])
04215             return -1;
04216       }
04217 
04218       jb_reset(iaxs[fr->callno]->jb);
04219 
04220       ast_sched_thread_del(sched, iaxs[fr->callno]->jbid);
04221 
04222       /* deliver this frame now */
04223       if (tsout)
04224          *tsout = fr->ts;
04225       __do_deliver(fr);
04226       return -1;
04227    }
04228    if (owner) {
04229       ast_channel_unlock(owner);
04230    }
04231 
04232    /* insert into jitterbuffer */
04233    /* TODO: Perhaps we could act immediately if it's not droppable and late */
04234    ret = jb_put(iaxs[fr->callno]->jb, fr, type, len, fr->ts,
04235          calc_rxstamp(iaxs[fr->callno],fr->ts));
04236    if (ret == JB_DROP) {
04237       needfree++;
04238    } else if (ret == JB_SCHED) {
04239       update_jbsched(iaxs[fr->callno]);
04240    }
04241    if (tsout)
04242       *tsout = fr->ts;
04243    if (needfree) {
04244       /* Free our iax frame */
04245       iax2_frame_free(fr);
04246       return -1;
04247    }
04248    return 0;
04249 }
04250 
04251 static int transmit_frame(void *data)
04252 {
04253    struct iax_frame *fr = data;
04254 
04255    ast_mutex_lock(&iaxsl[fr->callno]);
04256 
04257    fr->sentyet = 1;
04258 
04259    if (iaxs[fr->callno]) {
04260       send_packet(fr);
04261    }
04262 
04263    if (fr->retries < 0) {
04264       ast_mutex_unlock(&iaxsl[fr->callno]);
04265       /* No retransmit requested */
04266       iax_frame_free(fr);
04267    } else {
04268       /* We need reliable delivery.  Schedule a retransmission */
04269       AST_LIST_INSERT_TAIL(&frame_queue[fr->callno], fr, list);
04270       fr->retries++;
04271       fr->retrans = iax2_sched_add(sched, fr->retrytime, attempt_transmit, fr);
04272       ast_mutex_unlock(&iaxsl[fr->callno]);
04273    }
04274 
04275    return 0;
04276 }
04277 
04278 static int iax2_transmit(struct iax_frame *fr)
04279 {
04280    fr->sentyet = 0;
04281 
04282    return ast_taskprocessor_push(transmit_processor, transmit_frame, fr);
04283 }
04284 
04285 static int iax2_digit_begin(struct ast_channel *c, char digit)
04286 {
04287    return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_DTMF_BEGIN, digit, 0, NULL, 0, -1);
04288 }
04289 
04290 static int iax2_digit_end(struct ast_channel *c, char digit, unsigned int duration)
04291 {
04292    return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_DTMF_END, digit, 0, NULL, 0, -1);
04293 }
04294 
04295 static int iax2_sendtext(struct ast_channel *c, const char *text)
04296 {
04297    
04298    return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_TEXT,
04299       0, 0, (unsigned char *)text, strlen(text) + 1, -1);
04300 }
04301 
04302 static int iax2_sendimage(struct ast_channel *c, struct ast_frame *img)
04303 {
04304    return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_IMAGE, img->subclass.integer, 0, img->data.ptr, img->datalen, -1);
04305 }
04306 
04307 static int iax2_sendhtml(struct ast_channel *c, int subclass, const char *data, int datalen)
04308 {
04309    return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_HTML, subclass, 0, (unsigned char *)data, datalen, -1);
04310 }
04311 
04312 static int iax2_fixup(struct ast_channel *oldchannel, struct ast_channel *newchan)
04313 {
04314    unsigned short callno = PTR_TO_CALLNO(newchan->tech_pvt);
04315    ast_mutex_lock(&iaxsl[callno]);
04316    if (iaxs[callno])
04317       iaxs[callno]->owner = newchan;
04318    else
04319       ast_log(LOG_WARNING, "Uh, this isn't a good sign...\n");
04320    ast_mutex_unlock(&iaxsl[callno]);
04321    return 0;
04322 }
04323 
04324 /*!
04325  * \note This function calls reg_source_db -> iax2_poke_peer -> find_callno,
04326  *       so do not call this with a pvt lock held.
04327  */
04328 static struct iax2_peer *realtime_peer(const char *peername, struct sockaddr_in *sin)
04329 {
04330    struct ast_variable *var = NULL;
04331    struct ast_variable *tmp;
04332    struct iax2_peer *peer=NULL;
04333    time_t regseconds = 0, nowtime;
04334    int dynamic=0;
04335 
04336    if (peername) {
04337       var = ast_load_realtime("iaxpeers", "name", peername, "host", "dynamic", SENTINEL);
04338       if (!var && sin)
04339          var = ast_load_realtime("iaxpeers", "name", peername, "host", ast_inet_ntoa(sin->sin_addr), SENTINEL);
04340    } else if (sin) {
04341       char porta[25];
04342       sprintf(porta, "%d", ntohs(sin->sin_port));
04343       var = ast_load_realtime("iaxpeers", "ipaddr", ast_inet_ntoa(sin->sin_addr), "port", porta, SENTINEL);
04344       if (var) {
04345          /* We'll need the peer name in order to build the structure! */
04346          for (tmp = var; tmp; tmp = tmp->next) {
04347             if (!strcasecmp(tmp->name, "name"))
04348                peername = tmp->value;
04349          }
04350       }
04351    }
04352    if (!var && peername) { /* Last ditch effort */
04353       var = ast_load_realtime("iaxpeers", "name", peername, SENTINEL);
04354       /*!\note
04355        * If this one loaded something, then we need to ensure that the host
04356        * field matched.  The only reason why we can't have this as a criteria
04357        * is because we only have the IP address and the host field might be
04358        * set as a name (and the reverse PTR might not match).
04359        */
04360       if (var && sin) {
04361          for (tmp = var; tmp; tmp = tmp->next) {
04362             if (!strcasecmp(tmp->name, "host")) {
04363                struct ast_hostent ahp;
04364                struct hostent *hp;
04365                if (!(hp = ast_gethostbyname(tmp->value, &ahp)) || (memcmp(hp->h_addr, &sin->sin_addr, sizeof(hp->h_addr)))) {
04366                   /* No match */
04367                   ast_variables_destroy(var);
04368                   var = NULL;
04369                }
04370                break;
04371             }
04372          }
04373       }
04374    }
04375    if (!var)
04376       return NULL;
04377 
04378    peer = build_peer(peername, var, NULL, ast_test_flag64((&globalflags), IAX_RTCACHEFRIENDS) ? 0 : 1);
04379 
04380    if (!peer) {
04381       ast_variables_destroy(var);
04382       return NULL;
04383    }
04384 
04385    for (tmp = var; tmp; tmp = tmp->next) {
04386       /* Make sure it's not a user only... */
04387       if (!strcasecmp(tmp->name, "type")) {
04388          if (strcasecmp(tmp->value, "friend") &&
04389              strcasecmp(tmp->value, "peer")) {
04390             /* Whoops, we weren't supposed to exist! */
04391             peer = peer_unref(peer);
04392             break;
04393          } 
04394       } else if (!strcasecmp(tmp->name, "regseconds")) {
04395          ast_get_time_t(tmp->value, &regseconds, 0, NULL);
04396       } else if (!strcasecmp(tmp->name, "ipaddr")) {
04397          ast_sockaddr_parse(&peer->addr, tmp->value, PARSE_PORT_IGNORE);
04398       } else if (!strcasecmp(tmp->name, "port")) {
04399          ast_sockaddr_set_port(&peer->addr, atoi(tmp->value));
04400       } else if (!strcasecmp(tmp->name, "host")) {
04401          if (!strcasecmp(tmp->value, "dynamic"))
04402             dynamic = 1;
04403       }
04404    }
04405 
04406    ast_variables_destroy(var);
04407 
04408    if (!peer)
04409       return NULL;
04410 
04411    if (ast_test_flag64((&globalflags), IAX_RTCACHEFRIENDS)) {
04412       ast_copy_flags64(peer, &globalflags, IAX_RTAUTOCLEAR|IAX_RTCACHEFRIENDS);
04413       if (ast_test_flag64(peer, IAX_RTAUTOCLEAR)) {
04414          if (peer->expire > -1) {
04415             if (!ast_sched_thread_del(sched, peer->expire)) {
04416                peer->expire = -1;
04417                peer_unref(peer);
04418             }
04419          }
04420          peer->expire = iax2_sched_add(sched, (global_rtautoclear) * 1000, expire_registry, peer_ref(peer));
04421          if (peer->expire == -1)
04422             peer_unref(peer);
04423       }
04424       ao2_link(peers, peer);
04425       if (ast_test_flag64(peer, IAX_DYNAMIC))
04426          reg_source_db(peer);
04427    } else {
04428       ast_set_flag64(peer, IAX_TEMPONLY);
04429    }
04430 
04431    if (!ast_test_flag64(&globalflags, IAX_RTIGNOREREGEXPIRE) && dynamic) {
04432       time(&nowtime);
04433       if ((nowtime - regseconds) > IAX_DEFAULT_REG_EXPIRE) {
04434          memset(&peer->addr, 0, sizeof(peer->addr));
04435          realtime_update_peer(peer->name, &peer->addr, 0);
04436          ast_debug(1, "realtime_peer: Bah, '%s' is expired (%d/%d/%d)!\n",
04437             peername, (int)(nowtime - regseconds), (int)regseconds, (int)nowtime);
04438       }
04439       else {
04440          ast_debug(1, "realtime_peer: Registration for '%s' still active (%d/%d/%d)!\n",
04441             peername, (int)(nowtime - regseconds), (int)regseconds, (int)nowtime);
04442       }
04443    }
04444 
04445    return peer;
04446 }
04447 
04448 static struct iax2_user *realtime_user(const char *username, struct sockaddr_in *sin)
04449 {
04450    struct ast_variable *var;
04451    struct ast_variable *tmp;
04452    struct iax2_user *user=NULL;
04453 
04454    var = ast_load_realtime("iaxusers", "name", username, "host", "dynamic", SENTINEL);
04455    if (!var)
04456       var = ast_load_realtime("iaxusers", "name", username, "host", ast_inet_ntoa(sin->sin_addr), SENTINEL);
04457    if (!var && sin) {
04458       char porta[6];
04459       snprintf(porta, sizeof(porta), "%d", ntohs(sin->sin_port));
04460       var = ast_load_realtime("iaxusers", "name", username, "ipaddr", ast_inet_ntoa(sin->sin_addr), "port", porta, SENTINEL);
04461       if (!var)
04462          var = ast_load_realtime("iaxusers", "ipaddr", ast_inet_ntoa(sin->sin_addr), "port", porta, SENTINEL);
04463    }
04464    if (!var) { /* Last ditch effort */
04465       var = ast_load_realtime("iaxusers", "name", username, SENTINEL);
04466       /*!\note
04467        * If this one loaded something, then we need to ensure that the host
04468        * field matched.  The only reason why we can't have this as a criteria
04469        * is because we only have the IP address and the host field might be
04470        * set as a name (and the reverse PTR might not match).
04471        */
04472       if (var) {
04473          for (tmp = var; tmp; tmp = tmp->next) {
04474             if (!strcasecmp(tmp->name, "host")) {
04475                struct ast_hostent ahp;
04476                struct hostent *hp;
04477                if (!(hp = ast_gethostbyname(tmp->value, &ahp)) || (memcmp(hp->h_addr, &sin->sin_addr, sizeof(hp->h_addr)))) {
04478                   /* No match */
04479                   ast_variables_destroy(var);
04480                   var = NULL;
04481                }
04482                break;
04483             }
04484          }
04485       }
04486    }
04487    if (!var)
04488       return NULL;
04489 
04490    tmp = var;
04491    while(tmp) {
04492       /* Make sure it's not a peer only... */
04493       if (!strcasecmp(tmp->name, "type")) {
04494          if (strcasecmp(tmp->value, "friend") &&
04495              strcasecmp(tmp->value, "user")) {
04496             return NULL;
04497          } 
04498       }
04499       tmp = tmp->next;
04500    }
04501 
04502    user = build_user(username, var, NULL, !ast_test_flag64((&globalflags), IAX_RTCACHEFRIENDS));
04503 
04504    ast_variables_destroy(var);
04505 
04506    if (!user)
04507       return NULL;
04508 
04509    if (ast_test_flag64((&globalflags), IAX_RTCACHEFRIENDS)) {
04510       ast_set_flag64(user, IAX_RTCACHEFRIENDS);
04511       ao2_link(users, user);
04512    } else {
04513       ast_set_flag64(user, IAX_TEMPONLY);
04514    }
04515 
04516    return user;
04517 }
04518 
04519 static void realtime_update_peer(const char *peername, struct ast_sockaddr *sockaddr, time_t regtime)
04520 {
04521    char port[10];
04522    char regseconds[20];
04523    const char *sysname = ast_config_AST_SYSTEM_NAME;
04524    char *syslabel = NULL;
04525 
04526    if (ast_strlen_zero(sysname)) /* No system name, disable this */
04527       sysname = NULL;
04528    else if (ast_test_flag64(&globalflags, IAX_RTSAVE_SYSNAME))
04529       syslabel = "regserver";
04530 
04531    snprintf(regseconds, sizeof(regseconds), "%d", (int)regtime);
04532    snprintf(port, sizeof(port), "%d", ast_sockaddr_port(sockaddr));
04533    ast_update_realtime("iaxpeers", "name", peername, 
04534       "ipaddr", ast_sockaddr_stringify_addr(sockaddr), "port", port, 
04535       "regseconds", regseconds, syslabel, sysname, SENTINEL); /* note syslable can be NULL */
04536 }
04537 
04538 struct create_addr_info {
04539    format_t capability;
04540    uint64_t flags;
04541    int maxtime;
04542    int encmethods;
04543    int found;
04544    int sockfd;
04545    int adsi;
04546    char username[80];
04547    char secret[80];
04548    char outkey[80];
04549    char timezone[80];
04550    char prefs[32];
04551    char cid_num[80];
04552    char cid_name[80];
04553    char context[AST_MAX_CONTEXT];
04554    char peercontext[AST_MAX_CONTEXT];
04555    char mohinterpret[MAX_MUSICCLASS];
04556    char mohsuggest[MAX_MUSICCLASS];
04557 };
04558 
04559 static int create_addr(const char *peername, struct ast_channel *c, struct sockaddr_in *sin, struct create_addr_info *cai)
04560 {
04561    struct iax2_peer *peer;
04562    int res = -1;
04563    struct ast_codec_pref ourprefs;
04564    struct sockaddr_in peer_addr;
04565 
04566    ast_clear_flag64(cai, IAX_SENDANI | IAX_TRUNK);
04567    cai->sockfd = defaultsockfd;
04568    cai->maxtime = 0;
04569    sin->sin_family = AF_INET;
04570 
04571    if (!(peer = find_peer(peername, 1))) {
04572       struct ast_sockaddr sin_tmp;
04573 
04574       cai->found = 0;
04575       sin_tmp.ss.ss_family = AF_INET;
04576       if (ast_get_ip_or_srv(&sin_tmp, peername, srvlookup ? "_iax._udp" : NULL)) {
04577          ast_log(LOG_WARNING, "No such host: %s\n", peername);
04578          return -1;
04579       }
04580       ast_sockaddr_to_sin(&sin_tmp, sin);
04581       if (sin->sin_port == 0) {
04582          sin->sin_port = htons(IAX_DEFAULT_PORTNO);
04583       }
04584       /* use global iax prefs for unknown peer/user */
04585       /* But move the calling channel's native codec to the top of the preference list */
04586       memcpy(&ourprefs, &prefs, sizeof(ourprefs));
04587       if (c)
04588          ast_codec_pref_prepend(&ourprefs, c->nativeformats, 1);
04589       ast_codec_pref_convert(&ourprefs, cai->prefs, sizeof(cai->prefs), 1);
04590       return 0;
04591    }
04592 
04593    cai->found = 1;
04594 
04595    ast_sockaddr_to_sin(&peer->addr, &peer_addr);
04596 
04597    /* if the peer has no address (current or default), return failure */
04598    if (!(peer_addr.sin_addr.s_addr || peer->defaddr.sin_addr.s_addr)) {
04599       goto return_unref;
04600    }
04601 
04602    /* if the peer is being monitored and is currently unreachable, return failure */
04603    if (peer->maxms && ((peer->lastms > peer->maxms) || (peer->lastms < 0)))
04604       goto return_unref;
04605 
04606    ast_copy_flags64(cai, peer, IAX_SENDANI | IAX_TRUNK | IAX_NOTRANSFER | IAX_TRANSFERMEDIA | IAX_USEJITTERBUF | IAX_FORCEJITTERBUF | IAX_SENDCONNECTEDLINE | IAX_RECVCONNECTEDLINE | IAX_FORCE_ENCRYPT);
04607    cai->maxtime = peer->maxms;
04608    cai->capability = peer->capability;
04609    cai->encmethods = peer->encmethods;
04610    cai->sockfd = peer->sockfd;
04611    cai->adsi = peer->adsi;
04612    memcpy(&ourprefs, &peer->prefs, sizeof(ourprefs));
04613    /* Move the calling channel's native codec to the top of the preference list */
04614    if (c) {
04615       ast_debug(1, "prepending %llx to prefs\n", (unsigned long long) c->nativeformats);
04616       ast_codec_pref_prepend(&ourprefs, c->nativeformats, 1);
04617    }
04618    ast_codec_pref_convert(&ourprefs, cai->prefs, sizeof(cai->prefs), 1);
04619    ast_copy_string(cai->context, peer->context, sizeof(cai->context));
04620    ast_copy_string(cai->peercontext, peer->peercontext, sizeof(cai->peercontext));
04621    ast_copy_string(cai->username, peer->username, sizeof(cai->username));
04622    ast_copy_string(cai->timezone, peer->zonetag, sizeof(cai->timezone));
04623    ast_copy_string(cai->outkey, peer->outkey, sizeof(cai->outkey));
04624    ast_copy_string(cai->cid_num, peer->cid_num, sizeof(cai->cid_num));
04625    ast_copy_string(cai->cid_name, peer->cid_name, sizeof(cai->cid_name));
04626    ast_copy_string(cai->mohinterpret, peer->mohinterpret, sizeof(cai->mohinterpret));
04627    ast_copy_string(cai->mohsuggest, peer->mohsuggest, sizeof(cai->mohsuggest));
04628    if (ast_strlen_zero(peer->dbsecret)) {
04629       ast_copy_string(cai->secret, peer->secret, sizeof(cai->secret));
04630    } else {
04631       char *family;
04632       char *key = NULL;
04633 
04634       family = ast_strdupa(peer->dbsecret);
04635       key = strchr(family, '/');
04636       if (key)
04637          *key++ = '\0';
04638       if (!key || ast_db_get(family, key, cai->secret, sizeof(cai->secret))) {
04639          ast_log(LOG_WARNING, "Unable to retrieve database password for family/key '%s'!\n", peer->dbsecret);
04640          goto return_unref;
04641       }
04642    }
04643 
04644    if (peer_addr.sin_addr.s_addr) {
04645       sin->sin_addr = peer_addr.sin_addr;
04646       sin->sin_port = peer_addr.sin_port;
04647    } else {
04648       sin->sin_addr = peer->defaddr.sin_addr;
04649       sin->sin_port = peer->defaddr.sin_port;
04650    }
04651 
04652    res = 0;
04653 
04654 return_unref:
04655    peer_unref(peer);
04656 
04657    return res;
04658 }
04659 
04660 static void __auto_congest(const void *nothing)
04661 {
04662    int callno = PTR_TO_CALLNO(nothing);
04663    struct ast_frame f = { AST_FRAME_CONTROL, { AST_CONTROL_CONGESTION } };
04664    ast_mutex_lock(&iaxsl[callno]);
04665    if (iaxs[callno]) {
04666       iaxs[callno]->initid = -1;
04667       iax2_queue_frame(callno, &f);
04668       ast_log(LOG_NOTICE, "Auto-congesting call due to slow response\n");
04669    }
04670    ast_mutex_unlock(&iaxsl[callno]);
04671 }
04672 
04673 static int auto_congest(const void *data)
04674 {
04675 #ifdef SCHED_MULTITHREADED
04676    if (schedule_action(__auto_congest, data))
04677 #endif      
04678       __auto_congest(data);
04679    return 0;
04680 }
04681 
04682 static unsigned int iax2_datetime(const char *tz)
04683 {
04684    struct timeval t = ast_tvnow();
04685    struct ast_tm tm;
04686    unsigned int tmp;
04687    ast_localtime(&t, &tm, ast_strlen_zero(tz) ? NULL : tz);
04688    tmp  = (tm.tm_sec >> 1) & 0x1f;        /* 5 bits of seconds */
04689    tmp |= (tm.tm_min & 0x3f) << 5;        /* 6 bits of minutes */
04690    tmp |= (tm.tm_hour & 0x1f) << 11;      /* 5 bits of hours */
04691    tmp |= (tm.tm_mday & 0x1f) << 16;      /* 5 bits of day of month */
04692    tmp |= ((tm.tm_mon + 1) & 0xf) << 21;     /* 4 bits of month */
04693    tmp |= ((tm.tm_year - 100) & 0x7f) << 25; /* 7 bits of year */
04694    return tmp;
04695 }
04696 
04697 struct parsed_dial_string {
04698    char *username;
04699    char *password;
04700    char *key;
04701    char *peer;
04702    char *port;
04703    char *exten;
04704    char *context;
04705    char *options;
04706 };
04707 
04708 static int send_apathetic_reply(unsigned short callno, unsigned short dcallno,
04709       struct sockaddr_in *sin, int command, int ts, unsigned char seqno,
04710       int sockfd, struct iax_ie_data *ied)
04711 {
04712    struct {
04713       struct ast_iax2_full_hdr f;
04714       struct iax_ie_data ied;
04715    } data;
04716    size_t size = sizeof(struct ast_iax2_full_hdr);
04717 
04718    if (ied) {
04719       size += ied->pos;
04720       memcpy(&data.ied, ied->buf, ied->pos);
04721    }
04722 
04723    data.f.scallno = htons(0x8000 | callno);
04724    data.f.dcallno = htons(dcallno & ~IAX_FLAG_RETRANS);
04725    data.f.ts = htonl(ts);
04726    data.f.iseqno = seqno;
04727    data.f.oseqno = 0;
04728    data.f.type = AST_FRAME_IAX;
04729    data.f.csub = compress_subclass(command);
04730 
04731    if (iaxdebug) {
04732       iax_outputframe(NULL, &data.f, 0, sin, size - sizeof(struct ast_iax2_full_hdr));
04733    }
04734 
04735    return sendto(sockfd, &data, size, 0, (struct sockaddr *)sin, sizeof(*sin));
04736 }
04737 
04738 static void add_empty_calltoken_ie(struct chan_iax2_pvt *pvt, struct iax_ie_data *ied)
04739 {
04740    /* first make sure their are two empty bytes left in ied->buf */
04741    if (pvt && ied && (2 < ((int) sizeof(ied->buf) - ied->pos))) {
04742       ied->buf[ied->pos++] = IAX_IE_CALLTOKEN;  /* type */
04743       ied->buf[ied->pos++] = 0;   /* data size,  ZERO in this case */
04744       pvt->calltoken_ie_len = 2;
04745    }
04746 }
04747 
04748 static void resend_with_token(int callno, struct iax_frame *f, const char *newtoken)
04749 {
04750    struct chan_iax2_pvt *pvt = iaxs[callno];
04751    int frametype = f->af.frametype;
04752    int subclass = f->af.subclass.integer;
04753    struct {
04754       struct ast_iax2_full_hdr fh;
04755       struct iax_ie_data ied;
04756    } data = {
04757       .ied.buf = { 0 },
04758       .ied.pos = 0,
04759    };
04760    /* total len - header len gives us the frame's IE len */
04761    int ie_data_pos = f->datalen - sizeof(struct ast_iax2_full_hdr);
04762 
04763    if (!pvt) {
04764       return;  /* this should not be possible if called from socket_process() */
04765    }
04766 
04767    /* 
04768     * Check to make sure last frame sent is valid for call token resend
04769     * 1. Frame should _NOT_ be encrypted since it starts the IAX dialog 
04770     * 2. Frame should _NOT_ already have a destination callno
04771     * 3. Frame must be a valid iax_frame subclass capable of starting dialog
04772     * 4. Pvt must have a calltoken_ie_len which represents the number of
04773     *    bytes at the end of the frame used for the previous calltoken ie.
04774     * 5. Pvt's calltoken_ie_len must be _LESS_ than the total IE length
04775     * 6. Total length of f->data must be _LESS_ than size of our data struct
04776     *    because f->data must be able to fit within data. 
04777     */
04778    if (f->encmethods || f->dcallno || !iax2_allow_new(frametype, subclass, 0)
04779       || !pvt->calltoken_ie_len || (pvt->calltoken_ie_len > ie_data_pos) ||
04780       (f->datalen > sizeof(data))) {
04781 
04782       return;  /* ignore resend, token was not valid for the dialog */
04783    }
04784 
04785    /* token is valid
04786     * 1. Copy frame data over
04787     * 2. Redo calltoken IE, it will always be the last ie in the frame.
04788     *    NOTE: Having the ie always be last is not protocol specified,
04789     *    it is only an implementation choice.  Since we only expect the ie to
04790     *    be last for frames we have sent, this can no way be affected by
04791     *    another end point.
04792     * 3. Remove frame from queue
04793     * 4. Free old frame
04794     * 5. Clear previous seqnos
04795     * 6. Resend with CALLTOKEN ie.
04796     */
04797 
04798    /* ---1.--- */
04799    memcpy(&data, f->data, f->datalen);
04800    data.ied.pos = ie_data_pos;
04801 
04802    /* ---2.--- */
04803    /* move to the beginning of the calltoken ie so we can write over it */
04804    data.ied.pos -= pvt->calltoken_ie_len;
04805    iax_ie_append_str(&data.ied, IAX_IE_CALLTOKEN, newtoken);
04806 
04807    /* make sure to update token length incase it ever has to be stripped off again */
04808    pvt->calltoken_ie_len = data.ied.pos - ie_data_pos; /* new pos minus old pos tells how big token ie is */
04809 
04810    /* ---3.--- */
04811    AST_LIST_REMOVE(&frame_queue[callno], f, list);
04812 
04813    /* ---4.--- */
04814    iax2_frame_free(f);
04815 
04816    /* ---5.--- */
04817    pvt->oseqno = 0;
04818    pvt->rseqno = 0;
04819    pvt->iseqno = 0;
04820    pvt->aseqno = 0;
04821    if (pvt->peercallno) {
04822       remove_by_peercallno(pvt);
04823       pvt->peercallno = 0;
04824    }
04825 
04826    /* ---6.--- */
04827    send_command(pvt, AST_FRAME_IAX, subclass, 0, data.ied.buf, data.ied.pos, -1);
04828 }
04829 
04830 static void requirecalltoken_mark_auto(const char *name, int subclass)
04831 {
04832    struct iax2_user *user = NULL;
04833    struct iax2_peer *peer = NULL;
04834 
04835    if (ast_strlen_zero(name)) {
04836       return; /* no username given */
04837    }
04838 
04839    if ((subclass == IAX_COMMAND_NEW) && (user = find_user(name)) && (user->calltoken_required == CALLTOKEN_AUTO)) {
04840       user->calltoken_required = CALLTOKEN_YES;
04841    } else if ((subclass != IAX_COMMAND_NEW) && (peer = find_peer(name, 1)) && (peer->calltoken_required == CALLTOKEN_AUTO)) {
04842       peer->calltoken_required = CALLTOKEN_YES;
04843    }
04844 
04845    if (peer) {
04846       peer_unref(peer);
04847    }
04848    if (user) {
04849       user_unref(user);
04850    }
04851 }
04852 
04853 /*!
04854  * \internal
04855  *
04856  * \brief handles calltoken logic for a received iax_frame.
04857  * 
04858  * \note frametype must be AST_FRAME_IAX.
04859  * 
04860  * \note
04861  * Three different cases are possible here.
04862  * Case 1. An empty calltoken is provided. This means the client supports
04863  *         calltokens but has not yet received one from us.  In this case
04864  *         a full calltoken IE is created and sent in a calltoken fullframe.
04865  * Case 2. A full calltoken is received and must be checked for validity.
04866  * Case 3. No calltoken is received indicating that the client does not
04867  *         support calltokens.  In this case it is up to the configuration
04868  *         to decide how this should be handled (reject or permit without calltoken)
04869  */
04870 static int handle_call_token(struct ast_iax2_full_hdr *fh, struct iax_ies *ies,
04871       struct sockaddr_in *sin, int fd)
04872 {
04873 #define CALLTOKEN_HASH_FORMAT "%s%d%u%d"  /* address + port + ts + randomcalldata */
04874 #define CALLTOKEN_IE_FORMAT   "%u?%s"     /* time + ? + (40 char hash) */
04875    struct ast_str *buf = ast_str_alloca(256);
04876    time_t t = time(NULL);
04877    char hash[41]; /* 40 char sha1 hash */
04878    int subclass = uncompress_subclass(fh->csub);
04879 
04880    /* ----- Case 1 ----- */
04881    if (ies->calltoken && !ies->calltokendata) {  /* empty calltoken is provided, client supports calltokens */
04882       struct iax_ie_data ied = {
04883          .buf = { 0 },
04884          .pos = 0,
04885       };
04886 
04887       /* create the hash with their address data and our timestamp */
04888       ast_str_set(&buf, 0, CALLTOKEN_HASH_FORMAT, ast_inet_ntoa(sin->sin_addr), sin->sin_port, (unsigned int) t, randomcalltokendata);
04889       ast_sha1_hash(hash, ast_str_buffer(buf));
04890 
04891       ast_str_set(&buf, 0, CALLTOKEN_IE_FORMAT, (unsigned int) t, hash);
04892       iax_ie_append_str(&ied, IAX_IE_CALLTOKEN, ast_str_buffer(buf));
04893       send_apathetic_reply(1, ntohs(fh->scallno), sin, IAX_COMMAND_CALLTOKEN, ntohl(fh->ts), fh->iseqno + 1, fd, &ied);
04894 
04895       return 1;
04896 
04897    /* ----- Case 2 ----- */
04898    } else if (ies->calltoken && ies->calltokendata) { /* calltoken received, check to see if it is valid */
04899       char *rec_hash = NULL;    /* the received hash, make sure it matches with ours. */
04900       char *rec_ts = NULL;      /* received timestamp */
04901       unsigned int rec_time;  /* received time_t */
04902 
04903       /* split the timestamp from the hash data */
04904       rec_hash = strchr((char *) ies->calltokendata, '?');
04905       if (rec_hash) {
04906          *rec_hash++ = '\0';
04907          rec_ts = (char *) ies->calltokendata;
04908       }
04909 
04910       /* check that we have valid data before we do any comparisons */
04911       if (!rec_hash || !rec_ts) {
04912          goto reject;
04913       } else if (sscanf(rec_ts, "%u", &rec_time) != 1) {
04914          goto reject;
04915       }
04916 
04917       /* create a hash with their address and the _TOKEN'S_ timestamp */
04918       ast_str_set(&buf, 0, CALLTOKEN_HASH_FORMAT, ast_inet_ntoa(sin->sin_addr), sin->sin_port, (unsigned int) rec_time, randomcalltokendata);
04919       ast_sha1_hash(hash, ast_str_buffer(buf));
04920 
04921       /* compare hashes and then check timestamp delay */
04922       if (strcmp(hash, rec_hash)) {
04923          ast_log(LOG_WARNING, "Address %s failed CallToken hash inspection\n", ast_inet_ntoa(sin->sin_addr));
04924          goto reject; /* received hash does not match ours, reject */
04925       } else if ((t < rec_time) || ((t - rec_time) >= MAX_CALLTOKEN_DELAY)) {
04926          ast_log(LOG_WARNING, "Too much delay in IAX2 calltoken timestamp from address %s\n", ast_inet_ntoa(sin->sin_addr));
04927          goto reject; /* too much delay, reject */
04928       }
04929 
04930       /* at this point the call token is valid, returning 0 
04931        * will allow socket_process to continue as usual */
04932       requirecalltoken_mark_auto(ies->username, subclass);
04933       return 0;
04934 
04935    /* ----- Case 3 ----- */
04936    } else { /* calltokens are not supported for this client, how do we respond? */
04937       if (calltoken_required(sin, ies->username, subclass)) {
04938          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"));
04939          goto reject;
04940       }
04941       return 0; /* calltoken is not required for this addr, so permit it. */
04942    }
04943 
04944 reject:
04945    /* received frame has failed calltoken inspection, send apathetic reject messages */
04946    if (subclass == IAX_COMMAND_REGREQ || subclass == IAX_COMMAND_REGREL) {
04947       send_apathetic_reply(1, ntohs(fh->scallno), sin, IAX_COMMAND_REGREJ, ntohl(fh->ts), fh->iseqno + 1, fd, NULL);
04948    } else {
04949       send_apathetic_reply(1, ntohs(fh->scallno), sin, IAX_COMMAND_REJECT, ntohl(fh->ts), fh->iseqno + 1, fd, NULL);
04950    }
04951 
04952    return 1;
04953 }
04954 
04955 /*!
04956  * \brief Parses an IAX dial string into its component parts.
04957  * \param data the string to be parsed
04958  * \param pds pointer to a \c struct \c parsed_dial_string to be filled in
04959  * \return nothing
04960  *
04961  * This function parses the string and fills the structure
04962  * with pointers to its component parts. The input string
04963  * will be modified.
04964  *
04965  * \note This function supports both plaintext passwords and RSA
04966  * key names; if the password string is formatted as '[keyname]',
04967  * then the keyname will be placed into the key field, and the
04968  * password field will be set to NULL.
04969  *
04970  * \note The dial string format is:
04971  *       [username[:password]@]peer[:port][/exten[@@context]][/options]
04972  */
04973 static void parse_dial_string(char *data, struct parsed_dial_string *pds)
04974 {
04975    if (ast_strlen_zero(data))
04976       return;
04977 
04978    pds->peer = strsep(&data, "/");
04979    pds->exten = strsep(&data, "/");
04980    pds->options = data;
04981 
04982    if (pds->exten) {
04983       data = pds->exten;
04984       pds->exten = strsep(&data, "@");
04985       pds->context = data;
04986    }
04987 
04988    if (strchr(pds->peer, '@')) {
04989       data = pds->peer;
04990       pds->username = strsep(&data, "@");
04991       pds->peer = data;
04992    }
04993 
04994    if (pds->username) {
04995       data = pds->username;
04996       pds->username = strsep(&data, ":");
04997       pds->password = data;
04998    }
04999 
05000    data = pds->peer;
05001    pds->peer = strsep(&data, ":");
05002    pds->port = data;
05003 
05004    /* check for a key name wrapped in [] in the secret position, if found,
05005       move it to the key field instead
05006    */
05007    if (pds->password && (pds->password[0] == '[')) {
05008       pds->key = ast_strip_quoted(pds->password, "[", "]");
05009       pds->password = NULL;
05010    }
05011 }
05012 
05013 static int iax2_call(struct ast_channel *c, char *dest, int timeout)
05014 {
05015    struct sockaddr_in sin;
05016    char *l=NULL, *n=NULL, *tmpstr;
05017    struct iax_ie_data ied;
05018    char *defaultrdest = "s";
05019    unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
05020    struct parsed_dial_string pds;
05021    struct create_addr_info cai;
05022    struct ast_var_t *var;
05023    struct ast_datastore *variablestore = ast_channel_datastore_find(c, &iax2_variable_datastore_info, NULL);
05024    const char* osp_token_ptr;
05025    unsigned int osp_token_length;
05026    unsigned char osp_block_index;
05027    unsigned int osp_block_length;
05028    unsigned char osp_buffer[256];
05029 
05030    if ((c->_state != AST_STATE_DOWN) && (c->_state != AST_STATE_RESERVED)) {
05031       ast_log(LOG_WARNING, "Channel is already in use (%s)?\n", c->name);
05032       return -1;
05033    }
05034 
05035    memset(&cai, 0, sizeof(cai));
05036    cai.encmethods = iax2_encryption;
05037 
05038    memset(&pds, 0, sizeof(pds));
05039    tmpstr = ast_strdupa(dest);
05040    parse_dial_string(tmpstr, &pds);
05041 
05042    if (ast_strlen_zero(pds.peer)) {
05043       ast_log(LOG_WARNING, "No peer provided in the IAX2 dial string '%s'\n", dest);
05044       return -1;
05045    }
05046    if (!pds.exten) {
05047       pds.exten = defaultrdest;
05048    }
05049    if (create_addr(pds.peer, c, &sin, &cai)) {
05050       ast_log(LOG_WARNING, "No address associated with '%s'\n", pds.peer);
05051       return -1;
05052    }
05053    if (ast_test_flag64(iaxs[callno], IAX_FORCE_ENCRYPT) && !cai.encmethods) {
05054       ast_log(LOG_WARNING, "Encryption forced for call, but not enabled\n");
05055       c->hangupcause = AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
05056       return -1;
05057    }
05058    if (ast_strlen_zero(cai.secret) && ast_test_flag64(iaxs[callno], IAX_FORCE_ENCRYPT)) {
05059       ast_log(LOG_WARNING, "Call terminated. No secret given and force encrypt enabled\n");
05060       return -1;
05061    }
05062    if (!pds.username && !ast_strlen_zero(cai.username))
05063       pds.username = cai.username;
05064    if (!pds.password && !ast_strlen_zero(cai.secret))
05065       pds.password = cai.secret;
05066    if (!pds.key && !ast_strlen_zero(cai.outkey))
05067       pds.key = cai.outkey;
05068    if (!pds.context && !ast_strlen_zero(cai.peercontext))
05069       pds.context = cai.peercontext;
05070 
05071    /* Keep track of the context for outgoing calls too */
05072    ast_copy_string(c->context, cai.context, sizeof(c->context));
05073 
05074    if (pds.port)
05075       sin.sin_port = htons(atoi(pds.port));
05076 
05077    l = c->connected.id.number.valid ? c->connected.id.number.str : NULL;
05078    n = c->connected.id.name.valid ? c->connected.id.name.str : NULL;
05079 
05080    /* Now build request */ 
05081    memset(&ied, 0, sizeof(ied));
05082 
05083    /* On new call, first IE MUST be IAX version of caller */
05084    iax_ie_append_short(&ied, IAX_IE_VERSION, IAX_PROTO_VERSION);
05085    iax_ie_append_str(&ied, IAX_IE_CALLED_NUMBER, pds.exten);
05086    if (pds.options && strchr(pds.options, 'a')) {
05087       /* Request auto answer */
05088       iax_ie_append(&ied, IAX_IE_AUTOANSWER);
05089    }
05090 
05091    /* WARNING: this breaks down at 190 bits! */
05092    iax_ie_append_str(&ied, IAX_IE_CODEC_PREFS, cai.prefs);
05093 
05094    if (l) {
05095       iax_ie_append_str(&ied, IAX_IE_CALLING_NUMBER, l);
05096       iax_ie_append_byte(&ied, IAX_IE_CALLINGPRES,
05097          ast_party_id_presentation(&c->connected.id));
05098    } else if (n) {
05099       iax_ie_append_byte(&ied, IAX_IE_CALLINGPRES,
05100          ast_party_id_presentation(&c->connected.id));
05101    } else {
05102       iax_ie_append_byte(&ied, IAX_IE_CALLINGPRES, AST_PRES_NUMBER_NOT_AVAILABLE);
05103    }
05104 
05105    iax_ie_append_byte(&ied, IAX_IE_CALLINGTON, c->connected.id.number.plan);
05106    iax_ie_append_short(&ied, IAX_IE_CALLINGTNS, c->dialed.transit_network_select);
05107 
05108    if (n)
05109       iax_ie_append_str(&ied, IAX_IE_CALLING_NAME, n);
05110    if (ast_test_flag64(iaxs[callno], IAX_SENDANI)
05111       && c->connected.ani.number.valid
05112       && c->connected.ani.number.str) {
05113       iax_ie_append_str(&ied, IAX_IE_CALLING_ANI, c->connected.ani.number.str);
05114    }
05115 
05116    if (!ast_strlen_zero(c->language))
05117       iax_ie_append_str(&ied, IAX_IE_LANGUAGE, c->language);
05118    if (!ast_strlen_zero(c->dialed.number.str)) {
05119       iax_ie_append_str(&ied, IAX_IE_DNID, c->dialed.number.str);
05120    }
05121    if (c->redirecting.from.number.valid
05122       && !ast_strlen_zero(c->redirecting.from.number.str)) {
05123       iax_ie_append_str(&ied, IAX_IE_RDNIS, c->redirecting.from.number.str);
05124    }
05125 
05126    if (pds.context)
05127       iax_ie_append_str(&ied, IAX_IE_CALLED_CONTEXT, pds.context);
05128 
05129    if (pds.username)
05130       iax_ie_append_str(&ied, IAX_IE_USERNAME, pds.username);
05131 
05132    if (cai.encmethods)
05133       iax_ie_append_short(&ied, IAX_IE_ENCRYPTION, cai.encmethods);
05134 
05135    ast_mutex_lock(&iaxsl[callno]);
05136 
05137    if (!ast_strlen_zero(c->context))
05138       ast_string_field_set(iaxs[callno], context, c->context);
05139 
05140    if (pds.username)
05141       ast_string_field_set(iaxs[callno], username, pds.username);
05142 
05143    iaxs[callno]->encmethods = cai.encmethods;
05144 
05145    iaxs[callno]->adsi = cai.adsi;
05146    
05147    ast_string_field_set(iaxs[callno], mohinterpret, cai.mohinterpret);
05148    ast_string_field_set(iaxs[callno], mohsuggest, cai.mohsuggest);
05149 
05150    if (pds.key)
05151       ast_string_field_set(iaxs[callno], outkey, pds.key);
05152    if (pds.password)
05153       ast_string_field_set(iaxs[callno], secret, pds.password);
05154 
05155    iax_ie_append_int(&ied, IAX_IE_FORMAT, (int) c->nativeformats);
05156    iax_ie_append_versioned_uint64(&ied, IAX_IE_FORMAT2, 0, c->nativeformats);
05157    iax_ie_append_int(&ied, IAX_IE_CAPABILITY, (int) iaxs[callno]->capability);
05158    iax_ie_append_versioned_uint64(&ied, IAX_IE_CAPABILITY2, 0, iaxs[callno]->capability);
05159    iax_ie_append_short(&ied, IAX_IE_ADSICPE, c->adsicpe);
05160    iax_ie_append_int(&ied, IAX_IE_DATETIME, iax2_datetime(cai.timezone));
05161 
05162    if (iaxs[callno]->maxtime) {
05163       /* Initialize pingtime and auto-congest time */
05164       iaxs[callno]->pingtime = iaxs[callno]->maxtime / 2;
05165       iaxs[callno]->initid = iax2_sched_add(sched, iaxs[callno]->maxtime * 2, auto_congest, CALLNO_TO_PTR(callno));
05166    } else if (autokill) {
05167       iaxs[callno]->pingtime = autokill / 2;
05168       iaxs[callno]->initid = iax2_sched_add(sched, autokill * 2, auto_congest, CALLNO_TO_PTR(callno));
05169    }
05170 
05171    /* Check if there is an OSP token */
05172    osp_token_ptr = pbx_builtin_getvar_helper(c, "IAX2OSPTOKEN");
05173    if (!ast_strlen_zero(osp_token_ptr)) {
05174       if ((osp_token_length = strlen(osp_token_ptr)) <= IAX_MAX_OSPTOKEN_SIZE) {
05175          osp_block_index = 0;
05176          while (osp_token_length > 0) {
05177             osp_block_length = IAX_MAX_OSPBLOCK_SIZE < osp_token_length ? IAX_MAX_OSPBLOCK_SIZE : osp_token_length;
05178             osp_buffer[0] = osp_block_index;
05179             memcpy(osp_buffer + 1, osp_token_ptr, osp_block_length);
05180             iax_ie_append_raw(&ied, IAX_IE_OSPTOKEN, osp_buffer, osp_block_length + 1);
05181             osp_block_index++;
05182             osp_token_ptr += osp_block_length;
05183             osp_token_length -= osp_block_length;
05184          } 
05185       } else
05186          ast_log(LOG_WARNING, "OSP token is too long\n");
05187    } else if (iaxdebug)
05188       ast_debug(1, "OSP token is undefined\n");
05189 
05190    /* send the command using the appropriate socket for this peer */
05191    iaxs[callno]->sockfd = cai.sockfd;
05192 
05193    /* Add remote vars */
05194    if (variablestore) {
05195       AST_LIST_HEAD(, ast_var_t) *variablelist = variablestore->data;
05196       ast_debug(1, "Found an IAX variable store on this channel\n");
05197       AST_LIST_LOCK(variablelist);
05198       AST_LIST_TRAVERSE(variablelist, var, entries) {
05199          char tmp[256];
05200          int i;
05201          ast_debug(1, "Found IAXVAR '%s' with value '%s' (to transmit)\n", ast_var_name(var), ast_var_value(var));
05202          /* Automatically divide the value up into sized chunks */
05203          for (i = 0; i < strlen(ast_var_value(var)); i += 255 - (strlen(ast_var_name(var)) + 1)) {
05204             snprintf(tmp, sizeof(tmp), "%s=%s", ast_var_name(var), ast_var_value(var) + i);
05205             iax_ie_append_str(&ied, IAX_IE_VARIABLE, tmp);
05206          }
05207       }
05208       AST_LIST_UNLOCK(variablelist);
05209    }
05210 
05211    /* Transmit the string in a "NEW" request */
05212    add_empty_calltoken_ie(iaxs[callno], &ied); /* this _MUST_ be the last ie added */
05213    send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_NEW, 0, ied.buf, ied.pos, -1);
05214 
05215    ast_mutex_unlock(&iaxsl[callno]);
05216    ast_setstate(c, AST_STATE_RINGING);
05217 
05218    return 0;
05219 }
05220 
05221 static int iax2_hangup(struct ast_channel *c) 
05222 {
05223    unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
05224    struct iax_ie_data ied;
05225    int alreadygone;
05226    memset(&ied, 0, sizeof(ied));
05227    ast_mutex_lock(&iaxsl[callno]);
05228    if (callno && iaxs[callno]) {
05229       ast_debug(1, "We're hanging up %s now...\n", c->name);
05230       alreadygone = ast_test_flag64(iaxs[callno], IAX_ALREADYGONE);
05231       /* Send the hangup unless we have had a transmission error or are already gone */
05232       iax_ie_append_byte(&ied, IAX_IE_CAUSECODE, (unsigned char)c->hangupcause);
05233       if (!iaxs[callno]->error && !alreadygone) {
05234          if (send_command_final(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_HANGUP, 0, ied.buf, ied.pos, -1)) {
05235             ast_log(LOG_WARNING, "No final packet could be sent for callno %d\n", callno);
05236          }
05237          if (!iaxs[callno]) {
05238             ast_mutex_unlock(&iaxsl[callno]);
05239             return 0;
05240          }
05241       }
05242       /* Explicitly predestroy it */
05243       iax2_predestroy(callno);
05244       /* If we were already gone to begin with, destroy us now */
05245       if (iaxs[callno] && alreadygone) {
05246          ast_debug(1, "Really destroying %s now...\n", c->name);
05247          iax2_destroy(callno);
05248       } else if (iaxs[callno]) {
05249          if (ast_sched_thread_add(sched, 10000, scheduled_destroy, CALLNO_TO_PTR(callno)) < 0) {
05250             ast_log(LOG_ERROR, "Unable to schedule iax2 callno %d destruction?!!  Destroying immediately.\n", callno);
05251             iax2_destroy(callno);
05252          }
05253       }
05254    } else if (c->tech_pvt) {
05255       /* If this call no longer exists, but the channel still
05256        * references it we need to set the channel's tech_pvt to null
05257        * to avoid ast_channel_free() trying to free it.
05258        */
05259       c->tech_pvt = NULL;
05260    }
05261    ast_mutex_unlock(&iaxsl[callno]);
05262    ast_verb(3, "Hungup '%s'\n", c->name);
05263    return 0;
05264 }
05265 
05266 /*!
05267  * \note expects the pvt to be locked
05268  */
05269 static int wait_for_peercallno(struct chan_iax2_pvt *pvt)
05270 {
05271    unsigned short callno = pvt->callno;
05272 
05273    if (!pvt->peercallno) {
05274       /* We don't know the remote side's call number, yet.  :( */
05275       int count = 10;
05276       while (count-- && pvt && !pvt->peercallno) {
05277          DEADLOCK_AVOIDANCE(&iaxsl[callno]);
05278          pvt = iaxs[callno];
05279       }
05280       if (!pvt->peercallno) {
05281          return -1;
05282       }
05283    }
05284 
05285    return 0;
05286 }
05287 
05288 static int iax2_setoption(struct ast_channel *c, int option, void *data, int datalen)
05289 {
05290    struct ast_option_header *h;
05291    int res;
05292 
05293    switch (option) {
05294    case AST_OPTION_TXGAIN:
05295    case AST_OPTION_RXGAIN:
05296       /* these two cannot be sent, because they require a result */
05297       errno = ENOSYS;
05298       return -1;
05299    case AST_OPTION_OPRMODE:
05300       errno = EINVAL;
05301       return -1;
05302    case AST_OPTION_SECURE_SIGNALING:
05303    case AST_OPTION_SECURE_MEDIA:
05304    {
05305       unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
05306       ast_mutex_lock(&iaxsl[callno]);
05307       if ((*(int *) data)) {
05308          ast_set_flag64(iaxs[callno], IAX_FORCE_ENCRYPT);
05309       } else {
05310          ast_clear_flag64(iaxs[callno], IAX_FORCE_ENCRYPT);
05311       }
05312       ast_mutex_unlock(&iaxsl[callno]);
05313       return 0;
05314    }
05315    /* These options are sent to the other side across the network where
05316     * they will be passed to whatever channel is bridged there. Don't
05317     * do anything silly like pass an option that transmits pointers to
05318     * memory on this machine to a remote machine to use */
05319    case AST_OPTION_TONE_VERIFY:
05320    case AST_OPTION_TDD:
05321    case AST_OPTION_RELAXDTMF:
05322    case AST_OPTION_AUDIO_MODE:
05323    case AST_OPTION_DIGIT_DETECT:
05324    case AST_OPTION_FAX_DETECT:
05325    {
05326       unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
05327       struct chan_iax2_pvt *pvt;
05328 
05329       ast_mutex_lock(&iaxsl[callno]);
05330       pvt = iaxs[callno];
05331 
05332       if (wait_for_peercallno(pvt)) {
05333          ast_mutex_unlock(&iaxsl[callno]);
05334          return -1;
05335       }
05336 
05337       ast_mutex_unlock(&iaxsl[callno]);
05338 
05339       if (!(h = ast_malloc(datalen + sizeof(*h)))) {
05340          return -1;
05341       }
05342 
05343       h->flag = AST_OPTION_FLAG_REQUEST;
05344       h->option = htons(option);
05345       memcpy(h->data, data, datalen);
05346       res = send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_CONTROL,
05347                  AST_CONTROL_OPTION, 0, (unsigned char *) h,
05348                  datalen + sizeof(*h), -1);
05349       ast_free(h);
05350       return res;
05351    }
05352    default:
05353       return -1;
05354    }
05355 
05356    /* Just in case someone does a break instead of a return */
05357    return -1;
05358 }
05359 
05360 static int iax2_queryoption(struct ast_channel *c, int option, void *data, int *datalen)
05361 {
05362    switch (option) {
05363    case AST_OPTION_SECURE_SIGNALING:
05364    case AST_OPTION_SECURE_MEDIA:
05365    {
05366       unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
05367       ast_mutex_lock(&iaxsl[callno]);
05368       *((int *) data) = ast_test_flag64(iaxs[callno], IAX_FORCE_ENCRYPT) ? 1 : 0;
05369       ast_mutex_unlock(&iaxsl[callno]);
05370       return 0;
05371    }
05372    default:
05373       return -1;
05374    }
05375 }
05376 
05377 static struct ast_frame *iax2_read(struct ast_channel *c) 
05378 {
05379    ast_debug(1, "I should never be called!\n");
05380    return &ast_null_frame;
05381 }
05382 
05383 static int iax2_key_rotate(const void *vpvt)
05384 {
05385    int res = 0;
05386    struct chan_iax2_pvt *pvt = (void *) vpvt;
05387    struct MD5Context md5;
05388    char key[17] = "";
05389    struct iax_ie_data ied = {
05390       .pos = 0,   
05391    };
05392    
05393    ast_mutex_lock(&iaxsl[pvt->callno]);
05394    pvt->keyrotateid = 
05395       ast_sched_thread_add(sched, 120000 + (ast_random() % 180001), iax2_key_rotate, vpvt);
05396 
05397    snprintf(key, sizeof(key), "%lX", ast_random());
05398 
05399    MD5Init(&md5);
05400    MD5Update(&md5, (unsigned char *) key, strlen(key));
05401    MD5Final((unsigned char *) key, &md5);
05402 
05403    IAX_DEBUGDIGEST("Sending", key);
05404 
05405    iax_ie_append_raw(&ied, IAX_IE_CHALLENGE, key, 16);
05406 
05407    res = send_command(pvt, AST_FRAME_IAX, IAX_COMMAND_RTKEY, 0, ied.buf, ied.pos, -1);
05408 
05409    build_ecx_key((unsigned char *) key, pvt);
05410 
05411    ast_mutex_unlock(&iaxsl[pvt->callno]);
05412 
05413    return res;
05414 }
05415 
05416 static int iax2_start_transfer(unsigned short callno0, unsigned short callno1, int mediaonly)
05417 {
05418    int res;
05419    struct iax_ie_data ied0;
05420    struct iax_ie_data ied1;
05421    unsigned int transferid = (unsigned int)ast_random();
05422 
05423    if (IAX_CALLENCRYPTED(iaxs[callno0]) || IAX_CALLENCRYPTED(iaxs[callno1])) {
05424       ast_debug(1, "transfers are not supported for encrypted calls at this time");
05425       ast_set_flag64(iaxs[callno0], IAX_NOTRANSFER);
05426       ast_set_flag64(iaxs[callno1], IAX_NOTRANSFER);
05427       return 0;
05428    }
05429 
05430    memset(&ied0, 0, sizeof(ied0));
05431    iax_ie_append_addr(&ied0, IAX_IE_APPARENT_ADDR, &iaxs[callno1]->addr);
05432    iax_ie_append_short(&ied0, IAX_IE_CALLNO, iaxs[callno1]->peercallno);
05433    iax_ie_append_int(&ied0, IAX_IE_TRANSFERID, transferid);
05434 
05435    memset(&ied1, 0, sizeof(ied1));
05436    iax_ie_append_addr(&ied1, IAX_IE_APPARENT_ADDR, &iaxs[callno0]->addr);
05437    iax_ie_append_short(&ied1, IAX_IE_CALLNO, iaxs[callno0]->peercallno);
05438    iax_ie_append_int(&ied1, IAX_IE_TRANSFERID, transferid);
05439    
05440    res = send_command(iaxs[callno0], AST_FRAME_IAX, IAX_COMMAND_TXREQ, 0, ied0.buf, ied0.pos, -1);
05441    if (res)
05442       return -1;
05443    res = send_command(iaxs[callno1], AST_FRAME_IAX, IAX_COMMAND_TXREQ, 0, ied1.buf, ied1.pos, -1);
05444    if (res)
05445       return -1;
05446    iaxs[callno0]->transferring = mediaonly ? TRANSFER_MBEGIN : TRANSFER_BEGIN;
05447    iaxs[callno1]->transferring = mediaonly ? TRANSFER_MBEGIN : TRANSFER_BEGIN;
05448    return 0;
05449 }
05450 
05451 static void lock_both(unsigned short callno0, unsigned short callno1)
05452 {
05453    ast_mutex_lock(&iaxsl[callno0]);
05454    while (ast_mutex_trylock(&iaxsl[callno1])) {
05455       DEADLOCK_AVOIDANCE(&iaxsl[callno0]);
05456    }
05457 }
05458 
05459 static void unlock_both(unsigned short callno0, unsigned short callno1)
05460 {
05461    ast_mutex_unlock(&iaxsl[callno1]);
05462    ast_mutex_unlock(&iaxsl[callno0]);
05463 }
05464 
05465 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)
05466 {
05467    struct ast_channel *cs[3];
05468    struct ast_channel *who, *other;
05469    int to = -1;
05470    int res = -1;
05471    int transferstarted=0;
05472    struct ast_frame *f;
05473    unsigned short callno0 = PTR_TO_CALLNO(c0->tech_pvt);
05474    unsigned short callno1 = PTR_TO_CALLNO(c1->tech_pvt);
05475    struct timeval waittimer = {0, 0};
05476 
05477    /* We currently do not support native bridging if a timeoutms value has been provided */
05478    if (timeoutms > 0) {
05479       return AST_BRIDGE_FAILED;
05480    }
05481 
05482    timeoutms = -1;
05483 
05484    lock_both(callno0, callno1);
05485    if (!iaxs[callno0] || !iaxs[callno1]) {
05486       unlock_both(callno0, callno1);
05487       return AST_BRIDGE_FAILED;
05488    }
05489    /* Put them in native bridge mode */
05490    if (!(flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1))) {
05491       iaxs[callno0]->bridgecallno = callno1;
05492       iaxs[callno1]->bridgecallno = callno0;
05493    }
05494    unlock_both(callno0, callno1);
05495 
05496    /* If not, try to bridge until we can execute a transfer, if we can */
05497    cs[0] = c0;
05498    cs[1] = c1;
05499    for (/* ever */;;) {
05500       /* Check in case we got masqueraded into */
05501       if ((c0->tech != &iax2_tech) || (c1->tech != &iax2_tech)) {
05502          ast_verb(3, "Can't masquerade, we're different...\n");
05503          /* Remove from native mode */
05504          if (c0->tech == &iax2_tech) {
05505             ast_mutex_lock(&iaxsl[callno0]);
05506             iaxs[callno0]->bridgecallno = 0;
05507             ast_mutex_unlock(&iaxsl[callno0]);
05508          }
05509          if (c1->tech == &iax2_tech) {
05510             ast_mutex_lock(&iaxsl[callno1]);
05511             iaxs[callno1]->bridgecallno = 0;
05512             ast_mutex_unlock(&iaxsl[callno1]);
05513          }
05514          return AST_BRIDGE_FAILED_NOWARN;
05515       }
05516       if (c0->nativeformats != c1->nativeformats) {
05517          char buf0[256];
05518          char buf1[256];
05519          ast_getformatname_multiple(buf0, sizeof(buf0), c0->nativeformats);
05520          ast_getformatname_multiple(buf1, sizeof(buf1), c1->nativeformats);
05521          ast_verb(3, "Operating with different codecs [%s] [%s] , can't native bridge...\n", buf0, buf1);
05522          /* Remove from native mode */
05523          lock_both(callno0, callno1);
05524          if (iaxs[callno0])
05525             iaxs[callno0]->bridgecallno = 0;
05526          if (iaxs[callno1])
05527             iaxs[callno1]->bridgecallno = 0;
05528          unlock_both(callno0, callno1);
05529          return AST_BRIDGE_FAILED_NOWARN;
05530       }
05531       /* check if transfered and if we really want native bridging */
05532       if (!transferstarted && !ast_test_flag64(iaxs[callno0], IAX_NOTRANSFER) && !ast_test_flag64(iaxs[callno1], IAX_NOTRANSFER)) {
05533          /* Try the transfer */
05534          if (iax2_start_transfer(callno0, callno1, (flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1)) ||
05535                      ast_test_flag64(iaxs[callno0], IAX_TRANSFERMEDIA) | ast_test_flag64(iaxs[callno1], IAX_TRANSFERMEDIA)))
05536             ast_log(LOG_WARNING, "Unable to start the transfer\n");
05537          transferstarted = 1;
05538       }
05539       if ((iaxs[callno0]->transferring == TRANSFER_RELEASED) && (iaxs[callno1]->transferring == TRANSFER_RELEASED)) {
05540          /* Call has been transferred.  We're no longer involved */
05541          struct timeval now = ast_tvnow();
05542          if (ast_tvzero(waittimer)) {
05543             waittimer = now;
05544          } else if (now.tv_sec - waittimer.tv_sec > IAX_LINGER_TIMEOUT) {
05545             c0->_softhangup |= AST_SOFTHANGUP_DEV;
05546             c1->_softhangup |= AST_SOFTHANGUP_DEV;
05547             *fo = NULL;
05548             *rc = c0;
05549             res = AST_BRIDGE_COMPLETE;
05550             break;
05551          }
05552       }
05553       to = 1000;
05554       who = ast_waitfor_n(cs, 2, &to);
05555       if (timeoutms > -1) {
05556          timeoutms -= (1000 - to);
05557          if (timeoutms < 0)
05558             timeoutms = 0;
05559       }
05560       if (!who) {
05561          if (!timeoutms) {
05562             res = AST_BRIDGE_RETRY;
05563             break;
05564          }
05565          if (ast_check_hangup(c0) || ast_check_hangup(c1)) {
05566             res = AST_BRIDGE_FAILED;
05567             break;
05568          }
05569          continue;
05570       }
05571       f = ast_read(who);
05572       if (!f) {
05573          *fo = NULL;
05574          *rc = who;
05575          res = AST_BRIDGE_COMPLETE;
05576          break;
05577       }
05578       if ((f->frametype == AST_FRAME_CONTROL) && !(flags & AST_BRIDGE_IGNORE_SIGS) && (f->subclass.integer != AST_CONTROL_SRCUPDATE)) {
05579          *fo = f;
05580          *rc = who;
05581          res =  AST_BRIDGE_COMPLETE;
05582          break;
05583       }
05584       other = (who == c0) ? c1 : c0;  /* the 'other' channel */
05585       if ((f->frametype == AST_FRAME_VOICE) ||
05586          (f->frametype == AST_FRAME_TEXT) ||
05587          (f->frametype == AST_FRAME_VIDEO) || 
05588          (f->frametype == AST_FRAME_IMAGE) ||
05589          (f->frametype == AST_FRAME_DTMF) ||
05590          (f->frametype == AST_FRAME_CONTROL)) {
05591          /* monitored dtmf take out of the bridge.
05592           * check if we monitor the specific source.
05593           */
05594          int monitored_source = (who == c0) ? AST_BRIDGE_DTMF_CHANNEL_0 : AST_BRIDGE_DTMF_CHANNEL_1;
05595          if (f->frametype == AST_FRAME_DTMF && (flags & monitored_source)) {
05596             *rc = who;
05597             *fo = f;
05598             res = AST_BRIDGE_COMPLETE;
05599             /* Remove from native mode */
05600             break;
05601          }
05602          /* everything else goes to the other side */
05603          ast_write(other, f);
05604       }
05605       ast_frfree(f);
05606       /* Swap who gets priority */
05607       cs[2] = cs[0];
05608       cs[0] = cs[1];
05609       cs[1] = cs[2];
05610    }
05611    lock_both(callno0, callno1);
05612    if(iaxs[callno0])
05613       iaxs[callno0]->bridgecallno = 0;
05614    if(iaxs[callno1])
05615       iaxs[callno1]->bridgecallno = 0;
05616    unlock_both(callno0, callno1);
05617    return res;
05618 }
05619 
05620 static int iax2_answer(struct ast_channel *c)
05621 {
05622    unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
05623    ast_debug(1, "Answering IAX2 call\n");
05624    ast_mutex_lock(&iaxsl[callno]);
05625    if (iaxs[callno])
05626       iax2_ami_channelupdate(iaxs[callno]);
05627    ast_mutex_unlock(&iaxsl[callno]);
05628    return send_command_locked(callno, AST_FRAME_CONTROL, AST_CONTROL_ANSWER, 0, NULL, 0, -1);
05629 }
05630 
05631 static int iax2_indicate(struct ast_channel *c, int condition, const void *data, size_t datalen)
05632 {
05633    unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
05634    struct chan_iax2_pvt *pvt;
05635    int res = 0;
05636 
05637    if (iaxdebug)
05638       ast_debug(1, "Indicating condition %d\n", condition);
05639 
05640    ast_mutex_lock(&iaxsl[callno]);
05641    pvt = iaxs[callno];
05642 
05643    if (wait_for_peercallno(pvt)) {
05644       res = -1;
05645       goto done;
05646    }
05647 
05648    switch (condition) {
05649    case AST_CONTROL_HOLD:
05650       if (strcasecmp(pvt->mohinterpret, "passthrough")) {
05651          ast_moh_start(c, data, pvt->mohinterpret);
05652          goto done;
05653       }
05654       break;
05655    case AST_CONTROL_UNHOLD:
05656       if (strcasecmp(pvt->mohinterpret, "passthrough")) {
05657          ast_moh_stop(c);
05658          goto done;
05659       }
05660       break;
05661    case AST_CONTROL_CONNECTED_LINE:
05662       if (!ast_test_flag64(pvt, IAX_SENDCONNECTEDLINE))
05663          goto done;
05664       break;
05665    }
05666 
05667    res = send_command(pvt, AST_FRAME_CONTROL, condition, 0, data, datalen, -1);
05668 
05669 done:
05670    ast_mutex_unlock(&iaxsl[callno]);
05671 
05672    return res;
05673 }
05674    
05675 static int iax2_transfer(struct ast_channel *c, const char *dest)
05676 {
05677    unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
05678    struct iax_ie_data ied = { "", };
05679    char tmp[256], *context;
05680    enum ast_control_transfer message = AST_TRANSFER_SUCCESS;
05681    ast_copy_string(tmp, dest, sizeof(tmp));
05682    context = strchr(tmp, '@');
05683    if (context) {
05684       *context = '\0';
05685       context++;
05686    }
05687    iax_ie_append_str(&ied, IAX_IE_CALLED_NUMBER, tmp);
05688    if (context)
05689       iax_ie_append_str(&ied, IAX_IE_CALLED_CONTEXT, context);
05690    ast_debug(1, "Transferring '%s' to '%s'\n", c->name, dest);
05691    ast_queue_control_data(c, AST_CONTROL_TRANSFER, &message, sizeof(message));
05692    return send_command_locked(callno, AST_FRAME_IAX, IAX_COMMAND_TRANSFER, 0, ied.buf, ied.pos, -1);
05693 }
05694    
05695 static int iax2_getpeertrunk(struct sockaddr_in sin)
05696 {
05697    struct iax2_peer *peer;
05698    int res = 0;
05699    struct ao2_iterator i;
05700 
05701    i = ao2_iterator_init(peers, 0);
05702    while ((peer = ao2_iterator_next(&i))) {
05703       struct sockaddr_in peer_addr;
05704 
05705       ast_sockaddr_to_sin(&peer->addr, &peer_addr);
05706 
05707       if ((peer_addr.sin_addr.s_addr == sin.sin_addr.s_addr) &&
05708           (peer_addr.sin_port == sin.sin_port)) {
05709          res = ast_test_flag64(peer, IAX_TRUNK);
05710          peer_unref(peer);
05711          break;
05712       }
05713       peer_unref(peer);
05714    }
05715    ao2_iterator_destroy(&i);
05716 
05717    return res;
05718 }
05719 
05720 /*! \brief  Create new call, interface with the PBX core */
05721 static struct ast_channel *ast_iax2_new(int callno, int state, format_t capability, const char *linkedid)
05722 {
05723    struct ast_channel *tmp;
05724    struct chan_iax2_pvt *i;
05725    struct ast_variable *v = NULL;
05726 
05727    if (!(i = iaxs[callno])) {
05728       ast_log(LOG_WARNING, "No IAX2 pvt found for callno '%d' !\n", callno);
05729       return NULL;
05730    }
05731 
05732    /* Don't hold call lock */
05733    ast_mutex_unlock(&iaxsl[callno]);
05734    tmp = ast_channel_alloc(1, state, i->cid_num, i->cid_name, i->accountcode, i->exten, i->context, linkedid, i->amaflags, "IAX2/%s-%d", i->host, i->callno);
05735    ast_mutex_lock(&iaxsl[callno]);
05736    if (i != iaxs[callno]) {
05737       if (tmp) {
05738          /* unlock and relock iaxsl[callno] to preserve locking order */
05739          ast_mutex_unlock(&iaxsl[callno]);
05740          tmp = ast_channel_release(tmp);
05741          ast_mutex_lock(&iaxsl[callno]);
05742       }
05743       return NULL;
05744    }
05745    iax2_ami_channelupdate(i);
05746    if (!tmp)
05747       return NULL;
05748    tmp->tech = &iax2_tech;
05749    /* We can support any format by default, until we get restricted */
05750    tmp->nativeformats = capability;
05751    tmp->readformat = tmp->rawreadformat = ast_best_codec(capability);
05752    tmp->writeformat = tmp->rawwriteformat = ast_best_codec(capability);
05753    tmp->tech_pvt = CALLNO_TO_PTR(i->callno);
05754 
05755    if (!ast_strlen_zero(i->parkinglot))
05756       ast_string_field_set(tmp, parkinglot, i->parkinglot);
05757    /* Don't use ast_set_callerid() here because it will
05758     * generate a NewCallerID event before the NewChannel event */
05759    if (!ast_strlen_zero(i->ani)) {
05760       tmp->caller.ani.number.valid = 1;
05761       tmp->caller.ani.number.str = ast_strdup(i->ani);
05762    } else if (!ast_strlen_zero(i->cid_num)) {
05763       tmp->caller.ani.number.valid = 1;
05764       tmp->caller.ani.number.str = ast_strdup(i->cid_num);
05765    }
05766    tmp->dialed.number.str = ast_strdup(i->dnid);
05767    if (!ast_strlen_zero(i->rdnis)) {
05768       tmp->redirecting.from.number.valid = 1;
05769       tmp->redirecting.from.number.str = ast_strdup(i->rdnis);
05770    }
05771    tmp->caller.id.name.presentation = i->calling_pres;
05772    tmp->caller.id.number.presentation = i->calling_pres;
05773    tmp->caller.id.number.plan = i->calling_ton;
05774    tmp->dialed.transit_network_select = i->calling_tns;
05775    if (!ast_strlen_zero(i->language))
05776       ast_string_field_set(tmp, language, i->language);
05777    if (!ast_strlen_zero(i->accountcode))
05778       ast_string_field_set(tmp, accountcode, i->accountcode);
05779    if (i->amaflags)
05780       tmp->amaflags = i->amaflags;
05781    ast_copy_string(tmp->context, i->context, sizeof(tmp->context));
05782    ast_copy_string(tmp->exten, i->exten, sizeof(tmp->exten));
05783    if (i->adsi)
05784       tmp->adsicpe = i->peeradsicpe;
05785    else
05786       tmp->adsicpe = AST_ADSI_UNAVAILABLE;
05787    i->owner = tmp;
05788    i->capability = capability;
05789 
05790    /* Set inherited variables */
05791    if (i->vars) {
05792       for (v = i->vars ; v ; v = v->next)
05793          pbx_builtin_setvar_helper(tmp, v->name, v->value);
05794    }
05795    if (i->iaxvars) {
05796       struct ast_datastore *variablestore;
05797       struct ast_variable *var, *prev = NULL;
05798       AST_LIST_HEAD(, ast_var_t) *varlist;
05799       ast_debug(1, "Loading up the channel with IAXVARs\n");
05800       varlist = ast_calloc(1, sizeof(*varlist));
05801       variablestore = ast_datastore_alloc(&iax2_variable_datastore_info, NULL);
05802       if (variablestore && varlist) {
05803          variablestore->data = varlist;
05804          variablestore->inheritance = DATASTORE_INHERIT_FOREVER;
05805          AST_LIST_HEAD_INIT(varlist);
05806          for (var = i->iaxvars; var; var = var->next) {
05807             struct ast_var_t *newvar = ast_var_assign(var->name, var->value);
05808             if (prev)
05809                ast_free(prev);
05810             prev = var;
05811             if (!newvar) {
05812                /* Don't abort list traversal, as this would leave i->iaxvars in an inconsistent state. */
05813                ast_log(LOG_ERROR, "Memory allocation error while processing IAX2 variables\n");
05814             } else {
05815                AST_LIST_INSERT_TAIL(varlist, newvar, entries);
05816             }
05817          }
05818          if (prev)
05819             ast_free(prev);
05820          i->iaxvars = NULL;
05821          ast_channel_datastore_add(i->owner, variablestore);
05822       } else {
05823          if (variablestore) {
05824             ast_datastore_free(variablestore);
05825          }
05826          if (varlist) {
05827             ast_free(varlist);
05828          }
05829       }
05830    }
05831 
05832    if (state != AST_STATE_DOWN) {
05833       if (ast_pbx_start(tmp)) {
05834          ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
05835          ast_hangup(tmp);
05836          i->owner = NULL;
05837          return NULL;
05838       }
05839    }
05840 
05841    ast_module_ref(ast_module_info->self);
05842    return tmp;
05843 }
05844 
05845 static unsigned int calc_txpeerstamp(struct iax2_trunk_peer *tpeer, int sampms, struct timeval *now)
05846 {
05847    unsigned long int mssincetx; /* unsigned to handle overflows */
05848    long int ms, pred;
05849 
05850    tpeer->trunkact = *now;
05851    mssincetx = ast_tvdiff_ms(*now, tpeer->lasttxtime);
05852    if (mssincetx > 5000 || ast_tvzero(tpeer->txtrunktime)) {
05853       /* If it's been at least 5 seconds since the last time we transmitted on this trunk, reset our timers */
05854       tpeer->txtrunktime = *now;
05855       tpeer->lastsent = 999999;
05856    }
05857    /* Update last transmit time now */
05858    tpeer->lasttxtime = *now;
05859    
05860    /* Calculate ms offset */
05861    ms = ast_tvdiff_ms(*now, tpeer->txtrunktime);
05862    /* Predict from last value */
05863    pred = tpeer->lastsent + sampms;
05864    if (abs(ms - pred) < MAX_TIMESTAMP_SKEW)
05865       ms = pred;
05866    
05867    /* We never send the same timestamp twice, so fudge a little if we must */
05868    if (ms == tpeer->lastsent)
05869       ms = tpeer->lastsent + 1;
05870    tpeer->lastsent = ms;
05871    return ms;
05872 }
05873 
05874 static unsigned int fix_peerts(struct timeval *rxtrunktime, int callno, unsigned int ts)
05875 {
05876    long ms; /* NOT unsigned */
05877    if (ast_tvzero(iaxs[callno]->rxcore)) {
05878       /* Initialize rxcore time if appropriate */
05879       iaxs[callno]->rxcore = ast_tvnow();
05880       /* Round to nearest 20ms so traces look pretty */
05881       iaxs[callno]->rxcore.tv_usec -= iaxs[callno]->rxcore.tv_usec % 20000;
05882    }
05883    /* Calculate difference between trunk and channel */
05884    ms = ast_tvdiff_ms(*rxtrunktime, iaxs[callno]->rxcore);
05885    /* Return as the sum of trunk time and the difference between trunk and real time */
05886    return ms + ts;
05887 }
05888 
05889 static unsigned int calc_timestamp(struct chan_iax2_pvt *p, unsigned int ts, struct ast_frame *f)
05890 {
05891    int ms;
05892    int voice = 0;
05893    int genuine = 0;
05894    int adjust;
05895    int rate = ast_format_rate(f->subclass.codec) / 1000;
05896    struct timeval *delivery = NULL;
05897 
05898 
05899    /* What sort of frame do we have?: voice is self-explanatory
05900       "genuine" means an IAX frame - things like LAGRQ/RP, PING/PONG, ACK
05901       non-genuine frames are CONTROL frames [ringing etc], DTMF
05902       The "genuine" distinction is needed because genuine frames must get a clock-based timestamp,
05903       the others need a timestamp slaved to the voice frames so that they go in sequence
05904    */
05905    if (f) {
05906       if (f->frametype == AST_FRAME_VOICE) {
05907          voice = 1;
05908          delivery = &f->delivery;
05909       } else if (f->frametype == AST_FRAME_IAX) {
05910          genuine = 1;
05911       } else if (f->frametype == AST_FRAME_CNG) {
05912          p->notsilenttx = 0;  
05913       }
05914    }
05915    if (ast_tvzero(p->offset)) {
05916       p->offset = ast_tvnow();
05917       /* Round to nearest 20ms for nice looking traces */
05918       p->offset.tv_usec -= p->offset.tv_usec % 20000;
05919    }
05920    /* If the timestamp is specified, just send it as is */
05921    if (ts)
05922       return ts;
05923    /* If we have a time that the frame arrived, always use it to make our timestamp */
05924    if (delivery && !ast_tvzero(*delivery)) {
05925       ms = ast_tvdiff_ms(*delivery, p->offset);
05926       if (ms < 0) {
05927          ms = 0;
05928       }
05929       if (iaxdebug)
05930          ast_debug(3, "calc_timestamp: call %d/%d: Timestamp slaved to delivery time\n", p->callno, iaxs[p->callno]->peercallno);
05931    } else {
05932       ms = ast_tvdiff_ms(ast_tvnow(), p->offset);
05933       if (ms < 0)
05934          ms = 0;
05935       if (voice) {
05936          /* On a voice frame, use predicted values if appropriate */
05937          if (p->notsilenttx && abs(ms - p->nextpred) <= MAX_TIMESTAMP_SKEW) {
05938             /* Adjust our txcore, keeping voice and non-voice synchronized */
05939             /* AN EXPLANATION:
05940                When we send voice, we usually send "calculated" timestamps worked out
05941                on the basis of the number of samples sent. When we send other frames,
05942                we usually send timestamps worked out from the real clock.
05943                The problem is that they can tend to drift out of step because the 
05944                   source channel's clock and our clock may not be exactly at the same rate.
05945                We fix this by continuously "tweaking" p->offset.  p->offset is "time zero"
05946                for this call.  Moving it adjusts timestamps for non-voice frames.
05947                We make the adjustment in the style of a moving average.  Each time we
05948                adjust p->offset by 10% of the difference between our clock-derived
05949                timestamp and the predicted timestamp.  That's why you see "10000"
05950                below even though IAX2 timestamps are in milliseconds.
05951                The use of a moving average avoids offset moving too radically.
05952                Generally, "adjust" roams back and forth around 0, with offset hardly
05953                changing at all.  But if a consistent different starts to develop it
05954                will be eliminated over the course of 10 frames (200-300msecs) 
05955             */
05956             adjust = (ms - p->nextpred);
05957             if (adjust < 0)
05958                p->offset = ast_tvsub(p->offset, ast_samp2tv(abs(adjust), 10000));
05959             else if (adjust > 0)
05960                p->offset = ast_tvadd(p->offset, ast_samp2tv(adjust, 10000));
05961 
05962             if (!p->nextpred) {
05963                p->nextpred = ms; /*f->samples / rate;*/
05964                if (p->nextpred <= p->lastsent)
05965                   p->nextpred = p->lastsent + 3;
05966             }
05967             ms = p->nextpred;
05968          } else {
05969                 /* in this case, just use the actual
05970             * time, since we're either way off
05971             * (shouldn't happen), or we're  ending a
05972             * silent period -- and seed the next
05973             * predicted time.  Also, round ms to the
05974             * next multiple of frame size (so our
05975             * silent periods are multiples of
05976             * frame size too) */
05977 
05978             if (iaxdebug && abs(ms - p->nextpred) > MAX_TIMESTAMP_SKEW )
05979                ast_debug(1, "predicted timestamp skew (%u) > max (%u), using real ts instead.\n",
05980                   abs(ms - p->nextpred), MAX_TIMESTAMP_SKEW);
05981 
05982             if (f->samples >= rate) /* check to make sure we don't core dump */
05983             {
05984                int diff = ms % (f->samples / rate);
05985                if (diff)
05986                    ms += f->samples/rate - diff;
05987             }
05988 
05989             p->nextpred = ms;
05990             p->notsilenttx = 1;
05991          }
05992       } else if ( f->frametype == AST_FRAME_VIDEO ) {
05993          /*
05994          * IAX2 draft 03 says that timestamps MUST be in order.
05995          * It does not say anything about several frames having the same timestamp
05996          * When transporting video, we can have a frame that spans multiple iax packets
05997          * (so called slices), so it would make sense to use the same timestamp for all of
05998          * them
05999          * We do want to make sure that frames don't go backwards though
06000          */
06001          if ( (unsigned int)ms < p->lastsent )
06002             ms = p->lastsent;
06003       } else {
06004          /* On a dataframe, use last value + 3 (to accomodate jitter buffer shrinking) if appropriate unless
06005             it's a genuine frame */
06006          if (genuine) {
06007             /* genuine (IAX LAGRQ etc) must keep their clock-based stamps */
06008             if (ms <= p->lastsent)
06009                ms = p->lastsent + 3;
06010          } else if (abs(ms - p->lastsent) <= MAX_TIMESTAMP_SKEW) {
06011             /* non-genuine frames (!?) (DTMF, CONTROL) should be pulled into the predicted stream stamps */
06012             ms = p->lastsent + 3;
06013          }
06014       }
06015    }
06016    p->lastsent = ms;
06017    if (voice)
06018       p->nextpred = p->nextpred + f->samples / rate;
06019    return ms;
06020 }
06021 
06022 static unsigned int calc_rxstamp(struct chan_iax2_pvt *p, unsigned int offset)
06023 {
06024    /* Returns where in "receive time" we are.  That is, how many ms
06025       since we received (or would have received) the frame with timestamp 0 */
06026    int ms;
06027 #ifdef IAXTESTS
06028    int jit;
06029 #endif /* IAXTESTS */
06030    /* Setup rxcore if necessary */
06031    if (ast_tvzero(p->rxcore)) {
06032       p->rxcore = ast_tvnow();
06033       if (iaxdebug)
06034          ast_debug(1, "calc_rxstamp: call=%d: rxcore set to %d.%6.6d - %dms\n",
06035                p->callno, (int)(p->rxcore.tv_sec), (int)(p->rxcore.tv_usec), offset);
06036       p->rxcore = ast_tvsub(p->rxcore, ast_samp2tv(offset, 1000));
06037 #if 1
06038       if (iaxdebug)
06039          ast_debug(1, "calc_rxstamp: call=%d: works out as %d.%6.6d\n",
06040                p->callno, (int)(p->rxcore.tv_sec),(int)( p->rxcore.tv_usec));
06041 #endif
06042    }
06043 
06044    ms = ast_tvdiff_ms(ast_tvnow(), p->rxcore);
06045 #ifdef IAXTESTS
06046    if (test_jit) {
06047       if (!test_jitpct || ((100.0 * ast_random() / (RAND_MAX + 1.0)) < test_jitpct)) {
06048          jit = (int)((float)test_jit * ast_random() / (RAND_MAX + 1.0));
06049          if ((int)(2.0 * ast_random() / (RAND_MAX + 1.0)))
06050             jit = -jit;
06051          ms += jit;
06052       }
06053    }
06054    if (test_late) {
06055       ms += test_late;
06056       test_late = 0;
06057    }
06058 #endif /* IAXTESTS */
06059    return ms;
06060 }
06061 
06062 static struct iax2_trunk_peer *find_tpeer(struct sockaddr_in *sin, int fd)
06063 {
06064    struct iax2_trunk_peer *tpeer = NULL;
06065    
06066    /* Finds and locks trunk peer */
06067    AST_LIST_LOCK(&tpeers);
06068 
06069    AST_LIST_TRAVERSE(&tpeers, tpeer, list) {
06070       if (!inaddrcmp(&tpeer->addr, sin)) {
06071          ast_mutex_lock(&tpeer->lock);
06072          break;
06073       }
06074    }
06075 
06076    if (!tpeer) {
06077       if ((tpeer = ast_calloc(1, sizeof(*tpeer)))) {
06078          ast_mutex_init(&tpeer->lock);
06079          tpeer->lastsent = 9999;
06080          memcpy(&tpeer->addr, sin, sizeof(tpeer->addr));
06081          tpeer->trunkact = ast_tvnow();
06082          ast_mutex_lock(&tpeer->lock);
06083          tpeer->sockfd = fd;
06084 #ifdef SO_NO_CHECK
06085          setsockopt(tpeer->sockfd, SOL_SOCKET, SO_NO_CHECK, &nochecksums, sizeof(nochecksums));
06086 #endif
06087          ast_debug(1, "Created trunk peer for '%s:%d'\n", ast_inet_ntoa(tpeer->addr.sin_addr), ntohs(tpeer->addr.sin_port));
06088          AST_LIST_INSERT_TAIL(&tpeers, tpeer, list);
06089       }
06090    }
06091 
06092    AST_LIST_UNLOCK(&tpeers);
06093 
06094    return tpeer;
06095 }
06096 
06097 static int iax2_trunk_queue(struct chan_iax2_pvt *pvt, struct iax_frame *fr)
06098 {
06099    struct ast_frame *f;
06100    struct iax2_trunk_peer *tpeer;
06101    void *tmp, *ptr;
06102    struct timeval now;
06103    struct ast_iax2_meta_trunk_entry *met;
06104    struct ast_iax2_meta_trunk_mini *mtm;
06105 
06106    f = &fr->af;
06107    tpeer = find_tpeer(&pvt->addr, pvt->sockfd);
06108    if (tpeer) {
06109       if (tpeer->trunkdatalen + f->datalen + 4 >= tpeer->trunkdataalloc) {
06110          /* Need to reallocate space */
06111          if (tpeer->trunkdataalloc < trunkmaxsize) {
06112             if (!(tmp = ast_realloc(tpeer->trunkdata, tpeer->trunkdataalloc + DEFAULT_TRUNKDATA + IAX2_TRUNK_PREFACE))) {
06113                ast_mutex_unlock(&tpeer->lock);
06114                return -1;
06115             }
06116             
06117             tpeer->trunkdataalloc += DEFAULT_TRUNKDATA;
06118             tpeer->trunkdata = tmp;
06119             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);
06120          } else {
06121             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));
06122             ast_mutex_unlock(&tpeer->lock);
06123             return -1;
06124          }
06125       }
06126 
06127       /* Append to meta frame */
06128       ptr = tpeer->trunkdata + IAX2_TRUNK_PREFACE + tpeer->trunkdatalen;
06129       if (ast_test_flag64(&globalflags, IAX_TRUNKTIMESTAMPS)) {
06130          mtm = (struct ast_iax2_meta_trunk_mini *)ptr;
06131          mtm->len = htons(f->datalen);
06132          mtm->mini.callno = htons(pvt->callno);
06133          mtm->mini.ts = htons(0xffff & fr->ts);
06134          ptr += sizeof(struct ast_iax2_meta_trunk_mini);
06135          tpeer->trunkdatalen += sizeof(struct ast_iax2_meta_trunk_mini);
06136       } else {
06137          met = (struct ast_iax2_meta_trunk_entry *)ptr;
06138          /* Store call number and length in meta header */
06139          met->callno = htons(pvt->callno);
06140          met->len = htons(f->datalen);
06141          /* Advance pointers/decrease length past trunk entry header */
06142          ptr += sizeof(struct ast_iax2_meta_trunk_entry);
06143          tpeer->trunkdatalen += sizeof(struct ast_iax2_meta_trunk_entry);
06144       }
06145       /* Copy actual trunk data */
06146       memcpy(ptr, f->data.ptr, f->datalen);
06147       tpeer->trunkdatalen += f->datalen;
06148 
06149       tpeer->calls++;
06150 
06151       /* track the largest mtu we actually have sent */
06152       if (tpeer->trunkdatalen + f->datalen + 4 > trunk_maxmtu) 
06153          trunk_maxmtu = tpeer->trunkdatalen + f->datalen + 4 ; 
06154 
06155       /* if we have enough for a full MTU, ship it now without waiting */
06156       if (global_max_trunk_mtu > 0 && tpeer->trunkdatalen + f->datalen + 4 >= global_max_trunk_mtu) {
06157          now = ast_tvnow();
06158          send_trunk(tpeer, &now); 
06159          trunk_untimed ++; 
06160       }
06161 
06162       ast_mutex_unlock(&tpeer->lock);
06163    }
06164    return 0;
06165 }
06166 
06167 /* IAX2 encryption requires 16 to 32 bytes of random padding to be present
06168  * before the encryption data.  This function randomizes that data. */
06169 static void build_rand_pad(unsigned char *buf, ssize_t len)
06170 {
06171    long tmp;
06172    for (tmp = ast_random(); len > 0; tmp = ast_random()) {
06173       memcpy(buf, (unsigned char *) &tmp, (len > sizeof(tmp)) ? sizeof(tmp) : len);
06174       buf += sizeof(tmp);
06175       len -= sizeof(tmp);
06176    }
06177 }
06178 
06179 static void build_encryption_keys(const unsigned char *digest, struct chan_iax2_pvt *pvt)
06180 {
06181    build_ecx_key(digest, pvt);
06182    ast_aes_set_decrypt_key(digest, &pvt->dcx);
06183 }
06184 
06185 static void build_ecx_key(const unsigned char *digest, struct chan_iax2_pvt *pvt)
06186 {
06187    /* it is required to hold the corresponding decrypt key to our encrypt key
06188     * in the pvt struct because queued frames occasionally need to be decrypted and
06189     * re-encrypted when updated for a retransmission */
06190    build_rand_pad(pvt->semirand, sizeof(pvt->semirand));
06191    ast_aes_set_encrypt_key(digest, &pvt->ecx);
06192    ast_aes_set_decrypt_key(digest, &pvt->mydcx);
06193 }
06194 
06195 static void memcpy_decrypt(unsigned char *dst, const unsigned char *src, int len, ast_aes_decrypt_key *dcx)
06196 {
06197 #if 0
06198    /* Debug with "fake encryption" */
06199    int x;
06200    if (len % 16)
06201       ast_log(LOG_WARNING, "len should be multiple of 16, not %d!\n", len);
06202    for (x=0;x<len;x++)
06203       dst[x] = src[x] ^ 0xff;
06204 #else 
06205    unsigned char lastblock[16] = { 0 };
06206    int x;
06207    while(len > 0) {
06208       ast_aes_decrypt(src, dst, dcx);
06209       for (x=0;x<16;x++)
06210          dst[x] ^= lastblock[x];
06211       memcpy(lastblock, src, sizeof(lastblock));
06212       dst += 16;
06213       src += 16;
06214       len -= 16;
06215    }
06216 #endif
06217 }
06218 
06219 static void memcpy_encrypt(unsigned char *dst, const unsigned char *src, int len, ast_aes_encrypt_key *ecx)
06220 {
06221 #if 0
06222    /* Debug with "fake encryption" */
06223    int x;
06224    if (len % 16)
06225       ast_log(LOG_WARNING, "len should be multiple of 16, not %d!\n", len);
06226    for (x=0;x<len;x++)
06227       dst[x] = src[x] ^ 0xff;
06228 #else
06229    unsigned char curblock[16] = { 0 };
06230    int x;
06231    while(len > 0) {
06232       for (x=0;x<16;x++)
06233          curblock[x] ^= src[x];
06234       ast_aes_encrypt(curblock, dst, ecx);
06235       memcpy(curblock, dst, sizeof(curblock)); 
06236       dst += 16;
06237       src += 16;
06238       len -= 16;
06239    }
06240 #endif
06241 }
06242 
06243 static int decode_frame(ast_aes_decrypt_key *dcx, struct ast_iax2_full_hdr *fh, struct ast_frame *f, int *datalen)
06244 {
06245    int padding;
06246    unsigned char *workspace;
06247 
06248    workspace = alloca(*datalen);
06249    memset(f, 0, sizeof(*f));
06250    if (ntohs(fh->scallno) & IAX_FLAG_FULL) {
06251       struct ast_iax2_full_enc_hdr *efh = (struct ast_iax2_full_enc_hdr *)fh;
06252       if (*datalen < 16 + sizeof(struct ast_iax2_full_hdr))
06253          return -1;
06254       /* Decrypt */
06255       memcpy_decrypt(workspace, efh->encdata, *datalen - sizeof(struct ast_iax2_full_enc_hdr), dcx);
06256 
06257       padding = 16 + (workspace[15] & 0x0f);
06258       if (iaxdebug)
06259          ast_debug(1, "Decoding full frame with length %d (padding = %d) (15=%02x)\n", *datalen, padding, workspace[15]);
06260       if (*datalen < padding + sizeof(struct ast_iax2_full_hdr))
06261          return -1;
06262 
06263       *datalen -= padding;
06264       memcpy(efh->encdata, workspace + padding, *datalen - sizeof(struct ast_iax2_full_enc_hdr));
06265       f->frametype = fh->type;
06266       if (f->frametype == AST_FRAME_VIDEO) {
06267          f->subclass.codec = uncompress_subclass(fh->csub & ~0x40) | ((fh->csub >> 6) & 0x1);
06268       } else if (f->frametype == AST_FRAME_VOICE) {
06269          f->subclass.codec = uncompress_subclass(fh->csub);
06270       } else {
06271          f->subclass.integer = uncompress_subclass(fh->csub);
06272       }
06273    } else {
06274       struct ast_iax2_mini_enc_hdr *efh = (struct ast_iax2_mini_enc_hdr *)fh;
06275       if (iaxdebug)
06276          ast_debug(1, "Decoding mini with length %d\n", *datalen);
06277       if (*datalen < 16 + sizeof(struct ast_iax2_mini_hdr))
06278          return -1;
06279       /* Decrypt */
06280       memcpy_decrypt(workspace, efh->encdata, *datalen - sizeof(struct ast_iax2_mini_enc_hdr), dcx);
06281       padding = 16 + (workspace[15] & 0x0f);
06282       if (*datalen < padding + sizeof(struct ast_iax2_mini_hdr))
06283          return -1;
06284       *datalen -= padding;
06285       memcpy(efh->encdata, workspace + padding, *datalen - sizeof(struct ast_iax2_mini_enc_hdr));
06286    }
06287    return 0;
06288 }
06289 
06290 static int encrypt_frame(ast_aes_encrypt_key *ecx, struct ast_iax2_full_hdr *fh, unsigned char *poo, int *datalen)
06291 {
06292    int padding;
06293    unsigned char *workspace;
06294    workspace = alloca(*datalen + 32);
06295    if (!workspace)
06296       return -1;
06297    if (ntohs(fh->scallno) & IAX_FLAG_FULL) {
06298       struct ast_iax2_full_enc_hdr *efh = (struct ast_iax2_full_enc_hdr *)fh;
06299       if (iaxdebug)
06300          ast_debug(1, "Encoding full frame %d/%d with length %d\n", fh->type, fh->csub, *datalen);
06301       padding = 16 - ((*datalen - sizeof(struct ast_iax2_full_enc_hdr)) % 16);
06302       padding = 16 + (padding & 0xf);
06303       memcpy(workspace, poo, padding);
06304       memcpy(workspace + padding, efh->encdata, *datalen - sizeof(struct ast_iax2_full_enc_hdr));
06305       workspace[15] &= 0xf0;
06306       workspace[15] |= (padding & 0xf);
06307       if (iaxdebug)
06308          ast_debug(1, "Encoding full frame %d/%d with length %d + %d padding (15=%02x)\n", fh->type, fh->csub, *datalen, padding, workspace[15]);
06309       *datalen += padding;
06310       memcpy_encrypt(efh->encdata, workspace, *datalen - sizeof(struct ast_iax2_full_enc_hdr), ecx);
06311       if (*datalen >= 32 + sizeof(struct ast_iax2_full_enc_hdr))
06312          memcpy(poo, workspace + *datalen - 32, 32);
06313    } else {
06314       struct ast_iax2_mini_enc_hdr *efh = (struct ast_iax2_mini_enc_hdr *)fh;
06315       if (iaxdebug)
06316          ast_debug(1, "Encoding mini frame with length %d\n", *datalen);
06317       padding = 16 - ((*datalen - sizeof(struct ast_iax2_mini_enc_hdr)) % 16);
06318       padding = 16 + (padding & 0xf);
06319       memcpy(workspace, poo, padding);
06320       memcpy(workspace + padding, efh->encdata, *datalen - sizeof(struct ast_iax2_mini_enc_hdr));
06321       workspace[15] &= 0xf0;
06322       workspace[15] |= (padding & 0x0f);
06323       *datalen += padding;
06324       memcpy_encrypt(efh->encdata, workspace, *datalen - sizeof(struct ast_iax2_mini_enc_hdr), ecx);
06325       if (*datalen >= 32 + sizeof(struct ast_iax2_mini_enc_hdr))
06326          memcpy(poo, workspace + *datalen - 32, 32);
06327    }
06328    return 0;
06329 }
06330 
06331 static int decrypt_frame(int callno, struct ast_iax2_full_hdr *fh, struct ast_frame *f, int *datalen)
06332 {
06333    int res=-1;
06334    if (!ast_test_flag64(iaxs[callno], IAX_KEYPOPULATED)) {
06335       /* Search for possible keys, given secrets */
06336       struct MD5Context md5;
06337       unsigned char digest[16];
06338       char *tmppw, *stringp;
06339       
06340       tmppw = ast_strdupa(iaxs[callno]->secret);
06341       stringp = tmppw;
06342       while ((tmppw = strsep(&stringp, ";"))) {
06343          MD5Init(&md5);
06344          MD5Update(&md5, (unsigned char *)iaxs[callno]->challenge, strlen(iaxs[callno]->challenge));
06345          MD5Update(&md5, (unsigned char *)tmppw, strlen(tmppw));
06346          MD5Final(digest, &md5);
06347          build_encryption_keys(digest, iaxs[callno]);
06348          res = decode_frame(&iaxs[callno]->dcx, fh, f, datalen);
06349          if (!res) {
06350             ast_set_flag64(iaxs[callno], IAX_KEYPOPULATED);
06351             break;
06352          }
06353       }
06354    } else 
06355       res = decode_frame(&iaxs[callno]->dcx, fh, f, datalen);
06356    return res;
06357 }
06358 
06359 static int iax2_send(struct chan_iax2_pvt *pvt, struct ast_frame *f, unsigned int ts, int seqno, int now, int transfer, int final)
06360 {
06361    /* Queue a packet for delivery on a given private structure.  Use "ts" for
06362       timestamp, or calculate if ts is 0.  Send immediately without retransmission
06363       or delayed, with retransmission */
06364    struct ast_iax2_full_hdr *fh;
06365    struct ast_iax2_mini_hdr *mh;
06366    struct ast_iax2_video_hdr *vh;
06367    struct {
06368       struct iax_frame fr2;
06369       unsigned char buffer[4096];
06370    } frb;
06371    struct iax_frame *fr;
06372    int res;
06373    int sendmini=0;
06374    unsigned int lastsent;
06375    unsigned int fts;
06376 
06377    frb.fr2.afdatalen = sizeof(frb.buffer);
06378 
06379    if (!pvt) {
06380       ast_log(LOG_WARNING, "No private structure for packet?\n");
06381       return -1;
06382    }
06383    
06384    lastsent = pvt->lastsent;
06385 
06386    /* Calculate actual timestamp */
06387    fts = calc_timestamp(pvt, ts, f);
06388 
06389    /* Bail here if this is an "interp" frame; we don't want or need to send these placeholders out
06390     * (the endpoint should detect the lost packet itself).  But, we want to do this here, so that we
06391     * increment the "predicted timestamps" for voice, if we're predicting */
06392    if(f->frametype == AST_FRAME_VOICE && f->datalen == 0)
06393       return 0;
06394 #if 0
06395    ast_log(LOG_NOTICE, 
06396       "f->frametype %c= AST_FRAME_VOICE, %sencrypted, %srotation scheduled...\n",
06397       *("=!" + (f->frametype == AST_FRAME_VOICE)),
06398       IAX_CALLENCRYPTED(pvt) ? "" : "not ",
06399       pvt->keyrotateid != -1 ? "" : "no "
06400    );
06401 #endif
06402    if (pvt->keyrotateid == -1 && f->frametype == AST_FRAME_VOICE && IAX_CALLENCRYPTED(pvt)) {
06403       iax2_key_rotate(pvt);
06404    }
06405 
06406    if ((ast_test_flag64(pvt, IAX_TRUNK) || 
06407          (((fts & 0xFFFF0000L) == (lastsent & 0xFFFF0000L)) ||
06408          ((fts & 0xFFFF0000L) == ((lastsent + 0x10000) & 0xFFFF0000L))))
06409       /* High two bytes are the same on timestamp, or sending on a trunk */ &&
06410        (f->frametype == AST_FRAME_VOICE) 
06411       /* is a voice frame */ &&
06412       (f->subclass.codec == pvt->svoiceformat) 
06413       /* is the same type */ ) {
06414          /* Force immediate rather than delayed transmission */
06415          now = 1;
06416          /* Mark that mini-style frame is appropriate */
06417          sendmini = 1;
06418    }
06419    if ( f->frametype == AST_FRAME_VIDEO ) {
06420       /*
06421        * If the lower 15 bits of the timestamp roll over, or if
06422        * the video format changed then send a full frame.
06423        * Otherwise send a mini video frame
06424        */
06425       if (((fts & 0xFFFF8000L) == (pvt->lastvsent & 0xFFFF8000L)) &&
06426           ((f->subclass.codec & ~0x1LL) == pvt->svideoformat)
06427          ) {
06428          now = 1;
06429          sendmini = 1;
06430       } else {
06431          now = 0;
06432          sendmini = 0;
06433       }
06434       pvt->lastvsent = fts;
06435    }
06436    if (f->frametype == AST_FRAME_IAX) {
06437       /* 0x8000 marks this message as TX:, this bit will be stripped later */
06438       pvt->last_iax_message = f->subclass.integer | MARK_IAX_SUBCLASS_TX;
06439       if (!pvt->first_iax_message) {
06440          pvt->first_iax_message = pvt->last_iax_message;
06441       }
06442    }
06443    /* Allocate an iax_frame */
06444    if (now) {
06445       fr = &frb.fr2;
06446    } else
06447       fr = iax_frame_new(DIRECTION_OUTGRESS, ast_test_flag64(pvt, IAX_ENCRYPTED) ? f->datalen + 32 : f->datalen, (f->frametype == AST_FRAME_VOICE) || (f->frametype == AST_FRAME_VIDEO));
06448    if (!fr) {
06449       ast_log(LOG_WARNING, "Out of memory\n");
06450       return -1;
06451    }
06452    /* Copy our prospective frame into our immediate or retransmitted wrapper */
06453    iax_frame_wrap(fr, f);
06454 
06455    fr->ts = fts;
06456    fr->callno = pvt->callno;
06457    fr->transfer = transfer;
06458    fr->final = final;
06459    fr->encmethods = 0;
06460    if (!sendmini) {
06461       /* We need a full frame */
06462       if (seqno > -1)
06463          fr->oseqno = seqno;
06464       else
06465          fr->oseqno = pvt->oseqno++;
06466       fr->iseqno = pvt->iseqno;
06467       fh = (struct ast_iax2_full_hdr *)(fr->af.data.ptr - sizeof(struct ast_iax2_full_hdr));
06468       fh->scallno = htons(fr->callno | IAX_FLAG_FULL);
06469       fh->ts = htonl(fr->ts);
06470       fh->oseqno = fr->oseqno;
06471       if (transfer) {
06472          fh->iseqno = 0;
06473       } else
06474          fh->iseqno = fr->iseqno;
06475       /* Keep track of the last thing we've acknowledged */
06476       if (!transfer)
06477          pvt->aseqno = fr->iseqno;
06478       fh->type = fr->af.frametype & 0xFF;
06479 
06480       if (fr->af.frametype == AST_FRAME_VIDEO) {
06481          fh->csub = compress_subclass(fr->af.subclass.codec & ~0x1LL) | ((fr->af.subclass.codec & 0x1LL) << 6);
06482       } else if (fr->af.frametype == AST_FRAME_VOICE) {
06483          fh->csub = compress_subclass(fr->af.subclass.codec);
06484       } else {
06485          fh->csub = compress_subclass(fr->af.subclass.integer);
06486       }
06487 
06488       if (transfer) {
06489          fr->dcallno = pvt->transfercallno;
06490       } else
06491          fr->dcallno = pvt->peercallno;
06492       fh->dcallno = htons(fr->dcallno);
06493       fr->datalen = fr->af.datalen + sizeof(struct ast_iax2_full_hdr);
06494       fr->data = fh;
06495       fr->retries = 0;
06496       /* Retry after 2x the ping time has passed */
06497       fr->retrytime = pvt->pingtime * 2;
06498       if (fr->retrytime < MIN_RETRY_TIME)
06499          fr->retrytime = MIN_RETRY_TIME;
06500       if (fr->retrytime > MAX_RETRY_TIME)
06501          fr->retrytime = MAX_RETRY_TIME;
06502       /* Acks' don't get retried */
06503       if ((f->frametype == AST_FRAME_IAX) && (f->subclass.integer == IAX_COMMAND_ACK))
06504          fr->retries = -1;
06505       else if (f->frametype == AST_FRAME_VOICE)
06506          pvt->svoiceformat = f->subclass.codec;
06507       else if (f->frametype == AST_FRAME_VIDEO)
06508          pvt->svideoformat = f->subclass.codec & ~0x1LL;
06509       if (ast_test_flag64(pvt, IAX_ENCRYPTED)) {
06510          if (ast_test_flag64(pvt, IAX_KEYPOPULATED)) {
06511             if (fr->transfer)
06512                iax_outputframe(fr, NULL, 2, &pvt->transfer, fr->datalen - sizeof(struct ast_iax2_full_hdr));
06513             else
06514                iax_outputframe(fr, NULL, 2, &pvt->addr, fr->datalen - sizeof(struct ast_iax2_full_hdr));
06515             encrypt_frame(&pvt->ecx, fh, pvt->semirand, &fr->datalen);
06516             fr->encmethods = pvt->encmethods;
06517             fr->ecx = pvt->ecx;
06518             fr->mydcx = pvt->mydcx;
06519             memcpy(fr->semirand, pvt->semirand, sizeof(fr->semirand));
06520          } else
06521             ast_log(LOG_WARNING, "Supposed to send packet encrypted, but no key?\n");
06522       }
06523 
06524       if (now) {
06525          res = send_packet(fr);
06526       } else
06527          res = iax2_transmit(fr);
06528    } else {
06529       if (ast_test_flag64(pvt, IAX_TRUNK)) {
06530          iax2_trunk_queue(pvt, fr);
06531          res = 0;
06532       } else if (fr->af.frametype == AST_FRAME_VIDEO) {
06533          /* Video frame have no sequence number */
06534          fr->oseqno = -1;
06535          fr->iseqno = -1;
06536          vh = (struct ast_iax2_video_hdr *)(fr->af.data.ptr - sizeof(struct ast_iax2_video_hdr));
06537          vh->zeros = 0;
06538          vh->callno = htons(0x8000 | fr->callno);
06539          vh->ts = htons((fr->ts & 0x7FFF) | (fr->af.subclass.codec & 0x1LL ? 0x8000 : 0));
06540          fr->datalen = fr->af.datalen + sizeof(struct ast_iax2_video_hdr);
06541          fr->data = vh;
06542          fr->retries = -1;
06543          res = send_packet(fr);
06544       } else {
06545          /* Mini-frames have no sequence number */
06546          fr->oseqno = -1;
06547          fr->iseqno = -1;
06548          /* Mini frame will do */
06549          mh = (struct ast_iax2_mini_hdr *)(fr->af.data.ptr - sizeof(struct ast_iax2_mini_hdr));
06550          mh->callno = htons(fr->callno);
06551          mh->ts = htons(fr->ts & 0xFFFF);
06552          fr->datalen = fr->af.datalen + sizeof(struct ast_iax2_mini_hdr);
06553          fr->data = mh;
06554          fr->retries = -1;
06555          if (pvt->transferring == TRANSFER_MEDIAPASS)
06556             fr->transfer = 1;
06557          if (ast_test_flag64(pvt, IAX_ENCRYPTED)) {
06558             if (ast_test_flag64(pvt, IAX_KEYPOPULATED)) {
06559                encrypt_frame(&pvt->ecx, (struct ast_iax2_full_hdr *)mh, pvt->semirand, &fr->datalen);
06560             } else
06561                ast_log(LOG_WARNING, "Supposed to send packet encrypted, but no key?\n");
06562          }
06563          res = send_packet(fr);
06564       }
06565    }
06566    return res;
06567 }
06568 
06569 static char *handle_cli_iax2_show_users(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
06570 {
06571    regex_t regexbuf;
06572    int havepattern = 0;
06573 
06574 #define FORMAT "%-15.15s  %-20.20s  %-15.15s  %-15.15s  %-5.5s  %-5.10s\n"
06575 #define FORMAT2 "%-15.15s  %-20.20s  %-15.15d  %-15.15s  %-5.5s  %-5.10s\n"
06576 
06577    struct iax2_user *user = NULL;
06578    char auth[90];
06579    char *pstr = "";
06580    struct ao2_iterator i;
06581 
06582    switch (cmd) {
06583    case CLI_INIT:
06584       e->command = "iax2 show users [like]";
06585       e->usage =
06586          "Usage: iax2 show users [like <pattern>]\n"
06587          "       Lists all known IAX2 users.\n"
06588          "       Optional regular expression pattern is used to filter the user list.\n";
06589       return NULL;
06590    case CLI_GENERATE:
06591       return NULL;
06592    }
06593 
06594    switch (a->argc) {
06595    case 5:
06596       if (!strcasecmp(a->argv[3], "like")) {
06597          if (regcomp(&regexbuf, a->argv[4], REG_EXTENDED | REG_NOSUB))
06598             return CLI_SHOWUSAGE;
06599          havepattern = 1;
06600       } else
06601          return CLI_SHOWUSAGE;
06602    case 3:
06603       break;
06604    default:
06605       return CLI_SHOWUSAGE;
06606    }
06607 
06608    ast_cli(a->fd, FORMAT, "Username", "Secret", "Authen", "Def.Context", "A/C","Codec Pref");
06609    i = ao2_iterator_init(users, 0);
06610    for (; (user = ao2_iterator_next(&i)); user_unref(user)) {
06611       if (havepattern && regexec(&regexbuf, user->name, 0, NULL, 0))
06612          continue;
06613 
06614       if (!ast_strlen_zero(user->secret)) {
06615          ast_copy_string(auth,user->secret, sizeof(auth));
06616       } else if (!ast_strlen_zero(user->inkeys)) {
06617          snprintf(auth, sizeof(auth), "Key: %-15.15s ", user->inkeys);
06618       } else
06619          ast_copy_string(auth, "-no secret-", sizeof(auth));
06620 
06621       if(ast_test_flag64(user, IAX_CODEC_NOCAP))
06622          pstr = "REQ Only";
06623       else if(ast_test_flag64(user, IAX_CODEC_NOPREFS))
06624          pstr = "Disabled";
06625       else
06626          pstr = ast_test_flag64(user, IAX_CODEC_USER_FIRST) ? "Caller" : "Host";
06627 
06628       ast_cli(a->fd, FORMAT2, user->name, auth, user->authmethods, 
06629          user->contexts ? user->contexts->context : DEFAULT_CONTEXT,
06630          user->ha ? "Yes" : "No", pstr);
06631    }
06632    ao2_iterator_destroy(&i);
06633 
06634    if (havepattern)
06635       regfree(&regexbuf);
06636 
06637    return CLI_SUCCESS;
06638 #undef FORMAT
06639 #undef FORMAT2
06640 }
06641 
06642 static int __iax2_show_peers(int fd, int *total, struct mansession *s, const int argc, const char * const argv[])
06643 {
06644    regex_t regexbuf;
06645    int havepattern = 0;
06646    int total_peers = 0;
06647    int online_peers = 0;
06648    int offline_peers = 0;
06649    int unmonitored_peers = 0;
06650    struct ao2_iterator i;
06651 
06652 #define FORMAT2 "%-15.15s  %-15.15s %s  %-15.15s  %-8s  %s %-10s\n"
06653 #define FORMAT "%-15.15s  %-15.15s %s  %-15.15s  %-5d%s  %s %-10s\n"
06654 
06655    struct iax2_peer *peer = NULL;
06656    char name[256];
06657    struct ast_str *encmethods = ast_str_alloca(256);
06658    int registeredonly=0;
06659    char idtext[256] = "";
06660    switch (argc) {
06661    case 6:
06662       if (!strcasecmp(argv[3], "registered"))
06663          registeredonly = 1;
06664       else
06665          return RESULT_SHOWUSAGE;
06666       if (!strcasecmp(argv[4], "like")) {
06667          if (regcomp(&regexbuf, argv[5], REG_EXTENDED | REG_NOSUB))
06668             return RESULT_SHOWUSAGE;
06669          havepattern = 1;
06670       } else
06671          return RESULT_SHOWUSAGE;
06672       break;
06673    case 5:
06674       if (!strcasecmp(argv[3], "like")) {
06675          if (regcomp(&regexbuf, argv[4], REG_EXTENDED | REG_NOSUB))
06676             return RESULT_SHOWUSAGE;
06677          havepattern = 1;
06678       } else
06679          return RESULT_SHOWUSAGE;
06680       break;
06681    case 4:
06682       if (!strcasecmp(argv[3], "registered"))
06683          registeredonly = 1;
06684       else
06685          return RESULT_SHOWUSAGE;
06686       break;
06687    case 3:
06688       break;
06689    default:
06690       return RESULT_SHOWUSAGE;
06691    }
06692 
06693 
06694    if (!s)
06695       ast_cli(fd, FORMAT2, "Name/Username", "Host", "   ", "Mask", "Port", "   ", "Status");
06696 
06697    i = ao2_iterator_init(peers, 0);
06698    for (; (peer = ao2_iterator_next(&i)); peer_unref(peer)) {
06699       char nm[20];
06700       char status[20];
06701       int retstatus;
06702       struct sockaddr_in peer_addr;
06703 
06704       ast_sockaddr_to_sin(&peer->addr, &peer_addr);
06705 
06706       if (registeredonly && !peer_addr.sin_addr.s_addr) {
06707          continue;
06708       }
06709       if (havepattern && regexec(&regexbuf, peer->name, 0, NULL, 0)) {
06710          continue;
06711       }
06712 
06713       if (!ast_strlen_zero(peer->username))
06714          snprintf(name, sizeof(name), "%s/%s", peer->name, peer->username);
06715       else
06716          ast_copy_string(name, peer->name, sizeof(name));
06717 
06718       encmethods_to_str(peer->encmethods, encmethods);
06719       retstatus = peer_status(peer, status, sizeof(status));
06720       if (retstatus > 0)
06721          online_peers++;
06722       else if (!retstatus)
06723          offline_peers++;
06724       else
06725          unmonitored_peers++;
06726 
06727       ast_copy_string(nm, ast_inet_ntoa(peer->mask), sizeof(nm));
06728 
06729       if (s) {
06730          astman_append(s,
06731             "Event: PeerEntry\r\n%s"
06732             "Channeltype: IAX2\r\n"
06733             "ObjectName: %s\r\n"
06734             "ChanObjectType: peer\r\n"
06735             "IPaddress: %s\r\n"
06736             "IPport: %d\r\n"
06737             "Dynamic: %s\r\n"
06738             "Trunk: %s\r\n"
06739             "Encryption: %s\r\n"
06740             "Status: %s\r\n\r\n",
06741             idtext,
06742             name,
06743             ast_sockaddr_stringify_addr(&peer->addr),
06744             ast_sockaddr_port(&peer->addr),
06745             ast_test_flag64(peer, IAX_DYNAMIC) ? "yes" : "no",
06746             ast_test_flag64(peer, IAX_TRUNK) ? "yes" : "no",
06747             peer->encmethods ? ast_str_buffer(encmethods) : "no",
06748             status);
06749       } else {
06750          ast_cli(fd, FORMAT, name,
06751             ast_sockaddr_stringify_addr(&peer->addr),
06752             ast_test_flag64(peer, IAX_DYNAMIC) ? "(D)" : "(S)",
06753             nm,
06754             ast_sockaddr_port(&peer->addr),
06755             ast_test_flag64(peer, IAX_TRUNK) ? "(T)" : "   ",
06756             peer->encmethods ? "(E)" : "   ",
06757             status);
06758       }
06759       total_peers++;
06760    }
06761    ao2_iterator_destroy(&i);
06762 
06763    if (!s)
06764       ast_cli(fd,"%d iax2 peers [%d online, %d offline, %d unmonitored]\n",
06765          total_peers, online_peers, offline_peers, unmonitored_peers);
06766 
06767    if (havepattern)
06768       regfree(&regexbuf);
06769 
06770    if (total)
06771       *total = total_peers;
06772 
06773    return RESULT_SUCCESS;
06774 #undef FORMAT
06775 #undef FORMAT2
06776 }
06777 
06778 static char *handle_cli_iax2_show_threads(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
06779 {
06780    struct iax2_thread *thread = NULL;
06781    time_t t;
06782    int threadcount = 0, dynamiccount = 0;
06783    char type;
06784 
06785    switch (cmd) {
06786    case CLI_INIT:
06787       e->command = "iax2 show threads";
06788       e->usage =
06789          "Usage: iax2 show threads\n"
06790          "       Lists status of IAX helper threads\n";
06791       return NULL;
06792    case CLI_GENERATE:
06793       return NULL;
06794    }
06795    if (a->argc != 3)
06796       return CLI_SHOWUSAGE;
06797       
06798    ast_cli(a->fd, "IAX2 Thread Information\n");
06799    time(&t);
06800    ast_cli(a->fd, "Idle Threads:\n");
06801    AST_LIST_LOCK(&idle_list);
06802    AST_LIST_TRAVERSE(&idle_list, thread, list) {
06803 #ifdef DEBUG_SCHED_MULTITHREAD
06804       ast_cli(a->fd, "Thread %d: state=%d, update=%d, actions=%d, func='%s'\n", 
06805          thread->threadnum, thread->iostate, (int)(t - thread->checktime), thread->actions, thread->curfunc);
06806 #else
06807       ast_cli(a->fd, "Thread %d: state=%d, update=%d, actions=%d\n", 
06808          thread->threadnum, thread->iostate, (int)(t - thread->checktime), thread->actions);
06809 #endif
06810       threadcount++;
06811    }
06812    AST_LIST_UNLOCK(&idle_list);
06813    ast_cli(a->fd, "Active Threads:\n");
06814    AST_LIST_LOCK(&active_list);
06815    AST_LIST_TRAVERSE(&active_list, thread, list) {
06816       if (thread->type == IAX_THREAD_TYPE_DYNAMIC)
06817          type = 'D';
06818       else
06819          type = 'P';
06820 #ifdef DEBUG_SCHED_MULTITHREAD
06821       ast_cli(a->fd, "Thread %c%d: state=%d, update=%d, actions=%d, func='%s'\n", 
06822          type, thread->threadnum, thread->iostate, (int)(t - thread->checktime), thread->actions, thread->curfunc);
06823 #else
06824       ast_cli(a->fd, "Thread %c%d: state=%d, update=%d, actions=%d\n", 
06825          type, thread->threadnum, thread->iostate, (int)(t - thread->checktime), thread->actions);
06826 #endif
06827       threadcount++;
06828    }
06829    AST_LIST_UNLOCK(&active_list);
06830    ast_cli(a->fd, "Dynamic Threads:\n");
06831    AST_LIST_LOCK(&dynamic_list);
06832    AST_LIST_TRAVERSE(&dynamic_list, thread, list) {
06833 #ifdef DEBUG_SCHED_MULTITHREAD
06834       ast_cli(a->fd, "Thread %d: state=%d, update=%d, actions=%d, func='%s'\n",
06835          thread->threadnum, thread->iostate, (int)(t - thread->checktime), thread->actions, thread->curfunc);
06836 #else
06837       ast_cli(a->fd, "Thread %d: state=%d, update=%d, actions=%d\n",
06838          thread->threadnum, thread->iostate, (int)(t - thread->checktime), thread->actions);
06839 #endif
06840       dynamiccount++;
06841    }
06842    AST_LIST_UNLOCK(&dynamic_list);
06843    ast_cli(a->fd, "%d of %d threads accounted for with %d dynamic threads\n", threadcount, iaxthreadcount, dynamiccount);
06844    return CLI_SUCCESS;
06845 }
06846 
06847 static char *handle_cli_iax2_unregister(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
06848 {
06849    struct iax2_peer *p;
06850 
06851    switch (cmd) {
06852    case CLI_INIT:
06853       e->command = "iax2 unregister";
06854       e->usage =
06855          "Usage: iax2 unregister <peername>\n"
06856          "       Unregister (force expiration) an IAX2 peer from the registry.\n";
06857       return NULL;
06858    case CLI_GENERATE:
06859       return complete_iax2_unregister(a->line, a->word, a->pos, a->n);
06860    }
06861 
06862    if (a->argc != 3)
06863       return CLI_SHOWUSAGE;
06864 
06865    p = find_peer(a->argv[2], 1);
06866    if (p) {
06867       if (p->expire > 0) {
06868          struct iax2_peer tmp_peer = {
06869             .name = a->argv[2],
06870          };
06871          struct iax2_peer *peer;
06872 
06873          peer = ao2_find(peers, &tmp_peer, OBJ_POINTER);
06874          if (peer) {
06875             expire_registry(peer_ref(peer)); /* will release its own reference when done */
06876             peer_unref(peer); /* ref from ao2_find() */
06877             ast_cli(a->fd, "Peer %s unregistered\n", a->argv[2]);
06878          } else {
06879             ast_cli(a->fd, "Peer %s not found\n", a->argv[2]);
06880          }
06881       } else {
06882          ast_cli(a->fd, "Peer %s not registered\n", a->argv[2]);
06883       }
06884    } else {
06885       ast_cli(a->fd, "Peer unknown: %s. Not unregistered\n", a->argv[2]);
06886    }
06887    return CLI_SUCCESS;
06888 }
06889 
06890 static char *complete_iax2_unregister(const char *line, const char *word, int pos, int state)
06891 {
06892    int which = 0;
06893    struct iax2_peer *p = NULL;
06894    char *res = NULL;
06895    int wordlen = strlen(word);
06896 
06897    /* 0 - iax2; 1 - unregister; 2 - <peername> */
06898    if (pos == 2) {
06899       struct ao2_iterator i = ao2_iterator_init(peers, 0);
06900       while ((p = ao2_iterator_next(&i))) {
06901          if (!strncasecmp(p->name, word, wordlen) && 
06902             ++which > state && p->expire > 0) {
06903             res = ast_strdup(p->name);
06904             peer_unref(p);
06905             break;
06906          }
06907          peer_unref(p);
06908       }
06909       ao2_iterator_destroy(&i);
06910    }
06911 
06912    return res;
06913 }
06914 
06915 static char *handle_cli_iax2_show_peers(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
06916 {
06917    switch (cmd) {
06918    case CLI_INIT:
06919       e->command = "iax2 show peers";
06920       e->usage =
06921          "Usage: iax2 show peers [registered] [like <pattern>]\n"
06922          "       Lists all known IAX2 peers.\n"
06923          "       Optional 'registered' argument lists only peers with known addresses.\n"
06924          "       Optional regular expression pattern is used to filter the peer list.\n";
06925       return NULL;
06926    case CLI_GENERATE:
06927       return NULL;
06928    }
06929 
06930    switch (__iax2_show_peers(a->fd, NULL, NULL, a->argc, a->argv)) {
06931    case RESULT_SHOWUSAGE:
06932       return CLI_SHOWUSAGE;
06933    case RESULT_FAILURE:
06934       return CLI_FAILURE;
06935    default:
06936       return CLI_SUCCESS;
06937    }
06938 }
06939 
06940 static int manager_iax2_show_netstats(struct mansession *s, const struct message *m)
06941 {
06942    ast_cli_netstats(s, -1, 0);
06943    astman_append(s, "\r\n");
06944    return RESULT_SUCCESS;
06945 }
06946 
06947 static char *handle_cli_iax2_show_firmware(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
06948 {
06949    struct iax_firmware *cur = NULL;
06950 
06951    switch (cmd) {
06952    case CLI_INIT:
06953       e->command = "iax2 show firmware";
06954       e->usage =
06955          "Usage: iax2 show firmware\n"
06956          "       Lists all known IAX firmware images.\n";
06957       return NULL;
06958    case CLI_GENERATE:
06959       return NULL;
06960    }
06961 
06962    if (a->argc != 3 && a->argc != 4)
06963       return CLI_SHOWUSAGE;
06964 
06965    ast_cli(a->fd, "%-15.15s  %-15.15s %-15.15s\n", "Device", "Version", "Size");
06966    AST_LIST_LOCK(&firmwares);
06967    AST_LIST_TRAVERSE(&firmwares, cur, list) {
06968       if ((a->argc == 3) || (!strcasecmp(a->argv[3], (char *) cur->fwh->devname)))  {
06969          ast_cli(a->fd, "%-15.15s  %-15d %-15d\n", cur->fwh->devname, 
06970             ntohs(cur->fwh->version), (int)ntohl(cur->fwh->datalen));
06971       }
06972    }
06973    AST_LIST_UNLOCK(&firmwares);
06974 
06975    return CLI_SUCCESS;
06976 }
06977 
06978 /*! \brief callback to display iax peers in manager */
06979 static int manager_iax2_show_peers(struct mansession *s, const struct message *m)
06980 {
06981    static const char * const a[] = { "iax2", "show", "peers" };
06982    const char *id = astman_get_header(m,"ActionID");
06983    char idtext[256] = "";
06984    int total = 0;
06985 
06986    if (!ast_strlen_zero(id))
06987       snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
06988 
06989    astman_send_listack(s, m, "Peer status list will follow", "start");
06990         /* List the peers in separate manager events */
06991    __iax2_show_peers(-1, &total, s, 3, a);
06992         /* Send final confirmation */
06993         astman_append(s,
06994         "Event: PeerlistComplete\r\n"
06995         "EventList: Complete\r\n"
06996         "ListItems: %d\r\n"
06997         "%s"
06998         "\r\n", total, idtext);
06999         return 0;
07000 }
07001 
07002 /*! \brief callback to display iax peers in manager format */
07003 static int manager_iax2_show_peer_list(struct mansession *s, const struct message *m)
07004 {
07005    struct iax2_peer *peer = NULL;
07006    int peer_count = 0;
07007    char nm[20];
07008    char status[20];
07009    const char *id = astman_get_header(m,"ActionID");
07010    char idtext[256] = "";
07011    struct ast_str *encmethods = ast_str_alloca(256);
07012    struct ao2_iterator i;
07013 
07014    if (!ast_strlen_zero(id))
07015       snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
07016 
07017    astman_append(s, "Response: Success\r\n%sMessage: IAX Peer status list will follow\r\n\r\n", idtext);
07018 
07019 
07020    i = ao2_iterator_init(peers, 0);
07021    for (; (peer = ao2_iterator_next(&i)); peer_unref(peer)) {
07022       encmethods_to_str(peer->encmethods, encmethods);
07023       astman_append(s, "Event: PeerEntry\r\n%sChanneltype: IAX\r\n", idtext);
07024       if (!ast_strlen_zero(peer->username)) {
07025          astman_append(s, "ObjectName: %s\r\nObjectUsername: %s\r\n", peer->name, peer->username);
07026       } else {
07027          astman_append(s, "ObjectName: %s\r\n", peer->name);
07028       }
07029       astman_append(s, "ChanObjectType: peer\r\n");
07030       astman_append(s, "IPaddress: %s\r\n", ast_sockaddr_stringify_addr(&peer->addr));
07031       ast_copy_string(nm, ast_inet_ntoa(peer->mask), sizeof(nm));
07032       astman_append(s, "Mask: %s\r\n", nm);
07033       astman_append(s, "Port: %d\r\n", ast_sockaddr_port(&peer->addr));
07034       astman_append(s, "Dynamic: %s\r\n", ast_test_flag64(peer, IAX_DYNAMIC) ? "Yes" : "No");
07035       astman_append(s, "Trunk: %s\r\n", ast_test_flag64(peer, IAX_TRUNK) ? "Yes" : "No");
07036       astman_append(s, "Encryption: %s\r\n", peer->encmethods ? ast_str_buffer(encmethods) : "No");
07037       peer_status(peer, status, sizeof(status));
07038       astman_append(s, "Status: %s\r\n\r\n", status);
07039       peer_count++;
07040    }
07041    ao2_iterator_destroy(&i);
07042 
07043    astman_append(s, "Event: PeerlistComplete\r\n%sListItems: %d\r\n\r\n", idtext, peer_count);
07044    return RESULT_SUCCESS;
07045 }
07046 
07047 
07048 static char *regstate2str(int regstate)
07049 {
07050    switch(regstate) {
07051    case REG_STATE_UNREGISTERED:
07052       return "Unregistered";
07053    case REG_STATE_REGSENT:
07054       return "Request Sent";
07055    case REG_STATE_AUTHSENT:
07056       return "Auth. Sent";
07057    case REG_STATE_REGISTERED:
07058       return "Registered";
07059    case REG_STATE_REJECTED:
07060       return "Rejected";
07061    case REG_STATE_TIMEOUT:
07062       return "Timeout";
07063    case REG_STATE_NOAUTH:
07064       return "No Authentication";
07065    default:
07066       return "Unknown";
07067    }
07068 }
07069 
07070 static char *handle_cli_iax2_show_registry(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
07071 {
07072 #define FORMAT2 "%-20.20s  %-6.6s  %-10.10s  %-20.20s %8.8s  %s\n"
07073 #define FORMAT  "%-20.20s  %-6.6s  %-10.10s  %-20.20s %8d  %s\n"
07074    struct iax2_registry *reg = NULL;
07075    char host[80];
07076    char perceived[80];
07077    int counter = 0;
07078 
07079    switch (cmd) {
07080    case CLI_INIT:
07081       e->command = "iax2 show registry";
07082       e->usage =
07083          "Usage: iax2 show registry\n"
07084          "       Lists all registration requests and status.\n";
07085       return NULL;
07086    case CLI_GENERATE:
07087       return NULL;
07088    }
07089    if (a->argc != 3)
07090       return CLI_SHOWUSAGE;
07091    ast_cli(a->fd, FORMAT2, "Host", "dnsmgr", "Username", "Perceived", "Refresh", "State");
07092    AST_LIST_LOCK(&registrations);
07093    AST_LIST_TRAVERSE(&registrations, reg, entry) {
07094       snprintf(host, sizeof(host), "%s", ast_sockaddr_stringify(&reg->addr));
07095       if (reg->us.sin_addr.s_addr) 
07096          snprintf(perceived, sizeof(perceived), "%s:%d", ast_inet_ntoa(reg->us.sin_addr), ntohs(reg->us.sin_port));
07097       else
07098          ast_copy_string(perceived, "<Unregistered>", sizeof(perceived));
07099       ast_cli(a->fd, FORMAT, host, 
07100                (reg->dnsmgr) ? "Y" : "N", 
07101                reg->username, perceived, reg->refresh, regstate2str(reg->regstate));
07102       counter++;
07103    }
07104    AST_LIST_UNLOCK(&registrations);
07105    ast_cli(a->fd, "%d IAX2 registrations.\n", counter);
07106    return CLI_SUCCESS;
07107 #undef FORMAT
07108 #undef FORMAT2
07109 }
07110 
07111 static int manager_iax2_show_registry(struct mansession *s, const struct message *m)
07112 {
07113    const char *id = astman_get_header(m, "ActionID");
07114    struct iax2_registry *reg = NULL;
07115    char idtext[256] = "";
07116    char host[80] = "";
07117    char perceived[80] = "";
07118    int total = 0;
07119 
07120    if (!ast_strlen_zero(id))
07121       snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
07122 
07123    astman_send_listack(s, m, "Registrations will follow", "start");
07124 
07125    AST_LIST_LOCK(&registrations);
07126    AST_LIST_TRAVERSE(&registrations, reg, entry) {
07127       snprintf(host, sizeof(host), "%s", ast_sockaddr_stringify(&reg->addr));
07128       
07129       if (reg->us.sin_addr.s_addr) {
07130          snprintf(perceived, sizeof(perceived), "%s:%d", ast_inet_ntoa(reg->us.sin_addr), ntohs(reg->us.sin_port));
07131       } else {
07132          ast_copy_string(perceived, "<Unregistered>", sizeof(perceived));
07133       }
07134       
07135       astman_append(s,
07136          "Event: RegistryEntry\r\n"
07137          "%s"
07138          "Host: %s\r\n"
07139          "DNSmanager: %s\r\n"
07140          "Username: %s\r\n"
07141          "Perceived: %s\r\n"
07142          "Refresh: %d\r\n"
07143          "State: %s\r\n"
07144          "\r\n", idtext, host, (reg->dnsmgr) ? "Y" : "N", reg->username, perceived, 
07145          reg->refresh, regstate2str(reg->regstate));
07146 
07147       total++;
07148    }
07149    AST_LIST_UNLOCK(&registrations);
07150 
07151    astman_append(s,
07152       "Event: RegistrationsComplete\r\n"
07153       "EventList: Complete\r\n"
07154       "ListItems: %d\r\n"
07155       "%s"
07156       "\r\n", total, idtext);
07157    
07158    return 0;
07159 }
07160 
07161 static char *handle_cli_iax2_show_channels(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
07162 {
07163 #define FORMAT2 "%-20.20s  %-15.15s  %-10.10s  %-11.11s  %-11.11s  %-7.7s  %-6.6s  %-6.6s  %s  %s  %9s\n"
07164 #define FORMAT  "%-20.20s  %-15.15s  %-10.10s  %5.5d/%5.5d  %5.5d/%5.5d  %-5.5dms  %-4.4dms  %-4.4dms  %-6.6s  %s%s  %3s%s\n"
07165 #define FORMATB "%-20.20s  %-15.15s  %-10.10s  %5.5d/%5.5d  %5.5d/%5.5d  [Native Bridged to ID=%5.5d]\n"
07166    int x;
07167    int numchans = 0;
07168    char first_message[10] = { 0, };
07169    char last_message[10] = { 0, };
07170 
07171    switch (cmd) {
07172    case CLI_INIT:
07173       e->command = "iax2 show channels";
07174       e->usage =
07175          "Usage: iax2 show channels\n"
07176          "       Lists all currently active IAX channels.\n";
07177       return NULL;
07178    case CLI_GENERATE:
07179       return NULL;
07180    }
07181 
07182    if (a->argc != 3)
07183       return CLI_SHOWUSAGE;
07184    ast_cli(a->fd, FORMAT2, "Channel", "Peer", "Username", "ID (Lo/Rem)", "Seq (Tx/Rx)", "Lag", "Jitter", "JitBuf", "Format", "FirstMsg", "LastMsg");
07185    for (x = 0; x < ARRAY_LEN(iaxs); x++) {
07186       ast_mutex_lock(&iaxsl[x]);
07187       if (iaxs[x]) {
07188          int lag, jitter, localdelay;
07189          jb_info jbinfo;
07190          if (ast_test_flag64(iaxs[x], IAX_USEJITTERBUF)) {
07191             jb_getinfo(iaxs[x]->jb, &jbinfo);
07192             jitter = jbinfo.jitter;
07193             localdelay = jbinfo.current - jbinfo.min;
07194          } else {
07195             jitter = -1;
07196             localdelay = 0;
07197          }
07198 
07199          iax_frame_subclass2str(iaxs[x]->first_iax_message & ~MARK_IAX_SUBCLASS_TX, first_message, sizeof(first_message));
07200          iax_frame_subclass2str(iaxs[x]->last_iax_message & ~MARK_IAX_SUBCLASS_TX, last_message, sizeof(last_message));
07201          lag = iaxs[x]->remote_rr.delay;
07202          ast_cli(a->fd, FORMAT,
07203             iaxs[x]->owner ? iaxs[x]->owner->name : "(None)",
07204             ast_inet_ntoa(iaxs[x]->addr.sin_addr),
07205             S_OR(iaxs[x]->username, "(None)"),
07206             iaxs[x]->callno, iaxs[x]->peercallno,
07207             iaxs[x]->oseqno, iaxs[x]->iseqno,
07208             lag,
07209             jitter,
07210             localdelay,
07211             ast_getformatname(iaxs[x]->voiceformat),
07212             (iaxs[x]->first_iax_message & MARK_IAX_SUBCLASS_TX) ? "Tx:" : "Rx:",
07213             first_message,
07214             (iaxs[x]->last_iax_message & MARK_IAX_SUBCLASS_TX) ? "Tx:" : "Rx:",
07215             last_message);
07216          numchans++;
07217       }
07218       ast_mutex_unlock(&iaxsl[x]);
07219    }
07220    ast_cli(a->fd, "%d active IAX channel%s\n", numchans, (numchans != 1) ? "s" : "");
07221    return CLI_SUCCESS;
07222 #undef FORMAT
07223 #undef FORMAT2
07224 #undef FORMATB
07225 }
07226 
07227 static int ast_cli_netstats(struct mansession *s, int fd, int limit_fmt)
07228 {
07229    int x;
07230    int numchans = 0;
07231    char first_message[10] = { 0, };
07232    char last_message[10] = { 0, };
07233 #define ACN_FORMAT1 "%-20.25s %4d %4d %4d %5d %3d %5d %4d %6d %4d %4d %5d %3d %5d %4d %6d %s%s %4s%s\n"
07234 #define ACN_FORMAT2 "%s %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %s%s %s%s\n"
07235    for (x = 0; x < ARRAY_LEN(iaxs); x++) {
07236       ast_mutex_lock(&iaxsl[x]);
07237       if (iaxs[x]) {
07238          int localjitter, localdelay, locallost, locallosspct, localdropped, localooo;
07239          jb_info jbinfo;
07240          iax_frame_subclass2str(iaxs[x]->first_iax_message & ~MARK_IAX_SUBCLASS_TX, first_message, sizeof(first_message));
07241          iax_frame_subclass2str(iaxs[x]->last_iax_message & ~MARK_IAX_SUBCLASS_TX, last_message, sizeof(last_message));
07242 
07243          if(ast_test_flag64(iaxs[x], IAX_USEJITTERBUF)) {
07244             jb_getinfo(iaxs[x]->jb, &jbinfo);
07245             localjitter = jbinfo.jitter;
07246             localdelay = jbinfo.current - jbinfo.min;
07247             locallost = jbinfo.frames_lost;
07248             locallosspct = jbinfo.losspct/1000;
07249             localdropped = jbinfo.frames_dropped;
07250             localooo = jbinfo.frames_ooo;
07251          } else {
07252             localjitter = -1;
07253             localdelay = 0;
07254             locallost = -1;
07255             locallosspct = -1;
07256             localdropped = 0;
07257             localooo = -1;
07258          }
07259          if (s)
07260             astman_append(s, limit_fmt ? ACN_FORMAT1 : ACN_FORMAT2,
07261                iaxs[x]->owner ? iaxs[x]->owner->name : "(None)",
07262                iaxs[x]->pingtime,
07263                localjitter,
07264                localdelay,
07265                locallost,
07266                locallosspct,
07267                localdropped,
07268                localooo,
07269                iaxs[x]->frames_received/1000,
07270                iaxs[x]->remote_rr.jitter,
07271                iaxs[x]->remote_rr.delay,
07272                iaxs[x]->remote_rr.losscnt,
07273                iaxs[x]->remote_rr.losspct,
07274                iaxs[x]->remote_rr.dropped,
07275                iaxs[x]->remote_rr.ooo,
07276                iaxs[x]->remote_rr.packets/1000,
07277                (iaxs[x]->first_iax_message & MARK_IAX_SUBCLASS_TX) ? "Tx:" : "Rx:",
07278                first_message,
07279                (iaxs[x]->last_iax_message & MARK_IAX_SUBCLASS_TX) ? "Tx:" : "Rx:",
07280                last_message);
07281          else
07282             ast_cli(fd, limit_fmt ? ACN_FORMAT1 : ACN_FORMAT2,
07283                iaxs[x]->owner ? iaxs[x]->owner->name : "(None)",
07284                iaxs[x]->pingtime,
07285                localjitter,
07286                localdelay,
07287                locallost,
07288                locallosspct,
07289                localdropped,
07290                localooo,
07291                iaxs[x]->frames_received/1000,
07292                iaxs[x]->remote_rr.jitter,
07293                iaxs[x]->remote_rr.delay,
07294                iaxs[x]->remote_rr.losscnt,
07295                iaxs[x]->remote_rr.losspct,
07296                iaxs[x]->remote_rr.dropped,
07297                iaxs[x]->remote_rr.ooo,
07298                iaxs[x]->remote_rr.packets/1000,
07299                (iaxs[x]->first_iax_message & MARK_IAX_SUBCLASS_TX) ? "Tx:" : "Rx:",
07300                first_message,
07301                (iaxs[x]->last_iax_message & MARK_IAX_SUBCLASS_TX) ? "Tx:" : "Rx:",
07302                last_message);
07303          numchans++;
07304       }
07305       ast_mutex_unlock(&iaxsl[x]);
07306    }
07307 
07308    return numchans;
07309 }
07310 
07311 static char *handle_cli_iax2_show_netstats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
07312 {
07313    int numchans = 0;
07314 
07315    switch (cmd) {
07316    case CLI_INIT:
07317       e->command = "iax2 show netstats";
07318       e->usage =
07319          "Usage: iax2 show netstats\n"
07320          "       Lists network status for all currently active IAX channels.\n";
07321       return NULL;
07322    case CLI_GENERATE:
07323       return NULL;
07324    }
07325    if (a->argc != 3)
07326       return CLI_SHOWUSAGE;
07327    ast_cli(a->fd, "                           -------- LOCAL ---------------------  -------- REMOTE --------------------\n");
07328    ast_cli(a->fd, "Channel               RTT  Jit  Del  Lost   %%  Drop  OOO  Kpkts  Jit  Del  Lost   %%  Drop  OOO  Kpkts FirstMsg    LastMsg\n");
07329    numchans = ast_cli_netstats(NULL, a->fd, 1);
07330    ast_cli(a->fd, "%d active IAX channel%s\n", numchans, (numchans != 1) ? "s" : "");
07331    return CLI_SUCCESS;
07332 }
07333 
07334 static char *handle_cli_iax2_set_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
07335 {
07336    switch (cmd) {
07337    case CLI_INIT:
07338       e->command = "iax2 set debug {on|off|peer}";
07339       e->usage =
07340          "Usage: iax2 set debug {on|off|peer peername}\n"
07341          "       Enables/Disables dumping of IAX packets for debugging purposes.\n";
07342       return NULL;
07343    case CLI_GENERATE:
07344       if (a->pos == 4 && !strcasecmp(a->argv[3], "peer"))
07345          return complete_iax2_peers(a->line, a->word, a->pos, a->n, 0);
07346       return NULL;
07347    }
07348 
07349    if (a->argc < e->args  || a->argc > e->args + 1)
07350       return CLI_SHOWUSAGE;
07351 
07352    if (!strcasecmp(a->argv[3], "peer")) {
07353       struct iax2_peer *peer;
07354       struct sockaddr_in peer_addr;
07355 
07356 
07357       if (a->argc != e->args + 1)
07358          return CLI_SHOWUSAGE;
07359 
07360       peer = find_peer(a->argv[4], 1);
07361 
07362       if (!peer) {
07363          ast_cli(a->fd, "IAX2 peer '%s' does not exist\n", a->argv[e->args-1]);
07364          return CLI_FAILURE;
07365       }
07366 
07367       ast_sockaddr_to_sin(&peer->addr, &peer_addr);
07368 
07369       debugaddr.sin_addr = peer_addr.sin_addr;
07370       debugaddr.sin_port = peer_addr.sin_port;
07371 
07372       ast_cli(a->fd, "IAX2 Debugging Enabled for IP: %s:%d\n",
07373          ast_inet_ntoa(debugaddr.sin_addr), ntohs(debugaddr.sin_port));
07374 
07375       ao2_ref(peer, -1);
07376    } else if (!strncasecmp(a->argv[3], "on", 2)) {
07377       iaxdebug = 1;
07378       ast_cli(a->fd, "IAX2 Debugging Enabled\n");
07379    } else {
07380       iaxdebug = 0;
07381       memset(&debugaddr, 0, sizeof(debugaddr));
07382       ast_cli(a->fd, "IAX2 Debugging Disabled\n");
07383    }
07384    return CLI_SUCCESS;
07385 }
07386 
07387 static char *handle_cli_iax2_set_debug_trunk(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
07388 {
07389    switch (cmd) {
07390    case CLI_INIT:
07391       e->command = "iax2 set debug trunk {on|off}";
07392       e->usage =
07393          "Usage: iax2 set debug trunk {on|off}\n"
07394          "       Enables/Disables debugging of IAX trunking\n";
07395       return NULL;
07396    case CLI_GENERATE:
07397       return NULL;
07398    }
07399 
07400    if (a->argc != e->args)
07401       return CLI_SHOWUSAGE;
07402 
07403    if (!strncasecmp(a->argv[e->args - 1], "on", 2)) {
07404       iaxtrunkdebug = 1;
07405       ast_cli(a->fd, "IAX2 Trunk Debugging Enabled\n");
07406    } else {
07407       iaxtrunkdebug = 0;
07408       ast_cli(a->fd, "IAX2 Trunk Debugging Disabled\n");
07409    }
07410    return CLI_SUCCESS;
07411 }
07412 
07413 static char *handle_cli_iax2_set_debug_jb(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
07414 {
07415    switch (cmd) {
07416    case CLI_INIT:
07417       e->command = "iax2 set debug jb {on|off}";
07418       e->usage =
07419          "Usage: iax2 set debug jb {on|off}\n"
07420          "       Enables/Disables jitterbuffer debugging information\n";
07421       return NULL;
07422    case CLI_GENERATE:
07423       return NULL;
07424    }
07425 
07426    if (a->argc != e->args)
07427       return CLI_SHOWUSAGE;
07428    
07429    if (!strncasecmp(a->argv[e->args -1], "on", 2)) {
07430       jb_setoutput(jb_error_output, jb_warning_output, jb_debug_output);
07431       ast_cli(a->fd, "IAX2 Jitterbuffer Debugging Enabled\n");
07432    } else {
07433       jb_setoutput(jb_error_output, jb_warning_output, NULL);
07434       ast_cli(a->fd, "IAX2 Jitterbuffer Debugging Disabled\n");
07435    }
07436    return CLI_SUCCESS;
07437 }
07438 
07439 static int iax2_write(struct ast_channel *c, struct ast_frame *f)
07440 {
07441    unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
07442    int res = -1;
07443    ast_mutex_lock(&iaxsl[callno]);
07444    if (iaxs[callno]) {
07445    /* If there's an outstanding error, return failure now */
07446       if (!iaxs[callno]->error) {
07447          if (ast_test_flag64(iaxs[callno], IAX_ALREADYGONE))
07448             res = 0;
07449             /* Don't waste bandwidth sending null frames */
07450          else if (f->frametype == AST_FRAME_NULL)
07451             res = 0;
07452          else if ((f->frametype == AST_FRAME_VOICE) && ast_test_flag64(iaxs[callno], IAX_QUELCH))
07453             res = 0;
07454          else if (!ast_test_flag(&iaxs[callno]->state, IAX_STATE_STARTED))
07455             res = 0;
07456          else
07457          /* Simple, just queue for transmission */
07458             res = iax2_send(iaxs[callno], f, 0, -1, 0, 0, 0);
07459       } else {
07460          ast_debug(1, "Write error: %s\n", strerror(errno));
07461       }
07462    }
07463    /* If it's already gone, just return */
07464    ast_mutex_unlock(&iaxsl[callno]);
07465    return res;
07466 }
07467 
07468 static int __send_command(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, const unsigned char *data, int datalen, int seqno, 
07469       int now, int transfer, int final)
07470 {
07471    struct ast_frame f = { 0, };
07472    int res = 0;
07473 
07474    f.frametype = type;
07475    f.subclass.integer = command;
07476    f.datalen = datalen;
07477    f.src = __FUNCTION__;
07478    f.data.ptr = (void *) data;
07479 
07480    if ((res = queue_signalling(i, &f)) <= 0) {
07481       return res;
07482    }
07483 
07484    return iax2_send(i, &f, ts, seqno, now, transfer, final);
07485 }
07486 
07487 static int send_command(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, const unsigned char *data, int datalen, int seqno)
07488 {
07489    return __send_command(i, type, command, ts, data, datalen, seqno, 0, 0, 0);
07490 }
07491 
07492 static int send_command_locked(unsigned short callno, char type, int command, unsigned int ts, const unsigned char *data, int datalen, int seqno)
07493 {
07494    int res;
07495    ast_mutex_lock(&iaxsl[callno]);
07496    res = send_command(iaxs[callno], type, command, ts, data, datalen, seqno);
07497    ast_mutex_unlock(&iaxsl[callno]);
07498    return res;
07499 }
07500 
07501 /*!
07502  * \note Since this function calls iax2_predestroy() -> iax2_queue_hangup(),
07503  *       the pvt struct for the given call number may disappear during its 
07504  *       execution.
07505  */
07506 static int send_command_final(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, const unsigned char *data, int datalen, int seqno)
07507 {
07508    int call_num = i->callno;
07509    /* It is assumed that the callno has already been locked */
07510    iax2_predestroy(i->callno);
07511    if (!iaxs[call_num])
07512       return -1;
07513    return __send_command(i, type, command, ts, data, datalen, seqno, 0, 0, 1);
07514 }
07515 
07516 static int send_command_immediate(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, const unsigned char *data, int datalen, int seqno)
07517 {
07518    return __send_command(i, type, command, ts, data, datalen, seqno, 1, 0, 0);
07519 }
07520 
07521 static int send_command_transfer(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, const unsigned char *data, int datalen)
07522 {
07523    return __send_command(i, type, command, ts, data, datalen, 0, 0, 1, 0);
07524 }
07525 
07526 static int apply_context(struct iax2_context *con, const char *context)
07527 {
07528    while(con) {
07529       if (!strcmp(con->context, context) || !strcmp(con->context, "*"))
07530          return -1;
07531       con = con->next;
07532    }
07533    return 0;
07534 }
07535 
07536 
07537 static int check_access(int callno, struct sockaddr_in *sin, struct iax_ies *ies)
07538 {
07539    /* Start pessimistic */
07540    int res = -1;
07541    int version = 2;
07542    struct iax2_user *user = NULL, *best = NULL;
07543    int bestscore = 0;
07544    int gotcapability = 0;
07545    struct ast_variable *v = NULL, *tmpvar = NULL;
07546    struct ao2_iterator i;
07547    struct ast_sockaddr addr;
07548 
07549    if (!iaxs[callno])
07550       return res;
07551    if (ies->called_number)
07552       ast_string_field_set(iaxs[callno], exten, ies->called_number);
07553    if (ies->calling_number) {
07554       if (ast_test_flag64(&globalflags, IAX_SHRINKCALLERID)) { 
07555          ast_shrink_phone_number(ies->calling_number);
07556       }
07557       ast_string_field_set(iaxs[callno], cid_num, ies->calling_number);
07558    }
07559    if (ies->calling_name)
07560       ast_string_field_set(iaxs[callno], cid_name, ies->calling_name);
07561    if (ies->calling_ani)
07562       ast_string_field_set(iaxs[callno], ani, ies->calling_ani);
07563    if (ies->dnid)
07564       ast_string_field_set(iaxs[callno], dnid, ies->dnid);
07565    if (ies->rdnis)
07566       ast_string_field_set(iaxs[callno], rdnis, ies->rdnis);
07567    if (ies->called_context)
07568       ast_string_field_set(iaxs[callno], context, ies->called_context);
07569    if (ies->language)
07570       ast_string_field_set(iaxs[callno], language, ies->language);
07571    if (ies->username)
07572       ast_string_field_set(iaxs[callno], username, ies->username);
07573    if (ies->calling_ton > -1)
07574       iaxs[callno]->calling_ton = ies->calling_ton;
07575    if (ies->calling_tns > -1)
07576       iaxs[callno]->calling_tns = ies->calling_tns;
07577    if (ies->calling_pres > -1)
07578       iaxs[callno]->calling_pres = ies->calling_pres;
07579    if (ies->format)
07580       iaxs[callno]->peerformat = ies->format;
07581    if (ies->adsicpe)
07582       iaxs[callno]->peeradsicpe = ies->adsicpe;
07583    if (ies->capability) {
07584       gotcapability = 1;
07585       iaxs[callno]->peercapability = ies->capability;
07586    } 
07587    if (ies->version)
07588       version = ies->version;
07589 
07590    /* Use provided preferences until told otherwise for actual preferences */
07591    if (ies->codec_prefs) {
07592       ast_codec_pref_convert(&iaxs[callno]->rprefs, ies->codec_prefs, 32, 0);
07593       ast_codec_pref_convert(&iaxs[callno]->prefs, ies->codec_prefs, 32, 0);
07594    }
07595 
07596    if (!gotcapability) 
07597       iaxs[callno]->peercapability = iaxs[callno]->peerformat;
07598    if (version > IAX_PROTO_VERSION) {
07599       ast_log(LOG_WARNING, "Peer '%s' has too new a protocol version (%d) for me\n", 
07600          ast_inet_ntoa(sin->sin_addr), version);
07601       return res;
07602    }
07603    /* Search the userlist for a compatible entry, and fill in the rest */
07604    ast_sockaddr_from_sin(&addr, sin);
07605    i = ao2_iterator_init(users, 0);
07606    while ((user = ao2_iterator_next(&i))) {
07607       if ((ast_strlen_zero(iaxs[callno]->username) ||          /* No username specified */
07608          !strcmp(iaxs[callno]->username, user->name)) /* Or this username specified */
07609          && ast_apply_ha(user->ha, &addr)    /* Access is permitted from this IP */
07610          && (ast_strlen_zero(iaxs[callno]->context) ||         /* No context specified */
07611               apply_context(user->contexts, iaxs[callno]->context))) {        /* Context is permitted */
07612          if (!ast_strlen_zero(iaxs[callno]->username)) {
07613             /* Exact match, stop right now. */
07614             if (best)
07615                user_unref(best);
07616             best = user;
07617             break;
07618          } else if (ast_strlen_zero(user->secret) && ast_strlen_zero(user->dbsecret) && ast_strlen_zero(user->inkeys)) {
07619             /* No required authentication */
07620             if (user->ha) {
07621                /* There was host authentication and we passed, bonus! */
07622                if (bestscore < 4) {
07623                   bestscore = 4;
07624                   if (best)
07625                      user_unref(best);
07626                   best = user;
07627                   continue;
07628                }
07629             } else {
07630                /* No host access, but no secret, either, not bad */
07631                if (bestscore < 3) {
07632                   bestscore = 3;
07633                   if (best)
07634                      user_unref(best);
07635                   best = user;
07636                   continue;
07637                }
07638             }
07639          } else {
07640             if (user->ha) {
07641                /* Authentication, but host access too, eh, it's something.. */
07642                if (bestscore < 2) {
07643                   bestscore = 2;
07644                   if (best)
07645                      user_unref(best);
07646                   best = user;
07647                   continue;
07648                }
07649             } else {
07650                /* Authentication and no host access...  This is our baseline */
07651                if (bestscore < 1) {
07652                   bestscore = 1;
07653                   if (best)
07654                      user_unref(best);
07655                   best = user;
07656                   continue;
07657                }
07658             }
07659          }
07660       }
07661       user_unref(user);
07662    }
07663    ao2_iterator_destroy(&i);
07664    user = best;
07665    if (!user && !ast_strlen_zero(iaxs[callno]->username)) {
07666       user = realtime_user(iaxs[callno]->username, sin);
07667       if (user && !ast_strlen_zero(iaxs[callno]->context) &&         /* No context specified */
07668           !apply_context(user->contexts, iaxs[callno]->context)) {      /* Context is permitted */
07669          user = user_unref(user);
07670       }
07671    }
07672    if (user) {
07673       /* We found our match (use the first) */
07674       /* copy vars */
07675       for (v = user->vars ; v ; v = v->next) {
07676          if((tmpvar = ast_variable_new(v->name, v->value, v->file))) {
07677             tmpvar->next = iaxs[callno]->vars; 
07678             iaxs[callno]->vars = tmpvar;
07679          }
07680       }
07681       /* If a max AUTHREQ restriction is in place, activate it */
07682       if (user->maxauthreq > 0)
07683          ast_set_flag64(iaxs[callno], IAX_MAXAUTHREQ);
07684       iaxs[callno]->prefs = user->prefs;
07685       ast_copy_flags64(iaxs[callno], user, IAX_CODEC_USER_FIRST | IAX_IMMEDIATE | IAX_CODEC_NOPREFS | IAX_CODEC_NOCAP | IAX_FORCE_ENCRYPT);
07686       iaxs[callno]->encmethods = user->encmethods;
07687       /* Store the requested username if not specified */
07688       if (ast_strlen_zero(iaxs[callno]->username))
07689          ast_string_field_set(iaxs[callno], username, user->name);
07690       /* Store whether this is a trunked call, too, of course, and move if appropriate */
07691       ast_copy_flags64(iaxs[callno], user, IAX_TRUNK);
07692       iaxs[callno]->capability = user->capability;
07693       /* And use the default context */
07694       if (ast_strlen_zero(iaxs[callno]->context)) {
07695          if (user->contexts)
07696             ast_string_field_set(iaxs[callno], context, user->contexts->context);
07697          else
07698             ast_string_field_set(iaxs[callno], context, DEFAULT_CONTEXT);
07699       }
07700       /* And any input keys */
07701       ast_string_field_set(iaxs[callno], inkeys, user->inkeys);
07702       /* And the permitted authentication methods */
07703       iaxs[callno]->authmethods = user->authmethods;
07704       iaxs[callno]->adsi = user->adsi;
07705       /* If the user has callerid, override the remote caller id. */
07706       if (ast_test_flag64(user, IAX_HASCALLERID)) {
07707          iaxs[callno]->calling_tns = 0;
07708          iaxs[callno]->calling_ton = 0;
07709          ast_string_field_set(iaxs[callno], cid_num, user->cid_num);
07710          ast_string_field_set(iaxs[callno], cid_name, user->cid_name);
07711          ast_string_field_set(iaxs[callno], ani, user->cid_num);
07712          iaxs[callno]->calling_pres = AST_PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN;
07713       } else if (ast_strlen_zero(iaxs[callno]->cid_num) && ast_strlen_zero(iaxs[callno]->cid_name)) {
07714          iaxs[callno]->calling_pres = AST_PRES_NUMBER_NOT_AVAILABLE;
07715       } /* else user is allowed to set their own CID settings */
07716       if (!ast_strlen_zero(user->accountcode))
07717          ast_string_field_set(iaxs[callno], accountcode, user->accountcode);
07718       if (!ast_strlen_zero(user->mohinterpret))
07719          ast_string_field_set(iaxs[callno], mohinterpret, user->mohinterpret);
07720       if (!ast_strlen_zero(user->mohsuggest))
07721          ast_string_field_set(iaxs[callno], mohsuggest, user->mohsuggest);
07722       if (!ast_strlen_zero(user->parkinglot))
07723          ast_string_field_set(iaxs[callno], parkinglot, user->parkinglot);
07724       if (user->amaflags)
07725          iaxs[callno]->amaflags = user->amaflags;
07726       if (!ast_strlen_zero(user->language))
07727          ast_string_field_set(iaxs[callno], language, user->language);
07728       ast_copy_flags64(iaxs[callno], user, IAX_NOTRANSFER | IAX_TRANSFERMEDIA | IAX_USEJITTERBUF | IAX_FORCEJITTERBUF | IAX_SENDCONNECTEDLINE | IAX_RECVCONNECTEDLINE); 
07729       /* Keep this check last */
07730       if (!ast_strlen_zero(user->dbsecret)) {
07731          char *family, *key=NULL;
07732          char buf[80];
07733          family = ast_strdupa(user->dbsecret);
07734          key = strchr(family, '/');
07735          if (key) {
07736             *key = '\0';
07737             key++;
07738          }
07739          if (!key || ast_db_get(family, key, buf, sizeof(buf)))
07740             ast_log(LOG_WARNING, "Unable to retrieve database password for family/key '%s'!\n", user->dbsecret);
07741          else
07742             ast_string_field_set(iaxs[callno], secret, buf);
07743       } else
07744          ast_string_field_set(iaxs[callno], secret, user->secret);
07745       res = 0;
07746       user = user_unref(user);
07747    } else {
07748        /* user was not found, but we should still fake an AUTHREQ.
07749         * Set authmethods to the last known authmethod used by the system
07750         * Set a fake secret, it's not looked at, just required to attempt authentication.
07751         * Set authrej so the AUTHREP is rejected without even looking at its contents */
07752       iaxs[callno]->authmethods = last_authmethod ? last_authmethod : (IAX_AUTH_MD5 | IAX_AUTH_PLAINTEXT);
07753       ast_string_field_set(iaxs[callno], secret, "badsecret");
07754       iaxs[callno]->authrej = 1;
07755       if (!ast_strlen_zero(iaxs[callno]->username)) {
07756          /* only send the AUTHREQ if a username was specified. */
07757          res = 0;
07758       }
07759    }
07760    ast_set2_flag64(iaxs[callno], iax2_getpeertrunk(*sin), IAX_TRUNK);
07761    return res;
07762 }
07763 
07764 static int raw_hangup(struct sockaddr_in *sin, unsigned short src, unsigned short dst, int sockfd)
07765 {
07766    struct ast_iax2_full_hdr fh;
07767    fh.scallno = htons(src | IAX_FLAG_FULL);
07768    fh.dcallno = htons(dst);
07769    fh.ts = 0;
07770    fh.oseqno = 0;
07771    fh.iseqno = 0;
07772    fh.type = AST_FRAME_IAX;
07773    fh.csub = compress_subclass(IAX_COMMAND_INVAL);
07774    iax_outputframe(NULL, &fh, 0, sin, 0);
07775 #if 0
07776    if (option_debug)
07777 #endif   
07778       ast_debug(1, "Raw Hangup %s:%d, src=%d, dst=%d\n",
07779          ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port), src, dst);
07780    return sendto(sockfd, &fh, sizeof(fh), 0, (struct sockaddr *)sin, sizeof(*sin));
07781 }
07782 
07783 static void merge_encryption(struct chan_iax2_pvt *p, unsigned int enc)
07784 {
07785    /* Select exactly one common encryption if there are any */
07786    p->encmethods &= enc;
07787    if (p->encmethods) {
07788       if (!(p->encmethods & IAX_ENCRYPT_KEYROTATE)){ /* if key rotation is not supported, turn off keyrotation. */
07789          p->keyrotateid = -2;
07790       }
07791       if (p->encmethods & IAX_ENCRYPT_AES128)
07792          p->encmethods = IAX_ENCRYPT_AES128;
07793       else
07794          p->encmethods = 0;
07795    }
07796 }
07797 
07798 /*!
07799  * \pre iaxsl[call_num] is locked
07800  *
07801  * \note Since this function calls send_command_final(), the pvt struct for the given
07802  *       call number may disappear while executing this function.
07803  */
07804 static int authenticate_request(int call_num)
07805 {
07806    struct iax_ie_data ied;
07807    int res = -1, authreq_restrict = 0;
07808    char challenge[10];
07809    struct chan_iax2_pvt *p = iaxs[call_num];
07810 
07811    memset(&ied, 0, sizeof(ied));
07812 
07813    /* If an AUTHREQ restriction is in place, make sure we can send an AUTHREQ back */
07814    if (ast_test_flag64(p, IAX_MAXAUTHREQ)) {
07815       struct iax2_user *user, tmp_user = {
07816          .name = p->username, 
07817       };
07818 
07819       user = ao2_find(users, &tmp_user, OBJ_POINTER);
07820       if (user) {
07821          if (user->curauthreq == user->maxauthreq)
07822             authreq_restrict = 1;
07823          else
07824             user->curauthreq++;
07825          user = user_unref(user);
07826       }
07827    }
07828 
07829    /* If the AUTHREQ limit test failed, send back an error */
07830    if (authreq_restrict) {
07831       iax_ie_append_str(&ied, IAX_IE_CAUSE, "Unauthenticated call limit reached");
07832       iax_ie_append_byte(&ied, IAX_IE_CAUSECODE, AST_CAUSE_CALL_REJECTED);
07833       send_command_final(p, AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied.buf, ied.pos, -1);
07834       return 0;
07835    }
07836 
07837    iax_ie_append_short(&ied, IAX_IE_AUTHMETHODS, p->authmethods);
07838    if (p->authmethods & (IAX_AUTH_MD5 | IAX_AUTH_RSA)) {
07839       snprintf(challenge, sizeof(challenge), "%d", (int)ast_random());
07840       ast_string_field_set(p, challenge, challenge);
07841       /* snprintf(p->challenge, sizeof(p->challenge), "%d", (int)ast_random()); */
07842       iax_ie_append_str(&ied, IAX_IE_CHALLENGE, p->challenge);
07843    }
07844    if (p->encmethods)
07845       iax_ie_append_short(&ied, IAX_IE_ENCRYPTION, p->encmethods);
07846 
07847    iax_ie_append_str(&ied,IAX_IE_USERNAME, p->username);
07848 
07849    res = send_command(p, AST_FRAME_IAX, IAX_COMMAND_AUTHREQ, 0, ied.buf, ied.pos, -1);
07850 
07851    if (p->encmethods)
07852       ast_set_flag64(p, IAX_ENCRYPTED);
07853 
07854    return res;
07855 }
07856 
07857 static int authenticate_verify(struct chan_iax2_pvt *p, struct iax_ies *ies)
07858 {
07859    char requeststr[256];
07860    char md5secret[256] = "";
07861    char secret[256] = "";
07862    char rsasecret[256] = "";
07863    int res = -1; 
07864    int x;
07865    struct iax2_user *user, tmp_user = {
07866       .name = p->username, 
07867    };
07868 
07869    if (p->authrej) {
07870       return res;
07871    }
07872    user = ao2_find(users, &tmp_user, OBJ_POINTER);
07873    if (user) {
07874       if (ast_test_flag64(p, IAX_MAXAUTHREQ)) {
07875          ast_atomic_fetchadd_int(&user->curauthreq, -1);
07876          ast_clear_flag64(p, IAX_MAXAUTHREQ);
07877       }
07878       ast_string_field_set(p, host, user->name);
07879       user = user_unref(user);
07880    }
07881    if (ast_test_flag64(p, IAX_FORCE_ENCRYPT) && !p->encmethods) { 
07882       ast_log(LOG_NOTICE, "Call Terminated, Incoming call is unencrypted while force encrypt is enabled.");
07883       return res;
07884    }
07885    if (!ast_test_flag(&p->state, IAX_STATE_AUTHENTICATED))
07886       return res;
07887    if (ies->password)
07888       ast_copy_string(secret, ies->password, sizeof(secret));
07889    if (ies->md5_result)
07890       ast_copy_string(md5secret, ies->md5_result, sizeof(md5secret));
07891    if (ies->rsa_result)
07892       ast_copy_string(rsasecret, ies->rsa_result, sizeof(rsasecret));
07893    if ((p->authmethods & IAX_AUTH_RSA) && !ast_strlen_zero(rsasecret) && !ast_strlen_zero(p->inkeys)) {
07894       struct ast_key *key;
07895       char *keyn;
07896       char tmpkey[256];
07897       char *stringp=NULL;
07898       ast_copy_string(tmpkey, p->inkeys, sizeof(tmpkey));
07899       stringp=tmpkey;
07900       keyn = strsep(&stringp, ":");
07901       while(keyn) {
07902          key = ast_key_get(keyn, AST_KEY_PUBLIC);
07903          if (key && !ast_check_signature(key, p->challenge, rsasecret)) {
07904             res = 0;
07905             break;
07906          } else if (!key)
07907             ast_log(LOG_WARNING, "requested inkey '%s' for RSA authentication does not exist\n", keyn);
07908          keyn = strsep(&stringp, ":");
07909       }
07910    } else if (p->authmethods & IAX_AUTH_MD5) {
07911       struct MD5Context md5;
07912       unsigned char digest[16];
07913       char *tmppw, *stringp;
07914       
07915       tmppw = ast_strdupa(p->secret);
07916       stringp = tmppw;
07917       while((tmppw = strsep(&stringp, ";"))) {
07918          MD5Init(&md5);
07919          MD5Update(&md5, (unsigned char *)p->challenge, strlen(p->challenge));
07920          MD5Update(&md5, (unsigned char *)tmppw, strlen(tmppw));
07921          MD5Final(digest, &md5);
07922          /* If they support md5, authenticate with it.  */
07923          for (x=0;x<16;x++)
07924             sprintf(requeststr + (x << 1), "%2.2x", digest[x]); /* safe */
07925          if (!strcasecmp(requeststr, md5secret)) {
07926             res = 0;
07927             break;
07928          }
07929       }
07930    } else if (p->authmethods & IAX_AUTH_PLAINTEXT) {
07931       if (!strcmp(secret, p->secret))
07932          res = 0;
07933    }
07934    return res;
07935 }
07936 
07937 /*! \brief Verify inbound registration */
07938 static int register_verify(int callno, struct sockaddr_in *sin, struct iax_ies *ies)
07939 {
07940    char requeststr[256] = "";
07941    char peer[256] = "";
07942    char md5secret[256] = "";
07943    char rsasecret[256] = "";
07944    char secret[256] = "";
07945    struct iax2_peer *p = NULL;
07946    struct ast_key *key;
07947    char *keyn;
07948    int x;
07949    int expire = 0;
07950    int res = -1;
07951    struct ast_sockaddr addr;
07952 
07953    ast_clear_flag(&iaxs[callno]->state, IAX_STATE_AUTHENTICATED);
07954    /* iaxs[callno]->peer[0] = '\0'; not necc. any more-- stringfield is pre-inited to null string */
07955    if (ies->username)
07956       ast_copy_string(peer, ies->username, sizeof(peer));
07957    if (ies->password)
07958       ast_copy_string(secret, ies->password, sizeof(secret));
07959    if (ies->md5_result)
07960       ast_copy_string(md5secret, ies->md5_result, sizeof(md5secret));
07961    if (ies->rsa_result)
07962       ast_copy_string(rsasecret, ies->rsa_result, sizeof(rsasecret));
07963    if (ies->refresh)
07964       expire = ies->refresh;
07965 
07966    if (ast_strlen_zero(peer)) {
07967       ast_log(LOG_NOTICE, "Empty registration from %s\n", ast_inet_ntoa(sin->sin_addr));
07968       return -1;
07969    }
07970 
07971    /* SLD: first call to lookup peer during registration */
07972    ast_mutex_unlock(&iaxsl[callno]);
07973    p = find_peer(peer, 1);
07974    ast_mutex_lock(&iaxsl[callno]);
07975    if (!p || !iaxs[callno]) {
07976       if (iaxs[callno]) {
07977          int plaintext = ((last_authmethod & IAX_AUTH_PLAINTEXT) | (iaxs[callno]->authmethods & IAX_AUTH_PLAINTEXT));
07978          /* Anything, as long as it's non-blank */
07979          ast_string_field_set(iaxs[callno], secret, "badsecret");
07980          /* An AUTHREQ must be sent in response to a REGREQ of an invalid peer unless
07981           * 1. A challenge already exists indicating a AUTHREQ was already sent out.
07982           * 2. A plaintext secret is present in ie as result of a previous AUTHREQ requesting it.
07983           * 3. A plaintext secret is present in the ie and the last_authmethod used by a peer happened
07984           *    to be plaintext, indicating it is an authmethod used by other peers on the system. 
07985           *
07986           * If none of these cases exist, res will be returned as 0 without authentication indicating
07987           * an AUTHREQ needs to be sent out. */
07988 
07989          if (ast_strlen_zero(iaxs[callno]->challenge) &&
07990             !(!ast_strlen_zero(secret) && plaintext)) {
07991             /* by setting res to 0, an REGAUTH will be sent */
07992             res = 0;
07993          }
07994       }
07995       if (authdebug && !p)
07996          ast_log(LOG_NOTICE, "No registration for peer '%s' (from %s)\n", peer, ast_inet_ntoa(sin->sin_addr));
07997       goto return_unref;
07998    }
07999 
08000    if (!ast_test_flag64(p, IAX_DYNAMIC)) {
08001       if (authdebug)
08002          ast_log(LOG_NOTICE, "Peer '%s' is not dynamic (from %s)\n", peer, ast_inet_ntoa(sin->sin_addr));
08003       goto return_unref;
08004    }
08005 
08006    ast_sockaddr_from_sin(&addr, sin);
08007    if (!ast_apply_ha(p->ha, &addr)) {
08008       if (authdebug)
08009          ast_log(LOG_NOTICE, "Host %s denied access to register peer '%s'\n", ast_inet_ntoa(sin->sin_addr), p->name);
08010       goto return_unref;
08011    }
08012    ast_string_field_set(iaxs[callno], secret, p->secret);
08013    ast_string_field_set(iaxs[callno], inkeys, p->inkeys);
08014    /* Check secret against what we have on file */
08015    if (!ast_strlen_zero(rsasecret) && (p->authmethods & IAX_AUTH_RSA) && !ast_strlen_zero(iaxs[callno]->challenge)) {
08016       if (!ast_strlen_zero(p->inkeys)) {
08017          char tmpkeys[256];
08018          char *stringp=NULL;
08019          ast_copy_string(tmpkeys, p->inkeys, sizeof(tmpkeys));
08020          stringp=tmpkeys;
08021          keyn = strsep(&stringp, ":");
08022          while(keyn) {
08023             key = ast_key_get(keyn, AST_KEY_PUBLIC);
08024             if (key && !ast_check_signature(key, iaxs[callno]->challenge, rsasecret)) {
08025                ast_set_flag(&iaxs[callno]->state, IAX_STATE_AUTHENTICATED);
08026                break;
08027             } else if (!key)
08028                ast_log(LOG_WARNING, "requested inkey '%s' does not exist\n", keyn);
08029             keyn = strsep(&stringp, ":");
08030          }
08031          if (!keyn) {
08032             if (authdebug)
08033                ast_log(LOG_NOTICE, "Host %s failed RSA authentication with inkeys '%s'\n", peer, p->inkeys);
08034             goto return_unref;
08035          }
08036       } else {
08037          if (authdebug)
08038             ast_log(LOG_NOTICE, "Host '%s' trying to do RSA authentication, but we have no inkeys\n", peer);
08039          goto return_unref;
08040       }
08041    } else if (!ast_strlen_zero(md5secret) && (p->authmethods & IAX_AUTH_MD5) && !ast_strlen_zero(iaxs[callno]->challenge)) {
08042       struct MD5Context md5;
08043       unsigned char digest[16];
08044       char *tmppw, *stringp;
08045 
08046       tmppw = ast_strdupa(p->secret);
08047       stringp = tmppw;
08048       while((tmppw = strsep(&stringp, ";"))) {
08049          MD5Init(&md5);
08050          MD5Update(&md5, (unsigned char *)iaxs[callno]->challenge, strlen(iaxs[callno]->challenge));
08051          MD5Update(&md5, (unsigned char *)tmppw, strlen(tmppw));
08052          MD5Final(digest, &md5);
08053          for (x=0;x<16;x++)
08054             sprintf(requeststr + (x << 1), "%2.2x", digest[x]); /* safe */
08055          if (!strcasecmp(requeststr, md5secret))
08056             break;
08057       }
08058       if (tmppw) {
08059          ast_set_flag(&iaxs[callno]->state, IAX_STATE_AUTHENTICATED);
08060       } else {
08061          if (authdebug)
08062             ast_log(LOG_NOTICE, "Host %s failed MD5 authentication for '%s' (%s != %s)\n", ast_inet_ntoa(sin->sin_addr), p->name, requeststr, md5secret);
08063          goto return_unref;
08064       }
08065    } else if (!ast_strlen_zero(secret) && (p->authmethods & IAX_AUTH_PLAINTEXT)) {
08066       /* They've provided a plain text password and we support that */
08067       if (strcmp(secret, p->secret)) {
08068          if (authdebug)
08069             ast_log(LOG_NOTICE, "Host %s did not provide proper plaintext password for '%s'\n", ast_inet_ntoa(sin->sin_addr), p->name);
08070          goto return_unref;
08071       } else
08072          ast_set_flag(&iaxs[callno]->state, IAX_STATE_AUTHENTICATED);
08073    } else if (!ast_strlen_zero(iaxs[callno]->challenge) && ast_strlen_zero(md5secret) && ast_strlen_zero(rsasecret)) {
08074       /* if challenge has been sent, but no challenge response if given, reject. */
08075       goto return_unref;
08076    }
08077    ast_devstate_changed(AST_DEVICE_UNKNOWN, "IAX2/%s", p->name); /* Activate notification */
08078 
08079    /* either Authentication has taken place, or a REGAUTH must be sent before verifying registration */
08080    res = 0;
08081 
08082 return_unref:
08083    if (iaxs[callno]) {
08084       ast_string_field_set(iaxs[callno], peer, peer);
08085 
08086       /* Choose lowest expiry number */
08087       if (expire && (expire < iaxs[callno]->expiry)) {
08088          iaxs[callno]->expiry = expire;
08089       }
08090    }
08091 
08092    if (p) {
08093       peer_unref(p);
08094    }
08095    return res;
08096 }
08097 
08098 static int authenticate(const char *challenge, const char *secret, const char *keyn, int authmethods, struct iax_ie_data *ied, struct sockaddr_in *sin, struct chan_iax2_pvt *pvt)
08099 {
08100    int res = -1;
08101    int x;
08102    if (!ast_strlen_zero(keyn)) {
08103       if (!(authmethods & IAX_AUTH_RSA)) {
08104          if (ast_strlen_zero(secret)) 
08105             ast_log(LOG_NOTICE, "Asked to authenticate to %s with an RSA key, but they don't allow RSA authentication\n", ast_inet_ntoa(sin->sin_addr));
08106       } else if (ast_strlen_zero(challenge)) {
08107          ast_log(LOG_NOTICE, "No challenge provided for RSA authentication to %s\n", ast_inet_ntoa(sin->sin_addr));
08108       } else {
08109          char sig[256];
08110          struct ast_key *key;
08111          key = ast_key_get(keyn, AST_KEY_PRIVATE);
08112          if (!key) {
08113             ast_log(LOG_NOTICE, "Unable to find private key '%s'\n", keyn);
08114          } else {
08115             if (ast_sign(key, (char*)challenge, sig)) {
08116                ast_log(LOG_NOTICE, "Unable to sign challenge with key\n");
08117                res = -1;
08118             } else {
08119                iax_ie_append_str(ied, IAX_IE_RSA_RESULT, sig);
08120                res = 0;
08121             }
08122          }
08123       }
08124    } 
08125    /* Fall back */
08126    if (res && !ast_strlen_zero(secret)) {
08127       if ((authmethods & IAX_AUTH_MD5) && !ast_strlen_zero(challenge)) {
08128          struct MD5Context md5;
08129          unsigned char digest[16];
08130          char digres[128];
08131          MD5Init(&md5);
08132          MD5Update(&md5, (unsigned char *)challenge, strlen(challenge));
08133          MD5Update(&md5, (unsigned char *)secret, strlen(secret));
08134          MD5Final(digest, &md5);
08135          /* If they support md5, authenticate with it.  */
08136          for (x=0;x<16;x++)
08137             sprintf(digres + (x << 1),  "%2.2x", digest[x]); /* safe */
08138          if (pvt) {
08139             build_encryption_keys(digest, pvt);
08140          }
08141          iax_ie_append_str(ied, IAX_IE_MD5_RESULT, digres);
08142          res = 0;
08143       } else if (authmethods & IAX_AUTH_PLAINTEXT) {
08144          iax_ie_append_str(ied, IAX_IE_PASSWORD, secret);
08145          res = 0;
08146       } else
08147          ast_log(LOG_NOTICE, "No way to send secret to peer '%s' (their methods: %d)\n", ast_inet_ntoa(sin->sin_addr), authmethods);
08148    }
08149    return res;
08150 }
08151 
08152 /*!
08153  * \note This function calls realtime_peer -> reg_source_db -> iax2_poke_peer -> find_callno,
08154  *       so do not call this function with a pvt lock held.
08155  */
08156 static int authenticate_reply(struct chan_iax2_pvt *p, struct sockaddr_in *sin, struct iax_ies *ies, const char *override, const char *okey)
08157 {
08158    struct iax2_peer *peer = NULL;
08159    /* Start pessimistic */
08160    int res = -1;
08161    int authmethods = 0;
08162    struct iax_ie_data ied;
08163    uint16_t callno = p->callno;
08164 
08165    memset(&ied, 0, sizeof(ied));
08166    
08167    if (ies->username)
08168       ast_string_field_set(p, username, ies->username);
08169    if (ies->challenge)
08170       ast_string_field_set(p, challenge, ies->challenge);
08171    if (ies->authmethods)
08172       authmethods = ies->authmethods;
08173    if (authmethods & IAX_AUTH_MD5)
08174       merge_encryption(p, ies->encmethods);
08175    else
08176       p->encmethods = 0;
08177 
08178    /* Check for override RSA authentication first */
08179    if (!ast_strlen_zero(override) || !ast_strlen_zero(okey)) {
08180       /* Normal password authentication */
08181       res = authenticate(p->challenge, override, okey, authmethods, &ied, sin, p);
08182    } else {
08183       struct ao2_iterator i = ao2_iterator_init(peers, 0);
08184       while ((peer = ao2_iterator_next(&i))) {
08185          struct sockaddr_in peer_addr;
08186 
08187          ast_sockaddr_to_sin(&peer->addr, &peer_addr);
08188 
08189          if ((ast_strlen_zero(p->peer) || !strcmp(p->peer, peer->name)) 
08190              /* No peer specified at our end, or this is the peer */
08191              && (ast_strlen_zero(peer->username) || (!strcmp(peer->username, p->username)))
08192              /* No username specified in peer rule, or this is the right username */
08193              && (!peer_addr.sin_addr.s_addr || ((sin->sin_addr.s_addr & peer->mask.s_addr) == (peer_addr.sin_addr.s_addr & peer->mask.s_addr)))
08194              /* No specified host, or this is our host */
08195             ) {
08196             res = authenticate(p->challenge, peer->secret, peer->outkey, authmethods, &ied, sin, p);
08197             if (!res) {
08198                peer_unref(peer);
08199                break;
08200             }
08201          }
08202          peer_unref(peer);
08203       }
08204       ao2_iterator_destroy(&i);
08205       if (!peer) {
08206          /* We checked our list and didn't find one.  It's unlikely, but possible, 
08207             that we're trying to authenticate *to* a realtime peer */
08208          const char *peer_name = ast_strdupa(p->peer);
08209          ast_mutex_unlock(&iaxsl[callno]);
08210          if ((peer = realtime_peer(peer_name, NULL))) {
08211             ast_mutex_lock(&iaxsl[callno]);
08212             if (!(p = iaxs[callno])) {
08213                peer_unref(peer);
08214                return -1;
08215             }
08216             res = authenticate(p->challenge, peer->secret,peer->outkey, authmethods, &ied, sin, p);
08217             peer_unref(peer);
08218          }
08219          if (!peer) {
08220             ast_mutex_lock(&iaxsl[callno]);
08221             if (!(p = iaxs[callno]))
08222                return -1;
08223          }
08224       }
08225    }
08226 
08227    if (ies->encmethods) {
08228       ast_set_flag64(p, IAX_ENCRYPTED | IAX_KEYPOPULATED);
08229    } else if (ast_test_flag64(iaxs[callno], IAX_FORCE_ENCRYPT)) {
08230       ast_log(LOG_NOTICE, "Call initiated without encryption while forceencryption=yes option is set");
08231       return -1;             /* if force encryption is yes, and no encryption methods, then return -1 to hangup */
08232    }
08233    if (!res) {
08234       struct ast_datastore *variablestore;
08235       struct ast_variable *var, *prev = NULL;
08236       AST_LIST_HEAD(, ast_var_t) *varlist;
08237       varlist = ast_calloc(1, sizeof(*varlist));
08238       variablestore = ast_datastore_alloc(&iax2_variable_datastore_info, NULL);
08239       if (variablestore && varlist && p->owner) {
08240          variablestore->data = varlist;
08241          variablestore->inheritance = DATASTORE_INHERIT_FOREVER;
08242          AST_LIST_HEAD_INIT(varlist);
08243          for (var = ies->vars; var; var = var->next) {
08244             struct ast_var_t *newvar = ast_var_assign(var->name, var->value);
08245             if (prev)
08246                ast_free(prev);
08247             prev = var;
08248             if (!newvar) {
08249                /* Don't abort list traversal, as this would leave ies->vars in an inconsistent state. */
08250                ast_log(LOG_ERROR, "Memory allocation error while processing IAX2 variables\n");
08251             } else {
08252                AST_LIST_INSERT_TAIL(varlist, newvar, entries);
08253             }
08254          }
08255          if (prev)
08256             ast_free(prev);
08257          ies->vars = NULL;
08258          ast_channel_datastore_add(p->owner, variablestore);
08259       } else {
08260          if (p->owner)
08261             ast_log(LOG_ERROR, "Memory allocation error while processing IAX2 variables\n");
08262          if (variablestore)
08263             ast_datastore_free(variablestore);
08264          if (varlist)
08265             ast_free(varlist);
08266       }
08267    }
08268 
08269    if (!res)
08270       res = send_command(p, AST_FRAME_IAX, IAX_COMMAND_AUTHREP, 0, ied.buf, ied.pos, -1);
08271    return res;
08272 }
08273 
08274 static int iax2_do_register(struct iax2_registry *reg);
08275 
08276 static void __iax2_do_register_s(const void *data)
08277 {
08278    struct iax2_registry *reg = (struct iax2_registry *)data;
08279    reg->expire = -1;
08280    iax2_do_register(reg);
08281 }
08282 
08283 static int iax2_do_register_s(const void *data)
08284 {
08285 #ifdef SCHED_MULTITHREADED
08286    if (schedule_action(__iax2_do_register_s, data))
08287 #endif      
08288       __iax2_do_register_s(data);
08289    return 0;
08290 }
08291 
08292 static int try_transfer(struct chan_iax2_pvt *pvt, struct iax_ies *ies)
08293 {
08294    int newcall = 0;
08295    char newip[256];
08296    struct iax_ie_data ied;
08297    struct sockaddr_in new;
08298    
08299    
08300    memset(&ied, 0, sizeof(ied));
08301    if (ies->apparent_addr)
08302       memmove(&new, ies->apparent_addr, sizeof(new));
08303    if (ies->callno)
08304       newcall = ies->callno;
08305    if (!newcall || !new.sin_addr.s_addr || !new.sin_port) {
08306       ast_log(LOG_WARNING, "Invalid transfer request\n");
08307       return -1;
08308    }
08309    pvt->transfercallno = newcall;
08310    memcpy(&pvt->transfer, &new, sizeof(pvt->transfer));
08311    inet_aton(newip, &pvt->transfer.sin_addr);
08312    pvt->transfer.sin_family = AF_INET;
08313    pvt->transferid = ies->transferid;
08314    /* only store by transfercallno if this is a new transfer,
08315     * just in case we get a duplicate TXREQ */
08316    if (pvt->transferring == TRANSFER_NONE) {
08317       store_by_transfercallno(pvt);
08318    }
08319    pvt->transferring = TRANSFER_BEGIN;
08320 
08321    if (ies->transferid)
08322       iax_ie_append_int(&ied, IAX_IE_TRANSFERID, ies->transferid);
08323    send_command_transfer(pvt, AST_FRAME_IAX, IAX_COMMAND_TXCNT, 0, ied.buf, ied.pos);
08324    return 0;
08325 }
08326 
08327 static int complete_dpreply(struct chan_iax2_pvt *pvt, struct iax_ies *ies)
08328 {
08329    char exten[256] = "";
08330    int status = CACHE_FLAG_UNKNOWN, expiry = iaxdefaultdpcache, x, matchmore = 0;
08331    struct iax2_dpcache *dp = NULL;
08332    
08333    if (ies->called_number)
08334       ast_copy_string(exten, ies->called_number, sizeof(exten));
08335    
08336    if (ies->dpstatus & IAX_DPSTATUS_EXISTS)
08337       status = CACHE_FLAG_EXISTS;
08338    else if (ies->dpstatus & IAX_DPSTATUS_CANEXIST)
08339       status = CACHE_FLAG_CANEXIST;
08340    else if (ies->dpstatus & IAX_DPSTATUS_NONEXISTENT)
08341       status = CACHE_FLAG_NONEXISTENT;
08342 
08343    if (ies->refresh)
08344       expiry = ies->refresh;
08345    if (ies->dpstatus & IAX_DPSTATUS_MATCHMORE)
08346       matchmore = CACHE_FLAG_MATCHMORE;
08347    
08348    AST_LIST_LOCK(&dpcache);
08349    AST_LIST_TRAVERSE_SAFE_BEGIN(&dpcache, dp, peer_list) {
08350       if (strcmp(dp->exten, exten))
08351          continue;
08352       AST_LIST_REMOVE_CURRENT(peer_list);
08353       dp->callno = 0;
08354       dp->expiry.tv_sec = dp->orig.tv_sec + expiry;
08355       if (dp->flags & CACHE_FLAG_PENDING) {
08356          dp->flags &= ~CACHE_FLAG_PENDING;
08357          dp->flags |= status;
08358          dp->flags |= matchmore;
08359       }
08360       /* Wake up waiters */
08361       for (x = 0; x < ARRAY_LEN(dp->waiters); x++) {
08362          if (dp->waiters[x] > -1) {
08363             if (write(dp->waiters[x], "asdf", 4) < 0) {
08364             }
08365          }
08366       }
08367    }
08368    AST_LIST_TRAVERSE_SAFE_END;
08369    AST_LIST_UNLOCK(&dpcache);
08370 
08371    return 0;
08372 }
08373 
08374 static int complete_transfer(int callno, struct iax_ies *ies)
08375 {
08376    int peercallno = 0;
08377    struct chan_iax2_pvt *pvt = iaxs[callno];
08378    struct iax_frame *cur;
08379    jb_frame frame;
08380 
08381    if (ies->callno)
08382       peercallno = ies->callno;
08383 
08384    if (peercallno < 1) {
08385       ast_log(LOG_WARNING, "Invalid transfer request\n");
08386       return -1;
08387    }
08388    remove_by_transfercallno(pvt);
08389    /* since a transfer has taken place, the address will change.
08390     * This must be accounted for in the peercnts table.  Remove
08391     * the old address and add the new one */
08392    peercnt_remove_by_addr(&pvt->addr);
08393    peercnt_add(&pvt->transfer);
08394    /* now copy over the new address */
08395    memcpy(&pvt->addr, &pvt->transfer, sizeof(pvt->addr));
08396    memset(&pvt->transfer, 0, sizeof(pvt->transfer));
08397    /* Reset sequence numbers */
08398    pvt->oseqno = 0;
08399    pvt->rseqno = 0;
08400    pvt->iseqno = 0;
08401    pvt->aseqno = 0;
08402 
08403    if (pvt->peercallno) {
08404       remove_by_peercallno(pvt);
08405    }
08406    pvt->peercallno = peercallno;
08407    /*this is where the transfering call swiches hash tables */
08408    store_by_peercallno(pvt);
08409    pvt->transferring = TRANSFER_NONE;
08410    pvt->svoiceformat = -1;
08411    pvt->voiceformat = 0;
08412    pvt->svideoformat = -1;
08413    pvt->videoformat = 0;
08414    pvt->transfercallno = 0;
08415    memset(&pvt->rxcore, 0, sizeof(pvt->rxcore));
08416    memset(&pvt->offset, 0, sizeof(pvt->offset));
08417    /* reset jitterbuffer */
08418    while(jb_getall(pvt->jb,&frame) == JB_OK)
08419       iax2_frame_free(frame.data);
08420    jb_reset(pvt->jb);
08421    pvt->lag = 0;
08422    pvt->last = 0;
08423    pvt->lastsent = 0;
08424    pvt->nextpred = 0;
08425    pvt->pingtime = DEFAULT_RETRY_TIME;
08426    AST_LIST_TRAVERSE(&frame_queue[callno], cur, list) {
08427       /* We must cancel any packets that would have been transmitted
08428          because now we're talking to someone new.  It's okay, they
08429          were transmitted to someone that didn't care anyway. */
08430       cur->retries = -1;
08431    }
08432    return 0;
08433 }
08434 
08435 /*! \brief Acknowledgment received for OUR registration */
08436 static int iax2_ack_registry(struct iax_ies *ies, struct sockaddr_in *sin, int callno)
08437 {
08438    struct iax2_registry *reg;
08439    /* Start pessimistic */
08440    char peer[256] = "";
08441    char msgstatus[60];
08442    int refresh = 60;
08443    char ourip[256] = "<Unspecified>";
08444    struct sockaddr_in oldus;
08445    struct sockaddr_in us;
08446    int oldmsgs;
08447    struct sockaddr_in reg_addr;
08448 
08449    memset(&us, 0, sizeof(us));
08450    if (ies->apparent_addr) {
08451       memmove(&us, ies->apparent_addr, sizeof(us));
08452    }
08453    if (ies->username) {
08454       ast_copy_string(peer, ies->username, sizeof(peer));
08455    }
08456    if (ies->refresh) {
08457       refresh = ies->refresh;
08458    }
08459    if (ies->calling_number) {
08460       /* We don't do anything with it really, but maybe we should */
08461    }
08462    reg = iaxs[callno]->reg;
08463    if (!reg) {
08464       ast_log(LOG_WARNING, "Registry acknowledge on unknown registry '%s'\n", peer);
08465       return -1;
08466    }
08467    memcpy(&oldus, &reg->us, sizeof(oldus));
08468    oldmsgs = reg->messages;
08469    ast_sockaddr_to_sin(&reg->addr, &reg_addr);
08470    if (inaddrcmp(&reg_addr, sin)) {
08471       ast_log(LOG_WARNING, "Received unsolicited registry ack from '%s'\n", ast_inet_ntoa(sin->sin_addr));
08472       return -1;
08473    }
08474    memcpy(&reg->us, &us, sizeof(reg->us));
08475    if (ies->msgcount >= 0) {
08476       reg->messages = ies->msgcount & 0xffff;      /* only low 16 bits are used in the transmission of the IE */
08477    }
08478    /* always refresh the registration at the interval requested by the server
08479       we are registering to
08480    */
08481    reg->refresh = refresh;
08482    reg->expire = iax2_sched_replace(reg->expire, sched,
08483       (5 * reg->refresh / 6) * 1000, iax2_do_register_s, reg);
08484    if (inaddrcmp(&oldus, &reg->us) || (reg->messages != oldmsgs)) {
08485       if (reg->messages > 255) {
08486          snprintf(msgstatus, sizeof(msgstatus), " with %d new and %d old messages waiting", reg->messages & 0xff, reg->messages >> 8);
08487       } else if (reg->messages > 1) {
08488          snprintf(msgstatus, sizeof(msgstatus), " with %d new messages waiting", reg->messages);
08489       } else if (reg->messages > 0) {
08490          ast_copy_string(msgstatus, " with 1 new message waiting", sizeof(msgstatus));
08491       } else {
08492          ast_copy_string(msgstatus, " with no messages waiting", sizeof(msgstatus));
08493       }
08494       snprintf(ourip, sizeof(ourip), "%s:%d", ast_inet_ntoa(reg->us.sin_addr), ntohs(reg->us.sin_port));
08495       ast_verb(3, "Registered IAX2 to '%s', who sees us as %s%s\n", ast_inet_ntoa(sin->sin_addr), ourip, msgstatus);
08496       manager_event(EVENT_FLAG_SYSTEM, "Registry", "ChannelType: IAX2\r\nDomain: %s\r\nStatus: Registered\r\n", ast_inet_ntoa(sin->sin_addr));
08497    }
08498    reg->regstate = REG_STATE_REGISTERED;
08499    return 0;
08500 }
08501 
08502 static int iax2_append_register(const char *hostname, const char *username,
08503    const char *secret, const char *porta)
08504 {
08505    struct iax2_registry *reg;
08506 
08507    if (!(reg = ast_calloc(1, sizeof(*reg))))
08508       return -1;
08509 
08510    reg->addr.ss.ss_family = AF_INET;
08511    if (ast_dnsmgr_lookup(hostname, &reg->addr, &reg->dnsmgr, srvlookup ? "_iax._udp" : NULL) < 0) {
08512       ast_free(reg);
08513       return -1;
08514    }
08515 
08516    ast_copy_string(reg->username, username, sizeof(reg->username));
08517 
08518    if (secret)
08519       ast_copy_string(reg->secret, secret, sizeof(reg->secret));
08520 
08521    reg->expire = -1;
08522    reg->refresh = IAX_DEFAULT_REG_EXPIRE;
08523    ast_sockaddr_set_port(&reg->addr, porta ? atoi(porta) : IAX_DEFAULT_PORTNO);
08524 
08525    AST_LIST_LOCK(&registrations);
08526    AST_LIST_INSERT_HEAD(&registrations, reg, entry);
08527    AST_LIST_UNLOCK(&registrations);
08528    
08529    return 0;
08530 }
08531 
08532 static int iax2_register(const char *value, int lineno)
08533 {
08534    char copy[256];
08535    char *username, *hostname, *secret;
08536    char *porta;
08537    char *stringp=NULL;
08538    
08539    if (!value)
08540       return -1;
08541 
08542    ast_copy_string(copy, value, sizeof(copy));
08543    stringp = copy;
08544    username = strsep(&stringp, "@");
08545    hostname = strsep(&stringp, "@");
08546 
08547    if (!hostname) {
08548       ast_log(LOG_WARNING, "Format for registration is user[:secret]@host[:port] at line %d\n", lineno);
08549       return -1;
08550    }
08551 
08552    stringp = username;
08553    username = strsep(&stringp, ":");
08554    secret = strsep(&stringp, ":");
08555    stringp = hostname;
08556    hostname = strsep(&stringp, ":");
08557    porta = strsep(&stringp, ":");
08558    
08559    if (porta && !atoi(porta)) {
08560       ast_log(LOG_WARNING, "%s is not a valid port number at line %d\n", porta, lineno);
08561       return -1;
08562    }
08563 
08564    return iax2_append_register(hostname, username, secret, porta);
08565 }
08566 
08567 
08568 static void register_peer_exten(struct iax2_peer *peer, int onoff)
08569 {
08570    char multi[256];
08571    char *stringp, *ext;
08572    if (!ast_strlen_zero(regcontext)) {
08573       ast_copy_string(multi, S_OR(peer->regexten, peer->name), sizeof(multi));
08574       stringp = multi;
08575       while((ext = strsep(&stringp, "&"))) {
08576          if (onoff) {
08577             if (!ast_exists_extension(NULL, regcontext, ext, 1, NULL))
08578                ast_add_extension(regcontext, 1, ext, 1, NULL, NULL,
08579                        "Noop", ast_strdup(peer->name), ast_free_ptr, "IAX2");
08580          } else
08581             ast_context_remove_extension(regcontext, ext, 1, NULL);
08582       }
08583    }
08584 }
08585 static void prune_peers(void);
08586 
08587 static void unlink_peer(struct iax2_peer *peer)
08588 {
08589    if (peer->expire > -1) {
08590       if (!ast_sched_thread_del(sched, peer->expire)) {
08591          peer->expire = -1;
08592          peer_unref(peer);
08593       }
08594    }
08595 
08596    if (peer->pokeexpire > -1) {
08597       if (!ast_sched_thread_del(sched, peer->pokeexpire)) {
08598          peer->pokeexpire = -1;
08599          peer_unref(peer);
08600       }
08601    }
08602 
08603    ao2_unlink(peers, peer);
08604 }
08605 
08606 static void __expire_registry(const void *data)
08607 {
08608    struct iax2_peer *peer = (struct iax2_peer *) data;
08609 
08610    if (!peer)
08611       return;
08612    if (peer->expire == -1) {
08613       /* Removed already (possibly through CLI), ignore */
08614       return;
08615    }
08616 
08617    peer->expire = -1;
08618 
08619    ast_debug(1, "Expiring registration for peer '%s'\n", peer->name);
08620    if (ast_test_flag64((&globalflags), IAX_RTUPDATE) && (ast_test_flag64(peer, IAX_TEMPONLY|IAX_RTCACHEFRIENDS)))
08621       realtime_update_peer(peer->name, &peer->addr, 0);
08622    manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: IAX2\r\nPeer: IAX2/%s\r\nPeerStatus: Unregistered\r\nCause: Expired\r\n", peer->name);
08623    /* modify entry in peercnts table as _not_ registered */
08624    peercnt_modify(0, 0, &peer->addr);
08625    /* Reset the address */
08626    memset(&peer->addr, 0, sizeof(peer->addr));
08627    /* Reset expiry value */
08628    peer->expiry = min_reg_expire;
08629    if (!ast_test_flag64(peer, IAX_TEMPONLY))
08630       ast_db_del("IAX/Registry", peer->name);
08631    register_peer_exten(peer, 0);
08632    ast_devstate_changed(AST_DEVICE_UNAVAILABLE, "IAX2/%s", peer->name); /* Activate notification */
08633    if (iax2_regfunk)
08634       iax2_regfunk(peer->name, 0);
08635 
08636    if (ast_test_flag64(peer, IAX_RTAUTOCLEAR))
08637       unlink_peer(peer);
08638 
08639    peer_unref(peer);
08640 }
08641 
08642 static int expire_registry(const void *data)
08643 {
08644 #ifdef SCHED_MULTITHREADED
08645    if (schedule_action(__expire_registry, data))
08646 #endif      
08647       __expire_registry(data);
08648    return 0;
08649 }
08650 
08651 static int iax2_poke_peer(struct iax2_peer *peer, int heldcall);
08652 
08653 static void reg_source_db(struct iax2_peer *p)
08654 {
08655    char data[80];
08656    char *expiry;
08657 
08658    if (ast_test_flag64(p, IAX_TEMPONLY) || ast_db_get("IAX/Registry", p->name, data, sizeof(data))) {
08659       return;
08660    }
08661 
08662    expiry = strrchr(data, ':');
08663    if (!expiry) {
08664       ast_log(LOG_NOTICE, "IAX/Registry astdb entry missing expiry: '%s'\n", data);
08665    }
08666    *expiry++ = '\0';
08667 
08668    if (!ast_sockaddr_parse(&p->addr, data, PARSE_PORT_REQUIRE)) {
08669       ast_log(LOG_NOTICE, "IAX/Registry astdb host:port invalid - '%s'\n", data);
08670       return;
08671    }
08672 
08673    p->expiry = atoi(expiry);
08674 
08675    ast_verb(3, "Seeding '%s' at %s for %d\n", p->name,
08676       ast_sockaddr_stringify(&p->addr), p->expiry);
08677 
08678    iax2_poke_peer(p, 0);
08679    if (p->expire > -1) {
08680       if (!ast_sched_thread_del(sched, p->expire)) {
08681          p->expire = -1;
08682          peer_unref(p);
08683       }
08684    }
08685 
08686    ast_devstate_changed(AST_DEVICE_UNKNOWN, "IAX2/%s", p->name); /* Activate notification */
08687 
08688    p->expire = iax2_sched_add(sched, (p->expiry + 10) * 1000, expire_registry, peer_ref(p));
08689    if (p->expire == -1) {
08690       peer_unref(p);
08691    }
08692 
08693    if (iax2_regfunk) {
08694       iax2_regfunk(p->name, 1);
08695    }
08696 
08697    register_peer_exten(p, 1);
08698 }
08699 
08700 /*!
08701  * \pre iaxsl[callno] is locked
08702  *
08703  * \note Since this function calls send_command_final(), the pvt struct for
08704  *       the given call number may disappear while executing this function.
08705  */
08706 static int update_registry(struct sockaddr_in *sin, int callno, char *devtype, int fd, unsigned short refresh)
08707 {
08708    /* Called from IAX thread only, with proper iaxsl lock */
08709    struct iax_ie_data ied = {
08710       .pos = 0,
08711    };
08712    struct iax2_peer *p;
08713    int msgcount;
08714    char data[80];
08715    int version;
08716    const char *peer_name;
08717    int res = -1;
08718    struct ast_sockaddr sockaddr;
08719 
08720    ast_sockaddr_from_sin(&sockaddr, sin);
08721 
08722    peer_name = ast_strdupa(iaxs[callno]->peer);
08723 
08724    /* SLD: Another find_peer call during registration - this time when we are really updating our registration */
08725    ast_mutex_unlock(&iaxsl[callno]);
08726    if (!(p = find_peer(peer_name, 1))) {
08727       ast_mutex_lock(&iaxsl[callno]);
08728       ast_log(LOG_WARNING, "No such peer '%s'\n", peer_name);
08729       return -1;
08730    }
08731    ast_mutex_lock(&iaxsl[callno]);
08732    if (!iaxs[callno])
08733       goto return_unref;
08734 
08735    if (ast_test_flag64((&globalflags), IAX_RTUPDATE) && (ast_test_flag64(p, IAX_TEMPONLY|IAX_RTCACHEFRIENDS))) {
08736       if (sin->sin_addr.s_addr) {
08737          time_t nowtime;
08738          time(&nowtime);
08739          realtime_update_peer(peer_name, &sockaddr, nowtime);
08740       } else {
08741          realtime_update_peer(peer_name, &sockaddr, 0);
08742       }
08743    }
08744 
08745    if (ast_sockaddr_cmp(&p->addr, &sockaddr)) {
08746       if (iax2_regfunk) {
08747          iax2_regfunk(p->name, 1);
08748       }
08749 
08750       /* modify entry in peercnts table as _not_ registered */
08751       peercnt_modify(0, 0, &p->addr);
08752 
08753       /* Stash the IP address from which they registered */
08754       ast_sockaddr_from_sin(&p->addr, sin);
08755 
08756       snprintf(data, sizeof(data), "%s:%d:%d", ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port), p->expiry);
08757       if (!ast_test_flag64(p, IAX_TEMPONLY) && sin->sin_addr.s_addr) {
08758          ast_db_put("IAX/Registry", p->name, data);
08759          ast_verb(3, "Registered IAX2 '%s' (%s) at %s:%d\n", p->name,
08760                    ast_test_flag(&iaxs[callno]->state, IAX_STATE_AUTHENTICATED) ? "AUTHENTICATED" : "UNAUTHENTICATED", ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
08761          manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: IAX2\r\nPeer: IAX2/%s\r\nPeerStatus: Registered\r\n", p->name);
08762          register_peer_exten(p, 1);
08763          ast_devstate_changed(AST_DEVICE_UNKNOWN, "IAX2/%s", p->name); /* Activate notification */
08764       } else if (!ast_test_flag64(p, IAX_TEMPONLY)) {
08765          ast_verb(3, "Unregistered IAX2 '%s' (%s)\n", p->name,
08766                    ast_test_flag(&iaxs[callno]->state, IAX_STATE_AUTHENTICATED) ? "AUTHENTICATED" : "UNAUTHENTICATED");
08767          manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: IAX2\r\nPeer: IAX2/%s\r\nPeerStatus: Unregistered\r\n", p->name);
08768          register_peer_exten(p, 0);
08769          ast_db_del("IAX/Registry", p->name);
08770          ast_devstate_changed(AST_DEVICE_UNAVAILABLE, "IAX2/%s", p->name); /* Activate notification */
08771       }
08772       /* Update the host */
08773       /* Verify that the host is really there */
08774       iax2_poke_peer(p, callno);
08775    }
08776 
08777    /* modify entry in peercnts table as registered */
08778    if (p->maxcallno) {
08779       peercnt_modify(1, p->maxcallno, &p->addr);
08780    }
08781 
08782    /* Make sure our call still exists, an INVAL at the right point may make it go away */
08783    if (!iaxs[callno]) {
08784       res = -1;
08785       goto return_unref;
08786    }
08787 
08788    /* Store socket fd */
08789    p->sockfd = fd;
08790    /* Setup the expiry */
08791    if (p->expire > -1) {
08792       if (!ast_sched_thread_del(sched, p->expire)) {
08793          p->expire = -1;
08794          peer_unref(p);
08795       }
08796    }
08797    /* treat an unspecified refresh interval as the minimum */
08798    if (!refresh)
08799       refresh = min_reg_expire;
08800    if (refresh > max_reg_expire) {
08801       ast_log(LOG_NOTICE, "Restricting registration for peer '%s' to %d seconds (requested %d)\n",
08802          p->name, max_reg_expire, refresh);
08803       p->expiry = max_reg_expire;
08804    } else if (refresh < min_reg_expire) {
08805       ast_log(LOG_NOTICE, "Restricting registration for peer '%s' to %d seconds (requested %d)\n",
08806          p->name, min_reg_expire, refresh);
08807       p->expiry = min_reg_expire;
08808    } else {
08809       p->expiry = refresh;
08810    }
08811    if (p->expiry && sin->sin_addr.s_addr) {
08812       p->expire = iax2_sched_add(sched, (p->expiry + 10) * 1000, expire_registry, peer_ref(p));
08813       if (p->expire == -1)
08814          peer_unref(p);
08815    }
08816    iax_ie_append_str(&ied, IAX_IE_USERNAME, p->name);
08817    iax_ie_append_int(&ied, IAX_IE_DATETIME, iax2_datetime(p->zonetag));
08818    if (sin->sin_addr.s_addr) {
08819       struct sockaddr_in peer_addr;
08820 
08821       ast_sockaddr_to_sin(&p->addr, &peer_addr);
08822 
08823       iax_ie_append_short(&ied, IAX_IE_REFRESH, p->expiry);
08824       iax_ie_append_addr(&ied, IAX_IE_APPARENT_ADDR, &peer_addr);
08825       if (!ast_strlen_zero(p->mailbox)) {
08826          struct ast_event *event;
08827          int new, old;
08828          char *mailbox, *context;
08829 
08830          context = mailbox = ast_strdupa(p->mailbox);
08831          strsep(&context, "@");
08832          if (ast_strlen_zero(context))
08833             context = "default";
08834 
08835          event = ast_event_get_cached(AST_EVENT_MWI,
08836             AST_EVENT_IE_MAILBOX, AST_EVENT_IE_PLTYPE_STR, mailbox,
08837             AST_EVENT_IE_CONTEXT, AST_EVENT_IE_PLTYPE_STR, context,
08838             AST_EVENT_IE_END);
08839          if (event) {
08840             new = ast_event_get_ie_uint(event, AST_EVENT_IE_NEWMSGS);
08841             old = ast_event_get_ie_uint(event, AST_EVENT_IE_OLDMSGS);
08842             ast_event_destroy(event);
08843          } else { /* Fall back on checking the mailbox directly */
08844             ast_app_inboxcount(p->mailbox, &new, &old);
08845          }
08846 
08847          if (new > 255) {
08848             new = 255;
08849          }
08850          if (old > 255) {
08851             old = 255;
08852          }
08853          msgcount = (old << 8) | new;
08854 
08855          iax_ie_append_short(&ied, IAX_IE_MSGCOUNT, msgcount);
08856       }
08857       if (ast_test_flag64(p, IAX_HASCALLERID)) {
08858          iax_ie_append_str(&ied, IAX_IE_CALLING_NUMBER, p->cid_num);
08859          iax_ie_append_str(&ied, IAX_IE_CALLING_NAME, p->cid_name);
08860       }
08861    }
08862    version = iax_check_version(devtype);
08863    if (version) 
08864       iax_ie_append_short(&ied, IAX_IE_FIRMWAREVER, version);
08865 
08866    res = 0;
08867 
08868 return_unref:
08869    peer_unref(p);
08870 
08871    return res ? res : send_command_final(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_REGACK, 0, ied.buf, ied.pos, -1);
08872 }
08873 
08874 static int registry_authrequest(int callno)
08875 {
08876    struct iax_ie_data ied;
08877    struct iax2_peer *p;
08878    char challenge[10];
08879    const char *peer_name;
08880    int sentauthmethod;
08881 
08882    peer_name = ast_strdupa(iaxs[callno]->peer);
08883 
08884    /* SLD: third call to find_peer in registration */
08885    ast_mutex_unlock(&iaxsl[callno]);
08886    if ((p = find_peer(peer_name, 1))) {
08887       last_authmethod = p->authmethods;
08888    }
08889 
08890    ast_mutex_lock(&iaxsl[callno]);
08891    if (!iaxs[callno])
08892       goto return_unref;
08893 
08894    memset(&ied, 0, sizeof(ied));
08895    /* The selection of which delayed reject is sent may leak information,
08896     * if it sets a static response.  For example, if a host is known to only
08897     * use MD5 authentication, then an RSA response would indicate that the
08898     * peer does not exist, and vice-versa.
08899     * Therefore, we use whatever the last peer used (which may vary over the
08900     * course of a server, which should leak minimal information). */
08901    sentauthmethod = p ? p->authmethods : last_authmethod ? last_authmethod : (IAX_AUTH_MD5 | IAX_AUTH_PLAINTEXT);
08902    if (!p) {
08903       iaxs[callno]->authmethods = sentauthmethod;
08904    }
08905    iax_ie_append_short(&ied, IAX_IE_AUTHMETHODS, sentauthmethod);
08906    if (sentauthmethod & (IAX_AUTH_RSA | IAX_AUTH_MD5)) {
08907       /* Build the challenge */
08908       snprintf(challenge, sizeof(challenge), "%d", (int)ast_random());
08909       ast_string_field_set(iaxs[callno], challenge, challenge);
08910       iax_ie_append_str(&ied, IAX_IE_CHALLENGE, iaxs[callno]->challenge);
08911    }
08912    iax_ie_append_str(&ied, IAX_IE_USERNAME, peer_name);
08913 
08914 return_unref:
08915    if (p) {
08916       peer_unref(p);
08917    }
08918 
08919    return iaxs[callno] ? send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_REGAUTH, 0, ied.buf, ied.pos, -1) : -1;
08920 }
08921 
08922 static int registry_rerequest(struct iax_ies *ies, int callno, struct sockaddr_in *sin)
08923 {
08924    struct iax2_registry *reg;
08925    /* Start pessimistic */
08926    struct iax_ie_data ied;
08927    char peer[256] = "";
08928    char challenge[256] = "";
08929    int res;
08930    int authmethods = 0;
08931    if (ies->authmethods)
08932       authmethods = ies->authmethods;
08933    if (ies->username)
08934       ast_copy_string(peer, ies->username, sizeof(peer));
08935    if (ies->challenge)
08936       ast_copy_string(challenge, ies->challenge, sizeof(challenge));
08937    memset(&ied, 0, sizeof(ied));
08938    reg = iaxs[callno]->reg;
08939    if (reg) {
08940       struct sockaddr_in reg_addr;
08941 
08942       ast_sockaddr_to_sin(&reg->addr, &reg_addr);
08943 
08944       if (inaddrcmp(&reg_addr, sin)) {
08945          ast_log(LOG_WARNING, "Received unsolicited registry authenticate request from '%s'\n", ast_inet_ntoa(sin->sin_addr));
08946          return -1;
08947       }
08948       if (ast_strlen_zero(reg->secret)) {
08949          ast_log(LOG_NOTICE, "No secret associated with peer '%s'\n", reg->username);
08950          reg->regstate = REG_STATE_NOAUTH;
08951          return -1;
08952       }
08953       iax_ie_append_str(&ied, IAX_IE_USERNAME, reg->username);
08954       iax_ie_append_short(&ied, IAX_IE_REFRESH, reg->refresh);
08955       if (reg->secret[0] == '[') {
08956          char tmpkey[256];
08957          ast_copy_string(tmpkey, reg->secret + 1, sizeof(tmpkey));
08958          tmpkey[strlen(tmpkey) - 1] = '\0';
08959          res = authenticate(challenge, NULL, tmpkey, authmethods, &ied, sin, NULL);
08960       } else
08961          res = authenticate(challenge, reg->secret, NULL, authmethods, &ied, sin, NULL);
08962       if (!res) {
08963          reg->regstate = REG_STATE_AUTHSENT;
08964          add_empty_calltoken_ie(iaxs[callno], &ied); /* this _MUST_ be the last ie added */
08965          return send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_REGREQ, 0, ied.buf, ied.pos, -1);
08966       } else
08967          return -1;
08968       ast_log(LOG_WARNING, "Registry acknowledge on unknown registery '%s'\n", peer);
08969    } else   
08970       ast_log(LOG_NOTICE, "Can't reregister without a reg\n");
08971    return -1;
08972 }
08973 
08974 static void stop_stuff(int callno)
08975 {
08976    iax2_destroy_helper(iaxs[callno]);
08977 }
08978 
08979 static void __auth_reject(const void *nothing)
08980 {
08981    /* Called from IAX thread only, without iaxs lock */
08982    int callno = (int)(long)(nothing);
08983    struct iax_ie_data ied;
08984    ast_mutex_lock(&iaxsl[callno]);
08985    if (iaxs[callno]) {
08986       memset(&ied, 0, sizeof(ied));
08987       if (iaxs[callno]->authfail == IAX_COMMAND_REGREJ) {
08988          iax_ie_append_str(&ied, IAX_IE_CAUSE, "Registration Refused");
08989          iax_ie_append_byte(&ied, IAX_IE_CAUSECODE, AST_CAUSE_FACILITY_REJECTED);
08990       } else if (iaxs[callno]->authfail == IAX_COMMAND_REJECT) {
08991          iax_ie_append_str(&ied, IAX_IE_CAUSE, "No authority found");
08992          iax_ie_append_byte(&ied, IAX_IE_CAUSECODE, AST_CAUSE_FACILITY_NOT_SUBSCRIBED);
08993       }
08994       send_command_final(iaxs[callno], AST_FRAME_IAX, iaxs[callno]->authfail, 0, ied.buf, ied.pos, -1);
08995    }
08996    ast_mutex_unlock(&iaxsl[callno]);
08997 }
08998 
08999 static int auth_reject(const void *data)
09000 {
09001    int callno = (int)(long)(data);
09002    ast_mutex_lock(&iaxsl[callno]);
09003    if (iaxs[callno])
09004       iaxs[callno]->authid = -1;
09005    ast_mutex_unlock(&iaxsl[callno]);
09006 #ifdef SCHED_MULTITHREADED
09007    if (schedule_action(__auth_reject, data))
09008 #endif      
09009       __auth_reject(data);
09010    return 0;
09011 }
09012 
09013 static int auth_fail(int callno, int failcode)
09014 {
09015    /* Schedule sending the authentication failure in one second, to prevent
09016       guessing */
09017    if (iaxs[callno]) {
09018       iaxs[callno]->authfail = failcode;
09019       if (delayreject) {
09020          iaxs[callno]->authid = iax2_sched_replace(iaxs[callno]->authid, 
09021             sched, 1000, auth_reject, (void *)(long)callno);
09022       } else
09023          auth_reject((void *)(long)callno);
09024    }
09025    return 0;
09026 }
09027 
09028 static void __auto_hangup(const void *nothing)
09029 {
09030    /* Called from IAX thread only, without iaxs lock */
09031    int callno = (int)(long)(nothing);
09032    struct iax_ie_data ied;
09033    ast_mutex_lock(&iaxsl[callno]);
09034    if (iaxs[callno]) {
09035       memset(&ied, 0, sizeof(ied));
09036       iax_ie_append_str(&ied, IAX_IE_CAUSE, "Timeout");
09037       iax_ie_append_byte(&ied, IAX_IE_CAUSECODE, AST_CAUSE_NO_USER_RESPONSE);
09038       send_command_final(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_HANGUP, 0, ied.buf, ied.pos, -1);
09039    }
09040    ast_mutex_unlock(&iaxsl[callno]);
09041 }
09042 
09043 static int auto_hangup(const void *data)
09044 {
09045    int callno = (int)(long)(data);
09046    ast_mutex_lock(&iaxsl[callno]);
09047    if (iaxs[callno]) {
09048       iaxs[callno]->autoid = -1;
09049    }
09050    ast_mutex_unlock(&iaxsl[callno]);
09051 #ifdef SCHED_MULTITHREADED
09052    if (schedule_action(__auto_hangup, data))
09053 #endif      
09054       __auto_hangup(data);
09055    return 0;
09056 }
09057 
09058 static void iax2_dprequest(struct iax2_dpcache *dp, int callno)
09059 {
09060    struct iax_ie_data ied;
09061    /* Auto-hangup with 30 seconds of inactivity */
09062    iaxs[callno]->autoid = iax2_sched_replace(iaxs[callno]->autoid, 
09063       sched, 30000, auto_hangup, (void *)(long)callno);
09064    memset(&ied, 0, sizeof(ied));
09065    iax_ie_append_str(&ied, IAX_IE_CALLED_NUMBER, dp->exten);
09066    send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_DPREQ, 0, ied.buf, ied.pos, -1);
09067    dp->flags |= CACHE_FLAG_TRANSMITTED;
09068 }
09069 
09070 static int iax2_vnak(int callno)
09071 {
09072    return send_command_immediate(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_VNAK, 0, NULL, 0, iaxs[callno]->iseqno);
09073 }
09074 
09075 static void vnak_retransmit(int callno, int last)
09076 {
09077    struct iax_frame *f;
09078 
09079    AST_LIST_TRAVERSE(&frame_queue[callno], f, list) {
09080       /* Send a copy immediately */
09081       if (((unsigned char) (f->oseqno - last) < 128) &&
09082             (f->retries >= 0)) {
09083          send_packet(f);
09084       }
09085    }
09086 }
09087 
09088 static void __iax2_poke_peer_s(const void *data)
09089 {
09090    struct iax2_peer *peer = (struct iax2_peer *)data;
09091    iax2_poke_peer(peer, 0);
09092    peer_unref(peer);
09093 }
09094 
09095 static int iax2_poke_peer_s(const void *data)
09096 {
09097    struct iax2_peer *peer = (struct iax2_peer *)data;
09098    peer->pokeexpire = -1;
09099 #ifdef SCHED_MULTITHREADED
09100    if (schedule_action(__iax2_poke_peer_s, data))
09101 #endif      
09102       __iax2_poke_peer_s(data);
09103    return 0;
09104 }
09105 
09106 static int send_trunk(struct iax2_trunk_peer *tpeer, struct timeval *now)
09107 {
09108    int res = 0;
09109    struct iax_frame *fr;
09110    struct ast_iax2_meta_hdr *meta;
09111    struct ast_iax2_meta_trunk_hdr *mth;
09112    int calls = 0;
09113    
09114    /* Point to frame */
09115    fr = (struct iax_frame *)tpeer->trunkdata;
09116    /* Point to meta data */
09117    meta = (struct ast_iax2_meta_hdr *)fr->afdata;
09118    mth = (struct ast_iax2_meta_trunk_hdr *)meta->data;
09119    if (tpeer->trunkdatalen) {
09120       /* We're actually sending a frame, so fill the meta trunk header and meta header */
09121       meta->zeros = 0;
09122       meta->metacmd = IAX_META_TRUNK;
09123       if (ast_test_flag64(&globalflags, IAX_TRUNKTIMESTAMPS))
09124          meta->cmddata = IAX_META_TRUNK_MINI;
09125       else
09126          meta->cmddata = IAX_META_TRUNK_SUPERMINI;
09127       mth->ts = htonl(calc_txpeerstamp(tpeer, trunkfreq, now));
09128       /* And the rest of the ast_iax2 header */
09129       fr->direction = DIRECTION_OUTGRESS;
09130       fr->retrans = -1;
09131       fr->transfer = 0;
09132       /* Any appropriate call will do */
09133       fr->data = fr->afdata;
09134       fr->datalen = tpeer->trunkdatalen + sizeof(struct ast_iax2_meta_hdr) + sizeof(struct ast_iax2_meta_trunk_hdr);
09135       res = transmit_trunk(fr, &tpeer->addr, tpeer->sockfd);
09136       calls = tpeer->calls;
09137 #if 0
09138       ast_debug(1, "Trunking %d call chunks in %d bytes to %s:%d, ts=%d\n", calls, fr->datalen, ast_inet_ntoa(tpeer->addr.sin_addr), ntohs(tpeer->addr.sin_port), ntohl(mth->ts));
09139 #endif      
09140       /* Reset transmit trunk side data */
09141       tpeer->trunkdatalen = 0;
09142       tpeer->calls = 0;
09143    }
09144    if (res < 0)
09145       return res;
09146    return calls;
09147 }
09148 
09149 static inline int iax2_trunk_expired(struct iax2_trunk_peer *tpeer, struct timeval *now)
09150 {
09151    /* Drop when trunk is about 5 seconds idle */
09152    if (now->tv_sec > tpeer->trunkact.tv_sec + 5) 
09153       return 1;
09154    return 0;
09155 }
09156 
09157 static int timing_read(int *id, int fd, short events, void *cbdata)
09158 {
09159    int res, processed = 0, totalcalls = 0;
09160    struct iax2_trunk_peer *tpeer = NULL, *drop = NULL;
09161    struct timeval now = ast_tvnow();
09162 
09163    if (iaxtrunkdebug)
09164       ast_verbose("Beginning trunk processing. Trunk queue ceiling is %d bytes per host\n", trunkmaxsize);
09165 
09166    if (timer) { 
09167       ast_timer_ack(timer, 1);
09168    }
09169 
09170    /* For each peer that supports trunking... */
09171    AST_LIST_LOCK(&tpeers);
09172    AST_LIST_TRAVERSE_SAFE_BEGIN(&tpeers, tpeer, list) {
09173       processed++;
09174       res = 0;
09175       ast_mutex_lock(&tpeer->lock);
09176       /* We can drop a single tpeer per pass.  That makes all this logic
09177          substantially easier */
09178       if (!drop && iax2_trunk_expired(tpeer, &now)) {
09179          /* Take it out of the list, but don't free it yet, because it
09180             could be in use */
09181          AST_LIST_REMOVE_CURRENT(list);
09182          drop = tpeer;
09183       } else {
09184          res = send_trunk(tpeer, &now);
09185          trunk_timed++; 
09186          if (iaxtrunkdebug)
09187             ast_verbose(" - Trunk peer (%s:%d) has %d call chunk%s in transit, %d bytes backloged and has hit a high water mark of %d bytes\n", ast_inet_ntoa(tpeer->addr.sin_addr), ntohs(tpeer->addr.sin_port), res, (res != 1) ? "s" : "", tpeer->trunkdatalen, tpeer->trunkdataalloc);
09188       }     
09189       totalcalls += res;   
09190       res = 0;
09191       ast_mutex_unlock(&tpeer->lock);
09192    }
09193    AST_LIST_TRAVERSE_SAFE_END;
09194    AST_LIST_UNLOCK(&tpeers);
09195 
09196    if (drop) {
09197       ast_mutex_lock(&drop->lock);
09198       /* Once we have this lock, we're sure nobody else is using it or could use it once we release it, 
09199          because by the time they could get tpeerlock, we've already grabbed it */
09200       ast_debug(1, "Dropping unused iax2 trunk peer '%s:%d'\n", ast_inet_ntoa(drop->addr.sin_addr), ntohs(drop->addr.sin_port));
09201       if (drop->trunkdata) {
09202          ast_free(drop->trunkdata);
09203          drop->trunkdata = NULL;
09204       }
09205       ast_mutex_unlock(&drop->lock);
09206       ast_mutex_destroy(&drop->lock);
09207       ast_free(drop);
09208       
09209    }
09210 
09211    if (iaxtrunkdebug)
09212       ast_verbose("Ending trunk processing with %d peers and %d call chunks processed\n", processed, totalcalls);
09213    iaxtrunkdebug = 0;
09214 
09215    return 1;
09216 }
09217 
09218 struct dpreq_data {
09219    int callno;
09220    char context[AST_MAX_EXTENSION];
09221    char callednum[AST_MAX_EXTENSION];
09222    char *callerid;
09223 };
09224 
09225 static void dp_lookup(int callno, const char *context, const char *callednum, const char *callerid, int skiplock)
09226 {
09227    unsigned short dpstatus = 0;
09228    struct iax_ie_data ied1;
09229    int mm;
09230 
09231    memset(&ied1, 0, sizeof(ied1));
09232    mm = ast_matchmore_extension(NULL, context, callednum, 1, callerid);
09233    /* Must be started */
09234    if (ast_parking_ext_valid(callednum, NULL, context) || ast_exists_extension(NULL, context, callednum, 1, callerid)) {
09235       dpstatus = IAX_DPSTATUS_EXISTS;
09236    } else if (ast_canmatch_extension(NULL, context, callednum, 1, callerid)) {
09237       dpstatus = IAX_DPSTATUS_CANEXIST;
09238    } else {
09239       dpstatus = IAX_DPSTATUS_NONEXISTENT;
09240    }
09241    if (ast_ignore_pattern(context, callednum))
09242       dpstatus |= IAX_DPSTATUS_IGNOREPAT;
09243    if (mm)
09244       dpstatus |= IAX_DPSTATUS_MATCHMORE;
09245    if (!skiplock)
09246       ast_mutex_lock(&iaxsl[callno]);
09247    if (iaxs[callno]) {
09248       iax_ie_append_str(&ied1, IAX_IE_CALLED_NUMBER, callednum);
09249       iax_ie_append_short(&ied1, IAX_IE_DPSTATUS, dpstatus);
09250       iax_ie_append_short(&ied1, IAX_IE_REFRESH, iaxdefaultdpcache);
09251       send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_DPREP, 0, ied1.buf, ied1.pos, -1);
09252    }
09253    if (!skiplock)
09254       ast_mutex_unlock(&iaxsl[callno]);
09255 }
09256 
09257 static void *dp_lookup_thread(void *data)
09258 {
09259    /* Look up for dpreq */
09260    struct dpreq_data *dpr = data;
09261    dp_lookup(dpr->callno, dpr->context, dpr->callednum, dpr->callerid, 0);
09262    if (dpr->callerid)
09263       ast_free(dpr->callerid);
09264    ast_free(dpr);
09265    return NULL;
09266 }
09267 
09268 static void spawn_dp_lookup(int callno, const char *context, const char *callednum, const char *callerid)
09269 {
09270    pthread_t newthread;
09271    struct dpreq_data *dpr;
09272    
09273    if (!(dpr = ast_calloc(1, sizeof(*dpr))))
09274       return;
09275 
09276    dpr->callno = callno;
09277    ast_copy_string(dpr->context, context, sizeof(dpr->context));
09278    ast_copy_string(dpr->callednum, callednum, sizeof(dpr->callednum));
09279    if (callerid)
09280       dpr->callerid = ast_strdup(callerid);
09281    if (ast_pthread_create_detached(&newthread, NULL, dp_lookup_thread, dpr)) {
09282       ast_log(LOG_WARNING, "Unable to start lookup thread!\n");
09283    }
09284 }
09285 
09286 struct iax_dual {
09287    struct ast_channel *chan1;
09288    struct ast_channel *chan2;
09289    char *park_exten;
09290    char *park_context;
09291 };
09292 
09293 static void *iax_park_thread(void *stuff)
09294 {
09295    struct iax_dual *d;
09296    int res;
09297    int ext = 0;
09298 
09299    d = stuff;
09300 
09301    ast_debug(4, "IAX Park: Transferer channel %s, Transferee %s\n",
09302       d->chan2->name, d->chan1->name);
09303 
09304    res = ast_park_call_exten(d->chan1, d->chan2, d->park_exten, d->park_context, 0, &ext);
09305    if (res) {
09306       /* Parking failed. */
09307       ast_hangup(d->chan1);
09308    } else {
09309       ast_log(LOG_NOTICE, "Parked on extension '%d'\n", ext);
09310    }
09311    ast_hangup(d->chan2);
09312 
09313    ast_free(d->park_exten);
09314    ast_free(d->park_context);
09315    ast_free(d);
09316    return NULL;
09317 }
09318 
09319 /*! DO NOT hold any locks while calling iax_park */
09320 static int iax_park(struct ast_channel *chan1, struct ast_channel *chan2, const char *park_exten, const char *park_context)
09321 {
09322    struct iax_dual *d;
09323    struct ast_channel *chan1m, *chan2m;/* Chan2m: The transferer, chan1m: The transferee */
09324    pthread_t th;
09325 
09326    chan1m = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, chan2->accountcode, chan1->exten, chan1->context, chan1->linkedid, chan1->amaflags, "Parking/%s", chan1->name);
09327    chan2m = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, chan2->accountcode, chan2->exten, chan2->context, chan2->linkedid, chan2->amaflags, "IAXPeer/%s", chan2->name);
09328    d = ast_calloc(1, sizeof(*d));
09329    if (!chan1m || !chan2m || !d) {
09330       if (chan1m) {
09331          ast_hangup(chan1m);
09332       }
09333       if (chan2m) {
09334          ast_hangup(chan2m);
09335       }
09336       ast_free(d);
09337       return -1;
09338    }
09339    d->park_exten = ast_strdup(park_exten);
09340    d->park_context = ast_strdup(park_context);
09341    if (!d->park_exten || !d->park_context) {
09342       ast_hangup(chan1m);
09343       ast_hangup(chan2m);
09344       ast_free(d->park_exten);
09345       ast_free(d->park_context);
09346       ast_free(d);
09347       return -1;
09348    }
09349 
09350    /* Make formats okay */
09351    chan1m->readformat = chan1->readformat;
09352    chan1m->writeformat = chan1->writeformat;
09353 
09354    /* Prepare for taking over the channel */
09355    if (ast_channel_masquerade(chan1m, chan1)) {
09356       ast_hangup(chan1m);
09357       ast_hangup(chan2m);
09358       ast_free(d->park_exten);
09359       ast_free(d->park_context);
09360       ast_free(d);
09361       return -1;
09362    }
09363 
09364    /* Setup the extensions and such */
09365    ast_copy_string(chan1m->context, chan1->context, sizeof(chan1m->context));
09366    ast_copy_string(chan1m->exten, chan1->exten, sizeof(chan1m->exten));
09367    chan1m->priority = chan1->priority;
09368 
09369    ast_do_masquerade(chan1m);
09370 
09371    /* We make a clone of the peer channel too, so we can play
09372       back the announcement */
09373 
09374    /* Make formats okay */
09375    chan2m->readformat = chan2->readformat;
09376    chan2m->writeformat = chan2->writeformat;
09377    ast_string_field_set(chan2m, parkinglot, chan2->parkinglot);
09378 
09379    /* Prepare for taking over the channel */
09380    if (ast_channel_masquerade(chan2m, chan2)) {
09381       ast_hangup(chan1m);
09382       ast_hangup(chan2m);
09383       ast_free(d->park_exten);
09384       ast_free(d->park_context);
09385       ast_free(d);
09386       return -1;
09387    }
09388 
09389    /* Setup the extensions and such */
09390    ast_copy_string(chan2m->context, chan2->context, sizeof(chan2m->context));
09391    ast_copy_string(chan2m->exten, chan2->exten, sizeof(chan2m->exten));
09392    chan2m->priority = chan2->priority;
09393 
09394    ast_do_masquerade(chan2m);
09395 
09396    d->chan1 = chan1m;   /* Transferee */
09397    d->chan2 = chan2m;   /* Transferer */
09398    if (ast_pthread_create_detached_background(&th, NULL, iax_park_thread, d) < 0) {
09399       /* Could not start thread */
09400       ast_hangup(chan1m);
09401       ast_hangup(chan2m);
09402       ast_free(d->park_exten);
09403       ast_free(d->park_context);
09404       ast_free(d);
09405       return -1;
09406    }
09407    return 0;
09408 }
09409 
09410 static int check_provisioning(struct sockaddr_in *sin, int sockfd, char *si, unsigned int ver)
09411 {
09412    unsigned int ourver;
09413    char rsi[80];
09414    snprintf(rsi, sizeof(rsi), "si-%s", si);
09415    if (iax_provision_version(&ourver, rsi, 1))
09416       return 0;
09417    ast_debug(1, "Service identifier '%s', we think '%08x', they think '%08x'\n", si, ourver, ver);
09418    if (ourver != ver) 
09419       iax2_provision(sin, sockfd, NULL, rsi, 1);
09420    return 0;
09421 }
09422 
09423 static void construct_rr(struct chan_iax2_pvt *pvt, struct iax_ie_data *iep) 
09424 {
09425    jb_info stats;
09426    jb_getinfo(pvt->jb, &stats);
09427    
09428    memset(iep, 0, sizeof(*iep));
09429 
09430    iax_ie_append_int(iep,IAX_IE_RR_JITTER, stats.jitter);
09431    if(stats.frames_in == 0) stats.frames_in = 1;
09432    iax_ie_append_int(iep,IAX_IE_RR_LOSS, ((0xff & (stats.losspct/1000)) << 24 | (stats.frames_lost & 0x00ffffff)));
09433    iax_ie_append_int(iep,IAX_IE_RR_PKTS, stats.frames_in);
09434    iax_ie_append_short(iep,IAX_IE_RR_DELAY, stats.current - stats.min);
09435    iax_ie_append_int(iep,IAX_IE_RR_DROPPED, stats.frames_dropped);
09436    iax_ie_append_int(iep,IAX_IE_RR_OOO, stats.frames_ooo);
09437 }
09438 
09439 static void save_rr(struct iax_frame *fr, struct iax_ies *ies) 
09440 {
09441    iaxs[fr->callno]->remote_rr.jitter = ies->rr_jitter;
09442    iaxs[fr->callno]->remote_rr.losspct = ies->rr_loss >> 24;
09443    iaxs[fr->callno]->remote_rr.losscnt = ies->rr_loss & 0xffffff;
09444    iaxs[fr->callno]->remote_rr.packets = ies->rr_pkts;
09445    iaxs[fr->callno]->remote_rr.delay = ies->rr_delay;
09446    iaxs[fr->callno]->remote_rr.dropped = ies->rr_dropped;
09447    iaxs[fr->callno]->remote_rr.ooo = ies->rr_ooo;
09448 }
09449 
09450 static void save_osptoken(struct iax_frame *fr, struct iax_ies *ies) 
09451 {
09452    int i;
09453    unsigned int length, offset = 0;
09454    char full_osptoken[IAX_MAX_OSPBUFF_SIZE];
09455 
09456    for (i = 0; i < IAX_MAX_OSPBLOCK_NUM; i++) {
09457       length = ies->ospblocklength[i];
09458       if (length != 0) {
09459          if (length > IAX_MAX_OSPBLOCK_SIZE) {
09460             /* OSP token block length wrong, clear buffer */
09461             offset = 0;
09462             break;
09463          } else {
09464             memcpy(full_osptoken + offset, ies->osptokenblock[i], length);
09465             offset += length;
09466          }
09467       } else {
09468          break;
09469       }
09470    }
09471    *(full_osptoken + offset) = '\0';
09472    if (strlen(full_osptoken) != offset) {
09473       /* OSP token length wrong, clear buffer */
09474       *full_osptoken = '\0';
09475    }
09476 
09477    ast_string_field_set(iaxs[fr->callno], osptoken, full_osptoken);
09478 }
09479 
09480 static void log_jitterstats(unsigned short callno)
09481 {
09482    int localjitter = -1, localdelay = 0, locallost = -1, locallosspct = -1, localdropped = 0, localooo = -1, localpackets = -1;
09483    jb_info jbinfo;
09484 
09485    ast_mutex_lock(&iaxsl[callno]);
09486    if (iaxs[callno] && iaxs[callno]->owner && iaxs[callno]->owner->name) {
09487       if(ast_test_flag64(iaxs[callno], IAX_USEJITTERBUF)) {
09488          jb_getinfo(iaxs[callno]->jb, &jbinfo);
09489          localjitter = jbinfo.jitter;
09490          localdelay = jbinfo.current - jbinfo.min;
09491          locallost = jbinfo.frames_lost;
09492          locallosspct = jbinfo.losspct/1000;
09493          localdropped = jbinfo.frames_dropped;
09494          localooo = jbinfo.frames_ooo;
09495          localpackets = jbinfo.frames_in;
09496       }
09497       ast_debug(3, "JB STATS:%s ping=%d ljitterms=%d ljbdelayms=%d ltotlost=%d lrecentlosspct=%d ldropped=%d looo=%d lrecvd=%d rjitterms=%d rjbdelayms=%d rtotlost=%d rrecentlosspct=%d rdropped=%d rooo=%d rrecvd=%d\n",
09498          iaxs[callno]->owner->name,
09499          iaxs[callno]->pingtime,
09500          localjitter,
09501          localdelay,
09502          locallost,
09503          locallosspct,
09504          localdropped,
09505          localooo,
09506          localpackets,
09507          iaxs[callno]->remote_rr.jitter,
09508          iaxs[callno]->remote_rr.delay,
09509          iaxs[callno]->remote_rr.losscnt,
09510          iaxs[callno]->remote_rr.losspct/1000,
09511          iaxs[callno]->remote_rr.dropped,
09512          iaxs[callno]->remote_rr.ooo,
09513          iaxs[callno]->remote_rr.packets);
09514       manager_event(EVENT_FLAG_REPORTING, "JitterBufStats", "Owner: %s\r\nPing: %d\r\nLocalJitter: %d\r\nLocalJBDelay: %d\r\nLocalTotalLost: %d\r\nLocalLossPercent: %d\r\nLocalDropped: %d\r\nLocalooo: %d\r\nLocalReceived: %d\r\nRemoteJitter: %d\r\nRemoteJBDelay: %d\r\nRemoteTotalLost: %d\r\nRemoteLossPercent: %d\r\nRemoteDropped: %d\r\nRemoteooo: %d\r\nRemoteReceived: %d\r\n",
09515          iaxs[callno]->owner->name,
09516          iaxs[callno]->pingtime,
09517          localjitter,
09518          localdelay,
09519          locallost,
09520          locallosspct,
09521          localdropped,
09522          localooo,
09523          localpackets,
09524          iaxs[callno]->remote_rr.jitter,
09525          iaxs[callno]->remote_rr.delay,
09526          iaxs[callno]->remote_rr.losscnt,
09527          iaxs[callno]->remote_rr.losspct/1000,
09528          iaxs[callno]->remote_rr.dropped,
09529          iaxs[callno]->remote_rr.ooo,
09530          iaxs[callno]->remote_rr.packets);
09531    }
09532    ast_mutex_unlock(&iaxsl[callno]);
09533 }
09534 
09535 static int socket_process(struct iax2_thread *thread);
09536 
09537 /*!
09538  * \brief Handle any deferred full frames for this thread
09539  */
09540 static void handle_deferred_full_frames(struct iax2_thread *thread)
09541 {
09542    struct iax2_pkt_buf *pkt_buf;
09543 
09544    ast_mutex_lock(&thread->lock);
09545 
09546    while ((pkt_buf = AST_LIST_REMOVE_HEAD(&thread->full_frames, entry))) {
09547       ast_mutex_unlock(&thread->lock);
09548 
09549       thread->buf = pkt_buf->buf;
09550       thread->buf_len = pkt_buf->len;
09551       thread->buf_size = pkt_buf->len + 1;
09552       
09553       socket_process(thread);
09554 
09555       thread->buf = NULL;
09556       ast_free(pkt_buf);
09557 
09558       ast_mutex_lock(&thread->lock);
09559    }
09560 
09561    ast_mutex_unlock(&thread->lock);
09562 }
09563 
09564 /*!
09565  * \brief Queue the last read full frame for processing by a certain thread
09566  *
09567  * If there are already any full frames queued, they are sorted
09568  * by sequence number.
09569  */
09570 static void defer_full_frame(struct iax2_thread *from_here, struct iax2_thread *to_here)
09571 {
09572    struct iax2_pkt_buf *pkt_buf, *cur_pkt_buf;
09573    struct ast_iax2_full_hdr *fh, *cur_fh;
09574 
09575    if (!(pkt_buf = ast_calloc(1, sizeof(*pkt_buf) + from_here->buf_len)))
09576       return;
09577 
09578    pkt_buf->len = from_here->buf_len;
09579    memcpy(pkt_buf->buf, from_here->buf, pkt_buf->len);
09580 
09581    fh = (struct ast_iax2_full_hdr *) pkt_buf->buf;
09582    ast_mutex_lock(&to_here->lock);
09583    AST_LIST_TRAVERSE_SAFE_BEGIN(&to_here->full_frames, cur_pkt_buf, entry) {
09584       cur_fh = (struct ast_iax2_full_hdr *) cur_pkt_buf->buf;
09585       if (fh->oseqno < cur_fh->oseqno) {
09586          AST_LIST_INSERT_BEFORE_CURRENT(pkt_buf, entry);
09587          break;
09588       }
09589    }
09590    AST_LIST_TRAVERSE_SAFE_END
09591 
09592    if (!cur_pkt_buf)
09593       AST_LIST_INSERT_TAIL(&to_here->full_frames, pkt_buf, entry);
09594    
09595    ast_mutex_unlock(&to_here->lock);
09596 }
09597 
09598 static int socket_read(int *id, int fd, short events, void *cbdata)
09599 {
09600    struct iax2_thread *thread;
09601    socklen_t len;
09602    time_t t;
09603    static time_t last_errtime = 0;
09604    struct ast_iax2_full_hdr *fh;
09605 
09606    if (!(thread = find_idle_thread())) {
09607       time(&t);
09608       if (t != last_errtime)
09609          ast_debug(1, "Out of idle IAX2 threads for I/O, pausing!\n");
09610       last_errtime = t;
09611       usleep(1);
09612       return 1;
09613    }
09614 
09615    len = sizeof(thread->iosin);
09616    thread->iofd = fd;
09617    thread->buf_len = recvfrom(fd, thread->readbuf, sizeof(thread->readbuf), 0, (struct sockaddr *) &thread->iosin, &len);
09618    thread->buf_size = sizeof(thread->readbuf);
09619    thread->buf = thread->readbuf;
09620    if (thread->buf_len < 0) {
09621       if (errno != ECONNREFUSED && errno != EAGAIN)
09622          ast_log(LOG_WARNING, "Error: %s\n", strerror(errno));
09623       handle_error();
09624       thread->iostate = IAX_IOSTATE_IDLE;
09625       signal_condition(&thread->lock, &thread->cond);
09626       return 1;
09627    }
09628    if (test_losspct && ((100.0 * ast_random() / (RAND_MAX + 1.0)) < test_losspct)) { /* simulate random loss condition */
09629       thread->iostate = IAX_IOSTATE_IDLE;
09630       signal_condition(&thread->lock, &thread->cond);
09631       return 1;
09632    }
09633    
09634    /* Determine if this frame is a full frame; if so, and any thread is currently
09635       processing a full frame for the same callno from this peer, then drop this
09636       frame (and the peer will retransmit it) */
09637    fh = (struct ast_iax2_full_hdr *) thread->buf;
09638    if (ntohs(fh->scallno) & IAX_FLAG_FULL) {
09639       struct iax2_thread *cur = NULL;
09640       uint16_t callno = ntohs(fh->scallno) & ~IAX_FLAG_FULL;
09641       
09642       AST_LIST_LOCK(&active_list);
09643       AST_LIST_TRAVERSE(&active_list, cur, list) {
09644          if ((cur->ffinfo.callno == callno) &&
09645              !inaddrcmp(&cur->ffinfo.sin, &thread->iosin))
09646             break;
09647       }
09648       if (cur) {
09649          /* we found another thread processing a full frame for this call,
09650             so queue it up for processing later. */
09651          defer_full_frame(thread, cur);
09652          AST_LIST_UNLOCK(&active_list);
09653          thread->iostate = IAX_IOSTATE_IDLE;
09654          signal_condition(&thread->lock, &thread->cond);
09655          return 1;
09656       } else {
09657          /* this thread is going to process this frame, so mark it */
09658          thread->ffinfo.callno = callno;
09659          memcpy(&thread->ffinfo.sin, &thread->iosin, sizeof(thread->ffinfo.sin));
09660          thread->ffinfo.type = fh->type;
09661          thread->ffinfo.csub = fh->csub;
09662          AST_LIST_INSERT_HEAD(&active_list, thread, list);
09663       }
09664       AST_LIST_UNLOCK(&active_list);
09665    }
09666    
09667    /* Mark as ready and send on its way */
09668    thread->iostate = IAX_IOSTATE_READY;
09669 #ifdef DEBUG_SCHED_MULTITHREAD
09670    ast_copy_string(thread->curfunc, "socket_process", sizeof(thread->curfunc));
09671 #endif
09672    signal_condition(&thread->lock, &thread->cond);
09673 
09674    return 1;
09675 }
09676 
09677 static int socket_process_meta(int packet_len, struct ast_iax2_meta_hdr *meta, struct sockaddr_in *sin, int sockfd,
09678    struct iax_frame *fr)
09679 {
09680    unsigned char metatype;
09681    struct ast_iax2_meta_trunk_mini *mtm;
09682    struct ast_iax2_meta_trunk_hdr *mth;
09683    struct ast_iax2_meta_trunk_entry *mte;
09684    struct iax2_trunk_peer *tpeer;
09685    unsigned int ts;
09686    void *ptr;
09687    struct timeval rxtrunktime;
09688    struct ast_frame f = { 0, };
09689 
09690    if (packet_len < sizeof(*meta)) {
09691       ast_log(LOG_WARNING, "Rejecting packet from '%s.%d' that is flagged as a meta frame but is too short\n", 
09692          ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
09693       return 1;
09694    }
09695 
09696    if (meta->metacmd != IAX_META_TRUNK)
09697       return 1;
09698 
09699    if (packet_len < (sizeof(*meta) + sizeof(*mth))) {
09700       ast_log(LOG_WARNING, "midget meta trunk packet received (%d of %d min)\n", packet_len,
09701          (int) (sizeof(*meta) + sizeof(*mth)));
09702       return 1;
09703    }
09704    mth = (struct ast_iax2_meta_trunk_hdr *)(meta->data);
09705    ts = ntohl(mth->ts);
09706    metatype = meta->cmddata;
09707    packet_len -= (sizeof(*meta) + sizeof(*mth));
09708    ptr = mth->data;
09709    tpeer = find_tpeer(sin, sockfd);
09710    if (!tpeer) {
09711       ast_log(LOG_WARNING, "Unable to accept trunked packet from '%s:%d': No matching peer\n", 
09712          ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
09713       return 1;
09714    }
09715    tpeer->trunkact = ast_tvnow();
09716    if (!ts || ast_tvzero(tpeer->rxtrunktime))
09717       tpeer->rxtrunktime = tpeer->trunkact;
09718    rxtrunktime = tpeer->rxtrunktime;
09719    ast_mutex_unlock(&tpeer->lock);
09720    while (packet_len >= sizeof(*mte)) {
09721       /* Process channels */
09722       unsigned short callno, trunked_ts, len;
09723 
09724       if (metatype == IAX_META_TRUNK_MINI) {
09725          mtm = (struct ast_iax2_meta_trunk_mini *) ptr;
09726          ptr += sizeof(*mtm);
09727          packet_len -= sizeof(*mtm);
09728          len = ntohs(mtm->len);
09729          callno = ntohs(mtm->mini.callno);
09730          trunked_ts = ntohs(mtm->mini.ts);
09731       } else if (metatype == IAX_META_TRUNK_SUPERMINI) {
09732          mte = (struct ast_iax2_meta_trunk_entry *)ptr;
09733          ptr += sizeof(*mte);
09734          packet_len -= sizeof(*mte);
09735          len = ntohs(mte->len);
09736          callno = ntohs(mte->callno);
09737          trunked_ts = 0;
09738       } else {
09739          ast_log(LOG_WARNING, "Unknown meta trunk cmd from '%s:%d': dropping\n", ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
09740          break;
09741       }
09742       /* Stop if we don't have enough data */
09743       if (len > packet_len)
09744          break;
09745       fr->callno = find_callno_locked(callno & ~IAX_FLAG_FULL, 0, sin, NEW_PREVENT, sockfd, 0);
09746       if (!fr->callno)
09747          continue;
09748 
09749       /* If it's a valid call, deliver the contents.  If not, we
09750          drop it, since we don't have a scallno to use for an INVAL */
09751       /* Process as a mini frame */
09752       memset(&f, 0, sizeof(f));
09753       f.frametype = AST_FRAME_VOICE;
09754       if (!iaxs[fr->callno]) {
09755          /* drop it */
09756       } else if (iaxs[fr->callno]->voiceformat == 0) {
09757          ast_log(LOG_WARNING, "Received trunked frame before first full voice frame\n");
09758          iax2_vnak(fr->callno);
09759       } else {
09760          f.subclass.codec = iaxs[fr->callno]->voiceformat;
09761          f.datalen = len;
09762          if (f.datalen >= 0) {
09763             if (f.datalen)
09764                f.data.ptr = ptr;
09765             else
09766                f.data.ptr = NULL;
09767             if (trunked_ts)
09768                fr->ts = (iaxs[fr->callno]->last & 0xFFFF0000L) | (trunked_ts & 0xffff);
09769             else
09770                fr->ts = fix_peerts(&rxtrunktime, fr->callno, ts);
09771             /* Don't pass any packets until we're started */
09772             if (ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED)) {
09773                struct iax_frame *duped_fr;
09774 
09775                /* Common things */
09776                f.src = "IAX2";
09777                f.mallocd = 0;
09778                f.offset = 0;
09779                if (f.datalen && (f.frametype == AST_FRAME_VOICE)) 
09780                   f.samples = ast_codec_get_samples(&f);
09781                else
09782                   f.samples = 0;
09783                fr->outoforder = 0;
09784                iax_frame_wrap(fr, &f);
09785                duped_fr = iaxfrdup2(fr);
09786                if (duped_fr)
09787                   schedule_delivery(duped_fr, 1, 1, &fr->ts);
09788                if (iaxs[fr->callno] && iaxs[fr->callno]->last < fr->ts)
09789                   iaxs[fr->callno]->last = fr->ts;
09790             }
09791          } else {
09792             ast_log(LOG_WARNING, "Datalen < 0?\n");
09793          }
09794       }
09795       ast_mutex_unlock(&iaxsl[fr->callno]);
09796       ptr += len;
09797       packet_len -= len;
09798    }
09799 
09800    return 1;
09801 }
09802 
09803 static int acf_iaxvar_read(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
09804 {
09805    struct ast_datastore *variablestore = ast_channel_datastore_find(chan, &iax2_variable_datastore_info, NULL);
09806    AST_LIST_HEAD(, ast_var_t) *varlist;
09807    struct ast_var_t *var;
09808 
09809    if (!variablestore) {
09810       *buf = '\0';
09811       return 0;
09812    }
09813    varlist = variablestore->data;
09814 
09815    AST_LIST_LOCK(varlist);
09816    AST_LIST_TRAVERSE(varlist, var, entries) {
09817       if (strcmp(var->name, data) == 0) {
09818          ast_copy_string(buf, var->value, len);
09819          break;
09820       }
09821    }
09822    AST_LIST_UNLOCK(varlist);
09823    return 0;
09824 }
09825 
09826 static int acf_iaxvar_write(struct ast_channel *chan, const char *cmd, char *data, const char *value)
09827 {
09828    struct ast_datastore *variablestore = ast_channel_datastore_find(chan, &iax2_variable_datastore_info, NULL);
09829    AST_LIST_HEAD(, ast_var_t) *varlist;
09830    struct ast_var_t *var;
09831 
09832    if (!variablestore) {
09833       variablestore = ast_datastore_alloc(&iax2_variable_datastore_info, NULL);
09834       if (!variablestore) {
09835          ast_log(LOG_ERROR, "Memory allocation error\n");
09836          return -1;
09837       }
09838       varlist = ast_calloc(1, sizeof(*varlist));
09839       if (!varlist) {
09840          ast_log(LOG_ERROR, "Unable to assign new variable '%s'\n", data);
09841          return -1;
09842       }
09843 
09844       AST_LIST_HEAD_INIT(varlist);
09845       variablestore->data = varlist;
09846       variablestore->inheritance = DATASTORE_INHERIT_FOREVER;
09847       ast_channel_datastore_add(chan, variablestore);
09848    } else
09849       varlist = variablestore->data;
09850 
09851    AST_LIST_LOCK(varlist);
09852    AST_LIST_TRAVERSE_SAFE_BEGIN(varlist, var, entries) {
09853       if (strcmp(var->name, data) == 0) {
09854          AST_LIST_REMOVE_CURRENT(entries);
09855          ast_var_delete(var);
09856          break;
09857       }
09858    }
09859    AST_LIST_TRAVERSE_SAFE_END;
09860    var = ast_var_assign(data, value);
09861    if (var)
09862       AST_LIST_INSERT_TAIL(varlist, var, entries);
09863    else
09864       ast_log(LOG_ERROR, "Unable to assign new variable '%s'\n", data);
09865    AST_LIST_UNLOCK(varlist);
09866    return 0;
09867 }
09868 
09869 static struct ast_custom_function iaxvar_function = {
09870    .name = "IAXVAR",
09871    .read = acf_iaxvar_read,
09872    .write = acf_iaxvar_write,
09873 };
09874 
09875 static void set_hangup_source_and_cause(int callno, unsigned char causecode)
09876 {
09877    iax2_lock_owner(callno);
09878    if (iaxs[callno] && iaxs[callno]->owner) {
09879       if (causecode) {
09880          iaxs[callno]->owner->hangupcause = causecode;
09881       }
09882       ast_set_hangupsource(iaxs[callno]->owner, iaxs[callno]->owner->name, 0);
09883       ast_channel_unlock(iaxs[callno]->owner);
09884    }
09885 }
09886 
09887 static int socket_process(struct iax2_thread *thread)
09888 {
09889    struct sockaddr_in sin;
09890    int res;
09891    int updatehistory=1;
09892    int new = NEW_PREVENT;
09893    int dcallno = 0;
09894    char decrypted = 0;
09895    struct ast_iax2_full_hdr *fh = (struct ast_iax2_full_hdr *)thread->buf;
09896    struct ast_iax2_mini_hdr *mh = (struct ast_iax2_mini_hdr *)thread->buf;
09897    struct ast_iax2_meta_hdr *meta = (struct ast_iax2_meta_hdr *)thread->buf;
09898    struct ast_iax2_video_hdr *vh = (struct ast_iax2_video_hdr *)thread->buf;
09899    struct iax_frame *fr;
09900    struct iax_frame *cur;
09901    struct ast_frame f = { 0, };
09902    struct ast_channel *c = NULL;
09903    struct iax2_dpcache *dp;
09904    struct iax2_peer *peer;
09905    struct iax_ies ies;
09906    struct iax_ie_data ied0, ied1;
09907    format_t format;
09908    int fd;
09909    int exists;
09910    int minivid = 0;
09911    char empty[32]="";      /* Safety measure */
09912    struct iax_frame *duped_fr;
09913    char host_pref_buf[128];
09914    char caller_pref_buf[128];
09915    struct ast_codec_pref pref;
09916    char *using_prefs = "mine";
09917 
09918    /* allocate an iax_frame with 4096 bytes of data buffer */
09919    fr = alloca(sizeof(*fr) + 4096);
09920    memset(fr, 0, sizeof(*fr));
09921    fr->afdatalen = 4096; /* From alloca() above */
09922 
09923    /* Copy frequently used parameters to the stack */
09924    res = thread->buf_len;
09925    fd = thread->iofd;
09926    memcpy(&sin, &thread->iosin, sizeof(sin));
09927 
09928    if (res < sizeof(*mh)) {
09929       ast_log(LOG_WARNING, "midget packet received (%d of %d min)\n", res, (int) sizeof(*mh));
09930       return 1;
09931    }
09932    if ((vh->zeros == 0) && (ntohs(vh->callno) & 0x8000)) {
09933       if (res < sizeof(*vh)) {
09934          ast_log(LOG_WARNING, "Rejecting packet from '%s.%d' that is flagged as a video frame but is too short\n", ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
09935          return 1;
09936       }
09937 
09938       /* This is a video frame, get call number */
09939       fr->callno = find_callno(ntohs(vh->callno) & ~0x8000, dcallno, &sin, new, fd, 0);
09940       minivid = 1;
09941    } else if ((meta->zeros == 0) && !(ntohs(meta->metacmd) & 0x8000))
09942       return socket_process_meta(res, meta, &sin, fd, fr);
09943 
09944 #ifdef DEBUG_SUPPORT
09945    if (res >= sizeof(*fh))
09946       iax_outputframe(NULL, fh, 1, &sin, res - sizeof(*fh));
09947 #endif
09948    if (ntohs(mh->callno) & IAX_FLAG_FULL) {
09949       if (res < sizeof(*fh)) {
09950          ast_log(LOG_WARNING, "Rejecting packet from '%s.%d' that is flagged as a full frame but is too short\n", ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
09951          return 1;
09952       }
09953 
09954       /* Get the destination call number */
09955       dcallno = ntohs(fh->dcallno) & ~IAX_FLAG_RETRANS;
09956 
09957 
09958       /* check to make sure this full frame isn't encrypted before we attempt
09959        * to look inside of it. If it is encrypted, decrypt it first. Its ok if the
09960        * callno is not found here, that just means one hasn't been allocated for
09961        * this connection yet. */
09962       if ((dcallno != 1) && (fr->callno = find_callno(ntohs(mh->callno) & ~IAX_FLAG_FULL, dcallno, &sin, NEW_PREVENT, fd, 1))) {
09963          ast_mutex_lock(&iaxsl[fr->callno]);
09964          if (iaxs[fr->callno] && ast_test_flag64(iaxs[fr->callno], IAX_ENCRYPTED)) {
09965             if (decrypt_frame(fr->callno, fh, &f, &res)) {
09966                ast_log(LOG_NOTICE, "Packet Decrypt Failed!\n");
09967                ast_mutex_unlock(&iaxsl[fr->callno]);
09968                return 1;
09969             }
09970             decrypted = 1;
09971          }
09972          ast_mutex_unlock(&iaxsl[fr->callno]);
09973       }
09974 
09975       /* Retrieve the type and subclass */
09976       f.frametype = fh->type;
09977       if (f.frametype == AST_FRAME_VIDEO) {
09978          f.subclass.codec = uncompress_subclass(fh->csub & ~0x40) | ((fh->csub >> 6) & 0x1);
09979       } else if (f.frametype == AST_FRAME_VOICE) {
09980          f.subclass.codec = uncompress_subclass(fh->csub);
09981       } else {
09982          f.subclass.integer = uncompress_subclass(fh->csub);
09983       }
09984 
09985       /* Deal with POKE/PONG without allocating a callno */
09986       if (f.frametype == AST_FRAME_IAX && f.subclass.integer == IAX_COMMAND_POKE) {
09987          /* Reply back with a PONG, but don't care about the result. */
09988          send_apathetic_reply(1, ntohs(fh->scallno), &sin, IAX_COMMAND_PONG, ntohl(fh->ts), fh->iseqno + 1, fd, NULL);
09989          return 1;
09990       } else if (f.frametype == AST_FRAME_IAX && f.subclass.integer == IAX_COMMAND_ACK && dcallno == 1) {
09991          /* Ignore */
09992          return 1;
09993       }
09994 
09995       f.datalen = res - sizeof(*fh);
09996       if (f.datalen) {
09997          if (f.frametype == AST_FRAME_IAX) {
09998             if (iax_parse_ies(&ies, thread->buf + sizeof(struct ast_iax2_full_hdr), f.datalen)) {
09999                ast_log(LOG_WARNING, "Undecodable frame received from '%s'\n", ast_inet_ntoa(sin.sin_addr));
10000                ast_variables_destroy(ies.vars);
10001                return 1;
10002             }
10003             f.data.ptr = NULL;
10004             f.datalen = 0;
10005          } else {
10006             f.data.ptr = thread->buf + sizeof(struct ast_iax2_full_hdr);
10007             memset(&ies, 0, sizeof(ies));
10008          }
10009       } else {
10010          if (f.frametype == AST_FRAME_IAX)
10011             f.data.ptr = NULL;
10012          else
10013             f.data.ptr = empty;
10014          memset(&ies, 0, sizeof(ies));
10015       }
10016 
10017       if (!dcallno && iax2_allow_new(f.frametype, f.subclass.integer, 1)) {
10018          /* only set NEW_ALLOW if calltoken checks out */
10019          if (handle_call_token(fh, &ies, &sin, fd)) {
10020             ast_variables_destroy(ies.vars);
10021             return 1;
10022          }
10023 
10024          if (ies.calltoken && ies.calltokendata) {
10025             /* if we've gotten this far, and the calltoken ie data exists,
10026              * then calltoken validation _MUST_ have taken place.  If calltoken
10027              * data is provided, it is always validated reguardless of any
10028              * calltokenoptional or requirecalltoken options */
10029             new = NEW_ALLOW_CALLTOKEN_VALIDATED;
10030          } else {
10031             new = NEW_ALLOW;
10032          }
10033       }
10034    } else {
10035       /* Don't know anything about it yet */
10036       f.frametype = AST_FRAME_NULL;
10037       f.subclass.integer = 0;
10038       memset(&ies, 0, sizeof(ies));
10039    }
10040 
10041    if (!fr->callno) {
10042       int check_dcallno = 0;
10043 
10044       /*
10045        * We enforce accurate destination call numbers for ACKs.  This forces the other
10046        * end to know the destination call number before call setup can complete.
10047        *
10048        * Discussed in the following thread:
10049        *    http://lists.digium.com/pipermail/asterisk-dev/2008-May/033217.html 
10050        */
10051 
10052       if ((ntohs(mh->callno) & IAX_FLAG_FULL) && ((f.frametype == AST_FRAME_IAX) && (f.subclass.integer == IAX_COMMAND_ACK))) {
10053          check_dcallno = 1;
10054       }
10055 
10056       if (!(fr->callno = find_callno(ntohs(mh->callno) & ~IAX_FLAG_FULL, dcallno, &sin, new, fd, check_dcallno))) {
10057          if (f.frametype == AST_FRAME_IAX && f.subclass.integer == IAX_COMMAND_NEW) {
10058             send_apathetic_reply(1, ntohs(fh->scallno), &sin, IAX_COMMAND_REJECT, ntohl(fh->ts), fh->iseqno + 1, fd, NULL);
10059          } else if (f.frametype == AST_FRAME_IAX && (f.subclass.integer == IAX_COMMAND_REGREQ || f.subclass.integer == IAX_COMMAND_REGREL)) {
10060             send_apathetic_reply(1, ntohs(fh->scallno), &sin, IAX_COMMAND_REGREJ, ntohl(fh->ts), fh->iseqno + 1, fd, NULL);
10061          }
10062          ast_variables_destroy(ies.vars);
10063          return 1;
10064       }
10065    }
10066 
10067    if (fr->callno > 0)
10068       ast_mutex_lock(&iaxsl[fr->callno]);
10069 
10070    if (!fr->callno || !iaxs[fr->callno]) {
10071       /* A call arrived for a nonexistent destination.  Unless it's an "inval"
10072          frame, reply with an inval */
10073       if (ntohs(mh->callno) & IAX_FLAG_FULL) {
10074          /* We can only raw hangup control frames */
10075          if (((f.subclass.integer != IAX_COMMAND_INVAL) &&
10076              (f.subclass.integer != IAX_COMMAND_TXCNT) &&
10077              (f.subclass.integer != IAX_COMMAND_TXACC) &&
10078              (f.subclass.integer != IAX_COMMAND_FWDOWNL))||
10079              (f.frametype != AST_FRAME_IAX))
10080             raw_hangup(&sin, ntohs(fh->dcallno) & ~IAX_FLAG_RETRANS, ntohs(mh->callno) & ~IAX_FLAG_FULL,
10081             fd);
10082       }
10083       if (fr->callno > 0) 
10084          ast_mutex_unlock(&iaxsl[fr->callno]);
10085       ast_variables_destroy(ies.vars);
10086       return 1;
10087    }
10088    if (ast_test_flag64(iaxs[fr->callno], IAX_ENCRYPTED) && !decrypted) {
10089       if (decrypt_frame(fr->callno, fh, &f, &res)) {
10090          ast_log(LOG_NOTICE, "Packet Decrypt Failed!\n");
10091          ast_variables_destroy(ies.vars);
10092          ast_mutex_unlock(&iaxsl[fr->callno]);
10093          return 1;
10094       }
10095       decrypted = 1;
10096    }
10097 
10098 #ifdef DEBUG_SUPPORT
10099    if (decrypted) {
10100       iax_outputframe(NULL, fh, 3, &sin, res - sizeof(*fh));
10101    }
10102 #endif
10103 
10104 
10105    /* count this frame */
10106    iaxs[fr->callno]->frames_received++;
10107 
10108    if (!inaddrcmp(&sin, &iaxs[fr->callno]->addr) && !minivid &&
10109       f.subclass.integer != IAX_COMMAND_TXCNT &&      /* for attended transfer */
10110       f.subclass.integer != IAX_COMMAND_TXACC) {      /* for attended transfer */
10111       unsigned short new_peercallno;
10112       
10113       new_peercallno = (unsigned short) (ntohs(mh->callno) & ~IAX_FLAG_FULL);
10114       if (new_peercallno && new_peercallno != iaxs[fr->callno]->peercallno) {
10115          if (iaxs[fr->callno]->peercallno) {
10116             remove_by_peercallno(iaxs[fr->callno]);
10117          }
10118          iaxs[fr->callno]->peercallno = new_peercallno;
10119          store_by_peercallno(iaxs[fr->callno]);
10120       }
10121    }
10122    if (ntohs(mh->callno) & IAX_FLAG_FULL) {
10123       if (iaxdebug)
10124          ast_debug(1, "Received packet %d, (%d, %u)\n", fh->oseqno, f.frametype, f.subclass.integer);
10125       /* Check if it's out of order (and not an ACK or INVAL) */
10126       fr->oseqno = fh->oseqno;
10127       fr->iseqno = fh->iseqno;
10128       fr->ts = ntohl(fh->ts);
10129 #ifdef IAXTESTS
10130       if (test_resync) {
10131          ast_debug(1, "Simulating frame ts resync, was %u now %u\n", fr->ts, fr->ts + test_resync);
10132          fr->ts += test_resync;
10133       }
10134 #endif /* IAXTESTS */
10135 #if 0
10136       if ( (ntohs(fh->dcallno) & IAX_FLAG_RETRANS) ||
10137            ( (f.frametype != AST_FRAME_VOICE) && ! (f.frametype == AST_FRAME_IAX &&
10138                         (f.subclass == IAX_COMMAND_NEW ||
10139                          f.subclass == IAX_COMMAND_AUTHREQ ||
10140                          f.subclass == IAX_COMMAND_ACCEPT ||
10141                          f.subclass == IAX_COMMAND_REJECT))      ) )
10142 #endif
10143       if ((ntohs(fh->dcallno) & IAX_FLAG_RETRANS) || (f.frametype != AST_FRAME_VOICE))
10144          updatehistory = 0;
10145       if ((iaxs[fr->callno]->iseqno != fr->oseqno) &&
10146          (iaxs[fr->callno]->iseqno ||
10147             ((f.subclass.integer != IAX_COMMAND_TXCNT) &&
10148             (f.subclass.integer != IAX_COMMAND_TXREADY) &&     /* for attended transfer */
10149             (f.subclass.integer != IAX_COMMAND_TXREL) &&    /* for attended transfer */
10150             (f.subclass.integer != IAX_COMMAND_UNQUELCH ) &&   /* for attended transfer */
10151             (f.subclass.integer != IAX_COMMAND_TXACC)) ||
10152             (f.frametype != AST_FRAME_IAX))) {
10153          if (
10154           ((f.subclass.integer != IAX_COMMAND_ACK) &&
10155            (f.subclass.integer != IAX_COMMAND_INVAL) &&
10156            (f.subclass.integer != IAX_COMMAND_TXCNT) &&
10157            (f.subclass.integer != IAX_COMMAND_TXREADY) &&      /* for attended transfer */
10158            (f.subclass.integer != IAX_COMMAND_TXREL) &&     /* for attended transfer */
10159            (f.subclass.integer != IAX_COMMAND_UNQUELCH ) && /* for attended transfer */
10160            (f.subclass.integer != IAX_COMMAND_TXACC) &&
10161            (f.subclass.integer != IAX_COMMAND_VNAK)) ||
10162            (f.frametype != AST_FRAME_IAX)) {
10163             /* If it's not an ACK packet, it's out of order. */
10164             ast_debug(1, "Packet arrived out of order (expecting %d, got %d) (frametype = %d, subclass = %d)\n", 
10165                iaxs[fr->callno]->iseqno, fr->oseqno, f.frametype, f.subclass.integer);
10166             /* Check to see if we need to request retransmission,
10167              * and take sequence number wraparound into account */
10168             if ((unsigned char) (iaxs[fr->callno]->iseqno - fr->oseqno) < 128) {
10169                /* If we've already seen it, ack it XXX There's a border condition here XXX */
10170                if ((f.frametype != AST_FRAME_IAX) || 
10171                      ((f.subclass.integer != IAX_COMMAND_ACK) && (f.subclass.integer != IAX_COMMAND_INVAL))) {
10172                   ast_debug(1, "Acking anyway\n");
10173                   /* XXX Maybe we should handle its ack to us, but then again, it's probably outdated anyway, and if
10174                      we have anything to send, we'll retransmit and get an ACK back anyway XXX */
10175                   send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
10176                }
10177             } else {
10178                /* Send a VNAK requesting retransmission */
10179                iax2_vnak(fr->callno);
10180             }
10181             ast_variables_destroy(ies.vars);
10182             ast_mutex_unlock(&iaxsl[fr->callno]);
10183             return 1;
10184          }
10185       } else {
10186          /* Increment unless it's an ACK or VNAK */
10187          if (((f.subclass.integer != IAX_COMMAND_ACK) &&
10188              (f.subclass.integer != IAX_COMMAND_INVAL) &&
10189              (f.subclass.integer != IAX_COMMAND_TXCNT) &&
10190              (f.subclass.integer != IAX_COMMAND_TXACC) &&
10191             (f.subclass.integer != IAX_COMMAND_VNAK)) ||
10192              (f.frametype != AST_FRAME_IAX))
10193             iaxs[fr->callno]->iseqno++;
10194       }
10195       /* Ensure text frames are NULL-terminated */
10196       if (f.frametype == AST_FRAME_TEXT && thread->buf[res - 1] != '\0') {
10197          if (res < thread->buf_size)
10198             thread->buf[res++] = '\0';
10199          else /* Trims one character from the text message, but that's better than overwriting the end of the buffer. */
10200             thread->buf[res - 1] = '\0';
10201       }
10202 
10203       /* Handle implicit ACKing unless this is an INVAL, and only if this is 
10204          from the real peer, not the transfer peer */
10205       if (!inaddrcmp(&sin, &iaxs[fr->callno]->addr) && 
10206           ((f.subclass.integer != IAX_COMMAND_INVAL) ||
10207            (f.frametype != AST_FRAME_IAX))) {
10208          unsigned char x;
10209          int call_to_destroy;
10210          /* First we have to qualify that the ACKed value is within our window */
10211          if (iaxs[fr->callno]->rseqno >= iaxs[fr->callno]->oseqno || (fr->iseqno >= iaxs[fr->callno]->rseqno && fr->iseqno < iaxs[fr->callno]->oseqno))
10212             x = fr->iseqno;
10213          else 
10214             x = iaxs[fr->callno]->oseqno;
10215          if ((x != iaxs[fr->callno]->oseqno) || (iaxs[fr->callno]->oseqno == fr->iseqno)) {
10216             /* The acknowledgement is within our window.  Time to acknowledge everything
10217                that it says to */
10218             for (x=iaxs[fr->callno]->rseqno; x != fr->iseqno; x++) {
10219                /* Ack the packet with the given timestamp */
10220                if (iaxdebug)
10221                   ast_debug(1, "Cancelling transmission of packet %d\n", x);
10222                call_to_destroy = 0;
10223                AST_LIST_TRAVERSE(&frame_queue[fr->callno], cur, list) {
10224                   /* If it's our call, and our timestamp, mark -1 retries */
10225                   if (x == cur->oseqno) {
10226                      cur->retries = -1;
10227                      /* Destroy call if this is the end */
10228                      if (cur->final)
10229                         call_to_destroy = fr->callno;
10230                   }
10231                }
10232                if (call_to_destroy) {
10233                   if (iaxdebug)
10234                      ast_debug(1, "Really destroying %d, having been acked on final message\n", call_to_destroy);
10235                   ast_mutex_lock(&iaxsl[call_to_destroy]);
10236                   iax2_destroy(call_to_destroy);
10237                   ast_mutex_unlock(&iaxsl[call_to_destroy]);
10238                }
10239             }
10240             /* Note how much we've received acknowledgement for */
10241             if (iaxs[fr->callno])
10242                iaxs[fr->callno]->rseqno = fr->iseqno;
10243             else {
10244                /* Stop processing now */
10245                ast_variables_destroy(ies.vars);
10246                ast_mutex_unlock(&iaxsl[fr->callno]);
10247                return 1;
10248             }
10249          } else {
10250             ast_debug(1, "Received iseqno %d not within window %d->%d\n", fr->iseqno, iaxs[fr->callno]->rseqno, iaxs[fr->callno]->oseqno);
10251          }
10252       }
10253       if (inaddrcmp(&sin, &iaxs[fr->callno]->addr) && 
10254          ((f.frametype != AST_FRAME_IAX) || 
10255           ((f.subclass.integer != IAX_COMMAND_TXACC) &&
10256            (f.subclass.integer != IAX_COMMAND_TXCNT)))) {
10257          /* Only messages we accept from a transfer host are TXACC and TXCNT */
10258          ast_variables_destroy(ies.vars);
10259          ast_mutex_unlock(&iaxsl[fr->callno]);
10260          return 1;
10261       }
10262 
10263       /* when we receive the first full frame for a new incoming channel,
10264          it is safe to start the PBX on the channel because we have now
10265          completed a 3-way handshake with the peer */
10266       if ((f.frametype == AST_FRAME_VOICE) ||
10267           (f.frametype == AST_FRAME_VIDEO) ||
10268           (f.frametype == AST_FRAME_IAX)) {
10269          if (ast_test_flag64(iaxs[fr->callno], IAX_DELAYPBXSTART)) {
10270             ast_clear_flag64(iaxs[fr->callno], IAX_DELAYPBXSTART);
10271             if (!ast_iax2_new(fr->callno, AST_STATE_RING, iaxs[fr->callno]->chosenformat, NULL)) {
10272                ast_variables_destroy(ies.vars);
10273                ast_mutex_unlock(&iaxsl[fr->callno]);
10274                return 1;
10275             }
10276          }
10277 
10278          if (ies.vars) {
10279             struct ast_datastore *variablestore = NULL;
10280             struct ast_variable *var, *prev = NULL;
10281             AST_LIST_HEAD(, ast_var_t) *varlist;
10282 
10283             iax2_lock_owner(fr->callno);
10284             if (!iaxs[fr->callno]) {
10285                ast_variables_destroy(ies.vars);
10286                ast_mutex_unlock(&iaxsl[fr->callno]);
10287                return 1;
10288             }
10289             if ((c = iaxs[fr->callno]->owner)) {
10290                varlist = ast_calloc(1, sizeof(*varlist));
10291                variablestore = ast_datastore_alloc(&iax2_variable_datastore_info, NULL);
10292 
10293                if (variablestore && varlist) {
10294                   variablestore->data = varlist;
10295                   variablestore->inheritance = DATASTORE_INHERIT_FOREVER;
10296                   AST_LIST_HEAD_INIT(varlist);
10297                   ast_debug(1, "I can haz IAX vars?\n");
10298                   for (var = ies.vars; var; var = var->next) {
10299                      struct ast_var_t *newvar = ast_var_assign(var->name, var->value);
10300                      if (prev) {
10301                         ast_free(prev);
10302                      }
10303                      prev = var;
10304                      if (!newvar) {
10305                         /* Don't abort list traversal, as this would leave ies.vars in an inconsistent state. */
10306                         ast_log(LOG_ERROR, "Memory allocation error while processing IAX2 variables\n");
10307                      } else {
10308                         AST_LIST_INSERT_TAIL(varlist, newvar, entries);
10309                      }
10310                   }
10311                   if (prev) {
10312                      ast_free(prev);
10313                   }
10314                   ies.vars = NULL;
10315                   ast_channel_datastore_add(c, variablestore);
10316                } else {
10317                   ast_log(LOG_ERROR, "Memory allocation error while processing IAX2 variables\n");
10318                   if (variablestore) {
10319                      ast_datastore_free(variablestore);
10320                   }
10321                   if (varlist) {
10322                      ast_free(varlist);
10323                   }
10324                }
10325                ast_channel_unlock(c);
10326             } else {
10327                /* No channel yet, so transfer the variables directly over to the pvt,
10328                 * for later inheritance. */
10329                ast_debug(1, "No channel, so populating IAXVARs to the pvt, as an intermediate step.\n");
10330                for (var = ies.vars; var && var->next; var = var->next);
10331                if (var) {
10332                   var->next = iaxs[fr->callno]->iaxvars;
10333                   iaxs[fr->callno]->iaxvars = ies.vars;
10334                   ies.vars = NULL;
10335                }
10336             }
10337          }
10338 
10339          if (ies.vars) {
10340             ast_debug(1, "I have IAX variables, but they were not processed\n");
10341          }
10342       }
10343 
10344       /* once we receive our first IAX Full Frame that is not CallToken related, send all
10345        * queued signaling frames that were being held. */
10346       if ((f.frametype == AST_FRAME_IAX) && (f.subclass.integer != IAX_COMMAND_CALLTOKEN) && iaxs[fr->callno]->hold_signaling) {
10347          send_signaling(iaxs[fr->callno]);
10348       }
10349 
10350       if (f.frametype == AST_FRAME_VOICE) {
10351          if (f.subclass.codec != iaxs[fr->callno]->voiceformat) {
10352                iaxs[fr->callno]->voiceformat = f.subclass.codec;
10353                ast_debug(1, "Ooh, voice format changed to '%s'\n", ast_getformatname(f.subclass.codec));
10354                if (iaxs[fr->callno]->owner) {
10355                   iax2_lock_owner(fr->callno);
10356                   if (iaxs[fr->callno]) {
10357                      if (iaxs[fr->callno]->owner) {
10358                         format_t orignative;
10359 
10360                         orignative = iaxs[fr->callno]->owner->nativeformats;
10361                         iaxs[fr->callno]->owner->nativeformats = f.subclass.codec;
10362                         if (iaxs[fr->callno]->owner->readformat)
10363                            ast_set_read_format(iaxs[fr->callno]->owner, iaxs[fr->callno]->owner->readformat);
10364                         iaxs[fr->callno]->owner->nativeformats = orignative;
10365                         ast_channel_unlock(iaxs[fr->callno]->owner);
10366                      }
10367                   } else {
10368                      ast_debug(1, "Neat, somebody took away the channel at a magical time but i found it!\n");
10369                      /* Free remote variables (if any) */
10370                      if (ies.vars) {
10371                         ast_variables_destroy(ies.vars);
10372                         ast_debug(1, "I can haz iaxvars, but they is no good.  :-(\n");
10373                         ies.vars = NULL;
10374                      }
10375                      ast_mutex_unlock(&iaxsl[fr->callno]);
10376                      return 1;
10377                   }
10378                }
10379          }
10380       }
10381       if (f.frametype == AST_FRAME_VIDEO) {
10382          if (f.subclass.codec != iaxs[fr->callno]->videoformat) {
10383             ast_debug(1, "Ooh, video format changed to %s\n", ast_getformatname(f.subclass.codec & ~0x1LL));
10384             iaxs[fr->callno]->videoformat = f.subclass.codec & ~0x1LL;
10385          }
10386       }
10387       if (f.frametype == AST_FRAME_CONTROL && iaxs[fr->callno]->owner) {
10388          if (f.subclass.integer == AST_CONTROL_BUSY) {
10389             iaxs[fr->callno]->owner->hangupcause = AST_CAUSE_BUSY;
10390          } else if (f.subclass.integer == AST_CONTROL_CONGESTION) {
10391             iaxs[fr->callno]->owner->hangupcause = AST_CAUSE_CONGESTION;
10392          }
10393       }
10394       if (f.frametype == AST_FRAME_IAX) {
10395          ast_sched_thread_del(sched, iaxs[fr->callno]->initid);
10396          /* Handle the IAX pseudo frame itself */
10397          if (iaxdebug)
10398             ast_debug(1, "IAX subclass %d received\n", f.subclass.integer);
10399 
10400                         /* Update last ts unless the frame's timestamp originated with us. */
10401          if (iaxs[fr->callno]->last < fr->ts &&
10402                             f.subclass.integer != IAX_COMMAND_ACK &&
10403                             f.subclass.integer != IAX_COMMAND_PONG &&
10404                             f.subclass.integer != IAX_COMMAND_LAGRP) {
10405             iaxs[fr->callno]->last = fr->ts;
10406             if (iaxdebug)
10407                ast_debug(1, "For call=%d, set last=%d\n", fr->callno, fr->ts);
10408          }
10409          iaxs[fr->callno]->last_iax_message = f.subclass.integer;
10410          if (!iaxs[fr->callno]->first_iax_message) {
10411             iaxs[fr->callno]->first_iax_message = f.subclass.integer;
10412          }
10413          switch(f.subclass.integer) {
10414          case IAX_COMMAND_ACK:
10415             /* Do nothing */
10416             break;
10417          case IAX_COMMAND_QUELCH:
10418             if (ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED)) {
10419                     /* Generate Manager Hold event, if necessary*/
10420                if (iaxs[fr->callno]->owner) {
10421                   ast_manager_event(iaxs[fr->callno]->owner, EVENT_FLAG_CALL, "Hold",
10422                      "Status: On\r\n"
10423                      "Channel: %s\r\n"
10424                      "Uniqueid: %s\r\n",
10425                      iaxs[fr->callno]->owner->name,
10426                      iaxs[fr->callno]->owner->uniqueid);
10427                }
10428 
10429                ast_set_flag64(iaxs[fr->callno], IAX_QUELCH);
10430                if (ies.musiconhold) {
10431                   iax2_lock_owner(fr->callno);
10432                   if (!iaxs[fr->callno] || !iaxs[fr->callno]->owner) {
10433                      break;
10434                   }
10435                   if (ast_bridged_channel(iaxs[fr->callno]->owner)) {
10436                      const char *moh_suggest = iaxs[fr->callno]->mohsuggest;
10437 
10438                      /*
10439                       * We already hold the owner lock so we do not
10440                       * need to check iaxs[fr->callno] after it returns.
10441                       */
10442                      iax2_queue_control_data(fr->callno, AST_CONTROL_HOLD, 
10443                         S_OR(moh_suggest, NULL),
10444                         !ast_strlen_zero(moh_suggest) ? strlen(moh_suggest) + 1 : 0);
10445                   }
10446                   ast_channel_unlock(iaxs[fr->callno]->owner);
10447                }
10448             }
10449             break;
10450          case IAX_COMMAND_UNQUELCH:
10451             if (ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED)) {
10452                iax2_lock_owner(fr->callno);
10453                if (!iaxs[fr->callno]) {
10454                   break;
10455                }
10456                /* Generate Manager Unhold event, if necessary */
10457                if (iaxs[fr->callno]->owner && ast_test_flag64(iaxs[fr->callno], IAX_QUELCH)) {
10458                   ast_manager_event(iaxs[fr->callno]->owner, EVENT_FLAG_CALL, "Hold",
10459                      "Status: Off\r\n"
10460                      "Channel: %s\r\n"
10461                      "Uniqueid: %s\r\n",
10462                      iaxs[fr->callno]->owner->name,
10463                      iaxs[fr->callno]->owner->uniqueid);
10464                }
10465 
10466                ast_clear_flag64(iaxs[fr->callno], IAX_QUELCH);
10467                if (!iaxs[fr->callno]->owner) {
10468                   break;
10469                }
10470                if (ast_bridged_channel(iaxs[fr->callno]->owner)) {
10471                   /*
10472                    * We already hold the owner lock so we do not
10473                    * need to check iaxs[fr->callno] after it returns.
10474                    */
10475                   iax2_queue_control_data(fr->callno, AST_CONTROL_UNHOLD, NULL, 0);
10476                }
10477                ast_channel_unlock(iaxs[fr->callno]->owner);
10478             }
10479             break;
10480          case IAX_COMMAND_TXACC:
10481             if (iaxs[fr->callno]->transferring == TRANSFER_BEGIN) {
10482                /* Ack the packet with the given timestamp */
10483                AST_LIST_TRAVERSE(&frame_queue[fr->callno], cur, list) {
10484                   /* Cancel any outstanding txcnt's */
10485                   if (cur->transfer) {
10486                      cur->retries = -1;
10487                   }
10488                }
10489                memset(&ied1, 0, sizeof(ied1));
10490                iax_ie_append_short(&ied1, IAX_IE_CALLNO, iaxs[fr->callno]->callno);
10491                send_command(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_TXREADY, 0, ied1.buf, ied1.pos, -1);
10492                iaxs[fr->callno]->transferring = TRANSFER_READY;
10493             }
10494             break;
10495          case IAX_COMMAND_NEW:
10496             /* Ignore if it's already up */
10497             if (ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED | IAX_STATE_TBD))
10498                break;
10499             if (ies.provverpres && ies.serviceident && sin.sin_addr.s_addr) {
10500                ast_mutex_unlock(&iaxsl[fr->callno]);
10501                check_provisioning(&sin, fd, ies.serviceident, ies.provver);
10502                ast_mutex_lock(&iaxsl[fr->callno]);
10503                if (!iaxs[fr->callno]) {
10504                   break;
10505                }
10506             }
10507             /* If we're in trunk mode, do it now, and update the trunk number in our frame before continuing */
10508             if (ast_test_flag64(iaxs[fr->callno], IAX_TRUNK)) {
10509                int new_callno;
10510                if ((new_callno = make_trunk(fr->callno, 1)) != -1)
10511                   fr->callno = new_callno;
10512             }
10513             /* For security, always ack immediately */
10514             if (delayreject)
10515                send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
10516             if (check_access(fr->callno, &sin, &ies)) {
10517                /* They're not allowed on */
10518                auth_fail(fr->callno, IAX_COMMAND_REJECT);
10519                if (authdebug)
10520                   ast_log(LOG_NOTICE, "Rejected connect attempt from %s, who was trying to reach '%s@%s'\n", ast_inet_ntoa(sin.sin_addr), iaxs[fr->callno]->exten, iaxs[fr->callno]->context);
10521                break;
10522             }
10523             if (ast_strlen_zero(iaxs[fr->callno]->secret) && ast_test_flag64(iaxs[fr->callno], IAX_FORCE_ENCRYPT)) {
10524                auth_fail(fr->callno, IAX_COMMAND_REJECT);
10525                ast_log(LOG_WARNING, "Rejected connect attempt.  No secret present while force encrypt enabled.\n");
10526                break;
10527             }
10528             if (strcasecmp(iaxs[fr->callno]->exten, "TBD")) {
10529                const char *context, *exten, *cid_num;
10530 
10531                context = ast_strdupa(iaxs[fr->callno]->context);
10532                exten = ast_strdupa(iaxs[fr->callno]->exten);
10533                cid_num = ast_strdupa(iaxs[fr->callno]->cid_num);
10534 
10535                /* This might re-enter the IAX code and need the lock */
10536                ast_mutex_unlock(&iaxsl[fr->callno]);
10537                exists = ast_exists_extension(NULL, context, exten, 1, cid_num);
10538                ast_mutex_lock(&iaxsl[fr->callno]);
10539 
10540                if (!iaxs[fr->callno]) {
10541                   break;
10542                }
10543             } else
10544                exists = 0;
10545             /* Get OSP token if it does exist */
10546             save_osptoken(fr, &ies);
10547             if (ast_strlen_zero(iaxs[fr->callno]->secret) && ast_strlen_zero(iaxs[fr->callno]->inkeys)) {
10548                if (strcmp(iaxs[fr->callno]->exten, "TBD") && !exists) {
10549                   memset(&ied0, 0, sizeof(ied0));
10550                   iax_ie_append_str(&ied0, IAX_IE_CAUSE, "No such context/extension");
10551                   iax_ie_append_byte(&ied0, IAX_IE_CAUSECODE, AST_CAUSE_NO_ROUTE_DESTINATION);
10552                   send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
10553                   if (!iaxs[fr->callno]) {
10554                      break;
10555                   }
10556                   if (authdebug)
10557                      ast_log(LOG_NOTICE, "Rejected connect attempt from %s, request '%s@%s' does not exist\n", ast_inet_ntoa(sin.sin_addr), iaxs[fr->callno]->exten, iaxs[fr->callno]->context);
10558                } else {
10559                   /* Select an appropriate format */
10560 
10561                   if(ast_test_flag64(iaxs[fr->callno], IAX_CODEC_NOPREFS)) {
10562                      if(ast_test_flag64(iaxs[fr->callno], IAX_CODEC_NOCAP)) {
10563                         using_prefs = "reqonly";
10564                      } else {
10565                         using_prefs = "disabled";
10566                      }
10567                      format = iaxs[fr->callno]->peerformat & iaxs[fr->callno]->capability;
10568                      memset(&pref, 0, sizeof(pref));
10569                      strcpy(caller_pref_buf, "disabled");
10570                      strcpy(host_pref_buf, "disabled");
10571                   } else {
10572                      using_prefs = "mine";
10573                      /* If the information elements are in here... use them */
10574                      if (ies.codec_prefs)
10575                         ast_codec_pref_convert(&iaxs[fr->callno]->rprefs, ies.codec_prefs, 32, 0);
10576                      if (ast_codec_pref_index(&iaxs[fr->callno]->rprefs, 0)) {
10577                         /* If we are codec_first_choice we let the caller have the 1st shot at picking the codec.*/
10578                         if (ast_test_flag64(iaxs[fr->callno], IAX_CODEC_USER_FIRST)) {
10579                            pref = iaxs[fr->callno]->rprefs;
10580                            using_prefs = "caller";
10581                         } else {
10582                            pref = iaxs[fr->callno]->prefs;
10583                         }
10584                      } else
10585                         pref = iaxs[fr->callno]->prefs;
10586 
10587                      format = ast_codec_choose(&pref, iaxs[fr->callno]->capability & iaxs[fr->callno]->peercapability, 0);
10588                      ast_codec_pref_string(&iaxs[fr->callno]->rprefs, caller_pref_buf, sizeof(caller_pref_buf) - 1);
10589                      ast_codec_pref_string(&iaxs[fr->callno]->prefs, host_pref_buf, sizeof(host_pref_buf) - 1);
10590                   }
10591                   if (!format) {
10592                      if(!ast_test_flag64(iaxs[fr->callno], IAX_CODEC_NOCAP))
10593                         format = iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability;
10594                      if (!format) {
10595                         memset(&ied0, 0, sizeof(ied0));
10596                         iax_ie_append_str(&ied0, IAX_IE_CAUSE, "Unable to negotiate codec");
10597                         iax_ie_append_byte(&ied0, IAX_IE_CAUSECODE, AST_CAUSE_BEARERCAPABILITY_NOTAVAIL);
10598                         send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
10599                         if (!iaxs[fr->callno]) {
10600                            break;
10601                         }
10602                         if (authdebug) {
10603                            char tmp[256], tmp2[256], tmp3[256];
10604                            if (ast_test_flag64(iaxs[fr->callno], IAX_CODEC_NOCAP)) {
10605                               ast_log(LOG_NOTICE, "Rejected connect attempt from %s, requested '%s' incompatible with our capability '%s'.\n",
10606                                  ast_inet_ntoa(sin.sin_addr),
10607                                  ast_getformatname_multiple(tmp, sizeof(tmp), iaxs[fr->callno]->peerformat),
10608                                  ast_getformatname_multiple(tmp2, sizeof(tmp2), iaxs[fr->callno]->capability));
10609                            } else {
10610                               ast_log(LOG_NOTICE, "Rejected connect attempt from %s, requested/capability '%s'/'%s' incompatible with our capability '%s'.\n",
10611                                  ast_inet_ntoa(sin.sin_addr),
10612                                  ast_getformatname_multiple(tmp, sizeof(tmp), iaxs[fr->callno]->peerformat),
10613                                  ast_getformatname_multiple(tmp2, sizeof(tmp2), iaxs[fr->callno]->peercapability),
10614                                  ast_getformatname_multiple(tmp3, sizeof(tmp3), iaxs[fr->callno]->capability));
10615                            }
10616                         }
10617                      } else {
10618                         /* Pick one... */
10619                         if(ast_test_flag64(iaxs[fr->callno], IAX_CODEC_NOCAP)) {
10620                            if(!(iaxs[fr->callno]->peerformat & iaxs[fr->callno]->capability))
10621                               format = 0;
10622                         } else {
10623                            if(ast_test_flag64(iaxs[fr->callno], IAX_CODEC_NOPREFS)) {
10624                               using_prefs = ast_test_flag64(iaxs[fr->callno], IAX_CODEC_NOCAP) ? "reqonly" : "disabled";
10625                               memset(&pref, 0, sizeof(pref));
10626                               format = ast_best_codec(iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability);
10627                               strcpy(caller_pref_buf,"disabled");
10628                               strcpy(host_pref_buf,"disabled");
10629                            } else {
10630                               using_prefs = "mine";
10631                               if (ast_codec_pref_index(&iaxs[fr->callno]->rprefs, 0)) {
10632                                  /* Do the opposite of what we tried above. */
10633                                  if (ast_test_flag64(iaxs[fr->callno], IAX_CODEC_USER_FIRST)) {
10634                                     pref = iaxs[fr->callno]->prefs;
10635                                  } else {
10636                                     pref = iaxs[fr->callno]->rprefs;
10637                                     using_prefs = "caller";
10638                                  }
10639                                  format = ast_codec_choose(&pref, iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability, 1);
10640                               } else /* if no codec_prefs IE do it the old way */
10641                                  format = ast_best_codec(iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability);
10642                            }
10643                         }
10644 
10645                         if (!format) {
10646                            char tmp[256], tmp2[256], tmp3[256];
10647                            memset(&ied0, 0, sizeof(ied0));
10648                            iax_ie_append_str(&ied0, IAX_IE_CAUSE, "Unable to negotiate codec");
10649                            iax_ie_append_byte(&ied0, IAX_IE_CAUSECODE, AST_CAUSE_BEARERCAPABILITY_NOTAVAIL);
10650                            ast_log(LOG_ERROR, "No best format in '%s'???\n", ast_getformatname_multiple(tmp, sizeof(tmp), iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability));
10651                            send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
10652                            if (!iaxs[fr->callno]) {
10653                               break;
10654                            }
10655                            if (authdebug) {
10656                               ast_log(LOG_NOTICE, "Rejected connect attempt from %s, requested/capability '%s'/'%s' incompatible with our capability '%s'.\n",
10657                                  ast_inet_ntoa(sin.sin_addr),
10658                                  ast_getformatname_multiple(tmp, sizeof(tmp), iaxs[fr->callno]->peerformat),
10659                                  ast_getformatname_multiple(tmp2, sizeof(tmp2), iaxs[fr->callno]->peercapability),
10660                                  ast_getformatname_multiple(tmp3, sizeof(tmp3), iaxs[fr->callno]->capability));
10661                            }
10662                            ast_set_flag64(iaxs[fr->callno], IAX_ALREADYGONE);
10663                            break;
10664                         }
10665                      }
10666                   }
10667                   if (format) {
10668                      /* No authentication required, let them in */
10669                      memset(&ied1, 0, sizeof(ied1));
10670                      iax_ie_append_int(&ied1, IAX_IE_FORMAT, format);
10671                      iax_ie_append_versioned_uint64(&ied1, IAX_IE_FORMAT2, 0, format);
10672                      send_command(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACCEPT, 0, ied1.buf, ied1.pos, -1);
10673                      if (strcmp(iaxs[fr->callno]->exten, "TBD")) {
10674                         ast_set_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED);
10675                         ast_verb(3, "Accepting UNAUTHENTICATED call from %s:\n"
10676                                     "%srequested format = %s,\n"
10677                                     "%srequested prefs = %s,\n"
10678                                     "%sactual format = %s,\n"
10679                                     "%shost prefs = %s,\n"
10680                                     "%spriority = %s\n",
10681                                     ast_inet_ntoa(sin.sin_addr), 
10682                                     VERBOSE_PREFIX_4,
10683                                     ast_getformatname(iaxs[fr->callno]->peerformat), 
10684                                     VERBOSE_PREFIX_4,
10685                                     caller_pref_buf,
10686                                     VERBOSE_PREFIX_4,
10687                                     ast_getformatname(format), 
10688                                     VERBOSE_PREFIX_4,
10689                                     host_pref_buf, 
10690                                     VERBOSE_PREFIX_4,
10691                                     using_prefs);
10692 
10693                         iaxs[fr->callno]->chosenformat = format;
10694                         ast_set_flag64(iaxs[fr->callno], IAX_DELAYPBXSTART);
10695                      } else {
10696                         ast_set_flag(&iaxs[fr->callno]->state, IAX_STATE_TBD);
10697                         /* If this is a TBD call, we're ready but now what...  */
10698                         ast_verb(3, "Accepted unauthenticated TBD call from %s\n", ast_inet_ntoa(sin.sin_addr));
10699                      }
10700                   }
10701                }
10702                break;
10703             }
10704             if (iaxs[fr->callno]->authmethods & IAX_AUTH_MD5)
10705                merge_encryption(iaxs[fr->callno],ies.encmethods);
10706             else
10707                iaxs[fr->callno]->encmethods = 0;
10708             if (!authenticate_request(fr->callno) && iaxs[fr->callno])
10709                ast_set_flag(&iaxs[fr->callno]->state, IAX_STATE_AUTHENTICATED);
10710             break;
10711          case IAX_COMMAND_DPREQ:
10712             /* Request status in the dialplan */
10713             if (ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_TBD) &&
10714                !ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED) && ies.called_number) {
10715                if (iaxcompat) {
10716                   /* Spawn a thread for the lookup */
10717                   spawn_dp_lookup(fr->callno, iaxs[fr->callno]->context, ies.called_number, iaxs[fr->callno]->cid_num);
10718                } else {
10719                   /* Just look it up */
10720                   dp_lookup(fr->callno, iaxs[fr->callno]->context, ies.called_number, iaxs[fr->callno]->cid_num, 1);
10721                }
10722             }
10723             break;
10724          case IAX_COMMAND_HANGUP:
10725             ast_set_flag64(iaxs[fr->callno], IAX_ALREADYGONE);
10726             ast_debug(1, "Immediately destroying %d, having received hangup\n", fr->callno);
10727             /* Set hangup cause according to remote and hangupsource */
10728             if (iaxs[fr->callno]->owner) {
10729                set_hangup_source_and_cause(fr->callno, ies.causecode);
10730                if (!iaxs[fr->callno]) {
10731                   break;
10732                }
10733             }
10734 
10735             /* Send ack immediately, before we destroy */
10736             send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
10737             iax2_destroy(fr->callno);
10738             break;
10739          case IAX_COMMAND_REJECT:
10740             /* Set hangup cause according to remote and hangup source */
10741             if (iaxs[fr->callno]->owner) {
10742                set_hangup_source_and_cause(fr->callno, ies.causecode);
10743                if (!iaxs[fr->callno]) {
10744                   break;
10745                }
10746             }
10747 
10748             if (!ast_test_flag64(iaxs[fr->callno], IAX_PROVISION)) {
10749                if (iaxs[fr->callno]->owner && authdebug)
10750                   ast_log(LOG_WARNING, "Call rejected by %s: %s\n",
10751                      ast_inet_ntoa(iaxs[fr->callno]->addr.sin_addr),
10752                      ies.cause ? ies.cause : "<Unknown>");
10753                ast_debug(1, "Immediately destroying %d, having received reject\n",
10754                   fr->callno);
10755             }
10756             /* Send ack immediately, before we destroy */
10757             send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK,
10758                          fr->ts, NULL, 0, fr->iseqno);
10759             if (!ast_test_flag64(iaxs[fr->callno], IAX_PROVISION))
10760                iaxs[fr->callno]->error = EPERM;
10761             iax2_destroy(fr->callno);
10762             break;
10763          case IAX_COMMAND_TRANSFER:
10764          {
10765             struct ast_channel *bridged_chan;
10766             struct ast_channel *owner;
10767 
10768             iax2_lock_owner(fr->callno);
10769             if (!iaxs[fr->callno]) {
10770                /* Initiating call went away before we could transfer. */
10771                break;
10772             }
10773             owner = iaxs[fr->callno]->owner;
10774             bridged_chan = owner ? ast_bridged_channel(owner) : NULL;
10775             if (bridged_chan && ies.called_number) {
10776                const char *context;
10777 
10778                context = ast_strdupa(iaxs[fr->callno]->context);
10779 
10780                ast_channel_ref(owner);
10781                ast_channel_ref(bridged_chan);
10782                ast_channel_unlock(owner);
10783                ast_mutex_unlock(&iaxsl[fr->callno]);
10784 
10785                /* Set BLINDTRANSFER channel variables */
10786                pbx_builtin_setvar_helper(owner, "BLINDTRANSFER", bridged_chan->name);
10787                pbx_builtin_setvar_helper(bridged_chan, "BLINDTRANSFER", owner->name);
10788 
10789                /* DO NOT hold any locks while calling ast_parking_ext_valid() */
10790                if (ast_parking_ext_valid(ies.called_number, owner, context)) {
10791                   ast_debug(1, "Parking call '%s'\n", bridged_chan->name);
10792                   if (iax_park(bridged_chan, owner, ies.called_number, context)) {
10793                      ast_log(LOG_WARNING, "Failed to park call '%s'\n",
10794                         bridged_chan->name);
10795                   }
10796                } else {
10797                   if (ast_async_goto(bridged_chan, context, ies.called_number, 1)) {
10798                      ast_log(LOG_WARNING,
10799                         "Async goto of '%s' to '%s@%s' failed\n",
10800                         bridged_chan->name, ies.called_number, context);
10801                   } else {
10802                      ast_debug(1, "Async goto of '%s' to '%s@%s' started\n",
10803                         bridged_chan->name, ies.called_number, context);
10804                   }
10805                }
10806                ast_channel_unref(owner);
10807                ast_channel_unref(bridged_chan);
10808 
10809                ast_mutex_lock(&iaxsl[fr->callno]);
10810             } else {
10811                ast_debug(1, "Async goto not applicable on call %d\n", fr->callno);
10812                if (owner) {
10813                   ast_channel_unlock(owner);
10814                }
10815             }
10816 
10817             break;
10818          }
10819          case IAX_COMMAND_ACCEPT:
10820             /* Ignore if call is already up or needs authentication or is a TBD */
10821             if (ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED | IAX_STATE_TBD | IAX_STATE_AUTHENTICATED))
10822                break;
10823             if (ast_test_flag64(iaxs[fr->callno], IAX_PROVISION)) {
10824                /* Send ack immediately, before we destroy */
10825                send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
10826                iax2_destroy(fr->callno);
10827                break;
10828             }
10829             if (ies.format) {
10830                iaxs[fr->callno]->peerformat = ies.format;
10831             } else {
10832                if (iaxs[fr->callno]->owner)
10833                   iaxs[fr->callno]->peerformat = iaxs[fr->callno]->owner->nativeformats;
10834                else
10835                   iaxs[fr->callno]->peerformat = iaxs[fr->callno]->capability;
10836             }
10837             ast_verb(3, "Call accepted by %s (format %s)\n", ast_inet_ntoa(iaxs[fr->callno]->addr.sin_addr), ast_getformatname(iaxs[fr->callno]->peerformat));
10838             if (!(iaxs[fr->callno]->peerformat & iaxs[fr->callno]->capability)) {
10839                memset(&ied0, 0, sizeof(ied0));
10840                iax_ie_append_str(&ied0, IAX_IE_CAUSE, "Unable to negotiate codec");
10841                iax_ie_append_byte(&ied0, IAX_IE_CAUSECODE, AST_CAUSE_BEARERCAPABILITY_NOTAVAIL);
10842                send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
10843                if (!iaxs[fr->callno]) {
10844                   break;
10845                }
10846                if (authdebug) {
10847                   char tmp1[256], tmp2[256];
10848                   ast_log(LOG_NOTICE, "Rejected call to %s, format %s incompatible with our capability %s.\n",
10849                      ast_inet_ntoa(sin.sin_addr),
10850                      ast_getformatname_multiple(tmp1, sizeof(tmp1), iaxs[fr->callno]->peerformat),
10851                      ast_getformatname_multiple(tmp2, sizeof(tmp2), iaxs[fr->callno]->capability));
10852                }
10853             } else {
10854                ast_set_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED);
10855                iax2_lock_owner(fr->callno);
10856                if (iaxs[fr->callno] && iaxs[fr->callno]->owner) {
10857                   /* Switch us to use a compatible format */
10858                   iaxs[fr->callno]->owner->nativeformats = iaxs[fr->callno]->peerformat;
10859                   ast_verb(3, "Format for call is %s\n", ast_getformatname(iaxs[fr->callno]->owner->nativeformats));
10860 
10861                   /* Setup read/write formats properly. */
10862                   if (iaxs[fr->callno]->owner->writeformat)
10863                      ast_set_write_format(iaxs[fr->callno]->owner, iaxs[fr->callno]->owner->writeformat);   
10864                   if (iaxs[fr->callno]->owner->readformat)
10865                      ast_set_read_format(iaxs[fr->callno]->owner, iaxs[fr->callno]->owner->readformat);  
10866                   ast_channel_unlock(iaxs[fr->callno]->owner);
10867                }
10868             }
10869             if (iaxs[fr->callno]) {
10870                AST_LIST_LOCK(&dpcache);
10871                AST_LIST_TRAVERSE(&iaxs[fr->callno]->dpentries, dp, peer_list)
10872                   if (!(dp->flags & CACHE_FLAG_TRANSMITTED))
10873                      iax2_dprequest(dp, fr->callno);
10874                AST_LIST_UNLOCK(&dpcache);
10875             }
10876             break;
10877          case IAX_COMMAND_POKE:
10878             /* Send back a pong packet with the original timestamp */
10879             send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_PONG, fr->ts, NULL, 0, -1);
10880             break;
10881          case IAX_COMMAND_PING:
10882          {
10883             struct iax_ie_data pingied;
10884             construct_rr(iaxs[fr->callno], &pingied);
10885             /* Send back a pong packet with the original timestamp */
10886             send_command(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_PONG, fr->ts, pingied.buf, pingied.pos, -1);
10887          }
10888             break;
10889          case IAX_COMMAND_PONG:
10890             /* Calculate ping time */
10891             iaxs[fr->callno]->pingtime =  calc_timestamp(iaxs[fr->callno], 0, &f) - fr->ts;
10892             /* save RR info */
10893             save_rr(fr, &ies);
10894 
10895             /* Good time to write jb stats for this call */
10896             log_jitterstats(fr->callno);
10897 
10898             if (iaxs[fr->callno]->peerpoke) {
10899                peer = iaxs[fr->callno]->peerpoke;
10900                if ((peer->lastms < 0)  || (peer->historicms > peer->maxms)) {
10901                   if (iaxs[fr->callno]->pingtime <= peer->maxms) {
10902                      ast_log(LOG_NOTICE, "Peer '%s' is now REACHABLE! Time: %d\n", peer->name, iaxs[fr->callno]->pingtime);
10903                      manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: IAX2\r\nPeer: IAX2/%s\r\nPeerStatus: Reachable\r\nTime: %d\r\n", peer->name, iaxs[fr->callno]->pingtime); 
10904                      ast_devstate_changed(AST_DEVICE_NOT_INUSE, "IAX2/%s", peer->name); /* Activate notification */
10905                   }
10906                } else if ((peer->historicms > 0) && (peer->historicms <= peer->maxms)) {
10907                   if (iaxs[fr->callno]->pingtime > peer->maxms) {
10908                      ast_log(LOG_NOTICE, "Peer '%s' is now TOO LAGGED (%d ms)!\n", peer->name, iaxs[fr->callno]->pingtime);
10909                      manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: IAX2\r\nPeer: IAX2/%s\r\nPeerStatus: Lagged\r\nTime: %d\r\n", peer->name, iaxs[fr->callno]->pingtime); 
10910                      ast_devstate_changed(AST_DEVICE_UNAVAILABLE, "IAX2/%s", peer->name); /* Activate notification */
10911                   }
10912                }
10913                peer->lastms = iaxs[fr->callno]->pingtime;
10914                if (peer->smoothing && (peer->lastms > -1))
10915                   peer->historicms = (iaxs[fr->callno]->pingtime + peer->historicms) / 2;
10916                else if (peer->smoothing && peer->lastms < 0)
10917                   peer->historicms = (0 + peer->historicms) / 2;
10918                else              
10919                   peer->historicms = iaxs[fr->callno]->pingtime;
10920 
10921                /* Remove scheduled iax2_poke_noanswer */
10922                if (peer->pokeexpire > -1) {
10923                   if (!ast_sched_thread_del(sched, peer->pokeexpire)) {
10924                      peer_unref(peer);
10925                      peer->pokeexpire = -1;
10926                   }
10927                }
10928                /* Schedule the next cycle */
10929                if ((peer->lastms < 0)  || (peer->historicms > peer->maxms)) 
10930                   peer->pokeexpire = iax2_sched_add(sched, peer->pokefreqnotok, iax2_poke_peer_s, peer_ref(peer));
10931                else
10932                   peer->pokeexpire = iax2_sched_add(sched, peer->pokefreqok, iax2_poke_peer_s, peer_ref(peer));
10933                if (peer->pokeexpire == -1)
10934                   peer_unref(peer);
10935                /* and finally send the ack */
10936                send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
10937                /* And wrap up the qualify call */
10938                iax2_destroy(fr->callno);
10939                peer->callno = 0;
10940                ast_debug(1, "Peer %s: got pong, lastms %d, historicms %d, maxms %d\n", peer->name, peer->lastms, peer->historicms, peer->maxms);
10941             }
10942             break;
10943          case IAX_COMMAND_LAGRQ:
10944          case IAX_COMMAND_LAGRP:
10945             f.src = "LAGRQ";
10946             f.mallocd = 0;
10947             f.offset = 0;
10948             f.samples = 0;
10949             iax_frame_wrap(fr, &f);
10950             if (f.subclass.integer == IAX_COMMAND_LAGRQ) {
10951                /* Received a LAGRQ - echo back a LAGRP */
10952                fr->af.subclass.integer = IAX_COMMAND_LAGRP;
10953                iax2_send(iaxs[fr->callno], &fr->af, fr->ts, -1, 0, 0, 0);
10954             } else {
10955                /* Received LAGRP in response to our LAGRQ */
10956                unsigned int ts;
10957                /* This is a reply we've been given, actually measure the difference */
10958                ts = calc_timestamp(iaxs[fr->callno], 0, &fr->af);
10959                iaxs[fr->callno]->lag = ts - fr->ts;
10960                if (iaxdebug)
10961                   ast_debug(1, "Peer %s lag measured as %dms\n",
10962                      ast_inet_ntoa(iaxs[fr->callno]->addr.sin_addr), iaxs[fr->callno]->lag);
10963             }
10964             break;
10965          case IAX_COMMAND_AUTHREQ:
10966             if (ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED | IAX_STATE_TBD)) {
10967                ast_log(LOG_WARNING, "Call on %s is already up, can't start on it\n", iaxs[fr->callno]->owner ? iaxs[fr->callno]->owner->name : "<Unknown>");
10968                break;
10969             }
10970             if (authenticate_reply(iaxs[fr->callno], &iaxs[fr->callno]->addr, &ies, iaxs[fr->callno]->secret, iaxs[fr->callno]->outkey)) {
10971                struct ast_frame hangup_fr = { .frametype = AST_FRAME_CONTROL,
10972                         .subclass.integer = AST_CONTROL_HANGUP,
10973                };
10974                ast_log(LOG_WARNING, 
10975                   "I don't know how to authenticate %s to %s\n", 
10976                   ies.username ? ies.username : "<unknown>", ast_inet_ntoa(iaxs[fr->callno]->addr.sin_addr));
10977                iax2_queue_frame(fr->callno, &hangup_fr);
10978             }
10979             break;
10980          case IAX_COMMAND_AUTHREP:
10981             /* For security, always ack immediately */
10982             if (delayreject)
10983                send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
10984             /* Ignore once we've started */
10985             if (ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED | IAX_STATE_TBD)) {
10986                ast_log(LOG_WARNING, "Call on %s is already up, can't start on it\n", iaxs[fr->callno]->owner ? iaxs[fr->callno]->owner->name : "<Unknown>");
10987                break;
10988             }
10989             if (authenticate_verify(iaxs[fr->callno], &ies)) {
10990                if (authdebug)
10991                   ast_log(LOG_NOTICE, "Host %s failed to authenticate as %s\n", ast_inet_ntoa(iaxs[fr->callno]->addr.sin_addr), iaxs[fr->callno]->username);
10992                memset(&ied0, 0, sizeof(ied0));
10993                auth_fail(fr->callno, IAX_COMMAND_REJECT);
10994                break;
10995             }
10996             if (strcasecmp(iaxs[fr->callno]->exten, "TBD")) {
10997                /* This might re-enter the IAX code and need the lock */
10998                exists = ast_exists_extension(NULL, iaxs[fr->callno]->context, iaxs[fr->callno]->exten, 1, iaxs[fr->callno]->cid_num);
10999             } else
11000                exists = 0;
11001             if (strcmp(iaxs[fr->callno]->exten, "TBD") && !exists) {
11002                if (authdebug)
11003                   ast_log(LOG_NOTICE, "Rejected connect attempt from %s, request '%s@%s' does not exist\n", ast_inet_ntoa(sin.sin_addr), iaxs[fr->callno]->exten, iaxs[fr->callno]->context);
11004                memset(&ied0, 0, sizeof(ied0));
11005                iax_ie_append_str(&ied0, IAX_IE_CAUSE, "No such context/extension");
11006                iax_ie_append_byte(&ied0, IAX_IE_CAUSECODE, AST_CAUSE_NO_ROUTE_DESTINATION);
11007                send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
11008                if (!iaxs[fr->callno]) {
11009                   break;
11010                }
11011             } else {
11012                /* Select an appropriate format */
11013                if(ast_test_flag64(iaxs[fr->callno], IAX_CODEC_NOPREFS)) {
11014                   if(ast_test_flag64(iaxs[fr->callno], IAX_CODEC_NOCAP)) {
11015                      using_prefs = "reqonly";
11016                   } else {
11017                      using_prefs = "disabled";
11018                   }
11019                   format = iaxs[fr->callno]->peerformat & iaxs[fr->callno]->capability;
11020                   memset(&pref, 0, sizeof(pref));
11021                   strcpy(caller_pref_buf, "disabled");
11022                   strcpy(host_pref_buf, "disabled");
11023                } else {
11024                   using_prefs = "mine";
11025                   if (ies.codec_prefs)
11026                      ast_codec_pref_convert(&iaxs[fr->callno]->rprefs, ies.codec_prefs, 32, 0);
11027                   if (ast_codec_pref_index(&iaxs[fr->callno]->rprefs, 0)) {
11028                      if (ast_test_flag64(iaxs[fr->callno], IAX_CODEC_USER_FIRST)) {
11029                         pref = iaxs[fr->callno]->rprefs;
11030                         using_prefs = "caller";
11031                      } else {
11032                         pref = iaxs[fr->callno]->prefs;
11033                      }
11034                   } else /* if no codec_prefs IE do it the old way */
11035                      pref = iaxs[fr->callno]->prefs;
11036                   format = ast_codec_choose(&pref, iaxs[fr->callno]->capability & iaxs[fr->callno]->peercapability, 0);
11037                   ast_codec_pref_string(&iaxs[fr->callno]->rprefs, caller_pref_buf, sizeof(caller_pref_buf) - 1);
11038                   ast_codec_pref_string(&iaxs[fr->callno]->prefs, host_pref_buf, sizeof(host_pref_buf) - 1);
11039                }
11040                if (!format) {
11041                   char tmp1[256], tmp2[256], tmp3[256];
11042                   if(!ast_test_flag64(iaxs[fr->callno], IAX_CODEC_NOCAP)) {
11043                      ast_debug(1, "We don't do requested format %s, falling back to peer capability '%s'\n",
11044                         ast_getformatname(iaxs[fr->callno]->peerformat),
11045                         ast_getformatname_multiple(tmp1, sizeof(tmp1), iaxs[fr->callno]->peercapability));
11046                      format = iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability;
11047                   }
11048                   if (!format) {
11049                      if (authdebug) {
11050                         if (ast_test_flag64(iaxs[fr->callno], IAX_CODEC_NOCAP)) {
11051                            ast_log(LOG_NOTICE, "Rejected connect attempt from %s, requested '%s' incompatible with our capability '%s'.\n", ast_inet_ntoa(sin.sin_addr),
11052                               ast_getformatname_multiple(tmp1, sizeof(tmp1), iaxs[fr->callno]->peerformat),
11053                               ast_getformatname_multiple(tmp2, sizeof(tmp2), iaxs[fr->callno]->capability));
11054                         } else {
11055                            ast_log(LOG_NOTICE, "Rejected connect attempt from %s, requested/capability '%s'/'%s' incompatible with our capability '%s'.\n",
11056                               ast_inet_ntoa(sin.sin_addr),
11057                               ast_getformatname_multiple(tmp1, sizeof(tmp1), iaxs[fr->callno]->peerformat),
11058                               ast_getformatname_multiple(tmp2, sizeof(tmp2), iaxs[fr->callno]->peercapability),
11059                               ast_getformatname_multiple(tmp3, sizeof(tmp3), iaxs[fr->callno]->capability));
11060                         }
11061                      }
11062                      memset(&ied0, 0, sizeof(ied0));
11063                      iax_ie_append_str(&ied0, IAX_IE_CAUSE, "Unable to negotiate codec");
11064                      iax_ie_append_byte(&ied0, IAX_IE_CAUSECODE, AST_CAUSE_BEARERCAPABILITY_NOTAVAIL);
11065                      send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
11066                      if (!iaxs[fr->callno]) {
11067                         break;
11068                      }
11069                   } else {
11070                      /* Pick one... */
11071                      if(ast_test_flag64(iaxs[fr->callno], IAX_CODEC_NOCAP)) {
11072                         if(!(iaxs[fr->callno]->peerformat & iaxs[fr->callno]->capability))
11073                            format = 0;
11074                      } else {
11075                         if(ast_test_flag64(iaxs[fr->callno], IAX_CODEC_NOPREFS)) {
11076                            using_prefs = ast_test_flag64(iaxs[fr->callno], IAX_CODEC_NOCAP) ? "reqonly" : "disabled";
11077                            memset(&pref, 0, sizeof(pref));
11078                            format = ast_test_flag64(iaxs[fr->callno], IAX_CODEC_NOCAP) ?
11079                               iaxs[fr->callno]->peerformat : ast_best_codec(iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability);
11080                            strcpy(caller_pref_buf,"disabled");
11081                            strcpy(host_pref_buf,"disabled");
11082                         } else {
11083                            using_prefs = "mine";
11084                            if (ast_codec_pref_index(&iaxs[fr->callno]->rprefs, 0)) {
11085                               /* Do the opposite of what we tried above. */
11086                               if (ast_test_flag64(iaxs[fr->callno], IAX_CODEC_USER_FIRST)) {
11087                                  pref = iaxs[fr->callno]->prefs;
11088                               } else {
11089                                  pref = iaxs[fr->callno]->rprefs;
11090                                  using_prefs = "caller";
11091                               }
11092                               format = ast_codec_choose(&pref, iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability, 1);
11093                            } else /* if no codec_prefs IE do it the old way */
11094                               format = ast_best_codec(iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability); 
11095                         }
11096                      }
11097                      if (!format) {
11098                         char tmp1[256], tmp2[256], tmp3[256];
11099                         ast_log(LOG_ERROR, "No best format in %s???\n",
11100                            ast_getformatname_multiple(tmp1, sizeof(tmp1), iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability));
11101                         if (authdebug) {
11102                            if (ast_test_flag64(iaxs[fr->callno], IAX_CODEC_NOCAP)) {
11103                               ast_log(LOG_NOTICE, "Rejected connect attempt from %s, requested '%s' incompatible with our capability '%s'.\n",
11104                                  ast_inet_ntoa(sin.sin_addr),
11105                                  ast_getformatname_multiple(tmp1, sizeof(tmp1), iaxs[fr->callno]->peerformat),
11106                                  ast_getformatname_multiple(tmp2, sizeof(tmp2), iaxs[fr->callno]->capability));
11107                            } else {
11108                               ast_log(LOG_NOTICE, "Rejected connect attempt from %s, requested/capability '%s'/'%s' incompatible with our capability '%s'.\n",
11109                                  ast_inet_ntoa(sin.sin_addr),
11110                                  ast_getformatname_multiple(tmp1, sizeof(tmp1), iaxs[fr->callno]->peerformat),
11111                                  ast_getformatname_multiple(tmp2, sizeof(tmp2), iaxs[fr->callno]->peercapability),
11112                                  ast_getformatname_multiple(tmp3, sizeof(tmp3), iaxs[fr->callno]->capability));
11113                            }
11114                         }
11115                         memset(&ied0, 0, sizeof(ied0));
11116                         iax_ie_append_str(&ied0, IAX_IE_CAUSE, "Unable to negotiate codec");
11117                         iax_ie_append_byte(&ied0, IAX_IE_CAUSECODE, AST_CAUSE_BEARERCAPABILITY_NOTAVAIL);
11118                         send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
11119                         if (!iaxs[fr->callno]) {
11120                            break;
11121                         }
11122                      }
11123                   }
11124                }
11125                if (format) {
11126                   /* Authentication received */
11127                   memset(&ied1, 0, sizeof(ied1));
11128                   iax_ie_append_int(&ied1, IAX_IE_FORMAT, format);
11129                   iax_ie_append_versioned_uint64(&ied1, IAX_IE_FORMAT2, 0, format);
11130                   send_command(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACCEPT, 0, ied1.buf, ied1.pos, -1);
11131                   if (strcmp(iaxs[fr->callno]->exten, "TBD")) {
11132                      ast_set_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED);
11133                      ast_verb(3, "Accepting AUTHENTICATED call from %s:\n"
11134                                  "%srequested format = %s,\n"
11135                                  "%srequested prefs = %s,\n"
11136                                  "%sactual format = %s,\n"
11137                                  "%shost prefs = %s,\n"
11138                                  "%spriority = %s\n", 
11139                                  ast_inet_ntoa(sin.sin_addr), 
11140                                  VERBOSE_PREFIX_4,
11141                                  ast_getformatname(iaxs[fr->callno]->peerformat),
11142                                  VERBOSE_PREFIX_4,
11143                                  caller_pref_buf,
11144                                  VERBOSE_PREFIX_4,
11145                                  ast_getformatname(format),
11146                                  VERBOSE_PREFIX_4,
11147                                  host_pref_buf,
11148                                  VERBOSE_PREFIX_4,
11149                                  using_prefs);
11150 
11151                      ast_set_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED);
11152                      if (!(c = ast_iax2_new(fr->callno, AST_STATE_RING, format, NULL)))
11153                         iax2_destroy(fr->callno);
11154                      else if (ies.vars) {
11155                         struct ast_datastore *variablestore;
11156                         struct ast_variable *var, *prev = NULL;
11157                         AST_LIST_HEAD(, ast_var_t) *varlist;
11158                         varlist = ast_calloc(1, sizeof(*varlist));
11159                         variablestore = ast_datastore_alloc(&iax2_variable_datastore_info, NULL);
11160                         if (variablestore && varlist) {
11161                            variablestore->data = varlist;
11162                            variablestore->inheritance = DATASTORE_INHERIT_FOREVER;
11163                            AST_LIST_HEAD_INIT(varlist);
11164                            ast_debug(1, "I can haz IAX vars? w00t\n");
11165                            for (var = ies.vars; var; var = var->next) {
11166                               struct ast_var_t *newvar = ast_var_assign(var->name, var->value);
11167                               if (prev)
11168                                  ast_free(prev);
11169                               prev = var;
11170                               if (!newvar) {
11171                                  /* Don't abort list traversal, as this would leave ies.vars in an inconsistent state. */
11172                                  ast_log(LOG_ERROR, "Memory allocation error while processing IAX2 variables\n");
11173                               } else {
11174                                  AST_LIST_INSERT_TAIL(varlist, newvar, entries);
11175                               }
11176                            }
11177                            if (prev)
11178                               ast_free(prev);
11179                            ies.vars = NULL;
11180                            ast_channel_datastore_add(c, variablestore);
11181                         } else {
11182                            ast_log(LOG_ERROR, "Memory allocation error while processing IAX2 variables\n");
11183                            if (variablestore)
11184                               ast_datastore_free(variablestore);
11185                            if (varlist)
11186                               ast_free(varlist);
11187                         }
11188                      }
11189                   } else {
11190                      ast_set_flag(&iaxs[fr->callno]->state, IAX_STATE_TBD);
11191                      /* If this is a TBD call, we're ready but now what...  */
11192                      ast_verb(3, "Accepted AUTHENTICATED TBD call from %s\n", ast_inet_ntoa(sin.sin_addr));
11193                      if (ast_test_flag64(iaxs[fr->callno], IAX_IMMEDIATE)) {
11194                         goto immediatedial;
11195                      }
11196                   }
11197                }
11198             }
11199             break;
11200          case IAX_COMMAND_DIAL:
11201 immediatedial:
11202             if (ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_TBD)) {
11203                ast_clear_flag(&iaxs[fr->callno]->state, IAX_STATE_TBD);
11204                ast_string_field_set(iaxs[fr->callno], exten, ies.called_number ? ies.called_number : "s");
11205                if (!ast_exists_extension(NULL, iaxs[fr->callno]->context, iaxs[fr->callno]->exten, 1, iaxs[fr->callno]->cid_num)) {
11206                   if (authdebug)
11207                      ast_log(LOG_NOTICE, "Rejected dial attempt from %s, request '%s@%s' does not exist\n", ast_inet_ntoa(sin.sin_addr), iaxs[fr->callno]->exten, iaxs[fr->callno]->context);
11208                   memset(&ied0, 0, sizeof(ied0));
11209                   iax_ie_append_str(&ied0, IAX_IE_CAUSE, "No such context/extension");
11210                   iax_ie_append_byte(&ied0, IAX_IE_CAUSECODE, AST_CAUSE_NO_ROUTE_DESTINATION);
11211                   send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
11212                   if (!iaxs[fr->callno]) {
11213                      break;
11214                   }
11215                } else {
11216                   char tmp[256];
11217                   ast_set_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED);
11218                   ast_verb(3, "Accepting DIAL from %s, formats = %s\n",
11219                      ast_inet_ntoa(sin.sin_addr),
11220                      ast_getformatname_multiple(tmp, sizeof(tmp), iaxs[fr->callno]->peerformat));
11221                   ast_set_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED);
11222                   send_command(iaxs[fr->callno], AST_FRAME_CONTROL, AST_CONTROL_PROGRESS, 0, NULL, 0, -1);
11223                   if (!(c = ast_iax2_new(fr->callno, AST_STATE_RING, iaxs[fr->callno]->peerformat, NULL)))
11224                      iax2_destroy(fr->callno);
11225                   else if (ies.vars) {
11226                      struct ast_datastore *variablestore;
11227                      struct ast_variable *var, *prev = NULL;
11228                      AST_LIST_HEAD(, ast_var_t) *varlist;
11229                      varlist = ast_calloc(1, sizeof(*varlist));
11230                      variablestore = ast_datastore_alloc(&iax2_variable_datastore_info, NULL);
11231                      ast_debug(1, "I can haz IAX vars? w00t\n");
11232                      if (variablestore && varlist) {
11233                         variablestore->data = varlist;
11234                         variablestore->inheritance = DATASTORE_INHERIT_FOREVER;
11235                         AST_LIST_HEAD_INIT(varlist);
11236                         for (var = ies.vars; var; var = var->next) {
11237                            struct ast_var_t *newvar = ast_var_assign(var->name, var->value);
11238                            if (prev)
11239                               ast_free(prev);
11240                            prev = var;
11241                            if (!newvar) {
11242                               /* Don't abort list traversal, as this would leave ies.vars in an inconsistent state. */
11243                               ast_log(LOG_ERROR, "Memory allocation error while processing IAX2 variables\n");
11244                            } else {
11245                               AST_LIST_INSERT_TAIL(varlist, newvar, entries);
11246                            }
11247                         }
11248                         if (prev)
11249                            ast_free(prev);
11250                         ies.vars = NULL;
11251                         ast_channel_datastore_add(c, variablestore);
11252                      } else {
11253                         ast_log(LOG_ERROR, "Memory allocation error while processing IAX2 variables\n");
11254                         if (variablestore)
11255                            ast_datastore_free(variablestore);
11256                         if (varlist)
11257                            ast_free(varlist);
11258                      }
11259                   }
11260                }
11261             }
11262             break;
11263          case IAX_COMMAND_INVAL:
11264             iaxs[fr->callno]->error = ENOTCONN;
11265             ast_debug(1, "Immediately destroying %d, having received INVAL\n", fr->callno);
11266             iax2_destroy(fr->callno);
11267             ast_debug(1, "Destroying call %d\n", fr->callno);
11268             break;
11269          case IAX_COMMAND_VNAK:
11270             ast_debug(1, "Received VNAK: resending outstanding frames\n");
11271             /* Force retransmission */
11272             vnak_retransmit(fr->callno, fr->iseqno);
11273             break;
11274          case IAX_COMMAND_REGREQ:
11275          case IAX_COMMAND_REGREL:
11276             /* For security, always ack immediately */
11277             if (delayreject)
11278                send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
11279             if (register_verify(fr->callno, &sin, &ies)) {
11280                if (!iaxs[fr->callno]) {
11281                   break;
11282                }
11283                /* Send delayed failure */
11284                auth_fail(fr->callno, IAX_COMMAND_REGREJ);
11285                break;
11286             }
11287             if (!iaxs[fr->callno]) {
11288                break;
11289             }
11290             if ((ast_strlen_zero(iaxs[fr->callno]->secret) && ast_strlen_zero(iaxs[fr->callno]->inkeys)) ||
11291                   ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_AUTHENTICATED)) {
11292 
11293                if (f.subclass.integer == IAX_COMMAND_REGREL) {
11294                   memset(&sin, 0, sizeof(sin));
11295                   sin.sin_family = AF_INET;
11296                }
11297                if (update_registry(&sin, fr->callno, ies.devicetype, fd, ies.refresh)) {
11298                   ast_log(LOG_WARNING, "Registry error\n");
11299                }
11300                if (!iaxs[fr->callno]) {
11301                   break;
11302                }
11303                if (ies.provverpres && ies.serviceident && sin.sin_addr.s_addr) {
11304                   ast_mutex_unlock(&iaxsl[fr->callno]);
11305                   check_provisioning(&sin, fd, ies.serviceident, ies.provver);
11306                   ast_mutex_lock(&iaxsl[fr->callno]);
11307                }
11308                break;
11309             }
11310             registry_authrequest(fr->callno);
11311             break;
11312          case IAX_COMMAND_REGACK:
11313             if (iax2_ack_registry(&ies, &sin, fr->callno)) 
11314                ast_log(LOG_WARNING, "Registration failure\n");
11315             /* Send ack immediately, before we destroy */
11316             send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
11317             iax2_destroy(fr->callno);
11318             break;
11319          case IAX_COMMAND_REGREJ:
11320             if (iaxs[fr->callno]->reg) {
11321                if (authdebug) {
11322                   ast_log(LOG_NOTICE, "Registration of '%s' rejected: '%s' from: '%s'\n", iaxs[fr->callno]->reg->username, ies.cause ? ies.cause : "<unknown>", ast_inet_ntoa(sin.sin_addr));
11323                   manager_event(EVENT_FLAG_SYSTEM, "Registry", "ChannelType: IAX2\r\nUsername: %s\r\nStatus: Rejected\r\nCause: %s\r\n", iaxs[fr->callno]->reg->username, ies.cause ? ies.cause : "<unknown>");
11324                }
11325                iaxs[fr->callno]->reg->regstate = REG_STATE_REJECTED;
11326             }
11327             /* Send ack immediately, before we destroy */
11328             send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
11329             iax2_destroy(fr->callno);
11330             break;
11331          case IAX_COMMAND_REGAUTH:
11332             /* Authentication request */
11333             if (registry_rerequest(&ies, fr->callno, &sin)) {
11334                memset(&ied0, 0, sizeof(ied0));
11335                iax_ie_append_str(&ied0, IAX_IE_CAUSE, "No authority found");
11336                iax_ie_append_byte(&ied0, IAX_IE_CAUSECODE, AST_CAUSE_FACILITY_NOT_SUBSCRIBED);
11337                send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
11338             }
11339             break;
11340          case IAX_COMMAND_TXREJ:
11341             iaxs[fr->callno]->transferring = 0;
11342             ast_verb(3, "Channel '%s' unable to transfer\n", iaxs[fr->callno]->owner ? iaxs[fr->callno]->owner->name : "<Unknown>");
11343             memset(&iaxs[fr->callno]->transfer, 0, sizeof(iaxs[fr->callno]->transfer));
11344             if (iaxs[fr->callno]->bridgecallno) {
11345                if (iaxs[iaxs[fr->callno]->bridgecallno]->transferring) {
11346                   iaxs[iaxs[fr->callno]->bridgecallno]->transferring = 0;
11347                   send_command(iaxs[iaxs[fr->callno]->bridgecallno], AST_FRAME_IAX, IAX_COMMAND_TXREJ, 0, NULL, 0, -1);
11348                }
11349             }
11350             break;
11351          case IAX_COMMAND_TXREADY:
11352             if ((iaxs[fr->callno]->transferring == TRANSFER_BEGIN) ||
11353                 (iaxs[fr->callno]->transferring == TRANSFER_MBEGIN)) {
11354                if (iaxs[fr->callno]->transferring == TRANSFER_MBEGIN)
11355                   iaxs[fr->callno]->transferring = TRANSFER_MREADY;
11356                else
11357                   iaxs[fr->callno]->transferring = TRANSFER_READY;
11358                ast_verb(3, "Channel '%s' ready to transfer\n", iaxs[fr->callno]->owner ? iaxs[fr->callno]->owner->name : "<Unknown>");
11359                if (iaxs[fr->callno]->bridgecallno) {
11360                   if ((iaxs[iaxs[fr->callno]->bridgecallno]->transferring == TRANSFER_READY) ||
11361                       (iaxs[iaxs[fr->callno]->bridgecallno]->transferring == TRANSFER_MREADY)) {
11362                      /* They're both ready, now release them. */
11363                      if (iaxs[fr->callno]->transferring == TRANSFER_MREADY) {
11364                         ast_verb(3, "Attempting media bridge of %s and %s\n", iaxs[fr->callno]->owner ? iaxs[fr->callno]->owner->name : "<Unknown>",
11365                               iaxs[iaxs[fr->callno]->bridgecallno]->owner ? iaxs[iaxs[fr->callno]->bridgecallno]->owner->name : "<Unknown>");
11366 
11367                         iaxs[iaxs[fr->callno]->bridgecallno]->transferring = TRANSFER_MEDIA;
11368                         iaxs[fr->callno]->transferring = TRANSFER_MEDIA;
11369 
11370                         memset(&ied0, 0, sizeof(ied0));
11371                         memset(&ied1, 0, sizeof(ied1));
11372                         iax_ie_append_short(&ied0, IAX_IE_CALLNO, iaxs[iaxs[fr->callno]->bridgecallno]->peercallno);
11373                         iax_ie_append_short(&ied1, IAX_IE_CALLNO, iaxs[fr->callno]->peercallno);
11374                         send_command(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_TXMEDIA, 0, ied0.buf, ied0.pos, -1);
11375                         send_command(iaxs[iaxs[fr->callno]->bridgecallno], AST_FRAME_IAX, IAX_COMMAND_TXMEDIA, 0, ied1.buf, ied1.pos, -1);
11376                      } else {
11377                         ast_verb(3, "Releasing %s and %s\n", iaxs[fr->callno]->owner ? iaxs[fr->callno]->owner->name : "<Unknown>",
11378                               iaxs[iaxs[fr->callno]->bridgecallno]->owner ? iaxs[iaxs[fr->callno]->bridgecallno]->owner->name : "<Unknown>");
11379 
11380                         iaxs[iaxs[fr->callno]->bridgecallno]->transferring = TRANSFER_RELEASED;
11381                         iaxs[fr->callno]->transferring = TRANSFER_RELEASED;
11382                         ast_set_flag64(iaxs[iaxs[fr->callno]->bridgecallno], IAX_ALREADYGONE);
11383                         ast_set_flag64(iaxs[fr->callno], IAX_ALREADYGONE);
11384 
11385                         /* Stop doing lag & ping requests */
11386                         stop_stuff(fr->callno);
11387                         stop_stuff(iaxs[fr->callno]->bridgecallno);
11388 
11389                         memset(&ied0, 0, sizeof(ied0));
11390                         memset(&ied1, 0, sizeof(ied1));
11391                         iax_ie_append_short(&ied0, IAX_IE_CALLNO, iaxs[iaxs[fr->callno]->bridgecallno]->peercallno);
11392                         iax_ie_append_short(&ied1, IAX_IE_CALLNO, iaxs[fr->callno]->peercallno);
11393                         send_command(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_TXREL, 0, ied0.buf, ied0.pos, -1);
11394                         send_command(iaxs[iaxs[fr->callno]->bridgecallno], AST_FRAME_IAX, IAX_COMMAND_TXREL, 0, ied1.buf, ied1.pos, -1);
11395                      }
11396 
11397                   }
11398                }
11399             }
11400             break;
11401          case IAX_COMMAND_TXREQ:
11402             try_transfer(iaxs[fr->callno], &ies);
11403             break;
11404          case IAX_COMMAND_TXCNT:
11405             if (iaxs[fr->callno]->transferring)
11406                send_command_transfer(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_TXACC, 0, NULL, 0);
11407             break;
11408          case IAX_COMMAND_TXREL:
11409             /* Send ack immediately, rather than waiting until we've changed addresses */
11410             send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
11411             complete_transfer(fr->callno, &ies);
11412             stop_stuff(fr->callno); /* for attended transfer to work with libiax */
11413             break;   
11414          case IAX_COMMAND_TXMEDIA:
11415             if (iaxs[fr->callno]->transferring == TRANSFER_READY) {
11416                AST_LIST_TRAVERSE(&frame_queue[fr->callno], cur, list) {
11417                   /* Cancel any outstanding frames and start anew */
11418                   if (cur->transfer) {
11419                      cur->retries = -1;
11420                   }
11421                }
11422                /* Start sending our media to the transfer address, but otherwise leave the call as-is */
11423                iaxs[fr->callno]->transferring = TRANSFER_MEDIAPASS;
11424             }
11425             break;
11426          case IAX_COMMAND_RTKEY:
11427             if (!IAX_CALLENCRYPTED(iaxs[fr->callno])) {
11428                ast_log(LOG_WARNING, 
11429                   "we've been told to rotate our encryption key, "
11430                   "but this isn't an encrypted call. bad things will happen.\n"
11431                );
11432                break;
11433             }
11434 
11435             IAX_DEBUGDIGEST("Receiving", ies.challenge);
11436 
11437             ast_aes_set_decrypt_key((unsigned char *) ies.challenge, &iaxs[fr->callno]->dcx);
11438             break;
11439          case IAX_COMMAND_DPREP:
11440             complete_dpreply(iaxs[fr->callno], &ies);
11441             break;
11442          case IAX_COMMAND_UNSUPPORT:
11443             ast_log(LOG_NOTICE, "Peer did not understand our iax command '%d'\n", ies.iax_unknown);
11444             break;
11445          case IAX_COMMAND_FWDOWNL:
11446             /* Firmware download */
11447             if (!ast_test_flag64(&globalflags, IAX_ALLOWFWDOWNLOAD)) {
11448                send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_UNSUPPORT, 0, NULL, 0, -1);
11449                break;
11450             }
11451             memset(&ied0, 0, sizeof(ied0));
11452             res = iax_firmware_append(&ied0, (unsigned char *)ies.devicetype, ies.fwdesc);
11453             if (res < 0)
11454                send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
11455             else if (res > 0)
11456                send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_FWDATA, 0, ied0.buf, ied0.pos, -1);
11457             else
11458                send_command(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_FWDATA, 0, ied0.buf, ied0.pos, -1);
11459             break;
11460          case IAX_COMMAND_CALLTOKEN:
11461          {
11462             struct iax_frame *cur;
11463             /* find last sent frame */
11464             if ((cur = AST_LIST_LAST(&frame_queue[fr->callno])) && ies.calltoken && ies.calltokendata) {
11465                resend_with_token(fr->callno, cur, (char *) ies.calltokendata);
11466             }
11467             break;
11468          }
11469          default:
11470             ast_debug(1, "Unknown IAX command %d on %d/%d\n", f.subclass.integer, fr->callno, iaxs[fr->callno]->peercallno);
11471             memset(&ied0, 0, sizeof(ied0));
11472             iax_ie_append_byte(&ied0, IAX_IE_IAX_UNKNOWN, f.subclass.integer);
11473             send_command(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_UNSUPPORT, 0, ied0.buf, ied0.pos, -1);
11474          }
11475          /* Free remote variables (if any) */
11476          if (ies.vars) {
11477             ast_variables_destroy(ies.vars);
11478             ast_debug(1, "I can haz IAX vars, but they is no good :-(\n");
11479             ies.vars = NULL;
11480          }
11481 
11482          /* Don't actually pass these frames along */
11483          if ((f.subclass.integer != IAX_COMMAND_ACK) && 
11484            (f.subclass.integer != IAX_COMMAND_TXCNT) && 
11485            (f.subclass.integer != IAX_COMMAND_TXACC) && 
11486            (f.subclass.integer != IAX_COMMAND_INVAL) &&
11487            (f.subclass.integer != IAX_COMMAND_VNAK)) { 
11488             if (iaxs[fr->callno] && iaxs[fr->callno]->aseqno != iaxs[fr->callno]->iseqno)
11489                send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
11490          }
11491          ast_mutex_unlock(&iaxsl[fr->callno]);
11492          return 1;
11493       }
11494       /* Unless this is an ACK or INVAL frame, ack it */
11495       if (iaxs[fr->callno] && iaxs[fr->callno]->aseqno != iaxs[fr->callno]->iseqno)
11496          send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
11497    } else if (minivid) {
11498       f.frametype = AST_FRAME_VIDEO;
11499       if (iaxs[fr->callno]->videoformat > 0) 
11500          f.subclass.codec = iaxs[fr->callno]->videoformat | (ntohs(vh->ts) & 0x8000LL ? 1 : 0);
11501       else {
11502          ast_log(LOG_WARNING, "Received mini frame before first full video frame\n");
11503          iax2_vnak(fr->callno);
11504          ast_variables_destroy(ies.vars);
11505          ast_mutex_unlock(&iaxsl[fr->callno]);
11506          return 1;
11507       }
11508       f.datalen = res - sizeof(*vh);
11509       if (f.datalen)
11510          f.data.ptr = thread->buf + sizeof(*vh);
11511       else
11512          f.data.ptr = NULL;
11513 #ifdef IAXTESTS
11514       if (test_resync) {
11515          fr->ts = (iaxs[fr->callno]->last & 0xFFFF8000L) | ((ntohs(vh->ts) + test_resync) & 0x7fff);
11516       } else
11517 #endif /* IAXTESTS */
11518          fr->ts = (iaxs[fr->callno]->last & 0xFFFF8000L) | (ntohs(vh->ts) & 0x7fff);
11519    } else {
11520       /* A mini frame */
11521       f.frametype = AST_FRAME_VOICE;
11522       if (iaxs[fr->callno]->voiceformat > 0)
11523          f.subclass.codec = iaxs[fr->callno]->voiceformat;
11524       else {
11525          ast_debug(1, "Received mini frame before first full voice frame\n");
11526          iax2_vnak(fr->callno);
11527          ast_variables_destroy(ies.vars);
11528          ast_mutex_unlock(&iaxsl[fr->callno]);
11529          return 1;
11530       }
11531       f.datalen = res - sizeof(struct ast_iax2_mini_hdr);
11532       if (f.datalen < 0) {
11533          ast_log(LOG_WARNING, "Datalen < 0?\n");
11534          ast_variables_destroy(ies.vars);
11535          ast_mutex_unlock(&iaxsl[fr->callno]);
11536          return 1;
11537       }
11538       if (f.datalen)
11539          f.data.ptr = thread->buf + sizeof(*mh);
11540       else
11541          f.data.ptr = NULL;
11542 #ifdef IAXTESTS
11543       if (test_resync) {
11544          fr->ts = (iaxs[fr->callno]->last & 0xFFFF0000L) | ((ntohs(mh->ts) + test_resync) & 0xffff);
11545       } else
11546 #endif /* IAXTESTS */
11547       fr->ts = (iaxs[fr->callno]->last & 0xFFFF0000L) | ntohs(mh->ts);
11548       /* FIXME? Surely right here would be the right place to undo timestamp wraparound? */
11549    }
11550    /* Don't pass any packets until we're started */
11551    if (!ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED)) {
11552       ast_variables_destroy(ies.vars);
11553       ast_mutex_unlock(&iaxsl[fr->callno]);
11554       return 1;
11555    }
11556    /* Don't allow connected line updates unless we are configured to */
11557    if (f.frametype == AST_FRAME_CONTROL && f.subclass.integer == AST_CONTROL_CONNECTED_LINE) {
11558       struct ast_party_connected_line connected;
11559 
11560       if (!ast_test_flag64(iaxs[fr->callno], IAX_RECVCONNECTEDLINE)) {
11561          ast_variables_destroy(ies.vars);
11562          ast_mutex_unlock(&iaxsl[fr->callno]);
11563          return 1;
11564       }
11565 
11566       /* Initialize defaults */
11567       ast_party_connected_line_init(&connected);
11568       connected.id.number.presentation = iaxs[fr->callno]->calling_pres;
11569       connected.id.name.presentation = iaxs[fr->callno]->calling_pres;
11570 
11571       if (!ast_connected_line_parse_data(f.data.ptr, f.datalen, &connected)) {
11572          ast_string_field_set(iaxs[fr->callno], cid_num, connected.id.number.str);
11573          ast_string_field_set(iaxs[fr->callno], cid_name, connected.id.name.str);
11574          iaxs[fr->callno]->calling_pres = ast_party_id_presentation(&connected.id);
11575 
11576          if (iaxs[fr->callno]->owner) {
11577             ast_set_callerid(iaxs[fr->callno]->owner,
11578                S_COR(connected.id.number.valid, connected.id.number.str, ""),
11579                S_COR(connected.id.name.valid, connected.id.name.str, ""),
11580                NULL);
11581             iaxs[fr->callno]->owner->caller.id.number.presentation = connected.id.number.presentation;
11582             iaxs[fr->callno]->owner->caller.id.name.presentation = connected.id.name.presentation;
11583          }
11584       }
11585       ast_party_connected_line_free(&connected);
11586    }
11587    /* Common things */
11588    f.src = "IAX2";
11589    f.mallocd = 0;
11590    f.offset = 0;
11591    f.len = 0;
11592    if (f.datalen && (f.frametype == AST_FRAME_VOICE)) {
11593       f.samples = ast_codec_get_samples(&f);
11594       /* We need to byteswap incoming slinear samples from network byte order */
11595       if (f.subclass.codec == AST_FORMAT_SLINEAR)
11596          ast_frame_byteswap_be(&f);
11597    } else
11598       f.samples = 0;
11599    iax_frame_wrap(fr, &f);
11600 
11601    /* If this is our most recent packet, use it as our basis for timestamping */
11602    if (iaxs[fr->callno] && iaxs[fr->callno]->last < fr->ts) {
11603       /*iaxs[fr->callno]->last = fr->ts; (do it afterwards cos schedule/forward_delivery needs the last ts too)*/
11604       fr->outoforder = 0;
11605    } else {
11606       if (iaxdebug && iaxs[fr->callno])
11607          ast_debug(1, "Received out of order packet... (type=%d, subclass %d, ts = %d, last = %d)\n", f.frametype, f.subclass.integer, fr->ts, iaxs[fr->callno]->last);
11608       fr->outoforder = -1;
11609    }
11610    fr->cacheable = ((f.frametype == AST_FRAME_VOICE) || (f.frametype == AST_FRAME_VIDEO));
11611    duped_fr = iaxfrdup2(fr);
11612    if (duped_fr) {
11613       schedule_delivery(duped_fr, updatehistory, 0, &fr->ts);
11614    }
11615    if (iaxs[fr->callno] && iaxs[fr->callno]->last < fr->ts) {
11616       iaxs[fr->callno]->last = fr->ts;
11617 #if 1
11618       if (iaxdebug)
11619          ast_debug(1, "For call=%d, set last=%d\n", fr->callno, fr->ts);
11620 #endif
11621    }
11622 
11623    /* Always run again */
11624    ast_variables_destroy(ies.vars);
11625    ast_mutex_unlock(&iaxsl[fr->callno]);
11626    return 1;
11627 }
11628 
11629 /* Function to clean up process thread if it is cancelled */
11630 static void iax2_process_thread_cleanup(void *data)
11631 {
11632    struct iax2_thread *thread = data;
11633    ast_mutex_destroy(&thread->lock);
11634    ast_cond_destroy(&thread->cond);
11635    ast_mutex_destroy(&thread->init_lock);
11636    ast_cond_destroy(&thread->init_cond);
11637    ast_free(thread);
11638    ast_atomic_dec_and_test(&iaxactivethreadcount);
11639 }
11640 
11641 static void *iax2_process_thread(void *data)
11642 {
11643    struct iax2_thread *thread = data;
11644    struct timeval wait;
11645    struct timespec ts;
11646    int put_into_idle = 0;
11647    int first_time = 1;
11648    int old_state;
11649 
11650    ast_atomic_fetchadd_int(&iaxactivethreadcount, 1);
11651 
11652    pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &old_state);
11653    pthread_cleanup_push(iax2_process_thread_cleanup, data);
11654 
11655    for (;;) {
11656       /* Wait for something to signal us to be awake */
11657       ast_mutex_lock(&thread->lock);
11658 
11659       if (thread->stop) {
11660          ast_mutex_unlock(&thread->lock);
11661          break;
11662       }
11663 
11664       /* Flag that we're ready to accept signals */
11665       if (first_time) {
11666          signal_condition(&thread->init_lock, &thread->init_cond);
11667          first_time = 0;
11668       }
11669 
11670       /* Put into idle list if applicable */
11671       if (put_into_idle) {
11672          insert_idle_thread(thread);
11673       }
11674 
11675       if (thread->type == IAX_THREAD_TYPE_DYNAMIC) {
11676          struct iax2_thread *t = NULL;
11677          /* Wait to be signalled or time out */
11678          wait = ast_tvadd(ast_tvnow(), ast_samp2tv(30000, 1000));
11679          ts.tv_sec = wait.tv_sec;
11680          ts.tv_nsec = wait.tv_usec * 1000;
11681          if (ast_cond_timedwait(&thread->cond, &thread->lock, &ts) == ETIMEDOUT) {
11682             /* This thread was never put back into the available dynamic
11683              * thread list, so just go away. */
11684             if (!put_into_idle || thread->stop) {
11685                ast_mutex_unlock(&thread->lock);
11686                break;
11687             }
11688             AST_LIST_LOCK(&dynamic_list);
11689             /* Account for the case where this thread is acquired *right* after a timeout */
11690             if ((t = AST_LIST_REMOVE(&dynamic_list, thread, list)))
11691                ast_atomic_fetchadd_int(&iaxdynamicthreadcount, -1);
11692             AST_LIST_UNLOCK(&dynamic_list);
11693             if (t) {
11694                /* This dynamic thread timed out waiting for a task and was
11695                 * not acquired immediately after the timeout, 
11696                 * so it's time to go away. */
11697                ast_mutex_unlock(&thread->lock);
11698                break;
11699             }
11700             /* Someone grabbed our thread *right* after we timed out.
11701              * Wait for them to set us up with something to do and signal
11702              * us to continue. */
11703             wait = ast_tvadd(ast_tvnow(), ast_samp2tv(30000, 1000));
11704             ts.tv_sec = wait.tv_sec;
11705             ts.tv_nsec = wait.tv_usec * 1000;
11706             if (ast_cond_timedwait(&thread->cond, &thread->lock, &ts) == ETIMEDOUT) {
11707                ast_mutex_unlock(&thread->lock);
11708                break;
11709             }
11710          }
11711       } else {
11712          ast_cond_wait(&thread->cond, &thread->lock);
11713       }
11714 
11715       /* Go back into our respective list */
11716       put_into_idle = 1;
11717 
11718       ast_mutex_unlock(&thread->lock);
11719 
11720       if (thread->stop) {
11721          break;
11722       }
11723 
11724       if (thread->iostate == IAX_IOSTATE_IDLE)
11725          continue;
11726 
11727       /* See what we need to do */
11728       switch (thread->iostate) {
11729       case IAX_IOSTATE_READY:
11730          thread->actions++;
11731          thread->iostate = IAX_IOSTATE_PROCESSING;
11732          socket_process(thread);
11733          handle_deferred_full_frames(thread);
11734          break;
11735       case IAX_IOSTATE_SCHEDREADY:
11736          thread->actions++;
11737          thread->iostate = IAX_IOSTATE_PROCESSING;
11738 #ifdef SCHED_MULTITHREADED
11739          thread->schedfunc(thread->scheddata);
11740 #endif      
11741       default:
11742          break;
11743       }
11744       time(&thread->checktime);
11745       thread->iostate = IAX_IOSTATE_IDLE;
11746 #ifdef DEBUG_SCHED_MULTITHREAD
11747       thread->curfunc[0]='\0';
11748 #endif      
11749 
11750       /* The network thread added us to the active_thread list when we were given
11751        * frames to process, Now that we are done, we must remove ourselves from
11752        * the active list, and return to the idle list */
11753       AST_LIST_LOCK(&active_list);
11754       AST_LIST_REMOVE(&active_list, thread, list);
11755       AST_LIST_UNLOCK(&active_list);
11756 
11757       /* Make sure another frame didn't sneak in there after we thought we were done. */
11758       handle_deferred_full_frames(thread);
11759    }
11760 
11761    /*!
11762     * \note For some reason, idle threads are exiting without being removed
11763     * from an idle list, which is causing memory corruption.  Forcibly remove
11764     * it from the list, if it's there.
11765     */
11766    AST_LIST_LOCK(&idle_list);
11767    AST_LIST_REMOVE(&idle_list, thread, list);
11768    AST_LIST_UNLOCK(&idle_list);
11769 
11770    AST_LIST_LOCK(&dynamic_list);
11771    AST_LIST_REMOVE(&dynamic_list, thread, list);
11772    AST_LIST_UNLOCK(&dynamic_list);
11773 
11774    if (!thread->stop) {
11775       /* Nobody asked me to stop so nobody is waiting to join me. */
11776       pthread_detach(pthread_self());
11777    }
11778 
11779    /* I am exiting here on my own volition, I need to clean up my own data structures
11780    * Assume that I am no longer in any of the lists (idle, active, or dynamic)
11781    */
11782    pthread_cleanup_pop(1);
11783    return NULL;
11784 }
11785 
11786 static int iax2_do_register(struct iax2_registry *reg)
11787 {
11788    struct iax_ie_data ied;
11789    if (iaxdebug)
11790       ast_debug(1, "Sending registration request for '%s'\n", reg->username);
11791 
11792    if (reg->dnsmgr && 
11793        ((reg->regstate == REG_STATE_TIMEOUT) || !ast_sockaddr_ipv4(&reg->addr))) {
11794       /* Maybe the IP has changed, force DNS refresh */
11795       ast_dnsmgr_refresh(reg->dnsmgr);
11796    }
11797    
11798    /*
11799     * if IP has Changed, free allocated call to create a new one with new IP
11800     * call has the pointer to IP and must be updated to the new one
11801     */
11802    if (reg->dnsmgr && ast_dnsmgr_changed(reg->dnsmgr) && (reg->callno > 0)) {
11803       int callno = reg->callno;
11804       ast_mutex_lock(&iaxsl[callno]);
11805       iax2_destroy(callno);
11806       ast_mutex_unlock(&iaxsl[callno]);
11807       reg->callno = 0;
11808    }
11809    if (!ast_sockaddr_ipv4(&reg->addr)) {
11810       if (iaxdebug)
11811          ast_debug(1, "Unable to send registration request for '%s' without IP address\n", reg->username);
11812       /* Setup the next registration attempt */
11813       reg->expire = iax2_sched_replace(reg->expire, sched, 
11814          (5 * reg->refresh / 6) * 1000, iax2_do_register_s, reg);
11815       return -1;
11816    }
11817 
11818    if (!reg->callno) {
11819       struct sockaddr_in reg_addr;
11820 
11821       ast_debug(3, "Allocate call number\n");
11822 
11823       ast_sockaddr_to_sin(&reg->addr, &reg_addr);
11824 
11825       reg->callno = find_callno_locked(0, 0, &reg_addr, NEW_FORCE, defaultsockfd, 0);
11826       if (reg->callno < 1) {
11827          ast_log(LOG_WARNING, "Unable to create call for registration\n");
11828          return -1;
11829       } else
11830          ast_debug(3, "Registration created on call %d\n", reg->callno);
11831       iaxs[reg->callno]->reg = reg;
11832       ast_mutex_unlock(&iaxsl[reg->callno]);
11833    }
11834    /* Setup the next registration a little early */
11835    reg->expire = iax2_sched_replace(reg->expire, sched, 
11836       (5 * reg->refresh / 6) * 1000, iax2_do_register_s, reg);
11837    /* Send the request */
11838    memset(&ied, 0, sizeof(ied));
11839    iax_ie_append_str(&ied, IAX_IE_USERNAME, reg->username);
11840    iax_ie_append_short(&ied, IAX_IE_REFRESH, reg->refresh);
11841    add_empty_calltoken_ie(iaxs[reg->callno], &ied); /* this _MUST_ be the last ie added */
11842    send_command(iaxs[reg->callno],AST_FRAME_IAX, IAX_COMMAND_REGREQ, 0, ied.buf, ied.pos, -1);
11843    reg->regstate = REG_STATE_REGSENT;
11844    return 0;
11845 }
11846 
11847 static int iax2_provision(struct sockaddr_in *end, int sockfd, const char *dest, const char *template, int force)
11848 {
11849    /* Returns 1 if provisioned, -1 if not able to find destination, or 0 if no provisioning
11850       is found for template */
11851    struct iax_ie_data provdata;
11852    struct iax_ie_data ied;
11853    unsigned int sig;
11854    struct sockaddr_in sin;
11855    int callno;
11856    struct create_addr_info cai;
11857 
11858    memset(&cai, 0, sizeof(cai));
11859 
11860    ast_debug(1, "Provisioning '%s' from template '%s'\n", dest, template);
11861 
11862    if (iax_provision_build(&provdata, &sig, template, force)) {
11863       ast_debug(1, "No provisioning found for template '%s'\n", template);
11864       return 0;
11865    }
11866 
11867    if (end) {
11868       memcpy(&sin, end, sizeof(sin));
11869       cai.sockfd = sockfd;
11870    } else if (create_addr(dest, NULL, &sin, &cai))
11871       return -1;
11872 
11873    /* Build the rest of the message */
11874    memset(&ied, 0, sizeof(ied));
11875    iax_ie_append_raw(&ied, IAX_IE_PROVISIONING, provdata.buf, provdata.pos);
11876 
11877    callno = find_callno_locked(0, 0, &sin, NEW_FORCE, cai.sockfd, 0);
11878    if (!callno)
11879       return -1;
11880 
11881    if (iaxs[callno]) {
11882       /* Schedule autodestruct in case they don't ever give us anything back */
11883       iaxs[callno]->autoid = iax2_sched_replace(iaxs[callno]->autoid, 
11884          sched, 15000, auto_hangup, (void *)(long)callno);
11885       ast_set_flag64(iaxs[callno], IAX_PROVISION);
11886       /* Got a call number now, so go ahead and send the provisioning information */
11887       send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_PROVISION, 0, ied.buf, ied.pos, -1);
11888    }
11889    ast_mutex_unlock(&iaxsl[callno]);
11890 
11891    return 1;
11892 }
11893 
11894 static char *papp = "IAX2Provision";
11895 
11896 /*! iax2provision
11897 \ingroup applications
11898 */
11899 static int iax2_prov_app(struct ast_channel *chan, const char *data)
11900 {
11901    int res;
11902    char *sdata;
11903    char *opts;
11904    int force =0;
11905    unsigned short callno = PTR_TO_CALLNO(chan->tech_pvt);
11906    if (ast_strlen_zero(data))
11907       data = "default";
11908    sdata = ast_strdupa(data);
11909    opts = strchr(sdata, '|');
11910    if (opts)
11911       *opts='\0';
11912 
11913    if (chan->tech != &iax2_tech) {
11914       ast_log(LOG_NOTICE, "Can't provision a non-IAX device!\n");
11915       return -1;
11916    } 
11917    if (!callno || !iaxs[callno] || !iaxs[callno]->addr.sin_addr.s_addr) {
11918       ast_log(LOG_NOTICE, "Can't provision something with no IP?\n");
11919       return -1;
11920    }
11921    res = iax2_provision(&iaxs[callno]->addr, iaxs[callno]->sockfd, NULL, sdata, force);
11922    ast_verb(3, "Provisioned IAXY at '%s' with '%s'= %d\n",
11923       ast_inet_ntoa(iaxs[callno]->addr.sin_addr),
11924       sdata, res);
11925    return res;
11926 }
11927 
11928 static char *handle_cli_iax2_provision(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
11929 {
11930    int force = 0;
11931    int res;
11932 
11933    switch (cmd) {
11934    case CLI_INIT:
11935       e->command = "iax2 provision";
11936       e->usage = 
11937          "Usage: iax2 provision <host> <template> [forced]\n"
11938          "       Provisions the given peer or IP address using a template\n"
11939          "       matching either 'template' or '*' if the template is not\n"
11940          "       found.  If 'forced' is specified, even empty provisioning\n"
11941          "       fields will be provisioned as empty fields.\n";
11942       return NULL;
11943    case CLI_GENERATE:
11944       if (a->pos == 3)
11945          return iax_prov_complete_template(a->line, a->word, a->pos, a->n);
11946       return NULL;
11947    }
11948 
11949    if (a->argc < 4)
11950       return CLI_SHOWUSAGE;
11951    if (a->argc > 4) {
11952       if (!strcasecmp(a->argv[4], "forced"))
11953          force = 1;
11954       else
11955          return CLI_SHOWUSAGE;
11956    }
11957    res = iax2_provision(NULL, -1, a->argv[2], a->argv[3], force);
11958    if (res < 0)
11959       ast_cli(a->fd, "Unable to find peer/address '%s'\n", a->argv[2]);
11960    else if (res < 1)
11961       ast_cli(a->fd, "No template (including wildcard) matching '%s'\n", a->argv[3]);
11962    else
11963       ast_cli(a->fd, "Provisioning '%s' with template '%s'%s\n", a->argv[2], a->argv[3], force ? ", forced" : "");
11964    return CLI_SUCCESS;
11965 }
11966 
11967 static void __iax2_poke_noanswer(const void *data)
11968 {
11969    struct iax2_peer *peer = (struct iax2_peer *)data;
11970    int callno;
11971 
11972    if (peer->lastms > -1) {
11973       ast_log(LOG_NOTICE, "Peer '%s' is now UNREACHABLE! Time: %d\n", peer->name, peer->lastms);
11974       manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: IAX2\r\nPeer: IAX2/%s\r\nPeerStatus: Unreachable\r\nTime: %d\r\n", peer->name, peer->lastms);
11975       ast_devstate_changed(AST_DEVICE_UNAVAILABLE, "IAX2/%s", peer->name); /* Activate notification */
11976    }
11977    if ((callno = peer->callno) > 0) {
11978       ast_mutex_lock(&iaxsl[callno]);
11979       iax2_destroy(callno);
11980       ast_mutex_unlock(&iaxsl[callno]);
11981    }
11982    peer->callno = 0;
11983    peer->lastms = -1;
11984    /* Try again quickly */
11985    peer->pokeexpire = iax2_sched_add(sched, peer->pokefreqnotok, iax2_poke_peer_s, peer_ref(peer));
11986    if (peer->pokeexpire == -1)
11987       peer_unref(peer);
11988 }
11989 
11990 static int iax2_poke_noanswer(const void *data)
11991 {
11992    struct iax2_peer *peer = (struct iax2_peer *)data;
11993    peer->pokeexpire = -1;
11994 #ifdef SCHED_MULTITHREADED
11995    if (schedule_action(__iax2_poke_noanswer, data))
11996 #endif      
11997       __iax2_poke_noanswer(data);
11998    peer_unref(peer);
11999    return 0;
12000 }
12001 
12002 static int iax2_poke_peer_cb(void *obj, void *arg, int flags)
12003 {
12004    struct iax2_peer *peer = obj;
12005 
12006    iax2_poke_peer(peer, 0);
12007 
12008    return 0;
12009 }
12010 
12011 static int iax2_poke_peer(struct iax2_peer *peer, int heldcall)
12012 {
12013    int callno;
12014    struct sockaddr_in peer_addr;
12015 
12016    if (!peer->maxms || (!ast_sockaddr_ipv4(&peer->addr) && !peer->dnsmgr)) {
12017       /* IF we have no IP without dnsmgr, or this isn't to be monitored, return
12018         immediately after clearing things out */
12019       peer->lastms = 0;
12020       peer->historicms = 0;
12021       peer->pokeexpire = -1;
12022       peer->callno = 0;
12023       return 0;
12024    }
12025 
12026    ast_sockaddr_to_sin(&peer->addr, &peer_addr);
12027 
12028    /* The peer could change the callno inside iax2_destroy, since we do deadlock avoidance */
12029    if ((callno = peer->callno) > 0) {
12030       ast_log(LOG_NOTICE, "Still have a callno...\n");
12031       ast_mutex_lock(&iaxsl[callno]);
12032       iax2_destroy(callno);
12033       ast_mutex_unlock(&iaxsl[callno]);
12034    }
12035    if (heldcall)
12036       ast_mutex_unlock(&iaxsl[heldcall]);
12037    callno = peer->callno = find_callno(0, 0, &peer_addr, NEW_FORCE, peer->sockfd, 0);
12038    if (heldcall)
12039       ast_mutex_lock(&iaxsl[heldcall]);
12040    if (peer->callno < 1) {
12041       ast_log(LOG_WARNING, "Unable to allocate call for poking peer '%s'\n", peer->name);
12042       return -1;
12043    }
12044 
12045    /* Speed up retransmission times for this qualify call */
12046    iaxs[peer->callno]->pingtime = peer->maxms / 4 + 1;
12047    iaxs[peer->callno]->peerpoke = peer;
12048 
12049    if (peer->pokeexpire > -1) {
12050       if (!ast_sched_thread_del(sched, peer->pokeexpire)) {
12051          peer->pokeexpire = -1;
12052          peer_unref(peer);
12053       }
12054    }
12055  
12056    /* Queue up a new task to handle no reply */
12057    /* If the host is already unreachable then use the unreachable interval instead */
12058    if (peer->lastms < 0)
12059       peer->pokeexpire = iax2_sched_add(sched, peer->pokefreqnotok, iax2_poke_noanswer, peer_ref(peer));
12060    else
12061       peer->pokeexpire = iax2_sched_add(sched, DEFAULT_MAXMS * 2, iax2_poke_noanswer, peer_ref(peer));
12062 
12063    if (peer->pokeexpire == -1)
12064       peer_unref(peer);
12065 
12066    /* And send the poke */
12067    ast_mutex_lock(&iaxsl[callno]);
12068    if (iaxs[callno]) {
12069       struct iax_ie_data ied = {
12070          .buf = { 0 },
12071          .pos = 0,
12072       };
12073       add_empty_calltoken_ie(iaxs[callno], &ied); /* this _MUST_ be the last ie added */
12074       send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_POKE, 0, ied.buf, ied.pos, -1);
12075    }
12076    ast_mutex_unlock(&iaxsl[callno]);
12077 
12078    return 0;
12079 }
12080 
12081 static void free_context(struct iax2_context *con)
12082 {
12083    struct iax2_context *conl;
12084    while(con) {
12085       conl = con;
12086       con = con->next;
12087       ast_free(conl);
12088    }
12089 }
12090 
12091 static struct ast_channel *iax2_request(const char *type, format_t format, const struct ast_channel *requestor, void *data, int *cause)
12092 {
12093    int callno;
12094    int res;
12095    format_t fmt, native;
12096    struct sockaddr_in sin;
12097    struct ast_channel *c;
12098    struct parsed_dial_string pds;
12099    struct create_addr_info cai;
12100    char *tmpstr;
12101 
12102    memset(&pds, 0, sizeof(pds));
12103    tmpstr = ast_strdupa(data);
12104    parse_dial_string(tmpstr, &pds);
12105 
12106    if (ast_strlen_zero(pds.peer)) {
12107       ast_log(LOG_WARNING, "No peer provided in the IAX2 dial string '%s'\n", (char *) data);
12108       return NULL;
12109    }
12110           
12111    memset(&cai, 0, sizeof(cai));
12112    cai.capability = iax2_capability;
12113 
12114    ast_copy_flags64(&cai, &globalflags, IAX_NOTRANSFER | IAX_TRANSFERMEDIA | IAX_USEJITTERBUF | IAX_FORCEJITTERBUF | IAX_SENDCONNECTEDLINE | IAX_RECVCONNECTEDLINE);
12115    
12116    /* Populate our address from the given */
12117    if (create_addr(pds.peer, NULL, &sin, &cai)) {
12118       *cause = AST_CAUSE_UNREGISTERED;
12119       return NULL;
12120    }
12121 
12122    if (pds.port)
12123       sin.sin_port = htons(atoi(pds.port));
12124 
12125    callno = find_callno_locked(0, 0, &sin, NEW_FORCE, cai.sockfd, 0);
12126    if (callno < 1) {
12127       ast_log(LOG_WARNING, "Unable to create call\n");
12128       *cause = AST_CAUSE_CONGESTION;
12129       return NULL;
12130    }
12131 
12132    /* If this is a trunk, update it now */
12133    ast_copy_flags64(iaxs[callno], &cai, IAX_TRUNK | IAX_SENDANI | IAX_NOTRANSFER | IAX_TRANSFERMEDIA | IAX_USEJITTERBUF | IAX_FORCEJITTERBUF | IAX_SENDCONNECTEDLINE | IAX_RECVCONNECTEDLINE);
12134    if (ast_test_flag64(&cai, IAX_TRUNK)) {
12135       int new_callno;
12136       if ((new_callno = make_trunk(callno, 1)) != -1)
12137          callno = new_callno;
12138    }
12139    iaxs[callno]->maxtime = cai.maxtime;
12140    if (cai.found)
12141       ast_string_field_set(iaxs[callno], host, pds.peer);
12142 
12143    c = ast_iax2_new(callno, AST_STATE_DOWN, cai.capability, requestor ? requestor->linkedid : NULL);
12144 
12145    ast_mutex_unlock(&iaxsl[callno]);
12146 
12147    if (c) {
12148       /* Choose a format we can live with */
12149       if (c->nativeformats & format) 
12150          c->nativeformats &= format;
12151       else {
12152          native = c->nativeformats;
12153          fmt = format;
12154          res = ast_translator_best_choice(&fmt, &native);
12155          if (res < 0) {
12156             ast_log(LOG_WARNING, "Unable to create translator path for %s to %s on %s\n",
12157                ast_getformatname(c->nativeformats), ast_getformatname(fmt), c->name);
12158             ast_hangup(c);
12159             return NULL;
12160          }
12161          c->nativeformats = native;
12162       }
12163       c->readformat = ast_best_codec(c->nativeformats);
12164       c->writeformat = c->readformat;
12165    }
12166 
12167    return c;
12168 }
12169 
12170 static void *network_thread(void *ignore)
12171 {
12172    if (timer) {
12173       ast_io_add(io, ast_timer_fd(timer), timing_read, AST_IO_IN | AST_IO_PRI, NULL);
12174    }
12175 
12176    for (;;) {
12177       pthread_testcancel();
12178       /* Wake up once a second just in case SIGURG was sent while
12179        * we weren't in poll(), to make sure we don't hang when trying
12180        * to unload. */
12181       ast_io_wait(io, 1000);
12182    }
12183 
12184    return NULL;
12185 }
12186 
12187 static int start_network_thread(void)
12188 {
12189    struct iax2_thread *thread;
12190    int threadcount = 0;
12191    int x;
12192    for (x = 0; x < iaxthreadcount; x++) {
12193       thread = ast_calloc(1, sizeof(*thread));
12194       if (thread) {
12195          thread->type = IAX_THREAD_TYPE_POOL;
12196          thread->threadnum = ++threadcount;
12197          ast_mutex_init(&thread->lock);
12198          ast_cond_init(&thread->cond, NULL);
12199          ast_mutex_init(&thread->init_lock);
12200          ast_cond_init(&thread->init_cond, NULL);
12201          if (ast_pthread_create_background(&thread->threadid, NULL, iax2_process_thread, thread)) {
12202             ast_log(LOG_WARNING, "Failed to create new thread!\n");
12203             ast_mutex_destroy(&thread->lock);
12204             ast_cond_destroy(&thread->cond);
12205             ast_mutex_destroy(&thread->init_lock);
12206             ast_cond_destroy(&thread->init_cond);
12207             ast_free(thread);
12208             thread = NULL;
12209             continue;
12210          }
12211          AST_LIST_LOCK(&idle_list);
12212          AST_LIST_INSERT_TAIL(&idle_list, thread, list);
12213          AST_LIST_UNLOCK(&idle_list);
12214       }
12215    }
12216    ast_pthread_create_background(&netthreadid, NULL, network_thread, NULL);
12217    ast_verb(2, "%d helper threads started\n", threadcount);
12218    return 0;
12219 }
12220 
12221 static struct iax2_context *build_context(const char *context)
12222 {
12223    struct iax2_context *con;
12224 
12225    if ((con = ast_calloc(1, sizeof(*con))))
12226       ast_copy_string(con->context, context, sizeof(con->context));
12227    
12228    return con;
12229 }
12230 
12231 static int get_auth_methods(const char *value)
12232 {
12233    int methods = 0;
12234    if (strstr(value, "rsa"))
12235       methods |= IAX_AUTH_RSA;
12236    if (strstr(value, "md5"))
12237       methods |= IAX_AUTH_MD5;
12238    if (strstr(value, "plaintext"))
12239       methods |= IAX_AUTH_PLAINTEXT;
12240    return methods;
12241 }
12242 
12243 
12244 /*! \brief Check if address can be used as packet source.
12245  \return 0  address available, 1  address unavailable, -1  error
12246 */
12247 static int check_srcaddr(struct sockaddr *sa, socklen_t salen)
12248 {
12249    int sd;
12250    int res;
12251    
12252    sd = socket(AF_INET, SOCK_DGRAM, 0);
12253    if (sd < 0) {
12254       ast_log(LOG_ERROR, "Socket: %s\n", strerror(errno));
12255       return -1;
12256    }
12257 
12258    res = bind(sd, sa, salen);
12259    if (res < 0) {
12260       ast_debug(1, "Can't bind: %s\n", strerror(errno));
12261       close(sd);
12262       return 1;
12263    }
12264 
12265    close(sd);
12266    return 0;
12267 }
12268 
12269 /*! \brief Parse the "sourceaddress" value,
12270   lookup in netsock list and set peer's sockfd. Defaults to defaultsockfd if
12271   not found. */
12272 static int peer_set_srcaddr(struct iax2_peer *peer, const char *srcaddr)
12273 {
12274    struct sockaddr_in sin;
12275    struct ast_sockaddr sin_tmp;
12276    int nonlocal = 1;
12277    int port = IAX_DEFAULT_PORTNO;
12278    int sockfd = defaultsockfd;
12279    char *tmp;
12280    char *addr;
12281    char *portstr;
12282 
12283    if (!(tmp = ast_strdupa(srcaddr)))
12284       return -1;
12285 
12286    addr = strsep(&tmp, ":");
12287    portstr = tmp;
12288 
12289    if (portstr) {
12290       port = atoi(portstr);
12291       if (port < 1)
12292          port = IAX_DEFAULT_PORTNO;
12293    }
12294 
12295    sin_tmp.ss.ss_family = AF_INET;
12296    if (!ast_get_ip(&sin_tmp, addr)) {
12297       struct ast_netsock *sock;
12298       int res;
12299 
12300       ast_sockaddr_to_sin(&sin_tmp, &sin);
12301       sin.sin_port = 0;
12302       sin.sin_family = AF_INET;
12303       res = check_srcaddr((struct sockaddr *) &sin, sizeof(sin));
12304       if (res == 0) {
12305          /* ip address valid. */
12306          sin.sin_port = htons(port);
12307          if (!(sock = ast_netsock_find(netsock, &sin)))
12308             sock = ast_netsock_find(outsock, &sin);
12309          if (sock) {
12310             sockfd = ast_netsock_sockfd(sock);
12311             nonlocal = 0;
12312          } else {
12313             unsigned int orig_saddr = sin.sin_addr.s_addr;
12314             /* INADDR_ANY matches anyway! */
12315             sin.sin_addr.s_addr = INADDR_ANY;
12316             if (ast_netsock_find(netsock, &sin)) {
12317                sin.sin_addr.s_addr = orig_saddr;
12318                sock = ast_netsock_bind(outsock, io, srcaddr, port, qos.tos, qos.cos, socket_read, NULL);
12319                if (sock) {
12320                   sockfd = ast_netsock_sockfd(sock);
12321                   ast_netsock_unref(sock);
12322                   nonlocal = 0;
12323                } else {
12324                   nonlocal = 2;
12325                }
12326             }
12327          }
12328       }
12329    }
12330       
12331    peer->sockfd = sockfd;
12332 
12333    if (nonlocal == 1) {
12334       ast_log(LOG_WARNING, "Non-local or unbound address specified (%s) in sourceaddress for '%s', reverting to default\n",
12335          srcaddr, peer->name);
12336       return -1;
12337         } else if (nonlocal == 2) {
12338       ast_log(LOG_WARNING, "Unable to bind to sourceaddress '%s' for '%s', reverting to default\n",
12339          srcaddr, peer->name);
12340          return -1;
12341    } else {
12342       ast_debug(1, "Using sourceaddress %s for '%s'\n", srcaddr, peer->name);
12343       return 0;
12344    }
12345 }
12346 
12347 static void peer_destructor(void *obj)
12348 {
12349    struct iax2_peer *peer = obj;
12350    int callno = peer->callno;
12351 
12352    ast_free_ha(peer->ha);
12353 
12354    if (callno > 0) {
12355       ast_mutex_lock(&iaxsl[callno]);
12356       iax2_destroy(callno);
12357       ast_mutex_unlock(&iaxsl[callno]);
12358    }
12359 
12360    register_peer_exten(peer, 0);
12361 
12362    if (peer->dnsmgr)
12363       ast_dnsmgr_release(peer->dnsmgr);
12364 
12365    if (peer->mwi_event_sub)
12366       ast_event_unsubscribe(peer->mwi_event_sub);
12367 
12368    ast_string_field_free_memory(peer);
12369 }
12370 
12371 /*! \brief Create peer structure based on configuration */
12372 static struct iax2_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly)
12373 {
12374    struct iax2_peer *peer = NULL;
12375    struct ast_ha *oldha = NULL;
12376    int maskfound = 0;
12377    int found = 0;
12378    int firstpass = 1;
12379    struct iax2_peer tmp_peer = {
12380       .name = name,
12381    };
12382 
12383    if (!temponly) {
12384       peer = ao2_find(peers, &tmp_peer, OBJ_POINTER);
12385       if (peer && !ast_test_flag64(peer, IAX_DELME))
12386          firstpass = 0;
12387    }
12388 
12389    if (peer) {
12390       found++;
12391       if (firstpass) {
12392          oldha = peer->ha;
12393          peer->ha = NULL;
12394       }
12395       unlink_peer(peer);
12396    } else if ((peer = ao2_alloc(sizeof(*peer), peer_destructor))) {
12397       peer->expire = -1;
12398       peer->pokeexpire = -1;
12399       peer->sockfd = defaultsockfd;
12400       peer->addr.ss.ss_family = AF_INET;
12401       peer->addr.len = sizeof(struct sockaddr_in);
12402       if (ast_string_field_init(peer, 32))
12403          peer = peer_unref(peer);
12404    }
12405 
12406    if (peer) {
12407       if (firstpass) {
12408          ast_copy_flags64(peer, &globalflags, IAX_USEJITTERBUF | IAX_FORCEJITTERBUF | IAX_SENDCONNECTEDLINE | IAX_RECVCONNECTEDLINE | IAX_FORCE_ENCRYPT);
12409          peer->encmethods = iax2_encryption;
12410          peer->adsi = adsi;
12411          ast_string_field_set(peer,secret,"");
12412          if (!found) {
12413             ast_string_field_set(peer, name, name);
12414             ast_sockaddr_set_port(&peer->addr, IAX_DEFAULT_PORTNO);
12415             peer->expiry = min_reg_expire;
12416          }
12417          peer->prefs = prefs;
12418          peer->capability = iax2_capability;
12419          peer->smoothing = 0;
12420          peer->pokefreqok = DEFAULT_FREQ_OK;
12421          peer->pokefreqnotok = DEFAULT_FREQ_NOTOK;
12422          peer->maxcallno = 0;
12423          peercnt_modify(0, 0, &peer->addr);
12424          peer->calltoken_required = CALLTOKEN_DEFAULT;
12425          ast_string_field_set(peer,context,"");
12426          ast_string_field_set(peer,peercontext,"");
12427          ast_clear_flag64(peer, IAX_HASCALLERID);
12428          ast_string_field_set(peer, cid_name, "");
12429          ast_string_field_set(peer, cid_num, "");
12430          ast_string_field_set(peer, mohinterpret, mohinterpret);
12431          ast_string_field_set(peer, mohsuggest, mohsuggest);
12432       }
12433 
12434       if (!v) {
12435          v = alt;
12436          alt = NULL;
12437       }
12438       while(v) {
12439          if (!strcasecmp(v->name, "secret")) {
12440             ast_string_field_set(peer, secret, v->value);
12441          } else if (!strcasecmp(v->name, "mailbox")) {
12442             ast_string_field_set(peer, mailbox, v->value);
12443          } else if (!strcasecmp(v->name, "hasvoicemail")) {
12444             if (ast_true(v->value) && ast_strlen_zero(peer->mailbox)) {
12445                ast_string_field_set(peer, mailbox, name);
12446             }
12447          } else if (!strcasecmp(v->name, "mohinterpret")) {
12448             ast_string_field_set(peer, mohinterpret, v->value);
12449          } else if (!strcasecmp(v->name, "mohsuggest")) {
12450             ast_string_field_set(peer, mohsuggest, v->value);
12451          } else if (!strcasecmp(v->name, "dbsecret")) {
12452             ast_string_field_set(peer, dbsecret, v->value);
12453          } else if (!strcasecmp(v->name, "trunk")) {
12454             ast_set2_flag64(peer, ast_true(v->value), IAX_TRUNK); 
12455             if (ast_test_flag64(peer, IAX_TRUNK) && !timer) {
12456                ast_log(LOG_WARNING, "Unable to support trunking on peer '%s' without a timing interface\n", peer->name);
12457                ast_clear_flag64(peer, IAX_TRUNK);
12458             }
12459          } else if (!strcasecmp(v->name, "auth")) {
12460             peer->authmethods = get_auth_methods(v->value);
12461          } else if (!strcasecmp(v->name, "encryption")) {
12462             peer->encmethods |= get_encrypt_methods(v->value);
12463             if (!peer->encmethods) {
12464                ast_clear_flag64(peer, IAX_FORCE_ENCRYPT);
12465             }
12466          } else if (!strcasecmp(v->name, "forceencryption")) {
12467             if (ast_false(v->value)) {
12468                ast_clear_flag64(peer, IAX_FORCE_ENCRYPT);
12469             } else {
12470                peer->encmethods |= get_encrypt_methods(v->value);
12471                if (peer->encmethods) {
12472                   ast_set_flag64(peer, IAX_FORCE_ENCRYPT);
12473                }
12474             }
12475          } else if (!strcasecmp(v->name, "transfer")) {
12476             if (!strcasecmp(v->value, "mediaonly")) {
12477                ast_set_flags_to64(peer, IAX_NOTRANSFER|IAX_TRANSFERMEDIA, IAX_TRANSFERMEDIA);
12478             } else if (ast_true(v->value)) {
12479                ast_set_flags_to64(peer, IAX_NOTRANSFER|IAX_TRANSFERMEDIA, 0);
12480             } else
12481                ast_set_flags_to64(peer, IAX_NOTRANSFER|IAX_TRANSFERMEDIA, IAX_NOTRANSFER);
12482          } else if (!strcasecmp(v->name, "jitterbuffer")) {
12483             ast_set2_flag64(peer, ast_true(v->value), IAX_USEJITTERBUF);
12484          } else if (!strcasecmp(v->name, "forcejitterbuffer")) {
12485             ast_set2_flag64(peer, ast_true(v->value), IAX_FORCEJITTERBUF);
12486          } else if (!strcasecmp(v->name, "host")) {
12487             if (!strcasecmp(v->value, "dynamic")) {
12488                /* They'll register with us */
12489                ast_set_flag64(peer, IAX_DYNAMIC);
12490                if (!found) {
12491                   /* Initialize stuff iff we're not found, otherwise
12492                      we keep going with what we had */
12493                   if (ast_sockaddr_port(&peer->addr)) {
12494                      peer->defaddr.sin_port = htons(ast_sockaddr_port(&peer->addr));
12495                   }
12496                   ast_sockaddr_setnull(&peer->addr);
12497                }
12498             } else {
12499                /* Non-dynamic.  Make sure we become that way if we're not */
12500                ast_sched_thread_del(sched, peer->expire);
12501                ast_clear_flag64(peer, IAX_DYNAMIC);
12502                if (ast_dnsmgr_lookup(v->value, &peer->addr, &peer->dnsmgr, srvlookup ? "_iax._udp" : NULL))
12503                   return peer_unref(peer);
12504                if (!ast_sockaddr_port(&peer->addr)) {
12505                   ast_sockaddr_set_port(&peer->addr, IAX_DEFAULT_PORTNO);
12506                }
12507             }
12508             if (!maskfound)
12509                inet_aton("255.255.255.255", &peer->mask);
12510          } else if (!strcasecmp(v->name, "defaultip")) {
12511             struct ast_sockaddr peer_defaddr_tmp;
12512 
12513             peer_defaddr_tmp.ss.ss_family = AF_INET;
12514             if (ast_get_ip(&peer_defaddr_tmp, v->value)) {
12515                return peer_unref(peer);
12516             }
12517             ast_sockaddr_to_sin(&peer_defaddr_tmp,
12518                       &peer->defaddr);
12519          } else if (!strcasecmp(v->name, "sourceaddress")) {
12520             peer_set_srcaddr(peer, v->value);
12521          } else if (!strcasecmp(v->name, "permit") ||
12522                   !strcasecmp(v->name, "deny")) {
12523             peer->ha = ast_append_ha(v->name, v->value, peer->ha, NULL);
12524          } else if (!strcasecmp(v->name, "mask")) {
12525             maskfound++;
12526             inet_aton(v->value, &peer->mask);
12527          } else if (!strcasecmp(v->name, "context")) {
12528             ast_string_field_set(peer, context, v->value);
12529          } else if (!strcasecmp(v->name, "regexten")) {
12530             ast_string_field_set(peer, regexten, v->value);
12531          } else if (!strcasecmp(v->name, "peercontext")) {
12532             ast_string_field_set(peer, peercontext, v->value);
12533          } else if (!strcasecmp(v->name, "port")) {
12534             if (ast_test_flag64(peer, IAX_DYNAMIC)) {
12535                peer->defaddr.sin_port = htons(atoi(v->value));
12536             } else {
12537                ast_sockaddr_set_port(&peer->addr, atoi(v->value));
12538             }
12539          } else if (!strcasecmp(v->name, "username")) {
12540             ast_string_field_set(peer, username, v->value);
12541          } else if (!strcasecmp(v->name, "allow")) {
12542             ast_parse_allow_disallow(&peer->prefs, &peer->capability, v->value, 1);
12543          } else if (!strcasecmp(v->name, "disallow")) {
12544             ast_parse_allow_disallow(&peer->prefs, &peer->capability, v->value, 0);
12545          } else if (!strcasecmp(v->name, "callerid")) {
12546             if (!ast_strlen_zero(v->value)) {
12547                char name2[80];
12548                char num2[80];
12549                ast_callerid_split(v->value, name2, sizeof(name2), num2, sizeof(num2));
12550                ast_string_field_set(peer, cid_name, name2);
12551                ast_string_field_set(peer, cid_num, num2);
12552             } else {
12553                ast_string_field_set(peer, cid_name, "");
12554                ast_string_field_set(peer, cid_num, "");
12555             }
12556             ast_set_flag64(peer, IAX_HASCALLERID);
12557          } else if (!strcasecmp(v->name, "fullname")) {
12558             ast_string_field_set(peer, cid_name, S_OR(v->value, ""));
12559             ast_set_flag64(peer, IAX_HASCALLERID);
12560          } else if (!strcasecmp(v->name, "cid_number")) {
12561             ast_string_field_set(peer, cid_num, S_OR(v->value, ""));
12562             ast_set_flag64(peer, IAX_HASCALLERID);
12563          } else if (!strcasecmp(v->name, "sendani")) {
12564             ast_set2_flag64(peer, ast_true(v->value), IAX_SENDANI);
12565          } else if (!strcasecmp(v->name, "inkeys")) {
12566             ast_string_field_set(peer, inkeys, v->value);
12567          } else if (!strcasecmp(v->name, "outkey")) {
12568             ast_string_field_set(peer, outkey, v->value);
12569          } else if (!strcasecmp(v->name, "qualify")) {
12570             if (!strcasecmp(v->value, "no")) {
12571                peer->maxms = 0;
12572             } else if (!strcasecmp(v->value, "yes")) {
12573                peer->maxms = DEFAULT_MAXMS;
12574             } else if (sscanf(v->value, "%30d", &peer->maxms) != 1) {
12575                ast_log(LOG_WARNING, "Qualification of peer '%s' should be 'yes', 'no', or a number of milliseconds at line %d of iax.conf\n", peer->name, v->lineno);
12576                peer->maxms = 0;
12577             }
12578          } else if (!strcasecmp(v->name, "qualifysmoothing")) {
12579             peer->smoothing = ast_true(v->value);
12580          } else if (!strcasecmp(v->name, "qualifyfreqok")) {
12581             if (sscanf(v->value, "%30d", &peer->pokefreqok) != 1) {
12582                ast_log(LOG_WARNING, "Qualification testing frequency of peer '%s' when OK should a number of milliseconds at line %d of iax.conf\n", peer->name, v->lineno);
12583             }
12584          } else if (!strcasecmp(v->name, "qualifyfreqnotok")) {
12585             if (sscanf(v->value, "%30d", &peer->pokefreqnotok) != 1) {
12586                ast_log(LOG_WARNING, "Qualification testing frequency of peer '%s' when NOT OK should be a number of milliseconds at line %d of iax.conf\n", peer->name, v->lineno);
12587             }
12588          } else if (!strcasecmp(v->name, "timezone")) {
12589             ast_string_field_set(peer, zonetag, v->value);
12590          } else if (!strcasecmp(v->name, "adsi")) {
12591             peer->adsi = ast_true(v->value);
12592          } else if (!strcasecmp(v->name, "connectedline")) {
12593             if (ast_true(v->value)) {
12594                ast_set_flag64(peer, IAX_SENDCONNECTEDLINE | IAX_RECVCONNECTEDLINE);
12595             } else if (!strcasecmp(v->value, "send")) {
12596                ast_clear_flag64(peer, IAX_RECVCONNECTEDLINE);
12597                ast_set_flag64(peer, IAX_SENDCONNECTEDLINE);
12598             } else if (!strcasecmp(v->value, "receive")) {
12599                ast_clear_flag64(peer, IAX_SENDCONNECTEDLINE);
12600                ast_set_flag64(peer, IAX_RECVCONNECTEDLINE);
12601             } else {
12602                ast_clear_flag64(peer, IAX_SENDCONNECTEDLINE | IAX_RECVCONNECTEDLINE);
12603             }
12604          } else if (!strcasecmp(v->name, "maxcallnumbers")) {
12605             if (sscanf(v->value, "%10hu", &peer->maxcallno) != 1) {
12606                ast_log(LOG_WARNING, "maxcallnumbers must be set to a valid number. %s is not valid at line %d.\n", v->value, v->lineno);
12607             } else {
12608                peercnt_modify(1, peer->maxcallno, &peer->addr);
12609             }
12610          } else if (!strcasecmp(v->name, "requirecalltoken")) {
12611             /* default is required unless in optional ip list */
12612             if (ast_false(v->value)) {
12613                peer->calltoken_required = CALLTOKEN_NO;
12614             } else if (!strcasecmp(v->value, "auto")) {
12615                peer->calltoken_required = CALLTOKEN_AUTO;
12616             } else if (ast_true(v->value)) {
12617                peer->calltoken_required = CALLTOKEN_YES;
12618             } else {
12619                ast_log(LOG_WARNING, "requirecalltoken must be set to a valid value. at line %d\n", v->lineno);
12620             }
12621          } /* else if (strcasecmp(v->name,"type")) */
12622          /* ast_log(LOG_WARNING, "Ignoring %s\n", v->name); */
12623          v = v->next;
12624          if (!v) {
12625             v = alt;
12626             alt = NULL;
12627          }
12628       }
12629       if (!peer->authmethods)
12630          peer->authmethods = IAX_AUTH_MD5 | IAX_AUTH_PLAINTEXT;
12631       ast_clear_flag64(peer, IAX_DELME);
12632    }
12633 
12634    if (oldha)
12635       ast_free_ha(oldha);
12636 
12637    if (!ast_strlen_zero(peer->mailbox)) {
12638       char *mailbox, *context;
12639       context = mailbox = ast_strdupa(peer->mailbox);
12640       strsep(&context, "@");
12641       if (ast_strlen_zero(context))
12642          context = "default";
12643       peer->mwi_event_sub = ast_event_subscribe(AST_EVENT_MWI, mwi_event_cb, "IAX MWI subscription", NULL,
12644          AST_EVENT_IE_MAILBOX, AST_EVENT_IE_PLTYPE_STR, mailbox,
12645          AST_EVENT_IE_CONTEXT, AST_EVENT_IE_PLTYPE_STR, context,
12646          AST_EVENT_IE_END);
12647    }
12648 
12649    return peer;
12650 }
12651 
12652 static void user_destructor(void *obj)
12653 {
12654    struct iax2_user *user = obj;
12655 
12656    ast_free_ha(user->ha);
12657    free_context(user->contexts);
12658    if(user->vars) {
12659       ast_variables_destroy(user->vars);
12660       user->vars = NULL;
12661    }
12662    ast_string_field_free_memory(user);
12663 }
12664 
12665 /*! \brief Create in-memory user structure from configuration */
12666 static struct iax2_user *build_user(const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly)
12667 {
12668    struct iax2_user *user = NULL;
12669    struct iax2_context *con, *conl = NULL;
12670    struct ast_ha *oldha = NULL;
12671    struct iax2_context *oldcon = NULL;
12672    int format;
12673    int firstpass=1;
12674    int oldcurauthreq = 0;
12675    char *varname = NULL, *varval = NULL;
12676    struct ast_variable *tmpvar = NULL;
12677    struct iax2_user tmp_user = {
12678       .name = name,
12679    };
12680 
12681    if (!temponly) {
12682       user = ao2_find(users, &tmp_user, OBJ_POINTER);
12683       if (user && !ast_test_flag64(user, IAX_DELME))
12684          firstpass = 0;
12685    }
12686 
12687    if (user) {
12688       if (firstpass) {
12689          oldcurauthreq = user->curauthreq;
12690          oldha = user->ha;
12691          oldcon = user->contexts;
12692          user->ha = NULL;
12693          user->contexts = NULL;
12694       }
12695       /* Already in the list, remove it and it will be added back (or FREE'd) */
12696       ao2_unlink(users, user);
12697    } else {
12698       user = ao2_alloc(sizeof(*user), user_destructor);
12699    }
12700    
12701    if (user) {
12702       if (firstpass) {
12703          ast_string_field_free_memory(user);
12704          memset(user, 0, sizeof(struct iax2_user));
12705          if (ast_string_field_init(user, 32)) {
12706             user = user_unref(user);
12707             goto cleanup;
12708          }
12709          user->maxauthreq = maxauthreq;
12710          user->curauthreq = oldcurauthreq;
12711          user->prefs = prefs;
12712          user->capability = iax2_capability;
12713          user->encmethods = iax2_encryption;
12714          user->adsi = adsi;
12715          user->calltoken_required = CALLTOKEN_DEFAULT;
12716          ast_string_field_set(user, name, name);
12717          ast_string_field_set(user, language, language);
12718          ast_copy_flags64(user, &globalflags, IAX_USEJITTERBUF | IAX_FORCEJITTERBUF | IAX_CODEC_USER_FIRST | IAX_CODEC_NOPREFS | IAX_CODEC_NOCAP | IAX_SENDCONNECTEDLINE | IAX_RECVCONNECTEDLINE | IAX_FORCE_ENCRYPT);
12719          ast_clear_flag64(user, IAX_HASCALLERID);
12720          ast_string_field_set(user, cid_name, "");
12721          ast_string_field_set(user, cid_num, "");
12722          ast_string_field_set(user, accountcode, accountcode);
12723          ast_string_field_set(user, mohinterpret, mohinterpret);
12724          ast_string_field_set(user, mohsuggest, mohsuggest);
12725       }
12726       if (!v) {
12727          v = alt;
12728          alt = NULL;
12729       }
12730       while(v) {
12731          if (!strcasecmp(v->name, "context")) {
12732             con = build_context(v->value);
12733             if (con) {
12734                if (conl)
12735                   conl->next = con;
12736                else
12737                   user->contexts = con;
12738                conl = con;
12739             }
12740          } else if (!strcasecmp(v->name, "permit") ||
12741                   !strcasecmp(v->name, "deny")) {
12742             user->ha = ast_append_ha(v->name, v->value, user->ha, NULL);
12743          } else if (!strcasecmp(v->name, "setvar")) {
12744             varname = ast_strdupa(v->value);
12745             if (varname && (varval = strchr(varname,'='))) {
12746                *varval = '\0';
12747                varval++;
12748                if((tmpvar = ast_variable_new(varname, varval, ""))) {
12749                   tmpvar->next = user->vars; 
12750                   user->vars = tmpvar;
12751                }
12752             }
12753          } else if (!strcasecmp(v->name, "allow")) {
12754             ast_parse_allow_disallow(&user->prefs, &user->capability, v->value, 1);
12755          } else if (!strcasecmp(v->name, "disallow")) {
12756             ast_parse_allow_disallow(&user->prefs, &user->capability,v->value, 0);
12757          } else if (!strcasecmp(v->name, "trunk")) {
12758             ast_set2_flag64(user, ast_true(v->value), IAX_TRUNK); 
12759             if (ast_test_flag64(user, IAX_TRUNK) && !timer) {
12760                ast_log(LOG_WARNING, "Unable to support trunking on user '%s' without a timing interface\n", user->name);
12761                ast_clear_flag64(user, IAX_TRUNK);
12762             }
12763          } else if (!strcasecmp(v->name, "auth")) {
12764             user->authmethods = get_auth_methods(v->value);
12765          } else if (!strcasecmp(v->name, "encryption")) {
12766             user->encmethods |= get_encrypt_methods(v->value);
12767             if (!user->encmethods) {
12768                ast_clear_flag64(user, IAX_FORCE_ENCRYPT);
12769             }
12770          } else if (!strcasecmp(v->name, "forceencryption")) {
12771             if (ast_false(v->value)) {
12772                ast_clear_flag64(user, IAX_FORCE_ENCRYPT);
12773             } else {
12774                user->encmethods |= get_encrypt_methods(v->value);
12775                if (user->encmethods) {
12776                   ast_set_flag64(user, IAX_FORCE_ENCRYPT);
12777                }
12778             }
12779          } else if (!strcasecmp(v->name, "transfer")) {
12780             if (!strcasecmp(v->value, "mediaonly")) {
12781                ast_set_flags_to64(user, IAX_NOTRANSFER|IAX_TRANSFERMEDIA, IAX_TRANSFERMEDIA);
12782             } else if (ast_true(v->value)) {
12783                ast_set_flags_to64(user, IAX_NOTRANSFER|IAX_TRANSFERMEDIA, 0);
12784             } else
12785                ast_set_flags_to64(user, IAX_NOTRANSFER|IAX_TRANSFERMEDIA, IAX_NOTRANSFER);
12786          } else if (!strcasecmp(v->name, "codecpriority")) {
12787             if(!strcasecmp(v->value, "caller"))
12788                ast_set_flag64(user, IAX_CODEC_USER_FIRST);
12789             else if(!strcasecmp(v->value, "disabled"))
12790                ast_set_flag64(user, IAX_CODEC_NOPREFS);
12791             else if(!strcasecmp(v->value, "reqonly")) {
12792                ast_set_flag64(user, IAX_CODEC_NOCAP);
12793                ast_set_flag64(user, IAX_CODEC_NOPREFS);
12794             }
12795          } else if (!strcasecmp(v->name, "immediate")) {
12796             ast_set2_flag64(user, ast_true(v->value), IAX_IMMEDIATE);
12797          } else if (!strcasecmp(v->name, "jitterbuffer")) {
12798             ast_set2_flag64(user, ast_true(v->value), IAX_USEJITTERBUF);
12799          } else if (!strcasecmp(v->name, "forcejitterbuffer")) {
12800             ast_set2_flag64(user, ast_true(v->value), IAX_FORCEJITTERBUF);
12801          } else if (!strcasecmp(v->name, "dbsecret")) {
12802             ast_string_field_set(user, dbsecret, v->value);
12803          } else if (!strcasecmp(v->name, "secret")) {
12804             if (!ast_strlen_zero(user->secret)) {
12805                char *old = ast_strdupa(user->secret);
12806 
12807                ast_string_field_build(user, secret, "%s;%s", old, v->value);
12808             } else
12809                ast_string_field_set(user, secret, v->value);
12810          } else if (!strcasecmp(v->name, "callerid")) {
12811             if (!ast_strlen_zero(v->value) && strcasecmp(v->value, "asreceived")) {
12812                char name2[80];
12813                char num2[80];
12814                ast_callerid_split(v->value, name2, sizeof(name2), num2, sizeof(num2));
12815                ast_string_field_set(user, cid_name, name2);
12816                ast_string_field_set(user, cid_num, num2);
12817                ast_set_flag64(user, IAX_HASCALLERID);
12818             } else {
12819                ast_clear_flag64(user, IAX_HASCALLERID);
12820                ast_string_field_set(user, cid_name, "");
12821                ast_string_field_set(user, cid_num, "");
12822             }
12823          } else if (!strcasecmp(v->name, "fullname")) {
12824             if (!ast_strlen_zero(v->value)) {
12825                ast_string_field_set(user, cid_name, v->value);
12826                ast_set_flag64(user, IAX_HASCALLERID);
12827             } else {
12828                ast_string_field_set(user, cid_name, "");
12829                if (ast_strlen_zero(user->cid_num))
12830                   ast_clear_flag64(user, IAX_HASCALLERID);
12831             }
12832          } else if (!strcasecmp(v->name, "cid_number")) {
12833             if (!ast_strlen_zero(v->value)) {
12834                ast_string_field_set(user, cid_num, v->value);
12835                ast_set_flag64(user, IAX_HASCALLERID);
12836             } else {
12837                ast_string_field_set(user, cid_num, "");
12838                if (ast_strlen_zero(user->cid_name))
12839                   ast_clear_flag64(user, IAX_HASCALLERID);
12840             }
12841          } else if (!strcasecmp(v->name, "accountcode")) {
12842             ast_string_field_set(user, accountcode, v->value);
12843          } else if (!strcasecmp(v->name, "mohinterpret")) {
12844             ast_string_field_set(user, mohinterpret, v->value);
12845          } else if (!strcasecmp(v->name, "mohsuggest")) {
12846             ast_string_field_set(user, mohsuggest, v->value);
12847          } else if (!strcasecmp(v->name, "parkinglot")) {
12848             ast_string_field_set(user, parkinglot, v->value);
12849          } else if (!strcasecmp(v->name, "language")) {
12850             ast_string_field_set(user, language, v->value);
12851          } else if (!strcasecmp(v->name, "amaflags")) {
12852             format = ast_cdr_amaflags2int(v->value);
12853             if (format < 0) {
12854                ast_log(LOG_WARNING, "Invalid AMA Flags: %s at line %d\n", v->value, v->lineno);
12855             } else {
12856                user->amaflags = format;
12857             }
12858          } else if (!strcasecmp(v->name, "inkeys")) {
12859             ast_string_field_set(user, inkeys, v->value);
12860          } else if (!strcasecmp(v->name, "maxauthreq")) {
12861             user->maxauthreq = atoi(v->value);
12862             if (user->maxauthreq < 0)
12863                user->maxauthreq = 0;
12864          } else if (!strcasecmp(v->name, "adsi")) {
12865             user->adsi = ast_true(v->value);
12866          } else if (!strcasecmp(v->name, "connectedline")) {
12867             if (ast_true(v->value)) {
12868                ast_set_flag64(user, IAX_SENDCONNECTEDLINE | IAX_RECVCONNECTEDLINE);
12869             } else if (!strcasecmp(v->value, "send")) {
12870                ast_clear_flag64(user, IAX_RECVCONNECTEDLINE);
12871                ast_set_flag64(user, IAX_SENDCONNECTEDLINE);
12872             } else if (!strcasecmp(v->value, "receive")) {
12873                ast_clear_flag64(user, IAX_SENDCONNECTEDLINE);
12874                ast_set_flag64(user, IAX_RECVCONNECTEDLINE);
12875             } else {
12876                ast_clear_flag64(user, IAX_SENDCONNECTEDLINE | IAX_RECVCONNECTEDLINE);
12877             }
12878          } else if (!strcasecmp(v->name, "requirecalltoken")) {
12879             /* default is required unless in optional ip list */
12880             if (ast_false(v->value)) {
12881                user->calltoken_required = CALLTOKEN_NO;
12882             } else if (!strcasecmp(v->value, "auto")) {
12883                user->calltoken_required = CALLTOKEN_AUTO;
12884             } else if (ast_true(v->value)) {
12885                user->calltoken_required = CALLTOKEN_YES;
12886             } else {
12887                ast_log(LOG_WARNING, "requirecalltoken must be set to a valid value. at line %d\n", v->lineno);
12888             }
12889          } /* else if (strcasecmp(v->name,"type")) */
12890          /* ast_log(LOG_WARNING, "Ignoring %s\n", v->name); */
12891          v = v->next;
12892          if (!v) {
12893             v = alt;
12894             alt = NULL;
12895          }
12896       }
12897       if (!user->authmethods) {
12898          if (!ast_strlen_zero(user->secret)) {
12899             user->authmethods = IAX_AUTH_MD5 | IAX_AUTH_PLAINTEXT;
12900             if (!ast_strlen_zero(user->inkeys))
12901                user->authmethods |= IAX_AUTH_RSA;
12902          } else if (!ast_strlen_zero(user->inkeys)) {
12903             user->authmethods = IAX_AUTH_RSA;
12904          } else {
12905             user->authmethods = IAX_AUTH_MD5 | IAX_AUTH_PLAINTEXT;
12906          }
12907       }
12908       ast_clear_flag64(user, IAX_DELME);
12909    }
12910 cleanup:
12911    if (oldha)
12912       ast_free_ha(oldha);
12913    if (oldcon)
12914       free_context(oldcon);
12915    return user;
12916 }
12917 
12918 static int peer_delme_cb(void *obj, void *arg, int flags)
12919 {
12920    struct iax2_peer *peer = obj;
12921 
12922    ast_set_flag64(peer, IAX_DELME);
12923 
12924    return 0;
12925 }
12926 
12927 static int user_delme_cb(void *obj, void *arg, int flags)
12928 {
12929    struct iax2_user *user = obj;
12930 
12931    ast_set_flag64(user, IAX_DELME);
12932 
12933    return 0;
12934 }
12935 
12936 static void delete_users(void)
12937 {
12938    struct iax2_registry *reg;
12939 
12940    ao2_callback(users, 0, user_delme_cb, NULL);
12941 
12942    AST_LIST_LOCK(&registrations);
12943    while ((reg = AST_LIST_REMOVE_HEAD(&registrations, entry))) {
12944       if (sched) {
12945          ast_sched_thread_del(sched, reg->expire);
12946       }
12947       if (reg->callno) {
12948          int callno = reg->callno;
12949          ast_mutex_lock(&iaxsl[callno]);
12950          if (iaxs[callno]) {
12951             iaxs[callno]->reg = NULL;
12952             iax2_destroy(callno);
12953          }
12954          ast_mutex_unlock(&iaxsl[callno]);
12955       }
12956       if (reg->dnsmgr)
12957          ast_dnsmgr_release(reg->dnsmgr);
12958       ast_free(reg);
12959    }
12960    AST_LIST_UNLOCK(&registrations);
12961 
12962    ao2_callback(peers, 0, peer_delme_cb, NULL);
12963 }
12964 
12965 static void prune_users(void)
12966 {
12967    struct iax2_user *user;
12968    struct ao2_iterator i;
12969 
12970    i = ao2_iterator_init(users, 0);
12971    while ((user = ao2_iterator_next(&i))) {
12972       if (ast_test_flag64(user, IAX_DELME) || ast_test_flag64(user, IAX_RTCACHEFRIENDS)) {
12973          ao2_unlink(users, user);
12974       }
12975       user_unref(user);
12976    }
12977    ao2_iterator_destroy(&i);
12978 }
12979 
12980 /* Prune peers who still are supposed to be deleted */
12981 static void prune_peers(void)
12982 {
12983    struct iax2_peer *peer;
12984    struct ao2_iterator i;
12985 
12986    i = ao2_iterator_init(peers, 0);
12987    while ((peer = ao2_iterator_next(&i))) {
12988       if (ast_test_flag64(peer, IAX_DELME) || ast_test_flag64(peer, IAX_RTCACHEFRIENDS)) {
12989          unlink_peer(peer);
12990       }
12991       peer_unref(peer);
12992    }
12993    ao2_iterator_destroy(&i);
12994 }
12995 
12996 static void set_config_destroy(void)
12997 {
12998    strcpy(accountcode, "");
12999    strcpy(language, "");
13000    strcpy(mohinterpret, "default");
13001    strcpy(mohsuggest, "");
13002    trunkmaxsize = MAX_TRUNKDATA;
13003    amaflags = 0;
13004    delayreject = 0;
13005    ast_clear_flag64((&globalflags), IAX_NOTRANSFER | IAX_TRANSFERMEDIA | IAX_USEJITTERBUF |
13006       IAX_FORCEJITTERBUF | IAX_SENDCONNECTEDLINE | IAX_RECVCONNECTEDLINE);
13007    delete_users();
13008    ao2_callback(callno_limits, OBJ_NODATA, addr_range_delme_cb, NULL);
13009    ao2_callback(calltoken_ignores, OBJ_NODATA, addr_range_delme_cb, NULL);
13010 }
13011 
13012 /*! \brief Load configuration */
13013 static int set_config(const char *config_file, int reload)
13014 {
13015    struct ast_config *cfg, *ucfg;
13016    format_t capability = iax2_capability;
13017    struct ast_variable *v;
13018    char *cat;
13019    const char *utype;
13020    const char *tosval;
13021    int format;
13022    int portno = IAX_DEFAULT_PORTNO;
13023    int  x;
13024    int mtuv;
13025    int subscribe_network_change = 1;
13026    struct iax2_user *user;
13027    struct iax2_peer *peer;
13028    struct ast_netsock *ns;
13029    struct ast_flags config_flags = { reload ? CONFIG_FLAG_FILEUNCHANGED : 0 };
13030 #if 0
13031    static unsigned short int last_port=0;
13032 #endif
13033 
13034    cfg = ast_config_load(config_file, config_flags);
13035 
13036    if (!cfg) {
13037       ast_log(LOG_ERROR, "Unable to load config %s\n", config_file);
13038       return -1;
13039    } else if (cfg == CONFIG_STATUS_FILEUNCHANGED) {
13040       ucfg = ast_config_load("users.conf", config_flags);
13041       if (ucfg == CONFIG_STATUS_FILEUNCHANGED)
13042          return 0;
13043       /* Otherwise we need to reread both files */
13044       ast_clear_flag(&config_flags, CONFIG_FLAG_FILEUNCHANGED);
13045       if ((cfg = ast_config_load(config_file, config_flags)) == CONFIG_STATUS_FILEINVALID) {
13046          ast_log(LOG_ERROR, "Config file %s is in an invalid format.  Aborting.\n", config_file);
13047          ast_config_destroy(ucfg);
13048          return 0;
13049       }
13050    } else if (cfg == CONFIG_STATUS_FILEINVALID) {
13051       ast_log(LOG_ERROR, "Config file %s is in an invalid format.  Aborting.\n", config_file);
13052       return 0;
13053    } else { /* iax.conf changed, gotta reread users.conf, too */
13054       ast_clear_flag(&config_flags, CONFIG_FLAG_FILEUNCHANGED);
13055       if ((ucfg = ast_config_load("users.conf", config_flags)) == CONFIG_STATUS_FILEINVALID) {
13056          ast_log(LOG_ERROR, "Config file users.conf is in an invalid format.  Aborting.\n");
13057          ast_config_destroy(cfg);
13058          return 0;
13059       }
13060    }
13061 
13062    if (reload) {
13063       set_config_destroy();
13064    }
13065 
13066    /* Reset global codec prefs */
13067    memset(&prefs, 0 , sizeof(struct ast_codec_pref));
13068 
13069    /* Reset Global Flags */
13070    memset(&globalflags, 0, sizeof(globalflags));
13071    ast_set_flag64(&globalflags, IAX_RTUPDATE);
13072    ast_set_flag64((&globalflags), IAX_SHRINKCALLERID);
13073 
13074 #ifdef SO_NO_CHECK
13075    nochecksums = 0;
13076 #endif
13077    /* Reset default parking lot */
13078    default_parkinglot[0] = '\0';
13079 
13080    min_reg_expire = IAX_DEFAULT_REG_EXPIRE;
13081    max_reg_expire = IAX_DEFAULT_REG_EXPIRE;
13082    global_max_trunk_mtu = MAX_TRUNK_MTU;
13083    global_maxcallno = DEFAULT_MAXCALLNO_LIMIT;
13084    global_maxcallno_nonval = DEFAULT_MAXCALLNO_LIMIT_NONVAL;
13085 
13086    maxauthreq = 3;
13087 
13088    srvlookup = 0;
13089 
13090    v = ast_variable_browse(cfg, "general");
13091 
13092    /* Seed initial tos value */
13093    tosval = ast_variable_retrieve(cfg, "general", "tos");
13094    if (tosval) {
13095       if (ast_str2tos(tosval, &qos.tos))
13096          ast_log(LOG_WARNING, "Invalid tos value, refer to QoS documentation\n");
13097    }
13098    /* Seed initial cos value */
13099    tosval = ast_variable_retrieve(cfg, "general", "cos");
13100    if (tosval) {
13101       if (ast_str2cos(tosval, &qos.cos))
13102          ast_log(LOG_WARNING, "Invalid cos value, refer to QoS documentation\n");
13103    }
13104    while(v) {
13105       if (!strcasecmp(v->name, "bindport")){ 
13106          if (reload)
13107             ast_log(LOG_NOTICE, "Ignoring bindport on reload\n");
13108          else
13109             portno = atoi(v->value);
13110       } else if (!strcasecmp(v->name, "pingtime")) 
13111          ping_time = atoi(v->value);
13112       else if (!strcasecmp(v->name, "iaxthreadcount")) {
13113          if (reload) {
13114             if (atoi(v->value) != iaxthreadcount)
13115                ast_log(LOG_NOTICE, "Ignoring any changes to iaxthreadcount during reload\n");
13116          } else {
13117             iaxthreadcount = atoi(v->value);
13118             if (iaxthreadcount < 1) {
13119                ast_log(LOG_NOTICE, "iaxthreadcount must be at least 1.\n");
13120                iaxthreadcount = 1;
13121             } else if (iaxthreadcount > 256) {
13122                ast_log(LOG_NOTICE, "limiting iaxthreadcount to 256\n");
13123                iaxthreadcount = 256;
13124             }
13125          }
13126       } else if (!strcasecmp(v->name, "iaxmaxthreadcount")) {
13127          if (reload) {
13128             AST_LIST_LOCK(&dynamic_list);
13129             iaxmaxthreadcount = atoi(v->value);
13130             AST_LIST_UNLOCK(&dynamic_list);
13131          } else {
13132             iaxmaxthreadcount = atoi(v->value);
13133             if (iaxmaxthreadcount < 0) {
13134                ast_log(LOG_NOTICE, "iaxmaxthreadcount must be at least 0.\n");
13135                iaxmaxthreadcount = 0;
13136             } else if (iaxmaxthreadcount > 256) {
13137                ast_log(LOG_NOTICE, "Limiting iaxmaxthreadcount to 256\n");
13138                iaxmaxthreadcount = 256;
13139             }
13140          }
13141       } else if (!strcasecmp(v->name, "nochecksums")) {
13142 #ifdef SO_NO_CHECK
13143          if (ast_true(v->value))
13144             nochecksums = 1;
13145          else
13146             nochecksums = 0;
13147 #else
13148          if (ast_true(v->value))
13149             ast_log(LOG_WARNING, "Disabling RTP checksums is not supported on this operating system!\n");
13150 #endif
13151       }
13152       else if (!strcasecmp(v->name, "maxjitterbuffer")) 
13153          maxjitterbuffer = atoi(v->value);
13154       else if (!strcasecmp(v->name, "resyncthreshold")) 
13155          resyncthreshold = atoi(v->value);
13156       else if (!strcasecmp(v->name, "maxjitterinterps")) 
13157          maxjitterinterps = atoi(v->value);
13158       else if (!strcasecmp(v->name, "jittertargetextra"))
13159          jittertargetextra = atoi(v->value);
13160       else if (!strcasecmp(v->name, "lagrqtime")) 
13161          lagrq_time = atoi(v->value);
13162       else if (!strcasecmp(v->name, "maxregexpire")) 
13163          max_reg_expire = atoi(v->value);
13164       else if (!strcasecmp(v->name, "minregexpire")) 
13165          min_reg_expire = atoi(v->value);
13166       else if (!strcasecmp(v->name, "bindaddr")) {
13167          if (reload) {
13168             ast_log(LOG_NOTICE, "Ignoring bindaddr on reload\n");
13169          } else {
13170             if (!(ns = ast_netsock_bind(netsock, io, v->value, portno, qos.tos, qos.cos, socket_read, NULL))) {
13171                ast_log(LOG_WARNING, "Unable apply binding to '%s' at line %d\n", v->value, v->lineno);
13172             } else {
13173                   if (strchr(v->value, ':'))
13174                   ast_verb(2, "Binding IAX2 to '%s'\n", v->value);
13175                   else
13176                   ast_verb(2, "Binding IAX2 to '%s:%d'\n", v->value, portno);
13177                if (defaultsockfd < 0) 
13178                   defaultsockfd = ast_netsock_sockfd(ns);
13179                ast_netsock_unref(ns);
13180             }
13181          }
13182       } else if (!strcasecmp(v->name, "authdebug")) {
13183          authdebug = ast_true(v->value);
13184       } else if (!strcasecmp(v->name, "encryption")) {
13185             iax2_encryption |= get_encrypt_methods(v->value);
13186             if (!iax2_encryption) {
13187                ast_clear_flag64((&globalflags), IAX_FORCE_ENCRYPT);
13188             }
13189       } else if (!strcasecmp(v->name, "forceencryption")) {
13190          if (ast_false(v->value)) {
13191             ast_clear_flag64((&globalflags), IAX_FORCE_ENCRYPT);
13192          } else {
13193             iax2_encryption |= get_encrypt_methods(v->value);
13194             if (iax2_encryption) {
13195                ast_set_flag64((&globalflags), IAX_FORCE_ENCRYPT);
13196             }
13197          }
13198       } else if (!strcasecmp(v->name, "transfer")) {
13199          if (!strcasecmp(v->value, "mediaonly")) {
13200             ast_set_flags_to64((&globalflags), IAX_NOTRANSFER|IAX_TRANSFERMEDIA, IAX_TRANSFERMEDIA);
13201          } else if (ast_true(v->value)) {
13202             ast_set_flags_to64((&globalflags), IAX_NOTRANSFER|IAX_TRANSFERMEDIA, 0);
13203          } else
13204             ast_set_flags_to64((&globalflags), IAX_NOTRANSFER|IAX_TRANSFERMEDIA, IAX_NOTRANSFER);
13205       } else if (!strcasecmp(v->name, "codecpriority")) {
13206          if(!strcasecmp(v->value, "caller"))
13207             ast_set_flag64((&globalflags), IAX_CODEC_USER_FIRST);
13208          else if(!strcasecmp(v->value, "disabled"))
13209             ast_set_flag64((&globalflags), IAX_CODEC_NOPREFS);
13210          else if(!strcasecmp(v->value, "reqonly")) {
13211             ast_set_flag64((&globalflags), IAX_CODEC_NOCAP);
13212             ast_set_flag64((&globalflags), IAX_CODEC_NOPREFS);
13213          }
13214       } else if (!strcasecmp(v->name, "jitterbuffer"))
13215          ast_set2_flag64((&globalflags), ast_true(v->value), IAX_USEJITTERBUF);
13216       else if (!strcasecmp(v->name, "forcejitterbuffer"))
13217          ast_set2_flag64((&globalflags), ast_true(v->value), IAX_FORCEJITTERBUF);
13218       else if (!strcasecmp(v->name, "delayreject"))
13219          delayreject = ast_true(v->value);
13220       else if (!strcasecmp(v->name, "allowfwdownload"))
13221          ast_set2_flag64((&globalflags), ast_true(v->value), IAX_ALLOWFWDOWNLOAD);
13222       else if (!strcasecmp(v->name, "rtcachefriends"))
13223          ast_set2_flag64((&globalflags), ast_true(v->value), IAX_RTCACHEFRIENDS);
13224       else if (!strcasecmp(v->name, "rtignoreregexpire"))
13225          ast_set2_flag64((&globalflags), ast_true(v->value), IAX_RTIGNOREREGEXPIRE);
13226       else if (!strcasecmp(v->name, "rtupdate"))
13227          ast_set2_flag64((&globalflags), ast_true(v->value), IAX_RTUPDATE);
13228       else if (!strcasecmp(v->name, "rtsavesysname"))
13229          ast_set2_flag64((&globalflags), ast_true(v->value), IAX_RTSAVE_SYSNAME);
13230       else if (!strcasecmp(v->name, "trunktimestamps"))
13231          ast_set2_flag64(&globalflags, ast_true(v->value), IAX_TRUNKTIMESTAMPS);
13232       else if (!strcasecmp(v->name, "rtautoclear")) {
13233          int i = atoi(v->value);
13234          if(i > 0)
13235             global_rtautoclear = i;
13236          else
13237             i = 0;
13238          ast_set2_flag64((&globalflags), i || ast_true(v->value), IAX_RTAUTOCLEAR);
13239       } else if (!strcasecmp(v->name, "trunkfreq")) {
13240          trunkfreq = atoi(v->value);
13241          if (trunkfreq < 10) {
13242             ast_log(LOG_NOTICE, "trunkfreq must be between 10ms and 1000ms, using 10ms instead.\n");
13243             trunkfreq = 10;
13244          } else if (trunkfreq > 1000) {
13245             ast_log(LOG_NOTICE, "trunkfreq must be between 10ms and 1000ms, using 1000ms instead.\n");
13246             trunkfreq = 1000;
13247          }
13248       } else if (!strcasecmp(v->name, "trunkmtu")) {
13249          mtuv = atoi(v->value);
13250          if (mtuv  == 0 )
13251             global_max_trunk_mtu = 0;
13252          else if (mtuv >= 172 && mtuv < 4000)
13253             global_max_trunk_mtu = mtuv;
13254          else
13255             ast_log(LOG_NOTICE, "trunkmtu value out of bounds (%d) at line %d\n",
13256                mtuv, v->lineno);
13257       } else if (!strcasecmp(v->name, "trunkmaxsize")) {
13258          trunkmaxsize = atoi(v->value);
13259          if (trunkmaxsize == 0)
13260             trunkmaxsize = MAX_TRUNKDATA;
13261       } else if (!strcasecmp(v->name, "autokill")) {
13262          if (sscanf(v->value, "%30d", &x) == 1) {
13263             if (x >= 0)
13264                autokill = x;
13265             else
13266                ast_log(LOG_NOTICE, "Nice try, but autokill has to be >0 or 'yes' or 'no' at line %d\n", v->lineno);
13267          } else if (ast_true(v->value)) {
13268             autokill = DEFAULT_MAXMS;
13269          } else {
13270             autokill = 0;
13271          }
13272       } else if (!strcasecmp(v->name, "bandwidth")) {
13273          if (!strcasecmp(v->value, "low")) {
13274             capability = IAX_CAPABILITY_LOWBANDWIDTH;
13275          } else if (!strcasecmp(v->value, "medium")) {
13276             capability = IAX_CAPABILITY_MEDBANDWIDTH;
13277          } else if (!strcasecmp(v->value, "high")) {
13278             capability = IAX_CAPABILITY_FULLBANDWIDTH;
13279          } else
13280             ast_log(LOG_WARNING, "bandwidth must be either low, medium, or high\n");
13281       } else if (!strcasecmp(v->name, "allow")) {
13282          ast_parse_allow_disallow(&prefs, &capability, v->value, 1);
13283       } else if (!strcasecmp(v->name, "disallow")) {
13284          ast_parse_allow_disallow(&prefs, &capability, v->value, 0);
13285       } else if (!strcasecmp(v->name, "register")) {
13286          iax2_register(v->value, v->lineno);
13287       } else if (!strcasecmp(v->name, "iaxcompat")) {
13288          iaxcompat = ast_true(v->value);
13289       } else if (!strcasecmp(v->name, "regcontext")) {
13290          ast_copy_string(regcontext, v->value, sizeof(regcontext));
13291          /* Create context if it doesn't exist already */
13292          ast_context_find_or_create(NULL, NULL, regcontext, "IAX2");
13293       } else if (!strcasecmp(v->name, "tos")) {
13294          if (ast_str2tos(v->value, &qos.tos))
13295             ast_log(LOG_WARNING, "Invalid tos value at line %d, refer to QoS documentation\n", v->lineno);
13296       } else if (!strcasecmp(v->name, "cos")) {
13297          if (ast_str2cos(v->value, &qos.cos))
13298             ast_log(LOG_WARNING, "Invalid cos value at line %d, refer to QoS documentation\n", v->lineno);
13299       } else if (!strcasecmp(v->name, "parkinglot")) {
13300          ast_copy_string(default_parkinglot, v->value, sizeof(default_parkinglot));
13301       } else if (!strcasecmp(v->name, "accountcode")) {
13302          ast_copy_string(accountcode, v->value, sizeof(accountcode));
13303       } else if (!strcasecmp(v->name, "mohinterpret")) {
13304          ast_copy_string(mohinterpret, v->value, sizeof(mohinterpret));
13305       } else if (!strcasecmp(v->name, "mohsuggest")) {
13306          ast_copy_string(mohsuggest, v->value, sizeof(mohsuggest));
13307       } else if (!strcasecmp(v->name, "amaflags")) {
13308          format = ast_cdr_amaflags2int(v->value);
13309          if (format < 0) {
13310             ast_log(LOG_WARNING, "Invalid AMA Flags: %s at line %d\n", v->value, v->lineno);
13311          } else {
13312             amaflags = format;
13313          }
13314       } else if (!strcasecmp(v->name, "language")) {
13315          ast_copy_string(language, v->value, sizeof(language));
13316       } else if (!strcasecmp(v->name, "maxauthreq")) {
13317          maxauthreq = atoi(v->value);
13318          if (maxauthreq < 0)
13319             maxauthreq = 0;
13320       } else if (!strcasecmp(v->name, "adsi")) {
13321          adsi = ast_true(v->value);
13322       } else if (!strcasecmp(v->name, "srvlookup")) {
13323          srvlookup = ast_true(v->value);
13324       } else if (!strcasecmp(v->name, "connectedline")) {
13325          if (ast_true(v->value)) {
13326             ast_set_flag64((&globalflags), IAX_SENDCONNECTEDLINE | IAX_RECVCONNECTEDLINE);
13327          } else if (!strcasecmp(v->value, "send")) {
13328             ast_clear_flag64((&globalflags), IAX_RECVCONNECTEDLINE);
13329             ast_set_flag64((&globalflags), IAX_SENDCONNECTEDLINE);
13330          } else if (!strcasecmp(v->value, "receive")) {
13331             ast_clear_flag64((&globalflags), IAX_SENDCONNECTEDLINE);
13332             ast_set_flag64((&globalflags), IAX_RECVCONNECTEDLINE);
13333          } else {
13334             ast_clear_flag64((&globalflags), IAX_SENDCONNECTEDLINE | IAX_RECVCONNECTEDLINE);
13335          }
13336       } else if (!strcasecmp(v->name, "maxcallnumbers")) {
13337          if (sscanf(v->value, "%10hu", &global_maxcallno) != 1) {
13338             ast_log(LOG_WARNING, "maxcallnumbers must be set to a valid number.  %s is not valid at line %d\n", v->value, v->lineno);
13339          }
13340       } else if (!strcasecmp(v->name, "maxcallnumbers_nonvalidated")) {
13341          if (sscanf(v->value, "%10hu", &global_maxcallno_nonval) != 1) {
13342             ast_log(LOG_WARNING, "maxcallnumbers_nonvalidated must be set to a valid number.  %s is not valid at line %d.\n", v->value, v->lineno);
13343          }
13344       } else if (!strcasecmp(v->name, "calltokenoptional")) {
13345          if (add_calltoken_ignore(v->value)) {
13346             ast_log(LOG_WARNING, "Invalid calltokenoptional address range - '%s' line %d\n", v->value, v->lineno);
13347          }
13348       } else if (!strcasecmp(v->name, "subscribe_network_change_event")) {
13349          if (ast_true(v->value)) {
13350             subscribe_network_change = 1;
13351          } else if (ast_false(v->value)) {
13352             subscribe_network_change = 0;
13353          } else {
13354             ast_log(LOG_WARNING, "subscribe_network_change_event value %s is not valid at line %d.\n", v->value, v->lineno);
13355          }
13356       } else if (!strcasecmp(v->name, "shrinkcallerid")) {
13357          if (ast_true(v->value)) {
13358             ast_set_flag64((&globalflags), IAX_SHRINKCALLERID);
13359          } else if (ast_false(v->value)) {
13360             ast_clear_flag64((&globalflags), IAX_SHRINKCALLERID);
13361          } else {
13362             ast_log(LOG_WARNING, "shrinkcallerid value %s is not valid at line %d.\n", v->value, v->lineno);
13363          }
13364       }/*else if (strcasecmp(v->name,"type")) */
13365       /* ast_log(LOG_WARNING, "Ignoring %s\n", v->name); */
13366       v = v->next;
13367    }
13368 
13369    if (subscribe_network_change) {
13370       network_change_event_subscribe();
13371    } else {
13372       network_change_event_unsubscribe();
13373    }
13374 
13375    if (defaultsockfd < 0) {
13376       if (!(ns = ast_netsock_bind(netsock, io, "0.0.0.0", portno, qos.tos, qos.cos, socket_read, NULL))) {
13377          ast_log(LOG_ERROR, "Unable to create network socket: %s\n", strerror(errno));
13378       } else {
13379          ast_verb(2, "Binding IAX2 to default address 0.0.0.0:%d\n", portno);
13380          defaultsockfd = ast_netsock_sockfd(ns);
13381          ast_netsock_unref(ns);
13382       }
13383    }
13384    if (reload) {
13385       ast_netsock_release(outsock);
13386       outsock = ast_netsock_list_alloc();
13387       if (!outsock) {
13388          ast_log(LOG_ERROR, "Could not allocate outsock list.\n");
13389          return -1;
13390       }
13391       ast_netsock_init(outsock);
13392    }
13393 
13394    if (min_reg_expire > max_reg_expire) {
13395       ast_log(LOG_WARNING, "Minimum registration interval of %d is more than maximum of %d, resetting minimum to %d\n",
13396          min_reg_expire, max_reg_expire, max_reg_expire);
13397       min_reg_expire = max_reg_expire;
13398    }
13399    iax2_capability = capability;
13400    
13401    if (ucfg) {
13402       struct ast_variable *gen;
13403       int genhasiax;
13404       int genregisteriax;
13405       const char *hasiax, *registeriax;
13406       
13407       genhasiax = ast_true(ast_variable_retrieve(ucfg, "general", "hasiax"));
13408       genregisteriax = ast_true(ast_variable_retrieve(ucfg, "general", "registeriax"));
13409       gen = ast_variable_browse(ucfg, "general");
13410       cat = ast_category_browse(ucfg, NULL);
13411       while (cat) {
13412          if (strcasecmp(cat, "general")) {
13413             hasiax = ast_variable_retrieve(ucfg, cat, "hasiax");
13414             registeriax = ast_variable_retrieve(ucfg, cat, "registeriax");
13415             if (ast_true(hasiax) || (!hasiax && genhasiax)) {
13416                /* Start with general parameters, then specific parameters, user and peer */
13417                user = build_user(cat, gen, ast_variable_browse(ucfg, cat), 0);
13418                if (user) {
13419                   ao2_link(users, user);
13420                   user = user_unref(user);
13421                }
13422                peer = build_peer(cat, gen, ast_variable_browse(ucfg, cat), 0);
13423                if (peer) {
13424                   if (ast_test_flag64(peer, IAX_DYNAMIC))
13425                      reg_source_db(peer);
13426                   ao2_link(peers, peer);
13427                   peer = peer_unref(peer);
13428                }
13429             }
13430             if (ast_true(registeriax) || (!registeriax && genregisteriax)) {
13431                char tmp[256];
13432                const char *host = ast_variable_retrieve(ucfg, cat, "host");
13433                const char *username = ast_variable_retrieve(ucfg, cat, "username");
13434                const char *secret = ast_variable_retrieve(ucfg, cat, "secret");
13435                if (!host)
13436                   host = ast_variable_retrieve(ucfg, "general", "host");
13437                if (!username)
13438                   username = ast_variable_retrieve(ucfg, "general", "username");
13439                if (!secret)
13440                   secret = ast_variable_retrieve(ucfg, "general", "secret");
13441                if (!ast_strlen_zero(username) && !ast_strlen_zero(host)) {
13442                   if (!ast_strlen_zero(secret))
13443                      snprintf(tmp, sizeof(tmp), "%s:%s@%s", username, secret, host);
13444                   else
13445                      snprintf(tmp, sizeof(tmp), "%s@%s", username, host);
13446                   iax2_register(tmp, 0);
13447                }
13448             }
13449          }
13450          cat = ast_category_browse(ucfg, cat);
13451       }
13452       ast_config_destroy(ucfg);
13453    }
13454    
13455    cat = ast_category_browse(cfg, NULL);
13456    while(cat) {
13457       if (strcasecmp(cat, "general")) {
13458          utype = ast_variable_retrieve(cfg, cat, "type");
13459          if (!strcasecmp(cat, "callnumberlimits")) {
13460             build_callno_limits(ast_variable_browse(cfg, cat));
13461          } else if (utype) {
13462             if (!strcasecmp(utype, "user") || !strcasecmp(utype, "friend")) {
13463                user = build_user(cat, ast_variable_browse(cfg, cat), NULL, 0);
13464                if (user) {
13465                   ao2_link(users, user);
13466                   user = user_unref(user);
13467                }
13468             }
13469             if (!strcasecmp(utype, "peer") || !strcasecmp(utype, "friend")) {
13470                peer = build_peer(cat, ast_variable_browse(cfg, cat), NULL, 0);
13471                if (peer) {
13472                   if (ast_test_flag64(peer, IAX_DYNAMIC))
13473                      reg_source_db(peer);
13474                   ao2_link(peers, peer);
13475                   peer = peer_unref(peer);
13476                }
13477             } else if (strcasecmp(utype, "user")) {
13478                ast_log(LOG_WARNING, "Unknown type '%s' for '%s' in %s\n", utype, cat, config_file);
13479             }
13480          } else
13481             ast_log(LOG_WARNING, "Section '%s' lacks type\n", cat);
13482       }
13483       cat = ast_category_browse(cfg, cat);
13484    }
13485    ast_config_destroy(cfg);
13486    return 1;
13487 }
13488 
13489 static void poke_all_peers(void)
13490 {
13491    struct ao2_iterator i;
13492    struct iax2_peer *peer;
13493 
13494    i = ao2_iterator_init(peers, 0);
13495    while ((peer = ao2_iterator_next(&i))) {
13496       iax2_poke_peer(peer, 0);
13497       peer_unref(peer);
13498    }
13499    ao2_iterator_destroy(&i);
13500 }
13501 static int reload_config(void)
13502 {
13503    static const char config[] = "iax.conf";
13504    struct iax2_registry *reg;
13505 
13506    if (set_config(config, 1) > 0) {
13507       prune_peers();
13508       prune_users();
13509       ao2_callback(callno_limits, OBJ_NODATA | OBJ_UNLINK | OBJ_MULTIPLE, prune_addr_range_cb, NULL);
13510       ao2_callback(calltoken_ignores, OBJ_NODATA | OBJ_UNLINK | OBJ_MULTIPLE, prune_addr_range_cb, NULL);
13511       ao2_callback(peercnts, OBJ_NODATA, set_peercnt_limit_all_cb, NULL);
13512       trunk_timed = trunk_untimed = 0; 
13513       trunk_nmaxmtu = trunk_maxmtu = 0;
13514       memset(&debugaddr, '\0', sizeof(debugaddr));
13515 
13516       AST_LIST_LOCK(&registrations);
13517       AST_LIST_TRAVERSE(&registrations, reg, entry)
13518          iax2_do_register(reg);
13519       AST_LIST_UNLOCK(&registrations);
13520 
13521       /* Qualify hosts, too */
13522       poke_all_peers();
13523    }
13524    
13525    reload_firmware(0);
13526    iax_provision_reload(1);
13527    ast_unload_realtime("iaxpeers");
13528 
13529    return 0;
13530 }
13531 
13532 static char *handle_cli_iax2_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
13533 {
13534    switch (cmd) {
13535    case CLI_INIT:
13536       e->command = "iax2 reload";
13537       e->usage =
13538          "Usage: iax2 reload\n"
13539          "       Reloads IAX configuration from iax.conf\n";
13540       return NULL;
13541    case CLI_GENERATE:
13542       return NULL;
13543    }
13544 
13545    reload_config();
13546 
13547    return CLI_SUCCESS;
13548 }
13549 
13550 static int reload(void)
13551 {
13552    return reload_config();
13553 }
13554 
13555 static int cache_get_callno_locked(const char *data)
13556 {
13557    struct sockaddr_in sin;
13558    int x;
13559    int callno;
13560    struct iax_ie_data ied;
13561    struct create_addr_info cai;
13562    struct parsed_dial_string pds;
13563    char *tmpstr;
13564 
13565    for (x = 0; x < ARRAY_LEN(iaxs); x++) {
13566       /* Look for an *exact match* call.  Once a call is negotiated, it can only
13567          look up entries for a single context */
13568       if (!ast_mutex_trylock(&iaxsl[x])) {
13569          if (iaxs[x] && !strcasecmp(data, iaxs[x]->dproot))
13570             return x;
13571          ast_mutex_unlock(&iaxsl[x]);
13572       }
13573    }
13574 
13575    /* No match found, we need to create a new one */
13576 
13577    memset(&cai, 0, sizeof(cai));
13578    memset(&ied, 0, sizeof(ied));
13579    memset(&pds, 0, sizeof(pds));
13580 
13581    tmpstr = ast_strdupa(data);
13582    parse_dial_string(tmpstr, &pds);
13583 
13584    if (ast_strlen_zero(pds.peer)) {
13585       ast_log(LOG_WARNING, "No peer provided in the IAX2 dial string '%s'\n", data);
13586       return -1;
13587    }
13588 
13589    /* Populate our address from the given */
13590    if (create_addr(pds.peer, NULL, &sin, &cai))
13591       return -1;
13592 
13593    ast_debug(1, "peer: %s, username: %s, password: %s, context: %s\n",
13594       pds.peer, pds.username, pds.password, pds.context);
13595 
13596    callno = find_callno_locked(0, 0, &sin, NEW_FORCE, cai.sockfd, 0);
13597    if (callno < 1) {
13598       ast_log(LOG_WARNING, "Unable to create call\n");
13599       return -1;
13600    }
13601 
13602    ast_string_field_set(iaxs[callno], dproot, data);
13603    iaxs[callno]->capability = IAX_CAPABILITY_FULLBANDWIDTH;
13604 
13605    iax_ie_append_short(&ied, IAX_IE_VERSION, IAX_PROTO_VERSION);
13606    iax_ie_append_str(&ied, IAX_IE_CALLED_NUMBER, "TBD");
13607    /* the string format is slightly different from a standard dial string,
13608       because the context appears in the 'exten' position
13609    */
13610    if (pds.exten)
13611       iax_ie_append_str(&ied, IAX_IE_CALLED_CONTEXT, pds.exten);
13612    if (pds.username)
13613       iax_ie_append_str(&ied, IAX_IE_USERNAME, pds.username);
13614    iax_ie_append_int(&ied, IAX_IE_FORMAT, IAX_CAPABILITY_FULLBANDWIDTH);
13615    iax_ie_append_int(&ied, IAX_IE_CAPABILITY, IAX_CAPABILITY_FULLBANDWIDTH);
13616    /* Keep password handy */
13617    if (pds.password)
13618       ast_string_field_set(iaxs[callno], secret, pds.password);
13619    if (pds.key)
13620       ast_string_field_set(iaxs[callno], outkey, pds.key);
13621    /* Start the call going */
13622    add_empty_calltoken_ie(iaxs[callno], &ied); /* this _MUST_ be the last ie added */
13623    send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_NEW, 0, ied.buf, ied.pos, -1);
13624 
13625    return callno;
13626 }
13627 
13628 static struct iax2_dpcache *find_cache(struct ast_channel *chan, const char *data, const char *context, const char *exten, int priority)
13629 {
13630    struct iax2_dpcache *dp = NULL;
13631    struct timeval now = ast_tvnow();
13632    int x, com[2], timeout, old = 0, outfd, doabort, callno;
13633    struct ast_channel *c = NULL;
13634    struct ast_frame *f = NULL;
13635 
13636    AST_LIST_TRAVERSE_SAFE_BEGIN(&dpcache, dp, cache_list) {
13637       if (ast_tvcmp(now, dp->expiry) > 0) {
13638          AST_LIST_REMOVE_CURRENT(cache_list);
13639          if ((dp->flags & CACHE_FLAG_PENDING) || dp->callno)
13640             ast_log(LOG_WARNING, "DP still has peer field or pending or callno (flags = %d, peer = blah, callno = %d)\n", dp->flags, dp->callno);
13641          else
13642             ast_free(dp);
13643          continue;
13644       }
13645       if (!strcmp(dp->peercontext, data) && !strcmp(dp->exten, exten))
13646          break;
13647    }
13648    AST_LIST_TRAVERSE_SAFE_END;
13649 
13650    if (!dp) {
13651       /* No matching entry.  Create a new one. */
13652       /* First, can we make a callno? */
13653       if ((callno = cache_get_callno_locked(data)) < 0) {
13654          ast_log(LOG_WARNING, "Unable to generate call for '%s'\n", data);
13655          return NULL;
13656       }
13657       if (!(dp = ast_calloc(1, sizeof(*dp)))) {
13658          ast_mutex_unlock(&iaxsl[callno]);
13659          return NULL;
13660       }
13661       ast_copy_string(dp->peercontext, data, sizeof(dp->peercontext));
13662       ast_copy_string(dp->exten, exten, sizeof(dp->exten));
13663       dp->expiry = ast_tvnow();
13664       dp->orig = dp->expiry;
13665       /* Expires in 30 mins by default */
13666       dp->expiry.tv_sec += iaxdefaultdpcache;
13667       dp->flags = CACHE_FLAG_PENDING;
13668       for (x = 0; x < ARRAY_LEN(dp->waiters); x++)
13669          dp->waiters[x] = -1;
13670       /* Insert into the lists */
13671       AST_LIST_INSERT_TAIL(&dpcache, dp, cache_list);
13672       AST_LIST_INSERT_TAIL(&iaxs[callno]->dpentries, dp, peer_list);
13673       /* Send the request if we're already up */
13674       if (ast_test_flag(&iaxs[callno]->state, IAX_STATE_STARTED))
13675          iax2_dprequest(dp, callno);
13676       ast_mutex_unlock(&iaxsl[callno]);
13677    }
13678 
13679    /* By here we must have a dp */
13680    if (dp->flags & CACHE_FLAG_PENDING) {
13681       /* Okay, here it starts to get nasty.  We need a pipe now to wait
13682          for a reply to come back so long as it's pending */
13683       for (x = 0; x < ARRAY_LEN(dp->waiters); x++) {
13684          /* Find an empty slot */
13685          if (dp->waiters[x] < 0)
13686             break;
13687       }
13688       if (x >= ARRAY_LEN(dp->waiters)) {
13689          ast_log(LOG_WARNING, "No more waiter positions available\n");
13690          return NULL;
13691       }
13692       if (pipe(com)) {
13693          ast_log(LOG_WARNING, "Unable to create pipe for comm\n");
13694          return NULL;
13695       }
13696       dp->waiters[x] = com[1];
13697       /* Okay, now we wait */
13698       timeout = iaxdefaulttimeout * 1000;
13699       /* Temporarily unlock */
13700       AST_LIST_UNLOCK(&dpcache);
13701       /* Defer any dtmf */
13702       if (chan)
13703          old = ast_channel_defer_dtmf(chan);
13704       doabort = 0;
13705       while(timeout) {
13706          c = ast_waitfor_nandfds(&chan, chan ? 1 : 0, &com[0], 1, NULL, &outfd, &timeout);
13707          if (outfd > -1)
13708             break;
13709          if (!c)
13710             continue;
13711          if (!(f = ast_read(c))) {
13712             doabort = 1;
13713             break;
13714          }
13715          ast_frfree(f);
13716       }
13717       if (!timeout) {
13718          ast_log(LOG_WARNING, "Timeout waiting for %s exten %s\n", data, exten);
13719       }
13720       AST_LIST_LOCK(&dpcache);
13721       dp->waiters[x] = -1;
13722       close(com[1]);
13723       close(com[0]);
13724       if (doabort) {
13725          /* Don't interpret anything, just abort.  Not sure what th epoint
13726            of undeferring dtmf on a hung up channel is but hey whatever */
13727          if (!old && chan)
13728             ast_channel_undefer_dtmf(chan);
13729          return NULL;
13730       }
13731       if (!(dp->flags & CACHE_FLAG_TIMEOUT)) {
13732          /* Now to do non-independent analysis the results of our wait */
13733          if (dp->flags & CACHE_FLAG_PENDING) {
13734             /* Still pending... It's a timeout.  Wake everybody up.  Consider it no longer
13735                pending.  Don't let it take as long to timeout. */
13736             dp->flags &= ~CACHE_FLAG_PENDING;
13737             dp->flags |= CACHE_FLAG_TIMEOUT;
13738             /* Expire after only 60 seconds now.  This is designed to help reduce backlog in heavily loaded
13739                systems without leaving it unavailable once the server comes back online */
13740             dp->expiry.tv_sec = dp->orig.tv_sec + 60;
13741             for (x = 0; x < ARRAY_LEN(dp->waiters); x++) {
13742                if (dp->waiters[x] > -1) {
13743                   if (write(dp->waiters[x], "asdf", 4) < 0) {
13744                      ast_log(LOG_WARNING, "write() failed: %s\n", strerror(errno));
13745                   }
13746                }
13747             }
13748          }
13749       }
13750       /* Our caller will obtain the rest */
13751       if (!old && chan)
13752          ast_channel_undefer_dtmf(chan);
13753    }
13754    return dp;  
13755 }
13756 
13757 /*! \brief Part of the IAX2 switch interface */
13758 static int iax2_exists(struct ast_channel *chan, const char *context, const char *exten, int priority, const char *callerid, const char *data)
13759 {
13760    int res = 0;
13761    struct iax2_dpcache *dp = NULL;
13762 #if 0
13763    ast_log(LOG_NOTICE, "iax2_exists: con: %s, exten: %s, pri: %d, cid: %s, data: %s\n", context, exten, priority, callerid ? callerid : "<unknown>", data);
13764 #endif
13765    if ((priority != 1) && (priority != 2))
13766       return 0;
13767 
13768    AST_LIST_LOCK(&dpcache);
13769    if ((dp = find_cache(chan, data, context, exten, priority))) {
13770       if (dp->flags & CACHE_FLAG_EXISTS)
13771          res = 1;
13772    } else {
13773       ast_log(LOG_WARNING, "Unable to make DP cache\n");
13774    }
13775    AST_LIST_UNLOCK(&dpcache);
13776 
13777    return res;
13778 }
13779 
13780 /*! \brief part of the IAX2 dial plan switch interface */
13781 static int iax2_canmatch(struct ast_channel *chan, const char *context, const char *exten, int priority, const char *callerid, const char *data)
13782 {
13783    int res = 0;
13784    struct iax2_dpcache *dp = NULL;
13785 #if 0
13786    ast_log(LOG_NOTICE, "iax2_canmatch: con: %s, exten: %s, pri: %d, cid: %s, data: %s\n", context, exten, priority, callerid ? callerid : "<unknown>", data);
13787 #endif
13788    if ((priority != 1) && (priority != 2))
13789       return 0;
13790 
13791    AST_LIST_LOCK(&dpcache);
13792    if ((dp = find_cache(chan, data, context, exten, priority))) {
13793       if (dp->flags & CACHE_FLAG_CANEXIST)
13794          res = 1;
13795    } else {
13796       ast_log(LOG_WARNING, "Unable to make DP cache\n");
13797    }
13798    AST_LIST_UNLOCK(&dpcache);
13799 
13800    return res;
13801 }
13802 
13803 /*! \brief Part of the IAX2 Switch interface */
13804 static int iax2_matchmore(struct ast_channel *chan, const char *context, const char *exten, int priority, const char *callerid, const char *data)
13805 {
13806    int res = 0;
13807    struct iax2_dpcache *dp = NULL;
13808 #if 0
13809    ast_log(LOG_NOTICE, "iax2_matchmore: con: %s, exten: %s, pri: %d, cid: %s, data: %s\n", context, exten, priority, callerid ? callerid : "<unknown>", data);
13810 #endif
13811    if ((priority != 1) && (priority != 2))
13812       return 0;
13813 
13814    AST_LIST_LOCK(&dpcache);
13815    if ((dp = find_cache(chan, data, context, exten, priority))) {
13816       if (dp->flags & CACHE_FLAG_MATCHMORE)
13817          res = 1;
13818    } else {
13819       ast_log(LOG_WARNING, "Unable to make DP cache\n");
13820    }
13821    AST_LIST_UNLOCK(&dpcache);
13822 
13823    return res;
13824 }
13825 
13826 /*! \brief Execute IAX2 dialplan switch */
13827 static int iax2_exec(struct ast_channel *chan, const char *context, const char *exten, int priority, const char *callerid, const char *data)
13828 {
13829    char odata[256];
13830    char req[256];
13831    char *ncontext;
13832    struct iax2_dpcache *dp = NULL;
13833    struct ast_app *dial = NULL;
13834 #if 0
13835    ast_log(LOG_NOTICE, "iax2_exec: con: %s, exten: %s, pri: %d, cid: %s, data: %s, newstack: %d\n", context, exten, priority, callerid ? callerid : "<unknown>", data, newstack);
13836 #endif
13837    if (priority == 2) {
13838       /* Indicate status, can be overridden in dialplan */
13839       const char *dialstatus = pbx_builtin_getvar_helper(chan, "DIALSTATUS");
13840       if (dialstatus) {
13841          dial = pbx_findapp(dialstatus);
13842          if (dial) 
13843             pbx_exec(chan, dial, "");
13844       }
13845       return -1;
13846    } else if (priority != 1)
13847       return -1;
13848 
13849    AST_LIST_LOCK(&dpcache);
13850    if ((dp = find_cache(chan, data, context, exten, priority))) {
13851       if (dp->flags & CACHE_FLAG_EXISTS) {
13852          ast_copy_string(odata, data, sizeof(odata));
13853          ncontext = strchr(odata, '/');
13854          if (ncontext) {
13855             *ncontext = '\0';
13856             ncontext++;
13857             snprintf(req, sizeof(req), "IAX2/%s/%s@%s", odata, exten, ncontext);
13858          } else {
13859             snprintf(req, sizeof(req), "IAX2/%s/%s", odata, exten);
13860          }
13861          ast_verb(3, "Executing Dial('%s')\n", req);
13862       } else {
13863          AST_LIST_UNLOCK(&dpcache);
13864          ast_log(LOG_WARNING, "Can't execute nonexistent extension '%s[@%s]' in data '%s'\n", exten, context, data);
13865          return -1;
13866       }
13867    }
13868    AST_LIST_UNLOCK(&dpcache);
13869 
13870    if ((dial = pbx_findapp("Dial")))
13871       return pbx_exec(chan, dial, req);
13872    else
13873       ast_log(LOG_WARNING, "No dial application registered\n");
13874 
13875    return -1;
13876 }
13877 
13878 static int function_iaxpeer(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
13879 {
13880    struct iax2_peer *peer;
13881    char *peername, *colname;
13882 
13883    peername = ast_strdupa(data);
13884 
13885    /* if our channel, return the IP address of the endpoint of current channel */
13886    if (!strcmp(peername,"CURRENTCHANNEL")) {
13887            unsigned short callno;
13888       if (chan->tech != &iax2_tech)
13889          return -1;
13890       callno = PTR_TO_CALLNO(chan->tech_pvt);   
13891       ast_copy_string(buf, iaxs[callno]->addr.sin_addr.s_addr ? ast_inet_ntoa(iaxs[callno]->addr.sin_addr) : "", len);
13892       return 0;
13893    }
13894 
13895    if ((colname = strchr(peername, ',')))
13896       *colname++ = '\0';
13897    else
13898       colname = "ip";
13899 
13900    if (!(peer = find_peer(peername, 1)))
13901       return -1;
13902 
13903    if (!strcasecmp(colname, "ip")) {
13904       ast_copy_string(buf, ast_sockaddr_stringify_addr(&peer->addr), len);
13905    } else  if (!strcasecmp(colname, "status")) {
13906       peer_status(peer, buf, len); 
13907    } else  if (!strcasecmp(colname, "mailbox")) {
13908       ast_copy_string(buf, peer->mailbox, len);
13909    } else  if (!strcasecmp(colname, "context")) {
13910       ast_copy_string(buf, peer->context, len);
13911    } else  if (!strcasecmp(colname, "expire")) {
13912       snprintf(buf, len, "%d", peer->expire);
13913    } else  if (!strcasecmp(colname, "dynamic")) {
13914       ast_copy_string(buf, (ast_test_flag64(peer, IAX_DYNAMIC) ? "yes" : "no"), len);
13915    } else  if (!strcasecmp(colname, "callerid_name")) {
13916       ast_copy_string(buf, peer->cid_name, len);
13917    } else  if (!strcasecmp(colname, "callerid_num")) {
13918       ast_copy_string(buf, peer->cid_num, len);
13919    } else  if (!strcasecmp(colname, "codecs")) {
13920       ast_getformatname_multiple(buf, len -1, peer->capability);
13921    } else  if (!strncasecmp(colname, "codec[", 6)) {
13922       char *codecnum, *ptr;
13923       int codec = 0;
13924       
13925       codecnum = strchr(colname, '[');
13926       *codecnum = '\0';
13927       codecnum++;
13928       if ((ptr = strchr(codecnum, ']'))) {
13929          *ptr = '\0';
13930       }
13931       if((codec = ast_codec_pref_index(&peer->prefs, atoi(codecnum)))) {
13932          ast_copy_string(buf, ast_getformatname(codec), len);
13933       } else {
13934          buf[0] = '\0';
13935       }
13936    } else {
13937       buf[0] = '\0';
13938    }
13939 
13940    peer_unref(peer);
13941 
13942    return 0;
13943 }
13944 
13945 static struct ast_custom_function iaxpeer_function = {
13946    .name = "IAXPEER",
13947    .read = function_iaxpeer,
13948 };
13949 
13950 static int acf_channel_read(struct ast_channel *chan, const char *funcname, char *args, char *buf, size_t buflen)
13951 {
13952    struct chan_iax2_pvt *pvt;
13953    unsigned int callno;
13954    int res = 0;
13955 
13956    if (!chan || chan->tech != &iax2_tech) {
13957       ast_log(LOG_ERROR, "This function requires a valid IAX2 channel\n");
13958       return -1;
13959    }
13960 
13961    callno = PTR_TO_CALLNO(chan->tech_pvt);
13962    ast_mutex_lock(&iaxsl[callno]);
13963    if (!(pvt = iaxs[callno])) {
13964       ast_mutex_unlock(&iaxsl[callno]);
13965       return -1;
13966    }
13967 
13968    if (!strcasecmp(args, "osptoken")) {
13969       ast_copy_string(buf, pvt->osptoken, buflen);
13970    } else if (!strcasecmp(args, "peerip")) {
13971       ast_copy_string(buf, pvt->addr.sin_addr.s_addr ? ast_inet_ntoa(pvt->addr.sin_addr) : "", buflen);
13972    } else if (!strcasecmp(args, "peername")) {
13973       ast_copy_string(buf, pvt->username, buflen);
13974    } else if (!strcasecmp(args, "secure_signaling") || !strcasecmp(args, "secure_media")) {
13975       snprintf(buf, buflen, "%s", IAX_CALLENCRYPTED(pvt) ? "1" : "");
13976    } else {
13977       res = -1;
13978    }
13979 
13980    ast_mutex_unlock(&iaxsl[callno]);
13981 
13982    return res;
13983 }
13984 
13985 /*! \brief Part of the device state notification system ---*/
13986 static int iax2_devicestate(void *data) 
13987 {
13988    struct parsed_dial_string pds;
13989    char *tmp = ast_strdupa(data);
13990    struct iax2_peer *p;
13991    int res = AST_DEVICE_INVALID;
13992 
13993    memset(&pds, 0, sizeof(pds));
13994    parse_dial_string(tmp, &pds);
13995 
13996    if (ast_strlen_zero(pds.peer)) {
13997       ast_log(LOG_WARNING, "No peer provided in the IAX2 dial string '%s'\n", (char *) data);
13998       return res;
13999    }
14000    
14001    ast_debug(3, "Checking device state for device %s\n", pds.peer);
14002 
14003    /* SLD: FIXME: second call to find_peer during registration */
14004    if (!(p = find_peer(pds.peer, 1)))
14005       return res;
14006 
14007    res = AST_DEVICE_UNAVAILABLE;
14008    ast_debug(3, "iax2_devicestate: Found peer. What's device state of %s? addr=%d, defaddr=%d maxms=%d, lastms=%d\n",
14009       pds.peer, ast_sockaddr_ipv4(&p->addr), p->defaddr.sin_addr.s_addr, p->maxms, p->lastms);
14010    
14011    if ((ast_sockaddr_ipv4(&p->addr) || p->defaddr.sin_addr.s_addr) &&
14012        (!p->maxms || ((p->lastms > -1) && (p->historicms <= p->maxms)))) {
14013       /* Peer is registered, or have default IP address
14014          and a valid registration */
14015       if (p->historicms == 0 || p->historicms <= p->maxms)
14016          /* let the core figure out whether it is in use or not */
14017          res = AST_DEVICE_UNKNOWN;  
14018    }
14019 
14020    peer_unref(p);
14021 
14022    return res;
14023 }
14024 
14025 static struct ast_switch iax2_switch = 
14026 {
14027    name:        "IAX2",
14028    description: "IAX Remote Dialplan Switch",
14029    exists:      iax2_exists,
14030    canmatch:    iax2_canmatch,
14031    exec:        iax2_exec,
14032    matchmore:   iax2_matchmore,
14033 };
14034 
14035 /*
14036    { { "iax2", "show", "cache", NULL },
14037    iax2_show_cache, "Display IAX cached dialplan",
14038    show_cache_usage },
14039 
14040    { { "iax2", "show", "channels", NULL },
14041    iax2_show_channels, "List active IAX channels",
14042    show_channels_usage },
14043 
14044    { { "iax2", "show", "firmware", NULL },
14045    iax2_show_firmware, "List available IAX firmwares",
14046    show_firmware_usage },
14047 
14048    { { "iax2", "show", "netstats", NULL },
14049    iax2_show_netstats, "List active IAX channel netstats",
14050    show_netstats_usage },
14051 
14052    { { "iax2", "show", "peers", NULL },
14053    iax2_show_peers, "List defined IAX peers",
14054    show_peers_usage },
14055 
14056    { { "iax2", "show", "registry", NULL },
14057    iax2_show_registry, "Display IAX registration status",
14058    show_reg_usage },
14059 
14060    { { "iax2", "show", "stats", NULL },
14061    iax2_show_stats, "Display IAX statistics",
14062    show_stats_usage },
14063 
14064    { { "iax2", "show", "threads", NULL },
14065    iax2_show_threads, "Display IAX helper thread info",
14066    show_threads_usage },
14067 
14068    { { "iax2", "unregister", NULL },
14069    iax2_unregister, "Unregister (force expiration) an IAX2 peer from the registry",
14070    unregister_usage, complete_iax2_unregister },
14071 
14072    { { "iax2", "set", "mtu", NULL },
14073    iax2_set_mtu, "Set the IAX systemwide trunking MTU",
14074    set_mtu_usage, NULL, NULL },
14075 
14076    { { "iax2", "show", "users", NULL },
14077    iax2_show_users, "List defined IAX users",
14078    show_users_usage },
14079 
14080    { { "iax2", "prune", "realtime", NULL },
14081    iax2_prune_realtime, "Prune a cached realtime lookup",
14082    prune_realtime_usage, complete_iax2_show_peer },
14083 
14084    { { "iax2", "reload", NULL },
14085    iax2_reload, "Reload IAX configuration",
14086    iax2_reload_usage },
14087 
14088    { { "iax2", "show", "peer", NULL },
14089    iax2_show_peer, "Show details on specific IAX peer",
14090    show_peer_usage, complete_iax2_show_peer },
14091 
14092    { { "iax2", "set", "debug", NULL },
14093    iax2_do_debug, "Enable IAX debugging",
14094    debug_usage },
14095 
14096    { { "iax2", "set", "debug", "trunk", NULL },
14097    iax2_do_trunk_debug, "Enable IAX trunk debugging",
14098    debug_trunk_usage },
14099 
14100    { { "iax2", "set", "debug", "jb", NULL },
14101    iax2_do_jb_debug, "Enable IAX jitterbuffer debugging",
14102    debug_jb_usage },
14103 
14104    { { "iax2", "set", "debug", "off", NULL },
14105    iax2_no_debug, "Disable IAX debugging",
14106    no_debug_usage },
14107 
14108    { { "iax2", "set", "debug", "trunk", "off", NULL },
14109    iax2_no_trunk_debug, "Disable IAX trunk debugging",
14110    no_debug_trunk_usage },
14111 
14112    { { "iax2", "set", "debug", "jb", "off", NULL },
14113    iax2_no_jb_debug, "Disable IAX jitterbuffer debugging",
14114    no_debug_jb_usage },
14115 
14116    { { "iax2", "test", "losspct", NULL },
14117    iax2_test_losspct, "Set IAX2 incoming frame loss percentage",
14118    iax2_test_losspct_usage },
14119 
14120    { { "iax2", "provision", NULL },
14121    iax2_prov_cmd, "Provision an IAX device",
14122    show_prov_usage, iax2_prov_complete_template_3rd },
14123 
14124 #ifdef IAXTESTS
14125    { { "iax2", "test", "late", NULL },
14126    iax2_test_late, "Test the receipt of a late frame",
14127    iax2_test_late_usage },
14128 
14129    { { "iax2", "test", "resync", NULL },
14130    iax2_test_resync, "Test a resync in received timestamps",
14131    iax2_test_resync_usage },
14132 
14133    { { "iax2", "test", "jitter", NULL },
14134    iax2_test_jitter, "Simulates jitter for testing",
14135    iax2_test_jitter_usage },
14136 #endif
14137 */
14138 
14139 static struct ast_cli_entry cli_iax2[] = {
14140    AST_CLI_DEFINE(handle_cli_iax2_provision,           "Provision an IAX device"),
14141    AST_CLI_DEFINE(handle_cli_iax2_prune_realtime,      "Prune a cached realtime lookup"),
14142    AST_CLI_DEFINE(handle_cli_iax2_reload,              "Reload IAX configuration"),
14143    AST_CLI_DEFINE(handle_cli_iax2_set_mtu,             "Set the IAX systemwide trunking MTU"),
14144    AST_CLI_DEFINE(handle_cli_iax2_set_debug,           "Enable/Disable IAX debugging"),
14145    AST_CLI_DEFINE(handle_cli_iax2_set_debug_trunk,     "Enable/Disable IAX trunk debugging"),
14146    AST_CLI_DEFINE(handle_cli_iax2_set_debug_jb,        "Enable/Disable IAX jitterbuffer debugging"),
14147    AST_CLI_DEFINE(handle_cli_iax2_show_cache,          "Display IAX cached dialplan"),
14148    AST_CLI_DEFINE(handle_cli_iax2_show_channels,       "List active IAX channels"),
14149    AST_CLI_DEFINE(handle_cli_iax2_show_firmware,       "List available IAX firmware"),
14150    AST_CLI_DEFINE(handle_cli_iax2_show_netstats,       "List active IAX channel netstats"),
14151    AST_CLI_DEFINE(handle_cli_iax2_show_peer,           "Show details on specific IAX peer"),
14152    AST_CLI_DEFINE(handle_cli_iax2_show_peers,          "List defined IAX peers"),
14153    AST_CLI_DEFINE(handle_cli_iax2_show_registry,       "Display IAX registration status"),
14154    AST_CLI_DEFINE(handle_cli_iax2_show_stats,          "Display IAX statistics"),
14155    AST_CLI_DEFINE(handle_cli_iax2_show_threads,        "Display IAX helper thread info"),
14156    AST_CLI_DEFINE(handle_cli_iax2_show_users,          "List defined IAX users"),
14157    AST_CLI_DEFINE(handle_cli_iax2_test_losspct,        "Set IAX2 incoming frame loss percentage"),
14158    AST_CLI_DEFINE(handle_cli_iax2_unregister,          "Unregister (force expiration) an IAX2 peer from the registry"),
14159    AST_CLI_DEFINE(handle_cli_iax2_show_callno_limits,  "Show current entries in IP call number limit table"),
14160 #ifdef IAXTESTS
14161    AST_CLI_DEFINE(handle_cli_iax2_test_jitter,         "Simulates jitter for testing"),
14162    AST_CLI_DEFINE(handle_cli_iax2_test_late,           "Test the receipt of a late frame"),
14163    AST_CLI_DEFINE(handle_cli_iax2_test_resync,         "Test a resync in received timestamps"),
14164 #endif /* IAXTESTS */
14165 };
14166 
14167 #ifdef TEST_FRAMEWORK
14168 AST_TEST_DEFINE(test_iax2_peers_get)
14169 {
14170    struct ast_data_query query = {
14171       .path = "/asterisk/channel/iax2/peers",
14172       .search = "peers/peer/name=test_peer_data_provider"
14173    };
14174    struct ast_data *node;
14175    struct iax2_peer *peer;
14176 
14177    switch (cmd) {
14178       case TEST_INIT:
14179          info->name = "iax2_peers_get_data_test";
14180          info->category = "/main/data/iax2/peers/";
14181          info->summary = "IAX2 peers data providers unit test";
14182          info->description =
14183             "Tests whether the IAX2 peers data provider implementation works as expected.";
14184          return AST_TEST_NOT_RUN;
14185       case TEST_EXECUTE:
14186          break;
14187    }
14188 
14189    /* build a test peer */
14190    peer = build_peer("test_peer_data_provider", NULL, NULL, 0);
14191    if (!peer) {
14192       return AST_TEST_FAIL;
14193    }
14194    peer->expiry= 1010;
14195    ao2_link(peers, peer);
14196 
14197    node = ast_data_get(&query);
14198    if (!node) {
14199       ao2_unlink(peers, peer);
14200       peer_unref(peer);
14201       return AST_TEST_FAIL;
14202    }
14203 
14204    /* check returned data node. */
14205    if (strcmp(ast_data_retrieve_string(node, "peer/name"), "test_peer_data_provider")) {
14206       ao2_unlink(peers, peer);
14207       peer_unref(peer);
14208       ast_data_free(node);
14209       return AST_TEST_FAIL;
14210    }
14211 
14212    if (ast_data_retrieve_int(node, "peer/expiry") != 1010) {
14213       ao2_unlink(peers, peer);
14214       peer_unref(peer);
14215       ast_data_free(node);
14216       return AST_TEST_FAIL;
14217    }
14218 
14219    /* release resources */
14220    ast_data_free(node);
14221 
14222    ao2_unlink(peers, peer);
14223    peer_unref(peer);
14224 
14225    return AST_TEST_PASS;
14226 }
14227 
14228 AST_TEST_DEFINE(test_iax2_users_get)
14229 {
14230    struct ast_data_query query = {
14231       .path = "/asterisk/channel/iax2/users",
14232       .search = "users/user/name=test_user_data_provider"
14233    };
14234    struct ast_data *node;
14235    struct iax2_user *user;
14236 
14237    switch (cmd) {
14238       case TEST_INIT:
14239          info->name = "iax2_users_get_data_test";
14240          info->category = "/main/data/iax2/users/";
14241          info->summary = "IAX2 users data providers unit test";
14242          info->description =
14243             "Tests whether the IAX2 users data provider implementation works as expected.";
14244          return AST_TEST_NOT_RUN;
14245       case TEST_EXECUTE:
14246          break;
14247    }
14248 
14249    user = build_user("test_user_data_provider", NULL, NULL, 0);
14250    if (!user) {
14251       ast_test_status_update(test, "Failed to build a test user\n");
14252       return AST_TEST_FAIL;
14253    }
14254    user->amaflags = 1010;
14255    ao2_link(users, user);
14256 
14257    node = ast_data_get(&query);
14258    if (!node) {
14259       ast_test_status_update(test, "The data query to find our test user failed\n");
14260       ao2_unlink(users, user);
14261       user_unref(user);
14262       return AST_TEST_FAIL;
14263    }
14264 
14265    if (strcmp(ast_data_retrieve_string(node, "user/name"), "test_user_data_provider")) {
14266       ast_test_status_update(test, "Our data results did not return the test user created in the previous step.\n");
14267       ao2_unlink(users, user);
14268       user_unref(user);
14269       ast_data_free(node);
14270       return AST_TEST_FAIL;
14271    }
14272 
14273    if (ast_data_retrieve_int(node, "user/amaflags/value") != 1010) {
14274       ast_test_status_update(test, "The amaflags field in our test user was '%d' not the expected value '1010'\n", ast_data_retrieve_int(node, "user/amaflags/value"));
14275       ao2_unlink(users, user);
14276       user_unref(user);
14277       ast_data_free(node);
14278       return AST_TEST_FAIL;
14279    }
14280 
14281    ast_data_free(node);
14282 
14283    ao2_unlink(users, user);
14284    user_unref(user);
14285 
14286    return AST_TEST_PASS;
14287 }
14288 #endif
14289 
14290 static void cleanup_thread_list(void *head)
14291 {
14292    AST_LIST_HEAD(iax2_thread_list, iax2_thread);
14293    struct iax2_thread_list *list_head = head;
14294    struct iax2_thread *thread;
14295 
14296    AST_LIST_LOCK(list_head);
14297    while ((thread = AST_LIST_REMOVE_HEAD(&idle_list, list))) {
14298       pthread_t thread_id = thread->threadid;
14299 
14300       thread->stop = 1;
14301       signal_condition(&thread->lock, &thread->cond);
14302 
14303       AST_LIST_UNLOCK(list_head);
14304       pthread_join(thread_id, NULL);
14305       AST_LIST_LOCK(list_head);
14306    }
14307    AST_LIST_UNLOCK(list_head);
14308 }
14309 
14310 static int __unload_module(void)
14311 {
14312    struct ast_context *con;
14313    int x;
14314 
14315    network_change_event_unsubscribe();
14316 
14317    ast_manager_unregister("IAXpeers");
14318    ast_manager_unregister("IAXpeerlist");
14319    ast_manager_unregister("IAXnetstats");
14320    ast_manager_unregister("IAXregistry");
14321    ast_unregister_application(papp);
14322    ast_cli_unregister_multiple(cli_iax2, ARRAY_LEN(cli_iax2));
14323    ast_unregister_switch(&iax2_switch);
14324    ast_channel_unregister(&iax2_tech);
14325 
14326    if (netthreadid != AST_PTHREADT_NULL) {
14327       pthread_cancel(netthreadid);
14328       pthread_kill(netthreadid, SIGURG);
14329       pthread_join(netthreadid, NULL);
14330    }
14331 
14332    for (x = 0; x < ARRAY_LEN(iaxs); x++) {
14333       if (iaxs[x]) {
14334          iax2_destroy(x);
14335       }
14336    }
14337 
14338    /* Call for all threads to halt */
14339    cleanup_thread_list(&idle_list);
14340    cleanup_thread_list(&active_list);
14341    cleanup_thread_list(&dynamic_list);
14342 
14343    ast_netsock_release(netsock);
14344    ast_netsock_release(outsock);
14345    for (x = 0; x < ARRAY_LEN(iaxs); x++) {
14346       if (iaxs[x]) {
14347          iax2_destroy(x);
14348       }
14349    }
14350    ast_manager_unregister( "IAXpeers" );
14351    ast_manager_unregister( "IAXpeerlist" );
14352    ast_manager_unregister( "IAXnetstats" );
14353    ast_manager_unregister( "IAXregistry" );
14354    ast_unregister_application(papp);
14355 #ifdef TEST_FRAMEWORK
14356    AST_TEST_UNREGISTER(test_iax2_peers_get);
14357    AST_TEST_UNREGISTER(test_iax2_users_get);
14358 #endif
14359    ast_data_unregister(NULL);
14360    ast_cli_unregister_multiple(cli_iax2, ARRAY_LEN(cli_iax2));
14361    ast_unregister_switch(&iax2_switch);
14362    ast_channel_unregister(&iax2_tech);
14363    delete_users();
14364    iax_provision_unload();
14365    reload_firmware(1);
14366 
14367    for (x = 0; x < ARRAY_LEN(iaxsl); x++) {
14368       ast_mutex_destroy(&iaxsl[x]);
14369    }
14370 
14371    ao2_ref(peers, -1);
14372    ao2_ref(users, -1);
14373    ao2_ref(iax_peercallno_pvts, -1);
14374    ao2_ref(iax_transfercallno_pvts, -1);
14375    ao2_ref(peercnts, -1);
14376    ao2_ref(callno_limits, -1);
14377    ao2_ref(calltoken_ignores, -1);
14378    ao2_ref(callno_pool, -1);
14379    ao2_ref(callno_pool_trunk, -1);
14380    if (timer) {
14381       ast_timer_close(timer);
14382    }
14383    transmit_processor = ast_taskprocessor_unreference(transmit_processor);
14384    sched = ast_sched_thread_destroy(sched);
14385 
14386    con = ast_context_find(regcontext);
14387    if (con)
14388       ast_context_destroy(con, "IAX2");
14389    ast_unload_realtime("iaxpeers");
14390    return 0;
14391 }
14392 
14393 static int unload_module(void)
14394 {
14395    ast_custom_function_unregister(&iaxpeer_function);
14396    ast_custom_function_unregister(&iaxvar_function);
14397    return __unload_module();
14398 }
14399 
14400 static int peer_set_sock_cb(void *obj, void *arg, int flags)
14401 {
14402    struct iax2_peer *peer = obj;
14403 
14404    if (peer->sockfd < 0)
14405       peer->sockfd = defaultsockfd;
14406 
14407    return 0;
14408 }
14409 
14410 static int pvt_hash_cb(const void *obj, const int flags)
14411 {
14412    const struct chan_iax2_pvt *pvt = obj;
14413 
14414    return pvt->peercallno;
14415 }
14416 
14417 static int pvt_cmp_cb(void *obj, void *arg, int flags)
14418 {
14419    struct chan_iax2_pvt *pvt = obj, *pvt2 = arg;
14420 
14421    /* The frames_received field is used to hold whether we're matching
14422     * against a full frame or not ... */
14423 
14424    return match(&pvt2->addr, pvt2->peercallno, pvt2->callno, pvt, 
14425       pvt2->frames_received) ? CMP_MATCH | CMP_STOP : 0;
14426 }
14427 
14428 static int transfercallno_pvt_hash_cb(const void *obj, const int flags)
14429 {
14430    const struct chan_iax2_pvt *pvt = obj;
14431 
14432    return pvt->transfercallno;
14433 }
14434 
14435 static int transfercallno_pvt_cmp_cb(void *obj, void *arg, int flags)
14436 {
14437    struct chan_iax2_pvt *pvt = obj, *pvt2 = arg;
14438 
14439    /* The frames_received field is used to hold whether we're matching
14440     * against a full frame or not ... */
14441 
14442    return match(&pvt2->transfer, pvt2->transfercallno, pvt2->callno, pvt,
14443       pvt2->frames_received) ? CMP_MATCH | CMP_STOP : 0;
14444 }
14445 
14446 static int load_objects(void)
14447 {
14448    peers = users = iax_peercallno_pvts = iax_transfercallno_pvts = NULL;
14449    peercnts = callno_limits = calltoken_ignores = callno_pool = callno_pool_trunk = NULL;
14450 
14451    if (!(peers = ao2_container_alloc(MAX_PEER_BUCKETS, peer_hash_cb, peer_cmp_cb))) {
14452       goto container_fail;
14453    } else if (!(users = ao2_container_alloc(MAX_USER_BUCKETS, user_hash_cb, user_cmp_cb))) {
14454       goto container_fail;
14455    } else if (!(iax_peercallno_pvts = ao2_container_alloc(IAX_MAX_CALLS, pvt_hash_cb, pvt_cmp_cb))) {
14456       goto container_fail;
14457    } else if (!(iax_transfercallno_pvts = ao2_container_alloc(IAX_MAX_CALLS, transfercallno_pvt_hash_cb, transfercallno_pvt_cmp_cb))) {
14458       goto container_fail;
14459    } else if (!(peercnts = ao2_container_alloc(MAX_PEER_BUCKETS, peercnt_hash_cb, peercnt_cmp_cb))) {
14460       goto container_fail;
14461    } else if (!(callno_limits = ao2_container_alloc(MAX_PEER_BUCKETS, addr_range_hash_cb, addr_range_cmp_cb))) {
14462       goto container_fail;
14463    } else if (!(calltoken_ignores = ao2_container_alloc(MAX_PEER_BUCKETS, addr_range_hash_cb, addr_range_cmp_cb))) {
14464       goto container_fail;
14465    } else if (create_callno_pools()) {
14466       goto container_fail;
14467    } else if  (!(transmit_processor = ast_taskprocessor_get("iax2_transmit", TPS_REF_DEFAULT))) {
14468       goto container_fail;
14469    }
14470 
14471    return 0;
14472 
14473 container_fail:
14474    if (peers) {
14475       ao2_ref(peers, -1);
14476    }
14477    if (users) {
14478       ao2_ref(users, -1);
14479    }
14480    if (iax_peercallno_pvts) {
14481       ao2_ref(iax_peercallno_pvts, -1);
14482    }
14483    if (iax_transfercallno_pvts) {
14484       ao2_ref(iax_transfercallno_pvts, -1);
14485    }
14486    if (peercnts) {
14487       ao2_ref(peercnts, -1);
14488    }
14489    if (callno_limits) {
14490       ao2_ref(callno_limits, -1);
14491    }
14492    if (calltoken_ignores) {
14493       ao2_ref(calltoken_ignores, -1);
14494    }
14495    if (callno_pool) {
14496       ao2_ref(callno_pool, -1);
14497    }
14498    if (callno_pool_trunk) {
14499       ao2_ref(callno_pool_trunk, -1);
14500    }
14501    return AST_MODULE_LOAD_FAILURE;
14502 }
14503 
14504 
14505 #define DATA_EXPORT_IAX2_PEER(MEMBER)           \
14506    MEMBER(iax2_peer, name, AST_DATA_STRING)     \
14507    MEMBER(iax2_peer, username, AST_DATA_STRING)    \
14508    MEMBER(iax2_peer, secret, AST_DATA_PASSWORD)    \
14509    MEMBER(iax2_peer, dbsecret, AST_DATA_PASSWORD)     \
14510    MEMBER(iax2_peer, outkey, AST_DATA_STRING)      \
14511    MEMBER(iax2_peer, regexten, AST_DATA_STRING)    \
14512    MEMBER(iax2_peer, context, AST_DATA_STRING)     \
14513    MEMBER(iax2_peer, peercontext, AST_DATA_STRING)    \
14514    MEMBER(iax2_peer, mailbox, AST_DATA_STRING)     \
14515    MEMBER(iax2_peer, mohinterpret, AST_DATA_STRING)   \
14516    MEMBER(iax2_peer, mohsuggest, AST_DATA_STRING)     \
14517    MEMBER(iax2_peer, inkeys, AST_DATA_STRING)      \
14518    MEMBER(iax2_peer, cid_num, AST_DATA_STRING)     \
14519    MEMBER(iax2_peer, cid_name, AST_DATA_STRING)    \
14520    MEMBER(iax2_peer, zonetag, AST_DATA_STRING)     \
14521    MEMBER(iax2_peer, parkinglot, AST_DATA_STRING)     \
14522    MEMBER(iax2_peer, expiry, AST_DATA_SECONDS)     \
14523    MEMBER(iax2_peer, callno, AST_DATA_INTEGER)     \
14524    MEMBER(iax2_peer, lastms, AST_DATA_MILLISECONDS)   \
14525    MEMBER(iax2_peer, maxms, AST_DATA_MILLISECONDS)    \
14526    MEMBER(iax2_peer, pokefreqok, AST_DATA_MILLISECONDS)  \
14527    MEMBER(iax2_peer, pokefreqnotok, AST_DATA_MILLISECONDS)  \
14528    MEMBER(iax2_peer, historicms, AST_DATA_INTEGER)    \
14529    MEMBER(iax2_peer, smoothing, AST_DATA_BOOLEAN)     \
14530         MEMBER(iax2_peer, maxcallno, AST_DATA_INTEGER)
14531 
14532 AST_DATA_STRUCTURE(iax2_peer, DATA_EXPORT_IAX2_PEER);
14533 
14534 static int peers_data_provider_get(const struct ast_data_search *search,
14535    struct ast_data *data_root)
14536 {
14537    struct ast_data *data_peer;
14538    struct iax2_peer *peer;
14539    struct ao2_iterator i;
14540    char status[20];
14541    struct ast_str *encmethods = ast_str_alloca(256);
14542 
14543    i = ao2_iterator_init(peers, 0);
14544    while ((peer = ao2_iterator_next(&i))) {
14545       data_peer = ast_data_add_node(data_root, "peer");
14546       if (!data_peer) {
14547          peer_unref(peer);
14548          continue;
14549       }
14550 
14551       ast_data_add_structure(iax2_peer, data_peer, peer);
14552 
14553       ast_data_add_codecs(data_peer, "codecs", peer->capability);
14554 
14555       peer_status(peer, status, sizeof(status));
14556       ast_data_add_str(data_peer, "status", status);
14557 
14558       ast_data_add_str(data_peer, "host", ast_sockaddr_stringify_host(&peer->addr));
14559 
14560       ast_data_add_str(data_peer, "mask", ast_inet_ntoa(peer->mask));
14561 
14562       ast_data_add_int(data_peer, "port", ast_sockaddr_port(&peer->addr));
14563 
14564       ast_data_add_bool(data_peer, "trunk", ast_test_flag64(peer, IAX_TRUNK));
14565 
14566       ast_data_add_bool(data_peer, "dynamic", ast_test_flag64(peer, IAX_DYNAMIC));
14567 
14568       encmethods_to_str(peer->encmethods, encmethods);
14569       ast_data_add_str(data_peer, "encryption", peer->encmethods ? ast_str_buffer(encmethods) : "no");
14570 
14571       peer_unref(peer);
14572 
14573       if (!ast_data_search_match(search, data_peer)) {
14574          ast_data_remove_node(data_root, data_peer);
14575       }
14576    }
14577    ao2_iterator_destroy(&i);
14578 
14579    return 0;
14580 }
14581 
14582 #define DATA_EXPORT_IAX2_USER(MEMBER)              \
14583         MEMBER(iax2_user, name, AST_DATA_STRING)         \
14584         MEMBER(iax2_user, dbsecret, AST_DATA_PASSWORD)         \
14585         MEMBER(iax2_user, accountcode, AST_DATA_STRING)        \
14586         MEMBER(iax2_user, mohinterpret, AST_DATA_STRING)    \
14587         MEMBER(iax2_user, mohsuggest, AST_DATA_STRING)         \
14588         MEMBER(iax2_user, inkeys, AST_DATA_STRING)       \
14589         MEMBER(iax2_user, language, AST_DATA_STRING)        \
14590         MEMBER(iax2_user, cid_num, AST_DATA_STRING)         \
14591         MEMBER(iax2_user, cid_name, AST_DATA_STRING)        \
14592         MEMBER(iax2_user, parkinglot, AST_DATA_STRING)         \
14593         MEMBER(iax2_user, maxauthreq, AST_DATA_INTEGER)        \
14594         MEMBER(iax2_user, curauthreq, AST_DATA_INTEGER)
14595 
14596 AST_DATA_STRUCTURE(iax2_user, DATA_EXPORT_IAX2_USER);
14597 
14598 static int users_data_provider_get(const struct ast_data_search *search,
14599    struct ast_data *data_root)
14600 {
14601    struct ast_data *data_user, *data_authmethods, *data_enum_node;
14602    struct iax2_user *user;
14603    struct ao2_iterator i;
14604    char auth[90];
14605    char *pstr = "";
14606 
14607    i = ao2_iterator_init(users, 0);
14608    for (; (user = ao2_iterator_next(&i)); user_unref(user)) {
14609       data_user = ast_data_add_node(data_root, "user");
14610       if (!data_user) {
14611          continue;
14612       }
14613 
14614       ast_data_add_structure(iax2_user, data_user, user);
14615 
14616       ast_data_add_codecs(data_user, "codecs", user->capability);
14617 
14618       if (!ast_strlen_zero(user->secret)) {
14619          ast_copy_string(auth, user->secret, sizeof(auth));
14620       } else if (!ast_strlen_zero(user->inkeys)) {
14621          snprintf(auth, sizeof(auth), "Key: %s", user->inkeys);
14622       } else {
14623          ast_copy_string(auth, "no secret", sizeof(auth));
14624       }
14625       ast_data_add_password(data_user, "secret", auth);
14626 
14627       ast_data_add_str(data_user, "context", user->contexts ? user->contexts->context : DEFAULT_CONTEXT);
14628 
14629       /* authmethods */
14630       data_authmethods = ast_data_add_node(data_user, "authmethods");
14631       if (!data_authmethods) {
14632          ast_data_remove_node(data_root, data_user);
14633          continue;
14634       }
14635       ast_data_add_bool(data_authmethods, "rsa", user->authmethods & IAX_AUTH_RSA);
14636       ast_data_add_bool(data_authmethods, "md5", user->authmethods & IAX_AUTH_MD5);
14637       ast_data_add_bool(data_authmethods, "plaintext", user->authmethods & IAX_AUTH_PLAINTEXT);
14638 
14639       /* amaflags */
14640       data_enum_node = ast_data_add_node(data_user, "amaflags");
14641       if (!data_enum_node) {
14642          ast_data_remove_node(data_root, data_user);
14643          continue;
14644       }
14645       ast_data_add_int(data_enum_node, "value", user->amaflags);
14646       ast_data_add_str(data_enum_node, "text", ast_cdr_flags2str(user->amaflags));
14647 
14648       ast_data_add_bool(data_user, "access-control", user->ha ? 1 : 0);
14649 
14650       if (ast_test_flag64(user, IAX_CODEC_NOCAP)) {
14651          pstr = "REQ only";
14652       } else if (ast_test_flag64(user, IAX_CODEC_NOPREFS)) {
14653          pstr = "disabled";
14654       } else {
14655          pstr = ast_test_flag64(user, IAX_CODEC_USER_FIRST) ? "caller" : "host";
14656       }
14657       ast_data_add_str(data_user, "codec-preferences", pstr);
14658 
14659       if (!ast_data_search_match(search, data_user)) {
14660          ast_data_remove_node(data_root, data_user);
14661       }
14662    }
14663    ao2_iterator_destroy(&i);
14664 
14665    return 0;
14666 }
14667 
14668 static const struct ast_data_handler peers_data_provider = {
14669    .version = AST_DATA_HANDLER_VERSION,
14670    .get = peers_data_provider_get
14671 };
14672 
14673 static const struct ast_data_handler users_data_provider = {
14674    .version = AST_DATA_HANDLER_VERSION,
14675    .get = users_data_provider_get
14676 };
14677 
14678 static const struct ast_data_entry iax2_data_providers[] = {
14679    AST_DATA_ENTRY("asterisk/channel/iax2/peers", &peers_data_provider),
14680    AST_DATA_ENTRY("asterisk/channel/iax2/users", &users_data_provider),
14681 };
14682 
14683 /*! \brief Load IAX2 module, load configuraiton ---*/
14684 static int load_module(void)
14685 {
14686    static const char config[] = "iax.conf";
14687    int x = 0;
14688    struct iax2_registry *reg = NULL;
14689 
14690    if (load_objects()) {
14691       return AST_MODULE_LOAD_FAILURE;
14692    }
14693 
14694    memset(iaxs, 0, sizeof(iaxs));
14695 
14696    for (x = 0; x < ARRAY_LEN(iaxsl); x++) {
14697       ast_mutex_init(&iaxsl[x]);
14698    }
14699 
14700    if (!(sched = ast_sched_thread_create())) {
14701       ast_log(LOG_ERROR, "Failed to create scheduler thread\n");
14702       return AST_MODULE_LOAD_FAILURE;
14703    }
14704 
14705    if (!(io = io_context_create())) {
14706       ast_log(LOG_ERROR, "Failed to create I/O context\n");
14707       sched = ast_sched_thread_destroy(sched);
14708       return AST_MODULE_LOAD_FAILURE;
14709    }
14710 
14711    if (!(netsock = ast_netsock_list_alloc())) {
14712       ast_log(LOG_ERROR, "Failed to create netsock list\n");
14713       io_context_destroy(io);
14714       sched = ast_sched_thread_destroy(sched);
14715       return AST_MODULE_LOAD_FAILURE;
14716    }
14717    ast_netsock_init(netsock);
14718    
14719    outsock = ast_netsock_list_alloc();
14720    if (!outsock) {
14721       ast_log(LOG_ERROR, "Could not allocate outsock list.\n");
14722       io_context_destroy(io);
14723       sched = ast_sched_thread_destroy(sched);
14724       return AST_MODULE_LOAD_FAILURE;
14725    }
14726    ast_netsock_init(outsock);
14727 
14728    randomcalltokendata = ast_random();
14729 
14730    iax_set_output(iax_debug_output);
14731    iax_set_error(iax_error_output);
14732    jb_setoutput(jb_error_output, jb_warning_output, NULL);
14733    
14734    if ((timer = ast_timer_open())) {
14735       ast_timer_set_rate(timer, 1000 / trunkfreq);
14736    }
14737 
14738    if (set_config(config, 0) == -1) {
14739       if (timer) {
14740          ast_timer_close(timer);
14741       }
14742       return AST_MODULE_LOAD_DECLINE;
14743    }
14744 
14745 #ifdef TEST_FRAMEWORK
14746    AST_TEST_REGISTER(test_iax2_peers_get);
14747    AST_TEST_REGISTER(test_iax2_users_get);
14748 #endif
14749 
14750    /* Register AstData providers */
14751    ast_data_register_multiple(iax2_data_providers, ARRAY_LEN(iax2_data_providers));
14752    ast_cli_register_multiple(cli_iax2, ARRAY_LEN(cli_iax2));
14753 
14754    ast_register_application_xml(papp, iax2_prov_app);
14755 
14756    ast_custom_function_register(&iaxpeer_function);
14757    ast_custom_function_register(&iaxvar_function);
14758 
14759    ast_manager_register_xml("IAXpeers", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_iax2_show_peers);
14760    ast_manager_register_xml("IAXpeerlist", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_iax2_show_peer_list);
14761    ast_manager_register_xml("IAXnetstats", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_iax2_show_netstats);
14762    ast_manager_register_xml("IAXregistry", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_iax2_show_registry);
14763 
14764    if (ast_channel_register(&iax2_tech)) {
14765       ast_log(LOG_ERROR, "Unable to register channel class %s\n", "IAX2");
14766       __unload_module();
14767       return AST_MODULE_LOAD_FAILURE;
14768    }
14769 
14770    if (ast_register_switch(&iax2_switch)) {
14771       ast_log(LOG_ERROR, "Unable to register IAX switch\n");
14772    }
14773 
14774    if (start_network_thread()) {
14775       ast_log(LOG_ERROR, "Unable to start network thread\n");
14776       __unload_module();
14777       return AST_MODULE_LOAD_FAILURE;
14778    } else {
14779       ast_verb(2, "IAX Ready and Listening\n");
14780    }
14781 
14782    AST_LIST_LOCK(&registrations);
14783    AST_LIST_TRAVERSE(&registrations, reg, entry)
14784       iax2_do_register(reg);
14785    AST_LIST_UNLOCK(&registrations); 
14786    
14787    ao2_callback(peers, 0, peer_set_sock_cb, NULL);
14788    ao2_callback(peers, 0, iax2_poke_peer_cb, NULL);
14789 
14790 
14791    reload_firmware(0);
14792    iax_provision_reload(0);
14793 
14794    ast_realtime_require_field("iaxpeers", "name", RQ_CHAR, 10, "ipaddr", RQ_CHAR, 15, "port", RQ_UINTEGER2, 5, "regseconds", RQ_UINTEGER2, 6, SENTINEL);
14795 
14796    network_change_event_subscribe();
14797 
14798    return AST_MODULE_LOAD_SUCCESS;
14799 }
14800 
14801 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "Inter Asterisk eXchange (Ver 2)",
14802       .load = load_module,
14803       .unload = unload_module,
14804       .reload = reload,
14805       .load_pri = AST_MODPRI_CHANNEL_DRIVER,
14806       .nonoptreq = "res_crypto",
14807       );