Sat Apr 26 2014 22:01:31

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 type="external">crypto</use>
00036    <support_level>core</support_level>
00037  ***/
00038 
00039 #include "asterisk.h"
00040 
00041 ASTERISK_FILE_VERSION(__FILE__, "$Revision: 411314 $")
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 struct ast_event_sub *acl_change_event_subscription; /*!< subscription id for ACL change events */
00279 static int network_change_event_sched_id = -1;
00280 
00281 static int maxauthreq = 3;
00282 static int max_retries = 4;
00283 static int ping_time = 21;
00284 static int lagrq_time = 10;
00285 static int maxjitterbuffer=1000;
00286 static int resyncthreshold=1000;
00287 static int maxjitterinterps=10;
00288 static int jittertargetextra = 40; /* number of milliseconds the new jitter buffer adds on to its size */
00289 
00290 #define MAX_TRUNKDATA           640 * 200       /*!< 40ms, uncompressed linear * 200 channels */
00291 
00292 static int trunkfreq = 20;
00293 static int trunkmaxsize = MAX_TRUNKDATA;
00294 
00295 static int authdebug = 0;
00296 static int autokill = 0;
00297 static int iaxcompat = 0;
00298 static int last_authmethod = 0;
00299 
00300 static int iaxdefaultdpcache=10 * 60;  /* Cache dialplan entries for 10 minutes by default */
00301 
00302 static int iaxdefaulttimeout = 5;      /* Default to wait no more than 5 seconds for a reply to come back */
00303 
00304 static struct {
00305    unsigned int tos;
00306    unsigned int cos;
00307 } qos = { 0, 0 };
00308 
00309 static int min_reg_expire;
00310 static int max_reg_expire;
00311 
00312 static int srvlookup = 0;
00313 
00314 static struct ast_timer *timer;           /* Timer for trunking */
00315 
00316 static struct ast_netsock_list *netsock;
00317 static struct ast_netsock_list *outsock;     /*!< used if sourceaddress specified and bindaddr == INADDR_ANY */
00318 static int defaultsockfd = -1;
00319 
00320 static int (*iax2_regfunk)(const char *username, int onoff) = NULL;
00321 
00322 /* Ethernet, etc */
00323 #define IAX_CAPABILITY_FULLBANDWIDTH   0xFFFF
00324 /* T1, maybe ISDN */
00325 #define IAX_CAPABILITY_MEDBANDWIDTH (IAX_CAPABILITY_FULLBANDWIDTH & \
00326                      ~ast_format_id_to_old_bitfield(AST_FORMAT_SLINEAR) &      \
00327                      ~ast_format_id_to_old_bitfield(AST_FORMAT_SLINEAR16) &    \
00328                      ~ast_format_id_to_old_bitfield(AST_FORMAT_SIREN7) &       \
00329                      ~ast_format_id_to_old_bitfield(AST_FORMAT_SIREN14) &      \
00330                      ~ast_format_id_to_old_bitfield(AST_FORMAT_G719) &         \
00331                      ~ast_format_id_to_old_bitfield(AST_FORMAT_ULAW) &         \
00332                      ~ast_format_id_to_old_bitfield(AST_FORMAT_ALAW) &         \
00333                      ~ast_format_id_to_old_bitfield(AST_FORMAT_G722))
00334 /* A modem */
00335 #define IAX_CAPABILITY_LOWBANDWIDTH (IAX_CAPABILITY_MEDBANDWIDTH & \
00336                      ~ast_format_id_to_old_bitfield(AST_FORMAT_G726) &         \
00337                      ~ast_format_id_to_old_bitfield(AST_FORMAT_G726_AAL2) &    \
00338                      ~ast_format_id_to_old_bitfield(AST_FORMAT_ADPCM))
00339 
00340 #define IAX_CAPABILITY_LOWFREE      (IAX_CAPABILITY_LOWBANDWIDTH & \
00341                      ~ast_format_id_to_old_bitfield(AST_FORMAT_G723_1))
00342 
00343 
00344 #define DEFAULT_MAXMS      2000     /* Must be faster than 2 seconds by default */
00345 #define DEFAULT_FREQ_OK    60 * 1000   /* How often to check for the host to be up */
00346 #define DEFAULT_FREQ_NOTOK 10 * 1000   /* How often to check, if the host is down... */
00347 
00348 /* if a pvt has encryption setup done and is running on the call */
00349 #define IAX_CALLENCRYPTED(pvt) \
00350    (ast_test_flag64(pvt, IAX_ENCRYPTED) && ast_test_flag64(pvt, IAX_KEYPOPULATED))
00351 
00352 #define IAX_DEBUGDIGEST(msg, key) do { \
00353       int idx; \
00354       char digest[33] = ""; \
00355       \
00356       if (!iaxdebug) \
00357          break; \
00358       \
00359       for (idx = 0; idx < 16; idx++) \
00360          sprintf(digest + (idx << 1), "%2.2x", (unsigned char) key[idx]); \
00361       \
00362       ast_log(LOG_NOTICE, msg " IAX_COMMAND_RTKEY to rotate key to '%s'\n", digest); \
00363    } while(0)
00364 
00365 static struct io_context *io;
00366 static struct ast_sched_context *sched;
00367 
00368 #define DONT_RESCHEDULE -2
00369 
00370 static iax2_format iax2_capability = IAX_CAPABILITY_FULLBANDWIDTH;
00371 
00372 static int iaxdebug = 0;
00373 
00374 static int iaxtrunkdebug = 0;
00375 
00376 static int test_losspct = 0;
00377 #ifdef IAXTESTS
00378 static int test_late = 0;
00379 static int test_resync = 0;
00380 static int test_jit = 0;
00381 static int test_jitpct = 0;
00382 #endif /* IAXTESTS */
00383 
00384 static char accountcode[AST_MAX_ACCOUNT_CODE];
00385 static char mohinterpret[MAX_MUSICCLASS];
00386 static char mohsuggest[MAX_MUSICCLASS];
00387 static int amaflags = 0;
00388 static int adsi = 0;
00389 static int delayreject = 0;
00390 static int iax2_encryption = 0;
00391 
00392 static struct ast_flags64 globalflags = { 0 };
00393 
00394 static pthread_t netthreadid = AST_PTHREADT_NULL;
00395 
00396 enum iax2_state {
00397    IAX_STATE_STARTED =        (1 << 0),
00398    IAX_STATE_AUTHENTICATED =  (1 << 1),
00399    IAX_STATE_TBD =            (1 << 2),
00400 };
00401 
00402 struct iax2_context {
00403    char context[AST_MAX_CONTEXT];
00404    struct iax2_context *next;
00405 };
00406 
00407 
00408 #define  IAX_HASCALLERID         (uint64_t)(1 << 0)    /*!< CallerID has been specified */
00409 #define IAX_DELME               (uint64_t)(1 << 1)    /*!< Needs to be deleted */
00410 #define IAX_TEMPONLY            (uint64_t)(1 << 2)    /*!< Temporary (realtime) */
00411 #define IAX_TRUNK               (uint64_t)(1 << 3)    /*!< Treat as a trunk */
00412 #define IAX_NOTRANSFER          (uint64_t)(1 << 4)    /*!< Don't native bridge */
00413 #define IAX_USEJITTERBUF        (uint64_t)(1 << 5)    /*!< Use jitter buffer */
00414 #define IAX_DYNAMIC             (uint64_t)(1 << 6)    /*!< dynamic peer */
00415 #define IAX_SENDANI             (uint64_t)(1 << 7)    /*!< Send ANI along with CallerID */
00416 #define IAX_RTSAVE_SYSNAME      (uint64_t)(1 << 8)    /*!< Save Systname on Realtime Updates */
00417 #define IAX_ALREADYGONE         (uint64_t)(1 << 9)    /*!< Already disconnected */
00418 #define IAX_PROVISION           (uint64_t)(1 << 10)   /*!< This is a provisioning request */
00419 #define IAX_QUELCH              (uint64_t)(1 << 11)   /*!< Whether or not we quelch audio */
00420 #define IAX_ENCRYPTED           (uint64_t)(1 << 12)   /*!< Whether we should assume encrypted tx/rx */
00421 #define IAX_KEYPOPULATED        (uint64_t)(1 << 13)   /*!< Whether we have a key populated */
00422 #define IAX_CODEC_USER_FIRST    (uint64_t)(1 << 14)   /*!< are we willing to let the other guy choose the codec? */
00423 #define IAX_CODEC_NOPREFS       (uint64_t)(1 << 15)   /*!< Force old behaviour by turning off prefs */
00424 #define IAX_CODEC_NOCAP         (uint64_t)(1 << 16)   /*!< only consider requested format and ignore capabilities*/
00425 #define IAX_RTCACHEFRIENDS      (uint64_t)(1 << 17)   /*!< let realtime stay till your reload */
00426 #define IAX_RTUPDATE            (uint64_t)(1 << 18)   /*!< Send a realtime update */
00427 #define IAX_RTAUTOCLEAR         (uint64_t)(1 << 19)   /*!< erase me on expire */
00428 #define IAX_FORCEJITTERBUF      (uint64_t)(1 << 20)   /*!< Force jitterbuffer, even when bridged to a channel that can take jitter */
00429 #define IAX_RTIGNOREREGEXPIRE   (uint64_t)(1 << 21)   /*!< When using realtime, ignore registration expiration */
00430 #define IAX_TRUNKTIMESTAMPS     (uint64_t)(1 << 22)   /*!< Send trunk timestamps */
00431 #define IAX_TRANSFERMEDIA       (uint64_t)(1 << 23)   /*!< When doing IAX2 transfers, transfer media only */
00432 #define IAX_MAXAUTHREQ          (uint64_t)(1 << 24)   /*!< Maximum outstanding AUTHREQ restriction is in place */
00433 #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 */
00434 #define IAX_ALLOWFWDOWNLOAD     (uint64_t)(1 << 26)   /*!< Allow the FWDOWNL command? */
00435 #define IAX_IMMEDIATE           (uint64_t)(1 << 27)   /*!< Allow immediate off-hook to extension s */
00436 #define IAX_SENDCONNECTEDLINE   (uint64_t)(1 << 28)   /*!< Allow sending of connected line updates */
00437 #define IAX_RECVCONNECTEDLINE   (uint64_t)(1 << 29)   /*!< Allow receiving of connected line updates */
00438 #define IAX_FORCE_ENCRYPT       (uint64_t)(1 << 30)   /*!< Forces call encryption, if encryption not possible hangup */
00439 #define IAX_SHRINKCALLERID      (uint64_t)(1 << 31)   /*!< Turn on and off caller id shrinking */
00440 static int global_rtautoclear = 120;
00441 
00442 static int reload_config(int forced_reload);
00443 
00444 /*!
00445  * \brief Call token validation settings.
00446  */
00447 enum calltoken_peer_enum {
00448    /*! \brief Default calltoken required unless the ip is in the ignorelist */
00449    CALLTOKEN_DEFAULT = 0,
00450    /*! \brief Require call token validation. */
00451    CALLTOKEN_YES = 1,
00452    /*! \brief Require call token validation after a successful registration
00453     *         using call token validation occurs. */
00454    CALLTOKEN_AUTO = 2,
00455    /*! \brief Do not require call token validation. */
00456    CALLTOKEN_NO = 3,
00457 };
00458 
00459 struct iax2_user {
00460    AST_DECLARE_STRING_FIELDS(
00461       AST_STRING_FIELD(name);
00462       AST_STRING_FIELD(secret);
00463       AST_STRING_FIELD(dbsecret);
00464       AST_STRING_FIELD(accountcode);
00465       AST_STRING_FIELD(mohinterpret);
00466       AST_STRING_FIELD(mohsuggest);
00467       AST_STRING_FIELD(inkeys);               /*!< Key(s) this user can use to authenticate to us */
00468       AST_STRING_FIELD(language);
00469       AST_STRING_FIELD(cid_num);
00470       AST_STRING_FIELD(cid_name);
00471       AST_STRING_FIELD(parkinglot);           /*!< Default parkinglot for device */
00472    );
00473 
00474    int authmethods;
00475    int encmethods;
00476    int amaflags;
00477    int adsi;
00478    uint64_t flags;
00479    iax2_format capability;
00480    int maxauthreq; /*!< Maximum allowed outstanding AUTHREQs */
00481    int curauthreq; /*!< Current number of outstanding AUTHREQs */
00482    struct ast_codec_pref prefs;
00483    struct ast_acl_list *acl;
00484    struct iax2_context *contexts;
00485    struct ast_variable *vars;
00486    enum calltoken_peer_enum calltoken_required;        /*!< Is calltoken validation required or not, can be YES, NO, or AUTO */
00487 };
00488 
00489 struct iax2_peer {
00490    AST_DECLARE_STRING_FIELDS(
00491       AST_STRING_FIELD(name);
00492       AST_STRING_FIELD(username);
00493       AST_STRING_FIELD(description);      /*!< Description of the peer */
00494       AST_STRING_FIELD(secret);
00495       AST_STRING_FIELD(dbsecret);
00496       AST_STRING_FIELD(outkey);      /*!< What key we use to talk to this peer */
00497 
00498       AST_STRING_FIELD(regexten);     /*!< Extension to register (if regcontext is used) */
00499       AST_STRING_FIELD(context);      /*!< For transfers only */
00500       AST_STRING_FIELD(peercontext);  /*!< Context to pass to peer */
00501       AST_STRING_FIELD(mailbox);     /*!< Mailbox */
00502       AST_STRING_FIELD(mohinterpret);
00503       AST_STRING_FIELD(mohsuggest);
00504       AST_STRING_FIELD(inkeys);     /*!< Key(s) this peer can use to authenticate to us */
00505       /* Suggested caller id if registering */
00506       AST_STRING_FIELD(cid_num);    /*!< Default context (for transfer really) */
00507       AST_STRING_FIELD(cid_name);      /*!< Default context (for transfer really) */
00508       AST_STRING_FIELD(zonetag);    /*!< Time Zone */
00509       AST_STRING_FIELD(parkinglot);   /*!< Default parkinglot for device */
00510    );
00511    struct ast_codec_pref prefs;
00512    struct ast_dnsmgr_entry *dnsmgr;    /*!< DNS refresh manager */
00513    struct ast_sockaddr addr;
00514    int formats;
00515    int sockfd;             /*!< Socket to use for transmission */
00516    struct in_addr mask;
00517    int adsi;
00518    uint64_t flags;
00519 
00520    /* Dynamic Registration fields */
00521    struct sockaddr_in defaddr;         /*!< Default address if there is one */
00522    int authmethods;           /*!< Authentication methods (IAX_AUTH_*) */
00523    int encmethods;               /*!< Encryption methods (IAX_ENCRYPT_*) */
00524 
00525    int expire;             /*!< Schedule entry for expiry */
00526    int expiry;             /*!< How soon to expire */
00527    iax2_format capability;        /*!< Capability */
00528 
00529    /* Qualification */
00530    int callno;             /*!< Call number of POKE request */
00531    int pokeexpire;               /*!< Scheduled qualification-related task (ie iax2_poke_peer_s or iax2_poke_noanswer) */
00532    int lastms;             /*!< How long last response took (in ms), or -1 for no response */
00533    int maxms;              /*!< Max ms we will accept for the host to be up, 0 to not monitor */
00534 
00535    int pokefreqok;               /*!< How often to check if the host is up */
00536    int pokefreqnotok;            /*!< How often to check when the host has been determined to be down */
00537    int historicms;               /*!< How long recent average responses took */
00538    int smoothing;             /*!< Sample over how many units to determine historic ms */
00539    uint16_t maxcallno;              /*!< Max call number limit for this peer.  Set on registration */
00540 
00541    struct ast_event_sub *mwi_event_sub;
00542 
00543    struct ast_acl_list *acl;
00544    enum calltoken_peer_enum calltoken_required;        /*!< Is calltoken validation required or not, can be YES, NO, or AUTO */
00545 };
00546 
00547 #define IAX2_TRUNK_PREFACE (sizeof(struct iax_frame) + sizeof(struct ast_iax2_meta_hdr) + sizeof(struct ast_iax2_meta_trunk_hdr))
00548 
00549 struct iax2_trunk_peer {
00550    ast_mutex_t lock;
00551    int sockfd;
00552    struct sockaddr_in addr;
00553    struct timeval txtrunktime;      /*!< Transmit trunktime */
00554    struct timeval rxtrunktime;      /*!< Receive trunktime */
00555    struct timeval lasttxtime;    /*!< Last transmitted trunktime */
00556    struct timeval trunkact;      /*!< Last trunk activity */
00557    unsigned int lastsent;        /*!< Last sent time */
00558    /* Trunk data and length */
00559    unsigned char *trunkdata;
00560    unsigned int trunkdatalen;
00561    unsigned int trunkdataalloc;
00562    int trunkmaxmtu;
00563    int trunkerror;
00564    int calls;
00565    AST_LIST_ENTRY(iax2_trunk_peer) list;
00566 };
00567 
00568 static AST_LIST_HEAD_STATIC(tpeers, iax2_trunk_peer);
00569 
00570 struct iax_firmware {
00571    AST_LIST_ENTRY(iax_firmware) list;
00572    int fd;
00573    int mmaplen;
00574    int dead;
00575    struct ast_iax2_firmware_header *fwh;
00576    unsigned char *buf;
00577 };
00578 
00579 enum iax_reg_state {
00580    REG_STATE_UNREGISTERED = 0,
00581    REG_STATE_REGSENT,
00582    REG_STATE_AUTHSENT,
00583    REG_STATE_REGISTERED,
00584    REG_STATE_REJECTED,
00585    REG_STATE_TIMEOUT,
00586    REG_STATE_NOAUTH
00587 };
00588 
00589 enum iax_transfer_state {
00590    TRANSFER_NONE = 0,
00591    TRANSFER_BEGIN,
00592    TRANSFER_READY,
00593    TRANSFER_RELEASED,
00594    TRANSFER_PASSTHROUGH,
00595    TRANSFER_MBEGIN,
00596    TRANSFER_MREADY,
00597    TRANSFER_MRELEASED,
00598    TRANSFER_MPASSTHROUGH,
00599    TRANSFER_MEDIA,
00600    TRANSFER_MEDIAPASS
00601 };
00602 
00603 struct iax2_registry {
00604    struct ast_sockaddr addr;     /*!< Who we connect to for registration purposes */
00605    char username[80];
00606    char secret[80];        /*!< Password or key name in []'s */
00607    int expire;          /*!< Sched ID of expiration */
00608    int refresh;            /*!< How often to refresh */
00609    enum iax_reg_state regstate;
00610    int messages;           /*!< Message count, low 8 bits = new, high 8 bits = old */
00611    int callno;          /*!< Associated call number if applicable */
00612    struct sockaddr_in us;        /*!< Who the server thinks we are */
00613    struct ast_dnsmgr_entry *dnsmgr; /*!< DNS refresh manager */
00614    AST_LIST_ENTRY(iax2_registry) entry;
00615 };
00616 
00617 static AST_LIST_HEAD_STATIC(registrations, iax2_registry);
00618 
00619 /* Don't retry more frequently than every 10 ms, or less frequently than every 5 seconds */
00620 #define MIN_RETRY_TIME     100
00621 #define MAX_RETRY_TIME     10000
00622 
00623 #define MAX_JITTER_BUFFER  50
00624 #define MIN_JITTER_BUFFER  10
00625 
00626 #define DEFAULT_TRUNKDATA  640 * 10 /*!< 40ms, uncompressed linear * 10 channels */
00627 
00628 #define MAX_TIMESTAMP_SKEW 160      /*!< maximum difference between actual and predicted ts for sending */
00629 
00630 /* If consecutive voice frame timestamps jump by more than this many milliseconds, then jitter buffer will resync */
00631 #define TS_GAP_FOR_JB_RESYNC  5000
00632 
00633 /* used for first_iax_message and last_iax_message.  If this bit is set it was TX, else RX */
00634 #define MARK_IAX_SUBCLASS_TX  0x8000
00635 
00636 static int iaxthreadcount = DEFAULT_THREAD_COUNT;
00637 static int iaxmaxthreadcount = DEFAULT_MAX_THREAD_COUNT;
00638 static int iaxdynamicthreadcount = 0;
00639 static int iaxdynamicthreadnum = 0;
00640 static int iaxactivethreadcount = 0;
00641 
00642 struct iax_rr {
00643    int jitter;
00644    int losspct;
00645    int losscnt;
00646    int packets;
00647    int delay;
00648    int dropped;
00649    int ooo;
00650 };
00651 
00652 struct iax2_pvt_ref;
00653 
00654 struct chan_iax2_pvt {
00655    /*! Socket to send/receive on for this call */
00656    int sockfd;
00657    /*! ast_callid bound to dialog */
00658    struct ast_callid *callid;
00659    /*! Last received voice format */
00660    iax2_format voiceformat;
00661    /*! Last received video format */
00662    iax2_format videoformat;
00663    /*! Last sent voice format */
00664    iax2_format svoiceformat;
00665    /*! Last sent video format */
00666    iax2_format svideoformat;
00667    /*! What we are capable of sending */
00668    iax2_format capability;
00669    /*! Last received timestamp */
00670    unsigned int last;
00671    /*! Last sent timestamp - never send the same timestamp twice in a single call */
00672    unsigned int lastsent;
00673    /*! Timestamp of the last video frame sent */
00674    unsigned int lastvsent;
00675    /*! Next outgoing timestamp if everything is good */
00676    unsigned int nextpred;
00677    /*! iax frame subclass that began iax2_pvt entry. 0x8000 bit is set on TX */
00678    int first_iax_message;
00679    /*! Last iax frame subclass sent or received for a iax2_pvt. 0x8000 bit is set on TX */
00680    int last_iax_message;
00681    /*! True if the last voice we transmitted was not silence/CNG */
00682    unsigned int notsilenttx:1;
00683    /*! Ping time */
00684    unsigned int pingtime;
00685    /*! Max time for initial response */
00686    int maxtime;
00687    /*! Peer Address */
00688    struct sockaddr_in addr;
00689    /*! Actual used codec preferences */
00690    struct ast_codec_pref prefs;
00691    /*! Requested codec preferences */
00692    struct ast_codec_pref rprefs;
00693    /*! Our call number */
00694    unsigned short callno;
00695    /*! Our callno_entry entry */
00696    struct callno_entry *callno_entry;
00697    /*! Peer callno */
00698    unsigned short peercallno;
00699    /*! Negotiated format, this is only used to remember what format was
00700        chosen for an unauthenticated call so that the channel can get
00701        created later using the right format */
00702    iax2_format chosenformat;
00703    /*! Peer selected format */
00704    iax2_format peerformat;
00705    /*! Peer capability */
00706    iax2_format peercapability;
00707    /*! timeval that we base our transmission on */
00708    struct timeval offset;
00709    /*! timeval that we base our delivery on */
00710    struct timeval rxcore;
00711    /*! The jitterbuffer */
00712    jitterbuf *jb;
00713    /*! active jb read scheduler id */
00714    int jbid;
00715    /*! LAG */
00716    int lag;
00717    /*! Error, as discovered by the manager */
00718    int error;
00719    /*! Owner if we have one */
00720    struct ast_channel *owner;
00721    /*! What's our state? */
00722    struct ast_flags state;
00723    /*! Expiry (optional) */
00724    int expiry;
00725    /*! Next outgoing sequence number */
00726    unsigned char oseqno;
00727    /*! Next sequence number they have not yet acknowledged */
00728    unsigned char rseqno;
00729    /*! Next incoming sequence number */
00730    unsigned char iseqno;
00731    /*! Last incoming sequence number we have acknowledged */
00732    unsigned char aseqno;
00733 
00734    AST_DECLARE_STRING_FIELDS(
00735       /*! Peer name */
00736       AST_STRING_FIELD(peer);
00737       /*! Default Context */
00738       AST_STRING_FIELD(context);
00739       /*! Caller ID if available */
00740       AST_STRING_FIELD(cid_num);
00741       AST_STRING_FIELD(cid_name);
00742       /*! Hidden Caller ID (i.e. ANI) if appropriate */
00743       AST_STRING_FIELD(ani);
00744       /*! DNID */
00745       AST_STRING_FIELD(dnid);
00746       /*! RDNIS */
00747       AST_STRING_FIELD(rdnis);
00748       /*! Requested Extension */
00749       AST_STRING_FIELD(exten);
00750       /*! Expected Username */
00751       AST_STRING_FIELD(username);
00752       /*! Expected Secret */
00753       AST_STRING_FIELD(secret);
00754       /*! MD5 challenge */
00755       AST_STRING_FIELD(challenge);
00756       /*! Public keys permitted keys for incoming authentication */
00757       AST_STRING_FIELD(inkeys);
00758       /*! Private key for outgoing authentication */
00759       AST_STRING_FIELD(outkey);
00760       /*! Preferred language */
00761       AST_STRING_FIELD(language);
00762       /*! Hostname/peername for naming purposes */
00763       AST_STRING_FIELD(host);
00764 
00765       AST_STRING_FIELD(dproot);
00766       AST_STRING_FIELD(accountcode);
00767       AST_STRING_FIELD(mohinterpret);
00768       AST_STRING_FIELD(mohsuggest);
00769       /*! received OSP token */
00770       AST_STRING_FIELD(osptoken);
00771       /*! Default parkinglot */
00772       AST_STRING_FIELD(parkinglot);
00773    );
00774    /*! AUTHREJ all AUTHREP frames */
00775    int authrej;
00776    /*! permitted authentication methods */
00777    int authmethods;
00778    /*! permitted encryption methods */
00779    int encmethods;
00780    /*! Encryption AES-128 Key */
00781    ast_aes_encrypt_key ecx;
00782    /*! Decryption AES-128 Key corresponding to ecx */
00783    ast_aes_decrypt_key mydcx;
00784    /*! Decryption AES-128 Key used to decrypt peer frames */
00785    ast_aes_decrypt_key dcx;
00786    /*! scheduler id associated with iax_key_rotate 
00787     * for encrypted calls*/
00788    int keyrotateid;
00789    /*! 32 bytes of semi-random data */
00790    unsigned char semirand[32];
00791    /*! Associated registry */
00792    struct iax2_registry *reg;
00793    /*! Associated peer for poking */
00794    struct iax2_peer *peerpoke;
00795    /*! IAX_ flags */
00796    uint64_t flags;
00797    int adsi;
00798 
00799    /*! Transferring status */
00800    enum iax_transfer_state transferring;
00801    /*! Transfer identifier */
00802    int transferid;
00803    /*! Who we are IAX transferring to */
00804    struct sockaddr_in transfer;
00805    /*! What's the new call number for the transfer */
00806    unsigned short transfercallno;
00807    /*! Transfer encrypt AES-128 Key */
00808    ast_aes_encrypt_key tdcx;
00809 
00810    /*! Status of knowledge of peer ADSI capability */
00811    int peeradsicpe;
00812 
00813    /*! Callno of native bridge peer. (Valid if nonzero) */
00814    unsigned short bridgecallno;
00815 
00816    int pingid;       /*!< Transmit PING request */
00817    int lagid;        /*!< Retransmit lag request */
00818    int autoid;       /*!< Auto hangup for Dialplan requestor */
00819    int authid;       /*!< Authentication rejection ID */
00820    int authfail;        /*!< Reason to report failure */
00821    int initid;       /*!< Initial peer auto-congest ID (based on qualified peers) */
00822    int calling_ton;
00823    int calling_tns;
00824    int calling_pres;
00825    int amaflags;
00826    AST_LIST_HEAD_NOLOCK(, iax2_dpcache) dpentries;
00827    /*! variables inherited from the user definition */
00828    struct ast_variable *vars;
00829    /*! variables transmitted in a NEW packet */
00830    struct ast_variable *iaxvars;
00831    /*! last received remote rr */
00832    struct iax_rr remote_rr;
00833    /*! Current base time: (just for stats) */
00834    int min;
00835    /*! Dropped frame count: (just for stats) */
00836    int frames_dropped;
00837    /*! received frame count: (just for stats) */
00838    int frames_received;
00839    /*! num bytes used for calltoken ie, even an empty ie should contain 2 */
00840    unsigned char calltoken_ie_len;
00841    /*! hold all signaling frames from the pbx thread until we have a destination callno */
00842    char hold_signaling;
00843    /*! frame queue for signaling frames from pbx thread waiting for destination callno */
00844    AST_LIST_HEAD_NOLOCK(signaling_queue, signaling_queue_entry) signaling_queue;
00845 };
00846 
00847 struct signaling_queue_entry {
00848    struct ast_frame f;
00849    AST_LIST_ENTRY(signaling_queue_entry) next;
00850 };
00851 
00852 /*! table of available call numbers */
00853 static struct ao2_container *callno_pool;
00854 
00855 /*! table of available trunk call numbers */
00856 static struct ao2_container *callno_pool_trunk;
00857 
00858 static const unsigned int CALLNO_POOL_BUCKETS = 2699;
00859 
00860 /*!
00861  * \brief a list of frames that may need to be retransmitted
00862  *
00863  * \note The contents of this list do not need to be explicitly destroyed
00864  * on module unload.  This is because all active calls are destroyed, and
00865  * all frames in this queue will get destroyed as a part of that process.
00866  *
00867  * \note Contents protected by the iaxsl[] locks
00868  */
00869 static AST_LIST_HEAD_NOLOCK(, iax_frame) frame_queue[IAX_MAX_CALLS];
00870 
00871 static struct ast_taskprocessor *transmit_processor;
00872 
00873 static int randomcalltokendata;
00874 
00875 static const time_t MAX_CALLTOKEN_DELAY = 10;
00876 
00877 /*!
00878  * This module will get much higher performance when doing a lot of
00879  * user and peer lookups if the number of buckets is increased from 1.
00880  * However, to maintain old behavior for Asterisk 1.4, these are set to
00881  * 1 by default.  When using multiple buckets, search order through these
00882  * containers is considered random, so you will not be able to depend on
00883  * the order the entires are specified in iax.conf for matching order. */
00884 #ifdef LOW_MEMORY
00885 #define MAX_PEER_BUCKETS 17
00886 #else
00887 #define MAX_PEER_BUCKETS 563
00888 #endif
00889 static struct ao2_container *peers;
00890 
00891 #define MAX_USER_BUCKETS MAX_PEER_BUCKETS
00892 static struct ao2_container *users;
00893 
00894 /*! Table containing peercnt objects for every ip address consuming a callno */
00895 static struct ao2_container *peercnts;
00896 
00897 /*! Table containing custom callno limit rules for a range of ip addresses. */
00898 static struct ao2_container *callno_limits;
00899 
00900 /*! Table containing ip addresses not requiring calltoken validation */
00901 static struct ao2_container *calltoken_ignores;
00902 
00903 static uint16_t DEFAULT_MAXCALLNO_LIMIT = 2048;
00904 
00905 static uint16_t DEFAULT_MAXCALLNO_LIMIT_NONVAL = 8192;
00906 
00907 static uint16_t global_maxcallno;
00908 
00909 /*! Total num of call numbers allowed to be allocated without calltoken validation */
00910 static uint16_t global_maxcallno_nonval;
00911 
00912 static uint16_t total_nonval_callno_used = 0;
00913 
00914 /*! peer connection private, keeps track of all the call numbers
00915  *  consumed by a single ip address */
00916 struct peercnt {
00917    /*! ip address consuming call numbers */
00918    unsigned long addr;
00919    /*! Number of call numbers currently used by this ip address */
00920    uint16_t cur;
00921    /*! Max call numbers allowed for this ip address */
00922    uint16_t limit;
00923    /*! Specifies whether limit is set by a registration or not, if so normal
00924     *  limit setting rules do not apply to this address. */
00925    unsigned char reg;
00926 };
00927 
00928 /*! used by both callno_limits and calltoken_ignores containers */
00929 struct addr_range {
00930    /*! ip address range for custom callno limit rule */
00931    struct ast_ha ha;
00932    /*! callno limit for this ip address range, only used in callno_limits container */
00933    uint16_t limit;
00934    /*! delete me marker for reloads */
00935    unsigned char delme;
00936 };
00937 
00938 struct callno_entry {
00939    /*! callno used for this entry */
00940    uint16_t callno;
00941    /*! was this callno calltoken validated or not */
00942    unsigned char validated;
00943 };
00944 
00945 static AST_LIST_HEAD_STATIC(firmwares, iax_firmware);
00946 
00947 enum {
00948    /*! Extension exists */
00949    CACHE_FLAG_EXISTS      = (1 << 0),
00950    /*! Extension is nonexistent */
00951    CACHE_FLAG_NONEXISTENT = (1 << 1),
00952    /*! Extension can exist */
00953    CACHE_FLAG_CANEXIST    = (1 << 2),
00954    /*! Waiting to hear back response */
00955    CACHE_FLAG_PENDING     = (1 << 3),
00956    /*! Timed out */
00957    CACHE_FLAG_TIMEOUT     = (1 << 4),
00958    /*! Request transmitted */
00959    CACHE_FLAG_TRANSMITTED = (1 << 5),
00960    /*! Timeout */
00961    CACHE_FLAG_UNKNOWN     = (1 << 6),
00962    /*! Matchmore */
00963    CACHE_FLAG_MATCHMORE   = (1 << 7),
00964 };
00965 
00966 struct iax2_dpcache {
00967    char peercontext[AST_MAX_CONTEXT];
00968    char exten[AST_MAX_EXTENSION];
00969    struct timeval orig;
00970    struct timeval expiry;
00971    int flags;
00972    unsigned short callno;
00973    int waiters[256];
00974    AST_LIST_ENTRY(iax2_dpcache) cache_list;
00975    AST_LIST_ENTRY(iax2_dpcache) peer_list;
00976 };
00977 
00978 static AST_LIST_HEAD_STATIC(dpcache, iax2_dpcache);
00979 
00980 static void reg_source_db(struct iax2_peer *p);
00981 static struct iax2_peer *realtime_peer(const char *peername, struct sockaddr_in *sin);
00982 static struct iax2_user *realtime_user(const char *username, struct sockaddr_in *sin);
00983 
00984 static int ast_cli_netstats(struct mansession *s, int fd, int limit_fmt);
00985 static char *complete_iax2_peers(const char *line, const char *word, int pos, int state, uint64_t flags);
00986 static char *complete_iax2_unregister(const char *line, const char *word, int pos, int state);
00987 
00988 enum iax2_thread_iostate {
00989    IAX_IOSTATE_IDLE,
00990    IAX_IOSTATE_READY,
00991    IAX_IOSTATE_PROCESSING,
00992    IAX_IOSTATE_SCHEDREADY,
00993 };
00994 
00995 enum iax2_thread_type {
00996    IAX_THREAD_TYPE_POOL,
00997    IAX_THREAD_TYPE_DYNAMIC,
00998 };
00999 
01000 struct iax2_pkt_buf {
01001    AST_LIST_ENTRY(iax2_pkt_buf) entry;
01002    size_t len;
01003    unsigned char buf[1];
01004 };
01005 
01006 struct iax2_thread {
01007    AST_LIST_ENTRY(iax2_thread) list;
01008    enum iax2_thread_type type;
01009    enum iax2_thread_iostate iostate;
01010 #ifdef SCHED_MULTITHREADED
01011    void (*schedfunc)(const void *);
01012    const void *scheddata;
01013 #endif
01014 #ifdef DEBUG_SCHED_MULTITHREAD
01015    char curfunc[80];
01016 #endif   
01017    int actions;
01018    pthread_t threadid;
01019    int threadnum;
01020    struct sockaddr_in iosin;
01021    unsigned char readbuf[4096]; 
01022    unsigned char *buf;
01023    ssize_t buf_len;
01024    size_t buf_size;
01025    int iofd;
01026    time_t checktime;
01027    ast_mutex_t lock;
01028    ast_cond_t cond;
01029    ast_mutex_t init_lock;
01030    ast_cond_t init_cond;
01031    /*! if this thread is processing a full frame,
01032      some information about that frame will be stored
01033      here, so we can avoid dispatching any more full
01034      frames for that callno to other threads */
01035    struct {
01036       unsigned short callno;
01037       struct sockaddr_in sin;
01038       unsigned char type;
01039       unsigned char csub;
01040    } ffinfo;
01041    /*! Queued up full frames for processing.  If more full frames arrive for
01042     *  a call which this thread is already processing a full frame for, they
01043     *  are queued up here. */
01044    AST_LIST_HEAD_NOLOCK(, iax2_pkt_buf) full_frames;
01045    unsigned char stop;
01046 };
01047 
01048 /* Thread lists */
01049 static AST_LIST_HEAD_STATIC(idle_list, iax2_thread);
01050 static AST_LIST_HEAD_STATIC(active_list, iax2_thread);
01051 static AST_LIST_HEAD_STATIC(dynamic_list, iax2_thread);
01052 
01053 static void *iax2_process_thread(void *data);
01054 static void iax2_destroy(int callno);
01055 
01056 static void signal_condition(ast_mutex_t *lock, ast_cond_t *cond)
01057 {
01058    ast_mutex_lock(lock);
01059    ast_cond_signal(cond);
01060    ast_mutex_unlock(lock);
01061 }
01062 
01063 /*!
01064  * \brief an array of iax2 pvt structures
01065  *
01066  * The container for active chan_iax2_pvt structures is implemented as an
01067  * array for extremely quick direct access to the correct pvt structure
01068  * based on the local call number.  The local call number is used as the
01069  * index into the array where the associated pvt structure is stored.
01070  */
01071 static struct chan_iax2_pvt *iaxs[IAX_MAX_CALLS];
01072 
01073 static struct ast_callid *iax_pvt_callid_get(int callno)
01074 {
01075    if (iaxs[callno]->callid) {
01076       return ast_callid_ref(iaxs[callno]->callid);
01077    }
01078    return NULL;
01079 }
01080 
01081 static void iax_pvt_callid_set(int callno, struct ast_callid *callid)
01082 {
01083    if (iaxs[callno]->callid) {
01084       ast_callid_unref(iaxs[callno]->callid);
01085    }
01086    ast_callid_ref(callid);
01087    iaxs[callno]->callid = callid;
01088 }
01089 
01090 static void iax_pvt_callid_new(int callno)
01091 {
01092    struct ast_callid *callid = ast_create_callid();
01093    char buffer[AST_CALLID_BUFFER_LENGTH];
01094    ast_callid_strnprint(buffer, sizeof(buffer), callid);
01095    iax_pvt_callid_set(callno, callid);
01096    ast_callid_unref(callid);
01097 }
01098 
01099 /*!
01100  * \brief Another container of iax2_pvt structures
01101  *
01102  * Active IAX2 pvt structs are also stored in this container, if they are a part
01103  * of an active call where we know the remote side's call number.  The reason
01104  * for this is that incoming media frames do not contain our call number.  So,
01105  * instead of having to iterate the entire iaxs array, we use this container to
01106  * look up calls where the remote side is using a given call number.
01107  */
01108 static struct ao2_container *iax_peercallno_pvts;
01109 
01110 /*!
01111  * \brief chan_iax2_pvt structure locks
01112  *
01113  * These locks are used when accessing a pvt structure in the iaxs array.
01114  * The index used here is the same as used in the iaxs array.  It is the
01115  * local call number for the associated pvt struct.
01116  */
01117 static ast_mutex_t iaxsl[ARRAY_LEN(iaxs)];
01118 
01119 /*!
01120  *  * \brief Another container of iax2_pvt structures
01121  *  
01122  *  Active IAX2 pvt stucts used during transfering a call are stored here.  
01123  */
01124 static struct ao2_container *iax_transfercallno_pvts;
01125 
01126 /* Flag to use with trunk calls, keeping these calls high up.  It halves our effective use
01127    but keeps the division between trunked and non-trunked better. */
01128 #define TRUNK_CALL_START   (IAX_MAX_CALLS / 2)
01129 
01130 /* Debug routines... */
01131 static struct sockaddr_in debugaddr;
01132 
01133 static void iax_outputframe(struct iax_frame *f, struct ast_iax2_full_hdr *fhi, int rx, struct sockaddr_in *sin, int datalen)
01134 {
01135    if (iaxdebug ||
01136        (sin && debugaddr.sin_addr.s_addr && 
01137         (!ntohs(debugaddr.sin_port) ||
01138          debugaddr.sin_port == sin->sin_port) &&
01139         debugaddr.sin_addr.s_addr == sin->sin_addr.s_addr)) {
01140       if (iaxdebug) {
01141          iax_showframe(f, fhi, rx, sin, datalen);
01142       } else {
01143          iaxdebug = 1;
01144          iax_showframe(f, fhi, rx, sin, datalen);
01145          iaxdebug = 0;
01146       }
01147    }
01148 }
01149 
01150 static void iax_debug_output(const char *data)
01151 {
01152    if (iaxdebug)
01153       ast_verbose("%s", data);
01154 }
01155 
01156 static void iax_error_output(const char *data)
01157 {
01158    ast_log(LOG_WARNING, "%s", data);
01159 }
01160 
01161 static void __attribute__((format(printf, 1, 2))) jb_error_output(const char *fmt, ...)
01162 {
01163    va_list args;
01164    char buf[1024];
01165 
01166    va_start(args, fmt);
01167    vsnprintf(buf, sizeof(buf), fmt, args);
01168    va_end(args);
01169 
01170    ast_log(LOG_ERROR, "%s", buf);
01171 }
01172 
01173 static void __attribute__((format(printf, 1, 2))) jb_warning_output(const char *fmt, ...)
01174 {
01175    va_list args;
01176    char buf[1024];
01177 
01178    va_start(args, fmt);
01179    vsnprintf(buf, sizeof(buf), fmt, args);
01180    va_end(args);
01181 
01182    ast_log(LOG_WARNING, "%s", buf);
01183 }
01184 
01185 static void __attribute__((format(printf, 1, 2))) jb_debug_output(const char *fmt, ...)
01186 {
01187    va_list args;
01188    char buf[1024];
01189 
01190    va_start(args, fmt);
01191    vsnprintf(buf, sizeof(buf), fmt, args);
01192    va_end(args);
01193 
01194    ast_verbose("%s", buf);
01195 }
01196 
01197 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);
01198 static int expire_registry(const void *data);
01199 static int iax2_answer(struct ast_channel *c);
01200 static int iax2_call(struct ast_channel *c, const char *dest, int timeout);
01201 static int iax2_devicestate(const char *data);
01202 static int iax2_digit_begin(struct ast_channel *c, char digit);
01203 static int iax2_digit_end(struct ast_channel *c, char digit, unsigned int duration);
01204 static int iax2_do_register(struct iax2_registry *reg);
01205 static int iax2_fixup(struct ast_channel *oldchannel, struct ast_channel *newchan);
01206 static int iax2_hangup(struct ast_channel *c);
01207 static int iax2_indicate(struct ast_channel *c, int condition, const void *data, size_t datalen);
01208 static int iax2_poke_peer(struct iax2_peer *peer, int heldcall);
01209 static int iax2_provision(struct sockaddr_in *end, int sockfd, const char *dest, const char *template, int force);
01210 static int iax2_send(struct chan_iax2_pvt *pvt, struct ast_frame *f, unsigned int ts, int seqno, int now, int transfer, int final);
01211 static int iax2_sendhtml(struct ast_channel *c, int subclass, const char *data, int datalen);
01212 static int iax2_sendimage(struct ast_channel *c, struct ast_frame *img);
01213 static int iax2_sendtext(struct ast_channel *c, const char *text);
01214 static int iax2_setoption(struct ast_channel *c, int option, void *data, int datalen);
01215 static int iax2_queryoption(struct ast_channel *c, int option, void *data, int *datalen);
01216 static int iax2_transfer(struct ast_channel *c, const char *dest);
01217 static int iax2_write(struct ast_channel *c, struct ast_frame *f);
01218 static int iax2_sched_add(struct ast_sched_context *sched, int when, ast_sched_cb callback, const void *data);
01219 
01220 static int send_trunk(struct iax2_trunk_peer *tpeer, struct timeval *now);
01221 static int send_command(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
01222 static int send_command_final(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
01223 static int send_command_immediate(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
01224 static int send_command_locked(unsigned short callno, char, int, unsigned int, const unsigned char *, int, int);
01225 static int send_command_transfer(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int);
01226 static struct ast_channel *iax2_request(const char *type, struct ast_format_cap *cap, const struct ast_channel *requestor, const char *data, int *cause);
01227 static struct ast_frame *iax2_read(struct ast_channel *c);
01228 static struct iax2_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly);
01229 static struct iax2_user *build_user(const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly);
01230 static void realtime_update_peer(const char *peername, struct ast_sockaddr *sockaddr, time_t regtime);
01231 static void *iax2_dup_variable_datastore(void *);
01232 static void prune_peers(void);
01233 static void prune_users(void);
01234 static void iax2_free_variable_datastore(void *);
01235 
01236 static int acf_channel_read(struct ast_channel *chan, const char *funcname, char *preparse, char *buf, size_t buflen);
01237 static int decode_frame(ast_aes_decrypt_key *dcx, struct ast_iax2_full_hdr *fh, struct ast_frame *f, int *datalen);
01238 static int encrypt_frame(ast_aes_encrypt_key *ecx, struct ast_iax2_full_hdr *fh, unsigned char *poo, int *datalen);
01239 static void build_ecx_key(const unsigned char *digest, struct chan_iax2_pvt *pvt);
01240 static void build_rand_pad(unsigned char *buf, ssize_t len);
01241 static struct callno_entry *get_unused_callno(int trunk, int validated);
01242 static int replace_callno(const void *obj);
01243 static void sched_delay_remove(struct sockaddr_in *sin, struct callno_entry *callno_entry);
01244 static void network_change_event_cb(const struct ast_event *, void *);
01245 static void acl_change_event_cb(const struct ast_event *, void *);
01246 
01247 static struct ast_channel_tech iax2_tech = {
01248    .type = "IAX2",
01249    .description = tdesc,
01250    .properties = AST_CHAN_TP_WANTSJITTER,
01251    .requester = iax2_request,
01252    .devicestate = iax2_devicestate,
01253    .send_digit_begin = iax2_digit_begin,
01254    .send_digit_end = iax2_digit_end,
01255    .send_text = iax2_sendtext,
01256    .send_image = iax2_sendimage,
01257    .send_html = iax2_sendhtml,
01258    .call = iax2_call,
01259    .hangup = iax2_hangup,
01260    .answer = iax2_answer,
01261    .read = iax2_read,
01262    .write = iax2_write,
01263    .write_video = iax2_write,
01264    .indicate = iax2_indicate,
01265    .setoption = iax2_setoption,
01266    .queryoption = iax2_queryoption,
01267    .bridge = iax2_bridge,
01268    .transfer = iax2_transfer,
01269    .fixup = iax2_fixup,
01270    .func_channel_read = acf_channel_read,
01271 };
01272 
01273 /*!
01274  * \internal
01275  * \brief Obtain the owner channel lock if the owner exists.
01276  *
01277  * \param callno IAX2 call id.
01278  *
01279  * \note Assumes the iaxsl[callno] lock is already obtained.
01280  *
01281  * \note
01282  * IMPORTANT NOTE!!!  Any time this function is used, even if
01283  * iaxs[callno] was valid before calling it, it may no longer be
01284  * valid after calling it.  This function may unlock and lock
01285  * the mutex associated with this callno, meaning that another
01286  * thread may grab it and destroy the call.
01287  *
01288  * \return Nothing
01289  */
01290 static void iax2_lock_owner(int callno)
01291 {
01292    for (;;) {
01293       if (!iaxs[callno] || !iaxs[callno]->owner) {
01294          /* There is no owner lock to get. */
01295          break;
01296       }
01297       if (!ast_channel_trylock(iaxs[callno]->owner)) {
01298          /* We got the lock */
01299          break;
01300       }
01301       /* Avoid deadlock by pausing and trying again */
01302       DEADLOCK_AVOIDANCE(&iaxsl[callno]);
01303    }
01304 }
01305 
01306 /*!
01307  * \internal
01308  * \brief Check if a control subtype is allowed on the wire.
01309  *
01310  * \param subtype Control frame subtype to check if allowed to/from the wire.
01311  *
01312  * \retval non-zero if allowed.
01313  */
01314 static int iax2_is_control_frame_allowed(int subtype)
01315 {
01316    enum ast_control_frame_type control = subtype;
01317    int is_allowed;
01318 
01319    /*
01320     * Note: If we compare the enumeration type, which does not have any
01321     * negative constants, the compiler may optimize this code away.
01322     * Therefore, we must perform an integer comparison here.
01323     */
01324    if (subtype == -1) {
01325       return -1;
01326    }
01327 
01328    /* Default to not allowing control frames to pass. */
01329    is_allowed = 0;
01330 
01331    /*
01332     * The switch default is not present in order to take advantage
01333     * of the compiler complaining of a missing enum case.
01334     */
01335    switch (control) {
01336    /*
01337     * These control frames make sense to send/receive across the link.
01338     */
01339    case AST_CONTROL_HANGUP:
01340    case AST_CONTROL_RING:
01341    case AST_CONTROL_RINGING:
01342    case AST_CONTROL_ANSWER:
01343    case AST_CONTROL_BUSY:
01344    case AST_CONTROL_TAKEOFFHOOK:
01345    case AST_CONTROL_OFFHOOK:
01346    case AST_CONTROL_CONGESTION:
01347    case AST_CONTROL_FLASH:
01348    case AST_CONTROL_WINK:
01349    case AST_CONTROL_OPTION:
01350    case AST_CONTROL_RADIO_KEY:
01351    case AST_CONTROL_RADIO_UNKEY:
01352    case AST_CONTROL_PROGRESS:
01353    case AST_CONTROL_PROCEEDING:
01354    case AST_CONTROL_HOLD:
01355    case AST_CONTROL_UNHOLD:
01356    case AST_CONTROL_VIDUPDATE:
01357    case AST_CONTROL_CONNECTED_LINE:
01358    case AST_CONTROL_REDIRECTING:
01359    case AST_CONTROL_T38_PARAMETERS:
01360    case AST_CONTROL_AOC:
01361    case AST_CONTROL_INCOMPLETE:
01362    case AST_CONTROL_MCID:
01363       is_allowed = -1;
01364       break;
01365 
01366    /*
01367     * These control frames do not make sense to send/receive across the link.
01368     */
01369    case _XXX_AST_CONTROL_T38:
01370       /* The control value is deprecated in favor of AST_CONTROL_T38_PARAMETERS. */
01371    case AST_CONTROL_SRCUPDATE:
01372       /* Across an IAX link the source is still the same. */
01373    case AST_CONTROL_TRANSFER:
01374       /* A success/fail status report from calling ast_transfer() on this machine. */
01375    case AST_CONTROL_CC:
01376       /* The payload contains pointers that are valid for the sending machine only. */
01377    case AST_CONTROL_SRCCHANGE:
01378       /* Across an IAX link the source is still the same. */
01379    case AST_CONTROL_READ_ACTION:
01380       /* The action can only be done by the sending machine. */
01381    case AST_CONTROL_END_OF_Q:
01382       /* This frame would cause the call to unexpectedly hangup. */
01383    case AST_CONTROL_UPDATE_RTP_PEER:
01384       /* Only meaningful across a bridge on this machine for direct-media exchange. */
01385    case AST_CONTROL_PVT_CAUSE_CODE:
01386       /* Intended only for the sending machine's local channel structure. */
01387       break;
01388    }
01389    return is_allowed;
01390 }
01391 
01392 static void mwi_event_cb(const struct ast_event *event, void *userdata)
01393 {
01394    /* The MWI subscriptions exist just so the core knows we care about those
01395     * mailboxes.  However, we just grab the events out of the cache when it
01396     * is time to send MWI, since it is only sent with a REGACK. */
01397 }
01398 
01399 static void network_change_event_subscribe(void)
01400 {
01401    if (!network_change_event_subscription) {
01402       network_change_event_subscription = ast_event_subscribe(AST_EVENT_NETWORK_CHANGE,
01403          network_change_event_cb, "IAX2 Network Change", NULL, AST_EVENT_IE_END);
01404    }
01405 }
01406 
01407 static void network_change_event_unsubscribe(void)
01408 {
01409    if (network_change_event_subscription) {
01410       network_change_event_subscription = ast_event_unsubscribe(network_change_event_subscription);
01411    }
01412 }
01413 
01414 static void acl_change_event_subscribe(void)
01415 {
01416    if (!acl_change_event_subscription) {
01417       acl_change_event_subscription = ast_event_subscribe(AST_EVENT_ACL_CHANGE,
01418          acl_change_event_cb, "IAX2 ACL Change", NULL, AST_EVENT_IE_END);
01419    }
01420 }
01421 
01422 static void acl_change_event_unsubscribe(void)
01423 {
01424    if (acl_change_event_subscription) {
01425       acl_change_event_subscription = ast_event_unsubscribe(acl_change_event_subscription);
01426    }
01427 }
01428 
01429 static int network_change_event_sched_cb(const void *data)
01430 {
01431    struct iax2_registry *reg;
01432    network_change_event_sched_id = -1;
01433    AST_LIST_LOCK(&registrations);
01434    AST_LIST_TRAVERSE(&registrations, reg, entry) {
01435       iax2_do_register(reg);
01436    }
01437    AST_LIST_UNLOCK(&registrations);
01438 
01439    return 0;
01440 }
01441 
01442 static void network_change_event_cb(const struct ast_event *event, void *userdata)
01443 {
01444    ast_debug(1, "IAX, got a network change event, renewing all IAX registrations.\n");
01445    if (network_change_event_sched_id == -1) {
01446       network_change_event_sched_id = iax2_sched_add(sched, 1000, network_change_event_sched_cb, NULL);
01447    }
01448 
01449 }
01450 
01451 static void acl_change_event_cb(const struct ast_event *event, void *userdata)
01452 {
01453    ast_log(LOG_NOTICE, "Reloading chan_iax2 in response to ACL change event.\n");
01454    reload_config(1);
01455 }
01456 
01457 
01458 /*! \brief Send manager event at call setup to link between Asterisk channel name
01459    and IAX2 call identifiers */
01460 static void iax2_ami_channelupdate(struct chan_iax2_pvt *pvt)
01461 {
01462    manager_event(EVENT_FLAG_SYSTEM, "ChannelUpdate",
01463       "Channel: %s\r\nChanneltype: IAX2\r\nIAX2-callno-local: %d\r\nIAX2-callno-remote: %d\r\nIAX2-peer: %s\r\n",
01464       pvt->owner ? ast_channel_name(pvt->owner) : "",
01465       pvt->callno, pvt->peercallno, pvt->peer ? pvt->peer : "");
01466 }
01467 
01468 static const struct ast_datastore_info iax2_variable_datastore_info = {
01469    .type = "IAX2_VARIABLE",
01470    .duplicate = iax2_dup_variable_datastore,
01471    .destroy = iax2_free_variable_datastore,
01472 };
01473 
01474 static void *iax2_dup_variable_datastore(void *old)
01475 {
01476    AST_LIST_HEAD(, ast_var_t) *oldlist = old, *newlist;
01477    struct ast_var_t *oldvar, *newvar;
01478 
01479    newlist = ast_calloc(sizeof(*newlist), 1);
01480    if (!newlist) {
01481       ast_log(LOG_ERROR, "Unable to duplicate iax2 variables\n");
01482       return NULL;
01483    }
01484 
01485    AST_LIST_HEAD_INIT(newlist);
01486    AST_LIST_LOCK(oldlist);
01487    AST_LIST_TRAVERSE(oldlist, oldvar, entries) {
01488       newvar = ast_var_assign(ast_var_name(oldvar), ast_var_value(oldvar));
01489       if (newvar)
01490          AST_LIST_INSERT_TAIL(newlist, newvar, entries);
01491       else
01492          ast_log(LOG_ERROR, "Unable to duplicate iax2 variable '%s'\n", ast_var_name(oldvar));
01493    }
01494    AST_LIST_UNLOCK(oldlist);
01495    return newlist;
01496 }
01497 
01498 static void iax2_free_variable_datastore(void *old)
01499 {
01500    AST_LIST_HEAD(, ast_var_t) *oldlist = old;
01501    struct ast_var_t *oldvar;
01502 
01503    AST_LIST_LOCK(oldlist);
01504    while ((oldvar = AST_LIST_REMOVE_HEAD(oldlist, entries))) {
01505       ast_free(oldvar);
01506    }
01507    AST_LIST_UNLOCK(oldlist);
01508    AST_LIST_HEAD_DESTROY(oldlist);
01509    ast_free(oldlist);
01510 }
01511 
01512 
01513 /* WARNING: insert_idle_thread should only ever be called within the
01514  * context of an iax2_process_thread() thread.
01515  */
01516 static void insert_idle_thread(struct iax2_thread *thread)
01517 {
01518    if (thread->type == IAX_THREAD_TYPE_DYNAMIC) {
01519       AST_LIST_LOCK(&dynamic_list);
01520       AST_LIST_INSERT_TAIL(&dynamic_list, thread, list);
01521       AST_LIST_UNLOCK(&dynamic_list);
01522    } else {
01523       AST_LIST_LOCK(&idle_list);
01524       AST_LIST_INSERT_TAIL(&idle_list, thread, list);
01525       AST_LIST_UNLOCK(&idle_list);
01526    }
01527 
01528    return;
01529 }
01530 
01531 static struct iax2_thread *find_idle_thread(void)
01532 {
01533    struct iax2_thread *thread = NULL;
01534 
01535    /* Pop the head of the idle list off */
01536    AST_LIST_LOCK(&idle_list);
01537    thread = AST_LIST_REMOVE_HEAD(&idle_list, list);
01538    AST_LIST_UNLOCK(&idle_list);
01539 
01540    /* If we popped a thread off the idle list, just return it */
01541    if (thread) {
01542       memset(&thread->ffinfo, 0, sizeof(thread->ffinfo));
01543       return thread;
01544    }
01545 
01546    /* Pop the head of the dynamic list off */
01547    AST_LIST_LOCK(&dynamic_list);
01548    thread = AST_LIST_REMOVE_HEAD(&dynamic_list, list);
01549    AST_LIST_UNLOCK(&dynamic_list);
01550 
01551    /* If we popped a thread off the dynamic list, just return it */
01552    if (thread) {
01553       memset(&thread->ffinfo, 0, sizeof(thread->ffinfo));
01554       return thread;
01555    }
01556 
01557    /* If we can't create a new dynamic thread for any reason, return no thread at all */
01558    if (iaxdynamicthreadcount >= iaxmaxthreadcount || !(thread = ast_calloc(1, sizeof(*thread))))
01559       return NULL;
01560 
01561    /* Set default values */
01562    ast_atomic_fetchadd_int(&iaxdynamicthreadcount, 1);
01563    thread->threadnum = ast_atomic_fetchadd_int(&iaxdynamicthreadnum, 1);
01564    thread->type = IAX_THREAD_TYPE_DYNAMIC;
01565 
01566    /* Initialize lock and condition */
01567    ast_mutex_init(&thread->lock);
01568    ast_cond_init(&thread->cond, NULL);
01569    ast_mutex_init(&thread->init_lock);
01570    ast_cond_init(&thread->init_cond, NULL);
01571    ast_mutex_lock(&thread->init_lock);
01572 
01573    /* Create thread and send it on it's way */
01574    if (ast_pthread_create_background(&thread->threadid, NULL, iax2_process_thread, thread)) {
01575       ast_cond_destroy(&thread->cond);
01576       ast_mutex_destroy(&thread->lock);
01577       ast_mutex_unlock(&thread->init_lock);
01578       ast_cond_destroy(&thread->init_cond);
01579       ast_mutex_destroy(&thread->init_lock);
01580       ast_free(thread);
01581       return NULL;
01582    }
01583 
01584    /* this thread is not processing a full frame (since it is idle),
01585       so ensure that the field for the full frame call number is empty */
01586    memset(&thread->ffinfo, 0, sizeof(thread->ffinfo));
01587 
01588    /* Wait for the thread to be ready before returning it to the caller */
01589    ast_cond_wait(&thread->init_cond, &thread->init_lock);
01590 
01591    /* Done with init_lock */
01592    ast_mutex_unlock(&thread->init_lock);
01593 
01594    return thread;
01595 }
01596 
01597 #ifdef SCHED_MULTITHREADED
01598 static int __schedule_action(void (*func)(const void *data), const void *data, const char *funcname)
01599 {
01600    struct iax2_thread *thread;
01601    static time_t lasterror;
01602    time_t t;
01603 
01604    thread = find_idle_thread();
01605    if (thread != NULL) {
01606       thread->schedfunc = func;
01607       thread->scheddata = data;
01608       thread->iostate = IAX_IOSTATE_SCHEDREADY;
01609 #ifdef DEBUG_SCHED_MULTITHREAD
01610       ast_copy_string(thread->curfunc, funcname, sizeof(thread->curfunc));
01611 #endif
01612       signal_condition(&thread->lock, &thread->cond);
01613       return 0;
01614    }
01615    time(&t);
01616    if (t != lasterror) {
01617       lasterror = t;
01618       ast_debug(1, "Out of idle IAX2 threads for scheduling! (%s)\n", funcname);
01619    }
01620 
01621    return -1;
01622 }
01623 #define schedule_action(func, data) __schedule_action(func, data, __PRETTY_FUNCTION__)
01624 #endif
01625 
01626 static int iax2_sched_replace(int id, struct ast_sched_context *con, int when,
01627       ast_sched_cb callback, const void *data)
01628 {
01629    return ast_sched_replace(id, con, when, callback, data);
01630 }
01631 
01632 static int iax2_sched_add(struct ast_sched_context *con, int when,
01633       ast_sched_cb callback, const void *data)
01634 {
01635    return ast_sched_add(con, when, callback, data);
01636 }
01637 
01638 static int send_ping(const void *data);
01639 
01640 static void __send_ping(const void *data)
01641 {
01642    int callno = (long) data;
01643 
01644    ast_mutex_lock(&iaxsl[callno]);
01645 
01646    if (iaxs[callno]) {
01647       if (iaxs[callno]->peercallno) {
01648          send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_PING, 0, NULL, 0, -1);
01649          if (iaxs[callno]->pingid != DONT_RESCHEDULE) {
01650             iaxs[callno]->pingid = iax2_sched_add(sched, ping_time * 1000, send_ping, data);
01651          }
01652       }
01653    } else {
01654       ast_debug(1, "I was supposed to send a PING with callno %d, but no such call exists.\n", callno);
01655    }
01656 
01657    ast_mutex_unlock(&iaxsl[callno]);
01658 }
01659 
01660 static int send_ping(const void *data)
01661 {
01662    int callno = (long) data;
01663    ast_mutex_lock(&iaxsl[callno]);
01664    if (iaxs[callno] && iaxs[callno]->pingid != DONT_RESCHEDULE) {
01665       iaxs[callno]->pingid = -1;
01666    }
01667    ast_mutex_unlock(&iaxsl[callno]);
01668 
01669 #ifdef SCHED_MULTITHREADED
01670    if (schedule_action(__send_ping, data))
01671 #endif
01672       __send_ping(data);
01673 
01674    return 0;
01675 }
01676 
01677 static void encmethods_to_str(int e, struct ast_str **buf)
01678 {
01679    ast_str_set(buf, 0, "(");
01680    if (e & IAX_ENCRYPT_AES128) {
01681       ast_str_append(buf, 0, "aes128");
01682    }
01683    if (e & IAX_ENCRYPT_KEYROTATE) {
01684       ast_str_append(buf, 0, ",keyrotate");
01685    }
01686    if (ast_str_strlen(*buf) > 1) {
01687       ast_str_append(buf, 0, ")");
01688    } else {
01689       ast_str_set(buf, 0, "No");
01690    }
01691 }
01692 
01693 static int get_encrypt_methods(const char *s)
01694 {
01695    int e;
01696    if (!strcasecmp(s, "aes128"))
01697       e = IAX_ENCRYPT_AES128 | IAX_ENCRYPT_KEYROTATE;
01698    else if (ast_true(s))
01699       e = IAX_ENCRYPT_AES128 | IAX_ENCRYPT_KEYROTATE;
01700    else
01701       e = 0;
01702    return e;
01703 }
01704 
01705 static int send_lagrq(const void *data);
01706 
01707 static void __send_lagrq(const void *data)
01708 {
01709    int callno = (long) data;
01710 
01711    ast_mutex_lock(&iaxsl[callno]);
01712 
01713    if (iaxs[callno]) {
01714       if (iaxs[callno]->peercallno) {
01715          send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_LAGRQ, 0, NULL, 0, -1);
01716          if (iaxs[callno]->lagid != DONT_RESCHEDULE) {
01717             iaxs[callno]->lagid = iax2_sched_add(sched, lagrq_time * 1000, send_lagrq, data);
01718          }
01719       }
01720    } else {
01721       ast_debug(1, "I was supposed to send a LAGRQ with callno %d, but no such call exists.\n", callno);
01722    }
01723 
01724    ast_mutex_unlock(&iaxsl[callno]);
01725 }
01726 
01727 static int send_lagrq(const void *data)
01728 {
01729    int callno = (long) data;
01730    ast_mutex_lock(&iaxsl[callno]);
01731    if (iaxs[callno] && iaxs[callno]->lagid != DONT_RESCHEDULE) {
01732       iaxs[callno]->lagid = -1;
01733    }
01734    ast_mutex_unlock(&iaxsl[callno]);
01735 
01736 #ifdef SCHED_MULTITHREADED
01737    if (schedule_action(__send_lagrq, data))
01738 #endif
01739       __send_lagrq(data);
01740    return 0;
01741 }
01742 
01743 static unsigned char compress_subclass(iax2_format subclass)
01744 {
01745    int x;
01746    int power=-1;
01747    /* If it's 64 or smaller, just return it */
01748    if (subclass < IAX_FLAG_SC_LOG)
01749       return subclass;
01750    /* Otherwise find its power */
01751    for (x = 0; x < IAX_MAX_SHIFT; x++) {
01752       if (subclass & (1LL << x)) {
01753          if (power > -1) {
01754             ast_log(LOG_WARNING, "Can't compress subclass %lld\n", (long long) subclass);
01755             return 0;
01756          } else
01757             power = x;
01758       }
01759    }
01760    return power | IAX_FLAG_SC_LOG;
01761 }
01762 
01763 static iax2_format uncompress_subclass(unsigned char csub)
01764 {
01765    /* If the SC_LOG flag is set, return 2^csub otherwise csub */
01766    if (csub & IAX_FLAG_SC_LOG) {
01767       /* special case for 'compressed' -1 */
01768       if (csub == 0xff)
01769          return -1;
01770       else
01771          return 1LL << (csub & ~IAX_FLAG_SC_LOG & IAX_MAX_SHIFT);
01772    }
01773    else
01774       return csub;
01775 }
01776 
01777 static iax2_format iax2_codec_choose(struct ast_codec_pref *pref, iax2_format formats, int find_best)
01778 {
01779    struct ast_format_cap *cap;
01780    struct ast_format tmpfmt;
01781    iax2_format format = 0;
01782    if ((cap = ast_format_cap_alloc_nolock())) {
01783       ast_format_clear(&tmpfmt);
01784       ast_format_cap_from_old_bitfield(cap, formats);
01785       ast_codec_choose(pref, cap, find_best, &tmpfmt);
01786       format = ast_format_to_old_bitfield(&tmpfmt);
01787       cap = ast_format_cap_destroy(cap);
01788    }
01789 
01790    return format;
01791 }
01792 
01793 static iax2_format iax2_best_codec(iax2_format formats)
01794 {
01795    struct ast_format_cap *cap = ast_format_cap_alloc_nolock();
01796    struct ast_format tmpfmt;
01797    if (!cap) {
01798       return 0;
01799    }
01800 
01801    ast_format_clear(&tmpfmt);
01802    ast_format_cap_from_old_bitfield(cap, formats);
01803    ast_best_codec(cap, &tmpfmt);
01804    cap = ast_format_cap_destroy(cap);
01805    return ast_format_to_old_bitfield(&tmpfmt);
01806 }
01807 
01808 const char *iax2_getformatname(iax2_format format)
01809 {
01810    struct ast_format tmpfmt;
01811    if (!(ast_format_from_old_bitfield(&tmpfmt, format))) {
01812       return "Unknown";
01813    }
01814 
01815    return ast_getformatname(&tmpfmt);
01816 }
01817 
01818 static char *iax2_getformatname_multiple(char *codec_buf, size_t len, iax2_format format)
01819 {
01820    struct ast_format_cap *cap = ast_format_cap_alloc_nolock();
01821 
01822    if (!cap) {
01823       return "(Nothing)";
01824    }
01825    ast_format_cap_from_old_bitfield(cap, format);
01826    ast_getformatname_multiple(codec_buf, len, cap);
01827    cap = ast_format_cap_destroy(cap);
01828 
01829    return codec_buf;
01830 }
01831 
01832 static int iax2_parse_allow_disallow(struct ast_codec_pref *pref, iax2_format *formats, const char *list, int allowing)
01833 {
01834    int res;
01835    struct ast_format_cap *cap = ast_format_cap_alloc_nolock();
01836    if (!cap) {
01837       return 1;
01838    }
01839 
01840    ast_format_cap_from_old_bitfield(cap, *formats);
01841    res = ast_parse_allow_disallow(pref, cap, list, allowing);
01842    *formats = ast_format_cap_to_old_bitfield(cap);
01843    cap = ast_format_cap_destroy(cap);
01844 
01845    return res;
01846 }
01847 
01848 static int iax2_data_add_codecs(struct ast_data *root, const char *node_name, iax2_format formats)
01849 {
01850    int res;
01851    struct ast_format_cap *cap = ast_format_cap_alloc_nolock();
01852    if (!cap) {
01853       return -1;
01854    }
01855    ast_format_cap_from_old_bitfield(cap, formats);
01856    res = ast_data_add_codecs(root, node_name, cap);
01857    cap = ast_format_cap_destroy(cap);
01858    return res;
01859 }
01860 
01861 /*!
01862  * \note The only member of the peer passed here guaranteed to be set is the name field
01863  */
01864 static int peer_hash_cb(const void *obj, const int flags)
01865 {
01866    const struct iax2_peer *peer = obj;
01867    const char *name = obj;
01868 
01869    return ast_str_hash(flags & OBJ_KEY ? name : peer->name);
01870 }
01871 
01872 /*!
01873  * \note The only member of the peer passed here guaranteed to be set is the name field
01874  */
01875 static int peer_cmp_cb(void *obj, void *arg, int flags)
01876 {
01877    struct iax2_peer *peer = obj, *peer2 = arg;
01878    const char *name = arg;
01879 
01880    return !strcmp(peer->name, flags & OBJ_KEY ? name : peer2->name) ?
01881          CMP_MATCH | CMP_STOP : 0;
01882 }
01883 
01884 /*!
01885  * \note The only member of the user passed here guaranteed to be set is the name field
01886  */
01887 static int user_hash_cb(const void *obj, const int flags)
01888 {
01889    const struct iax2_user *user = obj;
01890    const char *name = obj;
01891 
01892    return ast_str_hash(flags & OBJ_KEY ? name : user->name);
01893 }
01894 
01895 /*!
01896  * \note The only member of the user passed here guaranteed to be set is the name field
01897  */
01898 static int user_cmp_cb(void *obj, void *arg, int flags)
01899 {
01900    struct iax2_user *user = obj, *user2 = arg;
01901    const char *name = arg;
01902 
01903    return !strcmp(user->name, flags & OBJ_KEY ? name : user2->name) ?
01904          CMP_MATCH | CMP_STOP : 0;
01905 }
01906 
01907 /*!
01908  * \note This funtion calls realtime_peer -> reg_source_db -> iax2_poke_peer -> find_callno,
01909  *       so do not call it with a pvt lock held.
01910  */
01911 static struct iax2_peer *find_peer(const char *name, int realtime) 
01912 {
01913    struct iax2_peer *peer = NULL;
01914 
01915    peer = ao2_find(peers, name, OBJ_KEY);
01916 
01917    /* Now go for realtime if applicable */
01918    if(!peer && realtime)
01919       peer = realtime_peer(name, NULL);
01920 
01921    return peer;
01922 }
01923 
01924 static struct iax2_peer *peer_ref(struct iax2_peer *peer)
01925 {
01926    ao2_ref(peer, +1);
01927    return peer;
01928 }
01929 
01930 static inline struct iax2_peer *peer_unref(struct iax2_peer *peer)
01931 {
01932    ao2_ref(peer, -1);
01933    return NULL;
01934 }
01935 
01936 static struct iax2_user *find_user(const char *name)
01937 {
01938    return ao2_find(users, name, OBJ_KEY);
01939 }
01940 static inline struct iax2_user *user_ref(struct iax2_user *user)
01941 {
01942    ao2_ref(user, +1);
01943    return user;
01944 }
01945 
01946 static inline struct iax2_user *user_unref(struct iax2_user *user)
01947 {
01948    ao2_ref(user, -1);
01949    return NULL;
01950 }
01951 
01952 static int iax2_getpeername(struct sockaddr_in sin, char *host, int len)
01953 {
01954    struct iax2_peer *peer = NULL;
01955    int res = 0;
01956    struct ao2_iterator i;
01957 
01958    i = ao2_iterator_init(peers, 0);
01959    while ((peer = ao2_iterator_next(&i))) {
01960       struct sockaddr_in peer_addr;
01961 
01962       ast_sockaddr_to_sin(&peer->addr, &peer_addr);
01963 
01964       if ((peer_addr.sin_addr.s_addr == sin.sin_addr.s_addr) &&
01965           (peer_addr.sin_port == sin.sin_port)) {
01966          ast_copy_string(host, peer->name, len);
01967          peer_unref(peer);
01968          res = 1;
01969          break;
01970       }
01971       peer_unref(peer);
01972    }
01973    ao2_iterator_destroy(&i);
01974 
01975    if (!peer) {
01976       peer = realtime_peer(NULL, &sin);
01977       if (peer) {
01978          ast_copy_string(host, peer->name, len);
01979          peer_unref(peer);
01980          res = 1;
01981       }
01982    }
01983 
01984    return res;
01985 }
01986 
01987 /*!\note Assumes the lock on the pvt is already held, when
01988  * iax2_destroy_helper() is called. */
01989 static void iax2_destroy_helper(struct chan_iax2_pvt *pvt)
01990 {
01991    /* Decrement AUTHREQ count if needed */
01992    if (ast_test_flag64(pvt, IAX_MAXAUTHREQ)) {
01993       struct iax2_user *user;
01994 
01995       user = ao2_find(users, pvt->username, OBJ_KEY);
01996       if (user) {
01997          ast_atomic_fetchadd_int(&user->curauthreq, -1);
01998          user_unref(user);
01999       }
02000 
02001       ast_clear_flag64(pvt, IAX_MAXAUTHREQ);
02002    }
02003    /* No more pings or lagrq's */
02004    AST_SCHED_DEL_SPINLOCK(sched, pvt->pingid, &iaxsl[pvt->callno]);
02005    pvt->pingid = DONT_RESCHEDULE;
02006    AST_SCHED_DEL_SPINLOCK(sched, pvt->lagid, &iaxsl[pvt->callno]);
02007    pvt->lagid = DONT_RESCHEDULE;
02008    AST_SCHED_DEL(sched, pvt->autoid);
02009    AST_SCHED_DEL(sched, pvt->authid);
02010    AST_SCHED_DEL(sched, pvt->initid);
02011    AST_SCHED_DEL(sched, pvt->jbid);
02012    AST_SCHED_DEL(sched, pvt->keyrotateid);
02013 }
02014 
02015 static void iax2_frame_free(struct iax_frame *fr)
02016 {
02017    AST_SCHED_DEL(sched, fr->retrans);
02018    iax_frame_free(fr);
02019 }
02020 
02021 static int scheduled_destroy(const void *vid)
02022 {
02023    unsigned short callno = PTR_TO_CALLNO(vid);
02024    ast_mutex_lock(&iaxsl[callno]);
02025    if (iaxs[callno]) {
02026       ast_debug(1, "Really destroying %d now...\n", callno);
02027       iax2_destroy(callno);
02028    }
02029    ast_mutex_unlock(&iaxsl[callno]);
02030    return 0;
02031 }
02032 
02033 static void free_signaling_queue_entry(struct signaling_queue_entry *s)
02034 {
02035    if (s->f.datalen) {
02036       ast_free(s->f.data.ptr);
02037    }
02038    ast_free(s);
02039 }
02040 
02041 /*! \brief This function must be called once we are sure the other side has
02042  *  given us a call number.  All signaling is held here until that point. */
02043 static void send_signaling(struct chan_iax2_pvt *pvt)
02044 {
02045    struct signaling_queue_entry *s = NULL;
02046 
02047    while ((s = AST_LIST_REMOVE_HEAD(&pvt->signaling_queue, next))) {
02048       iax2_send(pvt, &s->f, 0, -1, 0, 0, 0);
02049       free_signaling_queue_entry(s);
02050    }
02051    pvt->hold_signaling = 0;
02052 }
02053 
02054 /*! \brief All frames other than that of type AST_FRAME_IAX must be held until
02055  *  we have received a destination call number. */
02056 static int queue_signalling(struct chan_iax2_pvt *pvt, struct ast_frame *f)
02057 {
02058    struct signaling_queue_entry *qe;
02059 
02060    if (f->frametype == AST_FRAME_IAX || !pvt->hold_signaling) {
02061       return 1; /* do not queue this frame */
02062    } else if (!(qe = ast_calloc(1, sizeof(struct signaling_queue_entry)))) {
02063       return -1;  /* out of memory */
02064    }
02065 
02066    /* copy ast_frame into our queue entry */
02067    qe->f = *f;
02068    if (qe->f.datalen) {
02069       /* if there is data in this frame copy it over as well */
02070       if (!(qe->f.data.ptr = ast_malloc(qe->f.datalen))) {
02071          free_signaling_queue_entry(qe);
02072          return -1;
02073       }
02074       memcpy(qe->f.data.ptr, f->data.ptr, qe->f.datalen);
02075    }
02076    AST_LIST_INSERT_TAIL(&pvt->signaling_queue, qe, next);
02077 
02078    return 0;
02079 }
02080 
02081 static void pvt_destructor(void *obj)
02082 {
02083    struct chan_iax2_pvt *pvt = obj;
02084    struct iax_frame *cur = NULL;
02085    struct signaling_queue_entry *s = NULL;
02086 
02087    ast_mutex_lock(&iaxsl[pvt->callno]);
02088 
02089    iax2_destroy_helper(pvt);
02090 
02091    sched_delay_remove(&pvt->addr, pvt->callno_entry);
02092    pvt->callno_entry = NULL;
02093 
02094    /* Already gone */
02095    ast_set_flag64(pvt, IAX_ALREADYGONE);
02096 
02097    AST_LIST_TRAVERSE(&frame_queue[pvt->callno], cur, list) {
02098       /* Cancel any pending transmissions */
02099       cur->retries = -1;
02100    }
02101 
02102    ast_mutex_unlock(&iaxsl[pvt->callno]);
02103 
02104    while ((s = AST_LIST_REMOVE_HEAD(&pvt->signaling_queue, next))) {
02105       free_signaling_queue_entry(s);
02106    }
02107 
02108    if (pvt->reg) {
02109       pvt->reg->callno = 0;
02110    }
02111 
02112    if (!pvt->owner) {
02113       jb_frame frame;
02114       if (pvt->vars) {
02115           ast_variables_destroy(pvt->vars);
02116           pvt->vars = NULL;
02117       }
02118 
02119       while (jb_getall(pvt->jb, &frame) == JB_OK) {
02120          iax2_frame_free(frame.data);
02121       }
02122 
02123       jb_destroy(pvt->jb);
02124       ast_string_field_free_memory(pvt);
02125    }
02126 
02127    if (pvt->callid) {
02128       ast_callid_unref(pvt->callid);
02129    }
02130 
02131 }
02132 
02133 static struct chan_iax2_pvt *new_iax(struct sockaddr_in *sin, const char *host)
02134 {
02135    struct chan_iax2_pvt *tmp;
02136    jb_conf jbconf;
02137 
02138    if (!(tmp = ao2_alloc(sizeof(*tmp), pvt_destructor))) {
02139       return NULL;
02140    }
02141 
02142    if (ast_string_field_init(tmp, 32)) {
02143       ao2_ref(tmp, -1);
02144       tmp = NULL;
02145       return NULL;
02146    }
02147       
02148    tmp->prefs = prefs;
02149    tmp->pingid = -1;
02150    tmp->lagid = -1;
02151    tmp->autoid = -1;
02152    tmp->authid = -1;
02153    tmp->initid = -1;
02154    tmp->keyrotateid = -1;
02155 
02156    ast_string_field_set(tmp,exten, "s");
02157    ast_string_field_set(tmp,host, host);
02158 
02159    tmp->jb = jb_new();
02160    tmp->jbid = -1;
02161    jbconf.max_jitterbuf = maxjitterbuffer;
02162    jbconf.resync_threshold = resyncthreshold;
02163    jbconf.max_contig_interp = maxjitterinterps;
02164    jbconf.target_extra = jittertargetextra;
02165    jb_setconf(tmp->jb,&jbconf);
02166 
02167    AST_LIST_HEAD_INIT_NOLOCK(&tmp->dpentries);
02168 
02169    tmp->hold_signaling = 1;
02170    AST_LIST_HEAD_INIT_NOLOCK(&tmp->signaling_queue);
02171 
02172    return tmp;
02173 }
02174 
02175 static struct iax_frame *iaxfrdup2(struct iax_frame *fr)
02176 {
02177    struct iax_frame *new = iax_frame_new(DIRECTION_INGRESS, fr->af.datalen, fr->cacheable);
02178    if (new) {
02179       size_t afdatalen = new->afdatalen;
02180       memcpy(new, fr, sizeof(*new));
02181       iax_frame_wrap(new, &fr->af);
02182       new->afdatalen = afdatalen;
02183       new->data = NULL;
02184       new->datalen = 0;
02185       new->direction = DIRECTION_INGRESS;
02186       new->retrans = -1;
02187    }
02188    return new;
02189 }
02190 /* keep these defined in this order.  They are used in find_callno to
02191  * determine whether or not a new call number should be allowed. */
02192 enum {
02193    /* do not allow a new call number, only search ones in use for match */
02194    NEW_PREVENT = 0,
02195    /* search for match first, then allow a new one to be allocated */
02196    NEW_ALLOW = 1,
02197    /* do not search for match, force a new call number */
02198    NEW_FORCE = 2,
02199    /* do not search for match, force a new call number.  Signifies call number
02200     * has been calltoken validated */
02201    NEW_ALLOW_CALLTOKEN_VALIDATED = 3,
02202 };
02203 
02204 static int match(struct sockaddr_in *sin, unsigned short callno, unsigned short dcallno, const struct chan_iax2_pvt *cur, int check_dcallno)
02205 {
02206    if ((cur->addr.sin_addr.s_addr == sin->sin_addr.s_addr) &&
02207       (cur->addr.sin_port == sin->sin_port)) {
02208       /* This is the main host */
02209       if ( (cur->peercallno == 0 || cur->peercallno == callno) &&
02210           (check_dcallno ? dcallno == cur->callno : 1) ) {
02211          /* That's us.  Be sure we keep track of the peer call number */
02212          return 1;
02213       }
02214    }
02215    if ((cur->transfer.sin_addr.s_addr == sin->sin_addr.s_addr) &&
02216        (cur->transfer.sin_port == sin->sin_port) && (cur->transferring)) {
02217       /* We're transferring */
02218       if ((dcallno == cur->callno) || (cur->transferring == TRANSFER_MEDIAPASS && cur->transfercallno == callno))
02219          return 1;
02220    }
02221    return 0;
02222 }
02223 
02224 static int make_trunk(unsigned short callno, int locked)
02225 {
02226    int x;
02227    int res= 0;
02228    struct callno_entry *callno_entry;
02229    if (iaxs[callno]->oseqno) {
02230       ast_log(LOG_WARNING, "Can't make trunk once a call has started!\n");
02231       return -1;
02232    }
02233    if (callno >= TRUNK_CALL_START) {
02234       ast_log(LOG_WARNING, "Call %d is already a trunk\n", callno);
02235       return -1;
02236    }
02237 
02238    if (!(callno_entry = get_unused_callno(1, iaxs[callno]->callno_entry->validated))) {
02239       ast_log(LOG_WARNING, "Unable to trunk call: Insufficient space\n");
02240       return -1;
02241    }
02242 
02243    x = callno_entry->callno;
02244    ast_mutex_lock(&iaxsl[x]);
02245 
02246    /*!
02247     * \note We delete these before switching the slot, because if
02248     * they fire in the meantime, they will generate a warning.
02249     */
02250    AST_SCHED_DEL(sched, iaxs[callno]->pingid);
02251    AST_SCHED_DEL(sched, iaxs[callno]->lagid);
02252    iaxs[callno]->lagid = iaxs[callno]->pingid = -1;
02253    iaxs[x] = iaxs[callno];
02254    iaxs[x]->callno = x;
02255 
02256    /* since we copied over the pvt from a different callno, make sure the old entry is replaced
02257     * before assigning the new one */
02258    if (iaxs[x]->callno_entry) {
02259       iax2_sched_add(sched, MIN_REUSE_TIME * 1000, replace_callno, iaxs[x]->callno_entry);
02260    }
02261    iaxs[x]->callno_entry = callno_entry;
02262 
02263    iaxs[callno] = NULL;
02264    /* Update the two timers that should have been started */
02265    iaxs[x]->pingid = iax2_sched_add(sched, 
02266       ping_time * 1000, send_ping, (void *)(long)x);
02267    iaxs[x]->lagid = iax2_sched_add(sched, 
02268       lagrq_time * 1000, send_lagrq, (void *)(long)x);
02269 
02270    if (locked)
02271       ast_mutex_unlock(&iaxsl[callno]);
02272    res = x;
02273    if (!locked)
02274       ast_mutex_unlock(&iaxsl[x]);
02275 
02276    /* We moved this call from a non-trunked to a trunked call */
02277    ast_debug(1, "Made call %d into trunk call %d\n", callno, x);
02278 
02279    return res;
02280 }
02281 
02282 static void store_by_transfercallno(struct chan_iax2_pvt *pvt)
02283 {
02284    if (!pvt->transfercallno) {
02285       ast_log(LOG_ERROR, "This should not be called without a transfer call number.\n");
02286       return;
02287    }
02288 
02289    ao2_link(iax_transfercallno_pvts, pvt);
02290 }
02291 
02292 static void remove_by_transfercallno(struct chan_iax2_pvt *pvt)
02293 {
02294    if (!pvt->transfercallno) {
02295       ast_log(LOG_ERROR, "This should not be called without a transfer call number.\n");
02296       return;
02297    }
02298 
02299    ao2_unlink(iax_transfercallno_pvts, pvt);
02300 }
02301 static void store_by_peercallno(struct chan_iax2_pvt *pvt)
02302 {
02303    if (!pvt->peercallno) {
02304       ast_log(LOG_ERROR, "This should not be called without a peer call number.\n");
02305       return;
02306    }
02307 
02308    ao2_link(iax_peercallno_pvts, pvt);
02309 }
02310 
02311 static void remove_by_peercallno(struct chan_iax2_pvt *pvt)
02312 {
02313    if (!pvt->peercallno) {
02314       ast_log(LOG_ERROR, "This should not be called without a peer call number.\n");
02315       return;
02316    }
02317 
02318    ao2_unlink(iax_peercallno_pvts, pvt);
02319 }
02320 
02321 static int addr_range_delme_cb(void *obj, void *arg, int flags)
02322 {
02323    struct addr_range *lim = obj;
02324    lim->delme = 1;
02325    return 0;
02326 }
02327 
02328 static int addr_range_hash_cb(const void *obj, const int flags)
02329 {
02330    const struct addr_range *lim = obj;
02331    struct sockaddr_in sin;
02332    ast_sockaddr_to_sin(&lim->ha.addr, &sin);
02333    return abs((int) sin.sin_addr.s_addr);
02334 }
02335 
02336 static int addr_range_cmp_cb(void *obj, void *arg, int flags)
02337 {
02338    struct addr_range *lim1 = obj, *lim2 = arg;
02339    return (!(ast_sockaddr_cmp_addr(&lim1->ha.addr, &lim2->ha.addr)) &&
02340          !(ast_sockaddr_cmp_addr(&lim1->ha.netmask, &lim2->ha.netmask))) ?
02341          CMP_MATCH | CMP_STOP : 0;
02342 }
02343 
02344 static int peercnt_hash_cb(const void *obj, const int flags)
02345 {
02346    const struct peercnt *peercnt = obj;
02347    return abs((int) peercnt->addr);
02348 }
02349 
02350 static int peercnt_cmp_cb(void *obj, void *arg, int flags)
02351 {
02352    struct peercnt *peercnt1 = obj, *peercnt2 = arg;
02353    return (peercnt1->addr == peercnt2->addr) ? CMP_MATCH | CMP_STOP : 0;
02354 }
02355 
02356 static int addr_range_match_address_cb(void *obj, void *arg, int flags)
02357 {
02358    struct addr_range *addr_range = obj;
02359    struct sockaddr_in *sin = arg;
02360    struct sockaddr_in ha_netmask_sin;
02361    struct sockaddr_in ha_addr_sin;
02362 
02363    ast_sockaddr_to_sin(&addr_range->ha.netmask, &ha_netmask_sin);
02364    ast_sockaddr_to_sin(&addr_range->ha.addr, &ha_addr_sin);
02365 
02366    if ((sin->sin_addr.s_addr & ha_netmask_sin.sin_addr.s_addr) == ha_addr_sin.sin_addr.s_addr) {
02367       return CMP_MATCH | CMP_STOP;
02368    }
02369    return 0;
02370 }
02371 
02372 /*! 
02373  * \internal
02374  *
02375  * \brief compares sin to calltoken_ignores table to determine if validation is required.
02376  */
02377 static int calltoken_required(struct sockaddr_in *sin, const char *name, int subclass)
02378 {
02379    struct addr_range *addr_range;
02380    struct iax2_peer *peer = NULL;
02381    struct iax2_user *user = NULL;
02382    /* if no username is given, check for guest accounts */
02383    const char *find = S_OR(name, "guest");
02384    int res = 1;  /* required by default */
02385    int optional = 0;
02386    enum calltoken_peer_enum calltoken_required = CALLTOKEN_DEFAULT;
02387    /* There are only two cases in which calltoken validation is not required.
02388     * Case 1. sin falls within the list of address ranges specified in the calltoken optional table and
02389     *         the peer definition has not set the requirecalltoken option.
02390     * Case 2. Username is a valid peer/user, and that peer has requirecalltoken set either auto or no.
02391     */
02392 
02393    /* ----- Case 1 ----- */
02394    if ((addr_range = ao2_callback(calltoken_ignores, 0, addr_range_match_address_cb, sin))) {
02395       ao2_ref(addr_range, -1);
02396       optional = 1;
02397    }
02398 
02399    /* ----- Case 2 ----- */
02400    if ((subclass == IAX_COMMAND_NEW) && (user = find_user(find))) {
02401       calltoken_required = user->calltoken_required;
02402    } else if ((subclass == IAX_COMMAND_NEW) && (user = realtime_user(find, sin))) {
02403       calltoken_required = user->calltoken_required;
02404    } else if ((subclass != IAX_COMMAND_NEW) && (peer = find_peer(find, 0))) {
02405       calltoken_required = peer->calltoken_required;
02406    } else if ((subclass != IAX_COMMAND_NEW) && (peer = realtime_peer(find, sin))) {
02407       calltoken_required = peer->calltoken_required;
02408    }
02409 
02410    if (peer) {
02411       peer_unref(peer);
02412    }
02413    if (user) {
02414       user_unref(user);
02415    }
02416 
02417    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);
02418    if (((calltoken_required == CALLTOKEN_NO) || (calltoken_required == CALLTOKEN_AUTO)) ||
02419       (optional && (calltoken_required == CALLTOKEN_DEFAULT))) {
02420       res = 0;
02421    }
02422 
02423    return res;
02424 }
02425 
02426 /*! 
02427  * \internal
02428  *
02429  * \brief set peercnt callno limit.
02430  *
02431  * \details 
02432  * First looks in custom definitions. If not found, global limit
02433  * is used.  Entries marked as reg already have
02434  * a custom limit set by a registration and are not modified.
02435  */
02436 static void set_peercnt_limit(struct peercnt *peercnt)
02437 {
02438    uint16_t limit = global_maxcallno;
02439    struct addr_range *addr_range;
02440    struct sockaddr_in sin = {
02441       .sin_addr.s_addr = peercnt->addr,
02442    };
02443 
02444 
02445    if (peercnt->reg && peercnt->limit) {
02446       return; /* this peercnt has a custom limit set by a registration */
02447    }
02448 
02449    if ((addr_range = ao2_callback(callno_limits, 0, addr_range_match_address_cb, &sin))) {
02450       limit = addr_range->limit;
02451       ast_debug(1, "custom addr_range %d found for %s\n", limit, ast_inet_ntoa(sin.sin_addr));
02452       ao2_ref(addr_range, -1);
02453    }
02454 
02455    peercnt->limit = limit;
02456 }
02457 
02458 /*! 
02459  * \internal
02460  * \brief sets limits for all peercnts in table. done on reload to reflect changes in conf.
02461  */
02462 static int set_peercnt_limit_all_cb(void *obj, void *arg, int flags)
02463 {
02464    struct peercnt *peercnt = obj;
02465 
02466    set_peercnt_limit(peercnt);
02467    ast_debug(1, "Reset limits for peercnts table\n");
02468 
02469    return 0;
02470 }
02471 
02472 /*! 
02473  * \internal
02474  * \brief returns match if delme is set. 
02475  */
02476 static int prune_addr_range_cb(void *obj, void *arg, int flags)
02477 {
02478    struct addr_range *addr_range = obj;
02479 
02480    return addr_range->delme ? CMP_MATCH : 0;
02481 }
02482 
02483 /*! 
02484  * \internal
02485  * \brief modifies peercnt entry in peercnts table. Used to set custom limit or mark a registered ip
02486  */
02487 static void peercnt_modify(unsigned char reg, uint16_t limit, struct ast_sockaddr *sockaddr)
02488 {
02489    /* this function turns off and on custom callno limits set by peer registration */
02490    struct peercnt *peercnt;
02491    struct peercnt tmp = {
02492       .addr = 0,
02493    };
02494    struct sockaddr_in sin;
02495 
02496    ast_sockaddr_to_sin(sockaddr, &sin);
02497 
02498    tmp.addr = sin.sin_addr.s_addr;
02499 
02500    if ((peercnt = ao2_find(peercnts, &tmp, OBJ_POINTER))) {
02501       peercnt->reg = reg;
02502       if (limit) {
02503          peercnt->limit = limit;
02504       } else {
02505          set_peercnt_limit(peercnt);
02506       }
02507       ast_debug(1, "peercnt entry %s modified limit:%d registered:%d", ast_inet_ntoa(sin.sin_addr), peercnt->limit, peercnt->reg);
02508       ao2_ref(peercnt, -1); /* decrement ref from find */
02509    }
02510 }
02511 
02512 /*! 
02513  * \internal
02514  * \brief adds an ip to the peercnts table, increments connection count if it already exists
02515  *
02516  * \details First searches for the address in the peercnts table.  If found
02517  * the current count is incremented.  If not found a new peercnt is allocated
02518  * and linked into the peercnts table with a call number count of 1.
02519  */
02520 static int peercnt_add(struct sockaddr_in *sin)
02521 {
02522    struct peercnt *peercnt;
02523    unsigned long addr = sin->sin_addr.s_addr;
02524    int res = 0;
02525    struct peercnt tmp = {
02526       .addr = addr,
02527    };
02528 
02529    /* Reasoning for peercnts container lock:  Two identical ip addresses
02530     * could be added by different threads at the "same time". Without the container
02531     * lock, both threads could alloc space for the same object and attempt
02532     * to link to table.  With the lock, one would create the object and link
02533     * to table while the other would find the already created peercnt object
02534     * rather than creating a new one. */
02535    ao2_lock(peercnts);
02536    if ((peercnt = ao2_find(peercnts, &tmp, OBJ_POINTER))) {
02537       ao2_lock(peercnt);
02538    } else if ((peercnt = ao2_alloc(sizeof(*peercnt), NULL))) {
02539       ao2_lock(peercnt);
02540       /* create and set defaults */
02541       peercnt->addr = addr;
02542       set_peercnt_limit(peercnt);
02543       /* guarantees it does not go away after unlocking table
02544        * ao2_find automatically adds this */
02545       ao2_link(peercnts, peercnt);
02546    } else {
02547       ao2_unlock(peercnts);
02548       return -1;
02549    }
02550 
02551    /* check to see if the address has hit its callno limit.  If not increment cur. */
02552    if (peercnt->limit > peercnt->cur) {
02553       peercnt->cur++;
02554       ast_debug(1, "ip callno count incremented to %d for %s\n", peercnt->cur, ast_inet_ntoa(sin->sin_addr));
02555    } else { /* max num call numbers for this peer has been reached! */
02556       ast_log(LOG_ERROR, "maxcallnumber limit of %d for %s has been reached!\n", peercnt->limit, ast_inet_ntoa(sin->sin_addr));
02557       res = -1;
02558    }
02559 
02560    /* clean up locks and ref count */
02561    ao2_unlock(peercnt);
02562    ao2_unlock(peercnts);
02563    ao2_ref(peercnt, -1); /* decrement ref from find/alloc, only the container ref remains. */
02564 
02565    return res;
02566 }
02567 
02568 /*! 
02569  * \internal
02570  * \brief decrements a peercnts table entry
02571  */
02572 static void peercnt_remove(struct peercnt *peercnt)
02573 {
02574    struct sockaddr_in sin = {
02575       .sin_addr.s_addr = peercnt->addr,
02576    };
02577 
02578    /*
02579     * Container locked here since peercnt may be unlinked from
02580     * list.  If left unlocked, peercnt_add could try and grab this
02581     * entry from the table and modify it at the "same time" this
02582     * thread attemps to unlink it.
02583     */
02584    ao2_lock(peercnts);
02585    peercnt->cur--;
02586    ast_debug(1, "ip callno count decremented to %d for %s\n", peercnt->cur, ast_inet_ntoa(sin.sin_addr));
02587    /* if this was the last connection from the peer remove it from table */
02588    if (peercnt->cur == 0) {
02589       ao2_unlink(peercnts, peercnt);/* decrements ref from table, last ref is left to scheduler */
02590    }
02591    ao2_unlock(peercnts);
02592 }
02593 
02594 /*! 
02595  * \internal
02596  * \brief called by scheduler to decrement object
02597  */
02598 static int peercnt_remove_cb(const void *obj)
02599 {
02600    struct peercnt *peercnt = (struct peercnt *) obj;
02601 
02602    peercnt_remove(peercnt);
02603    ao2_ref(peercnt, -1); /* decrement ref from scheduler */
02604 
02605    return 0;
02606 }
02607 
02608 /*! 
02609  * \internal
02610  * \brief decrements peercnts connection count, finds by addr
02611  */
02612 static int peercnt_remove_by_addr(struct sockaddr_in *sin)
02613 {
02614    struct peercnt *peercnt;
02615    struct peercnt tmp = {
02616       .addr = sin->sin_addr.s_addr,
02617    };
02618 
02619    if ((peercnt = ao2_find(peercnts, &tmp, OBJ_POINTER))) {
02620       peercnt_remove(peercnt);
02621       ao2_ref(peercnt, -1); /* decrement ref from find */
02622    }
02623    return 0;
02624 }
02625 
02626 /*! 
02627  * \internal
02628  * \brief Create callno_limit entry based on configuration
02629  */
02630 static void build_callno_limits(struct ast_variable *v)
02631 {
02632    struct addr_range *addr_range = NULL;
02633    struct addr_range tmp;
02634    struct ast_ha *ha;
02635    int limit;
02636    int error;
02637    int found;
02638 
02639    for (; v; v = v->next) {
02640       limit = -1;
02641       error = 0;
02642       found = 0;
02643       ha = ast_append_ha("permit", v->name, NULL, &error);
02644 
02645       /* check for valid config information */
02646       if (error) {
02647          ast_log(LOG_ERROR, "Call number limit for %s could not be added, Invalid address range\n.", v->name);
02648          continue;
02649       } else if ((sscanf(v->value, "%d", &limit) != 1) || (limit < 0)) {
02650          ast_log(LOG_ERROR, "Call number limit for %s could not be added. Invalid limit %s\n.", v->name, v->value);
02651          ast_free_ha(ha);
02652          continue;
02653       }
02654 
02655       ast_copy_ha(ha, &tmp.ha);
02656       /* find or create the addr_range */
02657       if ((addr_range = ao2_find(callno_limits, &tmp, OBJ_POINTER))) {
02658          ao2_lock(addr_range);
02659          found = 1;
02660       } else if (!(addr_range = ao2_alloc(sizeof(*addr_range), NULL))) {
02661          ast_free_ha(ha);
02662          return; /* out of memory */
02663       }
02664 
02665       /* copy over config data into addr_range object */
02666       ast_copy_ha(ha, &addr_range->ha); /* this is safe because only one ha is possible for each limit */
02667       ast_free_ha(ha); /* cleanup the tmp ha */
02668       addr_range->limit = limit;
02669       addr_range->delme = 0;
02670 
02671       /* cleanup */
02672       if (found) {
02673          ao2_unlock(addr_range);
02674       } else {
02675          ao2_link(callno_limits, addr_range);
02676       }
02677       ao2_ref(addr_range, -1); /* decrement ref from ao2_find and ao2_alloc, only container ref remains */
02678    }
02679 }
02680 
02681 /*! 
02682  * \internal
02683  * \brief Create calltoken_ignores entry based on configuration
02684  */
02685 static int add_calltoken_ignore(const char *addr)
02686 {
02687    struct addr_range tmp;
02688    struct addr_range *addr_range = NULL;
02689    struct ast_ha *ha = NULL;
02690    int error = 0;
02691 
02692    if (ast_strlen_zero(addr)) {
02693       ast_log(LOG_WARNING, "invalid calltokenoptional %s\n", addr);
02694       return -1;
02695    }
02696 
02697    ha = ast_append_ha("permit", addr, NULL, &error);
02698 
02699    /* check for valid config information */
02700    if (error) {
02701       ast_log(LOG_WARNING, "Error %d creating calltokenoptional entry %s\n", error, addr);
02702       return -1;
02703    }
02704 
02705    ast_copy_ha(ha, &tmp.ha);
02706    /* find or create the addr_range */
02707    if ((addr_range = ao2_find(calltoken_ignores, &tmp, OBJ_POINTER))) {
02708       ao2_lock(addr_range);
02709       addr_range->delme = 0;
02710       ao2_unlock(addr_range);
02711    } else if ((addr_range = ao2_alloc(sizeof(*addr_range), NULL))) {
02712       /* copy over config data into addr_range object */
02713       ast_copy_ha(ha, &addr_range->ha); /* this is safe because only one ha is possible */
02714       ao2_link(calltoken_ignores, addr_range);
02715    } else {
02716       ast_free_ha(ha);
02717       return -1;
02718    }
02719 
02720    ast_free_ha(ha);
02721    ao2_ref(addr_range, -1); /* decrement ref from ao2_find and ao2_alloc, only container ref remains */
02722 
02723    return 0;
02724 }
02725 
02726 static char *handle_cli_iax2_show_callno_limits(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
02727 {
02728    struct ao2_iterator i;
02729    struct peercnt *peercnt;
02730    struct sockaddr_in sin;
02731    int found = 0;
02732 
02733    switch (cmd) {
02734    case CLI_INIT:
02735       e->command = "iax2 show callnumber usage";
02736       e->usage =
02737          "Usage: iax2 show callnumber usage [IP address]\n"
02738          "       Shows current IP addresses which are consuming iax2 call numbers\n";
02739       return NULL;
02740    case CLI_GENERATE:
02741       return NULL;
02742    case CLI_HANDLER:
02743       if (a->argc < 4 || a->argc > 5)
02744          return CLI_SHOWUSAGE;
02745 
02746       if (a->argc == 4) {
02747          ast_cli(a->fd, "%-15s %-12s %-12s\n", "Address", "Callno Usage", "Callno Limit");
02748       }
02749 
02750       i = ao2_iterator_init(peercnts, 0);
02751       while ((peercnt = ao2_iterator_next(&i))) {
02752          sin.sin_addr.s_addr = peercnt->addr;
02753          if (a->argc == 5) {
02754             if (!strcasecmp(a->argv[4], ast_inet_ntoa(sin.sin_addr))) {
02755                ast_cli(a->fd, "%-15s %-12s %-12s\n", "Address", "Callno Usage", "Callno Limit");
02756                ast_cli(a->fd, "%-15s %-12d %-12d\n", ast_inet_ntoa(sin.sin_addr), peercnt->cur, peercnt->limit);
02757                ao2_ref(peercnt, -1);
02758                found = 1;
02759                break;
02760             }
02761          } else {
02762             ast_cli(a->fd, "%-15s %-12d %-12d\n", ast_inet_ntoa(sin.sin_addr), peercnt->cur, peercnt->limit);
02763          }
02764          ao2_ref(peercnt, -1);
02765       }
02766       ao2_iterator_destroy(&i);
02767 
02768       if (a->argc == 4) {
02769          ast_cli(a->fd, "\nNon-CallToken Validation Callno Limit: %d\n"
02770                           "Non-CallToken Validated Callno Used:   %d\n",
02771             global_maxcallno_nonval,
02772             total_nonval_callno_used);
02773 
02774          ast_cli(a->fd,   "Total Available Callno:                %d\n"
02775                           "Regular Callno Available:              %d\n"
02776                           "Trunk Callno Available:                %d\n",
02777             ao2_container_count(callno_pool) + ao2_container_count(callno_pool_trunk),
02778             ao2_container_count(callno_pool),
02779             ao2_container_count(callno_pool_trunk));
02780       } else if (a->argc == 5 && !found) {
02781          ast_cli(a->fd, "No call number table entries for %s found\n", a->argv[4] );
02782       }
02783 
02784 
02785       return CLI_SUCCESS;
02786    default:
02787       return NULL;
02788    }
02789 }
02790 
02791 static struct callno_entry *get_unused_callno(int trunk, int validated)
02792 {
02793    struct callno_entry *callno_entry = NULL;
02794    if ((!ao2_container_count(callno_pool) && !trunk) || (!ao2_container_count(callno_pool_trunk) && trunk)) {
02795       ast_log(LOG_WARNING, "Out of CallNumbers\n");
02796       /* Minor optimization for the extreme case. */
02797       return NULL;
02798    }
02799 
02800    /* the callno_pool container is locked here primarily to ensure thread
02801     * safety of the total_nonval_callno_used check and increment */
02802    ao2_lock(callno_pool);
02803 
02804    /* only a certain number of nonvalidated call numbers should be allocated.
02805     * If there ever is an attack, this separates the calltoken validating
02806     * users from the non calltoken validating users. */
02807    if (!validated && (total_nonval_callno_used >= global_maxcallno_nonval)) {
02808       ast_log(LOG_WARNING, "NON-CallToken callnumber limit is reached. Current:%d Max:%d\n", total_nonval_callno_used, global_maxcallno_nonval);
02809       ao2_unlock(callno_pool);
02810       return NULL;
02811    }
02812 
02813    /* unlink the object from the container, taking over ownership
02814     * of the reference the container had to the object */
02815    callno_entry = ao2_find((trunk ? callno_pool_trunk : callno_pool), NULL, OBJ_POINTER | OBJ_UNLINK | OBJ_CONTINUE);
02816 
02817    if (callno_entry) {
02818       callno_entry->validated = validated;
02819       if (!validated) {
02820          total_nonval_callno_used++;
02821       }
02822    }
02823 
02824    ao2_unlock(callno_pool);
02825    return callno_entry;
02826 }
02827 
02828 static int replace_callno(const void *obj)
02829 {
02830    struct callno_entry *callno_entry = (struct callno_entry *) obj;
02831 
02832    /* the callno_pool container is locked here primarily to ensure thread
02833     * safety of the total_nonval_callno_used check and decrement */
02834    ao2_lock(callno_pool);
02835 
02836    if (!callno_entry->validated && (total_nonval_callno_used != 0)) {
02837       total_nonval_callno_used--;
02838    } else if (!callno_entry->validated && (total_nonval_callno_used == 0)) {
02839       ast_log(LOG_ERROR, "Attempted to decrement total non calltoken validated callnumbers below zero... Callno is:%d \n", callno_entry->callno);
02840    }
02841 
02842    if (callno_entry->callno < TRUNK_CALL_START) {
02843       ao2_link(callno_pool, callno_entry);
02844    } else {
02845       ao2_link(callno_pool_trunk, callno_entry);
02846    }
02847    ao2_ref(callno_entry, -1); /* only container ref remains */
02848 
02849    ao2_unlock(callno_pool);
02850    return 0;
02851 }
02852 
02853 static int callno_hash(const void *obj, const int flags)
02854 {
02855    return abs(ast_random());
02856 }
02857 
02858 static int create_callno_pools(void)
02859 {
02860    uint16_t i;
02861 
02862    if (!(callno_pool = ao2_container_alloc(CALLNO_POOL_BUCKETS, callno_hash, NULL))) {
02863       return -1;
02864    }
02865 
02866    if (!(callno_pool_trunk = ao2_container_alloc(CALLNO_POOL_BUCKETS, callno_hash, NULL))) {
02867       return -1;
02868    }
02869 
02870    /* start at 2, 0 and 1 are reserved */
02871    for (i = 2; i < IAX_MAX_CALLS; i++) {
02872       struct callno_entry *callno_entry;
02873 
02874       if (!(callno_entry = ao2_alloc(sizeof(*callno_entry), NULL))) {
02875          return -1;
02876       }
02877 
02878       callno_entry->callno = i;
02879 
02880       if (i < TRUNK_CALL_START) {
02881          ao2_link(callno_pool, callno_entry);
02882       } else {
02883          ao2_link(callno_pool_trunk, callno_entry);
02884       }
02885 
02886       ao2_ref(callno_entry, -1);
02887    }
02888 
02889    return 0;
02890 }
02891 
02892 /*!
02893  * \internal
02894  * \brief Schedules delayed removal of iax2_pvt call number data
02895  *
02896  * \note After MIN_REUSE_TIME has passed for a destroyed iax2_pvt, the callno is
02897  * available again, and the address from the previous connection must be decremented
02898  * from the peercnts table.  This function schedules these operations to take place.
02899  */
02900 static void sched_delay_remove(struct sockaddr_in *sin, struct callno_entry *callno_entry)
02901 {
02902    int i;
02903    struct peercnt *peercnt;
02904    struct peercnt tmp = {
02905       .addr = sin->sin_addr.s_addr,
02906    };
02907 
02908    if ((peercnt = ao2_find(peercnts, &tmp, OBJ_POINTER))) {
02909       /* refcount is incremented with ao2_find.  keep that ref for the scheduler */
02910       ast_debug(1, "schedule decrement of callno used for %s in %d seconds\n", ast_inet_ntoa(sin->sin_addr), MIN_REUSE_TIME);
02911       i = iax2_sched_add(sched, MIN_REUSE_TIME * 1000, peercnt_remove_cb, peercnt);
02912       if (i == -1) {
02913          ao2_ref(peercnt, -1);
02914       }
02915    }
02916 
02917    iax2_sched_add(sched, MIN_REUSE_TIME * 1000, replace_callno, callno_entry);
02918 }
02919 
02920 /*! 
02921  * \internal
02922  * \brief returns whether or not a frame is capable of starting a new IAX2 dialog. 
02923  *
02924  * \note For this implementation, inbound pokes should _NOT_ be capable of allocating
02925  * a new callno.
02926  */
02927 static inline int attribute_pure iax2_allow_new(int frametype, int subclass, int inbound)
02928 {
02929    if (frametype != AST_FRAME_IAX) {
02930       return 0;
02931    }
02932    switch (subclass) {
02933    case IAX_COMMAND_NEW:
02934    case IAX_COMMAND_REGREQ:
02935    case IAX_COMMAND_FWDOWNL:
02936    case IAX_COMMAND_REGREL:
02937       return 1;
02938    case IAX_COMMAND_POKE:
02939       if (!inbound) {
02940          return 1;
02941       }
02942       break;
02943    }
02944    return 0;
02945 }
02946 
02947 /*
02948  * \note Calling this function while holding another pvt lock can cause a deadlock.
02949  */
02950 static int __find_callno(unsigned short callno, unsigned short dcallno, struct sockaddr_in *sin, int new, int sockfd, int return_locked, int check_dcallno)
02951 {
02952    int res = 0;
02953    int x;
02954    /* this call is calltoken validated as long as it is either NEW_FORCE
02955     * or NEW_ALLOW_CALLTOKEN_VALIDATED */
02956    int validated = (new > NEW_ALLOW) ? 1 : 0;
02957    char host[80];
02958 
02959    if (new <= NEW_ALLOW) {
02960       if (callno) {
02961          struct chan_iax2_pvt *pvt;
02962          struct chan_iax2_pvt tmp_pvt = {
02963             .callno = dcallno,
02964             .peercallno = callno,
02965             .transfercallno = callno,
02966             /* hack!! */
02967             .frames_received = check_dcallno,
02968          };
02969 
02970          memcpy(&tmp_pvt.addr, sin, sizeof(tmp_pvt.addr));
02971          /* this works for finding normal call numbers not involving transfering */ 
02972          if ((pvt = ao2_find(iax_peercallno_pvts, &tmp_pvt, OBJ_POINTER))) {
02973             if (return_locked) {
02974                ast_mutex_lock(&iaxsl[pvt->callno]);
02975             }
02976             res = pvt->callno;
02977             ao2_ref(pvt, -1);
02978             pvt = NULL;
02979             return res;
02980          }
02981          /* this searches for transfer call numbers that might not get caught otherwise */
02982          memset(&tmp_pvt.addr, 0, sizeof(tmp_pvt.addr));
02983          memcpy(&tmp_pvt.transfer, sin, sizeof(tmp_pvt.transfer));
02984          if ((pvt = ao2_find(iax_transfercallno_pvts, &tmp_pvt, OBJ_POINTER))) {
02985             if (return_locked) {
02986                ast_mutex_lock(&iaxsl[pvt->callno]);
02987             }
02988             res = pvt->callno;
02989             ao2_ref(pvt, -1);
02990             pvt = NULL;
02991             return res;
02992          }
02993       }
02994          /* This will occur on the first response to a message that we initiated,
02995        * such as a PING. */
02996       if (dcallno) {
02997          ast_mutex_lock(&iaxsl[dcallno]);
02998       }
02999       if (callno && dcallno && iaxs[dcallno] && !iaxs[dcallno]->peercallno && match(sin, callno, dcallno, iaxs[dcallno], check_dcallno)) {
03000          iaxs[dcallno]->peercallno = callno;
03001          res = dcallno;
03002          store_by_peercallno(iaxs[dcallno]);
03003          if (!res || !return_locked) {
03004             ast_mutex_unlock(&iaxsl[dcallno]);
03005          }
03006          return res;
03007       }
03008       if (dcallno) {
03009          ast_mutex_unlock(&iaxsl[dcallno]);
03010       }
03011    }
03012    if (!res && (new >= NEW_ALLOW)) {
03013       struct callno_entry *callno_entry;
03014       /* It may seem odd that we look through the peer list for a name for
03015        * this *incoming* call.  Well, it is weird.  However, users don't
03016        * have an IP address/port number that we can match against.  So,
03017        * this is just checking for a peer that has that IP/port and
03018        * assuming that we have a user of the same name.  This isn't always
03019        * correct, but it will be changed if needed after authentication. */
03020       if (!iax2_getpeername(*sin, host, sizeof(host)))
03021          snprintf(host, sizeof(host), "%s:%d", ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
03022 
03023       if (peercnt_add(sin)) {
03024          /* This address has hit its callnumber limit.  When the limit
03025           * is reached, the connection is not added to the peercnts table.*/
03026          return 0;
03027       }
03028 
03029       if (!(callno_entry = get_unused_callno(0, validated))) {
03030          /* since we ran out of space, remove the peercnt
03031           * entry we added earlier */
03032          peercnt_remove_by_addr(sin);
03033          ast_log(LOG_WARNING, "No more space\n");
03034          return 0;
03035       }
03036       x = callno_entry->callno;
03037       ast_mutex_lock(&iaxsl[x]);
03038 
03039       iaxs[x] = new_iax(sin, host);
03040       if (iaxs[x]) {
03041          if (iaxdebug)
03042             ast_debug(1, "Creating new call structure %d\n", x);
03043          iaxs[x]->callno_entry = callno_entry;
03044          iaxs[x]->sockfd = sockfd;
03045          iaxs[x]->addr.sin_port = sin->sin_port;
03046          iaxs[x]->addr.sin_family = sin->sin_family;
03047          iaxs[x]->addr.sin_addr.s_addr = sin->sin_addr.s_addr;
03048          iaxs[x]->peercallno = callno;
03049          iaxs[x]->callno = x;
03050          iaxs[x]->pingtime = DEFAULT_RETRY_TIME;
03051          iaxs[x]->expiry = min_reg_expire;
03052          iaxs[x]->pingid = iax2_sched_add(sched, ping_time * 1000, send_ping, (void *)(long)x);
03053          iaxs[x]->lagid = iax2_sched_add(sched, lagrq_time * 1000, send_lagrq, (void *)(long)x);
03054          iaxs[x]->amaflags = amaflags;
03055          ast_copy_flags64(iaxs[x], &globalflags, IAX_NOTRANSFER | IAX_TRANSFERMEDIA | IAX_USEJITTERBUF | IAX_FORCEJITTERBUF | IAX_SENDCONNECTEDLINE | IAX_RECVCONNECTEDLINE | IAX_FORCE_ENCRYPT);
03056          ast_string_field_set(iaxs[x], accountcode, accountcode);
03057          ast_string_field_set(iaxs[x], mohinterpret, mohinterpret);
03058          ast_string_field_set(iaxs[x], mohsuggest, mohsuggest);
03059          ast_string_field_set(iaxs[x], parkinglot, default_parkinglot);
03060 
03061          if (iaxs[x]->peercallno) {
03062             store_by_peercallno(iaxs[x]);
03063          }
03064       } else {
03065          ast_log(LOG_WARNING, "Out of resources\n");
03066          ast_mutex_unlock(&iaxsl[x]);
03067          replace_callno(callno_entry);
03068          return 0;
03069       }
03070       if (!return_locked)
03071          ast_mutex_unlock(&iaxsl[x]);
03072       res = x;
03073    }
03074    return res;
03075 }
03076 
03077 static int find_callno(unsigned short callno, unsigned short dcallno, struct sockaddr_in *sin, int new, int sockfd, int full_frame) { 
03078    return __find_callno(callno, dcallno, sin, new, sockfd, 0, full_frame);
03079 }
03080 
03081 static int find_callno_locked(unsigned short callno, unsigned short dcallno, struct sockaddr_in *sin, int new, int sockfd, int full_frame) {
03082 
03083    return __find_callno(callno, dcallno, sin, new, sockfd, 1, full_frame);
03084 }
03085 
03086 /*!
03087  * \brief Queue a frame to a call's owning asterisk channel
03088  *
03089  * \pre This function assumes that iaxsl[callno] is locked when called.
03090  *
03091  * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
03092  * was valid before calling it, it may no longer be valid after calling it.
03093  * This function may unlock and lock the mutex associated with this callno,
03094  * meaning that another thread may grab it and destroy the call.
03095  */
03096 static int iax2_queue_frame(int callno, struct ast_frame *f)
03097 {
03098    iax2_lock_owner(callno);
03099    if (iaxs[callno] && iaxs[callno]->owner) {
03100       ast_queue_frame(iaxs[callno]->owner, f);
03101       ast_channel_unlock(iaxs[callno]->owner);
03102    }
03103    return 0;
03104 }
03105 
03106 /*!
03107  * \brief Queue a hangup frame on the ast_channel owner
03108  *
03109  * This function queues a hangup frame on the owner of the IAX2 pvt struct that
03110  * is active for the given call number.
03111  *
03112  * \pre Assumes lock for callno is already held.
03113  *
03114  * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
03115  * was valid before calling it, it may no longer be valid after calling it.
03116  * This function may unlock and lock the mutex associated with this callno,
03117  * meaning that another thread may grab it and destroy the call.
03118  */
03119 static int iax2_queue_hangup(int callno)
03120 {
03121    iax2_lock_owner(callno);
03122    if (iaxs[callno] && iaxs[callno]->owner) {
03123       ast_queue_hangup(iaxs[callno]->owner);
03124       ast_channel_unlock(iaxs[callno]->owner);
03125    }
03126    return 0;
03127 }
03128 
03129 /*!
03130  * \brief Queue a control frame on the ast_channel owner
03131  *
03132  * This function queues a control frame on the owner of the IAX2 pvt struct that
03133  * is active for the given call number.
03134  *
03135  * \pre Assumes lock for callno is already held.
03136  *
03137  * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
03138  * was valid before calling it, it may no longer be valid after calling it.
03139  * This function may unlock and lock the mutex associated with this callno,
03140  * meaning that another thread may grab it and destroy the call.
03141  */
03142 static int iax2_queue_control_data(int callno, 
03143    enum ast_control_frame_type control, const void *data, size_t datalen)
03144 {
03145    iax2_lock_owner(callno);
03146    if (iaxs[callno] && iaxs[callno]->owner) {
03147       ast_queue_control_data(iaxs[callno]->owner, control, data, datalen);
03148       ast_channel_unlock(iaxs[callno]->owner);
03149    }
03150    return 0;
03151 }
03152 static void destroy_firmware(struct iax_firmware *cur)
03153 {
03154    /* Close firmware */
03155    if (cur->fwh) {
03156       munmap((void*)cur->fwh, ntohl(cur->fwh->datalen) + sizeof(*(cur->fwh)));
03157    }
03158    close(cur->fd);
03159    ast_free(cur);
03160 }
03161 
03162 static int try_firmware(char *s)
03163 {
03164    struct stat stbuf;
03165    struct iax_firmware *cur = NULL;
03166    int ifd, fd, res, len, chunk;
03167    struct ast_iax2_firmware_header *fwh, fwh2;
03168    struct MD5Context md5;
03169    unsigned char sum[16], buf[1024];
03170    char *s2, *last;
03171 
03172    s2 = ast_alloca(strlen(s) + 100);
03173 
03174    last = strrchr(s, '/');
03175    if (last)
03176       last++;
03177    else
03178       last = s;
03179 
03180    snprintf(s2, strlen(s) + 100, "/var/tmp/%s-%ld", last, (unsigned long)ast_random());
03181 
03182    if (stat(s, &stbuf) < 0) {
03183       ast_log(LOG_WARNING, "Failed to stat '%s': %s\n", s, strerror(errno));
03184       return -1;
03185    }
03186 
03187    /* Make sure it's not a directory */
03188    if (S_ISDIR(stbuf.st_mode))
03189       return -1;
03190    ifd = open(s, O_RDONLY);
03191    if (ifd < 0) {
03192       ast_log(LOG_WARNING, "Cannot open '%s': %s\n", s, strerror(errno));
03193       return -1;
03194    }
03195    fd = open(s2, O_RDWR | O_CREAT | O_EXCL, AST_FILE_MODE);
03196    if (fd < 0) {
03197       ast_log(LOG_WARNING, "Cannot open '%s' for writing: %s\n", s2, strerror(errno));
03198       close(ifd);
03199       return -1;
03200    }
03201    /* Unlink our newly created file */
03202    unlink(s2);
03203    
03204    /* Now copy the firmware into it */
03205    len = stbuf.st_size;
03206    while(len) {
03207       chunk = len;
03208       if (chunk > sizeof(buf))
03209          chunk = sizeof(buf);
03210       res = read(ifd, buf, chunk);
03211       if (res != chunk) {
03212          ast_log(LOG_WARNING, "Only read %d of %d bytes of data :(: %s\n", res, chunk, strerror(errno));
03213          close(ifd);
03214          close(fd);
03215          return -1;
03216       }
03217       res = write(fd, buf, chunk);
03218       if (res != chunk) {
03219          ast_log(LOG_WARNING, "Only write %d of %d bytes of data :(: %s\n", res, chunk, strerror(errno));
03220          close(ifd);
03221          close(fd);
03222          return -1;
03223       }
03224       len -= chunk;
03225    }
03226    close(ifd);
03227    /* Return to the beginning */
03228    lseek(fd, 0, SEEK_SET);
03229    if ((res = read(fd, &fwh2, sizeof(fwh2))) != sizeof(fwh2)) {
03230       ast_log(LOG_WARNING, "Unable to read firmware header in '%s'\n", s);
03231       close(fd);
03232       return -1;
03233    }
03234    if (ntohl(fwh2.magic) != IAX_FIRMWARE_MAGIC) {
03235       ast_log(LOG_WARNING, "'%s' is not a valid firmware file\n", s);
03236       close(fd);
03237       return -1;
03238    }
03239    if (ntohl(fwh2.datalen) != (stbuf.st_size - sizeof(fwh2))) {
03240       ast_log(LOG_WARNING, "Invalid data length in firmware '%s'\n", s);
03241       close(fd);
03242       return -1;
03243    }
03244    if (fwh2.devname[sizeof(fwh2.devname) - 1] || ast_strlen_zero((char *)fwh2.devname)) {
03245       ast_log(LOG_WARNING, "No or invalid device type specified for '%s'\n", s);
03246       close(fd);
03247       return -1;
03248    }
03249    fwh = (struct ast_iax2_firmware_header*)mmap(NULL, stbuf.st_size, PROT_READ, MAP_PRIVATE, fd, 0); 
03250    if (fwh == MAP_FAILED) {
03251       ast_log(LOG_WARNING, "mmap failed: %s\n", strerror(errno));
03252       close(fd);
03253       return -1;
03254    }
03255    MD5Init(&md5);
03256    MD5Update(&md5, fwh->data, ntohl(fwh->datalen));
03257    MD5Final(sum, &md5);
03258    if (memcmp(sum, fwh->chksum, sizeof(sum))) {
03259       ast_log(LOG_WARNING, "Firmware file '%s' fails checksum\n", s);
03260       munmap((void*)fwh, stbuf.st_size);
03261       close(fd);
03262       return -1;
03263    }
03264 
03265    AST_LIST_TRAVERSE(&firmwares, cur, list) {
03266       if (!strcmp((char *)cur->fwh->devname, (char *)fwh->devname)) {
03267          /* Found a candidate */
03268          if (cur->dead || (ntohs(cur->fwh->version) < ntohs(fwh->version)))
03269             /* The version we have on loaded is older, load this one instead */
03270             break;
03271          /* This version is no newer than what we have.  Don't worry about it.
03272             We'll consider it a proper load anyhow though */
03273          munmap((void*)fwh, stbuf.st_size);
03274          close(fd);
03275          return 0;
03276       }
03277    }
03278    
03279    if (!cur && ((cur = ast_calloc(1, sizeof(*cur))))) {
03280       cur->fd = -1;
03281       AST_LIST_INSERT_TAIL(&firmwares, cur, list);
03282    }
03283    
03284    if (cur) {
03285       if (cur->fwh)
03286          munmap((void*)cur->fwh, cur->mmaplen);
03287       if (cur->fd > -1)
03288          close(cur->fd);
03289       cur->fwh = fwh;
03290       cur->fd = fd;
03291       cur->mmaplen = stbuf.st_size;
03292       cur->dead = 0;
03293    }
03294    
03295    return 0;
03296 }
03297 
03298 static int iax_check_version(char *dev)
03299 {
03300    int res = 0;
03301    struct iax_firmware *cur = NULL;
03302 
03303    if (ast_strlen_zero(dev))
03304       return 0;
03305 
03306    AST_LIST_LOCK(&firmwares);
03307    AST_LIST_TRAVERSE(&firmwares, cur, list) {
03308       if (!strcmp(dev, (char *)cur->fwh->devname)) {
03309          res = ntohs(cur->fwh->version);
03310          break;
03311       }
03312    }
03313    AST_LIST_UNLOCK(&firmwares);
03314 
03315    return res;
03316 }
03317 
03318 static int iax_firmware_append(struct iax_ie_data *ied, const unsigned char *dev, unsigned int desc)
03319 {
03320    int res = -1;
03321    unsigned int bs = desc & 0xff;
03322    unsigned int start = (desc >> 8) & 0xffffff;
03323    unsigned int bytes;
03324    struct iax_firmware *cur;
03325 
03326    if (ast_strlen_zero((char *)dev) || !bs)
03327       return -1;
03328 
03329    start *= bs;
03330    
03331    AST_LIST_LOCK(&firmwares);
03332    AST_LIST_TRAVERSE(&firmwares, cur, list) {
03333       if (strcmp((char *)dev, (char *)cur->fwh->devname))
03334          continue;
03335       iax_ie_append_int(ied, IAX_IE_FWBLOCKDESC, desc);
03336       if (start < ntohl(cur->fwh->datalen)) {
03337          bytes = ntohl(cur->fwh->datalen) - start;
03338          if (bytes > bs)
03339             bytes = bs;
03340          iax_ie_append_raw(ied, IAX_IE_FWBLOCKDATA, cur->fwh->data + start, bytes);
03341       } else {
03342          bytes = 0;
03343          iax_ie_append(ied, IAX_IE_FWBLOCKDATA);
03344       }
03345       if (bytes == bs)
03346          res = 0;
03347       else
03348          res = 1;
03349       break;
03350    }
03351    AST_LIST_UNLOCK(&firmwares);
03352 
03353    return res;
03354 }
03355 
03356 
03357 static void reload_firmware(int unload)
03358 {
03359    struct iax_firmware *cur = NULL;
03360    DIR *fwd;
03361    struct dirent *de;
03362    char dir[256], fn[256];
03363 
03364    AST_LIST_LOCK(&firmwares);
03365 
03366    /* Mark all as dead */
03367    AST_LIST_TRAVERSE(&firmwares, cur, list)
03368       cur->dead = 1;
03369 
03370    /* Now that we have marked them dead... load new ones */
03371    if (!unload) {
03372       snprintf(dir, sizeof(dir), "%s/firmware/iax", ast_config_AST_DATA_DIR);
03373       fwd = opendir(dir);
03374       if (fwd) {
03375          while((de = readdir(fwd))) {
03376             if (de->d_name[0] != '.') {
03377                snprintf(fn, sizeof(fn), "%s/%s", dir, de->d_name);
03378                if (!try_firmware(fn)) {
03379                   ast_verb(2, "Loaded firmware '%s'\n", de->d_name);
03380                }
03381             }
03382          }
03383          closedir(fwd);
03384       } else 
03385          ast_log(LOG_WARNING, "Error opening firmware directory '%s': %s\n", dir, strerror(errno));
03386    }
03387 
03388    /* Clean up leftovers */
03389    AST_LIST_TRAVERSE_SAFE_BEGIN(&firmwares, cur, list) {
03390       if (!cur->dead)
03391          continue;
03392       AST_LIST_REMOVE_CURRENT(list);
03393       destroy_firmware(cur);
03394    }
03395    AST_LIST_TRAVERSE_SAFE_END;
03396 
03397    AST_LIST_UNLOCK(&firmwares);
03398 }
03399 
03400 /*!
03401  * \note This function assumes that iaxsl[callno] is locked when called.
03402  *
03403  * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
03404  * was valid before calling it, it may no longer be valid after calling it.
03405  * This function calls iax2_queue_frame(), which may unlock and lock the mutex 
03406  * associated with this callno, meaning that another thread may grab it and destroy the call.
03407  */
03408 static int __do_deliver(void *data)
03409 {
03410    /* Just deliver the packet by using queueing.  This is called by
03411      the IAX thread with the iaxsl lock held. */
03412    struct iax_frame *fr = data;
03413    fr->retrans = -1;
03414    ast_clear_flag(&fr->af, AST_FRFLAG_HAS_TIMING_INFO);
03415    if (iaxs[fr->callno] && !ast_test_flag64(iaxs[fr->callno], IAX_ALREADYGONE))
03416       iax2_queue_frame(fr->callno, &fr->af);
03417    /* Free our iax frame */
03418    iax2_frame_free(fr);
03419    /* And don't run again */
03420    return 0;
03421 }
03422 
03423 static int handle_error(void)
03424 {
03425    /* XXX Ideally we should figure out why an error occurred and then abort those
03426       rather than continuing to try.  Unfortunately, the published interface does
03427       not seem to work XXX */
03428 #if 0
03429    struct sockaddr_in *sin;
03430    int res;
03431    struct msghdr m;
03432    struct sock_extended_err e;
03433    m.msg_name = NULL;
03434    m.msg_namelen = 0;
03435    m.msg_iov = NULL;
03436    m.msg_control = &e;
03437    m.msg_controllen = sizeof(e);
03438    m.msg_flags = 0;
03439    res = recvmsg(netsocket, &m, MSG_ERRQUEUE);
03440    if (res < 0)
03441       ast_log(LOG_WARNING, "Error detected, but unable to read error: %s\n", strerror(errno));
03442    else {
03443       if (m.msg_controllen) {
03444          sin = (struct sockaddr_in *)SO_EE_OFFENDER(&e);
03445          if (sin) 
03446             ast_log(LOG_WARNING, "Receive error from %s\n", ast_inet_ntoa(sin->sin_addr));
03447          else
03448             ast_log(LOG_WARNING, "No address detected??\n");
03449       } else {
03450          ast_log(LOG_WARNING, "Local error: %s\n", strerror(e.ee_errno));
03451       }
03452    }
03453 #endif
03454    return 0;
03455 }
03456 
03457 static int transmit_trunk(struct iax_frame *f, struct sockaddr_in *sin, int sockfd)
03458 {
03459    int res;
03460    res = sendto(sockfd, f->data, f->datalen, 0,(struct sockaddr *)sin,
03461                sizeof(*sin));
03462    if (res < 0) {
03463       ast_debug(1, "Received error: %s\n", strerror(errno));
03464       handle_error();
03465    } else
03466       res = 0;
03467    return res;
03468 }
03469 
03470 static int send_packet(struct iax_frame *f)
03471 {
03472    int res;
03473    int callno = f->callno;
03474 
03475    /* Don't send if there was an error, but return error instead */
03476    if (!callno || !iaxs[callno] || iaxs[callno]->error)
03477        return -1;
03478 
03479    /* Called with iaxsl held */
03480    if (iaxdebug)
03481       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));
03482 
03483    if (f->transfer) {
03484       iax_outputframe(f, NULL, 0, &iaxs[callno]->transfer, f->datalen - sizeof(struct ast_iax2_full_hdr));
03485       res = sendto(iaxs[callno]->sockfd, f->data, f->datalen, 0,(struct sockaddr *)&iaxs[callno]->transfer, sizeof(iaxs[callno]->transfer));
03486    } else {
03487       iax_outputframe(f, NULL, 0, &iaxs[callno]->addr, f->datalen - sizeof(struct ast_iax2_full_hdr));
03488       res = sendto(iaxs[callno]->sockfd, f->data, f->datalen, 0,(struct sockaddr *)&iaxs[callno]->addr, sizeof(iaxs[callno]->addr));
03489    }
03490    if (res < 0) {
03491       if (iaxdebug)
03492          ast_debug(1, "Received error: %s\n", strerror(errno));
03493       handle_error();
03494    } else
03495       res = 0;
03496 
03497    return res;
03498 }
03499 
03500 /*!
03501  * \note Since this function calls iax2_queue_hangup(), the pvt struct
03502  *       for the given call number may disappear during its execution.
03503  */
03504 static int iax2_predestroy(int callno)
03505 {
03506    struct ast_channel *c = NULL;
03507    struct chan_iax2_pvt *pvt = iaxs[callno];
03508 
03509    if (!pvt)
03510       return -1;
03511 
03512    if (!ast_test_flag64(pvt, IAX_ALREADYGONE)) {
03513       iax2_destroy_helper(pvt);
03514       ast_set_flag64(pvt, IAX_ALREADYGONE);
03515    }
03516 
03517    if ((c = pvt->owner)) {
03518       ast_channel_tech_pvt_set(c, NULL);
03519       iax2_queue_hangup(callno);
03520       pvt->owner = NULL;
03521       ast_module_unref(ast_module_info->self);
03522    }
03523 
03524    return 0;
03525 }
03526 
03527 static void iax2_destroy(int callno)
03528 {
03529    struct chan_iax2_pvt *pvt = NULL;
03530    struct ast_channel *owner = NULL;
03531 
03532 retry:
03533    if ((pvt = iaxs[callno])) {
03534 #if 0
03535       /* iax2_destroy_helper gets called from this function later on.  When
03536        * called twice, we get the (previously) familiar FRACK! errors in
03537        * devmode, from the scheduler.  An alternative to this approach is to
03538        * reset the scheduler entries to -1 when they're deleted in
03539        * iax2_destroy_helper().  That approach was previously decided to be
03540        * "wrong" because "the memory is going to be deallocated anyway.  Why
03541        * should we be resetting those values?" */
03542       iax2_destroy_helper(pvt);
03543 #endif
03544    }
03545 
03546    owner = pvt ? pvt->owner : NULL;
03547 
03548    if (owner) {
03549       if (ast_channel_trylock(owner)) {
03550          ast_debug(3, "Avoiding IAX destroy deadlock\n");
03551          DEADLOCK_AVOIDANCE(&iaxsl[callno]);
03552          goto retry;
03553       }
03554    }
03555 
03556    if (!owner) {
03557       iaxs[callno] = NULL;
03558    }
03559 
03560    if (pvt) {
03561       if (!owner) {
03562          pvt->owner = NULL;
03563       } else {
03564          /* If there's an owner, prod it to give up */
03565          /* It is ok to use ast_queue_hangup() here instead of iax2_queue_hangup()
03566           * because we already hold the owner channel lock. */
03567          ast_queue_hangup(owner);
03568       }
03569 
03570       if (pvt->peercallno) {
03571          remove_by_peercallno(pvt);
03572       }
03573 
03574       if (pvt->transfercallno) {
03575          remove_by_transfercallno(pvt);
03576       }
03577 
03578       if (!owner) {
03579          ao2_ref(pvt, -1);
03580          pvt = NULL;
03581       }
03582    }
03583 
03584    if (owner) {
03585       ast_channel_unlock(owner);
03586    }
03587 }
03588 
03589 static int update_packet(struct iax_frame *f)
03590 {
03591    /* Called with iaxsl lock held, and iaxs[callno] non-NULL */
03592    struct ast_iax2_full_hdr *fh = f->data;
03593    struct ast_frame af;
03594 
03595    /* if frame is encrypted. decrypt before updating it. */
03596    if (f->encmethods) {
03597       decode_frame(&f->mydcx, fh, &af, &f->datalen);
03598    }
03599    /* Mark this as a retransmission */
03600    fh->dcallno = ntohs(IAX_FLAG_RETRANS | f->dcallno);
03601    /* Update iseqno */
03602    f->iseqno = iaxs[f->callno]->iseqno;
03603    fh->iseqno = f->iseqno;
03604 
03605    /* Now re-encrypt the frame */
03606    if (f->encmethods) {
03607    /* since this is a retransmit frame, create a new random padding
03608     * before re-encrypting. */
03609       build_rand_pad(f->semirand, sizeof(f->semirand));
03610       encrypt_frame(&f->ecx, fh, f->semirand, &f->datalen);
03611    }
03612    return 0;
03613 }
03614 
03615 static int attempt_transmit(const void *data);
03616 static void __attempt_transmit(const void *data)
03617 {
03618    /* Attempt to transmit the frame to the remote peer...
03619       Called without iaxsl held. */
03620    struct iax_frame *f = (struct iax_frame *)data;
03621    int freeme = 0;
03622    int callno = f->callno;
03623 
03624    /* Make sure this call is still active */
03625    if (callno) 
03626       ast_mutex_lock(&iaxsl[callno]);
03627    if (callno && iaxs[callno]) {
03628       if (f->retries < 0) {
03629          /* Already ACK'd */
03630          freeme = 1;
03631       } else if (f->retries >= max_retries) {
03632          /* Too many attempts.  Record an error. */
03633          if (f->transfer) {
03634             /* Transfer timeout */
03635             send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_TXREJ, 0, NULL, 0, -1);
03636          } else if (f->final) {
03637             iax2_destroy(callno);
03638          } else {
03639             if (iaxs[callno]->owner) {
03640                ast_log(LOG_WARNING, "Max retries exceeded to host %s on %s (type = %d, subclass = %u, ts=%d, seqno=%d)\n",
03641                   ast_inet_ntoa(iaxs[f->callno]->addr.sin_addr),
03642                   ast_channel_name(iaxs[f->callno]->owner),
03643                   f->af.frametype,
03644                   f->af.subclass.integer,
03645                   f->ts,
03646                   f->oseqno);
03647             }
03648             iaxs[callno]->error = ETIMEDOUT;
03649             if (iaxs[callno]->owner) {
03650                struct ast_frame fr = { AST_FRAME_CONTROL, { AST_CONTROL_HANGUP }, .data.uint32 = AST_CAUSE_DESTINATION_OUT_OF_ORDER };
03651                /* Hangup the fd */
03652                iax2_queue_frame(callno, &fr); /* XXX */
03653                /* Remember, owner could disappear */
03654                if (iaxs[callno] && iaxs[callno]->owner)
03655                   ast_channel_hangupcause_set(iaxs[callno]->owner, AST_CAUSE_DESTINATION_OUT_OF_ORDER);
03656             } else {
03657                if (iaxs[callno]->reg) {
03658                   memset(&iaxs[callno]->reg->us, 0, sizeof(iaxs[callno]->reg->us));
03659                   iaxs[callno]->reg->regstate = REG_STATE_TIMEOUT;
03660                   iaxs[callno]->reg->refresh = IAX_DEFAULT_REG_EXPIRE;
03661                }
03662                iax2_destroy(callno);
03663             }
03664          }
03665          freeme = 1;
03666       } else {
03667          /* Update it if it needs it */
03668          update_packet(f);
03669          /* Attempt transmission */
03670          send_packet(f);
03671          f->retries++;
03672          /* Try again later after 10 times as long */
03673          f->retrytime *= 10;
03674          if (f->retrytime > MAX_RETRY_TIME)
03675             f->retrytime = MAX_RETRY_TIME;
03676          /* Transfer messages max out at one second */
03677          if (f->transfer && (f->retrytime > 1000))
03678             f->retrytime = 1000;
03679          f->retrans = iax2_sched_add(sched, f->retrytime, attempt_transmit, f);
03680       }
03681    } else {
03682       /* Make sure it gets freed */
03683       f->retries = -1;
03684       freeme = 1;
03685    }
03686 
03687    if (freeme) {
03688       /* Don't attempt delivery, just remove it from the queue */
03689       AST_LIST_REMOVE(&frame_queue[callno], f, list);
03690       ast_mutex_unlock(&iaxsl[callno]);
03691       f->retrans = -1; /* this is safe because this is the scheduled function */
03692       /* Free the IAX frame */
03693       iax2_frame_free(f);
03694    } else if (callno) {
03695       ast_mutex_unlock(&iaxsl[callno]);
03696    }
03697 }
03698 
03699 static int attempt_transmit(const void *data)
03700 {
03701 #ifdef SCHED_MULTITHREADED
03702    if (schedule_action(__attempt_transmit, data))
03703 #endif      
03704       __attempt_transmit(data);
03705    return 0;
03706 }
03707 
03708 static char *handle_cli_iax2_prune_realtime(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
03709 {
03710    struct iax2_peer *peer = NULL;
03711    struct iax2_user *user = NULL;
03712    static const char * const choices[] = { "all", NULL };
03713    char *cmplt;
03714 
03715    switch (cmd) {
03716    case CLI_INIT:
03717       e->command = "iax2 prune realtime";
03718       e->usage =
03719          "Usage: iax2 prune realtime [<peername>|all]\n"
03720          "       Prunes object(s) from the cache\n";
03721       return NULL;
03722    case CLI_GENERATE:
03723       if (a->pos == 3) {
03724          cmplt = ast_cli_complete(a->word, choices, a->n);
03725          if (!cmplt)
03726             cmplt = complete_iax2_peers(a->line, a->word, a->pos, a->n - sizeof(choices), IAX_RTCACHEFRIENDS);
03727          return cmplt;
03728       }
03729       return NULL;
03730    }
03731    if (a->argc != 4)
03732       return CLI_SHOWUSAGE;
03733    if (!strcmp(a->argv[3], "all")) {
03734       prune_users();
03735       prune_peers();
03736       ast_cli(a->fd, "Cache flushed successfully.\n");
03737       return CLI_SUCCESS;
03738    }
03739    peer = find_peer(a->argv[3], 0);
03740    user = find_user(a->argv[3]);
03741    if (peer || user) {
03742       if (peer) {
03743          if (ast_test_flag64(peer, IAX_RTCACHEFRIENDS)) {
03744             ast_set_flag64(peer, IAX_RTAUTOCLEAR);
03745             expire_registry(peer_ref(peer));
03746             ast_cli(a->fd, "Peer %s was removed from the cache.\n", a->argv[3]);
03747          } else {
03748             ast_cli(a->fd, "Peer %s is not eligible for this operation.\n", a->argv[3]);
03749          }
03750          peer_unref(peer);
03751       }
03752       if (user) {
03753          if (ast_test_flag64(user, IAX_RTCACHEFRIENDS)) {
03754             ast_set_flag64(user, IAX_RTAUTOCLEAR);
03755             ast_cli(a->fd, "User %s was removed from the cache.\n", a->argv[3]);
03756          } else {
03757             ast_cli(a->fd, "User %s is not eligible for this operation.\n", a->argv[3]);
03758          }
03759          ao2_unlink(users,user);
03760          user_unref(user);
03761       }
03762    } else {
03763       ast_cli(a->fd, "%s was not found in the cache.\n", a->argv[3]);
03764    }
03765 
03766    return CLI_SUCCESS;
03767 }
03768 
03769 static char *handle_cli_iax2_test_losspct(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
03770 {
03771    switch (cmd) {
03772    case CLI_INIT:
03773       e->command = "iax2 test losspct";
03774       e->usage =
03775          "Usage: iax2 test losspct <percentage>\n"
03776          "       For testing, throws away <percentage> percent of incoming packets\n";
03777       return NULL;
03778    case CLI_GENERATE:
03779       return NULL;
03780    }
03781    if (a->argc != 4)
03782       return CLI_SHOWUSAGE;
03783 
03784    test_losspct = atoi(a->argv[3]);
03785 
03786    return CLI_SUCCESS;
03787 }
03788 
03789 #ifdef IAXTESTS
03790 static char *handle_cli_iax2_test_late(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
03791 {
03792    switch (cmd) {
03793    case CLI_INIT:
03794       e->command = "iax2 test late";
03795       e->usage =
03796          "Usage: iax2 test late <ms>\n"
03797          "       For testing, count the next frame as <ms> ms late\n";
03798       return NULL;
03799    case CLI_GENERATE:
03800       return NULL;
03801    }
03802 
03803    if (a->argc != 4)
03804       return CLI_SHOWUSAGE;
03805 
03806    test_late = atoi(a->argv[3]);
03807 
03808    return CLI_SUCCESS;
03809 }
03810 
03811 static char *handle_cli_iax2_test_resync(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
03812 {
03813    switch (cmd) {
03814    case CLI_INIT:
03815       e->command = "iax2 test resync";
03816       e->usage =
03817          "Usage: iax2 test resync <ms>\n"
03818          "       For testing, adjust all future frames by <ms> ms\n";
03819       return NULL;
03820    case CLI_GENERATE:
03821       return NULL;
03822    }
03823 
03824    if (a->argc != 4)
03825       return CLI_SHOWUSAGE;
03826 
03827    test_resync = atoi(a->argv[3]);
03828 
03829    return CLI_SUCCESS;
03830 }
03831 
03832 static char *handle_cli_iax2_test_jitter(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
03833 {
03834    switch (cmd) {
03835    case CLI_INIT:
03836       e->command = "iax2 test jitter";
03837       e->usage =
03838          "Usage: iax2 test jitter <ms> <pct>\n"
03839          "       For testing, simulate maximum jitter of +/- <ms> on <pct>\n"
03840          "       percentage of packets. If <pct> is not specified, adds\n"
03841          "       jitter to all packets.\n";
03842       return NULL;
03843    case CLI_GENERATE:
03844       return NULL;
03845    }
03846 
03847    if (a->argc < 4 || a->argc > 5)
03848       return CLI_SHOWUSAGE;
03849 
03850    test_jit = atoi(a->argv[3]);
03851    if (a->argc == 5)
03852       test_jitpct = atoi(a->argv[4]);
03853 
03854    return CLI_SUCCESS;
03855 }
03856 #endif /* IAXTESTS */
03857 
03858 /*! \brief  peer_status: Report Peer status in character string */
03859 /*    returns 1 if peer is online, -1 if unmonitored */
03860 static int peer_status(struct iax2_peer *peer, char *status, int statuslen)
03861 {
03862    int res = 0;
03863    if (peer->maxms) {
03864       if (peer->lastms < 0) {
03865          ast_copy_string(status, "UNREACHABLE", statuslen);
03866       } else if (peer->lastms > peer->maxms) {
03867          snprintf(status, statuslen, "LAGGED (%d ms)", peer->lastms);
03868          res = 1;
03869       } else if (peer->lastms) {
03870          snprintf(status, statuslen, "OK (%d ms)", peer->lastms);
03871          res = 1;
03872       } else {
03873          ast_copy_string(status, "UNKNOWN", statuslen);
03874       }
03875    } else { 
03876       ast_copy_string(status, "Unmonitored", statuslen);
03877       res = -1;
03878    }
03879    return res;
03880 }
03881 
03882 /*! \brief Show one peer in detail */
03883 static char *handle_cli_iax2_show_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
03884 {
03885    char status[30];
03886    char cbuf[256];
03887    struct iax2_peer *peer;
03888    char codec_buf[512];
03889    struct ast_str *encmethods = ast_str_alloca(256);
03890    int x = 0, load_realtime = 0;
03891 
03892    switch (cmd) {
03893    case CLI_INIT:
03894       e->command = "iax2 show peer";
03895       e->usage =
03896          "Usage: iax2 show peer <name>\n"
03897          "       Display details on specific IAX peer\n";
03898       return NULL;
03899    case CLI_GENERATE:
03900       if (a->pos == 3)
03901          return complete_iax2_peers(a->line, a->word, a->pos, a->n, 0);
03902       return NULL;
03903    }
03904 
03905    if (a->argc < 4)
03906       return CLI_SHOWUSAGE;
03907 
03908    load_realtime = (a->argc == 5 && !strcmp(a->argv[4], "load")) ? 1 : 0;
03909 
03910    peer = find_peer(a->argv[3], load_realtime);
03911    if (peer) {
03912       struct sockaddr_in peer_addr;
03913 
03914       ast_sockaddr_to_sin(&peer->addr, &peer_addr);
03915 
03916       encmethods_to_str(peer->encmethods, &encmethods);
03917       ast_cli(a->fd, "\n\n");
03918       ast_cli(a->fd, "  * Name       : %s\n", peer->name);
03919       ast_cli(a->fd, "  Description  : %s\n", peer->description);
03920       ast_cli(a->fd, "  Secret       : %s\n", ast_strlen_zero(peer->secret) ? "<Not set>" : "<Set>");
03921       ast_cli(a->fd, "  Context      : %s\n", peer->context);
03922       ast_cli(a->fd, "  Parking lot  : %s\n", peer->parkinglot);
03923       ast_cli(a->fd, "  Mailbox      : %s\n", peer->mailbox);
03924       ast_cli(a->fd, "  Dynamic      : %s\n", ast_test_flag64(peer, IAX_DYNAMIC) ? "Yes" : "No");
03925       ast_cli(a->fd, "  Callnum limit: %d\n", peer->maxcallno);
03926       ast_cli(a->fd, "  Calltoken req: %s\n", (peer->calltoken_required == CALLTOKEN_YES) ? "Yes" : ((peer->calltoken_required == CALLTOKEN_AUTO) ? "Auto" : "No"));
03927       ast_cli(a->fd, "  Trunk        : %s\n", ast_test_flag64(peer, IAX_TRUNK) ? "Yes" : "No");
03928       ast_cli(a->fd, "  Encryption   : %s\n", peer->encmethods ? ast_str_buffer(encmethods) : "No");
03929       ast_cli(a->fd, "  Callerid     : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, "<unspecified>"));
03930       ast_cli(a->fd, "  Expire       : %d\n", peer->expire);
03931       ast_cli(a->fd, "  ACL          : %s\n", (ast_acl_list_is_empty(peer->acl) ? "No" : "Yes"));
03932       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));
03933       ast_cli(a->fd, "  Defaddr->IP  : %s Port %d\n", ast_inet_ntoa(peer->defaddr.sin_addr), ntohs(peer->defaddr.sin_port));
03934       ast_cli(a->fd, "  Username     : %s\n", peer->username);
03935       ast_cli(a->fd, "  Codecs       : ");
03936       iax2_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, peer->capability);
03937       ast_cli(a->fd, "%s\n", codec_buf);
03938 
03939       ast_cli(a->fd, "  Codec Order  : (");
03940       for(x = 0; x < AST_CODEC_PREF_SIZE; x++) {
03941          struct ast_format tmpfmt;
03942          if(!(ast_codec_pref_index(&peer->prefs, x, &tmpfmt)))
03943             break;
03944          ast_cli(a->fd, "%s", ast_getformatname(&tmpfmt));
03945          if(x < 31 && ast_codec_pref_index(&peer->prefs, x+1, &tmpfmt))
03946             ast_cli(a->fd, "|");
03947       }
03948 
03949       if (!x)
03950          ast_cli(a->fd, "none");
03951       ast_cli(a->fd, ")\n");
03952 
03953       ast_cli(a->fd, "  Status       : ");
03954       peer_status(peer, status, sizeof(status));   
03955       ast_cli(a->fd, "%s\n",status);
03956       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");
03957       ast_cli(a->fd, "\n");
03958       peer_unref(peer);
03959    } else {
03960       ast_cli(a->fd, "Peer %s not found.\n", a->argv[3]);
03961       ast_cli(a->fd, "\n");
03962    }
03963 
03964    return CLI_SUCCESS;
03965 }
03966 
03967 static char *complete_iax2_peers(const char *line, const char *word, int pos, int state, uint64_t flags)
03968 {
03969    int which = 0;
03970    struct iax2_peer *peer;
03971    char *res = NULL;
03972    int wordlen = strlen(word);
03973    struct ao2_iterator i;
03974 
03975    i = ao2_iterator_init(peers, 0);
03976    while ((peer = ao2_iterator_next(&i))) {
03977       if (!strncasecmp(peer->name, word, wordlen) && ++which > state
03978          && (!flags || ast_test_flag64(peer, flags))) {
03979          res = ast_strdup(peer->name);
03980          peer_unref(peer);
03981          break;
03982       }
03983       peer_unref(peer);
03984    }
03985    ao2_iterator_destroy(&i);
03986 
03987    return res;
03988 }
03989 
03990 static char *handle_cli_iax2_show_stats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
03991 {
03992    struct iax_frame *cur;
03993    int cnt = 0, dead = 0, final = 0, i = 0;
03994 
03995    switch (cmd) {
03996    case CLI_INIT:
03997       e->command = "iax2 show stats";
03998       e->usage =
03999          "Usage: iax2 show stats\n"
04000          "       Display statistics on IAX channel driver.\n";
04001       return NULL;
04002    case CLI_GENERATE:
04003       return NULL;
04004    }
04005 
04006    if (a->argc != 3)
04007       return CLI_SHOWUSAGE;
04008 
04009    for (i = 0; i < ARRAY_LEN(frame_queue); i++) {
04010       ast_mutex_lock(&iaxsl[i]);
04011       AST_LIST_TRAVERSE(&frame_queue[i], cur, list) {
04012          if (cur->retries < 0)
04013             dead++;
04014          if (cur->final)
04015             final++;
04016          cnt++;
04017       }
04018       ast_mutex_unlock(&iaxsl[i]);
04019    }
04020 
04021    ast_cli(a->fd, "    IAX Statistics\n");
04022    ast_cli(a->fd, "---------------------\n");
04023    ast_cli(a->fd, "Outstanding frames: %d (%d ingress, %d egress)\n", iax_get_frames(), iax_get_iframes(), iax_get_oframes());
04024    ast_cli(a->fd, "%d timed and %d untimed transmits; MTU %d/%d/%d\n", trunk_timed, trunk_untimed,
04025       trunk_maxmtu, trunk_nmaxmtu, global_max_trunk_mtu);
04026    ast_cli(a->fd, "Packets in transmit queue: %d dead, %d final, %d total\n\n", dead, final, cnt);
04027 
04028    trunk_timed = trunk_untimed = 0;
04029    if (trunk_maxmtu > trunk_nmaxmtu)
04030       trunk_nmaxmtu = trunk_maxmtu;
04031 
04032    return CLI_SUCCESS;
04033 }
04034 
04035 /*! \brief Set trunk MTU from CLI */
04036 static char *handle_cli_iax2_set_mtu(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
04037 {
04038    int mtuv;
04039 
04040    switch (cmd) {
04041    case CLI_INIT:
04042       e->command = "iax2 set mtu";
04043       e->usage =
04044          "Usage: iax2 set mtu <value>\n"
04045          "       Set the system-wide IAX IP mtu to <value> bytes net or\n"
04046          "       zero to disable. Disabling means that the operating system\n"
04047          "       must handle fragmentation of UDP packets when the IAX2 trunk\n"
04048          "       packet exceeds the UDP payload size. This is substantially\n"
04049          "       below the IP mtu. Try 1240 on ethernets. Must be 172 or\n"
04050          "       greater for G.711 samples.\n";
04051       return NULL;
04052    case CLI_GENERATE:
04053       return NULL;
04054    }
04055 
04056    if (a->argc != 4)
04057       return CLI_SHOWUSAGE; 
04058    if (strncasecmp(a->argv[3], "default", strlen(a->argv[3])) == 0)
04059       mtuv = MAX_TRUNK_MTU;
04060    else
04061       mtuv = atoi(a->argv[3]);
04062 
04063    if (mtuv == 0) {
04064       ast_cli(a->fd, "Trunk MTU control disabled (mtu was %d)\n", global_max_trunk_mtu); 
04065       global_max_trunk_mtu = 0; 
04066       return CLI_SUCCESS; 
04067    }
04068    if (mtuv < 172 || mtuv > 4000) {
04069       ast_cli(a->fd, "Trunk MTU must be between 172 and 4000\n"); 
04070       return CLI_SHOWUSAGE; 
04071    }
04072    ast_cli(a->fd, "Trunk MTU changed from %d to %d\n", global_max_trunk_mtu, mtuv); 
04073    global_max_trunk_mtu = mtuv; 
04074    return CLI_SUCCESS;
04075 }
04076 
04077 static char *handle_cli_iax2_show_cache(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
04078 {
04079    struct iax2_dpcache *dp = NULL;
04080    char tmp[1024], *pc = NULL;
04081    int s, x, y;
04082    struct timeval now = ast_tvnow();
04083 
04084    switch (cmd) {
04085    case CLI_INIT:
04086       e->command = "iax2 show cache";
04087       e->usage =
04088          "Usage: iax2 show cache\n"
04089          "       Display currently cached IAX Dialplan results.\n";
04090       return NULL;
04091    case CLI_GENERATE:
04092       return NULL;
04093    }
04094 
04095    AST_LIST_LOCK(&dpcache);
04096 
04097    ast_cli(a->fd, "%-20.20s %-12.12s %-9.9s %-8.8s %s\n", "Peer/Context", "Exten", "Exp.", "Wait.", "Flags");
04098 
04099    AST_LIST_TRAVERSE(&dpcache, dp, cache_list) {
04100       s = dp->expiry.tv_sec - now.tv_sec;
04101       tmp[0] = '\0';
04102       if (dp->flags & CACHE_FLAG_EXISTS)
04103          strncat(tmp, "EXISTS|", sizeof(tmp) - strlen(tmp) - 1);
04104       if (dp->flags & CACHE_FLAG_NONEXISTENT)
04105          strncat(tmp, "NONEXISTENT|", sizeof(tmp) - strlen(tmp) - 1);
04106       if (dp->flags & CACHE_FLAG_CANEXIST)
04107          strncat(tmp, "CANEXIST|", sizeof(tmp) - strlen(tmp) - 1);
04108       if (dp->flags & CACHE_FLAG_PENDING)
04109          strncat(tmp, "PENDING|", sizeof(tmp) - strlen(tmp) - 1);
04110       if (dp->flags & CACHE_FLAG_TIMEOUT)
04111          strncat(tmp, "TIMEOUT|", sizeof(tmp) - strlen(tmp) - 1);
04112       if (dp->flags & CACHE_FLAG_TRANSMITTED)
04113          strncat(tmp, "TRANSMITTED|", sizeof(tmp) - strlen(tmp) - 1);
04114       if (dp->flags & CACHE_FLAG_MATCHMORE)
04115          strncat(tmp, "MATCHMORE|", sizeof(tmp) - strlen(tmp) - 1);
04116       if (dp->flags & CACHE_FLAG_UNKNOWN)
04117          strncat(tmp, "UNKNOWN|", sizeof(tmp) - strlen(tmp) - 1);
04118       /* Trim trailing pipe */
04119       if (!ast_strlen_zero(tmp)) {
04120          tmp[strlen(tmp) - 1] = '\0';
04121       } else {
04122          ast_copy_string(tmp, "(none)", sizeof(tmp));
04123       }
04124       y = 0;
04125       pc = strchr(dp->peercontext, '@');
04126       if (!pc) {
04127          pc = dp->peercontext;
04128       } else {
04129          pc++;
04130       }
04131       for (x = 0; x < ARRAY_LEN(dp->waiters); x++) {
04132          if (dp->waiters[x] > -1)
04133             y++;
04134       }
04135       if (s > 0) {
04136          ast_cli(a->fd, "%-20.20s %-12.12s %-9d %-8d %s\n", pc, dp->exten, s, y, tmp);
04137       } else {
04138          ast_cli(a->fd, "%-20.20s %-12.12s %-9.9s %-8d %s\n", pc, dp->exten, "(expired)", y, tmp);
04139       }
04140    }
04141 
04142    AST_LIST_UNLOCK(&dpcache);
04143 
04144    return CLI_SUCCESS;
04145 }
04146 
04147 static unsigned int calc_rxstamp(struct chan_iax2_pvt *p, unsigned int offset);
04148 
04149 static void unwrap_timestamp(struct iax_frame *fr)
04150 {
04151    /* Video mini frames only encode the lower 15 bits of the session
04152     * timestamp, but other frame types (e.g. audio) encode 16 bits. */
04153    const int ts_shift = (fr->af.frametype == AST_FRAME_VIDEO) ? 15 : 16;
04154    const int lower_mask = (1 << ts_shift) - 1;
04155    const int upper_mask = ~lower_mask;
04156    const int last_upper = iaxs[fr->callno]->last & upper_mask;
04157 
04158    if ( (fr->ts & upper_mask) == last_upper ) {
04159       const int x = fr->ts - iaxs[fr->callno]->last;
04160       const int threshold = (ts_shift == 15) ? 25000 : 50000;
04161 
04162       if (x < -threshold) {
04163          /* Sudden big jump backwards in timestamp:
04164             What likely happened here is that miniframe timestamp has circled but we haven't
04165             gotten the update from the main packet.  We'll just pretend that we did, and
04166             update the timestamp appropriately. */
04167          fr->ts = (last_upper + (1 << ts_shift)) | (fr->ts & lower_mask);
04168          if (iaxdebug)
04169             ast_debug(1, "schedule_delivery: pushed forward timestamp\n");
04170       } else if (x > threshold) {
04171          /* Sudden apparent big jump forwards in timestamp:
04172             What's likely happened is this is an old miniframe belonging to the previous
04173             top 15 or 16-bit timestamp that has turned up out of order.
04174             Adjust the timestamp appropriately. */
04175          fr->ts = (last_upper - (1 << ts_shift)) | (fr->ts & lower_mask);
04176          if (iaxdebug)
04177             ast_debug(1, "schedule_delivery: pushed back timestamp\n");
04178       }
04179    }
04180 }
04181 
04182 static int get_from_jb(const void *p);
04183 
04184 static void update_jbsched(struct chan_iax2_pvt *pvt)
04185 {
04186    int when;
04187 
04188    when = ast_tvdiff_ms(ast_tvnow(), pvt->rxcore);
04189 
04190    when = jb_next(pvt->jb) - when;
04191 
04192    if (when <= 0) {
04193       /* XXX should really just empty until when > 0.. */
04194       when = 1;
04195    }
04196 
04197    pvt->jbid = iax2_sched_replace(pvt->jbid, sched, when, get_from_jb,
04198       CALLNO_TO_PTR(pvt->callno));
04199 }
04200 
04201 static void __get_from_jb(const void *p)
04202 {
04203    int callno = PTR_TO_CALLNO(p);
04204    struct chan_iax2_pvt *pvt = NULL;
04205    struct iax_frame *fr;
04206    jb_frame frame;
04207    int ret;
04208    long ms;
04209    long next;
04210    struct timeval now = ast_tvnow();
04211    
04212    /* Make sure we have a valid private structure before going on */
04213    ast_mutex_lock(&iaxsl[callno]);
04214    pvt = iaxs[callno];
04215    if (!pvt) {
04216       /* No go! */
04217       ast_mutex_unlock(&iaxsl[callno]);
04218       return;
04219    }
04220 
04221    pvt->jbid = -1;
04222    
04223    /* round up a millisecond since ast_sched_runq does; */
04224    /* prevents us from spinning while waiting for our now */
04225    /* to catch up with runq's now */
04226    now.tv_usec += 1000;
04227    
04228    ms = ast_tvdiff_ms(now, pvt->rxcore);
04229    
04230    if(ms >= (next = jb_next(pvt->jb))) {
04231       struct ast_format voicefmt;
04232       ast_format_from_old_bitfield(&voicefmt, pvt->voiceformat);
04233       ret = jb_get(pvt->jb, &frame, ms, ast_codec_interp_len(&voicefmt));
04234       switch(ret) {
04235       case JB_OK:
04236          fr = frame.data;
04237          __do_deliver(fr);
04238          /* __do_deliver() can cause the call to disappear */
04239          pvt = iaxs[callno];
04240          break;
04241       case JB_INTERP:
04242       {
04243          struct ast_frame af = { 0, };
04244          
04245          /* create an interpolation frame */
04246          af.frametype = AST_FRAME_VOICE;
04247          ast_format_copy(&af.subclass.format, &voicefmt);
04248          af.samples  = frame.ms * (ast_format_rate(&voicefmt) / 1000);
04249          af.src  = "IAX2 JB interpolation";
04250          af.delivery = ast_tvadd(pvt->rxcore, ast_samp2tv(next, 1000));
04251          af.offset = AST_FRIENDLY_OFFSET;
04252          
04253          /* queue the frame:  For consistency, we would call __do_deliver here, but __do_deliver wants an iax_frame,
04254           * which we'd need to malloc, and then it would free it.  That seems like a drag */
04255          if (!ast_test_flag64(iaxs[callno], IAX_ALREADYGONE)) {
04256             iax2_queue_frame(callno, &af);
04257             /* iax2_queue_frame() could cause the call to disappear */
04258             pvt = iaxs[callno];
04259          }
04260       }
04261          break;
04262       case JB_DROP:
04263          iax2_frame_free(frame.data);
04264          break;
04265       case JB_NOFRAME:
04266       case JB_EMPTY:
04267          /* do nothing */
04268          break;
04269       default:
04270          /* shouldn't happen */
04271          break;
04272       }
04273    }
04274    if (pvt)
04275       update_jbsched(pvt);
04276    ast_mutex_unlock(&iaxsl[callno]);
04277 }
04278 
04279 static int get_from_jb(const void *data)
04280 {
04281 #ifdef SCHED_MULTITHREADED
04282    if (schedule_action(__get_from_jb, data))
04283 #endif      
04284       __get_from_jb(data);
04285    return 0;
04286 }
04287 
04288 /*!
04289  * \note This function assumes fr->callno is locked
04290  *
04291  * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
04292  * was valid before calling it, it may no longer be valid after calling it.
04293  */
04294 static int schedule_delivery(struct iax_frame *fr, int updatehistory, int fromtrunk, unsigned int *tsout)
04295 {
04296    int type, len;
04297    int ret;
04298    int needfree = 0;
04299    struct ast_channel *owner = NULL;
04300    struct ast_channel *bridge = NULL;
04301 
04302    /*
04303     * Clear fr->af.data if there is no data in the buffer.  Things
04304     * like AST_CONTROL_HOLD without a suggested music class must
04305     * have a NULL pointer.
04306     */
04307    if (!fr->af.datalen) {
04308       memset(&fr->af.data, 0, sizeof(fr->af.data));
04309    }
04310 
04311    /* Attempt to recover wrapped timestamps */
04312    unwrap_timestamp(fr);
04313 
04314    /* delivery time is sender's sent timestamp converted back into absolute time according to our clock */
04315    if ( !fromtrunk && !ast_tvzero(iaxs[fr->callno]->rxcore))
04316       fr->af.delivery = ast_tvadd(iaxs[fr->callno]->rxcore, ast_samp2tv(fr->ts, 1000));
04317    else {
04318 #if 0
04319       ast_debug(1, "schedule_delivery: set delivery to 0 as we don't have an rxcore yet, or frame is from trunk.\n");
04320 #endif
04321       fr->af.delivery = ast_tv(0,0);
04322    }
04323 
04324    type = JB_TYPE_CONTROL;
04325    len = 0;
04326 
04327    if(fr->af.frametype == AST_FRAME_VOICE) {
04328       type = JB_TYPE_VOICE;
04329       len = ast_codec_get_samples(&fr->af) / (ast_format_rate(&fr->af.subclass.format) / 1000);
04330    } else if(fr->af.frametype == AST_FRAME_CNG) {
04331       type = JB_TYPE_SILENCE;
04332    }
04333 
04334    if ( (!ast_test_flag64(iaxs[fr->callno], IAX_USEJITTERBUF)) ) {
04335       if (tsout)
04336          *tsout = fr->ts;
04337       __do_deliver(fr);
04338       return -1;
04339    }
04340 
04341    iax2_lock_owner(fr->callno);
04342    if (!iaxs[fr->callno]) {
04343       /* The call dissappeared so discard this frame that we could not send. */
04344       iax2_frame_free(fr);
04345       return -1;
04346    }
04347    if ((owner = iaxs[fr->callno]->owner))
04348       bridge = ast_bridged_channel(owner);
04349 
04350    /* if the user hasn't requested we force the use of the jitterbuffer, and we're bridged to
04351     * a channel that can accept jitter, then flush and suspend the jb, and send this frame straight through */
04352    if ( (!ast_test_flag64(iaxs[fr->callno], IAX_FORCEJITTERBUF)) && owner && bridge && (ast_channel_tech(bridge)->properties & AST_CHAN_TP_WANTSJITTER) ) {
04353       jb_frame frame;
04354 
04355       ast_channel_unlock(owner);
04356 
04357       /* deliver any frames in the jb */
04358       while (jb_getall(iaxs[fr->callno]->jb, &frame) == JB_OK) {
04359          __do_deliver(frame.data);
04360          /* __do_deliver() can make the call disappear */
04361          if (!iaxs[fr->callno])
04362             return -1;
04363       }
04364 
04365       jb_reset(iaxs[fr->callno]->jb);
04366 
04367       AST_SCHED_DEL(sched, iaxs[fr->callno]->jbid);
04368 
04369       /* deliver this frame now */
04370       if (tsout)
04371          *tsout = fr->ts;
04372       __do_deliver(fr);
04373       return -1;
04374    }
04375    if (owner) {
04376       ast_channel_unlock(owner);
04377    }
04378 
04379    /* insert into jitterbuffer */
04380    /* TODO: Perhaps we could act immediately if it's not droppable and late */
04381    ret = jb_put(iaxs[fr->callno]->jb, fr, type, len, fr->ts,
04382          calc_rxstamp(iaxs[fr->callno],fr->ts));
04383    if (ret == JB_DROP) {
04384       needfree++;
04385    } else if (ret == JB_SCHED) {
04386       update_jbsched(iaxs[fr->callno]);
04387    }
04388    if (tsout)
04389       *tsout = fr->ts;
04390    if (needfree) {
04391       /* Free our iax frame */
04392       iax2_frame_free(fr);
04393       return -1;
04394    }
04395    return 0;
04396 }
04397 
04398 static int transmit_frame(void *data)
04399 {
04400    struct iax_frame *fr = data;
04401 
04402    ast_mutex_lock(&iaxsl[fr->callno]);
04403 
04404    fr->sentyet = 1;
04405 
04406    if (iaxs[fr->callno]) {
04407       send_packet(fr);
04408    }
04409 
04410    if (fr->retries < 0) {
04411       ast_mutex_unlock(&iaxsl[fr->callno]);
04412       /* No retransmit requested */
04413       iax_frame_free(fr);
04414    } else {
04415       /* We need reliable delivery.  Schedule a retransmission */
04416       AST_LIST_INSERT_TAIL(&frame_queue[fr->callno], fr, list);
04417       fr->retries++;
04418       fr->retrans = iax2_sched_add(sched, fr->retrytime, attempt_transmit, fr);
04419       ast_mutex_unlock(&iaxsl[fr->callno]);
04420    }
04421 
04422    return 0;
04423 }
04424 
04425 static int iax2_transmit(struct iax_frame *fr)
04426 {
04427    fr->sentyet = 0;
04428 
04429    return ast_taskprocessor_push(transmit_processor, transmit_frame, fr);
04430 }
04431 
04432 static int iax2_digit_begin(struct ast_channel *c, char digit)
04433 {
04434    return send_command_locked(PTR_TO_CALLNO(ast_channel_tech_pvt(c)), AST_FRAME_DTMF_BEGIN, digit, 0, NULL, 0, -1);
04435 }
04436 
04437 static int iax2_digit_end(struct ast_channel *c, char digit, unsigned int duration)
04438 {
04439    return send_command_locked(PTR_TO_CALLNO(ast_channel_tech_pvt(c)), AST_FRAME_DTMF_END, digit, 0, NULL, 0, -1);
04440 }
04441 
04442 static int iax2_sendtext(struct ast_channel *c, const char *text)
04443 {
04444    
04445    return send_command_locked(PTR_TO_CALLNO(ast_channel_tech_pvt(c)), AST_FRAME_TEXT,
04446       0, 0, (unsigned char *)text, strlen(text) + 1, -1);
04447 }
04448 
04449 static int iax2_sendimage(struct ast_channel *c, struct ast_frame *img)
04450 {
04451    return send_command_locked(PTR_TO_CALLNO(ast_channel_tech_pvt(c)), AST_FRAME_IMAGE, img->subclass.integer, 0, img->data.ptr, img->datalen, -1);
04452 }
04453 
04454 static int iax2_sendhtml(struct ast_channel *c, int subclass, const char *data, int datalen)
04455 {
04456    return send_command_locked(PTR_TO_CALLNO(ast_channel_tech_pvt(c)), AST_FRAME_HTML, subclass, 0, (unsigned char *)data, datalen, -1);
04457 }
04458 
04459 static int iax2_fixup(struct ast_channel *oldchannel, struct ast_channel *newchan)
04460 {
04461    unsigned short callno = PTR_TO_CALLNO(ast_channel_tech_pvt(newchan));
04462    ast_mutex_lock(&iaxsl[callno]);
04463    if (iaxs[callno])
04464       iaxs[callno]->owner = newchan;
04465    else
04466       ast_log(LOG_WARNING, "Uh, this isn't a good sign...\n");
04467    ast_mutex_unlock(&iaxsl[callno]);
04468    return 0;
04469 }
04470 
04471 /*!
04472  * \note This function calls reg_source_db -> iax2_poke_peer -> find_callno,
04473  *       so do not call this with a pvt lock held.
04474  */
04475 static struct iax2_peer *realtime_peer(const char *peername, struct sockaddr_in *sin)
04476 {
04477    struct ast_variable *var = NULL;
04478    struct ast_variable *tmp;
04479    struct iax2_peer *peer=NULL;
04480    time_t regseconds = 0, nowtime;
04481    int dynamic=0;
04482 
04483    if (peername) {
04484       var = ast_load_realtime("iaxpeers", "name", peername, "host", "dynamic", SENTINEL);
04485       if (!var && sin)
04486          var = ast_load_realtime("iaxpeers", "name", peername, "host", ast_inet_ntoa(sin->sin_addr), SENTINEL);
04487    } else if (sin) {
04488       char porta[25];
04489       sprintf(porta, "%d", ntohs(sin->sin_port));
04490       var = ast_load_realtime("iaxpeers", "ipaddr", ast_inet_ntoa(sin->sin_addr), "port", porta, SENTINEL);
04491       if (var) {
04492          /* We'll need the peer name in order to build the structure! */
04493          for (tmp = var; tmp; tmp = tmp->next) {
04494             if (!strcasecmp(tmp->name, "name"))
04495                peername = tmp->value;
04496          }
04497       }
04498    }
04499    if (!var && peername) { /* Last ditch effort */
04500       var = ast_load_realtime("iaxpeers", "name", peername, SENTINEL);
04501       /*!\note
04502        * If this one loaded something, then we need to ensure that the host
04503        * field matched.  The only reason why we can't have this as a criteria
04504        * is because we only have the IP address and the host field might be
04505        * set as a name (and the reverse PTR might not match).
04506        */
04507       if (var && sin) {
04508          for (tmp = var; tmp; tmp = tmp->next) {
04509             if (!strcasecmp(tmp->name, "host")) {
04510                struct ast_hostent ahp;
04511                struct hostent *hp;
04512                if (!(hp = ast_gethostbyname(tmp->value, &ahp)) || memcmp(hp->h_addr, &sin->sin_addr, hp->h_length)) {
04513                   /* No match */
04514                   ast_variables_destroy(var);
04515                   var = NULL;
04516                }
04517                break;
04518             }
04519          }
04520       }
04521    }
04522    if (!var)
04523       return NULL;
04524 
04525    peer = build_peer(peername, var, NULL, ast_test_flag64((&globalflags), IAX_RTCACHEFRIENDS) ? 0 : 1);
04526 
04527    if (!peer) {
04528       ast_variables_destroy(var);
04529       return NULL;
04530    }
04531 
04532    for (tmp = var; tmp; tmp = tmp->next) {
04533       /* Make sure it's not a user only... */
04534       if (!strcasecmp(tmp->name, "type")) {
04535          if (strcasecmp(tmp->value, "friend") &&
04536              strcasecmp(tmp->value, "peer")) {
04537             /* Whoops, we weren't supposed to exist! */
04538             peer = peer_unref(peer);
04539             break;
04540          }
04541       } else if (!strcasecmp(tmp->name, "regseconds")) {
04542          ast_get_time_t(tmp->value, &regseconds, 0, NULL);
04543       } else if (!strcasecmp(tmp->name, "ipaddr")) {
04544          if (!ast_sockaddr_parse(&peer->addr, tmp->value, PARSE_PORT_IGNORE)) {
04545             ast_log(LOG_WARNING, "Failed to parse sockaddr '%s' for ipaddr of realtime peer '%s'\n", tmp->value, tmp->name);
04546          }
04547       } else if (!strcasecmp(tmp->name, "port")) {
04548          ast_sockaddr_set_port(&peer->addr, atoi(tmp->value));
04549       } else if (!strcasecmp(tmp->name, "host")) {
04550          if (!strcasecmp(tmp->value, "dynamic"))
04551             dynamic = 1;
04552       }
04553    }
04554 
04555    ast_variables_destroy(var);
04556 
04557    if (!peer)
04558       return NULL;
04559 
04560    if (ast_test_flag64((&globalflags), IAX_RTCACHEFRIENDS)) {
04561       ast_copy_flags64(peer, &globalflags, IAX_RTAUTOCLEAR|IAX_RTCACHEFRIENDS);
04562       if (ast_test_flag64(peer, IAX_RTAUTOCLEAR)) {
04563          if (peer->expire > -1) {
04564             if (!AST_SCHED_DEL(sched, peer->expire)) {
04565                peer->expire = -1;
04566                peer_unref(peer);
04567             }
04568          }
04569          peer->expire = iax2_sched_add(sched, (global_rtautoclear) * 1000, expire_registry, peer_ref(peer));
04570          if (peer->expire == -1)
04571             peer_unref(peer);
04572       }
04573       ao2_link(peers, peer);
04574       if (ast_test_flag64(peer, IAX_DYNAMIC))
04575          reg_source_db(peer);
04576    } else {
04577       ast_set_flag64(peer, IAX_TEMPONLY);
04578    }
04579 
04580    if (!ast_test_flag64(&globalflags, IAX_RTIGNOREREGEXPIRE) && dynamic) {
04581       time(&nowtime);
04582       if ((nowtime - regseconds) > IAX_DEFAULT_REG_EXPIRE) {
04583          memset(&peer->addr, 0, sizeof(peer->addr));
04584          realtime_update_peer(peer->name, &peer->addr, 0);
04585          ast_debug(1, "realtime_peer: Bah, '%s' is expired (%d/%d/%d)!\n",
04586             peername, (int)(nowtime - regseconds), (int)regseconds, (int)nowtime);
04587       }
04588       else {
04589          ast_debug(1, "realtime_peer: Registration for '%s' still active (%d/%d/%d)!\n",
04590             peername, (int)(nowtime - regseconds), (int)regseconds, (int)nowtime);
04591       }
04592    }
04593 
04594    return peer;
04595 }
04596 
04597 static struct iax2_user *realtime_user(const char *username, struct sockaddr_in *sin)
04598 {
04599    struct ast_variable *var;
04600    struct ast_variable *tmp;
04601    struct iax2_user *user=NULL;
04602 
04603    var = ast_load_realtime("iaxusers", "name", username, "host", "dynamic", SENTINEL);
04604    if (!var)
04605       var = ast_load_realtime("iaxusers", "name", username, "host", ast_inet_ntoa(sin->sin_addr), SENTINEL);
04606    if (!var && sin) {
04607       char porta[6];
04608       snprintf(porta, sizeof(porta), "%d", ntohs(sin->sin_port));
04609       var = ast_load_realtime("iaxusers", "name", username, "ipaddr", ast_inet_ntoa(sin->sin_addr), "port", porta, SENTINEL);
04610       if (!var)
04611          var = ast_load_realtime("iaxusers", "ipaddr", ast_inet_ntoa(sin->sin_addr), "port", porta, SENTINEL);
04612    }
04613    if (!var) { /* Last ditch effort */
04614       var = ast_load_realtime("iaxusers", "name", username, SENTINEL);
04615       /*!\note
04616        * If this one loaded something, then we need to ensure that the host
04617        * field matched.  The only reason why we can't have this as a criteria
04618        * is because we only have the IP address and the host field might be
04619        * set as a name (and the reverse PTR might not match).
04620        */
04621       if (var) {
04622          for (tmp = var; tmp; tmp = tmp->next) {
04623             if (!strcasecmp(tmp->name, "host")) {
04624                struct ast_hostent ahp;
04625                struct hostent *hp;
04626                if (!(hp = ast_gethostbyname(tmp->value, &ahp)) || memcmp(hp->h_addr, &sin->sin_addr, hp->h_length)) {
04627                   /* No match */
04628                   ast_variables_destroy(var);
04629                   var = NULL;
04630                }
04631                break;
04632             }
04633          }
04634       }
04635    }
04636    if (!var)
04637       return NULL;
04638 
04639    tmp = var;
04640    while(tmp) {
04641       /* Make sure it's not a peer only... */
04642       if (!strcasecmp(tmp->name, "type")) {
04643          if (strcasecmp(tmp->value, "friend") &&
04644              strcasecmp(tmp->value, "user")) {
04645             return NULL;
04646          } 
04647       }
04648       tmp = tmp->next;
04649    }
04650 
04651    user = build_user(username, var, NULL, !ast_test_flag64((&globalflags), IAX_RTCACHEFRIENDS));
04652 
04653    ast_variables_destroy(var);
04654 
04655    if (!user)
04656       return NULL;
04657 
04658    if (ast_test_flag64((&globalflags), IAX_RTCACHEFRIENDS)) {
04659       ast_set_flag64(user, IAX_RTCACHEFRIENDS);
04660       ao2_link(users, user);
04661    } else {
04662       ast_set_flag64(user, IAX_TEMPONLY);
04663    }
04664 
04665    return user;
04666 }
04667 
04668 static void realtime_update_peer(const char *peername, struct ast_sockaddr *sockaddr, time_t regtime)
04669 {
04670    char port[10];
04671    char regseconds[20];
04672    const char *sysname = ast_config_AST_SYSTEM_NAME;
04673    char *syslabel = NULL;
04674 
04675    if (ast_strlen_zero(sysname)) /* No system name, disable this */
04676       sysname = NULL;
04677    else if (ast_test_flag64(&globalflags, IAX_RTSAVE_SYSNAME))
04678       syslabel = "regserver";
04679 
04680    snprintf(regseconds, sizeof(regseconds), "%d", (int)regtime);
04681    snprintf(port, sizeof(port), "%d", ast_sockaddr_port(sockaddr));
04682    ast_update_realtime("iaxpeers", "name", peername, 
04683       "ipaddr", ast_sockaddr_stringify_addr(sockaddr), "port", port, 
04684       "regseconds", regseconds, syslabel, sysname, SENTINEL); /* note syslable can be NULL */
04685 }
04686 
04687 struct create_addr_info {
04688    iax2_format capability;
04689    uint64_t flags;
04690    int maxtime;
04691    int encmethods;
04692    int found;
04693    int sockfd;
04694    int adsi;
04695    char username[80];
04696    char secret[80];
04697    char outkey[80];
04698    char timezone[80];
04699    char prefs[32];
04700    char cid_num[80];
04701    char cid_name[80];
04702    char context[AST_MAX_CONTEXT];
04703    char peercontext[AST_MAX_CONTEXT];
04704    char mohinterpret[MAX_MUSICCLASS];
04705    char mohsuggest[MAX_MUSICCLASS];
04706 };
04707 
04708 static int create_addr(const char *peername, struct ast_channel *c, struct sockaddr_in *sin, struct create_addr_info *cai)
04709 {
04710    struct iax2_peer *peer;
04711    int res = -1;
04712    struct ast_codec_pref ourprefs;
04713    struct sockaddr_in peer_addr;
04714 
04715    ast_clear_flag64(cai, IAX_SENDANI | IAX_TRUNK);
04716    cai->sockfd = defaultsockfd;
04717    cai->maxtime = 0;
04718    sin->sin_family = AF_INET;
04719 
04720    if (!(peer = find_peer(peername, 1))) {
04721       struct ast_sockaddr sin_tmp;
04722 
04723       cai->found = 0;
04724       sin_tmp.ss.ss_family = AF_INET;
04725       if (ast_get_ip_or_srv(&sin_tmp, peername, srvlookup ? "_iax._udp" : NULL)) {
04726          ast_log(LOG_WARNING, "No such host: %s\n", peername);
04727          return -1;
04728       }
04729       ast_sockaddr_to_sin(&sin_tmp, sin);
04730       if (sin->sin_port == 0) {
04731          sin->sin_port = htons(IAX_DEFAULT_PORTNO);
04732       }
04733       /* use global iax prefs for unknown peer/user */
04734       /* But move the calling channel's native codec to the top of the preference list */
04735       memcpy(&ourprefs, &prefs, sizeof(ourprefs));
04736       if (c) {
04737          struct ast_format tmpfmt;
04738          ast_format_cap_iter_start(ast_channel_nativeformats(c));
04739          while (!(ast_format_cap_iter_next(ast_channel_nativeformats(c), &tmpfmt))) {
04740             ast_codec_pref_prepend(&ourprefs, &tmpfmt, 1);
04741          }
04742          ast_format_cap_iter_end(ast_channel_nativeformats(c));
04743       }
04744       ast_codec_pref_convert(&ourprefs, cai->prefs, sizeof(cai->prefs), 1);
04745       return 0;
04746    }
04747 
04748    cai->found = 1;
04749 
04750    ast_sockaddr_to_sin(&peer->addr, &peer_addr);
04751 
04752    /* if the peer has no address (current or default), return failure */
04753    if (!(peer_addr.sin_addr.s_addr || peer->defaddr.sin_addr.s_addr)) {
04754       goto return_unref;
04755    }
04756 
04757    /* if the peer is being monitored and is currently unreachable, return failure */
04758    if (peer->maxms && ((peer->lastms > peer->maxms) || (peer->lastms < 0)))
04759       goto return_unref;
04760 
04761    ast_copy_flags64(cai, peer, IAX_SENDANI | IAX_TRUNK | IAX_NOTRANSFER | IAX_TRANSFERMEDIA | IAX_USEJITTERBUF | IAX_FORCEJITTERBUF | IAX_SENDCONNECTEDLINE | IAX_RECVCONNECTEDLINE | IAX_FORCE_ENCRYPT);
04762    cai->maxtime = peer->maxms;
04763    cai->capability = peer->capability;
04764    cai->encmethods = peer->encmethods;
04765    cai->sockfd = peer->sockfd;
04766    cai->adsi = peer->adsi;
04767    memcpy(&ourprefs, &peer->prefs, sizeof(ourprefs));
04768    /* Move the calling channel's native codec to the top of the preference list */
04769    if (c) {
04770       struct ast_format tmpfmt;
04771       ast_format_cap_iter_start(ast_channel_nativeformats(c));
04772       while (!(ast_format_cap_iter_next(ast_channel_nativeformats(c), &tmpfmt))) {
04773          ast_debug(1, "prepending %s to prefs\n", ast_getformatname(&tmpfmt));
04774          ast_codec_pref_prepend(&ourprefs, &tmpfmt, 1);
04775       }
04776       ast_format_cap_iter_end(ast_channel_nativeformats(c));
04777    }
04778    ast_codec_pref_convert(&ourprefs, cai->prefs, sizeof(cai->prefs), 1);
04779    ast_copy_string(cai->context, peer->context, sizeof(cai->context));
04780    ast_copy_string(cai->peercontext, peer->peercontext, sizeof(cai->peercontext));
04781    ast_copy_string(cai->username, peer->username, sizeof(cai->username));
04782    ast_copy_string(cai->timezone, peer->zonetag, sizeof(cai->timezone));
04783    ast_copy_string(cai->outkey, peer->outkey, sizeof(cai->outkey));
04784    ast_copy_string(cai->cid_num, peer->cid_num, sizeof(cai->cid_num));
04785    ast_copy_string(cai->cid_name, peer->cid_name, sizeof(cai->cid_name));
04786    ast_copy_string(cai->mohinterpret, peer->mohinterpret, sizeof(cai->mohinterpret));
04787    ast_copy_string(cai->mohsuggest, peer->mohsuggest, sizeof(cai->mohsuggest));
04788    if (ast_strlen_zero(peer->dbsecret)) {
04789       ast_copy_string(cai->secret, peer->secret, sizeof(cai->secret));
04790    } else {
04791       char *family;
04792       char *key = NULL;
04793 
04794       family = ast_strdupa(peer->dbsecret);
04795       key = strchr(family, '/');
04796       if (key)
04797          *key++ = '\0';
04798       if (!key || ast_db_get(family, key, cai->secret, sizeof(cai->secret))) {
04799          ast_log(LOG_WARNING, "Unable to retrieve database password for family/key '%s'!\n", peer->dbsecret);
04800          goto return_unref;
04801       }
04802    }
04803 
04804    if (peer_addr.sin_addr.s_addr) {
04805       sin->sin_addr = peer_addr.sin_addr;
04806       sin->sin_port = peer_addr.sin_port;
04807    } else {
04808       sin->sin_addr = peer->defaddr.sin_addr;
04809       sin->sin_port = peer->defaddr.sin_port;
04810    }
04811 
04812    res = 0;
04813 
04814 return_unref:
04815    peer_unref(peer);
04816 
04817    return res;
04818 }
04819 
04820 static void __auto_congest(const void *nothing)
04821 {
04822    int callno = PTR_TO_CALLNO(nothing);
04823    struct ast_frame f = { AST_FRAME_CONTROL, { AST_CONTROL_CONGESTION } };
04824    ast_mutex_lock(&iaxsl[callno]);
04825    if (iaxs[callno]) {
04826       iaxs[callno]->initid = -1;
04827       iax2_queue_frame(callno, &f);
04828       ast_log(LOG_NOTICE, "Auto-congesting call due to slow response\n");
04829    }
04830    ast_mutex_unlock(&iaxsl[callno]);
04831 }
04832 
04833 static int auto_congest(const void *data)
04834 {
04835 #ifdef SCHED_MULTITHREADED
04836    if (schedule_action(__auto_congest, data))
04837 #endif      
04838       __auto_congest(data);
04839    return 0;
04840 }
04841 
04842 static unsigned int iax2_datetime(const char *tz)
04843 {
04844    struct timeval t = ast_tvnow();
04845    struct ast_tm tm;
04846    unsigned int tmp;
04847    ast_localtime(&t, &tm, ast_strlen_zero(tz) ? NULL : tz);
04848    tmp  = (tm.tm_sec >> 1) & 0x1f;        /* 5 bits of seconds */
04849    tmp |= (tm.tm_min & 0x3f) << 5;        /* 6 bits of minutes */
04850    tmp |= (tm.tm_hour & 0x1f) << 11;      /* 5 bits of hours */
04851    tmp |= (tm.tm_mday & 0x1f) << 16;      /* 5 bits of day of month */
04852    tmp |= ((tm.tm_mon + 1) & 0xf) << 21;     /* 4 bits of month */
04853    tmp |= ((tm.tm_year - 100) & 0x7f) << 25; /* 7 bits of year */
04854    return tmp;
04855 }
04856 
04857 struct parsed_dial_string {
04858    char *username;
04859    char *password;
04860    char *key;
04861    char *peer;
04862    char *port;
04863    char *exten;
04864    char *context;
04865    char *options;
04866 };
04867 
04868 static int send_apathetic_reply(unsigned short callno, unsigned short dcallno,
04869       struct sockaddr_in *sin, int command, int ts, unsigned char seqno,
04870       int sockfd, struct iax_ie_data *ied)
04871 {
04872    struct {
04873       struct ast_iax2_full_hdr f;
04874       struct iax_ie_data ied;
04875    } data;
04876    size_t size = sizeof(struct ast_iax2_full_hdr);
04877 
04878    if (ied) {
04879       size += ied->pos;
04880       memcpy(&data.ied, ied->buf, ied->pos);
04881    }
04882 
04883    data.f.scallno = htons(0x8000 | callno);
04884    data.f.dcallno = htons(dcallno & ~IAX_FLAG_RETRANS);
04885    data.f.ts = htonl(ts);
04886    data.f.iseqno = seqno;
04887    data.f.oseqno = 0;
04888    data.f.type = AST_FRAME_IAX;
04889    data.f.csub = compress_subclass(command);
04890 
04891    iax_outputframe(NULL, &data.f, 0, sin, size - sizeof(struct ast_iax2_full_hdr));
04892 
04893    return sendto(sockfd, &data, size, 0, (struct sockaddr *)sin, sizeof(*sin));
04894 }
04895 
04896 static void add_empty_calltoken_ie(struct chan_iax2_pvt *pvt, struct iax_ie_data *ied)
04897 {
04898    /* first make sure their are two empty bytes left in ied->buf */
04899    if (pvt && ied && (2 < ((int) sizeof(ied->buf) - ied->pos))) {
04900       ied->buf[ied->pos++] = IAX_IE_CALLTOKEN;  /* type */
04901       ied->buf[ied->pos++] = 0;   /* data size,  ZERO in this case */
04902       pvt->calltoken_ie_len = 2;
04903    }
04904 }
04905 
04906 static void resend_with_token(int callno, struct iax_frame *f, const char *newtoken)
04907 {
04908    struct chan_iax2_pvt *pvt = iaxs[callno];
04909    int frametype = f->af.frametype;
04910    int subclass = f->af.subclass.integer;
04911    struct {
04912       struct ast_iax2_full_hdr fh;
04913       struct iax_ie_data ied;
04914    } data = {
04915       .ied.buf = { 0 },
04916       .ied.pos = 0,
04917    };
04918    /* total len - header len gives us the frame's IE len */
04919    int ie_data_pos = f->datalen - sizeof(struct ast_iax2_full_hdr);
04920 
04921    if (!pvt) {
04922       return;  /* this should not be possible if called from socket_process() */
04923    }
04924 
04925    /* 
04926     * Check to make sure last frame sent is valid for call token resend
04927     * 1. Frame should _NOT_ be encrypted since it starts the IAX dialog 
04928     * 2. Frame should _NOT_ already have a destination callno
04929     * 3. Frame must be a valid iax_frame subclass capable of starting dialog
04930     * 4. Pvt must have a calltoken_ie_len which represents the number of
04931     *    bytes at the end of the frame used for the previous calltoken ie.
04932     * 5. Pvt's calltoken_ie_len must be _LESS_ than the total IE length
04933     * 6. Total length of f->data must be _LESS_ than size of our data struct
04934     *    because f->data must be able to fit within data. 
04935     */
04936    if (f->encmethods || f->dcallno || !iax2_allow_new(frametype, subclass, 0)
04937       || !pvt->calltoken_ie_len || (pvt->calltoken_ie_len > ie_data_pos) ||
04938       (f->datalen > sizeof(data))) {
04939 
04940       return;  /* ignore resend, token was not valid for the dialog */
04941    }
04942 
04943    /* token is valid
04944     * 1. Copy frame data over
04945     * 2. Redo calltoken IE, it will always be the last ie in the frame.
04946     *    NOTE: Having the ie always be last is not protocol specified,
04947     *    it is only an implementation choice.  Since we only expect the ie to
04948     *    be last for frames we have sent, this can no way be affected by
04949     *    another end point.
04950     * 3. Remove frame from queue
04951     * 4. Free old frame
04952     * 5. Clear previous seqnos
04953     * 6. Resend with CALLTOKEN ie.
04954     */
04955 
04956    /* ---1.--- */
04957    memcpy(&data, f->data, f->datalen);
04958    data.ied.pos = ie_data_pos;
04959 
04960    /* ---2.--- */
04961    /* move to the beginning of the calltoken ie so we can write over it */
04962    data.ied.pos -= pvt->calltoken_ie_len;
04963    iax_ie_append_str(&data.ied, IAX_IE_CALLTOKEN, newtoken);
04964 
04965    /* make sure to update token length incase it ever has to be stripped off again */
04966    pvt->calltoken_ie_len = data.ied.pos - ie_data_pos; /* new pos minus old pos tells how big token ie is */
04967 
04968    /* ---3.--- */
04969    AST_LIST_REMOVE(&frame_queue[callno], f, list);
04970 
04971    /* ---4.--- */
04972    iax2_frame_free(f);
04973 
04974    /* ---5.--- */
04975    pvt->oseqno = 0;
04976    pvt->rseqno = 0;
04977    pvt->iseqno = 0;
04978    pvt->aseqno = 0;
04979    if (pvt->peercallno) {
04980       remove_by_peercallno(pvt);
04981       pvt->peercallno = 0;
04982    }
04983 
04984    /* ---6.--- */
04985    send_command(pvt, AST_FRAME_IAX, subclass, 0, data.ied.buf, data.ied.pos, -1);
04986 }
04987 
04988 static void requirecalltoken_mark_auto(const char *name, int subclass)
04989 {
04990    struct iax2_user *user = NULL;
04991    struct iax2_peer *peer = NULL;
04992 
04993    if (ast_strlen_zero(name)) {
04994       return; /* no username given */
04995    }
04996 
04997    if ((subclass == IAX_COMMAND_NEW) && (user = find_user(name)) && (user->calltoken_required == CALLTOKEN_AUTO)) {
04998       user->calltoken_required = CALLTOKEN_YES;
04999    } else if ((subclass != IAX_COMMAND_NEW) && (peer = find_peer(name, 1)) && (peer->calltoken_required == CALLTOKEN_AUTO)) {
05000       peer->calltoken_required = CALLTOKEN_YES;
05001    }
05002 
05003    if (peer) {
05004       peer_unref(peer);
05005    }
05006    if (user) {
05007       user_unref(user);
05008    }
05009 }
05010 
05011 /*!
05012  * \internal
05013  *
05014  * \brief handles calltoken logic for a received iax_frame.
05015  * 
05016  * \note frametype must be AST_FRAME_IAX.
05017  * 
05018  * \note
05019  * Three different cases are possible here.
05020  * Case 1. An empty calltoken is provided. This means the client supports
05021  *         calltokens but has not yet received one from us.  In this case
05022  *         a full calltoken IE is created and sent in a calltoken fullframe.
05023  * Case 2. A full calltoken is received and must be checked for validity.
05024  * Case 3. No calltoken is received indicating that the client does not
05025  *         support calltokens.  In this case it is up to the configuration
05026  *         to decide how this should be handled (reject or permit without calltoken)
05027  */
05028 static int handle_call_token(struct ast_iax2_full_hdr *fh, struct iax_ies *ies,
05029       struct sockaddr_in *sin, int fd)
05030 {
05031 #define CALLTOKEN_HASH_FORMAT "%s%d%u%d"  /* address + port + ts + randomcalldata */
05032 #define CALLTOKEN_IE_FORMAT   "%u?%s"     /* time + ? + (40 char hash) */
05033    struct ast_str *buf = ast_str_alloca(256);
05034    time_t t = time(NULL);
05035    char hash[41]; /* 40 char sha1 hash */
05036    int subclass = uncompress_subclass(fh->csub);
05037 
05038    /* ----- Case 1 ----- */
05039    if (ies->calltoken && !ies->calltokendata) {  /* empty calltoken is provided, client supports calltokens */
05040       struct iax_ie_data ied = {
05041          .buf = { 0 },
05042          .pos = 0,
05043       };
05044 
05045       /* create the hash with their address data and our timestamp */
05046       ast_str_set(&buf, 0, CALLTOKEN_HASH_FORMAT, ast_inet_ntoa(sin->sin_addr), sin->sin_port, (unsigned int) t, randomcalltokendata);
05047       ast_sha1_hash(hash, ast_str_buffer(buf));
05048 
05049       ast_str_set(&buf, 0, CALLTOKEN_IE_FORMAT, (unsigned int) t, hash);
05050       iax_ie_append_str(&ied, IAX_IE_CALLTOKEN, ast_str_buffer(buf));
05051       send_apathetic_reply(1, ntohs(fh->scallno), sin, IAX_COMMAND_CALLTOKEN, ntohl(fh->ts), fh->iseqno + 1, fd, &ied);
05052 
05053       return 1;
05054 
05055    /* ----- Case 2 ----- */
05056    } else if (ies->calltoken && ies->calltokendata) { /* calltoken received, check to see if it is valid */
05057       char *rec_hash = NULL;    /* the received hash, make sure it matches with ours. */
05058       char *rec_ts = NULL;      /* received timestamp */
05059       unsigned int rec_time;  /* received time_t */
05060 
05061       /* split the timestamp from the hash data */
05062       rec_hash = strchr((char *) ies->calltokendata, '?');
05063       if (rec_hash) {
05064          *rec_hash++ = '\0';
05065          rec_ts = (char *) ies->calltokendata;
05066       }
05067 
05068       /* check that we have valid data before we do any comparisons */
05069       if (!rec_hash || !rec_ts) {
05070          goto reject;
05071       } else if (sscanf(rec_ts, "%u", &rec_time) != 1) {
05072          goto reject;
05073       }
05074 
05075       /* create a hash with their address and the _TOKEN'S_ timestamp */
05076       ast_str_set(&buf, 0, CALLTOKEN_HASH_FORMAT, ast_inet_ntoa(sin->sin_addr), sin->sin_port, (unsigned int) rec_time, randomcalltokendata);
05077       ast_sha1_hash(hash, ast_str_buffer(buf));
05078 
05079       /* compare hashes and then check timestamp delay */
05080       if (strcmp(hash, rec_hash)) {
05081          ast_log(LOG_WARNING, "Address %s failed CallToken hash inspection\n", ast_inet_ntoa(sin->sin_addr));
05082          goto reject; /* received hash does not match ours, reject */
05083       } else if ((t < rec_time) || ((t - rec_time) >= MAX_CALLTOKEN_DELAY)) {
05084          ast_log(LOG_WARNING, "Too much delay in IAX2 calltoken timestamp from address %s\n", ast_inet_ntoa(sin->sin_addr));
05085          goto reject; /* too much delay, reject */
05086       }
05087 
05088       /* at this point the call token is valid, returning 0 
05089        * will allow socket_process to continue as usual */
05090       requirecalltoken_mark_auto(ies->username, subclass);
05091       return 0;
05092 
05093    /* ----- Case 3 ----- */
05094    } else { /* calltokens are not supported for this client, how do we respond? */
05095       if (calltoken_required(sin, ies->username, subclass)) {
05096          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"));
05097          goto reject;
05098       }
05099       return 0; /* calltoken is not required for this addr, so permit it. */
05100    }
05101 
05102 reject:
05103    /* received frame has failed calltoken inspection, send apathetic reject messages */
05104    if (subclass == IAX_COMMAND_REGREQ || subclass == IAX_COMMAND_REGREL) {
05105       send_apathetic_reply(1, ntohs(fh->scallno), sin, IAX_COMMAND_REGREJ, ntohl(fh->ts), fh->iseqno + 1, fd, NULL);
05106    } else {
05107       send_apathetic_reply(1, ntohs(fh->scallno), sin, IAX_COMMAND_REJECT, ntohl(fh->ts), fh->iseqno + 1, fd, NULL);
05108    }
05109 
05110    return 1;
05111 }
05112 
05113 /*!
05114  * \brief Parses an IAX dial string into its component parts.
05115  * \param data the string to be parsed
05116  * \param pds pointer to a \c struct \c parsed_dial_string to be filled in
05117  * \return nothing
05118  *
05119  * This function parses the string and fills the structure
05120  * with pointers to its component parts. The input string
05121  * will be modified.
05122  *
05123  * \note This function supports both plaintext passwords and RSA
05124  * key names; if the password string is formatted as '[keyname]',
05125  * then the keyname will be placed into the key field, and the
05126  * password field will be set to NULL.
05127  *
05128  * \note The dial string format is:
05129  *       [username[:password]@]peer[:port][/exten[@@context]][/options]
05130  */
05131 static void parse_dial_string(char *data, struct parsed_dial_string *pds)
05132 {
05133    if (ast_strlen_zero(data))
05134       return;
05135 
05136    pds->peer = strsep(&data, "/");
05137    pds->exten = strsep(&data, "/");
05138    pds->options = data;
05139 
05140    if (pds->exten) {
05141       data = pds->exten;
05142       pds->exten = strsep(&data, "@");
05143       pds->context = data;
05144    }
05145 
05146    if (strchr(pds->peer, '@')) {
05147       data = pds->peer;
05148       pds->username = strsep(&data, "@");
05149       pds->peer = data;
05150    }
05151 
05152    if (pds->username) {
05153       data = pds->username;
05154       pds->username = strsep(&data, ":");
05155       pds->password = data;
05156    }
05157 
05158    data = pds->peer;
05159    pds->peer = strsep(&data, ":");
05160    pds->port = data;
05161 
05162    /* check for a key name wrapped in [] in the secret position, if found,
05163       move it to the key field instead
05164    */
05165    if (pds->password && (pds->password[0] == '[')) {
05166       pds->key = ast_strip_quoted(pds->password, "[", "]");
05167       pds->password = NULL;
05168    }
05169 }
05170 
05171 static int iax2_call(struct ast_channel *c, const char *dest, int timeout)
05172 {
05173    struct sockaddr_in sin;
05174    char *l=NULL, *n=NULL, *tmpstr;
05175    struct iax_ie_data ied;
05176    char *defaultrdest = "s";
05177    unsigned short callno = PTR_TO_CALLNO(ast_channel_tech_pvt(c));
05178    struct parsed_dial_string pds;
05179    struct create_addr_info cai;
05180    struct ast_var_t *var;
05181    struct ast_datastore *variablestore = ast_channel_datastore_find(c, &iax2_variable_datastore_info, NULL);
05182    const char* osp_token_ptr;
05183    unsigned int osp_token_length;
05184    unsigned char osp_block_index;
05185    unsigned int osp_block_length;
05186    unsigned char osp_buffer[256];
05187    iax2_format iax2_tmpfmt;
05188 
05189    if ((ast_channel_state(c) != AST_STATE_DOWN) && (ast_channel_state(c) != AST_STATE_RESERVED)) {
05190       ast_log(LOG_WARNING, "Channel is already in use (%s)?\n", ast_channel_name(c));
05191       return -1;
05192    }
05193 
05194    memset(&cai, 0, sizeof(cai));
05195    cai.encmethods = iax2_encryption;
05196 
05197    memset(&pds, 0, sizeof(pds));
05198    tmpstr = ast_strdupa(dest);
05199    parse_dial_string(tmpstr, &pds);
05200 
05201    if (ast_strlen_zero(pds.peer)) {
05202       ast_log(LOG_WARNING, "No peer provided in the IAX2 dial string '%s'\n", dest);
05203       return -1;
05204    }
05205    if (!pds.exten) {
05206       pds.exten = defaultrdest;
05207    }
05208    if (create_addr(pds.peer, c, &sin, &cai)) {
05209       ast_log(LOG_WARNING, "No address associated with '%s'\n", pds.peer);
05210       return -1;
05211    }
05212    if (ast_test_flag64(iaxs[callno], IAX_FORCE_ENCRYPT) && !cai.encmethods) {
05213       ast_log(LOG_WARNING, "Encryption forced for call, but not enabled\n");
05214       ast_channel_hangupcause_set(c, AST_CAUSE_BEARERCAPABILITY_NOTAVAIL);
05215       return -1;
05216    }
05217    if (ast_strlen_zero(cai.secret) && ast_test_flag64(iaxs[callno], IAX_FORCE_ENCRYPT)) {
05218       ast_log(LOG_WARNING, "Call terminated. No secret given and force encrypt enabled\n");
05219       return -1;
05220    }
05221    if (!pds.username && !ast_strlen_zero(cai.username))
05222       pds.username = cai.username;
05223    if (!pds.password && !ast_strlen_zero(cai.secret))
05224       pds.password = cai.secret;
05225    if (!pds.key && !ast_strlen_zero(cai.outkey))
05226       pds.key = cai.outkey;
05227    if (!pds.context && !ast_strlen_zero(cai.peercontext))
05228       pds.context = cai.peercontext;
05229 
05230    /* Keep track of the context for outgoing calls too */
05231    ast_channel_context_set(c, cai.context);
05232 
05233    if (pds.port)
05234       sin.sin_port = htons(atoi(pds.port));
05235 
05236    l = ast_channel_connected(c)->id.number.valid ? ast_channel_connected(c)->id.number.str : NULL;
05237    n = ast_channel_connected(c)->id.name.valid ? ast_channel_connected(c)->id.name.str : NULL;
05238 
05239    /* Now build request */ 
05240    memset(&ied, 0, sizeof(ied));
05241 
05242    /* On new call, first IE MUST be IAX version of caller */
05243    iax_ie_append_short(&ied, IAX_IE_VERSION, IAX_PROTO_VERSION);
05244    iax_ie_append_str(&ied, IAX_IE_CALLED_NUMBER, pds.exten);
05245    if (pds.options && strchr(pds.options, 'a')) {
05246       /* Request auto answer */
05247       iax_ie_append(&ied, IAX_IE_AUTOANSWER);
05248    }
05249 
05250    /* WARNING: this breaks down at 190 bits! */
05251    iax_ie_append_str(&ied, IAX_IE_CODEC_PREFS, cai.prefs);
05252 
05253    if (l) {
05254       iax_ie_append_str(&ied, IAX_IE_CALLING_NUMBER, l);
05255       iax_ie_append_byte(&ied, IAX_IE_CALLINGPRES,
05256          ast_party_id_presentation(&ast_channel_connected(c)->id));
05257    } else if (n) {
05258       iax_ie_append_byte(&ied, IAX_IE_CALLINGPRES,
05259          ast_party_id_presentation(&ast_channel_connected(c)->id));
05260    } else {
05261       iax_ie_append_byte(&ied, IAX_IE_CALLINGPRES, AST_PRES_NUMBER_NOT_AVAILABLE);
05262    }
05263 
05264    iax_ie_append_byte(&ied, IAX_IE_CALLINGTON, ast_channel_connected(c)->id.number.plan);
05265    iax_ie_append_short(&ied, IAX_IE_CALLINGTNS, ast_channel_dialed(c)->transit_network_select);
05266 
05267    if (n)
05268       iax_ie_append_str(&ied, IAX_IE_CALLING_NAME, n);
05269    if (ast_test_flag64(iaxs[callno], IAX_SENDANI)
05270       && ast_channel_connected(c)->ani.number.valid
05271       && ast_channel_connected(c)->ani.number.str) {
05272       iax_ie_append_str(&ied, IAX_IE_CALLING_ANI, ast_channel_connected(c)->ani.number.str);
05273    }
05274 
05275    if (!ast_strlen_zero(ast_channel_language(c)))
05276       iax_ie_append_str(&ied, IAX_IE_LANGUAGE, ast_channel_language(c));
05277    if (!ast_strlen_zero(ast_channel_dialed(c)->number.str)) {
05278       iax_ie_append_str(&ied, IAX_IE_DNID, ast_channel_dialed(c)->number.str);
05279    }
05280    if (ast_channel_redirecting(c)->from.number.valid
05281       && !ast_strlen_zero(ast_channel_redirecting(c)->from.number.str)) {
05282       iax_ie_append_str(&ied, IAX_IE_RDNIS, ast_channel_redirecting(c)->from.number.str);
05283    }
05284 
05285    if (pds.context)
05286       iax_ie_append_str(&ied, IAX_IE_CALLED_CONTEXT, pds.context);
05287 
05288    if (pds.username)
05289       iax_ie_append_str(&ied, IAX_IE_USERNAME, pds.username);
05290 
05291    if (cai.encmethods)
05292       iax_ie_append_short(&ied, IAX_IE_ENCRYPTION, cai.encmethods);
05293 
05294    ast_mutex_lock(&iaxsl[callno]);
05295 
05296    if (!ast_strlen_zero(ast_channel_context(c)))
05297       ast_string_field_set(iaxs[callno], context, ast_channel_context(c));
05298 
05299    if (pds.username)
05300       ast_string_field_set(iaxs[callno], username, pds.username);
05301 
05302    iaxs[callno]->encmethods = cai.encmethods;
05303 
05304    iaxs[callno]->adsi = cai.adsi;
05305    
05306    ast_string_field_set(iaxs[callno], mohinterpret, cai.mohinterpret);
05307    ast_string_field_set(iaxs[callno], mohsuggest, cai.mohsuggest);
05308 
05309    if (pds.key)
05310       ast_string_field_set(iaxs[callno], outkey, pds.key);
05311    if (pds.password)
05312       ast_string_field_set(iaxs[callno], secret, pds.password);
05313 
05314    iax2_tmpfmt = ast_format_cap_to_old_bitfield(ast_channel_nativeformats(c));
05315    iax_ie_append_int(&ied, IAX_IE_FORMAT, (int) iax2_tmpfmt);
05316    iax_ie_append_versioned_uint64(&ied, IAX_IE_FORMAT2, 0, iax2_tmpfmt);
05317 
05318    iax_ie_append_int(&ied, IAX_IE_CAPABILITY, (int) iaxs[callno]->capability);
05319    iax_ie_append_versioned_uint64(&ied, IAX_IE_CAPABILITY2, 0, iaxs[callno]->capability);
05320    iax_ie_append_short(&ied, IAX_IE_ADSICPE, ast_channel_adsicpe(c));
05321    iax_ie_append_int(&ied, IAX_IE_DATETIME, iax2_datetime(cai.timezone));
05322 
05323    if (iaxs[callno]->maxtime) {
05324       /* Initialize pingtime and auto-congest time */
05325       iaxs[callno]->pingtime = iaxs[callno]->maxtime / 2;
05326       iaxs[callno]->initid = iax2_sched_add(sched, iaxs[callno]->maxtime * 2, auto_congest, CALLNO_TO_PTR(callno));
05327    } else if (autokill) {
05328       iaxs[callno]->pingtime = autokill / 2;
05329       iaxs[callno]->initid = iax2_sched_add(sched, autokill * 2, auto_congest, CALLNO_TO_PTR(callno));
05330    }
05331 
05332    /* Check if there is an OSP token */
05333    osp_token_ptr = pbx_builtin_getvar_helper(c, "IAX2OSPTOKEN");
05334    if (!ast_strlen_zero(osp_token_ptr)) {
05335       if ((osp_token_length = strlen(osp_token_ptr)) <= IAX_MAX_OSPTOKEN_SIZE) {
05336          osp_block_index = 0;
05337          while (osp_token_length > 0) {
05338             osp_block_length = IAX_MAX_OSPBLOCK_SIZE < osp_token_length ? IAX_MAX_OSPBLOCK_SIZE : osp_token_length;
05339             osp_buffer[0] = osp_block_index;
05340             memcpy(osp_buffer + 1, osp_token_ptr, osp_block_length);
05341             iax_ie_append_raw(&ied, IAX_IE_OSPTOKEN, osp_buffer, osp_block_length + 1);
05342             osp_block_index++;
05343             osp_token_ptr += osp_block_length;
05344             osp_token_length -= osp_block_length;
05345          } 
05346       } else
05347          ast_log(LOG_WARNING, "OSP token is too long\n");
05348    } else if (iaxdebug)
05349       ast_debug(1, "OSP token is undefined\n");
05350 
05351    /* send the command using the appropriate socket for this peer */
05352    iaxs[callno]->sockfd = cai.sockfd;
05353 
05354    /* Add remote vars */
05355    if (variablestore) {
05356       AST_LIST_HEAD(, ast_var_t) *variablelist = variablestore->data;
05357       ast_debug(1, "Found an IAX variable store on this channel\n");
05358       AST_LIST_LOCK(variablelist);
05359       AST_LIST_TRAVERSE(variablelist, var, entries) {
05360          char tmp[256];
05361          int i;
05362          ast_debug(1, "Found IAXVAR '%s' with value '%s' (to transmit)\n", ast_var_name(var), ast_var_value(var));
05363          /* Automatically divide the value up into sized chunks */
05364          for (i = 0; i < strlen(ast_var_value(var)); i += 255 - (strlen(ast_var_name(var)) + 1)) {
05365             snprintf(tmp, sizeof(tmp), "%s=%s", ast_var_name(var), ast_var_value(var) + i);
05366             iax_ie_append_str(&ied, IAX_IE_VARIABLE, tmp);
05367          }
05368       }
05369       AST_LIST_UNLOCK(variablelist);
05370    }
05371 
05372    /* Transmit the string in a "NEW" request */
05373    add_empty_calltoken_ie(iaxs[callno], &ied); /* this _MUST_ be the last ie added */
05374    send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_NEW, 0, ied.buf, ied.pos, -1);
05375 
05376    ast_mutex_unlock(&iaxsl[callno]);
05377    ast_setstate(c, AST_STATE_RINGING);
05378 
05379    return 0;
05380 }
05381 
05382 static int iax2_hangup(struct ast_channel *c)
05383 {
05384    unsigned short callno = PTR_TO_CALLNO(ast_channel_tech_pvt(c));
05385    struct iax_ie_data ied;
05386    int alreadygone;
05387    memset(&ied, 0, sizeof(ied));
05388    ast_mutex_lock(&iaxsl[callno]);
05389    if (callno && iaxs[callno]) {
05390       ast_debug(1, "We're hanging up %s now...\n", ast_channel_name(c));
05391       alreadygone = ast_test_flag64(iaxs[callno], IAX_ALREADYGONE);
05392       /* Send the hangup unless we have had a transmission error or are already gone */
05393       iax_ie_append_byte(&ied, IAX_IE_CAUSECODE, (unsigned char)ast_channel_hangupcause(c));
05394       if (!iaxs[callno]->error && !alreadygone) {
05395          if (send_command_final(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_HANGUP, 0, ied.buf, ied.pos, -1)) {
05396             ast_log(LOG_WARNING, "No final packet could be sent for callno %d\n", callno);
05397          }
05398          if (!iaxs[callno]) {
05399             ast_mutex_unlock(&iaxsl[callno]);
05400             return 0;
05401          }
05402       }
05403       /* Explicitly predestroy it */
05404       iax2_predestroy(callno);
05405       /* If we were already gone to begin with, destroy us now */
05406       if (iaxs[callno] && alreadygone) {
05407          ast_debug(1, "Really destroying %s now...\n", ast_channel_name(c));
05408          iax2_destroy(callno);
05409       } else if (iaxs[callno]) {
05410          if (ast_sched_add(sched, 10000, scheduled_destroy, CALLNO_TO_PTR(callno)) < 0) {
05411             ast_log(LOG_ERROR, "Unable to schedule iax2 callno %d destruction?!!  Destroying immediately.\n", callno);
05412             iax2_destroy(callno);
05413          }
05414       }
05415    } else if (ast_channel_tech_pvt(c)) {
05416       /* If this call no longer exists, but the channel still
05417        * references it we need to set the channel's tech_pvt to null
05418        * to avoid ast_channel_free() trying to free it.
05419        */
05420       ast_channel_tech_pvt_set(c, NULL);
05421    }
05422    ast_mutex_unlock(&iaxsl[callno]);
05423    ast_verb(3, "Hungup '%s'\n", ast_channel_name(c));
05424    return 0;
05425 }
05426 
05427 /*!
05428  * \note expects the pvt to be locked
05429  */
05430 static int wait_for_peercallno(struct chan_iax2_pvt *pvt)
05431 {
05432    unsigned short callno = pvt->callno;
05433 
05434    if (!pvt->peercallno) {
05435       /* We don't know the remote side's call number, yet.  :( */
05436       int count = 10;
05437       while (count-- && pvt && !pvt->peercallno) {
05438          DEADLOCK_AVOIDANCE(&iaxsl[callno]);
05439          pvt = iaxs[callno];
05440       }
05441       if (!pvt || !pvt->peercallno) {
05442          return -1;
05443       }
05444    }
05445 
05446    return 0;
05447 }
05448 
05449 static int iax2_setoption(struct ast_channel *c, int option, void *data, int datalen)
05450 {
05451    struct ast_option_header *h;
05452    int res;
05453 
05454    switch (option) {
05455    case AST_OPTION_TXGAIN:
05456    case AST_OPTION_RXGAIN:
05457       /* these two cannot be sent, because they require a result */
05458       errno = ENOSYS;
05459       return -1;
05460    case AST_OPTION_OPRMODE:
05461       errno = EINVAL;
05462       return -1;
05463    case AST_OPTION_SECURE_SIGNALING:
05464    case AST_OPTION_SECURE_MEDIA:
05465    {
05466       unsigned short callno = PTR_TO_CALLNO(ast_channel_tech_pvt(c));
05467       ast_mutex_lock(&iaxsl[callno]);
05468       if ((*(int *) data)) {
05469          ast_set_flag64(iaxs[callno], IAX_FORCE_ENCRYPT);
05470       } else {
05471          ast_clear_flag64(iaxs[callno], IAX_FORCE_ENCRYPT);
05472       }
05473       ast_mutex_unlock(&iaxsl[callno]);
05474       return 0;
05475    }
05476    /* These options are sent to the other side across the network where
05477     * they will be passed to whatever channel is bridged there. Don't
05478     * do anything silly like pass an option that transmits pointers to
05479     * memory on this machine to a remote machine to use */
05480    case AST_OPTION_TONE_VERIFY:
05481    case AST_OPTION_TDD:
05482    case AST_OPTION_RELAXDTMF:
05483    case AST_OPTION_AUDIO_MODE:
05484    case AST_OPTION_DIGIT_DETECT:
05485    case AST_OPTION_FAX_DETECT:
05486    {
05487       unsigned short callno = PTR_TO_CALLNO(ast_channel_tech_pvt(c));
05488       struct chan_iax2_pvt *pvt;
05489 
05490       ast_mutex_lock(&iaxsl[callno]);
05491       pvt = iaxs[callno];
05492 
05493       if (wait_for_peercallno(pvt)) {
05494          ast_mutex_unlock(&iaxsl[callno]);
05495          return -1;
05496       }
05497 
05498       ast_mutex_unlock(&iaxsl[callno]);
05499 
05500       if (!(h = ast_malloc(datalen + sizeof(*h)))) {
05501          return -1;
05502       }
05503 
05504       h->flag = AST_OPTION_FLAG_REQUEST;
05505       h->option = htons(option);
05506       memcpy(h->data, data, datalen);
05507       res = send_command_locked(PTR_TO_CALLNO(ast_channel_tech_pvt(c)), AST_FRAME_CONTROL,
05508                  AST_CONTROL_OPTION, 0, (unsigned char *) h,
05509                  datalen + sizeof(*h), -1);
05510       ast_free(h);
05511       return res;
05512    }
05513    default:
05514       return -1;
05515    }
05516 
05517    /* Just in case someone does a break instead of a return */
05518    return -1;
05519 }
05520 
05521 static int iax2_queryoption(struct ast_channel *c, int option, void *data, int *datalen)
05522 {
05523    switch (option) {
05524    case AST_OPTION_SECURE_SIGNALING:
05525    case AST_OPTION_SECURE_MEDIA:
05526    {
05527       unsigned short callno = PTR_TO_CALLNO(ast_channel_tech_pvt(c));
05528       ast_mutex_lock(&iaxsl[callno]);
05529       *((int *) data) = ast_test_flag64(iaxs[callno], IAX_FORCE_ENCRYPT) ? 1 : 0;
05530       ast_mutex_unlock(&iaxsl[callno]);
05531       return 0;
05532    }
05533    default:
05534       return -1;
05535    }
05536 }
05537 
05538 static struct ast_frame *iax2_read(struct ast_channel *c) 
05539 {
05540    ast_debug(1, "I should never be called!\n");
05541    return &ast_null_frame;
05542 }
05543 
05544 static int iax2_key_rotate(const void *vpvt)
05545 {
05546    int res = 0;
05547    struct chan_iax2_pvt *pvt = (void *) vpvt;
05548    struct MD5Context md5;
05549    char key[17] = "";
05550    struct iax_ie_data ied = {
05551       .pos = 0,
05552    };
05553 
05554    ast_mutex_lock(&iaxsl[pvt->callno]);
05555    pvt->keyrotateid = ast_sched_add(sched, 120000 + (ast_random() % 180001), iax2_key_rotate, vpvt);
05556 
05557    snprintf(key, sizeof(key), "%lX", ast_random());
05558 
05559    MD5Init(&md5);
05560    MD5Update(&md5, (unsigned char *) key, strlen(key));
05561    MD5Final((unsigned char *) key, &md5);
05562 
05563    IAX_DEBUGDIGEST("Sending", key);
05564 
05565    iax_ie_append_raw(&ied, IAX_IE_CHALLENGE, key, 16);
05566 
05567    res = send_command(pvt, AST_FRAME_IAX, IAX_COMMAND_RTKEY, 0, ied.buf, ied.pos, -1);
05568 
05569    build_ecx_key((unsigned char *) key, pvt);
05570 
05571    ast_mutex_unlock(&iaxsl[pvt->callno]);
05572 
05573    return res;
05574 }
05575 
05576 static int iax2_start_transfer(unsigned short callno0, unsigned short callno1, int mediaonly)
05577 {
05578    int res;
05579    struct iax_ie_data ied0;
05580    struct iax_ie_data ied1;
05581    unsigned int transferid = (unsigned int)ast_random();
05582 
05583    if (IAX_CALLENCRYPTED(iaxs[callno0]) || IAX_CALLENCRYPTED(iaxs[callno1])) {
05584       ast_debug(1, "transfers are not supported for encrypted calls at this time\n");
05585       ast_set_flag64(iaxs[callno0], IAX_NOTRANSFER);
05586       ast_set_flag64(iaxs[callno1], IAX_NOTRANSFER);
05587       return 0;
05588    }
05589 
05590    memset(&ied0, 0, sizeof(ied0));
05591    iax_ie_append_addr(&ied0, IAX_IE_APPARENT_ADDR, &iaxs[callno1]->addr);
05592    iax_ie_append_short(&ied0, IAX_IE_CALLNO, iaxs[callno1]->peercallno);
05593    iax_ie_append_int(&ied0, IAX_IE_TRANSFERID, transferid);
05594 
05595    memset(&ied1, 0, sizeof(ied1));
05596    iax_ie_append_addr(&ied1, IAX_IE_APPARENT_ADDR, &iaxs[callno0]->addr);
05597    iax_ie_append_short(&ied1, IAX_IE_CALLNO, iaxs[callno0]->peercallno);
05598    iax_ie_append_int(&ied1, IAX_IE_TRANSFERID, transferid);
05599 
05600    res = send_command(iaxs[callno0], AST_FRAME_IAX, IAX_COMMAND_TXREQ, 0, ied0.buf, ied0.pos, -1);
05601    if (res)
05602       return -1;
05603    res = send_command(iaxs[callno1], AST_FRAME_IAX, IAX_COMMAND_TXREQ, 0, ied1.buf, ied1.pos, -1);
05604    if (res)
05605       return -1;
05606    iaxs[callno0]->transferring = mediaonly ? TRANSFER_MBEGIN : TRANSFER_BEGIN;
05607    iaxs[callno1]->transferring = mediaonly ? TRANSFER_MBEGIN : TRANSFER_BEGIN;
05608    return 0;
05609 }
05610 
05611 static void lock_both(unsigned short callno0, unsigned short callno1)
05612 {
05613    ast_mutex_lock(&iaxsl[callno0]);
05614    while (ast_mutex_trylock(&iaxsl[callno1])) {
05615       DEADLOCK_AVOIDANCE(&iaxsl[callno0]);
05616    }
05617 }
05618 
05619 static void unlock_both(unsigned short callno0, unsigned short callno1)
05620 {
05621    ast_mutex_unlock(&iaxsl[callno1]);
05622    ast_mutex_unlock(&iaxsl[callno0]);
05623 }
05624 
05625 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)
05626 {
05627    struct ast_channel *cs[3];
05628    struct ast_channel *who, *other;
05629    int to = -1;
05630    int res = -1;
05631    int transferstarted=0;
05632    struct ast_frame *f;
05633    unsigned short callno0 = PTR_TO_CALLNO(ast_channel_tech_pvt(c0));
05634    unsigned short callno1 = PTR_TO_CALLNO(ast_channel_tech_pvt(c1));
05635    struct timeval waittimer = {0, 0};
05636 
05637    /* We currently do not support native bridging if a timeoutms value has been provided */
05638    if (timeoutms > 0) {
05639       return AST_BRIDGE_FAILED;
05640    }
05641 
05642    timeoutms = -1;
05643 
05644    lock_both(callno0, callno1);
05645    if (!iaxs[callno0] || !iaxs[callno1]) {
05646       unlock_both(callno0, callno1);
05647       return AST_BRIDGE_FAILED;
05648    }
05649    /* Put them in native bridge mode */
05650    if (!(flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1))) {
05651       iaxs[callno0]->bridgecallno = callno1;
05652       iaxs[callno1]->bridgecallno = callno0;
05653    }
05654    unlock_both(callno0, callno1);
05655 
05656    /* If not, try to bridge until we can execute a transfer, if we can */
05657    cs[0] = c0;
05658    cs[1] = c1;
05659    for (/* ever */;;) {
05660       /* Check in case we got masqueraded into */
05661       if ((ast_channel_tech(c0) != &iax2_tech) || (ast_channel_tech(c1) != &iax2_tech)) {
05662          ast_verb(3, "Can't masquerade, we're different...\n");
05663          /* Remove from native mode */
05664          if (ast_channel_tech(c0) == &iax2_tech) {
05665             ast_mutex_lock(&iaxsl[callno0]);
05666             iaxs[callno0]->bridgecallno = 0;
05667             ast_mutex_unlock(&iaxsl[callno0]);
05668          }
05669          if (ast_channel_tech(c1) == &iax2_tech) {
05670             ast_mutex_lock(&iaxsl[callno1]);
05671             iaxs[callno1]->bridgecallno = 0;
05672             ast_mutex_unlock(&iaxsl[callno1]);
05673          }
05674          return AST_BRIDGE_FAILED_NOWARN;
05675       }
05676       if (!(ast_format_cap_identical(ast_channel_nativeformats(c0), ast_channel_nativeformats(c1)))) {
05677          char buf0[256];
05678          char buf1[256];
05679          ast_getformatname_multiple(buf0, sizeof(buf0), ast_channel_nativeformats(c0));
05680          ast_getformatname_multiple(buf1, sizeof(buf1), ast_channel_nativeformats(c1));
05681          ast_verb(3, "Operating with different codecs [%s] [%s] , can't native bridge...\n", buf0, buf1);
05682          /* Remove from native mode */
05683          lock_both(callno0, callno1);
05684          if (iaxs[callno0])
05685             iaxs[callno0]->bridgecallno = 0;
05686          if (iaxs[callno1])
05687             iaxs[callno1]->bridgecallno = 0;
05688          unlock_both(callno0, callno1);
05689          return AST_BRIDGE_FAILED_NOWARN;
05690       }
05691       /* check if transferred and if we really want native bridging */
05692       if (!transferstarted && !ast_test_flag64(iaxs[callno0], IAX_NOTRANSFER) && !ast_test_flag64(iaxs[callno1], IAX_NOTRANSFER)) {
05693          /* Try the transfer */
05694          if (iax2_start_transfer(callno0, callno1, (flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1)) ||
05695                      ast_test_flag64(iaxs[callno0], IAX_TRANSFERMEDIA) | ast_test_flag64(iaxs[callno1], IAX_TRANSFERMEDIA)))
05696             ast_log(LOG_WARNING, "Unable to start the transfer\n");
05697          transferstarted = 1;
05698       }
05699       if ((iaxs[callno0]->transferring == TRANSFER_RELEASED) && (iaxs[callno1]->transferring == TRANSFER_RELEASED)) {
05700          /* Call has been transferred.  We're no longer involved */
05701          struct timeval now = ast_tvnow();
05702          if (ast_tvzero(waittimer)) {
05703             waittimer = now;
05704          } else if (now.tv_sec - waittimer.tv_sec > IAX_LINGER_TIMEOUT) {
05705             ast_channel_softhangup_internal_flag_add(c0, AST_SOFTHANGUP_DEV);
05706             ast_channel_softhangup_internal_flag_add(c1, AST_SOFTHANGUP_DEV);
05707             *fo = NULL;
05708             *rc = c0;
05709             res = AST_BRIDGE_COMPLETE;
05710             break;
05711          }
05712       }
05713       to = 1000;
05714       who = ast_waitfor_n(cs, 2, &to);
05715       /* XXX This will need to be updated to calculate
05716        * timeout correctly once timeoutms is allowed to be
05717        * > 0. Right now, this can go badly if the waitfor
05718        * times out in less than a millisecond
05719        */
05720       if (timeoutms > -1) {
05721          timeoutms -= (1000 - to);
05722          if (timeoutms < 0)
05723             timeoutms = 0;
05724       }
05725       if (!who) {
05726          if (!timeoutms) {
05727             res = AST_BRIDGE_RETRY;
05728             break;
05729          }
05730          if (ast_check_hangup(c0) || ast_check_hangup(c1)) {
05731             res = AST_BRIDGE_FAILED;
05732             break;
05733          }
05734          continue;
05735       }
05736       f = ast_read(who);
05737       if (!f) {
05738          *fo = NULL;
05739          *rc = who;
05740          res = AST_BRIDGE_COMPLETE;
05741          break;
05742       }
05743       other = (who == c0) ? c1 : c0;  /* the 'other' channel */
05744       if (f->frametype == AST_FRAME_CONTROL && !(flags & AST_BRIDGE_IGNORE_SIGS)) {
05745          switch (f->subclass.integer) {
05746          case AST_CONTROL_VIDUPDATE:
05747          case AST_CONTROL_SRCUPDATE:
05748          case AST_CONTROL_SRCCHANGE:
05749          case AST_CONTROL_T38_PARAMETERS:
05750             ast_write(other, f);
05751             break;
05752          case AST_CONTROL_PVT_CAUSE_CODE:
05753             ast_channel_hangupcause_hash_set(other, f->data.ptr, f->datalen);
05754             break;
05755          default:
05756             *fo = f;
05757             *rc = who;
05758             res = AST_BRIDGE_COMPLETE;
05759             break;
05760          }
05761          if (res == AST_BRIDGE_COMPLETE) {
05762             break;
05763          }
05764       } else if (f->frametype == AST_FRAME_VOICE
05765          || f->frametype == AST_FRAME_TEXT
05766          || f->frametype == AST_FRAME_VIDEO
05767          || f->frametype == AST_FRAME_IMAGE) {
05768          ast_write(other, f);
05769       } else if (f->frametype == AST_FRAME_DTMF) {
05770          /* monitored dtmf take out of the bridge.
05771           * check if we monitor the specific source.
05772           */
05773          int monitored_source = (who == c0) ? AST_BRIDGE_DTMF_CHANNEL_0 : AST_BRIDGE_DTMF_CHANNEL_1;
05774 
05775          if (flags & monitored_source) {
05776             *rc = who;
05777             *fo = f;
05778             res = AST_BRIDGE_COMPLETE;
05779             /* Remove from native mode */
05780             break;
05781          }
05782          ast_write(other, f);
05783       }
05784       ast_frfree(f);
05785       /* Swap who gets priority */
05786       cs[2] = cs[0];
05787       cs[0] = cs[1];
05788       cs[1] = cs[2];
05789    }
05790    lock_both(callno0, callno1);
05791    if(iaxs[callno0])
05792       iaxs[callno0]->bridgecallno = 0;
05793    if(iaxs[callno1])
05794       iaxs[callno1]->bridgecallno = 0;
05795    unlock_both(callno0, callno1);
05796    return res;
05797 }
05798 
05799 static int iax2_answer(struct ast_channel *c)
05800 {
05801    unsigned short callno = PTR_TO_CALLNO(ast_channel_tech_pvt(c));
05802    ast_debug(1, "Answering IAX2 call\n");
05803    ast_mutex_lock(&iaxsl[callno]);
05804    if (iaxs[callno])
05805       iax2_ami_channelupdate(iaxs[callno]);
05806    ast_mutex_unlock(&iaxsl[callno]);
05807    return send_command_locked(callno, AST_FRAME_CONTROL, AST_CONTROL_ANSWER, 0, NULL, 0, -1);
05808 }
05809 
05810 static int iax2_indicate(struct ast_channel *c, int condition, const void *data, size_t datalen)
05811 {
05812    unsigned short callno = PTR_TO_CALLNO(ast_channel_tech_pvt(c));
05813    struct chan_iax2_pvt *pvt;
05814    int res = 0;
05815 
05816    if (iaxdebug)
05817       ast_debug(1, "Indicating condition %d\n", condition);
05818 
05819    ast_mutex_lock(&iaxsl[callno]);
05820    pvt = iaxs[callno];
05821 
05822    if (wait_for_peercallno(pvt)) {
05823       res = -1;
05824       goto done;
05825    }
05826 
05827    switch (condition) {
05828    case AST_CONTROL_HOLD:
05829       if (strcasecmp(pvt->mohinterpret, "passthrough")) {
05830          ast_moh_start(c, data, pvt->mohinterpret);
05831          goto done;
05832       }
05833       break;
05834    case AST_CONTROL_UNHOLD:
05835       if (strcasecmp(pvt->mohinterpret, "passthrough")) {
05836          ast_moh_stop(c);
05837          goto done;
05838       }
05839       break;
05840    case AST_CONTROL_CONNECTED_LINE:
05841    case AST_CONTROL_REDIRECTING:
05842       if (!ast_test_flag64(pvt, IAX_SENDCONNECTEDLINE)) {
05843          /* We are not configured to allow sending these updates. */
05844          ast_debug(2, "Callno %u: Config blocked sending control frame %d.\n",
05845             callno, condition);
05846          goto done;
05847       }
05848       break;
05849    case AST_CONTROL_PVT_CAUSE_CODE:
05850       res = -1;
05851       goto done;
05852    }
05853 
05854    res = send_command(pvt, AST_FRAME_CONTROL, condition, 0, data, datalen, -1);
05855 
05856 done:
05857    ast_mutex_unlock(&iaxsl[callno]);
05858 
05859    return res;
05860 }
05861 
05862 static int iax2_transfer(struct ast_channel *c, const char *dest)
05863 {
05864    unsigned short callno = PTR_TO_CALLNO(ast_channel_tech_pvt(c));
05865    struct iax_ie_data ied = { "", };
05866    char tmp[256], *context;
05867    enum ast_control_transfer message = AST_TRANSFER_SUCCESS;
05868    ast_copy_string(tmp, dest, sizeof(tmp));
05869    context = strchr(tmp, '@');
05870    if (context) {
05871       *context = '\0';
05872       context++;
05873    }
05874    iax_ie_append_str(&ied, IAX_IE_CALLED_NUMBER, tmp);
05875    if (context)
05876       iax_ie_append_str(&ied, IAX_IE_CALLED_CONTEXT, context);
05877    ast_debug(1, "Transferring '%s' to '%s'\n", ast_channel_name(c), dest);
05878    ast_queue_control_data(c, AST_CONTROL_TRANSFER, &message, sizeof(message));
05879    return send_command_locked(callno, AST_FRAME_IAX, IAX_COMMAND_TRANSFER, 0, ied.buf, ied.pos, -1);
05880 }
05881 
05882 static int iax2_getpeertrunk(struct sockaddr_in sin)
05883 {
05884    struct iax2_peer *peer;
05885    int res = 0;
05886    struct ao2_iterator i;
05887 
05888    i = ao2_iterator_init(peers, 0);
05889    while ((peer = ao2_iterator_next(&i))) {
05890       struct sockaddr_in peer_addr;
05891 
05892       ast_sockaddr_to_sin(&peer->addr, &peer_addr);
05893 
05894       if ((peer_addr.sin_addr.s_addr == sin.sin_addr.s_addr) &&
05895           (peer_addr.sin_port == sin.sin_port)) {
05896          res = ast_test_flag64(peer, IAX_TRUNK);
05897          peer_unref(peer);
05898          break;
05899       }
05900       peer_unref(peer);
05901    }
05902    ao2_iterator_destroy(&i);
05903 
05904    return res;
05905 }
05906 
05907 /*! \brief  Create new call, interface with the PBX core */
05908 static struct ast_channel *ast_iax2_new(int callno, int state, iax2_format capability, const char *linkedid, unsigned int cachable)
05909 {
05910    struct ast_channel *tmp;
05911    struct chan_iax2_pvt *i;
05912    struct ast_variable *v = NULL;
05913    struct ast_format tmpfmt;
05914    struct ast_callid *callid;
05915 
05916    if (!(i = iaxs[callno])) {
05917       ast_log(LOG_WARNING, "No IAX2 pvt found for callno '%d' !\n", callno);
05918       return NULL;
05919    }
05920 
05921    /* Don't hold call lock */
05922    ast_mutex_unlock(&iaxsl[callno]);
05923    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);
05924    ast_mutex_lock(&iaxsl[callno]);
05925    if (i != iaxs[callno]) {
05926       if (tmp) {
05927          /* unlock and relock iaxsl[callno] to preserve locking order */
05928          ast_mutex_unlock(&iaxsl[callno]);
05929          tmp = ast_channel_release(tmp);
05930          ast_mutex_lock(&iaxsl[callno]);
05931       }
05932       return NULL;
05933    }
05934    iax2_ami_channelupdate(i);
05935    if (!tmp) {
05936       return NULL;
05937    }
05938 
05939    if ((callid = iaxs[callno]->callid)) {
05940       ast_channel_callid_set(tmp, callid);
05941    }
05942 
05943    ast_channel_tech_set(tmp, &iax2_tech);
05944    /* We can support any format by default, until we get restricted */
05945    ast_format_cap_from_old_bitfield(ast_channel_nativeformats(tmp), capability);
05946    ast_best_codec(ast_channel_nativeformats(tmp), &tmpfmt);
05947 
05948    ast_format_copy(ast_channel_readformat(tmp), &tmpfmt);
05949    ast_format_copy(ast_channel_rawreadformat(tmp), &tmpfmt);
05950    ast_format_copy(ast_channel_writeformat(tmp), &tmpfmt);
05951    ast_format_copy(ast_channel_rawwriteformat(tmp), &tmpfmt);
05952 
05953    ast_channel_tech_pvt_set(tmp, CALLNO_TO_PTR(i->callno));
05954 
05955    if (!ast_strlen_zero(i->parkinglot))
05956       ast_channel_parkinglot_set(tmp, i->parkinglot);
05957    /* Don't use ast_set_callerid() here because it will
05958     * generate a NewCallerID event before the NewChannel event */
05959    if (!ast_strlen_zero(i->ani)) {
05960       ast_channel_caller(tmp)->ani.number.valid = 1;
05961       ast_channel_caller(tmp)->ani.number.str = ast_strdup(i->ani);
05962    } else if (!ast_strlen_zero(i->cid_num)) {
05963       ast_channel_caller(tmp)->ani.number.valid = 1;
05964       ast_channel_caller(tmp)->ani.number.str = ast_strdup(i->cid_num);
05965    }
05966    ast_channel_dialed(tmp)->number.str = ast_strdup(i->dnid);
05967    if (!ast_strlen_zero(i->rdnis)) {
05968       ast_channel_redirecting(tmp)->from.number.valid = 1;
05969       ast_channel_redirecting(tmp)->from.number.str = ast_strdup(i->rdnis);
05970    }
05971    ast_channel_caller(tmp)->id.name.presentation = i->calling_pres;
05972    ast_channel_caller(tmp)->id.number.presentation = i->calling_pres;
05973    ast_channel_caller(tmp)->id.number.plan = i->calling_ton;
05974    ast_channel_dialed(tmp)->transit_network_select = i->calling_tns;
05975    if (!ast_strlen_zero(i->language))
05976       ast_channel_language_set(tmp, i->language);
05977    if (!ast_strlen_zero(i->accountcode))
05978       ast_channel_accountcode_set(tmp, i->accountcode);
05979    if (i->amaflags)
05980       ast_channel_amaflags_set(tmp, i->amaflags);
05981    ast_channel_context_set(tmp, i->context);
05982    ast_channel_exten_set(tmp, i->exten);
05983    if (i->adsi)
05984       ast_channel_adsicpe_set(tmp, i->peeradsicpe);
05985    else
05986       ast_channel_adsicpe_set(tmp, AST_ADSI_UNAVAILABLE);
05987    i->owner = tmp;
05988    i->capability = capability;
05989 
05990    if (!cachable) {
05991       ast_set_flag(ast_channel_flags(tmp), AST_FLAG_DISABLE_DEVSTATE_CACHE);
05992    }
05993 
05994    /* Set inherited variables */
05995    if (i->vars) {
05996       for (v = i->vars ; v ; v = v->next)
05997          pbx_builtin_setvar_helper(tmp, v->name, v->value);
05998    }
05999    if (i->iaxvars) {
06000       struct ast_datastore *variablestore;
06001       struct ast_variable *var, *prev = NULL;
06002       AST_LIST_HEAD(, ast_var_t) *varlist;
06003       ast_debug(1, "Loading up the channel with IAXVARs\n");
06004       varlist = ast_calloc(1, sizeof(*varlist));
06005       variablestore = ast_datastore_alloc(&iax2_variable_datastore_info, NULL);
06006       if (variablestore && varlist) {
06007          variablestore->data = varlist;
06008          variablestore->inheritance = DATASTORE_INHERIT_FOREVER;
06009          AST_LIST_HEAD_INIT(varlist);
06010          for (var = i->iaxvars; var; var = var->next) {
06011             struct ast_var_t *newvar = ast_var_assign(var->name, var->value);
06012             if (prev)
06013                ast_free(prev);
06014             prev = var;
06015             if (!newvar) {
06016                /* Don't abort list traversal, as this would leave i->iaxvars in an inconsistent state. */
06017                ast_log(LOG_ERROR, "Memory allocation error while processing IAX2 variables\n");
06018             } else {
06019                AST_LIST_INSERT_TAIL(varlist, newvar, entries);
06020             }
06021          }
06022          if (prev)
06023             ast_free(prev);
06024          i->iaxvars = NULL;
06025          ast_channel_datastore_add(i->owner, variablestore);
06026       } else {
06027          if (variablestore) {
06028             ast_datastore_free(variablestore);
06029          }
06030          if (varlist) {
06031             ast_free(varlist);
06032          }
06033       }
06034    }
06035 
06036    if (state != AST_STATE_DOWN) {
06037       if (ast_pbx_start(tmp)) {
06038          ast_log(LOG_WARNING, "Unable to start PBX on %s\n", ast_channel_name(tmp));
06039          ast_hangup(tmp);
06040          i->owner = NULL;
06041          return NULL;
06042       }
06043    }
06044 
06045    ast_module_ref(ast_module_info->self);
06046    return tmp;
06047 }
06048 
06049 static unsigned int calc_txpeerstamp(struct iax2_trunk_peer *tpeer, int sampms, struct timeval *now)
06050 {
06051    unsigned long int mssincetx; /* unsigned to handle overflows */
06052    long int ms, pred;
06053 
06054    tpeer->trunkact = *now;
06055    mssincetx = ast_tvdiff_ms(*now, tpeer->lasttxtime);
06056    if (mssincetx > 5000 || ast_tvzero(tpeer->txtrunktime)) {
06057       /* If it's been at least 5 seconds since the last time we transmitted on this trunk, reset our timers */
06058       tpeer->txtrunktime = *now;
06059       tpeer->lastsent = 999999;
06060    }
06061    /* Update last transmit time now */
06062    tpeer->lasttxtime = *now;
06063    
06064    /* Calculate ms offset */
06065    ms = ast_tvdiff_ms(*now, tpeer->txtrunktime);
06066    /* Predict from last value */
06067    pred = tpeer->lastsent + sampms;
06068    if (abs(ms - pred) < MAX_TIMESTAMP_SKEW)
06069       ms = pred;
06070    
06071    /* We never send the same timestamp twice, so fudge a little if we must */
06072    if (ms == tpeer->lastsent)
06073       ms = tpeer->lastsent + 1;
06074    tpeer->lastsent = ms;
06075    return ms;
06076 }
06077 
06078 static unsigned int fix_peerts(struct timeval *rxtrunktime, int callno, unsigned int ts)
06079 {
06080    long ms; /* NOT unsigned */
06081    if (ast_tvzero(iaxs[callno]->rxcore)) {
06082       /* Initialize rxcore time if appropriate */
06083       iaxs[callno]->rxcore = ast_tvnow();
06084       /* Round to nearest 20ms so traces look pretty */
06085       iaxs[callno]->rxcore.tv_usec -= iaxs[callno]->rxcore.tv_usec % 20000;
06086    }
06087    /* Calculate difference between trunk and channel */
06088    ms = ast_tvdiff_ms(*rxtrunktime, iaxs[callno]->rxcore);
06089    /* Return as the sum of trunk time and the difference between trunk and real time */
06090    return ms + ts;
06091 }
06092 
06093 static unsigned int calc_timestamp(struct chan_iax2_pvt *p, unsigned int ts, struct ast_frame *f)
06094 {
06095    int ms;
06096    int voice = 0;
06097    int genuine = 0;
06098    int adjust;
06099    int rate = ast_format_rate(&f->subclass.format) / 1000;
06100    struct timeval *delivery = NULL;
06101 
06102 
06103    /* What sort of frame do we have?: voice is self-explanatory
06104       "genuine" means an IAX frame - things like LAGRQ/RP, PING/PONG, ACK
06105       non-genuine frames are CONTROL frames [ringing etc], DTMF
06106       The "genuine" distinction is needed because genuine frames must get a clock-based timestamp,
06107       the others need a timestamp slaved to the voice frames so that they go in sequence
06108    */
06109    if (f->frametype == AST_FRAME_VOICE) {
06110       voice = 1;
06111       delivery = &f->delivery;
06112    } else if (f->frametype == AST_FRAME_IAX) {
06113       genuine = 1;
06114    } else if (f->frametype == AST_FRAME_CNG) {
06115       p->notsilenttx = 0;
06116    }
06117 
06118    if (ast_tvzero(p->offset)) {
06119       p->offset = ast_tvnow();
06120       /* Round to nearest 20ms for nice looking traces */
06121       p->offset.tv_usec -= p->offset.tv_usec % 20000;
06122    }
06123    /* If the timestamp is specified, just send it as is */
06124    if (ts)
06125       return ts;
06126    /* If we have a time that the frame arrived, always use it to make our timestamp */
06127    if (delivery && !ast_tvzero(*delivery)) {
06128       ms = ast_tvdiff_ms(*delivery, p->offset);
06129       if (ms < 0) {
06130          ms = 0;
06131       }
06132       if (iaxdebug)
06133          ast_debug(3, "calc_timestamp: call %d/%d: Timestamp slaved to delivery time\n", p->callno, iaxs[p->callno]->peercallno);
06134    } else {
06135       ms = ast_tvdiff_ms(ast_tvnow(), p->offset);
06136       if (ms < 0)
06137          ms = 0;
06138       if (voice) {
06139          /* On a voice frame, use predicted values if appropriate */
06140          if (p->notsilenttx && abs(ms - p->nextpred) <= MAX_TIMESTAMP_SKEW) {
06141             /* Adjust our txcore, keeping voice and non-voice synchronized */
06142             /* AN EXPLANATION:
06143                When we send voice, we usually send "calculated" timestamps worked out
06144                on the basis of the number of samples sent. When we send other frames,
06145                we usually send timestamps worked out from the real clock.
06146                The problem is that they can tend to drift out of step because the 
06147                   source channel's clock and our clock may not be exactly at the same rate.
06148                We fix this by continuously "tweaking" p->offset.  p->offset is "time zero"
06149                for this call.  Moving it adjusts timestamps for non-voice frames.
06150                We make the adjustment in the style of a moving average.  Each time we
06151                adjust p->offset by 10% of the difference between our clock-derived
06152                timestamp and the predicted timestamp.  That's why you see "10000"
06153                below even though IAX2 timestamps are in milliseconds.
06154                The use of a moving average avoids offset moving too radically.
06155                Generally, "adjust" roams back and forth around 0, with offset hardly
06156                changing at all.  But if a consistent different starts to develop it
06157                will be eliminated over the course of 10 frames (200-300msecs) 
06158             */
06159             adjust = (ms - p->nextpred);
06160             if (adjust < 0)
06161                p->offset = ast_tvsub(p->offset, ast_samp2tv(abs(adjust), 10000));
06162             else if (adjust > 0)
06163                p->offset = ast_tvadd(p->offset, ast_samp2tv(adjust, 10000));
06164 
06165             if (!p->nextpred) {
06166                p->nextpred = ms; /*f->samples / rate;*/
06167                if (p->nextpred <= p->lastsent)
06168                   p->nextpred = p->lastsent + 3;
06169             }
06170             ms = p->nextpred;
06171          } else {
06172                 /* in this case, just use the actual
06173             * time, since we're either way off
06174             * (shouldn't happen), or we're  ending a
06175             * silent period -- and seed the next
06176             * predicted time.  Also, round ms to the
06177             * next multiple of frame size (so our
06178             * silent periods are multiples of
06179             * frame size too) */
06180 
06181             if (iaxdebug && abs(ms - p->nextpred) > MAX_TIMESTAMP_SKEW )
06182                ast_debug(1, "predicted timestamp skew (%u) > max (%u), using real ts instead.\n",
06183                   abs(ms - p->nextpred), MAX_TIMESTAMP_SKEW);
06184 
06185             if (f->samples >= rate) /* check to make sure we don't core dump */
06186             {
06187                int diff = ms % (f->samples / rate);
06188                if (diff)
06189                    ms += f->samples/rate - diff;
06190             }
06191 
06192             p->nextpred = ms;
06193             p->notsilenttx = 1;
06194          }
06195       } else if ( f->frametype == AST_FRAME_VIDEO ) {
06196          /*
06197          * IAX2 draft 03 says that timestamps MUST be in order.
06198          * It does not say anything about several frames having the same timestamp
06199          * When transporting video, we can have a frame that spans multiple iax packets
06200          * (so called slices), so it would make sense to use the same timestamp for all of
06201          * them
06202          * We do want to make sure that frames don't go backwards though
06203          */
06204          if ( (unsigned int)ms < p->lastsent )
06205             ms = p->lastsent;
06206       } else {
06207          /* On a dataframe, use last value + 3 (to accomodate jitter buffer shrinking) if appropriate unless
06208             it's a genuine frame */
06209          if (genuine) {
06210             /* genuine (IAX LAGRQ etc) must keep their clock-based stamps */
06211             if (ms <= p->lastsent)
06212                ms = p->lastsent + 3;
06213          } else if (abs(ms - p->lastsent) <= MAX_TIMESTAMP_SKEW) {
06214             /* non-genuine frames (!?) (DTMF, CONTROL) should be pulled into the predicted stream stamps */
06215             ms = p->lastsent + 3;
06216          }
06217       }
06218    }
06219    p->lastsent = ms;
06220    if (voice)
06221       p->nextpred = p->nextpred + f->samples / rate;
06222    return ms;
06223 }
06224 
06225 static unsigned int calc_rxstamp(struct chan_iax2_pvt *p, unsigned int offset)
06226 {
06227    /* Returns where in "receive time" we are.  That is, how many ms
06228       since we received (or would have received) the frame with timestamp 0 */
06229    int ms;
06230 #ifdef IAXTESTS
06231    int jit;
06232 #endif /* IAXTESTS */
06233    /* Setup rxcore if necessary */
06234    if (ast_tvzero(p->rxcore)) {
06235       p->rxcore = ast_tvnow();
06236       if (iaxdebug)
06237          ast_debug(1, "calc_rxstamp: call=%d: rxcore set to %d.%6.6d - %dms\n",
06238                p->callno, (int)(p->rxcore.tv_sec), (int)(p->rxcore.tv_usec), offset);
06239       p->rxcore = ast_tvsub(p->rxcore, ast_samp2tv(offset, 1000));
06240 #if 1
06241       if (iaxdebug)
06242          ast_debug(1, "calc_rxstamp: call=%d: works out as %d.%6.6d\n",
06243                p->callno, (int)(p->rxcore.tv_sec),(int)( p->rxcore.tv_usec));
06244 #endif
06245    }
06246 
06247    ms = ast_tvdiff_ms(ast_tvnow(), p->rxcore);
06248 #ifdef IAXTESTS
06249    if (test_jit) {
06250       if (!test_jitpct || ((100.0 * ast_random() / (RAND_MAX + 1.0)) < test_jitpct)) {
06251          jit = (int)((float)test_jit * ast_random() / (RAND_MAX + 1.0));
06252          if ((int)(2.0 * ast_random() / (RAND_MAX + 1.0)))
06253             jit = -jit;
06254          ms += jit;
06255       }
06256    }
06257    if (test_late) {
06258       ms += test_late;
06259       test_late = 0;
06260    }
06261 #endif /* IAXTESTS */
06262    return ms;
06263 }
06264 
06265 static struct iax2_trunk_peer *find_tpeer(struct sockaddr_in *sin, int fd)
06266 {
06267    struct iax2_trunk_peer *tpeer = NULL;
06268    
06269    /* Finds and locks trunk peer */
06270    AST_LIST_LOCK(&tpeers);
06271 
06272    AST_LIST_TRAVERSE(&tpeers, tpeer, list) {
06273       if (!inaddrcmp(&tpeer->addr, sin)) {
06274          ast_mutex_lock(&tpeer->lock);
06275          break;
06276       }
06277    }
06278 
06279    if (!tpeer) {
06280       if ((tpeer = ast_calloc(1, sizeof(*tpeer)))) {
06281          ast_mutex_init(&tpeer->lock);
06282          tpeer->lastsent = 9999;
06283          memcpy(&tpeer->addr, sin, sizeof(tpeer->addr));
06284          tpeer->trunkact = ast_tvnow();
06285          ast_mutex_lock(&tpeer->lock);
06286          tpeer->sockfd = fd;
06287 #ifdef SO_NO_CHECK
06288          setsockopt(tpeer->sockfd, SOL_SOCKET, SO_NO_CHECK, &nochecksums, sizeof(nochecksums));
06289 #endif
06290          ast_debug(1, "Created trunk peer for '%s:%d'\n", ast_inet_ntoa(tpeer->addr.sin_addr), ntohs(tpeer->addr.sin_port));
06291          AST_LIST_INSERT_TAIL(&tpeers, tpeer, list);
06292       }
06293    }
06294 
06295    AST_LIST_UNLOCK(&tpeers);
06296 
06297    return tpeer;
06298 }
06299 
06300 static int iax2_trunk_queue(struct chan_iax2_pvt *pvt, struct iax_frame *fr)
06301 {
06302    struct ast_frame *f;
06303    struct iax2_trunk_peer *tpeer;
06304    void *tmp, *ptr;
06305    struct timeval now;
06306    struct ast_iax2_meta_trunk_entry *met;
06307    struct ast_iax2_meta_trunk_mini *mtm;
06308 
06309    f = &fr->af;
06310    tpeer = find_tpeer(&pvt->addr, pvt->sockfd);
06311    if (tpeer) {
06312       if (tpeer->trunkdatalen + f->datalen + 4 >= tpeer->trunkdataalloc) {
06313          /* Need to reallocate space */
06314          if (tpeer->trunkdataalloc < trunkmaxsize) {
06315             if (!(tmp = ast_realloc(tpeer->trunkdata, tpeer->trunkdataalloc + DEFAULT_TRUNKDATA + IAX2_TRUNK_PREFACE))) {
06316                ast_mutex_unlock(&tpeer->lock);
06317                return -1;
06318             }
06319 
06320             tpeer->trunkdataalloc += DEFAULT_TRUNKDATA;
06321             tpeer->trunkdata = tmp;
06322             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);
06323          } else {
06324             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));
06325             ast_mutex_unlock(&tpeer->lock);
06326             return -1;
06327          }
06328       }
06329 
06330       /* Append to meta frame */
06331       ptr = tpeer->trunkdata + IAX2_TRUNK_PREFACE + tpeer->trunkdatalen;
06332       if (ast_test_flag64(&globalflags, IAX_TRUNKTIMESTAMPS)) {
06333          mtm = (struct ast_iax2_meta_trunk_mini *)ptr;
06334          mtm->len = htons(f->datalen);
06335          mtm->mini.callno = htons(pvt->callno);
06336          mtm->mini.ts = htons(0xffff & fr->ts);
06337          ptr += sizeof(struct ast_iax2_meta_trunk_mini);
06338          tpeer->trunkdatalen += sizeof(struct ast_iax2_meta_trunk_mini);
06339       } else {
06340          met = (struct ast_iax2_meta_trunk_entry *)ptr;
06341          /* Store call number and length in meta header */
06342          met->callno = htons(pvt->callno);
06343          met->len = htons(f->datalen);
06344          /* Advance pointers/decrease length past trunk entry header */
06345          ptr += sizeof(struct ast_iax2_meta_trunk_entry);
06346          tpeer->trunkdatalen += sizeof(struct ast_iax2_meta_trunk_entry);
06347       }
06348       /* Copy actual trunk data */
06349       memcpy(ptr, f->data.ptr, f->datalen);
06350       tpeer->trunkdatalen += f->datalen;
06351 
06352       tpeer->calls++;
06353 
06354       /* track the largest mtu we actually have sent */
06355       if (tpeer->trunkdatalen + f->datalen + 4 > trunk_maxmtu) 
06356          trunk_maxmtu = tpeer->trunkdatalen + f->datalen + 4 ; 
06357 
06358       /* if we have enough for a full MTU, ship it now without waiting */
06359       if (global_max_trunk_mtu > 0 && tpeer->trunkdatalen + f->datalen + 4 >= global_max_trunk_mtu) {
06360          now = ast_tvnow();
06361          send_trunk(tpeer, &now); 
06362          trunk_untimed ++; 
06363       }
06364 
06365       ast_mutex_unlock(&tpeer->lock);
06366    }
06367    return 0;
06368 }
06369 
06370 /* IAX2 encryption requires 16 to 32 bytes of random padding to be present
06371  * before the encryption data.  This function randomizes that data. */
06372 static void build_rand_pad(unsigned char *buf, ssize_t len)
06373 {
06374    long tmp;
06375    for (tmp = ast_random(); len > 0; tmp = ast_random()) {
06376       memcpy(buf, (unsigned char *) &tmp, (len > sizeof(tmp)) ? sizeof(tmp) : len);
06377       buf += sizeof(tmp);
06378       len -= sizeof(tmp);
06379    }
06380 }
06381 
06382 static void build_encryption_keys(const unsigned char *digest, struct chan_iax2_pvt *pvt)
06383 {
06384    build_ecx_key(digest, pvt);
06385    ast_aes_set_decrypt_key(digest, &pvt->dcx);
06386 }
06387 
06388 static void build_ecx_key(const unsigned char *digest, struct chan_iax2_pvt *pvt)
06389 {
06390    /* it is required to hold the corresponding decrypt key to our encrypt key
06391     * in the pvt struct because queued frames occasionally need to be decrypted and
06392     * re-encrypted when updated for a retransmission */
06393    build_rand_pad(pvt->semirand, sizeof(pvt->semirand));
06394    ast_aes_set_encrypt_key(digest, &pvt->ecx);
06395    ast_aes_set_decrypt_key(digest, &pvt->mydcx);
06396 }
06397 
06398 static void memcpy_decrypt(unsigned char *dst, const unsigned char *src, int len, ast_aes_decrypt_key *dcx)
06399 {
06400 #if 0
06401    /* Debug with "fake encryption" */
06402    int x;
06403    if (len % 16)
06404       ast_log(LOG_WARNING, "len should be multiple of 16, not %d!\n", len);
06405    for (x=0;x<len;x++)
06406       dst[x] = src[x] ^ 0xff;
06407 #else 
06408    unsigned char lastblock[16] = { 0 };
06409    int x;
06410    while(len > 0) {
06411       ast_aes_decrypt(src, dst, dcx);
06412       for (x=0;x<16;x++)
06413          dst[x] ^= lastblock[x];
06414       memcpy(lastblock, src, sizeof(lastblock));
06415       dst += 16;
06416       src += 16;
06417       len -= 16;
06418    }
06419 #endif
06420 }
06421 
06422 static void memcpy_encrypt(unsigned char *dst, const unsigned char *src, int len, ast_aes_encrypt_key *ecx)
06423 {
06424 #if 0
06425    /* Debug with "fake encryption" */
06426    int x;
06427    if (len % 16)
06428       ast_log(LOG_WARNING, "len should be multiple of 16, not %d!\n", len);
06429    for (x=0;x<len;x++)
06430       dst[x] = src[x] ^ 0xff;
06431 #else
06432    unsigned char curblock[16] = { 0 };
06433    int x;
06434    while(len > 0) {
06435       for (x=0;x<16;x++)
06436          curblock[x] ^= src[x];
06437       ast_aes_encrypt(curblock, dst, ecx);
06438       memcpy(curblock, dst, sizeof(curblock)); 
06439       dst += 16;
06440       src += 16;
06441       len -= 16;
06442    }
06443 #endif
06444 }
06445 
06446 static int decode_frame(ast_aes_decrypt_key *dcx, struct ast_iax2_full_hdr *fh, struct ast_frame *f, int *datalen)
06447 {
06448    int padding;
06449    unsigned char *workspace;
06450 
06451    workspace = ast_alloca(*datalen);
06452    memset(f, 0, sizeof(*f));
06453    if (ntohs(fh->scallno) & IAX_FLAG_FULL) {
06454       struct ast_iax2_full_enc_hdr *efh = (struct ast_iax2_full_enc_hdr *)fh;
06455       if (*datalen < 16 + sizeof(struct ast_iax2_full_hdr))
06456          return -1;
06457       /* Decrypt */
06458       memcpy_decrypt(workspace, efh->encdata, *datalen - sizeof(struct ast_iax2_full_enc_hdr), dcx);
06459 
06460       padding = 16 + (workspace[15] & 0x0f);
06461       if (iaxdebug)
06462          ast_debug(1, "Decoding full frame with length %d (padding = %d) (15=%02x)\n", *datalen, padding, workspace[15]);
06463       if (*datalen < padding + sizeof(struct ast_iax2_full_hdr))
06464          return -1;
06465 
06466       *datalen -= padding;
06467       memcpy(efh->encdata, workspace + padding, *datalen - sizeof(struct ast_iax2_full_enc_hdr));
06468       f->frametype = fh->type;
06469       if (f->frametype == AST_FRAME_VIDEO) {
06470          ast_format_from_old_bitfield(&f->subclass.format, (uncompress_subclass(fh->csub & ~0x40) | ((fh->csub >> 6) & 0x1)));
06471       } else if (f->frametype == AST_FRAME_VOICE) {
06472          ast_format_from_old_bitfield(&f->subclass.format, uncompress_subclass(fh->csub));
06473       } else {
06474          f->subclass.integer = uncompress_subclass(fh->csub);
06475       }
06476    } else {
06477       struct ast_iax2_mini_enc_hdr *efh = (struct ast_iax2_mini_enc_hdr *)fh;
06478       if (iaxdebug)
06479          ast_debug(1, "Decoding mini with length %d\n", *datalen);
06480       if (*datalen < 16 + sizeof(struct ast_iax2_mini_hdr))
06481          return -1;
06482       /* Decrypt */
06483       memcpy_decrypt(workspace, efh->encdata, *datalen - sizeof(struct ast_iax2_mini_enc_hdr), dcx);
06484       padding = 16 + (workspace[15] & 0x0f);
06485       if (*datalen < padding + sizeof(struct ast_iax2_mini_hdr))
06486          return -1;
06487       *datalen -= padding;
06488       memcpy(efh->encdata, workspace + padding, *datalen - sizeof(struct ast_iax2_mini_enc_hdr));
06489    }
06490    return 0;
06491 }
06492 
06493 static int encrypt_frame(ast_aes_encrypt_key *ecx, struct ast_iax2_full_hdr *fh, unsigned char *poo, int *datalen)
06494 {
06495    int padding;
06496    unsigned char *workspace;
06497    workspace = ast_alloca(*datalen + 32);
06498    if (ntohs(fh->scallno) & IAX_FLAG_FULL) {
06499       struct ast_iax2_full_enc_hdr *efh = (struct ast_iax2_full_enc_hdr *)fh;
06500       if (iaxdebug)
06501          ast_debug(1, "Encoding full frame %d/%d with length %d\n", fh->type, fh->csub, *datalen);
06502       padding = 16 - ((*datalen - sizeof(struct ast_iax2_full_enc_hdr)) % 16);
06503       padding = 16 + (padding & 0xf);
06504       memcpy(workspace, poo, padding);
06505       memcpy(workspace + padding, efh->encdata, *datalen - sizeof(struct ast_iax2_full_enc_hdr));
06506       workspace[15] &= 0xf0;
06507       workspace[15] |= (padding & 0xf);
06508       if (iaxdebug)
06509          ast_debug(1, "Encoding full frame %d/%d with length %d + %d padding (15=%02x)\n", fh->type, fh->csub, *datalen, padding, workspace[15]);
06510       *datalen += padding;
06511       memcpy_encrypt(efh->encdata, workspace, *datalen - sizeof(struct ast_iax2_full_enc_hdr), ecx);
06512       if (*datalen >= 32 + sizeof(struct ast_iax2_full_enc_hdr))
06513          memcpy(poo, workspace + *datalen - 32, 32);
06514    } else {
06515       struct ast_iax2_mini_enc_hdr *efh = (struct ast_iax2_mini_enc_hdr *)fh;
06516       if (iaxdebug)
06517          ast_debug(1, "Encoding mini frame with length %d\n", *datalen);
06518       padding = 16 - ((*datalen - sizeof(struct ast_iax2_mini_enc_hdr)) % 16);
06519       padding = 16 + (padding & 0xf);
06520       memcpy(workspace, poo, padding);
06521       memcpy(workspace + padding, efh->encdata, *datalen - sizeof(struct ast_iax2_mini_enc_hdr));
06522       workspace[15] &= 0xf0;
06523       workspace[15] |= (padding & 0x0f);
06524       *datalen += padding;
06525       memcpy_encrypt(efh->encdata, workspace, *datalen - sizeof(struct ast_iax2_mini_enc_hdr), ecx);
06526       if (*datalen >= 32 + sizeof(struct ast_iax2_mini_enc_hdr))
06527          memcpy(poo, workspace + *datalen - 32, 32);
06528    }
06529    return 0;
06530 }
06531 
06532 static int decrypt_frame(int callno, struct ast_iax2_full_hdr *fh, struct ast_frame *f, int *datalen)
06533 {
06534    int res=-1;
06535    if (!ast_test_flag64(iaxs[callno], IAX_KEYPOPULATED)) {
06536       /* Search for possible keys, given secrets */
06537       struct MD5Context md5;
06538       unsigned char digest[16];
06539       char *tmppw, *stringp;
06540       
06541       tmppw = ast_strdupa(iaxs[callno]->secret);
06542       stringp = tmppw;
06543       while ((tmppw = strsep(&stringp, ";"))) {
06544          MD5Init(&md5);
06545          MD5Update(&md5, (unsigned char *)iaxs[callno]->challenge, strlen(iaxs[callno]->challenge));
06546          MD5Update(&md5, (unsigned char *)tmppw, strlen(tmppw));
06547          MD5Final(digest, &md5);
06548          build_encryption_keys(digest, iaxs[callno]);
06549          res = decode_frame(&iaxs[callno]->dcx, fh, f, datalen);
06550          if (!res) {
06551             ast_set_flag64(iaxs[callno], IAX_KEYPOPULATED);
06552             break;
06553          }
06554       }
06555    } else 
06556       res = decode_frame(&iaxs[callno]->dcx, fh, f, datalen);
06557    return res;
06558 }
06559 
06560 static int iax2_send(struct chan_iax2_pvt *pvt, struct ast_frame *f, unsigned int ts, int seqno, int now, int transfer, int final)
06561 {
06562    /* Queue a packet for delivery on a given private structure.  Use "ts" for
06563       timestamp, or calculate if ts is 0.  Send immediately without retransmission
06564       or delayed, with retransmission */
06565    struct ast_iax2_full_hdr *fh;
06566    struct ast_iax2_mini_hdr *mh;
06567    struct ast_iax2_video_hdr *vh;
06568    struct {
06569       struct iax_frame fr2;
06570       unsigned char buffer[4096];
06571    } frb;
06572    struct iax_frame *fr;
06573    int res;
06574    int sendmini=0;
06575    unsigned int lastsent;
06576    unsigned int fts;
06577 
06578    frb.fr2.afdatalen = sizeof(frb.buffer);
06579 
06580    if (!pvt) {
06581       ast_log(LOG_WARNING, "No private structure for packet?\n");
06582       return -1;
06583    }
06584    
06585    lastsent = pvt->lastsent;
06586 
06587    /* Calculate actual timestamp */
06588    fts = calc_timestamp(pvt, ts, f);
06589 
06590    /* Bail here if this is an "interp" frame; we don't want or need to send these placeholders out
06591     * (the endpoint should detect the lost packet itself).  But, we want to do this here, so that we
06592     * increment the "predicted timestamps" for voice, if we're predicting */
06593    if(f->frametype == AST_FRAME_VOICE && f->datalen == 0)
06594       return 0;
06595 #if 0
06596    ast_log(LOG_NOTICE, 
06597       "f->frametype %c= AST_FRAME_VOICE, %sencrypted, %srotation scheduled...\n",
06598       *("=!" + (f->frametype == AST_FRAME_VOICE)),
06599       IAX_CALLENCRYPTED(pvt) ? "" : "not ",
06600       pvt->keyrotateid != -1 ? "" : "no "
06601    );
06602 #endif
06603    if (pvt->keyrotateid == -1 && f->frametype == AST_FRAME_VOICE && IAX_CALLENCRYPTED(pvt)) {
06604       iax2_key_rotate(pvt);
06605    }
06606 
06607    if ((ast_test_flag64(pvt, IAX_TRUNK) || 
06608          (((fts & 0xFFFF0000L) == (lastsent & 0xFFFF0000L)) ||
06609          ((fts & 0xFFFF0000L) == ((lastsent + 0x10000) & 0xFFFF0000L))))
06610       /* High two bytes are the same on timestamp, or sending on a trunk */ &&
06611        (f->frametype == AST_FRAME_VOICE) 
06612       /* is a voice frame */ &&
06613       (f->subclass.format.id == ast_format_id_from_old_bitfield(pvt->svoiceformat))
06614       /* is the same type */ ) {
06615          /* Force immediate rather than delayed transmission */
06616          now = 1;
06617          /* Mark that mini-style frame is appropriate */
06618          sendmini = 1;
06619    }
06620    if ( f->frametype == AST_FRAME_VIDEO ) {
06621       /*
06622        * If the lower 15 bits of the timestamp roll over, or if
06623        * the video format changed then send a full frame.
06624        * Otherwise send a mini video frame
06625        */
06626       if (((fts & 0xFFFF8000L) == (pvt->lastvsent & 0xFFFF8000L)) &&
06627           ((f->subclass.format.id) == ast_format_id_from_old_bitfield(pvt->svideoformat))
06628          ) {
06629          now = 1;
06630          sendmini = 1;
06631       } else {
06632          now = 0;
06633          sendmini = 0;
06634       }
06635       pvt->lastvsent = fts;
06636    }
06637    if (f->frametype == AST_FRAME_IAX) {
06638       /* 0x8000 marks this message as TX:, this bit will be stripped later */
06639       pvt->last_iax_message = f->subclass.integer | MARK_IAX_SUBCLASS_TX;
06640       if (!pvt->first_iax_message) {
06641          pvt->first_iax_message = pvt->last_iax_message;
06642       }
06643    }
06644    /* Allocate an iax_frame */
06645    if (now) {
06646       fr = &frb.fr2;
06647    } else
06648       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));
06649    if (!fr) {
06650       ast_log(LOG_WARNING, "Out of memory\n");
06651       return -1;
06652    }
06653    /* Copy our prospective frame into our immediate or retransmitted wrapper */
06654    iax_frame_wrap(fr, f);
06655 
06656    fr->ts = fts;
06657    fr->callno = pvt->callno;
06658    fr->transfer = transfer;
06659    fr->final = final;
06660    fr->encmethods = 0;
06661    if (!sendmini) {
06662       /* We need a full frame */
06663       if (seqno > -1)
06664          fr->oseqno = seqno;
06665       else
06666          fr->oseqno = pvt->oseqno++;
06667       fr->iseqno = pvt->iseqno;
06668       fh = (struct ast_iax2_full_hdr *)(fr->af.data.ptr - sizeof(struct ast_iax2_full_hdr));
06669       fh->scallno = htons(fr->callno | IAX_FLAG_FULL);
06670       fh->ts = htonl(fr->ts);
06671       fh->oseqno = fr->oseqno;
06672       if (transfer) {
06673          fh->iseqno = 0;
06674       } else
06675          fh->iseqno = fr->iseqno;
06676       /* Keep track of the last thing we've acknowledged */
06677       if (!transfer)
06678          pvt->aseqno = fr->iseqno;
06679       fh->type = fr->af.frametype & 0xFF;
06680 
06681       if (fr->af.frametype == AST_FRAME_VIDEO) {
06682          iax2_format tmpfmt = ast_format_to_old_bitfield(&fr->af.subclass.format);
06683          tmpfmt |= ast_format_get_video_mark(&fr->af.subclass.format) ? 0x1LL : 0;
06684          fh->csub = compress_subclass(tmpfmt | ((tmpfmt & 0x1LL) << 6));
06685       } else if (fr->af.frametype == AST_FRAME_VOICE) {
06686          fh->csub = compress_subclass(ast_format_to_old_bitfield(&fr->af.subclass.format));
06687       } else {
06688          fh->csub = compress_subclass(fr->af.subclass.integer);
06689       }
06690 
06691       if (transfer) {
06692          fr->dcallno = pvt->transfercallno;
06693       } else
06694          fr->dcallno = pvt->peercallno;
06695       fh->dcallno = htons(fr->dcallno);
06696       fr->datalen = fr->af.datalen + sizeof(struct ast_iax2_full_hdr);
06697       fr->data = fh;
06698       fr->retries = 0;
06699       /* Retry after 2x the ping time has passed */
06700       fr->retrytime = pvt->pingtime * 2;
06701       if (fr->retrytime < MIN_RETRY_TIME)
06702          fr->retrytime = MIN_RETRY_TIME;
06703       if (fr->retrytime > MAX_RETRY_TIME)
06704          fr->retrytime = MAX_RETRY_TIME;
06705       /* Acks' don't get retried */
06706       if ((f->frametype == AST_FRAME_IAX) && (f->subclass.integer == IAX_COMMAND_ACK))
06707          fr->retries = -1;
06708       else if (f->frametype == AST_FRAME_VOICE)
06709          pvt->svoiceformat = ast_format_to_old_bitfield(&f->subclass.format);
06710       else if (f->frametype == AST_FRAME_VIDEO)
06711          pvt->svideoformat = ast_format_to_old_bitfield(&f->subclass.format);
06712       if (ast_test_flag64(pvt, IAX_ENCRYPTED)) {
06713          if (ast_test_flag64(pvt, IAX_KEYPOPULATED)) {
06714             if (fr->transfer)
06715                iax_outputframe(fr, NULL, 2, &pvt->transfer, fr->datalen - sizeof(struct ast_iax2_full_hdr));
06716             else
06717                iax_outputframe(fr, NULL, 2, &pvt->addr, fr->datalen - sizeof(struct ast_iax2_full_hdr));
06718             encrypt_frame(&pvt->ecx, fh, pvt->semirand, &fr->datalen);
06719             fr->encmethods = pvt->encmethods;
06720             fr->ecx = pvt->ecx;
06721             fr->mydcx = pvt->mydcx;
06722             memcpy(fr->semirand, pvt->semirand, sizeof(fr->semirand));
06723          } else
06724             ast_log(LOG_WARNING, "Supposed to send packet encrypted, but no key?\n");
06725       }
06726 
06727       if (now) {
06728          res = send_packet(fr);
06729       } else
06730          res = iax2_transmit(fr);
06731    } else {
06732       if (ast_test_flag64(pvt, IAX_TRUNK)) {
06733          iax2_trunk_queue(pvt, fr);
06734          res = 0;
06735       } else if (fr->af.frametype == AST_FRAME_VIDEO) {
06736          /* Video frame have no sequence number */
06737          fr->oseqno = -1;
06738          fr->iseqno = -1;
06739          vh = (struct ast_iax2_video_hdr *)(fr->af.data.ptr - sizeof(struct ast_iax2_video_hdr));
06740          vh->zeros = 0;
06741          vh->callno = htons(0x8000 | fr->callno);
06742          vh->ts = htons((fr->ts & 0x7FFF) | (ast_format_get_video_mark(&fr->af.subclass.format) ? 0x8000 : 0));
06743          fr->datalen = fr->af.datalen + sizeof(struct ast_iax2_video_hdr);
06744          fr->data = vh;
06745          fr->retries = -1;
06746          res = send_packet(fr);
06747       } else {
06748          /* Mini-frames have no sequence number */
06749          fr->oseqno = -1;
06750          fr->iseqno = -1;
06751          /* Mini frame will do */
06752          mh = (struct ast_iax2_mini_hdr *)(fr->af.data.ptr - sizeof(struct ast_iax2_mini_hdr));
06753          mh->callno = htons(fr->callno);
06754          mh->ts = htons(fr->ts & 0xFFFF);
06755          fr->datalen = fr->af.datalen + sizeof(struct ast_iax2_mini_hdr);
06756          fr->data = mh;
06757          fr->retries = -1;
06758          if (pvt->transferring == TRANSFER_MEDIAPASS)
06759             fr->transfer = 1;
06760          if (ast_test_flag64(pvt, IAX_ENCRYPTED)) {
06761             if (ast_test_flag64(pvt, IAX_KEYPOPULATED)) {
06762                encrypt_frame(&pvt->ecx, (struct ast_iax2_full_hdr *)mh, pvt->semirand, &fr->datalen);
06763             } else
06764                ast_log(LOG_WARNING, "Supposed to send packet encrypted, but no key?\n");
06765          }
06766          res = send_packet(fr);
06767       }
06768    }
06769    return res;
06770 }
06771 
06772 static char *handle_cli_iax2_show_users(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
06773 {
06774    regex_t regexbuf;
06775    int havepattern = 0;
06776 
06777 #define FORMAT "%-15.15s  %-20.20s  %-15.15s  %-15.15s  %-5.5s  %-5.10s\n"
06778 #define FORMAT2 "%-15.15s  %-20.20s  %-15.15d  %-15.15s  %-5.5s  %-5.10s\n"
06779 
06780    struct iax2_user *user = NULL;
06781    char auth[90];
06782    char *pstr = "";
06783    struct ao2_iterator i;
06784 
06785    switch (cmd) {
06786    case CLI_INIT:
06787       e->command = "iax2 show users [like]";
06788       e->usage =
06789          "Usage: iax2 show users [like <pattern>]\n"
06790          "       Lists all known IAX2 users.\n"
06791          "       Optional regular expression pattern is used to filter the user list.\n";
06792       return NULL;
06793    case CLI_GENERATE:
06794       return NULL;
06795    }
06796 
06797    switch (a->argc) {
06798    case 5:
06799       if (!strcasecmp(a->argv[3], "like")) {
06800          if (regcomp(&regexbuf, a->argv[4], REG_EXTENDED | REG_NOSUB))
06801             return CLI_SHOWUSAGE;
06802          havepattern = 1;
06803       } else
06804          return CLI_SHOWUSAGE;
06805    case 3:
06806       break;
06807    default:
06808       return CLI_SHOWUSAGE;
06809    }
06810 
06811    ast_cli(a->fd, FORMAT, "Username", "Secret", "Authen", "Def.Context", "A/C","Codec Pref");
06812    i = ao2_iterator_init(users, 0);
06813    for (; (user = ao2_iterator_next(&i)); user_unref(user)) {
06814       if (havepattern && regexec(&regexbuf, user->name, 0, NULL, 0))
06815          continue;
06816 
06817       if (!ast_strlen_zero(user->secret)) {
06818          ast_copy_string(auth,user->secret, sizeof(auth));
06819       } else if (!ast_strlen_zero(user->inkeys)) {
06820          snprintf(auth, sizeof(auth), "Key: %-15.15s ", user->inkeys);
06821       } else
06822          ast_copy_string(auth, "-no secret-", sizeof(auth));
06823 
06824       if(ast_test_flag64(user, IAX_CODEC_NOCAP))
06825          pstr = "REQ Only";
06826       else if(ast_test_flag64(user, IAX_CODEC_NOPREFS))
06827          pstr = "Disabled";
06828       else
06829          pstr = ast_test_flag64(user, IAX_CODEC_USER_FIRST) ? "Caller" : "Host";
06830 
06831       ast_cli(a->fd, FORMAT2, user->name, auth, user->authmethods, 
06832          user->contexts ? user->contexts->context : DEFAULT_CONTEXT,
06833          ast_acl_list_is_empty(user->acl) ? "No" : "Yes", pstr);
06834    }
06835    ao2_iterator_destroy(&i);
06836 
06837    if (havepattern)
06838       regfree(&regexbuf);
06839 
06840    return CLI_SUCCESS;
06841 #undef FORMAT
06842 #undef FORMAT2
06843 }
06844 
06845 static int __iax2_show_peers(int fd, int *total, struct mansession *s, const int argc, const char * const argv[])
06846 {
06847    regex_t regexbuf;
06848    int havepattern = 0;
06849    int total_peers = 0;
06850    int online_peers = 0;
06851    int offline_peers = 0;
06852    int unmonitored_peers = 0;
06853    struct ao2_iterator i;
06854 
06855 #define FORMAT2 "%-15.15s  %-15.15s %s  %-15.15s  %-8s  %s %-11s %-32.32s\n"
06856 #define FORMAT "%-15.15s  %-15.15s %s  %-15.15s  %-5d%s  %s %-11s %-32.32s\n"
06857 
06858    struct iax2_peer *peer = NULL;
06859    char name[256];
06860    struct ast_str *encmethods = ast_str_alloca(256);
06861    int registeredonly=0;
06862    char idtext[256] = "";
06863    switch (argc) {
06864    case 6:
06865       if (!strcasecmp(argv[3], "registered"))
06866          registeredonly = 1;
06867       else
06868          return RESULT_SHOWUSAGE;
06869       if (!strcasecmp(argv[4], "like")) {
06870          if (regcomp(&regexbuf, argv[5], REG_EXTENDED | REG_NOSUB))
06871             return RESULT_SHOWUSAGE;
06872          havepattern = 1;
06873       } else
06874          return RESULT_SHOWUSAGE;
06875       break;
06876    case 5:
06877       if (!strcasecmp(argv[3], "like")) {
06878          if (regcomp(&regexbuf, argv[4], REG_EXTENDED | REG_NOSUB))
06879             return RESULT_SHOWUSAGE;
06880          havepattern = 1;
06881       } else
06882          return RESULT_SHOWUSAGE;
06883       break;
06884    case 4:
06885       if (!strcasecmp(argv[3], "registered"))
06886          registeredonly = 1;
06887       else
06888          return RESULT_SHOWUSAGE;
06889       break;
06890    case 3:
06891       break;
06892    default:
06893       return RESULT_SHOWUSAGE;
06894    }
06895 
06896 
06897    if (!s)
06898       ast_cli(fd, FORMAT2, "Name/Username", "Host", "   ", "Mask", "Port", "   ", "Status", "Description");
06899 
06900    i = ao2_iterator_init(peers, 0);
06901    for (; (peer = ao2_iterator_next(&i)); peer_unref(peer)) {
06902       char nm[20];
06903       char status[20];
06904       int retstatus;
06905       struct sockaddr_in peer_addr;
06906 
06907       ast_sockaddr_to_sin(&peer->addr, &peer_addr);
06908 
06909       if (registeredonly && !peer_addr.sin_addr.s_addr) {
06910          continue;
06911       }
06912       if (havepattern && regexec(&regexbuf, peer->name, 0, NULL, 0)) {
06913          continue;
06914       }
06915 
06916       if (!ast_strlen_zero(peer->username))
06917          snprintf(name, sizeof(name), "%s/%s", peer->name, peer->username);
06918       else
06919          ast_copy_string(name, peer->name, sizeof(name));
06920 
06921       encmethods_to_str(peer->encmethods, &encmethods);
06922       retstatus = peer_status(peer, status, sizeof(status));
06923       if (retstatus > 0)
06924          online_peers++;
06925       else if (!retstatus)
06926          offline_peers++;
06927       else
06928          unmonitored_peers++;
06929 
06930       ast_copy_string(nm, ast_inet_ntoa(peer->mask), sizeof(nm));
06931 
06932       if (s) {
06933          astman_append(s,
06934             "Event: PeerEntry\r\n%s"
06935             "Channeltype: IAX2\r\n"
06936             "ObjectName: %s\r\n"
06937             "ChanObjectType: peer\r\n"
06938             "IPaddress: %s\r\n"
06939             "IPport: %d\r\n"
06940             "Dynamic: %s\r\n"
06941             "Trunk: %s\r\n"
06942             "Encryption: %s\r\n"
06943             "Status: %s\r\n"
06944             "Description: %s\r\n\r\n",
06945             idtext,
06946             name,
06947             ast_sockaddr_stringify_addr(&peer->addr),
06948             ast_sockaddr_port(&peer->addr),
06949             ast_test_flag64(peer, IAX_DYNAMIC) ? "yes" : "no",
06950             ast_test_flag64(peer, IAX_TRUNK) ? "yes" : "no",
06951             peer->encmethods ? ast_str_buffer(encmethods) : "no",
06952             status,
06953             peer->description);
06954       } else {
06955          ast_cli(fd, FORMAT, name,
06956             ast_sockaddr_stringify_addr(&peer->addr),
06957             ast_test_flag64(peer, IAX_DYNAMIC) ? "(D)" : "(S)",
06958             nm,
06959             ast_sockaddr_port(&peer->addr),
06960             ast_test_flag64(peer, IAX_TRUNK) ? "(T)" : "   ",
06961             peer->encmethods ? "(E)" : "   ",
06962             status,
06963             peer->description);
06964       }
06965       total_peers++;
06966    }
06967    ao2_iterator_destroy(&i);
06968 
06969    if (!s)
06970       ast_cli(fd,"%d iax2 peers [%d online, %d offline, %d unmonitored]\n",
06971          total_peers, online_peers, offline_peers, unmonitored_peers);
06972 
06973    if (havepattern)
06974       regfree(&regexbuf);
06975 
06976    if (total)
06977       *total = total_peers;
06978 
06979    return RESULT_SUCCESS;
06980 #undef FORMAT
06981 #undef FORMAT2
06982 }
06983 
06984 static char *handle_cli_iax2_show_threads(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
06985 {
06986    struct iax2_thread *thread = NULL;
06987    time_t t;
06988    int threadcount = 0, dynamiccount = 0;
06989    char type;
06990 
06991    switch (cmd) {
06992    case CLI_INIT:
06993       e->command = "iax2 show threads";
06994       e->usage =
06995          "Usage: iax2 show threads\n"
06996          "       Lists status of IAX helper threads\n";
06997       return NULL;
06998    case CLI_GENERATE:
06999       return NULL;
07000    }
07001    if (a->argc != 3)
07002       return CLI_SHOWUSAGE;
07003       
07004    ast_cli(a->fd, "IAX2 Thread Information\n");
07005    time(&t);
07006    ast_cli(a->fd, "Idle Threads:\n");
07007    AST_LIST_LOCK(&idle_list);
07008    AST_LIST_TRAVERSE(&idle_list, thread, list) {
07009 #ifdef DEBUG_SCHED_MULTITHREAD
07010       ast_cli(a->fd, "Thread %d: state=%d, update=%d, actions=%d, func='%s'\n", 
07011          thread->threadnum, thread->iostate, (int)(t - thread->checktime), thread->actions, thread->curfunc);
07012 #else
07013       ast_cli(a->fd, "Thread %d: state=%d, update=%d, actions=%d\n", 
07014          thread->threadnum, thread->iostate, (int)(t - thread->checktime), thread->actions);
07015 #endif
07016       threadcount++;
07017    }
07018    AST_LIST_UNLOCK(&idle_list);
07019    ast_cli(a->fd, "Active Threads:\n");
07020    AST_LIST_LOCK(&active_list);
07021    AST_LIST_TRAVERSE(&active_list, thread, list) {
07022       if (thread->type == IAX_THREAD_TYPE_DYNAMIC)
07023          type = 'D';
07024       else
07025          type = 'P';
07026 #ifdef DEBUG_SCHED_MULTITHREAD
07027       ast_cli(a->fd, "Thread %c%d: state=%d, update=%d, actions=%d, func='%s'\n", 
07028          type, thread->threadnum, thread->iostate, (int)(t - thread->checktime), thread->actions, thread->curfunc);
07029 #else
07030       ast_cli(a->fd, "Thread %c%d: state=%d, update=%d, actions=%d\n", 
07031          type, thread->threadnum, thread->iostate, (int)(t - thread->checktime), thread->actions);
07032 #endif
07033       threadcount++;
07034    }
07035    AST_LIST_UNLOCK(&active_list);
07036    ast_cli(a->fd, "Dynamic Threads:\n");
07037    AST_LIST_LOCK(&dynamic_list);
07038    AST_LIST_TRAVERSE(&dynamic_list, thread, list) {
07039 #ifdef DEBUG_SCHED_MULTITHREAD
07040       ast_cli(a->fd, "Thread %d: state=%d, update=%d, actions=%d, func='%s'\n",
07041          thread->threadnum, thread->iostate, (int)(t - thread->checktime), thread->actions, thread->curfunc);
07042 #else
07043       ast_cli(a->fd, "Thread %d: state=%d, update=%d, actions=%d\n",
07044          thread->threadnum, thread->iostate, (int)(t - thread->checktime), thread->actions);
07045 #endif
07046       dynamiccount++;
07047    }
07048    AST_LIST_UNLOCK(&dynamic_list);
07049    ast_cli(a->fd, "%d of %d threads accounted for with %d dynamic threads\n", threadcount, iaxthreadcount, dynamiccount);
07050    return CLI_SUCCESS;
07051 }
07052 
07053 static char *handle_cli_iax2_unregister(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
07054 {
07055    struct iax2_peer *p;
07056 
07057    switch (cmd) {
07058    case CLI_INIT:
07059       e->command = "iax2 unregister";
07060       e->usage =
07061          "Usage: iax2 unregister <peername>\n"
07062          "       Unregister (force expiration) an IAX2 peer from the registry.\n";
07063       return NULL;
07064    case CLI_GENERATE:
07065       return complete_iax2_unregister(a->line, a->word, a->pos, a->n);
07066    }
07067 
07068    if (a->argc != 3)
07069       return CLI_SHOWUSAGE;
07070 
07071    p = find_peer(a->argv[2], 1);
07072    if (p) {
07073       if (p->expire > 0) {
07074          struct iax2_peer *peer;
07075 
07076          peer = ao2_find(peers, a->argv[2], OBJ_KEY);
07077          if (peer) {
07078             expire_registry(peer_ref(peer)); /* will release its own reference when done */
07079             peer_unref(peer); /* ref from ao2_find() */
07080             ast_cli(a->fd, "Peer %s unregistered\n", a->argv[2]);
07081          } else {
07082             ast_cli(a->fd, "Peer %s not found\n", a->argv[2]);
07083          }
07084       } else {
07085          ast_cli(a->fd, "Peer %s not registered\n", a->argv[2]);
07086       }
07087       peer_unref(p);
07088    } else {
07089       ast_cli(a->fd, "Peer unknown: %s. Not unregistered\n", a->argv[2]);
07090    }
07091    return CLI_SUCCESS;
07092 }
07093 
07094 static char *complete_iax2_unregister(const char *line, const char *word, int pos, int state)
07095 {
07096    int which = 0;
07097    struct iax2_peer *p = NULL;
07098    char *res = NULL;
07099    int wordlen = strlen(word);
07100 
07101    /* 0 - iax2; 1 - unregister; 2 - <peername> */
07102    if (pos == 2) {
07103       struct ao2_iterator i = ao2_iterator_init(peers, 0);
07104       while ((p = ao2_iterator_next(&i))) {
07105          if (!strncasecmp(p->name, word, wordlen) && 
07106             ++which > state && p->expire > 0) {
07107             res = ast_strdup(p->name);
07108             peer_unref(p);
07109             break;
07110          }
07111          peer_unref(p);
07112       }
07113       ao2_iterator_destroy(&i);
07114    }
07115 
07116    return res;
07117 }
07118 
07119 static char *handle_cli_iax2_show_peers(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
07120 {
07121    switch (cmd) {
07122    case CLI_INIT:
07123       e->command = "iax2 show peers";
07124       e->usage =
07125          "Usage: iax2 show peers [registered] [like <pattern>]\n"
07126          "       Lists all known IAX2 peers.\n"
07127          "       Optional 'registered' argument lists only peers with known addresses.\n"
07128          "       Optional regular expression pattern is used to filter the peer list.\n";
07129       return NULL;
07130    case CLI_GENERATE:
07131       return NULL;
07132    }
07133 
07134    switch (__iax2_show_peers(a->fd, NULL, NULL, a->argc, a->argv)) {
07135    case RESULT_SHOWUSAGE:
07136       return CLI_SHOWUSAGE;
07137    case RESULT_FAILURE:
07138       return CLI_FAILURE;
07139    default:
07140       return CLI_SUCCESS;
07141    }
07142 }
07143 
07144 static int manager_iax2_show_netstats(struct mansession *s, const struct message *m)
07145 {
07146    ast_cli_netstats(s, -1, 0);
07147    astman_append(s, "\r\n");
07148    return RESULT_SUCCESS;
07149 }
07150 
07151 static char *handle_cli_iax2_show_firmware(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
07152 {
07153    struct iax_firmware *cur = NULL;
07154 
07155    switch (cmd) {
07156    case CLI_INIT:
07157       e->command = "iax2 show firmware";
07158       e->usage =
07159          "Usage: iax2 show firmware\n"
07160          "       Lists all known IAX firmware images.\n";
07161       return NULL;
07162    case CLI_GENERATE:
07163       return NULL;
07164    }
07165 
07166    if (a->argc != 3 && a->argc != 4)
07167       return CLI_SHOWUSAGE;
07168 
07169    ast_cli(a->fd, "%-15.15s  %-15.15s %-15.15s\n", "Device", "Version", "Size");
07170    AST_LIST_LOCK(&firmwares);
07171    AST_LIST_TRAVERSE(&firmwares, cur, list) {
07172       if ((a->argc == 3) || (!strcasecmp(a->argv[3], (char *) cur->fwh->devname)))  {
07173          ast_cli(a->fd, "%-15.15s  %-15d %-15d\n", cur->fwh->devname, 
07174             ntohs(cur->fwh->version), (int)ntohl(cur->fwh->datalen));
07175       }
07176    }
07177    AST_LIST_UNLOCK(&firmwares);
07178 
07179    return CLI_SUCCESS;
07180 }
07181 
07182 /*! \brief callback to display iax peers in manager */
07183 static int manager_iax2_show_peers(struct mansession *s, const struct message *m)
07184 {
07185    static const char * const a[] = { "iax2", "show", "peers" };
07186    const char *id = astman_get_header(m,"ActionID");
07187    char idtext[256] = "";
07188    int total = 0;
07189 
07190    if (!ast_strlen_zero(id))
07191       snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
07192 
07193    astman_send_listack(s, m, "Peer status list will follow", "start");
07194         /* List the peers in separate manager events */
07195    __iax2_show_peers(-1, &total, s, 3, a);
07196         /* Send final confirmation */
07197         astman_append(s,
07198         "Event: PeerlistComplete\r\n"
07199         "EventList: Complete\r\n"
07200         "ListItems: %d\r\n"
07201         "%s"
07202         "\r\n", total, idtext);
07203         return 0;
07204 }
07205 
07206 /*! \brief callback to display iax peers in manager format */
07207 static int manager_iax2_show_peer_list(struct mansession *s, const struct message *m)
07208 {
07209    struct iax2_peer *peer = NULL;
07210    int peer_count = 0;
07211    char nm[20];
07212    char status[20];
07213    const char *id = astman_get_header(m,"ActionID");
07214    char idtext[256] = "";
07215    struct ast_str *encmethods = ast_str_alloca(256);
07216    struct ao2_iterator i;
07217 
07218    if (!ast_strlen_zero(id))
07219       snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
07220 
07221    astman_append(s, "Response: Success\r\n%sMessage: IAX Peer status list will follow\r\n\r\n", idtext);
07222 
07223 
07224    i = ao2_iterator_init(peers, 0);
07225    for (; (peer = ao2_iterator_next(&i)); peer_unref(peer)) {
07226       encmethods_to_str(peer->encmethods, &encmethods);
07227       astman_append(s, "Event: PeerEntry\r\n%sChanneltype: IAX\r\n", idtext);
07228       if (!ast_strlen_zero(peer->username)) {
07229          astman_append(s, "ObjectName: %s\r\nObjectUsername: %s\r\n", peer->name, peer->username);
07230       } else {
07231          astman_append(s, "ObjectName: %s\r\n", peer->name);
07232       }
07233       astman_append(s, "ChanObjectType: peer\r\n");
07234       astman_append(s, "IPaddress: %s\r\n", ast_sockaddr_stringify_addr(&peer->addr));
07235       ast_copy_string(nm, ast_inet_ntoa(peer->mask), sizeof(nm));
07236       astman_append(s, "Mask: %s\r\n", nm);
07237       astman_append(s, "Port: %d\r\n", ast_sockaddr_port(&peer->addr));
07238       astman_append(s, "Dynamic: %s\r\n", ast_test_flag64(peer, IAX_DYNAMIC) ? "Yes" : "No");
07239       astman_append(s, "Trunk: %s\r\n", ast_test_flag64(peer, IAX_TRUNK) ? "Yes" : "No");
07240       astman_append(s, "Encryption: %s\r\n", peer->encmethods ? ast_str_buffer(encmethods) : "No");
07241       peer_status(peer, status, sizeof(status));
07242       astman_append(s, "Status: %s\r\n\r\n", status);
07243       peer_count++;
07244    }
07245    ao2_iterator_destroy(&i);
07246 
07247    astman_append(s, "Event: PeerlistComplete\r\n%sListItems: %d\r\n\r\n", idtext, peer_count);
07248    return RESULT_SUCCESS;
07249 }
07250 
07251 
07252 static char *regstate2str(int regstate)
07253 {
07254    switch(regstate) {
07255    case REG_STATE_UNREGISTERED:
07256       return "Unregistered";
07257    case REG_STATE_REGSENT:
07258       return "Request Sent";
07259    case REG_STATE_AUTHSENT:
07260       return "Auth. Sent";
07261    case REG_STATE_REGISTERED:
07262       return "Registered";
07263    case REG_STATE_REJECTED:
07264       return "Rejected";
07265    case REG_STATE_TIMEOUT:
07266       return "Timeout";
07267    case REG_STATE_NOAUTH:
07268       return "No Authentication";
07269    default:
07270       return "Unknown";
07271    }
07272 }
07273 
07274 static char *handle_cli_iax2_show_registry(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
07275 {
07276 #define FORMAT2 "%-20.20s  %-6.6s  %-10.10s  %-20.20s %8.8s  %s\n"
07277 #define FORMAT  "%-20.20s  %-6.6s  %-10.10s  %-20.20s %8d  %s\n"
07278    struct iax2_registry *reg = NULL;
07279    char host[80];
07280    char perceived[80];
07281    int counter = 0;
07282 
07283    switch (cmd) {
07284    case CLI_INIT:
07285       e->command = "iax2 show registry";
07286       e->usage =
07287          "Usage: iax2 show registry\n"
07288          "       Lists all registration requests and status.\n";
07289       return NULL;
07290    case CLI_GENERATE:
07291       return NULL;
07292    }
07293    if (a->argc != 3)
07294       return CLI_SHOWUSAGE;
07295    ast_cli(a->fd, FORMAT2, "Host", "dnsmgr", "Username", "Perceived", "Refresh", "State");
07296    AST_LIST_LOCK(&registrations);
07297    AST_LIST_TRAVERSE(&registrations, reg, entry) {
07298       snprintf(host, sizeof(host), "%s", ast_sockaddr_stringify(&reg->addr));
07299       if (reg->us.sin_addr.s_addr) 
07300          snprintf(perceived, sizeof(perceived), "%s:%d", ast_inet_ntoa(reg->us.sin_addr), ntohs(reg->us.sin_port));
07301       else
07302          ast_copy_string(perceived, "<Unregistered>", sizeof(perceived));
07303       ast_cli(a->fd, FORMAT, host, 
07304                (reg->dnsmgr) ? "Y" : "N", 
07305                reg->username, perceived, reg->refresh, regstate2str(reg->regstate));
07306       counter++;
07307    }
07308    AST_LIST_UNLOCK(&registrations);
07309    ast_cli(a->fd, "%d IAX2 registrations.\n", counter);
07310    return CLI_SUCCESS;
07311 #undef FORMAT
07312 #undef FORMAT2
07313 }
07314 
07315 static int manager_iax2_show_registry(struct mansession *s, const struct message *m)
07316 {
07317    const char *id = astman_get_header(m, "ActionID");
07318    struct iax2_registry *reg = NULL;
07319    char idtext[256] = "";
07320    char host[80] = "";
07321    char perceived[80] = "";
07322    int total = 0;
07323 
07324    if (!ast_strlen_zero(id))
07325       snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
07326 
07327    astman_send_listack(s, m, "Registrations will follow", "start");
07328 
07329    AST_LIST_LOCK(&registrations);
07330    AST_LIST_TRAVERSE(&registrations, reg, entry) {
07331       snprintf(host, sizeof(host), "%s", ast_sockaddr_stringify(&reg->addr));
07332       
07333       if (reg->us.sin_addr.s_addr) {
07334          snprintf(perceived, sizeof(perceived), "%s:%d", ast_inet_ntoa(reg->us.sin_addr), ntohs(reg->us.sin_port));
07335       } else {
07336          ast_copy_string(perceived, "<Unregistered>", sizeof(perceived));
07337       }
07338       
07339       astman_append(s,
07340          "Event: RegistryEntry\r\n"
07341          "%s"
07342          "Host: %s\r\n"
07343          "DNSmanager: %s\r\n"
07344          "Username: %s\r\n"
07345          "Perceived: %s\r\n"
07346          "Refresh: %d\r\n"
07347          "State: %s\r\n"
07348          "\r\n", idtext, host, (reg->dnsmgr) ? "Y" : "N", reg->username, perceived, 
07349          reg->refresh, regstate2str(reg->regstate));
07350 
07351       total++;
07352    }
07353    AST_LIST_UNLOCK(&registrations);
07354 
07355    astman_append(s,
07356       "Event: RegistrationsComplete\r\n"
07357       "EventList: Complete\r\n"
07358       "ListItems: %d\r\n"
07359       "%s"
07360       "\r\n", total, idtext);
07361    
07362    return 0;
07363 }
07364 
07365 static char *handle_cli_iax2_show_channels(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
07366 {
07367 #define FORMAT2 "%-20.20s  %-15.15s  %-10.10s  %-11.11s  %-11.11s  %-7.7s  %-6.6s  %-6.6s  %s  %s  %9s\n"
07368 #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"
07369 #define FORMATB "%-20.20s  %-15.15s  %-10.10s  %5.5d/%5.5d  %5.5d/%5.5d  [Native Bridged to ID=%5.5d]\n"
07370    int x;
07371    int numchans = 0;
07372    char first_message[10] = { 0, };
07373    char last_message[10] = { 0, };
07374 
07375    switch (cmd) {
07376    case CLI_INIT:
07377       e->command = "iax2 show channels";
07378       e->usage =
07379          "Usage: iax2 show channels\n"
07380          "       Lists all currently active IAX channels.\n";
07381       return NULL;
07382    case CLI_GENERATE:
07383       return NULL;
07384    }
07385 
07386    if (a->argc != 3)
07387       return CLI_SHOWUSAGE;
07388    ast_cli(a->fd, FORMAT2, "Channel", "Peer", "Username", "ID (Lo/Rem)", "Seq (Tx/Rx)", "Lag", "Jitter", "JitBuf", "Format", "FirstMsg", "LastMsg");
07389    for (x = 0; x < ARRAY_LEN(iaxs); x++) {
07390       ast_mutex_lock(&iaxsl[x]);
07391       if (iaxs[x]) {
07392          int lag, jitter, localdelay;
07393          jb_info jbinfo;
07394          if (ast_test_flag64(iaxs[x], IAX_USEJITTERBUF)) {
07395             jb_getinfo(iaxs[x]->jb, &jbinfo);
07396             jitter = jbinfo.jitter;
07397             localdelay = jbinfo.current - jbinfo.min;
07398          } else {
07399             jitter = -1;
07400             localdelay = 0;
07401          }
07402 
07403          iax_frame_subclass2str(iaxs[x]->first_iax_message & ~MARK_IAX_SUBCLASS_TX, first_message, sizeof(first_message));
07404          iax_frame_subclass2str(iaxs[x]->last_iax_message & ~MARK_IAX_SUBCLASS_TX, last_message, sizeof(last_message));
07405          lag = iaxs[x]->remote_rr.delay;
07406          ast_cli(a->fd, FORMAT,
07407             iaxs[x]->owner ? ast_channel_name(iaxs[x]->owner) : "(None)",
07408             ast_inet_ntoa(iaxs[x]->addr.sin_addr),
07409             S_OR(iaxs[x]->username, "(None)"),
07410             iaxs[x]->callno, iaxs[x]->peercallno,
07411             iaxs[x]->oseqno, iaxs[x]->iseqno,
07412             lag,
07413             jitter,
07414             localdelay,
07415             iax2_getformatname(iaxs[x]->voiceformat),
07416             (iaxs[x]->first_iax_message & MARK_IAX_SUBCLASS_TX) ? "Tx:" : "Rx:",
07417             first_message,
07418             (iaxs[x]->last_iax_message & MARK_IAX_SUBCLASS_TX) ? "Tx:" : "Rx:",
07419             last_message);
07420          numchans++;
07421       }
07422       ast_mutex_unlock(&iaxsl[x]);
07423    }
07424    ast_cli(a->fd, "%d active IAX channel%s\n", numchans, (numchans != 1) ? "s" : "");
07425    return CLI_SUCCESS;
07426 #undef FORMAT
07427 #undef FORMAT2
07428 #undef FORMATB
07429 }
07430 
07431 static int ast_cli_netstats(struct mansession *s, int fd, int limit_fmt)
07432 {
07433    int x;
07434    int numchans = 0;
07435    char first_message[10] = { 0, };
07436    char last_message[10] = { 0, };
07437 #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"
07438 #define ACN_FORMAT2 "%s %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %s%s %s%s\n"
07439    for (x = 0; x < ARRAY_LEN(iaxs); x++) {
07440       ast_mutex_lock(&iaxsl[x]);
07441       if (iaxs[x]) {
07442          int localjitter, localdelay, locallost, locallosspct, localdropped, localooo;
07443          jb_info jbinfo;
07444          iax_frame_subclass2str(iaxs[x]->first_iax_message & ~MARK_IAX_SUBCLASS_TX, first_message, sizeof(first_message));
07445          iax_frame_subclass2str(iaxs[x]->last_iax_message & ~MARK_IAX_SUBCLASS_TX, last_message, sizeof(last_message));
07446 
07447          if(ast_test_flag64(iaxs[x], IAX_USEJITTERBUF)) {
07448             jb_getinfo(iaxs[x]->jb, &jbinfo);
07449             localjitter = jbinfo.jitter;
07450             localdelay = jbinfo.current - jbinfo.min;
07451             locallost = jbinfo.frames_lost;
07452             locallosspct = jbinfo.losspct/1000;
07453             localdropped = jbinfo.frames_dropped;
07454             localooo = jbinfo.frames_ooo;
07455          } else {
07456             localjitter = -1;
07457             localdelay = 0;
07458             locallost = -1;
07459             locallosspct = -1;
07460             localdropped = 0;
07461             localooo = -1;
07462          }
07463          if (s)
07464             astman_append(s, limit_fmt ? ACN_FORMAT1 : ACN_FORMAT2,
07465                iaxs[x]->owner ? ast_channel_name(iaxs[x]->owner) : "(None)",
07466                iaxs[x]->pingtime,
07467                localjitter,
07468                localdelay,
07469                locallost,
07470                locallosspct,
07471                localdropped,
07472                localooo,
07473                iaxs[x]->frames_received/1000,
07474                iaxs[x]->remote_rr.jitter,
07475                iaxs[x]->remote_rr.delay,
07476                iaxs[x]->remote_rr.losscnt,
07477                iaxs[x]->remote_rr.losspct,
07478                iaxs[x]->remote_rr.dropped,
07479                iaxs[x]->remote_rr.ooo,
07480                iaxs[x]->remote_rr.packets/1000,
07481                (iaxs[x]->first_iax_message & MARK_IAX_SUBCLASS_TX) ? "Tx:" : "Rx:",
07482                first_message,
07483                (iaxs[x]->last_iax_message & MARK_IAX_SUBCLASS_TX) ? "Tx:" : "Rx:",
07484                last_message);
07485          else
07486             ast_cli(fd, limit_fmt ? ACN_FORMAT1 : ACN_FORMAT2,
07487                iaxs[x]->owner ? ast_channel_name(iaxs[x]->owner) : "(None)",
07488                iaxs[x]->pingtime,
07489                localjitter,
07490                localdelay,
07491                locallost,
07492                locallosspct,
07493                localdropped,
07494                localooo,
07495                iaxs[x]->frames_received/1000,
07496                iaxs[x]->remote_rr.jitter,
07497                iaxs[x]->remote_rr.delay,
07498                iaxs[x]->remote_rr.losscnt,
07499                iaxs[x]->remote_rr.losspct,
07500                iaxs[x]->remote_rr.dropped,
07501                iaxs[x]->remote_rr.ooo,
07502                iaxs[x]->remote_rr.packets/1000,
07503                (iaxs[x]->first_iax_message & MARK_IAX_SUBCLASS_TX) ? "Tx:" : "Rx:",
07504                first_message,
07505                (iaxs[x]->last_iax_message & MARK_IAX_SUBCLASS_TX) ? "Tx:" : "Rx:",
07506                last_message);
07507          numchans++;
07508       }
07509       ast_mutex_unlock(&iaxsl[x]);
07510    }
07511 
07512    return numchans;
07513 }
07514 
07515 static char *handle_cli_iax2_show_netstats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
07516 {
07517    int numchans = 0;
07518 
07519    switch (cmd) {
07520    case CLI_INIT:
07521       e->command = "iax2 show netstats";
07522       e->usage =
07523          "Usage: iax2 show netstats\n"
07524          "       Lists network status for all currently active IAX channels.\n";
07525       return NULL;
07526    case CLI_GENERATE:
07527       return NULL;
07528    }
07529    if (a->argc != 3)
07530       return CLI_SHOWUSAGE;
07531    ast_cli(a->fd, "                           -------- LOCAL ---------------------  -------- REMOTE --------------------\n");
07532    ast_cli(a->fd, "Channel               RTT  Jit  Del  Lost   %%  Drop  OOO  Kpkts  Jit  Del  Lost   %%  Drop  OOO  Kpkts FirstMsg    LastMsg\n");
07533    numchans = ast_cli_netstats(NULL, a->fd, 1);
07534    ast_cli(a->fd, "%d active IAX channel%s\n", numchans, (numchans != 1) ? "s" : "");
07535    return CLI_SUCCESS;
07536 }
07537 
07538 static char *handle_cli_iax2_set_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
07539 {
07540    switch (cmd) {
07541    case CLI_INIT:
07542       e->command = "iax2 set debug {on|off|peer}";
07543       e->usage =
07544          "Usage: iax2 set debug {on|off|peer peername}\n"
07545          "       Enables/Disables dumping of IAX packets for debugging purposes.\n";
07546       return NULL;
07547    case CLI_GENERATE:
07548       if (a->pos == 4 && !strcasecmp(a->argv[3], "peer"))
07549          return complete_iax2_peers(a->line, a->word, a->pos, a->n, 0);
07550       return NULL;
07551    }
07552 
07553    if (a->argc < e->args  || a->argc > e->args + 1)
07554       return CLI_SHOWUSAGE;
07555 
07556    if (!strcasecmp(a->argv[3], "peer")) {
07557       struct iax2_peer *peer;
07558       struct sockaddr_in peer_addr;
07559 
07560 
07561       if (a->argc != e->args + 1)
07562          return CLI_SHOWUSAGE;
07563 
07564       peer = find_peer(a->argv[4], 1);
07565 
07566       if (!peer) {
07567          ast_cli(a->fd, "IAX2 peer '%s' does not exist\n", a->argv[e->args-1]);
07568          return CLI_FAILURE;
07569       }
07570 
07571       ast_sockaddr_to_sin(&peer->addr, &peer_addr);
07572 
07573       debugaddr.sin_addr = peer_addr.sin_addr;
07574       debugaddr.sin_port = peer_addr.sin_port;
07575 
07576       ast_cli(a->fd, "IAX2 Debugging Enabled for IP: %s:%d\n",
07577          ast_inet_ntoa(debugaddr.sin_addr), ntohs(debugaddr.sin_port));
07578 
07579       ao2_ref(peer, -1);
07580    } else if (!strncasecmp(a->argv[3], "on", 2)) {
07581       iaxdebug = 1;
07582       ast_cli(a->fd, "IAX2 Debugging Enabled\n");
07583    } else {
07584       iaxdebug = 0;
07585       memset(&debugaddr, 0, sizeof(debugaddr));
07586       ast_cli(a->fd, "IAX2 Debugging Disabled\n");
07587    }
07588    return CLI_SUCCESS;
07589 }
07590 
07591 static char *handle_cli_iax2_set_debug_trunk(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
07592 {
07593    switch (cmd) {
07594    case CLI_INIT:
07595       e->command = "iax2 set debug trunk {on|off}";
07596       e->usage =
07597          "Usage: iax2 set debug trunk {on|off}\n"
07598          "       Enables/Disables debugging of IAX trunking\n";
07599       return NULL;
07600    case CLI_GENERATE:
07601       return NULL;
07602    }
07603 
07604    if (a->argc != e->args)
07605       return CLI_SHOWUSAGE;
07606 
07607    if (!strncasecmp(a->argv[e->args - 1], "on", 2)) {
07608       iaxtrunkdebug = 1;
07609       ast_cli(a->fd, "IAX2 Trunk Debugging Enabled\n");
07610    } else {
07611       iaxtrunkdebug = 0;
07612       ast_cli(a->fd, "IAX2 Trunk Debugging Disabled\n");
07613    }
07614    return CLI_SUCCESS;
07615 }
07616 
07617 static char *handle_cli_iax2_set_debug_jb(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
07618 {
07619    switch (cmd) {
07620    case CLI_INIT:
07621       e->command = "iax2 set debug jb {on|off}";
07622       e->usage =
07623          "Usage: iax2 set debug jb {on|off}\n"
07624          "       Enables/Disables jitterbuffer debugging information\n";
07625       return NULL;
07626    case CLI_GENERATE:
07627       return NULL;
07628    }
07629 
07630    if (a->argc != e->args)
07631       return CLI_SHOWUSAGE;
07632    
07633    if (!strncasecmp(a->argv[e->args -1], "on", 2)) {
07634       jb_setoutput(jb_error_output, jb_warning_output, jb_debug_output);
07635       ast_cli(a->fd, "IAX2 Jitterbuffer Debugging Enabled\n");
07636    } else {
07637       jb_setoutput(jb_error_output, jb_warning_output, NULL);
07638       ast_cli(a->fd, "IAX2 Jitterbuffer Debugging Disabled\n");
07639    }
07640    return CLI_SUCCESS;
07641 }
07642 
07643 static int iax2_write(struct ast_channel *c, struct ast_frame *f)
07644 {
07645    unsigned short callno = PTR_TO_CALLNO(ast_channel_tech_pvt(c));
07646    int res = -1;
07647    ast_mutex_lock(&iaxsl[callno]);
07648    if (iaxs[callno]) {
07649    /* If there's an outstanding error, return failure now */
07650       if (!iaxs[callno]->error) {
07651          if (ast_test_flag64(iaxs[callno], IAX_ALREADYGONE))
07652             res = 0;
07653             /* Don't waste bandwidth sending null frames */
07654          else if (f->frametype == AST_FRAME_NULL)
07655             res = 0;
07656          else if ((f->frametype == AST_FRAME_VOICE) && ast_test_flag64(iaxs[callno], IAX_QUELCH))
07657             res = 0;
07658          else if (!ast_test_flag(&iaxs[callno]->state, IAX_STATE_STARTED))
07659             res = 0;
07660          else
07661          /* Simple, just queue for transmission */
07662             res = iax2_send(iaxs[callno], f, 0, -1, 0, 0, 0);
07663       } else {
07664          ast_debug(1, "Write error: %s\n", strerror(errno));
07665       }
07666    }
07667    /* If it's already gone, just return */
07668    ast_mutex_unlock(&iaxsl[callno]);
07669    return res;
07670 }
07671 
07672 static int __send_command(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, const unsigned char *data, int datalen, int seqno,
07673       int now, int transfer, int final)
07674 {
07675    struct ast_frame f = { 0, };
07676    int res = 0;
07677 
07678    f.frametype = type;
07679    f.subclass.integer = command;
07680    f.datalen = datalen;
07681    f.src = __FUNCTION__;
07682    f.data.ptr = (void *) data;
07683 
07684    if ((res = queue_signalling(i, &f)) <= 0) {
07685       return res;
07686    }
07687 
07688    return iax2_send(i, &f, ts, seqno, now, transfer, final);
07689 }
07690 
07691 static int send_command(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, const unsigned char *data, int datalen, int seqno)
07692 {
07693    if (type == AST_FRAME_CONTROL && !iax2_is_control_frame_allowed(command)) {
07694       /* Control frame should not go out on the wire. */
07695       ast_debug(2, "Callno %u: Blocked sending control frame %d.\n",
07696          i->callno, command);
07697       return 0;
07698    }
07699    return __send_command(i, type, command, ts, data, datalen, seqno, 0, 0, 0);
07700 }
07701 
07702 static int send_command_locked(unsigned short callno, char type, int command, unsigned int ts, const unsigned char *data, int datalen, int seqno)
07703 {
07704    int res;
07705    ast_mutex_lock(&iaxsl[callno]);
07706    res = send_command(iaxs[callno], type, command, ts, data, datalen, seqno);
07707    ast_mutex_unlock(&iaxsl[callno]);
07708    return res;
07709 }
07710 
07711 /*!
07712  * \note Since this function calls iax2_predestroy() -> iax2_queue_hangup(),
07713  *       the pvt struct for the given call number may disappear during its 
07714  *       execution.
07715  */
07716 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)
07717 {
07718    int call_num = i->callno;
07719    /* It is assumed that the callno has already been locked */
07720    iax2_predestroy(i->callno);
07721    if (!iaxs[call_num])
07722       return -1;
07723    return __send_command(i, type, command, ts, data, datalen, seqno, 0, 0, 1);
07724 }
07725 
07726 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)
07727 {
07728    return __send_command(i, type, command, ts, data, datalen, seqno, 1, 0, 0);
07729 }
07730 
07731 static int send_command_transfer(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, const unsigned char *data, int datalen)
07732 {
07733    return __send_command(i, type, command, ts, data, datalen, 0, 0, 1, 0);
07734 }
07735 
07736 static int apply_context(struct iax2_context *con, const char *context)
07737 {
07738    while(con) {
07739       if (!strcmp(con->context, context) || !strcmp(con->context, "*"))
07740          return -1;
07741       con = con->next;
07742    }
07743    return 0;
07744 }
07745 
07746 
07747 static int check_access(int callno, struct sockaddr_in *sin, struct iax_ies *ies)
07748 {
07749    /* Start pessimistic */
07750    int res = -1;
07751    int version = 2;
07752    struct iax2_user *user = NULL, *best = NULL;
07753    int bestscore = 0;
07754    int gotcapability = 0;
07755    struct ast_variable *v = NULL, *tmpvar = NULL;
07756    struct ao2_iterator i;
07757    struct ast_sockaddr addr;
07758 
07759    if (!iaxs[callno])
07760       return res;
07761    if (ies->called_number)
07762       ast_string_field_set(iaxs[callno], exten, ies->called_number);
07763    if (ies->calling_number) {
07764       if (ast_test_flag64(&globalflags, IAX_SHRINKCALLERID)) { 
07765          ast_shrink_phone_number(ies->calling_number);
07766       }
07767       ast_string_field_set(iaxs[callno], cid_num, ies->calling_number);
07768    }
07769    if (ies->calling_name)
07770       ast_string_field_set(iaxs[callno], cid_name, ies->calling_name);
07771    if (ies->calling_ani)
07772       ast_string_field_set(iaxs[callno], ani, ies->calling_ani);
07773    if (ies->dnid)
07774       ast_string_field_set(iaxs[callno], dnid, ies->dnid);
07775    if (ies->rdnis)
07776       ast_string_field_set(iaxs[callno], rdnis, ies->rdnis);
07777    if (ies->called_context)
07778       ast_string_field_set(iaxs[callno], context, ies->called_context);
07779    if (ies->language)
07780       ast_string_field_set(iaxs[callno], language, ies->language);
07781    if (ies->username)
07782       ast_string_field_set(iaxs[callno], username, ies->username);
07783    if (ies->calling_ton > -1)
07784       iaxs[callno]->calling_ton = ies->calling_ton;
07785    if (ies->calling_tns > -1)
07786       iaxs[callno]->calling_tns = ies->calling_tns;
07787    if (ies->calling_pres > -1)
07788       iaxs[callno]->calling_pres = ies->calling_pres;
07789    if (ies->format)
07790       iaxs[callno]->peerformat = ies->format;
07791    if (ies->adsicpe)
07792       iaxs[callno]->peeradsicpe = ies->adsicpe;
07793    if (ies->capability) {
07794       gotcapability = 1;
07795       iaxs[callno]->peercapability = ies->capability;
07796    } 
07797    if (ies->version)
07798       version = ies->version;
07799 
07800    /* Use provided preferences until told otherwise for actual preferences */
07801    if (ies->codec_prefs) {
07802       ast_codec_pref_convert(&iaxs[callno]->rprefs, ies->codec_prefs, 32, 0);
07803       ast_codec_pref_convert(&iaxs[callno]->prefs, ies->codec_prefs, 32, 0);
07804    }
07805 
07806    if (!gotcapability) 
07807       iaxs[callno]->peercapability = iaxs[callno]->peerformat;
07808    if (version > IAX_PROTO_VERSION) {
07809       ast_log(LOG_WARNING, "Peer '%s' has too new a protocol version (%d) for me\n", 
07810          ast_inet_ntoa(sin->sin_addr), version);
07811       return res;
07812    }
07813    /* Search the userlist for a compatible entry, and fill in the rest */
07814    ast_sockaddr_from_sin(&addr, sin);
07815    i = ao2_iterator_init(users, 0);
07816    while ((user = ao2_iterator_next(&i))) {
07817       if ((ast_strlen_zero(iaxs[callno]->username) ||          /* No username specified */
07818          !strcmp(iaxs[callno]->username, user->name)) /* Or this username specified */
07819          && (ast_apply_acl(user->acl, &addr, "IAX2 user ACL: ") == AST_SENSE_ALLOW) /* Access is permitted from this IP */
07820          && (ast_strlen_zero(iaxs[callno]->context) ||         /* No context specified */
07821               apply_context(user->contexts, iaxs[callno]->context))) {        /* Context is permitted */
07822          if (!ast_strlen_zero(iaxs[callno]->username)) {
07823             /* Exact match, stop right now. */
07824             if (best)
07825                user_unref(best);
07826             best = user;
07827             break;
07828          } else if (ast_strlen_zero(user->secret) && ast_strlen_zero(user->dbsecret) && ast_strlen_zero(user->inkeys)) {
07829             /* No required authentication */
07830             if (user->acl) {
07831                /* There was host authentication and we passed, bonus! */
07832                if (bestscore < 4) {
07833                   bestscore = 4;
07834                   if (best)
07835                      user_unref(best);
07836                   best = user;
07837                   continue;
07838                }
07839             } else {
07840                /* No host access, but no secret, either, not bad */
07841                if (bestscore < 3) {
07842                   bestscore = 3;
07843                   if (best)
07844                      user_unref(best);
07845                   best = user;
07846                   continue;
07847                }
07848             }
07849          } else {
07850             if (user->acl) {
07851                /* Authentication, but host access too, eh, it's something.. */
07852                if (bestscore < 2) {
07853                   bestscore = 2;
07854                   if (best)
07855                      user_unref(best);
07856                   best = user;
07857                   continue;
07858                }
07859             } else {
07860                /* Authentication and no host access...  This is our baseline */
07861                if (bestscore < 1) {
07862                   bestscore = 1;
07863                   if (best)
07864                      user_unref(best);
07865                   best = user;
07866                   continue;
07867                }
07868             }
07869          }
07870       }
07871       user_unref(user);
07872    }
07873    ao2_iterator_destroy(&i);
07874    user = best;
07875    if (!user && !ast_strlen_zero(iaxs[callno]->username)) {
07876       user = realtime_user(iaxs[callno]->username, sin);
07877       if (user && (ast_apply_acl(user->acl, &addr, "IAX2 user ACL: ") == AST_SENSE_DENY      /* Access is denied from this IP */
07878          || (!ast_strlen_zero(iaxs[callno]->context) &&              /* No context specified */
07879             !apply_context(user->contexts, iaxs[callno]->context)))) {  /* Context is permitted */
07880          user = user_unref(user);
07881       }
07882    }
07883    if (user) {
07884       /* We found our match (use the first) */
07885       /* copy vars */
07886       for (v = user->vars ; v ; v = v->next) {
07887          if((tmpvar = ast_variable_new(v->name, v->value, v->file))) {
07888             tmpvar->next = iaxs[callno]->vars; 
07889             iaxs[callno]->vars = tmpvar;
07890          }
07891       }
07892       /* If a max AUTHREQ restriction is in place, activate it */
07893       if (user->maxauthreq > 0)
07894          ast_set_flag64(iaxs[callno], IAX_MAXAUTHREQ);
07895       iaxs[callno]->prefs = user->prefs;
07896       ast_copy_flags64(iaxs[callno], user, IAX_CODEC_USER_FIRST | IAX_IMMEDIATE | IAX_CODEC_NOPREFS | IAX_CODEC_NOCAP | IAX_FORCE_ENCRYPT);
07897       iaxs[callno]->encmethods = user->encmethods;
07898       /* Store the requested username if not specified */
07899       if (ast_strlen_zero(iaxs[callno]->username))
07900          ast_string_field_set(iaxs[callno], username, user->name);
07901       /* Store whether this is a trunked call, too, of course, and move if appropriate */
07902       ast_copy_flags64(iaxs[callno], user, IAX_TRUNK);
07903       iaxs[callno]->capability = user->capability;
07904       /* And use the default context */
07905       if (ast_strlen_zero(iaxs[callno]->context)) {
07906          if (user->contexts)
07907             ast_string_field_set(iaxs[callno], context, user->contexts->context);
07908          else
07909             ast_string_field_set(iaxs[callno], context, DEFAULT_CONTEXT);
07910       }
07911       /* And any input keys */
07912       ast_string_field_set(iaxs[callno], inkeys, user->inkeys);
07913       /* And the permitted authentication methods */
07914       iaxs[callno]->authmethods = user->authmethods;
07915       iaxs[callno]->adsi = user->adsi;
07916       /* If the user has callerid, override the remote caller id. */
07917       if (ast_test_flag64(user, IAX_HASCALLERID)) {
07918          iaxs[callno]->calling_tns = 0;
07919          iaxs[callno]->calling_ton = 0;
07920          ast_string_field_set(iaxs[callno], cid_num, user->cid_num);
07921          ast_string_field_set(iaxs[callno], cid_name, user->cid_name);
07922          ast_string_field_set(iaxs[callno], ani, user->cid_num);
07923          iaxs[callno]->calling_pres = AST_PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN;
07924       } else if (ast_strlen_zero(iaxs[callno]->cid_num) && ast_strlen_zero(iaxs[callno]->cid_name)) {
07925          iaxs[callno]->calling_pres = AST_PRES_NUMBER_NOT_AVAILABLE;
07926       } /* else user is allowed to set their own CID settings */
07927       if (!ast_strlen_zero(user->accountcode))
07928          ast_string_field_set(iaxs[callno], accountcode, user->accountcode);
07929       if (!ast_strlen_zero(user->mohinterpret))
07930          ast_string_field_set(iaxs[callno], mohinterpret, user->mohinterpret);
07931       if (!ast_strlen_zero(user->mohsuggest))
07932          ast_string_field_set(iaxs[callno], mohsuggest, user->mohsuggest);
07933       if (!ast_strlen_zero(user->parkinglot))
07934          ast_string_field_set(iaxs[callno], parkinglot, user->parkinglot);
07935       if (user->amaflags)
07936          iaxs[callno]->amaflags = user->amaflags;
07937       if (!ast_strlen_zero(user->language))
07938          ast_string_field_set(iaxs[callno], language, user->language);
07939       ast_copy_flags64(iaxs[callno], user, IAX_NOTRANSFER | IAX_TRANSFERMEDIA | IAX_USEJITTERBUF | IAX_FORCEJITTERBUF | IAX_SENDCONNECTEDLINE | IAX_RECVCONNECTEDLINE); 
07940       /* Keep this check last */
07941       if (!ast_strlen_zero(user->dbsecret)) {
07942          char *family, *key=NULL;
07943          char buf[80];
07944          family = ast_strdupa(user->dbsecret);
07945          key = strchr(family, '/');
07946          if (key) {
07947             *key = '\0';
07948             key++;
07949          }
07950          if (!key || ast_db_get(family, key, buf, sizeof(buf)))
07951             ast_log(LOG_WARNING, "Unable to retrieve database password for family/key '%s'!\n", user->dbsecret);
07952          else
07953             ast_string_field_set(iaxs[callno], secret, buf);
07954       } else
07955          ast_string_field_set(iaxs[callno], secret, user->secret);
07956       res = 0;
07957       user = user_unref(user);
07958    } else {
07959        /* user was not found, but we should still fake an AUTHREQ.
07960         * Set authmethods to the last known authmethod used by the system
07961         * Set a fake secret, it's not looked at, just required to attempt authentication.
07962         * Set authrej so the AUTHREP is rejected without even looking at its contents */
07963       iaxs[callno]->authmethods = last_authmethod ? last_authmethod : (IAX_AUTH_MD5 | IAX_AUTH_PLAINTEXT);
07964       ast_string_field_set(iaxs[callno], secret, "badsecret");
07965       iaxs[callno]->authrej = 1;
07966       if (!ast_strlen_zero(iaxs[callno]->username)) {
07967          /* only send the AUTHREQ if a username was specified. */
07968          res = 0;
07969       }
07970    }
07971    ast_set2_flag64(iaxs[callno], iax2_getpeertrunk(*sin), IAX_TRUNK);
07972    return res;
07973 }
07974 
07975 static int raw_hangup(struct sockaddr_in *sin, unsigned short src, unsigned short dst, int sockfd)
07976 {
07977    struct ast_iax2_full_hdr fh;
07978    fh.scallno = htons(src | IAX_FLAG_FULL);
07979    fh.dcallno = htons(dst);
07980    fh.ts = 0;
07981    fh.oseqno = 0;
07982    fh.iseqno = 0;
07983    fh.type = AST_FRAME_IAX;
07984    fh.csub = compress_subclass(IAX_COMMAND_INVAL);
07985    iax_outputframe(NULL, &fh, 0, sin, 0);
07986    ast_debug(1, "Raw Hangup %s:%d, src=%d, dst=%d\n",
07987       ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port), src, dst);
07988    return sendto(sockfd, &fh, sizeof(fh), 0, (struct sockaddr *)sin, sizeof(*sin));
07989 }
07990 
07991 static void merge_encryption(struct chan_iax2_pvt *p, unsigned int enc)
07992 {
07993    /* Select exactly one common encryption if there are any */
07994    p->encmethods &= enc;
07995    if (p->encmethods) {
07996       if (!(p->encmethods & IAX_ENCRYPT_KEYROTATE)){ /* if key rotation is not supported, turn off keyrotation. */
07997          p->keyrotateid = -2;
07998       }
07999       if (p->encmethods & IAX_ENCRYPT_AES128)
08000          p->encmethods = IAX_ENCRYPT_AES128;
08001       else
08002          p->encmethods = 0;
08003    }
08004 }
08005 
08006 /*!
08007  * \pre iaxsl[call_num] is locked
08008  *
08009  * \note Since this function calls send_command_final(), the pvt struct for the given
08010  *       call number may disappear while executing this function.
08011  */
08012 static int authenticate_request(int call_num)
08013 {
08014    struct iax_ie_data ied;
08015    int res = -1, authreq_restrict = 0;
08016    char challenge[10];
08017    struct chan_iax2_pvt *p = iaxs[call_num];
08018 
08019    memset(&ied, 0, sizeof(ied));
08020 
08021    /* If an AUTHREQ restriction is in place, make sure we can send an AUTHREQ back */
08022    if (ast_test_flag64(p, IAX_MAXAUTHREQ)) {
08023       struct iax2_user *user;
08024 
08025       user = ao2_find(users, p->username, OBJ_KEY);
08026       if (user) {
08027          if (user->curauthreq == user->maxauthreq)
08028             authreq_restrict = 1;
08029          else
08030             user->curauthreq++;
08031          user = user_unref(user);
08032       }
08033    }
08034 
08035    /* If the AUTHREQ limit test failed, send back an error */
08036    if (authreq_restrict) {
08037       iax_ie_append_str(&ied, IAX_IE_CAUSE, "Unauthenticated call limit reached");
08038       iax_ie_append_byte(&ied, IAX_IE_CAUSECODE, AST_CAUSE_CALL_REJECTED);
08039       send_command_final(p, AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied.buf, ied.pos, -1);
08040       return 0;
08041    }
08042 
08043    iax_ie_append_short(&ied, IAX_IE_AUTHMETHODS, p->authmethods);
08044    if (p->authmethods & (IAX_AUTH_MD5 | IAX_AUTH_RSA)) {
08045       snprintf(challenge, sizeof(challenge), "%d", (int)ast_random());
08046       ast_string_field_set(p, challenge, challenge);
08047       /* snprintf(p->challenge, sizeof(p->challenge), "%d", (int)ast_random()); */
08048       iax_ie_append_str(&ied, IAX_IE_CHALLENGE, p->challenge);
08049    }
08050    if (p->encmethods)
08051       iax_ie_append_short(&ied, IAX_IE_ENCRYPTION, p->encmethods);
08052 
08053    iax_ie_append_str(&ied,IAX_IE_USERNAME, p->username);
08054 
08055    res = send_command(p, AST_FRAME_IAX, IAX_COMMAND_AUTHREQ, 0, ied.buf, ied.pos, -1);
08056 
08057    if (p->encmethods)
08058       ast_set_flag64(p, IAX_ENCRYPTED);
08059 
08060    return res;
08061 }
08062 
08063 static int authenticate_verify(struct chan_iax2_pvt *p, struct iax_ies *ies)
08064 {
08065    char requeststr[256];
08066    char md5secret[256] = "";
08067    char secret[256] = "";
08068    char rsasecret[256] = "";
08069    int res = -1; 
08070    int x;
08071    struct iax2_user *user;
08072 
08073    if (p->authrej) {
08074       return res;
08075    }
08076    user = ao2_find(users, p->username, OBJ_KEY);
08077    if (user) {
08078       if (ast_test_flag64(p, IAX_MAXAUTHREQ)) {
08079          ast_atomic_fetchadd_int(&user->curauthreq, -1);
08080          ast_clear_flag64(p, IAX_MAXAUTHREQ);
08081       }
08082       ast_string_field_set(p, host, user->name);
08083       user = user_unref(user);
08084    }
08085    if (ast_test_flag64(p, IAX_FORCE_ENCRYPT) && !p->encmethods) { 
08086       ast_log(LOG_NOTICE, "Call Terminated, Incoming call is unencrypted while force encrypt is enabled.\n");
08087       return res;
08088    }
08089    if (!ast_test_flag(&p->state, IAX_STATE_AUTHENTICATED))
08090       return res;
08091    if (ies->password)
08092       ast_copy_string(secret, ies->password, sizeof(secret));
08093    if (ies->md5_result)
08094       ast_copy_string(md5secret, ies->md5_result, sizeof(md5secret));
08095    if (ies->rsa_result)
08096       ast_copy_string(rsasecret, ies->rsa_result, sizeof(rsasecret));
08097    if ((p->authmethods & IAX_AUTH_RSA) && !ast_strlen_zero(rsasecret) && !ast_strlen_zero(p->inkeys)) {
08098       struct ast_key *key;
08099       char *keyn;
08100       char tmpkey[256];
08101       char *stringp=NULL;
08102       ast_copy_string(tmpkey, p->inkeys, sizeof(tmpkey));
08103       stringp=tmpkey;
08104       keyn = strsep(&stringp, ":");
08105       while(keyn) {
08106          key = ast_key_get(keyn, AST_KEY_PUBLIC);
08107          if (key && !ast_check_signature(key, p->challenge, rsasecret)) {
08108             res = 0;
08109             break;
08110          } else if (!key)
08111             ast_log(LOG_WARNING, "requested inkey '%s' for RSA authentication does not exist\n", keyn);
08112          keyn = strsep(&stringp, ":");
08113       }
08114    } else if (p->authmethods & IAX_AUTH_MD5) {
08115       struct MD5Context md5;
08116       unsigned char digest[16];
08117       char *tmppw, *stringp;
08118       
08119       tmppw = ast_strdupa(p->secret);
08120       stringp = tmppw;
08121       while((tmppw = strsep(&stringp, ";"))) {
08122          MD5Init(&md5);
08123          MD5Update(&md5, (unsigned char *)p->challenge, strlen(p->challenge));
08124          MD5Update(&md5, (unsigned char *)tmppw, strlen(tmppw));
08125          MD5Final(digest, &md5);
08126          /* If they support md5, authenticate with it.  */
08127          for (x=0;x<16;x++)
08128             sprintf(requeststr + (x << 1), "%2.2x", digest[x]); /* safe */
08129          if (!strcasecmp(requeststr, md5secret)) {
08130             res = 0;
08131             break;
08132          }
08133       }
08134    } else if (p->authmethods & IAX_AUTH_PLAINTEXT) {
08135       if (!strcmp(secret, p->secret))
08136          res = 0;
08137    }
08138    return res;
08139 }
08140 
08141 /*! \brief Verify inbound registration */
08142 static int register_verify(int callno, struct sockaddr_in *sin, struct iax_ies *ies)
08143 {
08144    char requeststr[256] = "";
08145    char peer[256] = "";
08146    char md5secret[256] = "";
08147    char rsasecret[256] = "";
08148    char secret[256] = "";
08149    struct iax2_peer *p = NULL;
08150    struct ast_key *key;
08151    char *keyn;
08152    int x;
08153    int expire = 0;
08154    int res = -1;
08155    struct ast_sockaddr addr;
08156 
08157    ast_clear_flag(&iaxs[callno]->state, IAX_STATE_AUTHENTICATED);
08158    /* iaxs[callno]->peer[0] = '\0'; not necc. any more-- stringfield is pre-inited to null string */
08159    if (ies->username)
08160       ast_copy_string(peer, ies->username, sizeof(peer));
08161    if (ies->password)
08162       ast_copy_string(secret, ies->password, sizeof(secret));
08163    if (ies->md5_result)
08164       ast_copy_string(md5secret, ies->md5_result, sizeof(md5secret));
08165    if (ies->rsa_result)
08166       ast_copy_string(rsasecret, ies->rsa_result, sizeof(rsasecret));
08167    if (ies->refresh)
08168       expire = ies->refresh;
08169 
08170    if (ast_strlen_zero(peer)) {
08171       ast_log(LOG_NOTICE, "Empty registration from %s\n", ast_inet_ntoa(sin->sin_addr));
08172       return -1;
08173    }
08174 
08175    /* SLD: first call to lookup peer during registration */
08176    ast_mutex_unlock(&iaxsl[callno]);
08177    p = find_peer(peer, 1);
08178    ast_mutex_lock(&iaxsl[callno]);
08179    if (!p || !iaxs[callno]) {
08180       if (iaxs[callno]) {
08181          int plaintext = ((last_authmethod & IAX_AUTH_PLAINTEXT) | (iaxs[callno]->authmethods & IAX_AUTH_PLAINTEXT));
08182          /* Anything, as long as it's non-blank */
08183          ast_string_field_set(iaxs[callno], secret, "badsecret");
08184          /* An AUTHREQ must be sent in response to a REGREQ of an invalid peer unless
08185           * 1. A challenge already exists indicating a AUTHREQ was already sent out.
08186           * 2. A plaintext secret is present in ie as result of a previous AUTHREQ requesting it.
08187           * 3. A plaintext secret is present in the ie and the last_authmethod used by a peer happened
08188           *    to be plaintext, indicating it is an authmethod used by other peers on the system. 
08189           *
08190           * If none of these cases exist, res will be returned as 0 without authentication indicating
08191           * an AUTHREQ needs to be sent out. */
08192 
08193          if (ast_strlen_zero(iaxs[callno]->challenge) &&
08194             !(!ast_strlen_zero(secret) && plaintext)) {
08195             /* by setting res to 0, an REGAUTH will be sent */
08196             res = 0;
08197          }
08198       }
08199       if (authdebug && !p)
08200          ast_log(LOG_NOTICE, "No registration for peer '%s' (from %s)\n", peer, ast_inet_ntoa(sin->sin_addr));
08201       goto return_unref;
08202    }
08203 
08204    if (!ast_test_flag64(p, IAX_DYNAMIC)) {
08205       if (authdebug)
08206          ast_log(LOG_NOTICE, "Peer '%s' is not dynamic (from %s)\n", peer, ast_inet_ntoa(sin->sin_addr));
08207       goto return_unref;
08208    }
08209 
08210    ast_sockaddr_from_sin(&addr, sin);
08211    if (!ast_apply_acl(p->acl, &addr, "IAX2 Peer ACL: ")) {
08212       if (authdebug)
08213          ast_log(LOG_NOTICE, "Host %s denied access to register peer '%s'\n", ast_inet_ntoa(sin->sin_addr), p->name);
08214       goto return_unref;
08215    }
08216    ast_string_field_set(iaxs[callno], secret, p->secret);
08217    ast_string_field_set(iaxs[callno], inkeys, p->inkeys);
08218    /* Check secret against what we have on file */
08219    if (!ast_strlen_zero(rsasecret) && (p->authmethods & IAX_AUTH_RSA) && !ast_strlen_zero(iaxs[callno]->challenge)) {
08220       if (!ast_strlen_zero(p->inkeys)) {
08221          char tmpkeys[256];
08222          char *stringp=NULL;
08223          ast_copy_string(tmpkeys, p->inkeys, sizeof(tmpkeys));
08224          stringp=tmpkeys;
08225          keyn = strsep(&stringp, ":");
08226          while(keyn) {
08227             key = ast_key_get(keyn, AST_KEY_PUBLIC);
08228             if (key && !ast_check_signature(key, iaxs[callno]->challenge, rsasecret)) {
08229                ast_set_flag(&iaxs[callno]->state, IAX_STATE_AUTHENTICATED);
08230                break;
08231             } else if (!key)
08232                ast_log(LOG_WARNING, "requested inkey '%s' does not exist\n", keyn);
08233             keyn = strsep(&stringp, ":");
08234          }
08235          if (!keyn) {
08236             if (authdebug)
08237                ast_log(LOG_NOTICE, "Host %s failed RSA authentication with inkeys '%s'\n", peer, p->inkeys);
08238             goto return_unref;
08239          }
08240       } else {
08241          if (authdebug)
08242             ast_log(LOG_NOTICE, "Host '%s' trying to do RSA authentication, but we have no inkeys\n", peer);
08243          goto return_unref;
08244       }
08245    } else if (!ast_strlen_zero(md5secret) && (p->authmethods & IAX_AUTH_MD5) && !ast_strlen_zero(iaxs[callno]->challenge)) {
08246       struct MD5Context md5;
08247       unsigned char digest[16];
08248       char *tmppw, *stringp;
08249 
08250       tmppw = ast_strdupa(p->secret);
08251       stringp = tmppw;
08252       while((tmppw = strsep(&stringp, ";"))) {
08253          MD5Init(&md5);
08254          MD5Update(&md5, (unsigned char *)iaxs[callno]->challenge, strlen(iaxs[callno]->challenge));
08255          MD5Update(&md5, (unsigned char *)tmppw, strlen(tmppw));
08256          MD5Final(digest, &md5);
08257          for (x=0;x<16;x++)
08258             sprintf(requeststr + (x << 1), "%2.2x", digest[x]); /* safe */
08259          if (!strcasecmp(requeststr, md5secret))
08260             break;
08261       }
08262       if (tmppw) {
08263          ast_set_flag(&iaxs[callno]->state, IAX_STATE_AUTHENTICATED);
08264       } else {
08265          if (authdebug)
08266             ast_log(LOG_NOTICE, "Host %s failed MD5 authentication for '%s' (%s != %s)\n", ast_inet_ntoa(sin->sin_addr), p->name, requeststr, md5secret);
08267          goto return_unref;
08268       }
08269    } else if (!ast_strlen_zero(secret) && (p->authmethods & IAX_AUTH_PLAINTEXT)) {
08270       /* They've provided a plain text password and we support that */
08271       if (strcmp(secret, p->secret)) {
08272          if (authdebug)
08273             ast_log(LOG_NOTICE, "Host %s did not provide proper plaintext password for '%s'\n", ast_inet_ntoa(sin->sin_addr), p->name);
08274          goto return_unref;
08275       } else
08276          ast_set_flag(&iaxs[callno]->state, IAX_STATE_AUTHENTICATED);
08277    } else if (!ast_strlen_zero(iaxs[callno]->challenge) && ast_strlen_zero(md5secret) && ast_strlen_zero(rsasecret)) {
08278       /* if challenge has been sent, but no challenge response if given, reject. */
08279       goto return_unref;
08280    }
08281    ast_devstate_changed(AST_DEVICE_UNKNOWN, AST_DEVSTATE_CACHABLE, "IAX2/%s", p->name); /* Activate notification */
08282 
08283    /* either Authentication has taken place, or a REGAUTH must be sent before verifying registration */
08284    res = 0;
08285 
08286 return_unref:
08287    if (iaxs[callno]) {
08288       ast_string_field_set(iaxs[callno], peer, peer);
08289 
08290       /* Choose lowest expiry number */
08291       if (expire && (expire < iaxs[callno]->expiry)) {
08292          iaxs[callno]->expiry = expire;
08293       }
08294    }
08295 
08296    if (p) {
08297       peer_unref(p);
08298    }
08299    return res;
08300 }
08301 
08302 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)
08303 {
08304    int res = -1;
08305    int x;
08306    if (!ast_strlen_zero(keyn)) {
08307       if (!(authmethods & IAX_AUTH_RSA)) {
08308          if (ast_strlen_zero(secret)) 
08309             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));
08310       } else if (ast_strlen_zero(challenge)) {
08311          ast_log(LOG_NOTICE, "No challenge provided for RSA authentication to %s\n", ast_inet_ntoa(sin->sin_addr));
08312       } else {
08313          char sig[256];
08314          struct ast_key *key;
08315          key = ast_key_get(keyn, AST_KEY_PRIVATE);
08316          if (!key) {
08317             ast_log(LOG_NOTICE, "Unable to find private key '%s'\n", keyn);
08318          } else {
08319             if (ast_sign(key, (char*)challenge, sig)) {
08320                ast_log(LOG_NOTICE, "Unable to sign challenge with key\n");
08321                res = -1;
08322             } else {
08323                iax_ie_append_str(ied, IAX_IE_RSA_RESULT, sig);
08324                res = 0;
08325             }
08326          }
08327       }
08328    } 
08329    /* Fall back */
08330    if (res && !ast_strlen_zero(secret)) {
08331       if ((authmethods & IAX_AUTH_MD5) && !ast_strlen_zero(challenge)) {
08332          struct MD5Context md5;
08333          unsigned char digest[16];
08334          char digres[128];
08335          MD5Init(&md5);
08336          MD5Update(&md5, (unsigned char *)challenge, strlen(challenge));
08337          MD5Update(&md5, (unsigned char *)secret, strlen(secret));
08338          MD5Final(digest, &md5);
08339          /* If they support md5, authenticate with it.  */
08340          for (x=0;x<16;x++)
08341             sprintf(digres + (x << 1),  "%2.2x", digest[x]); /* safe */
08342          if (pvt) {
08343             build_encryption_keys(digest, pvt);
08344          }
08345          iax_ie_append_str(ied, IAX_IE_MD5_RESULT, digres);
08346          res = 0;
08347       } else if (authmethods & IAX_AUTH_PLAINTEXT) {
08348          iax_ie_append_str(ied, IAX_IE_PASSWORD, secret);
08349          res = 0;
08350       } else
08351          ast_log(LOG_NOTICE, "No way to send secret to peer '%s' (their methods: %d)\n", ast_inet_ntoa(sin->sin_addr), authmethods);
08352    }
08353    return res;
08354 }
08355 
08356 /*!
08357  * \note This function calls realtime_peer -> reg_source_db -> iax2_poke_peer -> find_callno,
08358  *       so do not call this function with a pvt lock held.
08359  */
08360 static int authenticate_reply(struct chan_iax2_pvt *p, struct sockaddr_in *sin, struct iax_ies *ies, const char *override, const char *okey)
08361 {
08362    struct iax2_peer *peer = NULL;
08363    /* Start pessimistic */
08364    int res = -1;
08365    int authmethods = 0;
08366    struct iax_ie_data ied;
08367    uint16_t callno = p->callno;
08368 
08369    memset(&ied, 0, sizeof(ied));
08370    
08371    if (ies->username)
08372       ast_string_field_set(p, username, ies->username);
08373    if (ies->challenge)
08374       ast_string_field_set(p, challenge, ies->challenge);
08375    if (ies->authmethods)
08376       authmethods = ies->authmethods;
08377    if (authmethods & IAX_AUTH_MD5)
08378       merge_encryption(p, ies->encmethods);
08379    else
08380       p->encmethods = 0;
08381 
08382    /* Check for override RSA authentication first */
08383    if (!ast_strlen_zero(override) || !ast_strlen_zero(okey)) {
08384       /* Normal password authentication */
08385       res = authenticate(p->challenge, override, okey, authmethods, &ied, sin, p);
08386    } else {
08387       struct ao2_iterator i = ao2_iterator_init(peers, 0);
08388       while ((peer = ao2_iterator_next(&i))) {
08389          struct sockaddr_in peer_addr;
08390 
08391          ast_sockaddr_to_sin(&peer->addr, &peer_addr);
08392 
08393          if ((ast_strlen_zero(p->peer) || !strcmp(p->peer, peer->name)) 
08394              /* No peer specified at our end, or this is the peer */
08395              && (ast_strlen_zero(peer->username) || (!strcmp(peer->username, p->username)))
08396              /* No username specified in peer rule, or this is the right username */
08397              && (!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)))
08398              /* No specified host, or this is our host */
08399             ) {
08400             res = authenticate(p->challenge, peer->secret, peer->outkey, authmethods, &ied, sin, p);
08401             if (!res) {
08402                peer_unref(peer);
08403                break;
08404             }
08405          }
08406          peer_unref(peer);
08407       }
08408       ao2_iterator_destroy(&i);
08409       if (!peer) {
08410          /* We checked our list and didn't find one.  It's unlikely, but possible, 
08411             that we're trying to authenticate *to* a realtime peer */
08412          const char *peer_name = ast_strdupa(p->peer);
08413          ast_mutex_unlock(&iaxsl[callno]);
08414          if ((peer = realtime_peer(peer_name, NULL))) {
08415             ast_mutex_lock(&iaxsl[callno]);
08416             if (!(p = iaxs[callno])) {
08417                peer_unref(peer);
08418                return -1;
08419             }
08420             res = authenticate(p->challenge, peer->secret,peer->outkey, authmethods, &ied, sin, p);
08421             peer_unref(peer);
08422          }
08423          if (!peer) {
08424             ast_mutex_lock(&iaxsl[callno]);
08425             if (!(p = iaxs[callno]))
08426                return -1;
08427          }
08428       }
08429    }
08430 
08431    if (ies->encmethods) {
08432       ast_set_flag64(p, IAX_ENCRYPTED | IAX_KEYPOPULATED);
08433    } else if (ast_test_flag64(iaxs[callno], IAX_FORCE_ENCRYPT)) {
08434       ast_log(LOG_NOTICE, "Call initiated without encryption while forceencryption=yes option is set\n");
08435       return -1;             /* if force encryption is yes, and no encryption methods, then return -1 to hangup */
08436    }
08437    if (!res) {
08438       struct ast_datastore *variablestore;
08439       struct ast_variable *var, *prev = NULL;
08440       AST_LIST_HEAD(, ast_var_t) *varlist;
08441       varlist = ast_calloc(1, sizeof(*varlist));
08442       variablestore = ast_datastore_alloc(&iax2_variable_datastore_info, NULL);
08443       if (variablestore && varlist && p->owner) {
08444          variablestore->data = varlist;
08445          variablestore->inheritance = DATASTORE_INHERIT_FOREVER;
08446          AST_LIST_HEAD_INIT(varlist);
08447          for (var = ies->vars; var; var = var->next) {
08448             struct ast_var_t *newvar = ast_var_assign(var->name, var->value);
08449             if (prev)
08450                ast_free(prev);
08451             prev = var;
08452             if (!newvar) {
08453                /* Don't abort list traversal, as this would leave ies->vars in an inconsistent state. */
08454                ast_log(LOG_ERROR, "Memory allocation error while processing IAX2 variables\n");
08455             } else {
08456                AST_LIST_INSERT_TAIL(varlist, newvar, entries);
08457             }
08458          }
08459          if (prev)
08460             ast_free(prev);
08461          ies->vars = NULL;
08462          ast_channel_datastore_add(p->owner, variablestore);
08463       } else {
08464          if (p->owner)
08465             ast_log(LOG_ERROR, "Memory allocation error while processing IAX2 variables\n");
08466          if (variablestore)
08467             ast_datastore_free(variablestore);
08468          if (varlist)
08469             ast_free(varlist);
08470       }
08471    }
08472 
08473    if (!res)
08474       res = send_command(p, AST_FRAME_IAX, IAX_COMMAND_AUTHREP, 0, ied.buf, ied.pos, -1);
08475    return res;
08476 }
08477 
08478 static int iax2_do_register(struct iax2_registry *reg);
08479 
08480 static void __iax2_do_register_s(const void *data)
08481 {
08482    struct iax2_registry *reg = (struct iax2_registry *)data;
08483    reg->expire = -1;
08484    iax2_do_register(reg);
08485 }
08486 
08487 static int iax2_do_register_s(const void *data)
08488 {
08489 #ifdef SCHED_MULTITHREADED
08490    if (schedule_action(__iax2_do_register_s, data))
08491 #endif      
08492       __iax2_do_register_s(data);
08493    return 0;
08494 }
08495 
08496 static int try_transfer(struct chan_iax2_pvt *pvt, struct iax_ies *ies)
08497 {
08498    int newcall = 0;
08499    char newip[256];
08500    struct iax_ie_data ied;
08501    struct sockaddr_in new = { 0, };
08502 
08503    memset(&ied, 0, sizeof(ied));
08504    if (ies->apparent_addr)
08505       memmove(&new, ies->apparent_addr, sizeof(new));
08506    if (ies->callno)
08507       newcall = ies->callno;
08508    if (!newcall || !new.sin_addr.s_addr || !new.sin_port) {
08509       ast_log(LOG_WARNING, "Invalid transfer request\n");
08510       return -1;
08511    }
08512    pvt->transfercallno = newcall;
08513    memcpy(&pvt->transfer, &new, sizeof(pvt->transfer));
08514    inet_aton(newip, &pvt->transfer.sin_addr);
08515    pvt->transfer.sin_family = AF_INET;
08516    pvt->transferid = ies->transferid;
08517    /* only store by transfercallno if this is a new transfer,
08518     * just in case we get a duplicate TXREQ */
08519    if (pvt->transferring == TRANSFER_NONE) {
08520       store_by_transfercallno(pvt);
08521    }
08522    pvt->transferring = TRANSFER_BEGIN;
08523 
08524    if (ies->transferid)
08525       iax_ie_append_int(&ied, IAX_IE_TRANSFERID, ies->transferid);
08526    send_command_transfer(pvt, AST_FRAME_IAX, IAX_COMMAND_TXCNT, 0, ied.buf, ied.pos);
08527    return 0;
08528 }
08529 
08530 static int complete_dpreply(struct chan_iax2_pvt *pvt, struct iax_ies *ies)
08531 {
08532    char exten[256] = "";
08533    int status = CACHE_FLAG_UNKNOWN, expiry = iaxdefaultdpcache, x, matchmore = 0;
08534    struct iax2_dpcache *dp = NULL;
08535    
08536    if (ies->called_number)
08537       ast_copy_string(exten, ies->called_number, sizeof(exten));
08538    
08539    if (ies->dpstatus & IAX_DPSTATUS_EXISTS)
08540       status = CACHE_FLAG_EXISTS;
08541    else if (ies->dpstatus & IAX_DPSTATUS_CANEXIST)
08542       status = CACHE_FLAG_CANEXIST;
08543    else if (ies->dpstatus & IAX_DPSTATUS_NONEXISTENT)
08544       status = CACHE_FLAG_NONEXISTENT;
08545 
08546    if (ies->refresh)
08547       expiry = ies->refresh;
08548    if (ies->dpstatus & IAX_DPSTATUS_MATCHMORE)
08549       matchmore = CACHE_FLAG_MATCHMORE;
08550    
08551    AST_LIST_LOCK(&dpcache);
08552    AST_LIST_TRAVERSE_SAFE_BEGIN(&dpcache, dp, peer_list) {
08553       if (strcmp(dp->exten, exten))
08554          continue;
08555       AST_LIST_REMOVE_CURRENT(peer_list);
08556       dp->callno = 0;
08557       dp->expiry.tv_sec = dp->orig.tv_sec + expiry;
08558       if (dp->flags & CACHE_FLAG_PENDING) {
08559          dp->flags &= ~CACHE_FLAG_PENDING;
08560          dp->flags |= status;
08561          dp->flags |= matchmore;
08562       }
08563       /* Wake up waiters */
08564       for (x = 0; x < ARRAY_LEN(dp->waiters); x++) {
08565          if (dp->waiters[x] > -1) {
08566             if (write(dp->waiters[x], "asdf", 4) < 0) {
08567             }
08568          }
08569       }
08570    }
08571    AST_LIST_TRAVERSE_SAFE_END;
08572    AST_LIST_UNLOCK(&dpcache);
08573 
08574    return 0;
08575 }
08576 
08577 static int complete_transfer(int callno, struct iax_ies *ies)
08578 {
08579    int peercallno = 0;
08580    struct chan_iax2_pvt *pvt = iaxs[callno];
08581    struct iax_frame *cur;
08582    jb_frame frame;
08583 
08584    if (ies->callno)
08585       peercallno = ies->callno;
08586 
08587    if (peercallno < 1) {
08588       ast_log(LOG_WARNING, "Invalid transfer request\n");
08589       return -1;
08590    }
08591    remove_by_transfercallno(pvt);
08592    /* since a transfer has taken place, the address will change.
08593     * This must be accounted for in the peercnts table.  Remove
08594     * the old address and add the new one */
08595    peercnt_remove_by_addr(&pvt->addr);
08596    peercnt_add(&pvt->transfer);
08597    /* now copy over the new address */
08598    memcpy(&pvt->addr, &pvt->transfer, sizeof(pvt->addr));
08599    memset(&pvt->transfer, 0, sizeof(pvt->transfer));
08600    /* Reset sequence numbers */
08601    pvt->oseqno = 0;
08602    pvt->rseqno = 0;
08603    pvt->iseqno = 0;
08604    pvt->aseqno = 0;
08605 
08606    if (pvt->peercallno) {
08607       remove_by_peercallno(pvt);
08608    }
08609    pvt->peercallno = peercallno;
08610    /*this is where the transfering call swiches hash tables */
08611    store_by_peercallno(pvt);
08612    pvt->transferring = TRANSFER_NONE;
08613    pvt->svoiceformat = -1;
08614    pvt->voiceformat = 0;
08615    pvt->svideoformat = -1;
08616    pvt->videoformat = 0;
08617    pvt->transfercallno = 0;
08618    memset(&pvt->rxcore, 0, sizeof(pvt->rxcore));
08619    memset(&pvt->offset, 0, sizeof(pvt->offset));
08620    /* reset jitterbuffer */
08621    while(jb_getall(pvt->jb,&frame) == JB_OK)
08622       iax2_frame_free(frame.data);
08623    jb_reset(pvt->jb);
08624    pvt->lag = 0;
08625    pvt->last = 0;
08626    pvt->lastsent = 0;
08627    pvt->nextpred = 0;
08628    pvt->pingtime = DEFAULT_RETRY_TIME;
08629    AST_LIST_TRAVERSE(&frame_queue[callno], cur, list) {
08630       /* We must cancel any packets that would have been transmitted
08631          because now we're talking to someone new.  It's okay, they
08632          were transmitted to someone that didn't care anyway. */
08633       cur->retries = -1;
08634    }
08635    return 0;
08636 }
08637 
08638 /*! \brief Acknowledgment received for OUR registration */
08639 static int iax2_ack_registry(struct iax_ies *ies, struct sockaddr_in *sin, int callno)
08640 {
08641    struct iax2_registry *reg;
08642    /* Start pessimistic */
08643    char peer[256] = "";
08644    char msgstatus[60];
08645    int refresh = 60;
08646    char ourip[256] = "<Unspecified>";
08647    struct sockaddr_in oldus;
08648    struct sockaddr_in us;
08649    int oldmsgs;
08650    struct sockaddr_in reg_addr;
08651 
08652    memset(&us, 0, sizeof(us));
08653    if (ies->apparent_addr) {
08654       memmove(&us, ies->apparent_addr, sizeof(us));
08655    }
08656    if (ies->username) {
08657       ast_copy_string(peer, ies->username, sizeof(peer));
08658    }
08659    if (ies->refresh) {
08660       refresh = ies->refresh;
08661    }
08662    if (ies->calling_number) {
08663       /* We don't do anything with it really, but maybe we should */
08664    }
08665    reg = iaxs[callno]->reg;
08666    if (!reg) {
08667       ast_log(LOG_WARNING, "Registry acknowledge on unknown registry '%s'\n", peer);
08668       return -1;
08669    }
08670    memcpy(&oldus, &reg->us, sizeof(oldus));
08671    oldmsgs = reg->messages;
08672    ast_sockaddr_to_sin(&reg->addr, &reg_addr);
08673    if (inaddrcmp(&reg_addr, sin)) {
08674       ast_log(LOG_WARNING, "Received unsolicited registry ack from '%s'\n", ast_inet_ntoa(sin->sin_addr));
08675       return -1;
08676    }
08677    memcpy(&reg->us, &us, sizeof(reg->us));
08678    if (ies->msgcount >= 0) {
08679       reg->messages = ies->msgcount & 0xffff;      /* only low 16 bits are used in the transmission of the IE */
08680    }
08681    /* always refresh the registration at the interval requested by the server
08682       we are registering to
08683    */
08684    reg->refresh = refresh;
08685    reg->expire = iax2_sched_replace(reg->expire, sched,
08686       (5 * reg->refresh / 6) * 1000, iax2_do_register_s, reg);
08687    if (inaddrcmp(&oldus, &reg->us) || (reg->messages != oldmsgs)) {
08688       if (reg->messages > 255) {
08689          snprintf(msgstatus, sizeof(msgstatus), " with %d new and %d old messages waiting", reg->messages & 0xff, reg->messages >> 8);
08690       } else if (reg->messages > 1) {
08691          snprintf(msgstatus, sizeof(msgstatus), " with %d new messages waiting", reg->messages);
08692       } else if (reg->messages > 0) {
08693          ast_copy_string(msgstatus, " with 1 new message waiting", sizeof(msgstatus));
08694       } else {
08695          ast_copy_string(msgstatus, " with no messages waiting", sizeof(msgstatus));
08696       }
08697       snprintf(ourip, sizeof(ourip), "%s:%d", ast_inet_ntoa(reg->us.sin_addr), ntohs(reg->us.sin_port));
08698       ast_verb(3, "Registered IAX2 to '%s', who sees us as %s%s\n", ast_inet_ntoa(sin->sin_addr), ourip, msgstatus);
08699       manager_event(EVENT_FLAG_SYSTEM, "Registry", "ChannelType: IAX2\r\nDomain: %s\r\nStatus: Registered\r\n", ast_inet_ntoa(sin->sin_addr));
08700    }
08701    reg->regstate = REG_STATE_REGISTERED;
08702    return 0;
08703 }
08704 
08705 static int iax2_append_register(const char *hostname, const char *username,
08706    const char *secret, const char *porta)
08707 {
08708    struct iax2_registry *reg;
08709 
08710    if (!(reg = ast_calloc(1, sizeof(*reg))))
08711       return -1;
08712 
08713    reg->addr.ss.ss_family = AF_INET;
08714    if (ast_dnsmgr_lookup(hostname, &reg->addr, &reg->dnsmgr, srvlookup ? "_iax._udp" : NULL) < 0) {
08715       ast_free(reg);
08716       return -1;
08717    }
08718 
08719    ast_copy_string(reg->username, username, sizeof(reg->username));
08720 
08721    if (secret)
08722       ast_copy_string(reg->secret, secret, sizeof(reg->secret));
08723 
08724    reg->expire = -1;
08725    reg->refresh = IAX_DEFAULT_REG_EXPIRE;
08726    ast_sockaddr_set_port(&reg->addr, porta ? atoi(porta) : IAX_DEFAULT_PORTNO);
08727 
08728    AST_LIST_LOCK(&registrations);
08729    AST_LIST_INSERT_HEAD(&registrations, reg, entry);
08730    AST_LIST_UNLOCK(&registrations);
08731    
08732    return 0;
08733 }
08734 
08735 static int iax2_register(const char *value, int lineno)
08736 {
08737    char copy[256];
08738    char *username, *hostname, *secret;
08739    char *porta;
08740    char *stringp=NULL;
08741    
08742    if (!value)
08743       return -1;
08744 
08745    ast_copy_string(copy, value, sizeof(copy));
08746    stringp = copy;
08747    username = strsep(&stringp, "@");
08748    hostname = strsep(&stringp, "@");
08749 
08750    if (!hostname) {
08751       ast_log(LOG_WARNING, "Format for registration is user[:secret]@host[:port] at line %d\n", lineno);
08752       return -1;
08753    }
08754 
08755    stringp = username;
08756    username = strsep(&stringp, ":");
08757    secret = strsep(&stringp, ":");
08758    stringp = hostname;
08759    hostname = strsep(&stringp, ":");
08760    porta = strsep(&stringp, ":");
08761    
08762    if (porta && !atoi(porta)) {
08763       ast_log(LOG_WARNING, "%s is not a valid port number at line %d\n", porta, lineno);
08764       return -1;
08765    }
08766 
08767    return iax2_append_register(hostname, username, secret, porta);
08768 }
08769 
08770 
08771 static void register_peer_exten(struct iax2_peer *peer, int onoff)
08772 {
08773    char multi[256];
08774    char *stringp, *ext;
08775    if (!ast_strlen_zero(regcontext)) {
08776       ast_copy_string(multi, S_OR(peer->regexten, peer->name), sizeof(multi));
08777       stringp = multi;
08778       while((ext = strsep(&stringp, "&"))) {
08779          if (onoff) {
08780             if (!ast_exists_extension(NULL, regcontext, ext, 1, NULL))
08781                ast_add_extension(regcontext, 1, ext, 1, NULL, NULL,
08782                        "Noop", ast_strdup(peer->name), ast_free_ptr, "IAX2");
08783          } else
08784             ast_context_remove_extension(regcontext, ext, 1, NULL);
08785       }
08786    }
08787 }
08788 static void prune_peers(void);
08789 
08790 static void unlink_peer(struct iax2_peer *peer)
08791 {
08792    if (peer->expire > -1) {
08793       if (!AST_SCHED_DEL(sched, peer->expire)) {
08794          peer->expire = -1;
08795          peer_unref(peer);
08796       }
08797    }
08798 
08799    if (peer->pokeexpire > -1) {
08800       if (!AST_SCHED_DEL(sched, peer->pokeexpire)) {
08801          peer->pokeexpire = -1;
08802          peer_unref(peer);
08803       }
08804    }
08805 
08806    ao2_unlink(peers, peer);
08807 }
08808 
08809 static void __expire_registry(const void *data)
08810 {
08811    struct iax2_peer *peer = (struct iax2_peer *) data;
08812 
08813    if (!peer)
08814       return;
08815    if (peer->expire == -1) {
08816       /* Removed already (possibly through CLI), ignore */
08817       return;
08818    }
08819 
08820    peer->expire = -1;
08821 
08822    ast_debug(1, "Expiring registration for peer '%s'\n", peer->name);
08823    if (ast_test_flag64((&globalflags), IAX_RTUPDATE) && (ast_test_flag64(peer, IAX_TEMPONLY|IAX_RTCACHEFRIENDS)))
08824       realtime_update_peer(peer->name, &peer->addr, 0);
08825    manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: IAX2\r\nPeer: IAX2/%s\r\nPeerStatus: Unregistered\r\nCause: Expired\r\n", peer->name);
08826    /* modify entry in peercnts table as _not_ registered */
08827    peercnt_modify((unsigned char) 0, 0, &peer->addr);
08828    /* Reset the address */
08829    memset(&peer->addr, 0, sizeof(peer->addr));
08830    /* Reset expiry value */
08831    peer->expiry = min_reg_expire;
08832    if (!ast_test_flag64(peer, IAX_TEMPONLY))
08833       ast_db_del("IAX/Registry", peer->name);
08834    register_peer_exten(peer, 0);
08835    ast_devstate_changed(AST_DEVICE_UNAVAILABLE, AST_DEVSTATE_CACHABLE, "IAX2/%s", peer->name); /* Activate notification */
08836    if (iax2_regfunk)
08837       iax2_regfunk(peer->name, 0);
08838 
08839    if (ast_test_flag64(peer, IAX_RTAUTOCLEAR))
08840       unlink_peer(peer);
08841 
08842    peer_unref(peer);
08843 }
08844 
08845 static int expire_registry(const void *data)
08846 {
08847 #ifdef SCHED_MULTITHREADED
08848    if (schedule_action(__expire_registry, data))
08849 #endif      
08850       __expire_registry(data);
08851    return 0;
08852 }
08853 
08854 static void reg_source_db(struct iax2_peer *p)
08855 {
08856    char data[80];
08857    char *expiry;
08858 
08859    if (ast_test_flag64(p, IAX_TEMPONLY) || ast_db_get("IAX/Registry", p->name, data, sizeof(data))) {
08860       return;
08861    }
08862 
08863    expiry = strrchr(data, ':');
08864    if (!expiry) {
08865       ast_log(LOG_NOTICE, "IAX/Registry astdb entry missing expiry: '%s'\n", data);
08866       return;
08867    }
08868    *expiry++ = '\0';
08869 
08870    if (!ast_sockaddr_parse(&p->addr, data, PARSE_PORT_REQUIRE)) {
08871       ast_log(LOG_NOTICE, "IAX/Registry astdb host:port invalid - '%s'\n", data);
08872       return;
08873    }
08874 
08875    p->expiry = atoi(expiry);
08876 
08877    ast_verb(3, "Seeding '%s' at %s for %d\n", p->name,
08878       ast_sockaddr_stringify(&p->addr), p->expiry);
08879 
08880    iax2_poke_peer(p, 0);
08881    if (p->expire > -1) {
08882       if (!AST_SCHED_DEL(sched, p->expire)) {
08883          p->expire = -1;
08884          peer_unref(p);
08885       }
08886    }
08887 
08888    ast_devstate_changed(AST_DEVICE_UNKNOWN, AST_DEVSTATE_CACHABLE, "IAX2/%s", p->name); /* Activate notification */
08889 
08890    p->expire = iax2_sched_add(sched, (p->expiry + 10) * 1000, expire_registry, peer_ref(p));
08891    if (p->expire == -1) {
08892       peer_unref(p);
08893    }
08894 
08895    if (iax2_regfunk) {
08896       iax2_regfunk(p->name, 1);
08897    }
08898 
08899    register_peer_exten(p, 1);
08900 }
08901 
08902 /*!
08903  * \pre iaxsl[callno] is locked
08904  *
08905  * \note Since this function calls send_command_final(), the pvt struct for
08906  *       the given call number may disappear while executing this function.
08907  */
08908 static int update_registry(struct sockaddr_in *sin, int callno, char *devtype, int fd, unsigned short refresh)
08909 {
08910    /* Called from IAX thread only, with proper iaxsl lock */
08911    struct iax_ie_data ied = {
08912       .pos = 0,
08913    };
08914    struct iax2_peer *p;
08915    int msgcount;
08916    char data[80];
08917    int version;
08918    const char *peer_name;
08919    int res = -1;
08920    struct ast_sockaddr sockaddr;
08921 
08922    ast_sockaddr_from_sin(&sockaddr, sin);
08923 
08924    peer_name = ast_strdupa(iaxs[callno]->peer);
08925 
08926    /* SLD: Another find_peer call during registration - this time when we are really updating our registration */
08927    ast_mutex_unlock(&iaxsl[callno]);
08928    if (!(p = find_peer(peer_name, 1))) {
08929       ast_mutex_lock(&iaxsl[callno]);
08930       ast_log(LOG_WARNING, "No such peer '%s'\n", peer_name);
08931       return -1;
08932    }
08933    ast_mutex_lock(&iaxsl[callno]);
08934    if (!iaxs[callno])
08935       goto return_unref;
08936 
08937    if (ast_test_flag64((&globalflags), IAX_RTUPDATE) && (ast_test_flag64(p, IAX_TEMPONLY|IAX_RTCACHEFRIENDS))) {
08938       if (sin->sin_addr.s_addr) {
08939          time_t nowtime;
08940          time(&nowtime);
08941          realtime_update_peer(peer_name, &sockaddr, nowtime);
08942       } else {
08943          realtime_update_peer(peer_name, &sockaddr, 0);
08944       }
08945    }
08946 
08947    /* treat an unspecified refresh interval as the minimum */
08948    if (!refresh) {
08949       refresh = min_reg_expire;
08950    }
08951    if (refresh > max_reg_expire) {
08952       ast_log(LOG_NOTICE, "Restricting registration for peer '%s' to %d seconds (requested %d)\n",
08953          p->name, max_reg_expire, refresh);
08954       p->expiry = max_reg_expire;
08955    } else if (refresh < min_reg_expire) {
08956       ast_log(LOG_NOTICE, "Restricting registration for peer '%s' to %d seconds (requested %d)\n",
08957          p->name, min_reg_expire, refresh);
08958       p->expiry = min_reg_expire;
08959    } else {
08960       p->expiry = refresh;
08961    }
08962 
08963    if (ast_sockaddr_cmp(&p->addr, &sockaddr)) {
08964       if (iax2_regfunk) {
08965          iax2_regfunk(p->name, 1);
08966       }
08967 
08968       /* modify entry in peercnts table as _not_ registered */
08969       peercnt_modify((unsigned char) 0, 0, &p->addr);
08970 
08971       /* Stash the IP address from which they registered */
08972       ast_sockaddr_from_sin(&p->addr, sin);
08973 
08974       snprintf(data, sizeof(data), "%s:%d:%d", ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port), p->expiry);
08975       if (!ast_test_flag64(p, IAX_TEMPONLY) && sin->sin_addr.s_addr) {
08976          ast_db_put("IAX/Registry", p->name, data);
08977          ast_verb(3, "Registered IAX2 '%s' (%s) at %s:%d\n", p->name,
08978                    ast_test_flag(&iaxs[callno]->state, IAX_STATE_AUTHENTICATED) ? "AUTHENTICATED" : "UNAUTHENTICATED", ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
08979          manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: IAX2\r\nPeer: IAX2/%s\r\nPeerStatus: Registered\r\nAddress: %s\r\nPort: %d\r\n", p->name, ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
08980          register_peer_exten(p, 1);
08981          ast_devstate_changed(AST_DEVICE_UNKNOWN, AST_DEVSTATE_CACHABLE, "IAX2/%s", p->name); /* Activate notification */
08982       } else if (!ast_test_flag64(p, IAX_TEMPONLY)) {
08983          ast_verb(3, "Unregistered IAX2 '%s' (%s)\n", p->name,
08984                    ast_test_flag(&iaxs[callno]->state, IAX_STATE_AUTHENTICATED) ? "AUTHENTICATED" : "UNAUTHENTICATED");
08985          manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: IAX2\r\nPeer: IAX2/%s\r\nPeerStatus: Unregistered\r\n", p->name);
08986          register_peer_exten(p, 0);
08987          ast_db_del("IAX/Registry", p->name);
08988          ast_devstate_changed(AST_DEVICE_UNAVAILABLE, AST_DEVSTATE_CACHABLE, "IAX2/%s", p->name); /* Activate notification */
08989       }
08990       /* Update the host */
08991       /* Verify that the host is really there */
08992       iax2_poke_peer(p, callno);
08993    }
08994 
08995    /* modify entry in peercnts table as registered */
08996    if (p->maxcallno) {
08997       peercnt_modify((unsigned char) 1, p->maxcallno, &p->addr);
08998    }
08999 
09000    /* Make sure our call still exists, an INVAL at the right point may make it go away */
09001    if (!iaxs[callno]) {
09002       res = -1;
09003       goto return_unref;
09004    }
09005 
09006    /* Store socket fd */
09007    p->sockfd = fd;
09008    /* Setup the expiry */
09009    if (p->expire > -1) {
09010       if (!AST_SCHED_DEL(sched, p->expire)) {
09011          p->expire = -1;
09012          peer_unref(p);
09013       }
09014    }
09015 
09016    if (p->expiry && sin->sin_addr.s_addr) {
09017       p->expire = iax2_sched_add(sched, (p->expiry + 10) * 1000, expire_registry, peer_ref(p));
09018       if (p->expire == -1)
09019          peer_unref(p);
09020    }
09021    iax_ie_append_str(&ied, IAX_IE_USERNAME, p->name);
09022    iax_ie_append_int(&ied, IAX_IE_DATETIME, iax2_datetime(p->zonetag));
09023    if (sin->sin_addr.s_addr) {
09024       struct sockaddr_in peer_addr;
09025 
09026       ast_sockaddr_to_sin(&p->addr, &peer_addr);
09027 
09028       iax_ie_append_short(&ied, IAX_IE_REFRESH, p->expiry);
09029       iax_ie_append_addr(&ied, IAX_IE_APPARENT_ADDR, &peer_addr);
09030       if (!ast_strlen_zero(p->mailbox)) {
09031          struct ast_event *event;
09032          int new, old;
09033          char *mailbox, *context;
09034 
09035          context = mailbox = ast_strdupa(p->mailbox);
09036          strsep(&context, "@");
09037          if (ast_strlen_zero(context))
09038             context = "default";
09039 
09040          event = ast_event_get_cached(AST_EVENT_MWI,
09041             AST_EVENT_IE_MAILBOX, AST_EVENT_IE_PLTYPE_STR, mailbox,
09042             AST_EVENT_IE_CONTEXT, AST_EVENT_IE_PLTYPE_STR, context,
09043             AST_EVENT_IE_END);
09044          if (event) {
09045             new = ast_event_get_ie_uint(event, AST_EVENT_IE_NEWMSGS);
09046             old = ast_event_get_ie_uint(event, AST_EVENT_IE_OLDMSGS);
09047             ast_event_destroy(event);
09048          } else { /* Fall back on checking the mailbox directly */
09049             ast_app_inboxcount(p->mailbox, &new, &old);
09050          }
09051 
09052          if (new > 255) {
09053             new = 255;
09054          }
09055          if (old > 255) {
09056             old = 255;
09057          }
09058          msgcount = (old << 8) | new;
09059 
09060          iax_ie_append_short(&ied, IAX_IE_MSGCOUNT, msgcount);
09061       }
09062       if (ast_test_flag64(p, IAX_HASCALLERID)) {
09063          iax_ie_append_str(&ied, IAX_IE_CALLING_NUMBER, p->cid_num);
09064          iax_ie_append_str(&ied, IAX_IE_CALLING_NAME, p->cid_name);
09065       }
09066    }
09067    version = iax_check_version(devtype);
09068    if (version) 
09069       iax_ie_append_short(&ied, IAX_IE_FIRMWAREVER, version);
09070 
09071    res = 0;
09072 
09073 return_unref:
09074    peer_unref(p);
09075 
09076    return res ? res : send_command_final(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_REGACK, 0, ied.buf, ied.pos, -1);
09077 }
09078 
09079 static int registry_authrequest(int callno)
09080 {
09081    struct iax_ie_data ied;
09082    struct iax2_peer *p;
09083    char challenge[10];
09084    const char *peer_name;
09085    int sentauthmethod;
09086 
09087    peer_name = ast_strdupa(iaxs[callno]->peer);
09088 
09089    /* SLD: third call to find_peer in registration */
09090    ast_mutex_unlock(&iaxsl[callno]);
09091    if ((p = find_peer(peer_name, 1))) {
09092       last_authmethod = p->authmethods;
09093    }
09094 
09095    ast_mutex_lock(&iaxsl[callno]);
09096    if (!iaxs[callno])
09097       goto return_unref;
09098 
09099    memset(&ied, 0, sizeof(ied));
09100    /* The selection of which delayed reject is sent may leak information,
09101     * if it sets a static response.  For example, if a host is known to only
09102     * use MD5 authentication, then an RSA response would indicate that the
09103     * peer does not exist, and vice-versa.
09104     * Therefore, we use whatever the last peer used (which may vary over the
09105     * course of a server, which should leak minimal information). */
09106    sentauthmethod = p ? p->authmethods : last_authmethod ? last_authmethod : (IAX_AUTH_MD5 | IAX_AUTH_PLAINTEXT);
09107    if (!p) {
09108       iaxs[callno]->authmethods = sentauthmethod;
09109    }
09110    iax_ie_append_short(&ied, IAX_IE_AUTHMETHODS, sentauthmethod);
09111    if (sentauthmethod & (IAX_AUTH_RSA | IAX_AUTH_MD5)) {
09112       /* Build the challenge */
09113       snprintf(challenge, sizeof(challenge), "%d", (int)ast_random());
09114       ast_string_field_set(iaxs[callno], challenge, challenge);
09115       iax_ie_append_str(&ied, IAX_IE_CHALLENGE, iaxs[callno]->challenge);
09116    }
09117    iax_ie_append_str(&ied, IAX_IE_USERNAME, peer_name);
09118 
09119 return_unref:
09120    if (p) {
09121       peer_unref(p);
09122    }
09123 
09124    return iaxs[callno] ? send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_REGAUTH, 0, ied.buf, ied.pos, -1) : -1;
09125 }
09126 
09127 static int registry_rerequest(struct iax_ies *ies, int callno, struct sockaddr_in *sin)
09128 {
09129    struct iax2_registry *reg;
09130    /* Start pessimistic */
09131    struct iax_ie_data ied;
09132    char peer[256] = "";
09133    char challenge[256] = "";
09134    int res;
09135    int authmethods = 0;
09136    if (ies->authmethods)
09137       authmethods = ies->authmethods;
09138    if (ies->username)
09139       ast_copy_string(peer, ies->username, sizeof(peer));
09140    if (ies->challenge)
09141       ast_copy_string(challenge, ies->challenge, sizeof(challenge));
09142    memset(&ied, 0, sizeof(ied));
09143    reg = iaxs[callno]->reg;
09144    if (reg) {
09145       struct sockaddr_in reg_addr;
09146 
09147       ast_sockaddr_to_sin(&reg->addr, &reg_addr);
09148 
09149       if (inaddrcmp(&reg_addr, sin)) {
09150          ast_log(LOG_WARNING, "Received unsolicited registry authenticate request from '%s'\n", ast_inet_ntoa(sin->sin_addr));
09151          return -1;
09152       }
09153       if (ast_strlen_zero(reg->secret)) {
09154          ast_log(LOG_NOTICE, "No secret associated with peer '%s'\n", reg->username);
09155          reg->regstate = REG_STATE_NOAUTH;
09156          return -1;
09157       }
09158       iax_ie_append_str(&ied, IAX_IE_USERNAME, reg->username);
09159       iax_ie_append_short(&ied, IAX_IE_REFRESH, reg->refresh);
09160       if (reg->secret[0] == '[') {
09161          char tmpkey[256];
09162          ast_copy_string(tmpkey, reg->secret + 1, sizeof(tmpkey));
09163          tmpkey[strlen(tmpkey) - 1] = '\0';
09164          res = authenticate(challenge, NULL, tmpkey, authmethods, &ied, sin, NULL);
09165       } else
09166          res = authenticate(challenge, reg->secret, NULL, authmethods, &ied, sin, NULL);
09167       if (!res) {
09168          reg->regstate = REG_STATE_AUTHSENT;
09169          add_empty_calltoken_ie(iaxs[callno], &ied); /* this _MUST_ be the last ie added */
09170          return send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_REGREQ, 0, ied.buf, ied.pos, -1);
09171       } else
09172          return -1;
09173       ast_log(LOG_WARNING, "Registry acknowledge on unknown registery '%s'\n", peer);
09174    } else   
09175       ast_log(LOG_NOTICE, "Can't reregister without a reg\n");
09176    return -1;
09177 }
09178 
09179 static void stop_stuff(int callno)
09180 {
09181    iax2_destroy_helper(iaxs[callno]);
09182 }
09183 
09184 static void __auth_reject(const void *nothing)
09185 {
09186    /* Called from IAX thread only, without iaxs lock */
09187    int callno = (int)(long)(nothing);
09188    struct iax_ie_data ied;
09189    ast_mutex_lock(&iaxsl[callno]);
09190    if (iaxs[callno]) {
09191       memset(&ied, 0, sizeof(ied));
09192       if (iaxs[callno]->authfail == IAX_COMMAND_REGREJ) {
09193          iax_ie_append_str(&ied, IAX_IE_CAUSE, "Registration Refused");
09194          iax_ie_append_byte(&ied, IAX_IE_CAUSECODE, AST_CAUSE_FACILITY_REJECTED);
09195       } else if (iaxs[callno]->authfail == IAX_COMMAND_REJECT) {
09196          iax_ie_append_str(&ied, IAX_IE_CAUSE, "No authority found");
09197          iax_ie_append_byte(&ied, IAX_IE_CAUSECODE, AST_CAUSE_FACILITY_NOT_SUBSCRIBED);
09198       }
09199       send_command_final(iaxs[callno], AST_FRAME_IAX, iaxs[callno]->authfail, 0, ied.buf, ied.pos, -1);
09200    }
09201    ast_mutex_unlock(&iaxsl[callno]);
09202 }
09203 
09204 static int auth_reject(const void *data)
09205 {
09206    int callno = (int)(long)(data);
09207    ast_mutex_lock(&iaxsl[callno]);
09208    if (iaxs[callno])
09209       iaxs[callno]->authid = -1;
09210    ast_mutex_unlock(&iaxsl[callno]);
09211 #ifdef SCHED_MULTITHREADED
09212    if (schedule_action(__auth_reject, data))
09213 #endif      
09214       __auth_reject(data);
09215    return 0;
09216 }
09217 
09218 static int auth_fail(int callno, int failcode)
09219 {
09220    /* Schedule sending the authentication failure in one second, to prevent
09221       guessing */
09222    if (iaxs[callno]) {
09223       iaxs[callno]->authfail = failcode;
09224       if (delayreject) {
09225          iaxs[callno]->authid = iax2_sched_replace(iaxs[callno]->authid, 
09226             sched, 1000, auth_reject, (void *)(long)callno);
09227       } else
09228          auth_reject((void *)(long)callno);
09229    }
09230    return 0;
09231 }
09232 
09233 static void __auto_hangup(const void *nothing)
09234 {
09235    /* Called from IAX thread only, without iaxs lock */
09236    int callno = (int)(long)(nothing);
09237    struct iax_ie_data ied;
09238    ast_mutex_lock(&iaxsl[callno]);
09239    if (iaxs[callno]) {
09240       memset(&ied, 0, sizeof(ied));
09241       iax_ie_append_str(&ied, IAX_IE_CAUSE, "Timeout");
09242       iax_ie_append_byte(&ied, IAX_IE_CAUSECODE, AST_CAUSE_NO_USER_RESPONSE);
09243       send_command_final(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_HANGUP, 0, ied.buf, ied.pos, -1);
09244    }
09245    ast_mutex_unlock(&iaxsl[callno]);
09246 }
09247 
09248 static int auto_hangup(const void *data)
09249 {
09250    int callno = (int)(long)(data);
09251    ast_mutex_lock(&iaxsl[callno]);
09252    if (iaxs[callno]) {
09253       iaxs[callno]->autoid = -1;
09254    }
09255    ast_mutex_unlock(&iaxsl[callno]);
09256 #ifdef SCHED_MULTITHREADED
09257    if (schedule_action(__auto_hangup, data))
09258 #endif      
09259       __auto_hangup(data);
09260    return 0;
09261 }
09262 
09263 static void iax2_dprequest(struct iax2_dpcache *dp, int callno)
09264 {
09265    struct iax_ie_data ied;
09266    /* Auto-hangup with 30 seconds of inactivity */
09267    iaxs[callno]->autoid = iax2_sched_replace(iaxs[callno]->autoid, 
09268       sched, 30000, auto_hangup, (void *)(long)callno);
09269    memset(&ied, 0, sizeof(ied));
09270    iax_ie_append_str(&ied, IAX_IE_CALLED_NUMBER, dp->exten);
09271    send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_DPREQ, 0, ied.buf, ied.pos, -1);
09272    dp->flags |= CACHE_FLAG_TRANSMITTED;
09273 }
09274 
09275 static int iax2_vnak(int callno)
09276 {
09277    return send_command_immediate(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_VNAK, 0, NULL, 0, iaxs[callno]->iseqno);
09278 }
09279 
09280 static void vnak_retransmit(int callno, int last)
09281 {
09282    struct iax_frame *f;
09283 
09284    AST_LIST_TRAVERSE(&frame_queue[callno], f, list) {
09285       /* Send a copy immediately */
09286       if (((unsigned char) (f->oseqno - last) < 128) &&
09287             (f->retries >= 0)) {
09288          send_packet(f);
09289       }
09290    }
09291 }
09292 
09293 static void __iax2_poke_peer_s(const void *data)
09294 {
09295    struct iax2_peer *peer = (struct iax2_peer *)data;
09296    iax2_poke_peer(peer, 0);
09297    peer_unref(peer);
09298 }
09299 
09300 static int iax2_poke_peer_s(const void *data)
09301 {
09302    struct iax2_peer *peer = (struct iax2_peer *)data;
09303    peer->pokeexpire = -1;
09304 #ifdef SCHED_MULTITHREADED
09305    if (schedule_action(__iax2_poke_peer_s, data))
09306 #endif      
09307       __iax2_poke_peer_s(data);
09308    return 0;
09309 }
09310 
09311 static int send_trunk(struct iax2_trunk_peer *tpeer, struct timeval *now)
09312 {
09313    int res = 0;
09314    struct iax_frame *fr;
09315    struct ast_iax2_meta_hdr *meta;
09316    struct ast_iax2_meta_trunk_hdr *mth;
09317    int calls = 0;
09318    
09319    /* Point to frame */
09320    fr = (struct iax_frame *)tpeer->trunkdata;
09321    /* Point to meta data */
09322    meta = (struct ast_iax2_meta_hdr *)fr->afdata;
09323    mth = (struct ast_iax2_meta_trunk_hdr *)meta->data;
09324    if (tpeer->trunkdatalen) {
09325       /* We're actually sending a frame, so fill the meta trunk header and meta header */
09326       meta->zeros = 0;
09327       meta->metacmd = IAX_META_TRUNK;
09328       if (ast_test_flag64(&globalflags, IAX_TRUNKTIMESTAMPS))
09329          meta->cmddata = IAX_META_TRUNK_MINI;
09330       else
09331          meta->cmddata = IAX_META_TRUNK_SUPERMINI;
09332       mth->ts = htonl(calc_txpeerstamp(tpeer, trunkfreq, now));
09333       /* And the rest of the ast_iax2 header */
09334       fr->direction = DIRECTION_OUTGRESS;
09335       fr->retrans = -1;
09336       fr->transfer = 0;
09337       /* Any appropriate call will do */
09338       fr->data = fr->afdata;
09339       fr->datalen = tpeer->trunkdatalen + sizeof(struct ast_iax2_meta_hdr) + sizeof(struct ast_iax2_meta_trunk_hdr);
09340       res = transmit_trunk(fr, &tpeer->addr, tpeer->sockfd);
09341       calls = tpeer->calls;
09342 #if 0
09343       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));
09344 #endif
09345       /* Reset transmit trunk side data */
09346       tpeer->trunkdatalen = 0;
09347       tpeer->calls = 0;
09348    }
09349    if (res < 0)
09350       return res;
09351    return calls;
09352 }
09353 
09354 static inline int iax2_trunk_expired(struct iax2_trunk_peer *tpeer, struct timeval *now)
09355 {
09356    /* Drop when trunk is about 5 seconds idle */
09357    if (now->tv_sec > tpeer->trunkact.tv_sec + 5) 
09358       return 1;
09359    return 0;
09360 }
09361 
09362 static int timing_read(int *id, int fd, short events, void *cbdata)
09363 {
09364    int res, processed = 0, totalcalls = 0;
09365    struct iax2_trunk_peer *tpeer = NULL, *drop = NULL;
09366    struct timeval now = ast_tvnow();
09367 
09368    if (iaxtrunkdebug)
09369       ast_verbose("Beginning trunk processing. Trunk queue ceiling is %d bytes per host\n", trunkmaxsize);
09370 
09371    if (timer) {
09372       if (ast_timer_ack(timer, 1) < 0) {
09373          ast_log(LOG_ERROR, "Timer failed acknowledge\n");
09374          return 0;
09375       }
09376    }
09377 
09378    /* For each peer that supports trunking... */
09379    AST_LIST_LOCK(&tpeers);
09380    AST_LIST_TRAVERSE_SAFE_BEGIN(&tpeers, tpeer, list) {
09381       processed++;
09382       res = 0;
09383       ast_mutex_lock(&tpeer->lock);
09384       /* We can drop a single tpeer per pass.  That makes all this logic
09385          substantially easier */
09386       if (!drop && iax2_trunk_expired(tpeer, &now)) {
09387          /* Take it out of the list, but don't free it yet, because it
09388             could be in use */
09389          AST_LIST_REMOVE_CURRENT(list);
09390          drop = tpeer;
09391       } else {
09392          res = send_trunk(tpeer, &now);
09393          trunk_timed++;
09394          if (iaxtrunkdebug)
09395             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);
09396       }
09397       totalcalls += res;
09398       res = 0;
09399       ast_mutex_unlock(&tpeer->lock);
09400    }
09401    AST_LIST_TRAVERSE_SAFE_END;
09402    AST_LIST_UNLOCK(&tpeers);
09403 
09404    if (drop) {
09405       ast_mutex_lock(&drop->lock);
09406       /* Once we have this lock, we're sure nobody else is using it or could use it once we release it, 
09407          because by the time they could get tpeerlock, we've already grabbed it */
09408       ast_debug(1, "Dropping unused iax2 trunk peer '%s:%d'\n", ast_inet_ntoa(drop->addr.sin_addr), ntohs(drop->addr.sin_port));
09409       if (drop->trunkdata) {
09410          ast_free(drop->trunkdata);
09411          drop->trunkdata = NULL;
09412       }
09413       ast_mutex_unlock(&drop->lock);
09414       ast_mutex_destroy(&drop->lock);
09415       ast_free(drop);
09416    }
09417 
09418    if (iaxtrunkdebug)
09419       ast_verbose("Ending trunk processing with %d peers and %d call chunks processed\n", processed, totalcalls);
09420    iaxtrunkdebug = 0;
09421 
09422    return 1;
09423 }
09424 
09425 struct dpreq_data {
09426    int callno;
09427    char context[AST_MAX_EXTENSION];
09428    char callednum[AST_MAX_EXTENSION];
09429    char *callerid;
09430 };
09431 
09432 static void dp_lookup(int callno, const char *context, const char *callednum, const char *callerid, int skiplock)
09433 {
09434    unsigned short dpstatus = 0;
09435    struct iax_ie_data ied1;
09436    int mm;
09437 
09438    memset(&ied1, 0, sizeof(ied1));
09439    mm = ast_matchmore_extension(NULL, context, callednum, 1, callerid);
09440    /* Must be started */
09441    if (ast_parking_ext_valid(callednum, NULL, context) || ast_exists_extension(NULL, context, callednum, 1, callerid)) {
09442       dpstatus = IAX_DPSTATUS_EXISTS;
09443    } else if (ast_canmatch_extension(NULL, context, callednum, 1, callerid)) {
09444       dpstatus = IAX_DPSTATUS_CANEXIST;
09445    } else {
09446       dpstatus = IAX_DPSTATUS_NONEXISTENT;
09447    }
09448    if (ast_ignore_pattern(context, callednum))
09449       dpstatus |= IAX_DPSTATUS_IGNOREPAT;
09450    if (mm)
09451       dpstatus |= IAX_DPSTATUS_MATCHMORE;
09452    if (!skiplock)
09453       ast_mutex_lock(&iaxsl[callno]);
09454    if (iaxs[callno]) {
09455       iax_ie_append_str(&ied1, IAX_IE_CALLED_NUMBER, callednum);
09456       iax_ie_append_short(&ied1, IAX_IE_DPSTATUS, dpstatus);
09457       iax_ie_append_short(&ied1, IAX_IE_REFRESH, iaxdefaultdpcache);
09458       send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_DPREP, 0, ied1.buf, ied1.pos, -1);
09459    }
09460    if (!skiplock)
09461       ast_mutex_unlock(&iaxsl[callno]);
09462 }
09463 
09464 static void *dp_lookup_thread(void *data)
09465 {
09466    /* Look up for dpreq */
09467    struct dpreq_data *dpr = data;
09468    dp_lookup(dpr->callno, dpr->context, dpr->callednum, dpr->callerid, 0);
09469    if (dpr->callerid)
09470       ast_free(dpr->callerid);
09471    ast_free(dpr);
09472    return NULL;
09473 }
09474 
09475 static void spawn_dp_lookup(int callno, const char *context, const char *callednum, const char *callerid)
09476 {
09477    pthread_t newthread;
09478    struct dpreq_data *dpr;
09479    
09480    if (!(dpr = ast_calloc(1, sizeof(*dpr))))
09481       return;
09482 
09483    dpr->callno = callno;
09484    ast_copy_string(dpr->context, context, sizeof(dpr->context));
09485    ast_copy_string(dpr->callednum, callednum, sizeof(dpr->callednum));
09486    if (callerid)
09487       dpr->callerid = ast_strdup(callerid);
09488    if (ast_pthread_create_detached(&newthread, NULL, dp_lookup_thread, dpr)) {
09489       ast_log(LOG_WARNING, "Unable to start lookup thread!\n");
09490    }
09491 }
09492 
09493 struct iax_dual {
09494    struct ast_channel *chan1;
09495    struct ast_channel *chan2;
09496    char *park_exten;
09497    char *park_context;
09498 };
09499 
09500 static void *iax_park_thread(void *stuff)
09501 {
09502    struct iax_dual *d;
09503    int res;
09504    int ext = 0;
09505 
09506    d = stuff;
09507 
09508    ast_debug(4, "IAX Park: Transferer channel %s, Transferee %s\n",
09509       ast_channel_name(d->chan2), ast_channel_name(d->chan1));
09510 
09511    res = ast_park_call_exten(d->chan1, d->chan2, d->park_exten, d->park_context, 0, &ext);
09512    if (res) {
09513       /* Parking failed. */
09514       ast_hangup(d->chan1);
09515    } else {
09516       ast_log(LOG_NOTICE, "Parked on extension '%d'\n", ext);
09517    }
09518    ast_hangup(d->chan2);
09519 
09520    ast_free(d->park_exten);
09521    ast_free(d->park_context);
09522    ast_free(d);
09523    return NULL;
09524 }
09525 
09526 /*! DO NOT hold any locks while calling iax_park */
09527 static int iax_park(struct ast_channel *chan1, struct ast_channel *chan2, const char *park_exten, const char *park_context)
09528 {
09529    struct iax_dual *d;
09530    struct ast_channel *chan1m, *chan2m;/* Chan2m: The transferer, chan1m: The transferee */
09531    pthread_t th;
09532 
09533    chan1m = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, ast_channel_accountcode(chan2), ast_channel_exten(chan1), ast_channel_context(chan1), ast_channel_linkedid(chan1), ast_channel_amaflags(chan1), "Parking/%s", ast_channel_name(chan1));
09534    chan2m = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, ast_channel_accountcode(chan2), ast_channel_exten(chan2), ast_channel_context(chan2), ast_channel_linkedid(chan2), ast_channel_amaflags(chan2), "IAXPeer/%s", ast_channel_name(chan2));
09535    d = ast_calloc(1, sizeof(*d));
09536    if (!chan1m || !chan2m || !d) {
09537       if (chan1m) {
09538          ast_hangup(chan1m);
09539       }
09540       if (chan2m) {
09541          ast_hangup(chan2m);
09542       }
09543       ast_free(d);
09544       return -1;
09545    }
09546    d->park_exten = ast_strdup(park_exten);
09547    d->park_context = ast_strdup(park_context);
09548    if (!d->park_exten || !d->park_context) {
09549       ast_hangup(chan1m);
09550       ast_hangup(chan2m);
09551       ast_free(d->park_exten);
09552       ast_free(d->park_context);
09553       ast_free(d);
09554       return -1;
09555    }
09556 
09557    /* Make formats okay */
09558    ast_format_copy(ast_channel_readformat(chan1m), ast_channel_readformat(chan1));
09559    ast_format_copy(ast_channel_writeformat(chan1m), ast_channel_writeformat(chan1));
09560 
09561    /* Prepare for taking over the channel */
09562    if (ast_channel_masquerade(chan1m, chan1)) {
09563       ast_hangup(chan1m);
09564       ast_hangup(chan2m);
09565       ast_free(d->park_exten);
09566       ast_free(d->park_context);
09567       ast_free(d);
09568       return -1;
09569    }
09570 
09571    /* Setup the extensions and such */
09572    ast_channel_context_set(chan1m, ast_channel_context(chan1));
09573    ast_channel_exten_set(chan1m, ast_channel_exten(chan1));
09574    ast_channel_priority_set(chan1m, ast_channel_priority(chan1));
09575 
09576    ast_do_masquerade(chan1m);
09577 
09578    /* We make a clone of the peer channel too, so we can play
09579       back the announcement */
09580 
09581    /* Make formats okay */
09582    ast_format_copy(ast_channel_readformat(chan2m), ast_channel_readformat(chan2));
09583    ast_format_copy(ast_channel_writeformat(chan2m), ast_channel_writeformat(chan2));
09584    ast_channel_parkinglot_set(chan2m, ast_channel_parkinglot(chan2));
09585 
09586    /* Prepare for taking over the channel */
09587    if (ast_channel_masquerade(chan2m, chan2)) {
09588       ast_hangup(chan1m);
09589       ast_hangup(chan2m);
09590       ast_free(d->park_exten);
09591       ast_free(d->park_context);
09592       ast_free(d);
09593       return -1;
09594    }
09595 
09596    /* Setup the extensions and such */
09597    ast_channel_context_set(chan2m, ast_channel_context(chan2));
09598    ast_channel_exten_set(chan2m, ast_channel_exten(chan2));
09599    ast_channel_priority_set(chan2m, ast_channel_priority(chan2));
09600 
09601    ast_do_masquerade(chan2m);
09602 
09603    d->chan1 = chan1m;   /* Transferee */
09604    d->chan2 = chan2m;   /* Transferer */
09605    if (ast_pthread_create_detached_background(&th, NULL, iax_park_thread, d) < 0) {
09606       /* Could not start thread */
09607       ast_hangup(chan1m);
09608       ast_hangup(chan2m);
09609       ast_free(d->park_exten);
09610       ast_free(d->park_context);
09611       ast_free(d);
09612       return -1;
09613    }
09614    return 0;
09615 }
09616 
09617 static int check_provisioning(struct sockaddr_in *sin, int sockfd, char *si, unsigned int ver)
09618 {
09619    unsigned int ourver;
09620    char rsi[80];
09621    snprintf(rsi, sizeof(rsi), "si-%s", si);
09622    if (iax_provision_version(&ourver, rsi, 1))
09623       return 0;
09624    ast_debug(1, "Service identifier '%s', we think '%08x', they think '%08x'\n", si, ourver, ver);
09625    if (ourver != ver)
09626       iax2_provision(sin, sockfd, NULL, rsi, 1);
09627    return 0;
09628 }
09629 
09630 static void construct_rr(struct chan_iax2_pvt *pvt, struct iax_ie_data *iep)
09631 {
09632    jb_info stats;
09633    jb_getinfo(pvt->jb, &stats);
09634 
09635    memset(iep, 0, sizeof(*iep));
09636 
09637    iax_ie_append_int(iep,IAX_IE_RR_JITTER, stats.jitter);
09638    if(stats.frames_in == 0) stats.frames_in = 1;
09639    iax_ie_append_int(iep,IAX_IE_RR_LOSS, ((0xff & (stats.losspct/1000)) << 24 | (stats.frames_lost & 0x00ffffff)));
09640    iax_ie_append_int(iep,IAX_IE_RR_PKTS, stats.frames_in);
09641    iax_ie_append_short(iep,IAX_IE_RR_DELAY, stats.current - stats.min);
09642    iax_ie_append_int(iep,IAX_IE_RR_DROPPED, stats.frames_dropped);
09643    iax_ie_append_int(iep,IAX_IE_RR_OOO, stats.frames_ooo);
09644 }
09645 
09646 static void save_rr(struct iax_frame *fr, struct iax_ies *ies) 
09647 {
09648    iaxs[fr->callno]->remote_rr.jitter = ies->rr_jitter;
09649    iaxs[fr->callno]->remote_rr.losspct = ies->rr_loss >> 24;
09650    iaxs[fr->callno]->remote_rr.losscnt = ies->rr_loss & 0xffffff;
09651    iaxs[fr->callno]->remote_rr.packets = ies->rr_pkts;
09652    iaxs[fr->callno]->remote_rr.delay = ies->rr_delay;
09653    iaxs[fr->callno]->remote_rr.dropped = ies->rr_dropped;
09654    iaxs[fr->callno]->remote_rr.ooo = ies->rr_ooo;
09655 }
09656 
09657 static void save_osptoken(struct iax_frame *fr, struct iax_ies *ies) 
09658 {
09659    int i;
09660    unsigned int length, offset = 0;
09661    char full_osptoken[IAX_MAX_OSPBUFF_SIZE];
09662 
09663    for (i = 0; i < IAX_MAX_OSPBLOCK_NUM; i++) {
09664       length = ies->ospblocklength[i];
09665       if (length != 0) {
09666          if (length > IAX_MAX_OSPBLOCK_SIZE) {
09667             /* OSP token block length wrong, clear buffer */
09668             offset = 0;
09669             break;
09670          } else {
09671             memcpy(full_osptoken + offset, ies->osptokenblock[i], length);
09672             offset += length;
09673          }
09674       } else {
09675          break;
09676       }
09677    }
09678    *(full_osptoken + offset) = '\0';
09679    if (strlen(full_osptoken) != offset) {
09680       /* OSP token length wrong, clear buffer */
09681       *full_osptoken = '\0';
09682    }
09683 
09684    ast_string_field_set(iaxs[fr->callno], osptoken, full_osptoken);
09685 }
09686 
09687 static void log_jitterstats(unsigned short callno)
09688 {
09689    int localjitter = -1, localdelay = 0, locallost = -1, locallosspct = -1, localdropped = 0, localooo = -1, localpackets = -1;
09690    jb_info jbinfo;
09691 
09692    ast_mutex_lock(&iaxsl[callno]);
09693    if (iaxs[callno] && iaxs[callno]->owner && ast_channel_name(iaxs[callno]->owner)) {
09694       if(ast_test_flag64(iaxs[callno], IAX_USEJITTERBUF)) {
09695          jb_getinfo(iaxs[callno]->jb, &jbinfo);
09696          localjitter = jbinfo.jitter;
09697          localdelay = jbinfo.current - jbinfo.min;
09698          locallost = jbinfo.frames_lost;
09699          locallosspct = jbinfo.losspct/1000;
09700          localdropped = jbinfo.frames_dropped;
09701          localooo = jbinfo.frames_ooo;
09702          localpackets = jbinfo.frames_in;
09703       }
09704       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",
09705          ast_channel_name(iaxs[callno]->owner),
09706          iaxs[callno]->pingtime,
09707          localjitter,
09708          localdelay,
09709          locallost,
09710          locallosspct,
09711          localdropped,
09712          localooo,
09713          localpackets,
09714          iaxs[callno]->remote_rr.jitter,
09715          iaxs[callno]->remote_rr.delay,
09716          iaxs[callno]->remote_rr.losscnt,
09717          iaxs[callno]->remote_rr.losspct/1000,
09718          iaxs[callno]->remote_rr.dropped,
09719          iaxs[callno]->remote_rr.ooo,
09720          iaxs[callno]->remote_rr.packets);
09721       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",
09722          ast_channel_name(iaxs[callno]->owner),
09723          iaxs[callno]->pingtime,
09724          localjitter,
09725          localdelay,
09726          locallost,
09727          locallosspct,
09728          localdropped,
09729          localooo,
09730          localpackets,
09731          iaxs[callno]->remote_rr.jitter,
09732          iaxs[callno]->remote_rr.delay,
09733          iaxs[callno]->remote_rr.losscnt,
09734          iaxs[callno]->remote_rr.losspct/1000,
09735          iaxs[callno]->remote_rr.dropped,
09736          iaxs[callno]->remote_rr.ooo,
09737          iaxs[callno]->remote_rr.packets);
09738    }
09739    ast_mutex_unlock(&iaxsl[callno]);
09740 }
09741 
09742 static int socket_process(struct iax2_thread *thread);
09743 
09744 /*!
09745  * \brief Handle any deferred full frames for this thread
09746  */
09747 static void handle_deferred_full_frames(struct iax2_thread *thread)
09748 {
09749    struct iax2_pkt_buf *pkt_buf;
09750 
09751    ast_mutex_lock(&thread->lock);
09752 
09753    while ((pkt_buf = AST_LIST_REMOVE_HEAD(&thread->full_frames, entry))) {
09754       ast_mutex_unlock(&thread->lock);
09755 
09756       thread->buf = pkt_buf->buf;
09757       thread->buf_len = pkt_buf->len;
09758       thread->buf_size = pkt_buf->len + 1;
09759       
09760       socket_process(thread);
09761 
09762       thread->buf = NULL;
09763       ast_free(pkt_buf);
09764 
09765       ast_mutex_lock(&thread->lock);
09766    }
09767 
09768    ast_mutex_unlock(&thread->lock);
09769 }
09770 
09771 /*!
09772  * \brief Queue the last read full frame for processing by a certain thread
09773  *
09774  * If there are already any full frames queued, they are sorted
09775  * by sequence number.
09776  */
09777 static void defer_full_frame(struct iax2_thread *from_here, struct iax2_thread *to_here)
09778 {
09779    struct iax2_pkt_buf *pkt_buf, *cur_pkt_buf;
09780    struct ast_iax2_full_hdr *fh, *cur_fh;
09781 
09782    if (!(pkt_buf = ast_calloc(1, sizeof(*pkt_buf) + from_here->buf_len)))
09783       return;
09784 
09785    pkt_buf->len = from_here->buf_len;
09786    memcpy(pkt_buf->buf, from_here->buf, pkt_buf->len);
09787 
09788    fh = (struct ast_iax2_full_hdr *) pkt_buf->buf;
09789    ast_mutex_lock(&to_here->lock);
09790    AST_LIST_TRAVERSE_SAFE_BEGIN(&to_here->full_frames, cur_pkt_buf, entry) {
09791       cur_fh = (struct ast_iax2_full_hdr *) cur_pkt_buf->buf;
09792       if (fh->oseqno < cur_fh->oseqno) {
09793          AST_LIST_INSERT_BEFORE_CURRENT(pkt_buf, entry);
09794          break;
09795       }
09796    }
09797    AST_LIST_TRAVERSE_SAFE_END
09798 
09799    if (!cur_pkt_buf)
09800       AST_LIST_INSERT_TAIL(&to_here->full_frames, pkt_buf, entry);
09801 
09802    to_here->iostate = IAX_IOSTATE_READY;
09803    ast_cond_signal(&to_here->cond);
09804 
09805    ast_mutex_unlock(&to_here->lock);
09806 }
09807 
09808 static int socket_read(int *id, int fd, short events, void *cbdata)
09809 {
09810    struct iax2_thread *thread;
09811    socklen_t len;
09812    time_t t;
09813    static time_t last_errtime = 0;
09814    struct ast_iax2_full_hdr *fh;
09815 
09816    if (!(thread = find_idle_thread())) {
09817       time(&t);
09818       if (t != last_errtime) {
09819          last_errtime = t;
09820          ast_debug(1, "Out of idle IAX2 threads for I/O, pausing!\n");
09821       }
09822       usleep(1);
09823       return 1;
09824    }
09825 
09826    len = sizeof(thread->iosin);
09827    thread->iofd = fd;
09828    thread->buf_len = recvfrom(fd, thread->readbuf, sizeof(thread->readbuf), 0, (struct sockaddr *) &thread->iosin, &len);
09829    thread->buf_size = sizeof(thread->readbuf);
09830    thread->buf = thread->readbuf;
09831    if (thread->buf_len < 0) {
09832       if (errno != ECONNREFUSED && errno != EAGAIN)
09833          ast_log(LOG_WARNING, "Error: %s\n", strerror(errno));
09834       handle_error();
09835       thread->iostate = IAX_IOSTATE_IDLE;
09836       signal_condition(&thread->lock, &thread->cond);
09837       return 1;
09838    }
09839    if (test_losspct && ((100.0 * ast_random() / (RAND_MAX + 1.0)) < test_losspct)) { /* simulate random loss condition */
09840       thread->iostate = IAX_IOSTATE_IDLE;
09841       signal_condition(&thread->lock, &thread->cond);
09842       return 1;
09843    }
09844    
09845    /* Determine if this frame is a full frame; if so, and any thread is currently
09846       processing a full frame for the same callno from this peer, then drop this
09847       frame (and the peer will retransmit it) */
09848    fh = (struct ast_iax2_full_hdr *) thread->buf;
09849    if (ntohs(fh->scallno) & IAX_FLAG_FULL) {
09850       struct iax2_thread *cur = NULL;
09851       uint16_t callno = ntohs(fh->scallno) & ~IAX_FLAG_FULL;
09852       
09853       AST_LIST_LOCK(&active_list);
09854       AST_LIST_TRAVERSE(&active_list, cur, list) {
09855          if ((cur->ffinfo.callno == callno) &&
09856              !inaddrcmp(&cur->ffinfo.sin, &thread->iosin))
09857             break;
09858       }
09859       if (cur) {
09860          /* we found another thread processing a full frame for this call,
09861             so queue it up for processing later. */
09862          defer_full_frame(thread, cur);
09863          AST_LIST_UNLOCK(&active_list);
09864          thread->iostate = IAX_IOSTATE_IDLE;
09865          signal_condition(&thread->lock, &thread->cond);
09866          return 1;
09867       } else {
09868          /* this thread is going to process this frame, so mark it */
09869          thread->ffinfo.callno = callno;
09870          memcpy(&thread->ffinfo.sin, &thread->iosin, sizeof(thread->ffinfo.sin));
09871          thread->ffinfo.type = fh->type;
09872          thread->ffinfo.csub = fh->csub;
09873          AST_LIST_INSERT_HEAD(&active_list, thread, list);
09874       }
09875       AST_LIST_UNLOCK(&active_list);
09876    }
09877    
09878    /* Mark as ready and send on its way */
09879    thread->iostate = IAX_IOSTATE_READY;
09880 #ifdef DEBUG_SCHED_MULTITHREAD
09881    ast_copy_string(thread->curfunc, "socket_process", sizeof(thread->curfunc));
09882 #endif
09883    signal_condition(&thread->lock, &thread->cond);
09884 
09885    return 1;
09886 }
09887 
09888 static int socket_process_meta(int packet_len, struct ast_iax2_meta_hdr *meta, struct sockaddr_in *sin, int sockfd,
09889    struct iax_frame *fr)
09890 {
09891    unsigned char metatype;
09892    struct ast_iax2_meta_trunk_mini *mtm;
09893    struct ast_iax2_meta_trunk_hdr *mth;
09894    struct ast_iax2_meta_trunk_entry *mte;
09895    struct iax2_trunk_peer *tpeer;
09896    unsigned int ts;
09897    void *ptr;
09898    struct timeval rxtrunktime;
09899    struct ast_frame f = { 0, };
09900 
09901    if (packet_len < sizeof(*meta)) {
09902       ast_log(LOG_WARNING, "Rejecting packet from '%s.%d' that is flagged as a meta frame but is too short\n", 
09903          ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
09904       return 1;
09905    }
09906 
09907    if (meta->metacmd != IAX_META_TRUNK)
09908       return 1;
09909 
09910    if (packet_len < (sizeof(*meta) + sizeof(*mth))) {
09911       ast_log(LOG_WARNING, "midget meta trunk packet received (%d of %d min)\n", packet_len,
09912          (int) (sizeof(*meta) + sizeof(*mth)));
09913       return 1;
09914    }
09915    mth = (struct ast_iax2_meta_trunk_hdr *)(meta->data);
09916    ts = ntohl(mth->ts);
09917    metatype = meta->cmddata;
09918    packet_len -= (sizeof(*meta) + sizeof(*mth));
09919    ptr = mth->data;
09920    tpeer = find_tpeer(sin, sockfd);
09921    if (!tpeer) {
09922       ast_log(LOG_WARNING, "Unable to accept trunked packet from '%s:%d': No matching peer\n", 
09923          ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
09924       return 1;
09925    }
09926    tpeer->trunkact = ast_tvnow();
09927    if (!ts || ast_tvzero(tpeer->rxtrunktime))
09928       tpeer->rxtrunktime = tpeer->trunkact;
09929    rxtrunktime = tpeer->rxtrunktime;
09930    ast_mutex_unlock(&tpeer->lock);
09931    while (packet_len >= sizeof(*mte)) {
09932       /* Process channels */
09933       unsigned short callno, trunked_ts, len;
09934 
09935       if (metatype == IAX_META_TRUNK_MINI) {
09936          mtm = (struct ast_iax2_meta_trunk_mini *) ptr;
09937          ptr += sizeof(*mtm);
09938          packet_len -= sizeof(*mtm);
09939          len = ntohs(mtm->len);
09940          callno = ntohs(mtm->mini.callno);
09941          trunked_ts = ntohs(mtm->mini.ts);
09942       } else if (metatype == IAX_META_TRUNK_SUPERMINI) {
09943          mte = (struct ast_iax2_meta_trunk_entry *)ptr;
09944          ptr += sizeof(*mte);
09945          packet_len -= sizeof(*mte);
09946          len = ntohs(mte->len);
09947          callno = ntohs(mte->callno);
09948          trunked_ts = 0;
09949       } else {
09950          ast_log(LOG_WARNING, "Unknown meta trunk cmd from '%s:%d': dropping\n", ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
09951          break;
09952       }
09953       /* Stop if we don't have enough data */
09954       if (len > packet_len)
09955          break;
09956       fr->callno = find_callno_locked(callno & ~IAX_FLAG_FULL, 0, sin, NEW_PREVENT, sockfd, 0);
09957       if (!fr->callno)
09958          continue;
09959 
09960       /* If it's a valid call, deliver the contents.  If not, we
09961          drop it, since we don't have a scallno to use for an INVAL */
09962       /* Process as a mini frame */
09963       memset(&f, 0, sizeof(f));
09964       f.frametype = AST_FRAME_VOICE;
09965       if (!iaxs[fr->callno]) {
09966          /* drop it */
09967       } else if (iaxs[fr->callno]->voiceformat == 0) {
09968          ast_log(LOG_WARNING, "Received trunked frame before first full voice frame\n");
09969          iax2_vnak(fr->callno);
09970       } else {
09971          ast_format_from_old_bitfield(&f.subclass.format, iaxs[fr->callno]->voiceformat);
09972          f.datalen = len;
09973          if (f.datalen >= 0) {
09974             if (f.datalen)
09975                f.data.ptr = ptr;
09976             else
09977                f.data.ptr = NULL;
09978             if (trunked_ts)
09979                fr->ts = (iaxs[fr->callno]->last & 0xFFFF0000L) | (trunked_ts & 0xffff);
09980             else
09981                fr->ts = fix_peerts(&rxtrunktime, fr->callno, ts);
09982             /* Don't pass any packets until we're started */
09983             if (ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED)) {
09984                struct iax_frame *duped_fr;
09985 
09986                /* Common things */
09987                f.src = "IAX2";
09988                f.mallocd = 0;
09989                f.offset = 0;
09990                if (f.datalen && (f.frametype == AST_FRAME_VOICE)) 
09991                   f.samples = ast_codec_get_samples(&f);
09992                else
09993                   f.samples = 0;
09994                fr->outoforder = 0;
09995                iax_frame_wrap(fr, &f);
09996                duped_fr = iaxfrdup2(fr);
09997                if (duped_fr)
09998                   schedule_delivery(duped_fr, 1, 1, &fr->ts);
09999                if (iaxs[fr->callno] && iaxs[fr->callno]->last < fr->ts)
10000                   iaxs[fr->callno]->last = fr->ts;
10001             }
10002          } else {
10003             ast_log(LOG_WARNING, "Datalen < 0?\n");
10004          }
10005       }
10006       ast_mutex_unlock(&iaxsl[fr->callno]);
10007       ptr += len;
10008       packet_len -= len;
10009    }
10010 
10011    return 1;
10012 }
10013 
10014 static int acf_iaxvar_read(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
10015 {
10016    struct ast_datastore *variablestore;
10017    AST_LIST_HEAD(, ast_var_t) *varlist;
10018    struct ast_var_t *var;
10019 
10020    if (!chan) {
10021       ast_log(LOG_WARNING, "No channel was provided to %s function.\n", cmd);
10022       return -1;
10023    }
10024 
10025    variablestore = ast_channel_datastore_find(chan, &iax2_variable_datastore_info, NULL);
10026    if (!variablestore) {
10027       *buf = '\0';
10028       return 0;
10029    }
10030    varlist = variablestore->data;
10031 
10032    AST_LIST_LOCK(varlist);
10033    AST_LIST_TRAVERSE(varlist, var, entries) {
10034       if (strcmp(var->name, data) == 0) {
10035          ast_copy_string(buf, var->value, len);
10036          break;
10037       }
10038    }
10039    AST_LIST_UNLOCK(varlist);
10040    return 0;
10041 }
10042 
10043 static int acf_iaxvar_write(struct ast_channel *chan, const char *cmd, char *data, const char *value)
10044 {
10045    struct ast_datastore *variablestore;
10046    AST_LIST_HEAD(, ast_var_t) *varlist;
10047    struct ast_var_t *var;
10048 
10049    if (!chan) {
10050       ast_log(LOG_WARNING, "No channel was provided to %s function.\n", cmd);
10051       return -1;
10052    }
10053 
10054    variablestore = ast_channel_datastore_find(chan, &iax2_variable_datastore_info, NULL);
10055    if (!variablestore) {
10056       variablestore = ast_datastore_alloc(&iax2_variable_datastore_info, NULL);
10057       if (!variablestore) {
10058          ast_log(LOG_ERROR, "Memory allocation error\n");
10059          return -1;
10060       }
10061       varlist = ast_calloc(1, sizeof(*varlist));
10062       if (!varlist) {
10063          ast_datastore_free(variablestore);
10064          ast_log(LOG_ERROR, "Unable to assign new variable '%s'\n", data);
10065          return -1;
10066       }
10067 
10068       AST_LIST_HEAD_INIT(varlist);
10069       variablestore->data = varlist;
10070       variablestore->inheritance = DATASTORE_INHERIT_FOREVER;
10071       ast_channel_datastore_add(chan, variablestore);
10072    } else
10073       varlist = variablestore->data;
10074 
10075    AST_LIST_LOCK(varlist);
10076    AST_LIST_TRAVERSE_SAFE_BEGIN(varlist, var, entries) {
10077       if (strcmp(var->name, data) == 0) {
10078          AST_LIST_REMOVE_CURRENT(entries);
10079          ast_var_delete(var);
10080          break;
10081       }
10082    }
10083    AST_LIST_TRAVERSE_SAFE_END;
10084    var = ast_var_assign(data, value);
10085    if (var)
10086       AST_LIST_INSERT_TAIL(varlist, var, entries);
10087    else
10088       ast_log(LOG_ERROR, "Unable to assign new variable '%s'\n", data);
10089    AST_LIST_UNLOCK(varlist);
10090    return 0;
10091 }
10092 
10093 static struct ast_custom_function iaxvar_function = {
10094    .name = "IAXVAR",
10095    .read = acf_iaxvar_read,
10096    .write = acf_iaxvar_write,
10097 };
10098 
10099 static void set_hangup_source_and_cause(int callno, unsigned char causecode)
10100 {
10101    iax2_lock_owner(callno);
10102    if (iaxs[callno] && iaxs[callno]->owner) {
10103       struct ast_channel *owner;
10104       const char *name;
10105 
10106       owner = iaxs[callno]->owner;
10107       if (causecode) {
10108          ast_channel_hangupcause_set(owner, causecode);
10109       }
10110       name = ast_strdupa(ast_channel_name(owner));
10111       ast_channel_ref(owner);
10112       ast_channel_unlock(owner);
10113       ast_mutex_unlock(&iaxsl[callno]);
10114       ast_set_hangupsource(owner, name, 0);
10115       ast_channel_unref(owner);
10116       ast_mutex_lock(&iaxsl[callno]);
10117    }
10118 }
10119 
10120 static int socket_process_helper(struct iax2_thread *thread)
10121 {
10122    struct sockaddr_in sin;
10123    int res;
10124    int updatehistory=1;
10125    int new = NEW_PREVENT;
10126    int dcallno = 0;
10127    char decrypted = 0;
10128    struct ast_iax2_full_hdr *fh = (struct ast_iax2_full_hdr *)thread->buf;
10129    struct ast_iax2_mini_hdr *mh = (struct ast_iax2_mini_hdr *)thread->buf;
10130    struct ast_iax2_meta_hdr *meta = (struct ast_iax2_meta_hdr *)thread->buf;
10131    struct ast_iax2_video_hdr *vh = (struct ast_iax2_video_hdr *)thread->buf;
10132    struct iax_frame *fr;
10133    struct iax_frame *cur;
10134    struct ast_frame f = { 0, };
10135    struct ast_channel *c = NULL;
10136    struct iax2_dpcache *dp;
10137    struct iax2_peer *peer;
10138    struct iax_ies ies;
10139    struct iax_ie_data ied0, ied1;
10140    iax2_format format;
10141    int fd;
10142    int exists;
10143    int minivid = 0;
10144    char empty[32]="";      /* Safety measure */
10145    struct iax_frame *duped_fr;
10146    char host_pref_buf[128];
10147    char caller_pref_buf[128];
10148    struct ast_codec_pref pref;
10149    char *using_prefs = "mine";
10150 
10151    /* allocate an iax_frame with 4096 bytes of data buffer */
10152    fr = ast_alloca(sizeof(*fr) + 4096);
10153    memset(fr, 0, sizeof(*fr));
10154    fr->afdatalen = 4096; /* From ast_alloca() above */
10155 
10156    /* Copy frequently used parameters to the stack */
10157    res = thread->buf_len;
10158    fd = thread->iofd;
10159    memcpy(&sin, &thread->iosin, sizeof(sin));
10160 
10161    if (res < sizeof(*mh)) {
10162       ast_log(LOG_WARNING, "midget packet received (%d of %d min)\n", res, (int) sizeof(*mh));
10163       return 1;
10164    }
10165    if ((vh->zeros == 0) && (ntohs(vh->callno) & 0x8000)) {
10166       if (res < sizeof(*vh)) {
10167          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));
10168          return 1;
10169       }
10170 
10171       /* This is a video frame, get call number */
10172       fr->callno = find_callno(ntohs(vh->callno) & ~0x8000, dcallno, &sin, new, fd, 0);
10173       minivid = 1;
10174    } else if ((meta->zeros == 0) && !(ntohs(meta->metacmd) & 0x8000))
10175       return socket_process_meta(res, meta, &sin, fd, fr);
10176 
10177 #ifdef DEBUG_SUPPORT
10178    if (res >= sizeof(*fh))
10179       iax_outputframe(NULL, fh, 1, &sin, res - sizeof(*fh));
10180 #endif
10181    if (ntohs(mh->callno) & IAX_FLAG_FULL) {
10182       if (res < sizeof(*fh)) {
10183          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));
10184          return 1;
10185       }
10186 
10187       /* Get the destination call number */
10188       dcallno = ntohs(fh->dcallno) & ~IAX_FLAG_RETRANS;
10189 
10190 
10191       /* check to make sure this full frame isn't encrypted before we attempt
10192        * to look inside of it. If it is encrypted, decrypt it first. Its ok if the
10193        * callno is not found here, that just means one hasn't been allocated for
10194        * this connection yet. */
10195       if ((dcallno != 1) && (fr->callno = find_callno(ntohs(mh->callno) & ~IAX_FLAG_FULL, dcallno, &sin, NEW_PREVENT, fd, 1))) {
10196          ast_mutex_lock(&iaxsl[fr->callno]);
10197          if (iaxs[fr->callno] && ast_test_flag64(iaxs[fr->callno], IAX_ENCRYPTED)) {
10198             if (decrypt_frame(fr->callno, fh, &f, &res)) {
10199                ast_log(LOG_NOTICE, "Packet Decrypt Failed!\n");
10200                ast_mutex_unlock(&iaxsl[fr->callno]);
10201                return 1;
10202             }
10203             decrypted = 1;
10204          }
10205          ast_mutex_unlock(&iaxsl[fr->callno]);
10206       }
10207 
10208       /* Retrieve the type and subclass */
10209       f.frametype = fh->type;
10210       if (f.frametype == AST_FRAME_VIDEO) {
10211          ast_format_from_old_bitfield(&f.subclass.format, (uncompress_subclass(fh->csub & ~0x40)));
10212          if ((fh->csub >> 6) & 0x1) {
10213             ast_format_set_video_mark(&f.subclass.format);
10214          }
10215       } else if (f.frametype == AST_FRAME_VOICE) {
10216          ast_format_from_old_bitfield(&f.subclass.format, uncompress_subclass(fh->csub));
10217       } else {
10218          f.subclass.integer = uncompress_subclass(fh->csub);
10219       }
10220 
10221       /* Deal with POKE/PONG without allocating a callno */
10222       if (f.frametype == AST_FRAME_IAX && f.subclass.integer == IAX_COMMAND_POKE) {
10223          /* Reply back with a PONG, but don't care about the result. */
10224          send_apathetic_reply(1, ntohs(fh->scallno), &sin, IAX_COMMAND_PONG, ntohl(fh->ts), fh->iseqno + 1, fd, NULL);
10225          return 1;
10226       } else if (f.frametype == AST_FRAME_IAX && f.subclass.integer == IAX_COMMAND_ACK && dcallno == 1) {
10227          /* Ignore */
10228          return 1;
10229       }
10230 
10231       f.datalen = res - sizeof(*fh);
10232       if (f.datalen) {
10233          if (f.frametype == AST_FRAME_IAX) {
10234             if (iax_parse_ies(&ies, thread->buf + sizeof(struct ast_iax2_full_hdr), f.datalen)) {
10235                ast_log(LOG_WARNING, "Undecodable frame received from '%s'\n", ast_inet_ntoa(sin.sin_addr));
10236                ast_variables_destroy(ies.vars);
10237                return 1;
10238             }
10239             f.data.ptr = NULL;
10240             f.datalen = 0;
10241          } else {
10242             f.data.ptr = thread->buf + sizeof(struct ast_iax2_full_hdr);
10243             memset(&ies, 0, sizeof(ies));
10244          }
10245       } else {
10246          if (f.frametype == AST_FRAME_IAX)
10247             f.data.ptr = NULL;
10248          else
10249             f.data.ptr = empty;
10250          memset(&ies, 0, sizeof(ies));
10251       }
10252 
10253       if (!dcallno && iax2_allow_new(f.frametype, f.subclass.integer, 1)) {
10254          /* only set NEW_ALLOW if calltoken checks out */
10255          if (handle_call_token(fh, &ies, &sin, fd)) {
10256             ast_variables_destroy(ies.vars);
10257             return 1;
10258          }
10259 
10260          if (ies.calltoken && ies.calltokendata) {
10261             /* if we've gotten this far, and the calltoken ie data exists,
10262              * then calltoken validation _MUST_ have taken place.  If calltoken
10263              * data is provided, it is always validated reguardless of any
10264              * calltokenoptional or requirecalltoken options */
10265             new = NEW_ALLOW_CALLTOKEN_VALIDATED;
10266          } else {
10267             new = NEW_ALLOW;
10268          }
10269       }
10270    } else {
10271       /* Don't know anything about it yet */
10272       f.frametype = AST_FRAME_NULL;
10273       f.subclass.integer = 0;
10274       memset(&ies, 0, sizeof(ies));
10275    }
10276 
10277    if (!fr->callno) {
10278       int check_dcallno = 0;
10279 
10280       /*
10281        * We enforce accurate destination call numbers for ACKs.  This forces the other
10282        * end to know the destination call number before call setup can complete.
10283        *
10284        * Discussed in the following thread:
10285        *    http://lists.digium.com/pipermail/asterisk-dev/2008-May/033217.html 
10286        */
10287 
10288       if ((ntohs(mh->callno) & IAX_FLAG_FULL) && ((f.frametype == AST_FRAME_IAX) && (f.subclass.integer == IAX_COMMAND_ACK))) {
10289          check_dcallno = 1;
10290       }
10291 
10292       if (!(fr->callno = find_callno(ntohs(mh->callno) & ~IAX_FLAG_FULL, dcallno, &sin, new, fd, check_dcallno))) {
10293          if (f.frametype == AST_FRAME_IAX && f.subclass.integer == IAX_COMMAND_NEW) {
10294             send_apathetic_reply(1, ntohs(fh->scallno), &sin, IAX_COMMAND_REJECT, ntohl(fh->ts), fh->iseqno + 1, fd, NULL);
10295          } else if (f.frametype == AST_FRAME_IAX && (f.subclass.integer == IAX_COMMAND_REGREQ || f.subclass.integer == IAX_COMMAND_REGREL)) {
10296             send_apathetic_reply(1, ntohs(fh->scallno), &sin, IAX_COMMAND_REGREJ, ntohl(fh->ts), fh->iseqno + 1, fd, NULL);
10297          }
10298          ast_variables_destroy(ies.vars);
10299          return 1;
10300       }
10301    }
10302 
10303    if (fr->callno > 0) {
10304       struct ast_callid *mount_callid;
10305       ast_mutex_lock(&iaxsl[fr->callno]);
10306       if (iaxs[fr->callno] && ((mount_callid = iax_pvt_callid_get(fr->callno)))) {
10307          /* Bind to thread */
10308          ast_callid_threadassoc_add(mount_callid);
10309          ast_callid_unref(mount_callid);
10310       }
10311    }
10312 
10313    if (!fr->callno || !iaxs[fr->callno]) {
10314       /* A call arrived for a nonexistent destination.  Unless it's an "inval"
10315          frame, reply with an inval */
10316       if (ntohs(mh->callno) & IAX_FLAG_FULL) {
10317          /* We can only raw hangup control frames */
10318          if (((f.subclass.integer != IAX_COMMAND_INVAL) &&
10319              (f.subclass.integer != IAX_COMMAND_TXCNT) &&
10320              (f.subclass.integer != IAX_COMMAND_TXACC) &&
10321              (f.subclass.integer != IAX_COMMAND_FWDOWNL))||
10322              (f.frametype != AST_FRAME_IAX))
10323             raw_hangup(&sin, ntohs(fh->dcallno) & ~IAX_FLAG_RETRANS, ntohs(mh->callno) & ~IAX_FLAG_FULL,
10324             fd);
10325       }
10326       if (fr->callno > 0) 
10327          ast_mutex_unlock(&iaxsl[fr->callno]);
10328       ast_variables_destroy(ies.vars);
10329       return 1;
10330    }
10331    if (ast_test_flag64(iaxs[fr->callno], IAX_ENCRYPTED) && !decrypted) {
10332       if (decrypt_frame(fr->callno, fh, &f, &res)) {
10333          ast_log(LOG_NOTICE, "Packet Decrypt Failed!\n");
10334          ast_variables_destroy(ies.vars);
10335          ast_mutex_unlock(&iaxsl[fr->callno]);
10336          return 1;
10337       }
10338       decrypted = 1;
10339    }
10340 
10341 #ifdef DEBUG_SUPPORT
10342    if (decrypted) {
10343       iax_outputframe(NULL, fh, 3, &sin, res - sizeof(*fh));
10344    }
10345 #endif
10346 
10347    if (iaxs[fr->callno]->owner && fh->type == AST_FRAME_IAX &&
10348          (fh->csub == IAX_COMMAND_HANGUP
10349          || fh->csub == IAX_COMMAND_REJECT
10350          || fh->csub == IAX_COMMAND_REGREJ
10351          || fh->csub == IAX_COMMAND_TXREJ)) {
10352       struct ast_control_pvt_cause_code *cause_code;
10353       int data_size = sizeof(*cause_code);
10354       char subclass[40] = "";
10355 
10356       /* get subclass text */
10357       iax_frame_subclass2str(fh->csub, subclass, sizeof(subclass));
10358 
10359       /* add length of "IAX2 " */
10360       data_size += 5;
10361       /* for IAX hangup frames, add length of () and number */
10362       data_size += 3;
10363       if (ies.causecode > 9) {
10364          data_size++;
10365       }
10366       if (ies.causecode > 99) {
10367          data_size++;
10368       }
10369       /* add length of subclass */
10370       data_size += strlen(subclass);
10371 
10372       cause_code = ast_alloca(data_size);
10373       memset(cause_code, 0, data_size);
10374       ast_copy_string(cause_code->chan_name, ast_channel_name(iaxs[fr->callno]->owner), AST_CHANNEL_NAME);
10375 
10376       cause_code->ast_cause = ies.causecode;
10377       snprintf(cause_code->code, data_size - sizeof(*cause_code) + 1, "IAX2 %s(%d)", subclass, ies.causecode);
10378 
10379       iax2_lock_owner(fr->callno);
10380       if (iaxs[fr->callno] && iaxs[fr->callno]->owner) {
10381          ast_queue_control_data(iaxs[fr->callno]->owner, AST_CONTROL_PVT_CAUSE_CODE, cause_code, data_size);
10382          ast_channel_hangupcause_hash_set(iaxs[fr->callno]->owner, cause_code, data_size);
10383          ast_channel_unlock(iaxs[fr->callno]->owner);
10384       }
10385       if (!iaxs[fr->callno]) {
10386          ast_variables_destroy(ies.vars);
10387          ast_mutex_unlock(&iaxsl[fr->callno]);
10388          return 1;
10389       }
10390    }
10391 
10392    /* count this frame */
10393    iaxs[fr->callno]->frames_received++;
10394 
10395    if (!inaddrcmp(&sin, &iaxs[fr->callno]->addr) && !minivid &&
10396       f.subclass.integer != IAX_COMMAND_TXCNT &&      /* for attended transfer */
10397       f.subclass.integer != IAX_COMMAND_TXACC) {      /* for attended transfer */
10398       unsigned short new_peercallno;
10399 
10400       new_peercallno = (unsigned short) (ntohs(mh->callno) & ~IAX_FLAG_FULL);
10401       if (new_peercallno && new_peercallno != iaxs[fr->callno]->peercallno) {
10402          if (iaxs[fr->callno]->peercallno) {
10403             remove_by_peercallno(iaxs[fr->callno]);
10404          }
10405          iaxs[fr->callno]->peercallno = new_peercallno;
10406          store_by_peercallno(iaxs[fr->callno]);
10407       }
10408    }
10409    if (ntohs(mh->callno) & IAX_FLAG_FULL) {
10410       if (iaxdebug)
10411          ast_debug(1, "Received packet %d, (%d, %u)\n", fh->oseqno, f.frametype, f.subclass.integer);
10412       /* Check if it's out of order (and not an ACK or INVAL) */
10413       fr->oseqno = fh->oseqno;
10414       fr->iseqno = fh->iseqno;
10415       fr->ts = ntohl(fh->ts);
10416 #ifdef IAXTESTS
10417       if (test_resync) {
10418          ast_debug(1, "Simulating frame ts resync, was %u now %u\n", fr->ts, fr->ts + test_resync);
10419          fr->ts += test_resync;
10420       }
10421 #endif /* IAXTESTS */
10422 #if 0
10423       if ( (ntohs(fh->dcallno) & IAX_FLAG_RETRANS) ||
10424            ( (f.frametype != AST_FRAME_VOICE) && ! (f.frametype == AST_FRAME_IAX &&
10425                         (f.subclass == IAX_COMMAND_NEW ||
10426                          f.subclass == IAX_COMMAND_AUTHREQ ||
10427                          f.subclass == IAX_COMMAND_ACCEPT ||
10428                          f.subclass == IAX_COMMAND_REJECT))      ) )
10429 #endif
10430       if ((ntohs(fh->dcallno) & IAX_FLAG_RETRANS) || (f.frametype != AST_FRAME_VOICE))
10431          updatehistory = 0;
10432       if ((iaxs[fr->callno]->iseqno != fr->oseqno) &&
10433          (iaxs[fr->callno]->iseqno ||
10434             ((f.subclass.integer != IAX_COMMAND_TXCNT) &&
10435             (f.subclass.integer != IAX_COMMAND_TXREADY) &&     /* for attended transfer */
10436             (f.subclass.integer != IAX_COMMAND_TXREL) &&    /* for attended transfer */
10437             (f.subclass.integer != IAX_COMMAND_UNQUELCH ) &&   /* for attended transfer */
10438             (f.subclass.integer != IAX_COMMAND_TXACC)) ||
10439             (f.frametype != AST_FRAME_IAX))) {
10440          if (
10441           ((f.subclass.integer != IAX_COMMAND_ACK) &&
10442            (f.subclass.integer != IAX_COMMAND_INVAL) &&
10443            (f.subclass.integer != IAX_COMMAND_TXCNT) &&
10444            (f.subclass.integer != IAX_COMMAND_TXREADY) &&      /* for attended transfer */
10445            (f.subclass.integer != IAX_COMMAND_TXREL) &&     /* for attended transfer */
10446            (f.subclass.integer != IAX_COMMAND_UNQUELCH ) && /* for attended transfer */
10447            (f.subclass.integer != IAX_COMMAND_TXACC) &&
10448            (f.subclass.integer != IAX_COMMAND_VNAK)) ||
10449            (f.frametype != AST_FRAME_IAX)) {
10450             /* If it's not an ACK packet, it's out of order. */
10451             ast_debug(1, "Packet arrived out of order (expecting %d, got %d) (frametype = %d, subclass = %d)\n",
10452                iaxs[fr->callno]->iseqno, fr->oseqno, f.frametype, f.subclass.integer);
10453             /* Check to see if we need to request retransmission,
10454              * and take sequence number wraparound into account */
10455             if ((unsigned char) (iaxs[fr->callno]->iseqno - fr->oseqno) < 128) {
10456                /* If we've already seen it, ack it XXX There's a border condition here XXX */
10457                if ((f.frametype != AST_FRAME_IAX) ||
10458                      ((f.subclass.integer != IAX_COMMAND_ACK) && (f.subclass.integer != IAX_COMMAND_INVAL))) {
10459                   ast_debug(1, "Acking anyway\n");
10460                   /* XXX Maybe we should handle its ack to us, but then again, it's probably outdated anyway, and if
10461                      we have anything to send, we'll retransmit and get an ACK back anyway XXX */
10462                   send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
10463                }
10464             } else {
10465                /* Send a VNAK requesting retransmission */
10466                iax2_vnak(fr->callno);
10467             }
10468             ast_variables_destroy(ies.vars);
10469             ast_mutex_unlock(&iaxsl[fr->callno]);
10470             return 1;
10471          }
10472       } else {
10473          /* Increment unless it's an ACK or VNAK */
10474          if (((f.subclass.integer != IAX_COMMAND_ACK) &&
10475              (f.subclass.integer != IAX_COMMAND_INVAL) &&
10476              (f.subclass.integer != IAX_COMMAND_TXCNT) &&
10477              (f.subclass.integer != IAX_COMMAND_TXACC) &&
10478             (f.subclass.integer != IAX_COMMAND_VNAK)) ||
10479              (f.frametype != AST_FRAME_IAX))
10480             iaxs[fr->callno]->iseqno++;
10481       }
10482       /* Ensure text frames are NULL-terminated */
10483       if (f.frametype == AST_FRAME_TEXT && thread->buf[res - 1] != '\0') {
10484          if (res < thread->buf_size)
10485             thread->buf[res++] = '\0';
10486          else /* Trims one character from the text message, but that's better than overwriting the end of the buffer. */
10487             thread->buf[res - 1] = '\0';
10488       }
10489 
10490       /* Handle implicit ACKing unless this is an INVAL, and only if this is 
10491          from the real peer, not the transfer peer */
10492       if (!inaddrcmp(&sin, &iaxs[fr->callno]->addr) &&
10493           ((f.subclass.integer != IAX_COMMAND_INVAL) ||
10494            (f.frametype != AST_FRAME_IAX))) {
10495          unsigned char x;
10496          int call_to_destroy;
10497          /* First we have to qualify that the ACKed value is within our window */
10498          if (iaxs[fr->callno]->rseqno >= iaxs[fr->callno]->oseqno || (fr->iseqno >= iaxs[fr->callno]->rseqno && fr->iseqno < iaxs[fr->callno]->oseqno))
10499             x = fr->iseqno;
10500          else
10501             x = iaxs[fr->callno]->oseqno;
10502          if ((x != iaxs[fr->callno]->oseqno) || (iaxs[fr->callno]->oseqno == fr->iseqno)) {
10503             /* The acknowledgement is within our window.  Time to acknowledge everything
10504                that it says to */
10505             for (x=iaxs[fr->callno]->rseqno; x != fr->iseqno; x++) {
10506                /* Ack the packet with the given timestamp */
10507                if (iaxdebug)
10508                   ast_debug(1, "Cancelling transmission of packet %d\n", x);
10509                call_to_destroy = 0;
10510                AST_LIST_TRAVERSE(&frame_queue[fr->callno], cur, list) {
10511                   /* If it's our call, and our timestamp, mark -1 retries */
10512                   if (x == cur->oseqno) {
10513                      cur->retries = -1;
10514                      /* Destroy call if this is the end */
10515                      if (cur->final)
10516                         call_to_destroy = fr->callno;
10517                   }
10518                }
10519                if (call_to_destroy) {
10520                   if (iaxdebug)
10521                      ast_debug(1, "Really destroying %d, having been acked on final message\n", call_to_destroy);
10522                   ast_mutex_lock(&iaxsl[call_to_destroy]);
10523                   iax2_destroy(call_to_destroy);
10524                   ast_mutex_unlock(&iaxsl[call_to_destroy]);
10525                }
10526             }
10527             /* Note how much we've received acknowledgement for */
10528             if (iaxs[fr->callno])
10529                iaxs[fr->callno]->rseqno = fr->iseqno;
10530             else {
10531                /* Stop processing now */
10532                ast_variables_destroy(ies.vars);
10533                ast_mutex_unlock(&iaxsl[fr->callno]);
10534                return 1;
10535             }
10536          } else {
10537             ast_debug(1, "Received iseqno %d not within window %d->%d\n", fr->iseqno, iaxs[fr->callno]->rseqno, iaxs[fr->callno]->oseqno);
10538          }
10539       }
10540       if (inaddrcmp(&sin, &iaxs[fr->callno]->addr) &&
10541          ((f.frametype != AST_FRAME_IAX) ||
10542           ((f.subclass.integer != IAX_COMMAND_TXACC) &&
10543            (f.subclass.integer != IAX_COMMAND_TXCNT)))) {
10544          /* Only messages we accept from a transfer host are TXACC and TXCNT */
10545          ast_variables_destroy(ies.vars);
10546          ast_mutex_unlock(&iaxsl[fr->callno]);
10547          return 1;
10548       }
10549 
10550       /* when we receive the first full frame for a new incoming channel,
10551          it is safe to start the PBX on the channel because we have now
10552          completed a 3-way handshake with the peer */
10553       if ((f.frametype == AST_FRAME_VOICE) ||
10554           (f.frametype == AST_FRAME_VIDEO) ||
10555           (f.frametype == AST_FRAME_IAX)) {
10556          if (ast_test_flag64(iaxs[fr->callno], IAX_DELAYPBXSTART)) {
10557             ast_clear_flag64(iaxs[fr->callno], IAX_DELAYPBXSTART);
10558             if (!ast_iax2_new(fr->callno, AST_STATE_RING, iaxs[fr->callno]->chosenformat, NULL,
10559                     ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_AUTHENTICATED))) {
10560                ast_variables_destroy(ies.vars);
10561                ast_mutex_unlock(&iaxsl[fr->callno]);
10562                return 1;
10563             }
10564          }
10565 
10566          if (ies.vars) {
10567             struct ast_datastore *variablestore = NULL;
10568             struct ast_variable *var, *prev = NULL;
10569             AST_LIST_HEAD(, ast_var_t) *varlist;
10570 
10571             iax2_lock_owner(fr->callno);
10572             if (!iaxs[fr->callno]) {
10573                ast_variables_destroy(ies.vars);
10574                ast_mutex_unlock(&iaxsl[fr->callno]);
10575                return 1;
10576             }
10577             if ((c = iaxs[fr->callno]->owner)) {
10578                varlist = ast_calloc(1, sizeof(*varlist));
10579                variablestore = ast_datastore_alloc(&iax2_variable_datastore_info, NULL);
10580 
10581                if (variablestore && varlist) {
10582                   variablestore->data = varlist;
10583                   variablestore->inheritance = DATASTORE_INHERIT_FOREVER;
10584                   AST_LIST_HEAD_INIT(varlist);
10585                   ast_debug(1, "I can haz IAX vars?\n");
10586                   for (var = ies.vars; var; var = var->next) {
10587                      struct ast_var_t *newvar = ast_var_assign(var->name, var->value);
10588                      if (prev) {
10589                         ast_free(prev);
10590                      }
10591                      prev = var;
10592                      if (!newvar) {
10593                         /* Don't abort list traversal, as this would leave ies.vars in an inconsistent state. */
10594                         ast_log(LOG_ERROR, "Memory allocation error while processing IAX2 variables\n");
10595                      } else {
10596                         AST_LIST_INSERT_TAIL(varlist, newvar, entries);
10597                      }
10598                   }
10599                   if (prev) {
10600                      ast_free(prev);
10601                   }
10602                   ies.vars = NULL;
10603                   ast_channel_datastore_add(c, variablestore);
10604                } else {
10605                   ast_log(LOG_ERROR, "Memory allocation error while processing IAX2 variables\n");
10606                   if (variablestore) {
10607                      ast_datastore_free(variablestore);
10608                   }
10609                   if (varlist) {
10610                      ast_free(varlist);
10611                   }
10612                }
10613                ast_channel_unlock(c);
10614             } else {
10615                /* No channel yet, so transfer the variables directly over to the pvt,
10616                 * for later inheritance. */
10617                ast_debug(1, "No channel, so populating IAXVARs to the pvt, as an intermediate step.\n");
10618                for (var = ies.vars; var && var->next; var = var->next);
10619                if (var) {
10620                   var->next = iaxs[fr->callno]->iaxvars;
10621                   iaxs[fr->callno]->iaxvars = ies.vars;
10622                   ies.vars = NULL;
10623                }
10624             }
10625          }
10626 
10627          if (ies.vars) {
10628             ast_debug(1, "I have IAX variables, but they were not processed\n");
10629          }
10630       }
10631 
10632       /* once we receive our first IAX Full Frame that is not CallToken related, send all
10633        * queued signaling frames that were being held. */
10634       if ((f.frametype == AST_FRAME_IAX) && (f.subclass.integer != IAX_COMMAND_CALLTOKEN) && iaxs[fr->callno]->hold_signaling) {
10635          send_signaling(iaxs[fr->callno]);
10636       }
10637 
10638       if (f.frametype == AST_FRAME_VOICE) {
10639          if (ast_format_to_old_bitfield(&f.subclass.format) != iaxs[fr->callno]->voiceformat) {
10640                iaxs[fr->callno]->voiceformat = ast_format_to_old_bitfield(&f.subclass.format);
10641                ast_debug(1, "Ooh, voice format changed to '%s'\n", ast_getformatname(&f.subclass.format));
10642                if (iaxs[fr->callno]->owner) {
10643                   iax2_lock_owner(fr->callno);
10644                   if (iaxs[fr->callno]) {
10645                      if (iaxs[fr->callno]->owner) {
10646                         struct ast_format_cap *orignative = ast_format_cap_dup(ast_channel_nativeformats(iaxs[fr->callno]->owner));
10647                         struct ast_format_cap *native = ast_channel_nativeformats(iaxs[fr->callno]->owner);
10648                         if (orignative) {
10649                            ast_format_cap_set(native, &f.subclass.format);
10650                            if (ast_channel_readformat(iaxs[fr->callno]->owner)->id) {
10651                               ast_set_read_format(iaxs[fr->callno]->owner, ast_channel_readformat(iaxs[fr->callno]->owner));
10652                            }
10653                            ast_format_cap_copy(native, orignative);
10654                            orignative = ast_format_cap_destroy(orignative);
10655                         }
10656                         ast_channel_unlock(iaxs[fr->callno]->owner);
10657                      }
10658                   } else {
10659                      ast_debug(1, "Neat, somebody took away the channel at a magical time but i found it!\n");
10660                      /* Free remote variables (if any) */
10661                      if (ies.vars) {
10662                         ast_variables_destroy(ies.vars);
10663                         ast_debug(1, "I can haz iaxvars, but they is no good.  :-(\n");
10664                         ies.vars = NULL;
10665                      }
10666                      ast_mutex_unlock(&iaxsl[fr->callno]);
10667                      return 1;
10668                   }
10669                }
10670          }
10671       }
10672       if (f.frametype == AST_FRAME_VIDEO) {
10673          if (f.subclass.format.id != ast_format_id_from_old_bitfield(iaxs[fr->callno]->videoformat)) {
10674             ast_debug(1, "Ooh, video format changed to %s\n", ast_getformatname(&f.subclass.format));
10675             iaxs[fr->callno]->videoformat = ast_format_to_old_bitfield(&f.subclass.format);
10676          }
10677       }
10678       if (f.frametype == AST_FRAME_IAX) {
10679          AST_SCHED_DEL(sched, iaxs[fr->callno]->initid);
10680          /* Handle the IAX pseudo frame itself */
10681          if (iaxdebug)
10682             ast_debug(1, "IAX subclass %d received\n", f.subclass.integer);
10683 
10684                         /* Update last ts unless the frame's timestamp originated with us. */
10685          if (iaxs[fr->callno]->last < fr->ts &&
10686                             f.subclass.integer != IAX_COMMAND_ACK &&
10687                             f.subclass.integer != IAX_COMMAND_PONG &&
10688                             f.subclass.integer != IAX_COMMAND_LAGRP) {
10689             iaxs[fr->callno]->last = fr->ts;
10690             if (iaxdebug)
10691                ast_debug(1, "For call=%d, set last=%d\n", fr->callno, fr->ts);
10692          }
10693          iaxs[fr->callno]->last_iax_message = f.subclass.integer;
10694          if (!iaxs[fr->callno]->first_iax_message) {
10695             iaxs[fr->callno]->first_iax_message = f.subclass.integer;
10696          }
10697          switch(f.subclass.integer) {
10698          case IAX_COMMAND_ACK:
10699             /* Do nothing */
10700             break;
10701          case IAX_COMMAND_QUELCH:
10702             if (ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED)) {
10703                     /* Generate Manager Hold event, if necessary*/
10704                if (iaxs[fr->callno]->owner) {
10705                   ast_manager_event(iaxs[fr->callno]->owner, EVENT_FLAG_CALL, "Hold",
10706                      "Status: On\r\n"
10707                      "Channel: %s\r\n"
10708                      "Uniqueid: %s\r\n",
10709                      ast_channel_name(iaxs[fr->callno]->owner),
10710                      ast_channel_uniqueid(iaxs[fr->callno]->owner));
10711                }
10712 
10713                ast_set_flag64(iaxs[fr->callno], IAX_QUELCH);
10714                if (ies.musiconhold) {
10715                   iax2_lock_owner(fr->callno);
10716                   if (!iaxs[fr->callno] || !iaxs[fr->callno]->owner) {
10717                      break;
10718                   }
10719                   if (ast_bridged_channel(iaxs[fr->callno]->owner)) {
10720                      const char *moh_suggest = iaxs[fr->callno]->mohsuggest;
10721 
10722                      /*
10723                       * We already hold the owner lock so we do not
10724                       * need to check iaxs[fr->callno] after it returns.
10725                       */
10726                      iax2_queue_control_data(fr->callno, AST_CONTROL_HOLD, 
10727                         S_OR(moh_suggest, NULL),
10728                         !ast_strlen_zero(moh_suggest) ? strlen(moh_suggest) + 1 : 0);
10729                   }
10730                   ast_channel_unlock(iaxs[fr->callno]->owner);
10731                }
10732             }
10733             break;
10734          case IAX_COMMAND_UNQUELCH:
10735             if (ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED)) {
10736                iax2_lock_owner(fr->callno);
10737                if (!iaxs[fr->callno]) {
10738                   break;
10739                }
10740                /* Generate Manager Unhold event, if necessary */
10741                if (iaxs[fr->callno]->owner && ast_test_flag64(iaxs[fr->callno], IAX_QUELCH)) {
10742                   ast_manager_event(iaxs[fr->callno]->owner, EVENT_FLAG_CALL, "Hold",
10743                      "Status: Off\r\n"
10744                      "Channel: %s\r\n"
10745                      "Uniqueid: %s\r\n",
10746                      ast_channel_name(iaxs[fr->callno]->owner),
10747                      ast_channel_uniqueid(iaxs[fr->callno]->owner));
10748                }
10749 
10750                ast_clear_flag64(iaxs[fr->callno], IAX_QUELCH);
10751                if (!iaxs[fr->callno]->owner) {
10752                   break;
10753                }
10754                if (ast_bridged_channel(iaxs[fr->callno]->owner)) {
10755                   /*
10756                    * We already hold the owner lock so we do not
10757                    * need to check iaxs[fr->callno] after it returns.
10758                    */
10759                   iax2_queue_control_data(fr->callno, AST_CONTROL_UNHOLD, NULL, 0);
10760                }
10761                ast_channel_unlock(iaxs[fr->callno]->owner);
10762             }
10763             break;
10764          case IAX_COMMAND_TXACC:
10765             if (iaxs[fr->callno]->transferring == TRANSFER_BEGIN) {
10766                /* Ack the packet with the given timestamp */
10767                AST_LIST_TRAVERSE(&frame_queue[fr->callno], cur, list) {
10768                   /* Cancel any outstanding txcnt's */
10769                   if (cur->transfer) {
10770                      cur->retries = -1;
10771                   }
10772                }
10773                memset(&ied1, 0, sizeof(ied1));
10774                iax_ie_append_short(&ied1, IAX_IE_CALLNO, iaxs[fr->callno]->callno);
10775                send_command(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_TXREADY, 0, ied1.buf, ied1.pos, -1);
10776                iaxs[fr->callno]->transferring = TRANSFER_READY;
10777             }
10778             break;
10779          case IAX_COMMAND_NEW:
10780             /* Ignore if it's already up */
10781             if (ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED | IAX_STATE_TBD))
10782                break;
10783             if (ies.provverpres && ies.serviceident && sin.sin_addr.s_addr) {
10784                ast_mutex_unlock(&iaxsl[fr->callno]);
10785                check_provisioning(&sin, fd, ies.serviceident, ies.provver);
10786                ast_mutex_lock(&iaxsl[fr->callno]);
10787                if (!iaxs[fr->callno]) {
10788                   break;
10789                }
10790             }
10791             /* If we're in trunk mode, do it now, and update the trunk number in our frame before continuing */
10792             if (ast_test_flag64(iaxs[fr->callno], IAX_TRUNK)) {
10793                int new_callno;
10794                if ((new_callno = make_trunk(fr->callno, 1)) != -1)
10795                   fr->callno = new_callno;
10796             }
10797             /* For security, always ack immediately */
10798             if (delayreject)
10799                send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
10800             if (check_access(fr->callno, &sin, &ies)) {
10801                /* They're not allowed on */
10802                auth_fail(fr->callno, IAX_COMMAND_REJECT);
10803                if (authdebug)
10804                   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);
10805                break;
10806             }
10807             if (ast_strlen_zero(iaxs[fr->callno]->secret) && ast_test_flag64(iaxs[fr->callno], IAX_FORCE_ENCRYPT)) {
10808                auth_fail(fr->callno, IAX_COMMAND_REJECT);
10809                ast_log(LOG_WARNING, "Rejected connect attempt.  No secret present while force encrypt enabled.\n");
10810                break;
10811             }
10812             if (strcasecmp(iaxs[fr->callno]->exten, "TBD")) {
10813                const char *context, *exten, *cid_num;
10814 
10815                context = ast_strdupa(iaxs[fr->callno]->context);
10816                exten = ast_strdupa(iaxs[fr->callno]->exten);
10817                cid_num = ast_strdupa(iaxs[fr->callno]->cid_num);
10818 
10819                /* This might re-enter the IAX code and need the lock */
10820                ast_mutex_unlock(&iaxsl[fr->callno]);
10821                exists = ast_exists_extension(NULL, context, exten, 1, cid_num);
10822                ast_mutex_lock(&iaxsl[fr->callno]);
10823 
10824                if (!iaxs[fr->callno]) {
10825                   break;
10826                }
10827             } else
10828                exists = 0;
10829             /* Get OSP token if it does exist */
10830             save_osptoken(fr, &ies);
10831             if (ast_strlen_zero(iaxs[fr->callno]->secret) && ast_strlen_zero(iaxs[fr->callno]->inkeys)) {
10832                if (strcmp(iaxs[fr->callno]->exten, "TBD") && !exists) {
10833                   memset(&ied0, 0, sizeof(ied0));
10834                   iax_ie_append_str(&ied0, IAX_IE_CAUSE, "No such context/extension");
10835                   iax_ie_append_byte(&ied0, IAX_IE_CAUSECODE, AST_CAUSE_NO_ROUTE_DESTINATION);
10836                   send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
10837                   if (!iaxs[fr->callno]) {
10838                      break;
10839                   }
10840                   if (authdebug)
10841                      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);
10842                } else {
10843                   /* Select an appropriate format */
10844 
10845                   if(ast_test_flag64(iaxs[fr->callno], IAX_CODEC_NOPREFS)) {
10846                      if(ast_test_flag64(iaxs[fr->callno], IAX_CODEC_NOCAP)) {
10847                         using_prefs = "reqonly";
10848                      } else {
10849                         using_prefs = "disabled";
10850                      }
10851                      format = iaxs[fr->callno]->peerformat & iaxs[fr->callno]->capability;
10852                      memset(&pref, 0, sizeof(pref));
10853                      strcpy(caller_pref_buf, "disabled");
10854                      strcpy(host_pref_buf, "disabled");
10855                   } else {
10856                      struct ast_format tmpfmt;
10857                      using_prefs = "mine";
10858                      /* If the information elements are in here... use them */
10859                      if (ies.codec_prefs)
10860                         ast_codec_pref_convert(&iaxs[fr->callno]->rprefs, ies.codec_prefs, 32, 0);
10861                      if (ast_codec_pref_index(&iaxs[fr->callno]->rprefs, 0, &tmpfmt)) {
10862                         /* If we are codec_first_choice we let the caller have the 1st shot at picking the codec.*/
10863                         if (ast_test_flag64(iaxs[fr->callno], IAX_CODEC_USER_FIRST)) {
10864                            pref = iaxs[fr->callno]->rprefs;
10865                            using_prefs = "caller";
10866                         } else {
10867                            pref = iaxs[fr->callno]->prefs;
10868                         }
10869                      } else
10870                         pref = iaxs[fr->callno]->prefs;
10871 
10872                      format = iax2_codec_choose(&pref, iaxs[fr->callno]->capability & iaxs[fr->callno]->peercapability, 0);
10873                      ast_codec_pref_string(&iaxs[fr->callno]->rprefs, caller_pref_buf, sizeof(caller_pref_buf) - 1);
10874                      ast_codec_pref_string(&iaxs[fr->callno]->prefs, host_pref_buf, sizeof(host_pref_buf) - 1);
10875                   }
10876                   if (!format) {
10877                      if(!ast_test_flag64(iaxs[fr->callno], IAX_CODEC_NOCAP))
10878                         format = iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability;
10879                      if (!format) {
10880                         memset(&ied0, 0, sizeof(ied0));
10881                         iax_ie_append_str(&ied0, IAX_IE_CAUSE, "Unable to negotiate codec");
10882                         iax_ie_append_byte(&ied0, IAX_IE_CAUSECODE, AST_CAUSE_BEARERCAPABILITY_NOTAVAIL);
10883                         send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
10884                         if (!iaxs[fr->callno]) {
10885                            break;
10886                         }
10887                         if (authdebug) {
10888                            char tmp[256], tmp2[256], tmp3[256];
10889                            if (ast_test_flag64(iaxs[fr->callno], IAX_CODEC_NOCAP)) {
10890                               ast_log(LOG_NOTICE, "Rejected connect attempt from %s, requested '%s' incompatible with our capability '%s'.\n",
10891                                  ast_inet_ntoa(sin.sin_addr),
10892                                  iax2_getformatname_multiple(tmp, sizeof(tmp), iaxs[fr->callno]->peerformat),
10893                                  iax2_getformatname_multiple(tmp2, sizeof(tmp2), iaxs[fr->callno]->capability));
10894                            } else {
10895                               ast_log(LOG_NOTICE, "Rejected connect attempt from %s, requested/capability '%s'/'%s' incompatible with our capability '%s'.\n",
10896                                  ast_inet_ntoa(sin.sin_addr),
10897                                  iax2_getformatname_multiple(tmp, sizeof(tmp), iaxs[fr->callno]->peerformat),
10898                                  iax2_getformatname_multiple(tmp2, sizeof(tmp2), iaxs[fr->callno]->peercapability),
10899                                  iax2_getformatname_multiple(tmp3, sizeof(tmp3), iaxs[fr->callno]->capability));
10900                            }
10901                         }
10902                      } else {
10903                         /* Pick one... */
10904                         if(ast_test_flag64(iaxs[fr->callno], IAX_CODEC_NOCAP)) {
10905                            if(!(iaxs[fr->callno]->peerformat & iaxs[fr->callno]->capability))
10906                               format = 0;
10907                         } else {
10908                            if(ast_test_flag64(iaxs[fr->callno], IAX_CODEC_NOPREFS)) {
10909                               using_prefs = ast_test_flag64(iaxs[fr->callno], IAX_CODEC_NOCAP) ? "reqonly" : "disabled";
10910                               memset(&pref, 0, sizeof(pref));
10911                               format = iax2_best_codec(iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability);
10912                               strcpy(caller_pref_buf,"disabled");
10913                               strcpy(host_pref_buf,"disabled");
10914                            } else {
10915                               struct ast_format tmpfmt;
10916                               using_prefs = "mine";
10917                               if (ast_codec_pref_index(&iaxs[fr->callno]->rprefs, 0, &tmpfmt)) {
10918                                  /* Do the opposite of what we tried above. */
10919                                  if (ast_test_flag64(iaxs[fr->callno], IAX_CODEC_USER_FIRST)) {
10920                                     pref = iaxs[fr->callno]->prefs;
10921                                  } else {
10922                                     pref = iaxs[fr->callno]->rprefs;
10923                                     using_prefs = "caller";
10924                                  }
10925                                  format = iax2_codec_choose(&pref, iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability, 1);
10926                               } else /* if no codec_prefs IE do it the old way */
10927                                  format = iax2_best_codec(iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability);
10928                            }
10929                         }
10930 
10931                         if (!format) {
10932                            char tmp[256], tmp2[256], tmp3[256];
10933                            memset(&ied0, 0, sizeof(ied0));
10934                            iax_ie_append_str(&ied0, IAX_IE_CAUSE, "Unable to negotiate codec");
10935                            iax_ie_append_byte(&ied0, IAX_IE_CAUSECODE, AST_CAUSE_BEARERCAPABILITY_NOTAVAIL);
10936                            ast_log(LOG_ERROR, "No best format in '%s'???\n", iax2_getformatname_multiple(tmp, sizeof(tmp), iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability));
10937                            send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
10938                            if (!iaxs[fr->callno]) {
10939                               break;
10940                            }
10941                            if (authdebug) {
10942                               ast_log(LOG_NOTICE, "Rejected connect attempt from %s, requested/capability '%s'/'%s' incompatible with our capability '%s'.\n",
10943                                  ast_inet_ntoa(sin.sin_addr),
10944                                  iax2_getformatname_multiple(tmp, sizeof(tmp), iaxs[fr->callno]->peerformat),
10945                                  iax2_getformatname_multiple(tmp2, sizeof(tmp2), iaxs[fr->callno]->peercapability),
10946                                  iax2_getformatname_multiple(tmp3, sizeof(tmp3), iaxs[fr->callno]->capability));
10947                            }
10948                            ast_set_flag64(iaxs[fr->callno], IAX_ALREADYGONE);
10949                            break;
10950                         }
10951                      }
10952                   }
10953                   if (format) {
10954                      /* No authentication required, let them in */
10955                      memset(&ied1, 0, sizeof(ied1));
10956                      iax_ie_append_int(&ied1, IAX_IE_FORMAT, format);
10957                      iax_ie_append_versioned_uint64(&ied1, IAX_IE_FORMAT2, 0, format);
10958                      send_command(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACCEPT, 0, ied1.buf, ied1.pos, -1);
10959                      if (strcmp(iaxs[fr->callno]->exten, "TBD")) {
10960                         ast_set_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED);
10961                         ast_verb(3, "Accepting UNAUTHENTICATED call from %s:\n"
10962                                     "%srequested format = %s,\n"
10963                                     "%srequested prefs = %s,\n"
10964                                     "%sactual format = %s,\n"
10965                                     "%shost prefs = %s,\n"
10966                                     "%spriority = %s\n",
10967                                     ast_inet_ntoa(sin.sin_addr), 
10968                                     VERBOSE_PREFIX_4,
10969                                     iax2_getformatname(iaxs[fr->callno]->peerformat), 
10970                                     VERBOSE_PREFIX_4,
10971                                     caller_pref_buf,
10972                                     VERBOSE_PREFIX_4,
10973                                     iax2_getformatname(format), 
10974                                     VERBOSE_PREFIX_4,
10975                                     host_pref_buf, 
10976                                     VERBOSE_PREFIX_4,
10977                                     using_prefs);
10978 
10979                         iaxs[fr->callno]->chosenformat = format;
10980 
10981                         /* Since this is a new call, we should go ahead and set the callid for it. */
10982                         iax_pvt_callid_new(fr->callno);
10983                         ast_set_flag64(iaxs[fr->callno], IAX_DELAYPBXSTART);
10984                      } else {
10985                         ast_set_flag(&iaxs[fr->callno]->state, IAX_STATE_TBD);
10986                         /* If this is a TBD call, we're ready but now what...  */
10987                         ast_verb(3, "Accepted unauthenticated TBD call from %s\n", ast_inet_ntoa(sin.sin_addr));
10988                      }
10989                   }
10990                }
10991                break;
10992             }
10993             if (iaxs[fr->callno]->authmethods & IAX_AUTH_MD5)
10994                merge_encryption(iaxs[fr->callno],ies.encmethods);
10995             else
10996                iaxs[fr->callno]->encmethods = 0;
10997             if (!authenticate_request(fr->callno) && iaxs[fr->callno])
10998                ast_set_flag(&iaxs[fr->callno]->state, IAX_STATE_AUTHENTICATED);
10999             break;
11000          case IAX_COMMAND_DPREQ:
11001             /* Request status in the dialplan */
11002             if (ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_TBD) &&
11003                !ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED) && ies.called_number) {
11004                if (iaxcompat) {
11005                   /* Spawn a thread for the lookup */
11006                   spawn_dp_lookup(fr->callno, iaxs[fr->callno]->context, ies.called_number, iaxs[fr->callno]->cid_num);
11007                } else {
11008                   /* Just look it up */
11009                   dp_lookup(fr->callno, iaxs[fr->callno]->context, ies.called_number, iaxs[fr->callno]->cid_num, 1);
11010                }
11011             }
11012             break;
11013          case IAX_COMMAND_HANGUP:
11014             ast_set_flag64(iaxs[fr->callno], IAX_ALREADYGONE);
11015             ast_debug(1, "Immediately destroying %d, having received hangup\n", fr->callno);
11016             /* Set hangup cause according to remote and hangupsource */
11017             if (iaxs[fr->callno]->owner) {
11018                set_hangup_source_and_cause(fr->callno, ies.causecode);
11019                if (!iaxs[fr->callno]) {
11020                   break;
11021                }
11022             }
11023 
11024             /* Send ack immediately, before we destroy */
11025             send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
11026             iax2_destroy(fr->callno);
11027             break;
11028          case IAX_COMMAND_REJECT:
11029             /* Set hangup cause according to remote and hangup source */
11030             if (iaxs[fr->callno]->owner) {
11031                set_hangup_source_and_cause(fr->callno, ies.causecode);
11032                if (!iaxs[fr->callno]) {
11033                   break;
11034                }
11035             }
11036 
11037             if (!ast_test_flag64(iaxs[fr->callno], IAX_PROVISION)) {
11038                if (iaxs[fr->callno]->owner && authdebug)
11039                   ast_log(LOG_WARNING, "Call rejected by %s: %s\n",
11040                      ast_inet_ntoa(iaxs[fr->callno]->addr.sin_addr),
11041                      ies.cause ? ies.cause : "<Unknown>");
11042                ast_debug(1, "Immediately destroying %d, having received reject\n",
11043                   fr->callno);
11044             }
11045             /* Send ack immediately, before we destroy */
11046             send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK,
11047                          fr->ts, NULL, 0, fr->iseqno);
11048             if (!ast_test_flag64(iaxs[fr->callno], IAX_PROVISION))
11049                iaxs[fr->callno]->error = EPERM;
11050             iax2_destroy(fr->callno);
11051             break;
11052          case IAX_COMMAND_TRANSFER:
11053          {
11054             struct ast_channel *bridged_chan;
11055             struct ast_channel *owner;
11056 
11057             iax2_lock_owner(fr->callno);
11058             if (!iaxs[fr->callno]) {
11059                /* Initiating call went away before we could transfer. */
11060                break;
11061             }
11062             owner = iaxs[fr->callno]->owner;
11063             bridged_chan = owner ? ast_bridged_channel(owner) : NULL;
11064             if (bridged_chan && ies.called_number) {
11065                const char *context;
11066 
11067                context = ast_strdupa(iaxs[fr->callno]->context);
11068 
11069                ast_channel_ref(owner);
11070                ast_channel_ref(bridged_chan);
11071                ast_channel_unlock(owner);
11072                ast_mutex_unlock(&iaxsl[fr->callno]);
11073 
11074                /* Set BLINDTRANSFER channel variables */
11075                pbx_builtin_setvar_helper(owner, "BLINDTRANSFER", ast_channel_name(bridged_chan));
11076                pbx_builtin_setvar_helper(bridged_chan, "BLINDTRANSFER", ast_channel_name(owner));
11077 
11078                /* DO NOT hold any locks while calling ast_parking_ext_valid() */
11079                if (ast_parking_ext_valid(ies.called_number, owner, context)) {
11080                   ast_debug(1, "Parking call '%s'\n", ast_channel_name(bridged_chan));
11081                   if (iax_park(bridged_chan, owner, ies.called_number, context)) {
11082                      ast_log(LOG_WARNING, "Failed to park call '%s'\n",
11083                         ast_channel_name(bridged_chan));
11084                   }
11085                } else {
11086                   if (ast_async_goto(bridged_chan, context, ies.called_number, 1)) {
11087                      ast_log(LOG_WARNING,
11088                         "Async goto of '%s' to '%s@%s' failed\n",
11089                         ast_channel_name(bridged_chan), ies.called_number, context);
11090                   } else {
11091                      ast_debug(1, "Async goto of '%s' to '%s@%s' started\n",
11092                         ast_channel_name(bridged_chan), ies.called_number, context);
11093                   }
11094                }
11095                ast_channel_unref(owner);
11096                ast_channel_unref(bridged_chan);
11097 
11098                ast_mutex_lock(&iaxsl[fr->callno]);
11099             } else {
11100                ast_debug(1, "Async goto not applicable on call %d\n", fr->callno);
11101                if (owner) {
11102                   ast_channel_unlock(owner);
11103                }
11104             }
11105 
11106             break;
11107          }
11108          case IAX_COMMAND_ACCEPT:
11109             /* Ignore if call is already up or needs authentication or is a TBD */
11110             if (ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED | IAX_STATE_TBD | IAX_STATE_AUTHENTICATED))
11111                break;
11112             if (ast_test_flag64(iaxs[fr->callno], IAX_PROVISION)) {
11113                /* Send ack immediately, before we destroy */
11114                send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
11115                iax2_destroy(fr->callno);
11116                break;
11117             }
11118             if (ies.format) {
11119                iaxs[fr->callno]->peerformat = ies.format;
11120             } else {
11121                if (iaxs[fr->callno]->owner)
11122                   iaxs[fr->callno]->peerformat = ast_format_cap_to_old_bitfield(ast_channel_nativeformats(iaxs[fr->callno]->owner));
11123                else
11124                   iaxs[fr->callno]->peerformat = iaxs[fr->callno]->capability;
11125             }
11126             ast_verb(3, "Call accepted by %s (format %s)\n", ast_inet_ntoa(iaxs[fr->callno]->addr.sin_addr), iax2_getformatname(iaxs[fr->callno]->peerformat));
11127             if (!(iaxs[fr->callno]->peerformat & iaxs[fr->callno]->capability)) {
11128                memset(&ied0, 0, sizeof(ied0));
11129                iax_ie_append_str(&ied0, IAX_IE_CAUSE, "Unable to negotiate codec");
11130                iax_ie_append_byte(&ied0, IAX_IE_CAUSECODE, AST_CAUSE_BEARERCAPABILITY_NOTAVAIL);
11131                send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
11132                if (!iaxs[fr->callno]) {
11133                   break;
11134                }
11135                if (authdebug) {
11136                   char tmp1[256], tmp2[256];
11137                   ast_log(LOG_NOTICE, "Rejected call to %s, format %s incompatible with our capability %s.\n",
11138                      ast_inet_ntoa(sin.sin_addr),
11139                      iax2_getformatname_multiple(tmp1, sizeof(tmp1), iaxs[fr->callno]->peerformat),
11140                      iax2_getformatname_multiple(tmp2, sizeof(tmp2), iaxs[fr->callno]->capability));
11141                }
11142             } else {
11143                ast_set_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED);
11144                iax2_lock_owner(fr->callno);
11145                if (iaxs[fr->callno] && iaxs[fr->callno]->owner) {
11146                   char tmp[256];
11147                   /* Switch us to use a compatible format */
11148                   ast_format_cap_from_old_bitfield(ast_channel_nativeformats(iaxs[fr->callno]->owner), iaxs[fr->callno]->peerformat);
11149                   ast_verb(3, "Format for call is %s\n", ast_getformatname_multiple(tmp, sizeof(tmp), ast_channel_nativeformats(iaxs[fr->callno]->owner)));
11150 
11151                   /* Setup read/write formats properly. */
11152                   if (ast_channel_writeformat(iaxs[fr->callno]->owner)->id)
11153                      ast_set_write_format(iaxs[fr->callno]->owner, ast_channel_writeformat(iaxs[fr->callno]->owner));
11154                   if (ast_channel_readformat(iaxs[fr->callno]->owner)->id)
11155                      ast_set_read_format(iaxs[fr->callno]->owner, ast_channel_readformat(iaxs[fr->callno]->owner));
11156                   ast_channel_unlock(iaxs[fr->callno]->owner);
11157                }
11158             }
11159             if (iaxs[fr->callno]) {
11160                AST_LIST_LOCK(&dpcache);
11161                AST_LIST_TRAVERSE(&iaxs[fr->callno]->dpentries, dp, peer_list)
11162                   if (!(dp->flags & CACHE_FLAG_TRANSMITTED))
11163                      iax2_dprequest(dp, fr->callno);
11164                AST_LIST_UNLOCK(&dpcache);
11165             }
11166             break;
11167          case IAX_COMMAND_POKE:
11168             /* Send back a pong packet with the original timestamp */
11169             send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_PONG, fr->ts, NULL, 0, -1);
11170             break;
11171          case IAX_COMMAND_PING:
11172          {
11173             struct iax_ie_data pingied;
11174             construct_rr(iaxs[fr->callno], &pingied);
11175             /* Send back a pong packet with the original timestamp */
11176             send_command(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_PONG, fr->ts, pingied.buf, pingied.pos, -1);
11177          }
11178             break;
11179          case IAX_COMMAND_PONG:
11180             /* Calculate ping time */
11181             iaxs[fr->callno]->pingtime =  calc_timestamp(iaxs[fr->callno], 0, &f) - fr->ts;
11182             /* save RR info */
11183             save_rr(fr, &ies);
11184 
11185             /* Good time to write jb stats for this call */
11186             log_jitterstats(fr->callno);
11187 
11188             if (iaxs[fr->callno]->peerpoke) {
11189                peer = iaxs[fr->callno]->peerpoke;
11190                if ((peer->lastms < 0)  || (peer->historicms > peer->maxms)) {
11191                   if (iaxs[fr->callno]->pingtime <= peer->maxms) {
11192                      ast_log(LOG_NOTICE, "Peer '%s' is now REACHABLE! Time: %d\n", peer->name, iaxs[fr->callno]->pingtime);
11193                      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); 
11194                      ast_devstate_changed(AST_DEVICE_NOT_INUSE, AST_DEVSTATE_CACHABLE, "IAX2/%s", peer->name); /* Activate notification */
11195                   }
11196                } else if ((peer->historicms > 0) && (peer->historicms <= peer->maxms)) {
11197                   if (iaxs[fr->callno]->pingtime > peer->maxms) {
11198                      ast_log(LOG_NOTICE, "Peer '%s' is now TOO LAGGED (%d ms)!\n", peer->name, iaxs[fr->callno]->pingtime);
11199                      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); 
11200                      ast_devstate_changed(AST_DEVICE_UNAVAILABLE, AST_DEVSTATE_CACHABLE, "IAX2/%s", peer->name); /* Activate notification */
11201                   }
11202                }
11203                peer->lastms = iaxs[fr->callno]->pingtime;
11204                if (peer->smoothing && (peer->lastms > -1))
11205                   peer->historicms = (iaxs[fr->callno]->pingtime + peer->historicms) / 2;
11206                else if (peer->smoothing && peer->lastms < 0)
11207                   peer->historicms = (0 + peer->historicms) / 2;
11208                else              
11209                   peer->historicms = iaxs[fr->callno]->pingtime;
11210 
11211                /* Remove scheduled iax2_poke_noanswer */
11212                if (peer->pokeexpire > -1) {
11213                   if (!AST_SCHED_DEL(sched, peer->pokeexpire)) {
11214                      peer_unref(peer);
11215                      peer->pokeexpire = -1;
11216                   }
11217                }
11218                /* Schedule the next cycle */
11219                if ((peer->lastms < 0)  || (peer->historicms > peer->maxms))
11220                   peer->pokeexpire = iax2_sched_add(sched, peer->pokefreqnotok, iax2_poke_peer_s, peer_ref(peer));
11221                else
11222                   peer->pokeexpire = iax2_sched_add(sched, peer->pokefreqok, iax2_poke_peer_s, peer_ref(peer));
11223                if (peer->pokeexpire == -1)
11224                   peer_unref(peer);
11225                /* and finally send the ack */
11226                send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
11227                /* And wrap up the qualify call */
11228                iax2_destroy(fr->callno);
11229                peer->callno = 0;
11230                ast_debug(1, "Peer %s: got pong, lastms %d, historicms %d, maxms %d\n", peer->name, peer->lastms, peer->historicms, peer->maxms);
11231             }
11232             break;
11233          case IAX_COMMAND_LAGRQ:
11234          case IAX_COMMAND_LAGRP:
11235             f.src = "LAGRQ";
11236             f.mallocd = 0;
11237             f.offset = 0;
11238             f.samples = 0;
11239             iax_frame_wrap(fr, &f);
11240             if (f.subclass.integer == IAX_COMMAND_LAGRQ) {
11241                /* Received a LAGRQ - echo back a LAGRP */
11242                fr->af.subclass.integer = IAX_COMMAND_LAGRP;
11243                iax2_send(iaxs[fr->callno], &fr->af, fr->ts, -1, 0, 0, 0);
11244             } else {
11245                /* Received LAGRP in response to our LAGRQ */
11246                unsigned int ts;
11247                /* This is a reply we've been given, actually measure the difference */
11248                ts = calc_timestamp(iaxs[fr->callno], 0, &fr->af);
11249                iaxs[fr->callno]->lag = ts - fr->ts;
11250                if (iaxdebug)
11251                   ast_debug(1, "Peer %s lag measured as %dms\n",
11252                      ast_inet_ntoa(iaxs[fr->callno]->addr.sin_addr), iaxs[fr->callno]->lag);
11253             }
11254             break;
11255          case IAX_COMMAND_AUTHREQ:
11256             if (ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED | IAX_STATE_TBD)) {
11257                ast_log(LOG_WARNING, "Call on %s is already up, can't start on it\n", iaxs[fr->callno]->owner ? ast_channel_name(iaxs[fr->callno]->owner) : "<Unknown>");
11258                break;
11259             }
11260             if (authenticate_reply(iaxs[fr->callno], &iaxs[fr->callno]->addr, &ies, iaxs[fr->callno]->secret, iaxs[fr->callno]->outkey)) {
11261                struct ast_frame hangup_fr = { .frametype = AST_FRAME_CONTROL,
11262                         .subclass.integer = AST_CONTROL_HANGUP,
11263                };
11264                ast_log(LOG_WARNING, 
11265                   "I don't know how to authenticate %s to %s\n", 
11266                   ies.username ? ies.username : "<unknown>", ast_inet_ntoa(iaxs[fr->callno]->addr.sin_addr));
11267                iax2_queue_frame(fr->callno, &hangup_fr);
11268             }
11269             break;
11270          case IAX_COMMAND_AUTHREP:
11271             /* For security, always ack immediately */
11272             if (delayreject)
11273                send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
11274             /* Ignore once we've started */
11275             if (ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED | IAX_STATE_TBD)) {
11276                ast_log(LOG_WARNING, "Call on %s is already up, can't start on it\n", iaxs[fr->callno]->owner ? ast_channel_name(iaxs[fr->callno]->owner) : "<Unknown>");
11277                break;
11278             }
11279             if (authenticate_verify(iaxs[fr->callno], &ies)) {
11280                if (authdebug)
11281                   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);
11282                memset(&ied0, 0, sizeof(ied0));
11283                auth_fail(fr->callno, IAX_COMMAND_REJECT);
11284                break;
11285             }
11286             if (strcasecmp(iaxs[fr->callno]->exten, "TBD")) {
11287                /* This might re-enter the IAX code and need the lock */
11288                exists = ast_exists_extension(NULL, iaxs[fr->callno]->context, iaxs[fr->callno]->exten, 1, iaxs[fr->callno]->cid_num);
11289             } else
11290                exists = 0;
11291             if (strcmp(iaxs[fr->callno]->exten, "TBD") && !exists) {
11292                if (authdebug)
11293                   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);
11294                memset(&ied0, 0, sizeof(ied0));
11295                iax_ie_append_str(&ied0, IAX_IE_CAUSE, "No such context/extension");
11296                iax_ie_append_byte(&ied0, IAX_IE_CAUSECODE, AST_CAUSE_NO_ROUTE_DESTINATION);
11297                send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
11298                if (!iaxs[fr->callno]) {
11299                   break;
11300                }
11301             } else {
11302                /* Select an appropriate format */
11303                if(ast_test_flag64(iaxs[fr->callno], IAX_CODEC_NOPREFS)) {
11304                   if(ast_test_flag64(iaxs[fr->callno], IAX_CODEC_NOCAP)) {
11305                      using_prefs = "reqonly";
11306                   } else {
11307                      using_prefs = "disabled";
11308                   }
11309                   format = iaxs[fr->callno]->peerformat & iaxs[fr->callno]->capability;
11310                   memset(&pref, 0, sizeof(pref));
11311                   strcpy(caller_pref_buf, "disabled");
11312                   strcpy(host_pref_buf, "disabled");
11313                } else {
11314                   struct ast_format tmpfmt;
11315                   using_prefs = "mine";
11316                   if (ies.codec_prefs)
11317                      ast_codec_pref_convert(&iaxs[fr->callno]->rprefs, ies.codec_prefs, 32, 0);
11318                   if (ast_codec_pref_index(&iaxs[fr->callno]->rprefs, 0, &tmpfmt)) {
11319                      if (ast_test_flag64(iaxs[fr->callno], IAX_CODEC_USER_FIRST)) {
11320                         pref = iaxs[fr->callno]->rprefs;
11321                         using_prefs = "caller";
11322                      } else {
11323                         pref = iaxs[fr->callno]->prefs;
11324                      }
11325                   } else /* if no codec_prefs IE do it the old way */
11326                      pref = iaxs[fr->callno]->prefs;
11327                   format = iax2_codec_choose(&pref, iaxs[fr->callno]->capability & iaxs[fr->callno]->peercapability, 0);
11328                   ast_codec_pref_string(&iaxs[fr->callno]->rprefs, caller_pref_buf, sizeof(caller_pref_buf) - 1);
11329                   ast_codec_pref_string(&iaxs[fr->callno]->prefs, host_pref_buf, sizeof(host_pref_buf) - 1);
11330                }
11331                if (!format) {
11332                   char tmp1[256], tmp2[256], tmp3[256];
11333                   if(!ast_test_flag64(iaxs[fr->callno], IAX_CODEC_NOCAP)) {
11334                      ast_debug(1, "We don't do requested format %s, falling back to peer capability '%s'\n",
11335                         iax2_getformatname(iaxs[fr->callno]->peerformat),
11336                         iax2_getformatname_multiple(tmp1, sizeof(tmp1), iaxs[fr->callno]->peercapability));
11337                      format = iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability;
11338                   }
11339                   if (!format) {
11340                      if (authdebug) {
11341                         if (ast_test_flag64(iaxs[fr->callno], IAX_CODEC_NOCAP)) {
11342                            ast_log(LOG_NOTICE, "Rejected connect attempt from %s, requested '%s' incompatible with our capability '%s'.\n", ast_inet_ntoa(sin.sin_addr),
11343                               iax2_getformatname_multiple(tmp1, sizeof(tmp1), iaxs[fr->callno]->peerformat),
11344                               iax2_getformatname_multiple(tmp2, sizeof(tmp2), iaxs[fr->callno]->capability));
11345                         } else {
11346                            ast_log(LOG_NOTICE, "Rejected connect attempt from %s, requested/capability '%s'/'%s' incompatible with our capability '%s'.\n",
11347                               ast_inet_ntoa(sin.sin_addr),
11348                               iax2_getformatname_multiple(tmp1, sizeof(tmp1), iaxs[fr->callno]->peerformat),
11349                               iax2_getformatname_multiple(tmp2, sizeof(tmp2), iaxs[fr->callno]->peercapability),
11350                               iax2_getformatname_multiple(tmp3, sizeof(tmp3), iaxs[fr->callno]->capability));
11351                         }
11352                      }
11353                      memset(&ied0, 0, sizeof(ied0));
11354                      iax_ie_append_str(&ied0, IAX_IE_CAUSE, "Unable to negotiate codec");
11355                      iax_ie_append_byte(&ied0, IAX_IE_CAUSECODE, AST_CAUSE_BEARERCAPABILITY_NOTAVAIL);
11356                      send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
11357                      if (!iaxs[fr->callno]) {
11358                         break;
11359                      }
11360                   } else {
11361                      /* Pick one... */
11362                      if(ast_test_flag64(iaxs[fr->callno], IAX_CODEC_NOCAP)) {
11363                         if(!(iaxs[fr->callno]->peerformat & iaxs[fr->callno]->capability))
11364                            format = 0;
11365                      } else {
11366                         if(ast_test_flag64(iaxs[fr->callno], IAX_CODEC_NOPREFS)) {
11367                            using_prefs = ast_test_flag64(iaxs[fr->callno], IAX_CODEC_NOCAP) ? "reqonly" : "disabled";
11368                            memset(&pref, 0, sizeof(pref));
11369                            format = ast_test_flag64(iaxs[fr->callno], IAX_CODEC_NOCAP) ?
11370                               iaxs[fr->callno]->peerformat : iax2_best_codec(iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability);
11371                            strcpy(caller_pref_buf,"disabled");
11372                            strcpy(host_pref_buf,"disabled");
11373                         } else {
11374                            struct ast_format tmpfmt;
11375                            using_prefs = "mine";
11376                            if (ast_codec_pref_index(&iaxs[fr->callno]->rprefs, 0, &tmpfmt)) {
11377                               /* Do the opposite of what we tried above. */
11378                               if (ast_test_flag64(iaxs[fr->callno], IAX_CODEC_USER_FIRST)) {
11379                                  pref = iaxs[fr->callno]->prefs;
11380                               } else {
11381                                  pref = iaxs[fr->callno]->rprefs;
11382                                  using_prefs = "caller";
11383                               }
11384                               format = iax2_codec_choose(&pref, iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability, 1);
11385                            } else /* if no codec_prefs IE do it the old way */
11386                               format = iax2_best_codec(iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability);   
11387                         }
11388                      }
11389                      if (!format) {
11390                         char tmp1[256], tmp2[256], tmp3[256];
11391                         ast_log(LOG_ERROR, "No best format in %s???\n",
11392                            iax2_getformatname_multiple(tmp1, sizeof(tmp1), iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability));
11393                         if (authdebug) {
11394                            if (ast_test_flag64(iaxs[fr->callno], IAX_CODEC_NOCAP)) {
11395                               ast_log(LOG_NOTICE, "Rejected connect attempt from %s, requested '%s' incompatible with our capability '%s'.\n",
11396                                  ast_inet_ntoa(sin.sin_addr),
11397                                  iax2_getformatname_multiple(tmp1, sizeof(tmp1), iaxs[fr->callno]->peerformat),
11398                                  iax2_getformatname_multiple(tmp2, sizeof(tmp2), iaxs[fr->callno]->capability));
11399                            } else {
11400                               ast_log(LOG_NOTICE, "Rejected connect attempt from %s, requested/capability '%s'/'%s' incompatible with our capability '%s'.\n",
11401                                  ast_inet_ntoa(sin.sin_addr),
11402                                  iax2_getformatname_multiple(tmp1, sizeof(tmp1), iaxs[fr->callno]->peerformat),
11403                                  iax2_getformatname_multiple(tmp2, sizeof(tmp2), iaxs[fr->callno]->peercapability),
11404                                  iax2_getformatname_multiple(tmp3, sizeof(tmp3), iaxs[fr->callno]->capability));
11405                            }
11406                         }
11407                         memset(&ied0, 0, sizeof(ied0));
11408                         iax_ie_append_str(&ied0, IAX_IE_CAUSE, "Unable to negotiate codec");
11409                         iax_ie_append_byte(&ied0, IAX_IE_CAUSECODE, AST_CAUSE_BEARERCAPABILITY_NOTAVAIL);
11410                         send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
11411                         if (!iaxs[fr->callno]) {
11412                            break;
11413                         }
11414                      }
11415                   }
11416                }
11417                if (format) {
11418                   /* Authentication received */
11419                   memset(&ied1, 0, sizeof(ied1));
11420                   iax_ie_append_int(&ied1, IAX_IE_FORMAT, format);
11421                   iax_ie_append_versioned_uint64(&ied1, IAX_IE_FORMAT2, 0, format);
11422                   send_command(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACCEPT, 0, ied1.buf, ied1.pos, -1);
11423                   if (strcmp(iaxs[fr->callno]->exten, "TBD")) {
11424                      ast_set_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED);
11425                      ast_verb(3, "Accepting AUTHENTICATED call from %s:\n"
11426                                  "%srequested format = %s,\n"
11427                                  "%srequested prefs = %s,\n"
11428                                  "%sactual format = %s,\n"
11429                                  "%shost prefs = %s,\n"
11430                                  "%spriority = %s\n", 
11431                                  ast_inet_ntoa(sin.sin_addr), 
11432                                  VERBOSE_PREFIX_4,
11433                                  iax2_getformatname(iaxs[fr->callno]->peerformat),
11434                                  VERBOSE_PREFIX_4,
11435                                  caller_pref_buf,
11436                                  VERBOSE_PREFIX_4,
11437                                  iax2_getformatname(format),
11438                                  VERBOSE_PREFIX_4,
11439                                  host_pref_buf,
11440                                  VERBOSE_PREFIX_4,
11441                                  using_prefs);
11442 
11443                      ast_set_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED);
11444                      if (!(c = ast_iax2_new(fr->callno, AST_STATE_RING, format, NULL, 1)))
11445                         iax2_destroy(fr->callno);
11446                      else if (ies.vars) {
11447                         struct ast_datastore *variablestore;
11448                         struct ast_variable *var, *prev = NULL;
11449                         AST_LIST_HEAD(, ast_var_t) *varlist;
11450                         varlist = ast_calloc(1, sizeof(*varlist));
11451                         variablestore = ast_datastore_alloc(&iax2_variable_datastore_info, NULL);
11452                         if (variablestore && varlist) {
11453                            variablestore->data = varlist;
11454                            variablestore->inheritance = DATASTORE_INHERIT_FOREVER;
11455                            AST_LIST_HEAD_INIT(varlist);
11456                            ast_debug(1, "I can haz IAX vars? w00t\n");
11457                            for (var = ies.vars; var; var = var->next) {
11458                               struct ast_var_t *newvar = ast_var_assign(var->name, var->value);
11459                               if (prev)
11460                                  ast_free(prev);
11461                               prev = var;
11462                               if (!newvar) {
11463                                  /* Don't abort list traversal, as this would leave ies.vars in an inconsistent state. */
11464                                  ast_log(LOG_ERROR, "Memory allocation error while processing IAX2 variables\n");
11465                               } else {
11466                                  AST_LIST_INSERT_TAIL(varlist, newvar, entries);
11467                               }
11468                            }
11469                            if (prev)
11470                               ast_free(prev);
11471                            ies.vars = NULL;
11472                            ast_channel_datastore_add(c, variablestore);
11473                         } else {
11474                            ast_log(LOG_ERROR, "Memory allocation error while processing IAX2 variables\n");
11475                            if (variablestore)
11476                               ast_datastore_free(variablestore);
11477                            if (varlist)
11478                               ast_free(varlist);
11479                         }
11480                      }
11481                   } else {
11482                      ast_set_flag(&iaxs[fr->callno]->state, IAX_STATE_TBD);
11483                      /* If this is a TBD call, we're ready but now what...  */
11484                      ast_verb(3, "Accepted AUTHENTICATED TBD call from %s\n", ast_inet_ntoa(sin.sin_addr));
11485                      if (ast_test_flag64(iaxs[fr->callno], IAX_IMMEDIATE)) {
11486                         goto immediatedial;
11487                      }
11488                   }
11489                }
11490             }
11491             break;
11492          case IAX_COMMAND_DIAL:
11493 immediatedial:
11494             if (ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_TBD)) {
11495                ast_clear_flag(&iaxs[fr->callno]->state, IAX_STATE_TBD);
11496                ast_string_field_set(iaxs[fr->callno], exten, ies.called_number ? ies.called_number : "s");
11497                if (!ast_exists_extension(NULL, iaxs[fr->callno]->context, iaxs[fr->callno]->exten, 1, iaxs[fr->callno]->cid_num)) {
11498                   if (authdebug)
11499                      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);
11500                   memset(&ied0, 0, sizeof(ied0));
11501                   iax_ie_append_str(&ied0, IAX_IE_CAUSE, "No such context/extension");
11502                   iax_ie_append_byte(&ied0, IAX_IE_CAUSECODE, AST_CAUSE_NO_ROUTE_DESTINATION);
11503                   send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
11504                   if (!iaxs[fr->callno]) {
11505                      break;
11506                   }
11507                } else {
11508                   char tmp[256];
11509                   ast_set_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED);
11510                   ast_verb(3, "Accepting DIAL from %s, formats = %s\n",
11511                      ast_inet_ntoa(sin.sin_addr),
11512                      iax2_getformatname_multiple(tmp, sizeof(tmp), iaxs[fr->callno]->peerformat));
11513                   ast_set_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED);
11514                   send_command(iaxs[fr->callno], AST_FRAME_CONTROL, AST_CONTROL_PROGRESS, 0, NULL, 0, -1);
11515                   if (!(c = ast_iax2_new(fr->callno, AST_STATE_RING, iaxs[fr->callno]->peerformat, NULL, 1)))
11516                      iax2_destroy(fr->callno);
11517                   else if (ies.vars) {
11518                      struct ast_datastore *variablestore;
11519                      struct ast_variable *var, *prev = NULL;
11520                      AST_LIST_HEAD(, ast_var_t) *varlist;
11521                      varlist = ast_calloc(1, sizeof(*varlist));
11522                      variablestore = ast_datastore_alloc(&iax2_variable_datastore_info, NULL);
11523                      ast_debug(1, "I can haz IAX vars? w00t\n");
11524                      if (variablestore && varlist) {
11525                         variablestore->data = varlist;
11526                         variablestore->inheritance = DATASTORE_INHERIT_FOREVER;
11527                         AST_LIST_HEAD_INIT(varlist);
11528                         for (var = ies.vars; var; var = var->next) {
11529                            struct ast_var_t *newvar = ast_var_assign(var->name, var->value);
11530                            if (prev)
11531                               ast_free(prev);
11532                            prev = var;
11533                            if (!newvar) {
11534                               /* Don't abort list traversal, as this would leave ies.vars in an inconsistent state. */
11535                               ast_log(LOG_ERROR, "Memory allocation error while processing IAX2 variables\n");
11536                            } else {
11537                               AST_LIST_INSERT_TAIL(varlist, newvar, entries);
11538                            }
11539                         }
11540                         if (prev)
11541                            ast_free(prev);
11542                         ies.vars = NULL;
11543                         ast_channel_datastore_add(c, variablestore);
11544                      } else {
11545                         ast_log(LOG_ERROR, "Memory allocation error while processing IAX2 variables\n");
11546                         if (variablestore)
11547                            ast_datastore_free(variablestore);
11548                         if (varlist)
11549                            ast_free(varlist);
11550                      }
11551                   }
11552                }
11553             }
11554             break;
11555          case IAX_COMMAND_INVAL:
11556             iaxs[fr->callno]->error = ENOTCONN;
11557             ast_debug(1, "Immediately destroying %d, having received INVAL\n", fr->callno);
11558             iax2_destroy(fr->callno);
11559             ast_debug(1, "Destroying call %d\n", fr->callno);
11560             break;
11561          case IAX_COMMAND_VNAK:
11562             ast_debug(1, "Received VNAK: resending outstanding frames\n");
11563             /* Force retransmission */
11564             vnak_retransmit(fr->callno, fr->iseqno);
11565             break;
11566          case IAX_COMMAND_REGREQ:
11567          case IAX_COMMAND_REGREL:
11568             /* For security, always ack immediately */
11569             if (delayreject)
11570                send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
11571             if (register_verify(fr->callno, &sin, &ies)) {
11572                if (!iaxs[fr->callno]) {
11573                   break;
11574                }
11575                /* Send delayed failure */
11576                auth_fail(fr->callno, IAX_COMMAND_REGREJ);
11577                break;
11578             }
11579             if (!iaxs[fr->callno]) {
11580                break;
11581             }
11582             if ((ast_strlen_zero(iaxs[fr->callno]->secret) && ast_strlen_zero(iaxs[fr->callno]->inkeys)) ||
11583                   ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_AUTHENTICATED)) {
11584 
11585                if (f.subclass.integer == IAX_COMMAND_REGREL) {
11586                   memset(&sin, 0, sizeof(sin));
11587                   sin.sin_family = AF_INET;
11588                }
11589                if (update_registry(&sin, fr->callno, ies.devicetype, fd, ies.refresh)) {
11590                   ast_log(LOG_WARNING, "Registry error\n");
11591                }
11592                if (!iaxs[fr->callno]) {
11593                   break;
11594                }
11595                if (ies.provverpres && ies.serviceident && sin.sin_addr.s_addr) {
11596                   ast_mutex_unlock(&iaxsl[fr->callno]);
11597                   check_provisioning(&sin, fd, ies.serviceident, ies.provver);
11598                   ast_mutex_lock(&iaxsl[fr->callno]);
11599                }
11600                break;
11601             }
11602             registry_authrequest(fr->callno);
11603             break;
11604          case IAX_COMMAND_REGACK:
11605             if (iax2_ack_registry(&ies, &sin, fr->callno)) 
11606                ast_log(LOG_WARNING, "Registration failure\n");
11607             /* Send ack immediately, before we destroy */
11608             send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
11609             iax2_destroy(fr->callno);
11610             break;
11611          case IAX_COMMAND_REGREJ:
11612             if (iaxs[fr->callno]->reg) {
11613                if (authdebug) {
11614                   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));
11615                   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>");
11616                }
11617                iaxs[fr->callno]->reg->regstate = REG_STATE_REJECTED;
11618             }
11619             /* Send ack immediately, before we destroy */
11620             send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
11621             iax2_destroy(fr->callno);
11622             break;
11623          case IAX_COMMAND_REGAUTH:
11624             /* Authentication request */
11625             if (registry_rerequest(&ies, fr->callno, &sin)) {
11626                memset(&ied0, 0, sizeof(ied0));
11627                iax_ie_append_str(&ied0, IAX_IE_CAUSE, "No authority found");
11628                iax_ie_append_byte(&ied0, IAX_IE_CAUSECODE, AST_CAUSE_FACILITY_NOT_SUBSCRIBED);
11629                send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
11630             }
11631             break;
11632          case IAX_COMMAND_TXREJ:
11633             while (iaxs[fr->callno]
11634                && iaxs[fr->callno]->bridgecallno
11635                && ast_mutex_trylock(&iaxsl[iaxs[fr->callno]->bridgecallno])) {
11636                DEADLOCK_AVOIDANCE(&iaxsl[fr->callno]);
11637             }
11638             if (!iaxs[fr->callno]) {
11639                break;
11640             }
11641 
11642             iaxs[fr->callno]->transferring = TRANSFER_NONE;
11643             ast_verb(3, "Channel '%s' unable to transfer\n", iaxs[fr->callno]->owner ? ast_channel_name(iaxs[fr->callno]->owner) : "<Unknown>");
11644             memset(&iaxs[fr->callno]->transfer, 0, sizeof(iaxs[fr->callno]->transfer));
11645 
11646             if (!iaxs[fr->callno]->bridgecallno) {
11647                break;
11648             }
11649 
11650             if (iaxs[iaxs[fr->callno]->bridgecallno]
11651                && iaxs[iaxs[fr->callno]->bridgecallno]->transferring) {
11652                iaxs[iaxs[fr->callno]->bridgecallno]->transferring = TRANSFER_NONE;
11653                send_command(iaxs[iaxs[fr->callno]->bridgecallno], AST_FRAME_IAX, IAX_COMMAND_TXREJ, 0, NULL, 0, -1);
11654             }
11655             ast_mutex_unlock(&iaxsl[iaxs[fr->callno]->bridgecallno]);
11656             break;
11657          case IAX_COMMAND_TXREADY:
11658             while (iaxs[fr->callno]
11659                && iaxs[fr->callno]->bridgecallno
11660                && ast_mutex_trylock(&iaxsl[iaxs[fr->callno]->bridgecallno])) {
11661                DEADLOCK_AVOIDANCE(&iaxsl[fr->callno]);
11662             }
11663             if (!iaxs[fr->callno]) {
11664                break;
11665             }
11666 
11667             if (iaxs[fr->callno]->transferring == TRANSFER_BEGIN) {
11668                iaxs[fr->callno]->transferring = TRANSFER_READY;
11669             } else if (iaxs[fr->callno]->transferring == TRANSFER_MBEGIN) {
11670                iaxs[fr->callno]->transferring = TRANSFER_MREADY;
11671             } else {
11672                if (iaxs[fr->callno]->bridgecallno) {
11673                   ast_mutex_unlock(&iaxsl[iaxs[fr->callno]->bridgecallno]);
11674                }
11675                break;
11676             }
11677             ast_verb(3, "Channel '%s' ready to transfer\n", iaxs[fr->callno]->owner ? ast_channel_name(iaxs[fr->callno]->owner) : "<Unknown>");
11678 
11679             if (!iaxs[fr->callno]->bridgecallno) {
11680                break;
11681             }
11682 
11683             if (!iaxs[iaxs[fr->callno]->bridgecallno]
11684                || (iaxs[iaxs[fr->callno]->bridgecallno]->transferring != TRANSFER_READY
11685                   && iaxs[iaxs[fr->callno]->bridgecallno]->transferring != TRANSFER_MREADY)) {
11686                ast_mutex_unlock(&iaxsl[iaxs[fr->callno]->bridgecallno]);
11687                break;
11688             }
11689 
11690             /* Both sides are ready */
11691 
11692             /* XXX what isn't checked here is that both sides match transfer types. */
11693 
11694             if (iaxs[fr->callno]->transferring == TRANSFER_MREADY) {
11695                ast_verb(3, "Attempting media bridge of %s and %s\n", iaxs[fr->callno]->owner ? ast_channel_name(iaxs[fr->callno]->owner) : "<Unknown>",
11696                      iaxs[iaxs[fr->callno]->bridgecallno]->owner ? ast_channel_name(iaxs[iaxs[fr->callno]->bridgecallno]->owner) : "<Unknown>");
11697 
11698                iaxs[iaxs[fr->callno]->bridgecallno]->transferring = TRANSFER_MEDIA;
11699                iaxs[fr->callno]->transferring = TRANSFER_MEDIA;
11700 
11701                memset(&ied0, 0, sizeof(ied0));
11702                memset(&ied1, 0, sizeof(ied1));
11703                iax_ie_append_short(&ied0, IAX_IE_CALLNO, iaxs[iaxs[fr->callno]->bridgecallno]->peercallno);
11704                iax_ie_append_short(&ied1, IAX_IE_CALLNO, iaxs[fr->callno]->peercallno);
11705                send_command(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_TXMEDIA, 0, ied0.buf, ied0.pos, -1);
11706                send_command(iaxs[iaxs[fr->callno]->bridgecallno], AST_FRAME_IAX, IAX_COMMAND_TXMEDIA, 0, ied1.buf, ied1.pos, -1);
11707             } else {
11708                ast_verb(3, "Releasing %s and %s\n", iaxs[fr->callno]->owner ? ast_channel_name(iaxs[fr->callno]->owner) : "<Unknown>",
11709                      iaxs[iaxs[fr->callno]->bridgecallno]->owner ? ast_channel_name(iaxs[iaxs[fr->callno]->bridgecallno]->owner) : "<Unknown>");
11710 
11711                iaxs[iaxs[fr->callno]->bridgecallno]->transferring = TRANSFER_RELEASED;
11712                iaxs[fr->callno]->transferring = TRANSFER_RELEASED;
11713                ast_set_flag64(iaxs[iaxs[fr->callno]->bridgecallno], IAX_ALREADYGONE);
11714                ast_set_flag64(iaxs[fr->callno], IAX_ALREADYGONE);
11715 
11716                /* Stop doing lag & ping requests */
11717                stop_stuff(fr->callno);
11718                stop_stuff(iaxs[fr->callno]->bridgecallno);
11719 
11720                memset(&ied0, 0, sizeof(ied0));
11721                memset(&ied1, 0, sizeof(ied1));
11722                iax_ie_append_short(&ied0, IAX_IE_CALLNO, iaxs[iaxs[fr->callno]->bridgecallno]->peercallno);
11723                iax_ie_append_short(&ied1, IAX_IE_CALLNO, iaxs[fr->callno]->peercallno);
11724                send_command(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_TXREL, 0, ied0.buf, ied0.pos, -1);
11725                send_command(iaxs[iaxs[fr->callno]->bridgecallno], AST_FRAME_IAX, IAX_COMMAND_TXREL, 0, ied1.buf, ied1.pos, -1);
11726             }
11727             ast_mutex_unlock(&iaxsl[iaxs[fr->callno]->bridgecallno]);
11728             break;
11729          case IAX_COMMAND_TXREQ:
11730             try_transfer(iaxs[fr->callno], &ies);
11731             break;
11732          case IAX_COMMAND_TXCNT:
11733             if (iaxs[fr->callno]->transferring)
11734                send_command_transfer(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_TXACC, 0, NULL, 0);
11735             break;
11736          case IAX_COMMAND_TXREL:
11737             /* Send ack immediately, rather than waiting until we've changed addresses */
11738             send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
11739             complete_transfer(fr->callno, &ies);
11740             stop_stuff(fr->callno); /* for attended transfer to work with libiax */
11741             break;   
11742          case IAX_COMMAND_TXMEDIA:
11743             if (iaxs[fr->callno]->transferring == TRANSFER_READY) {
11744                AST_LIST_TRAVERSE(&frame_queue[fr->callno], cur, list) {
11745                   /* Cancel any outstanding frames and start anew */
11746                   if (cur->transfer) {
11747                      cur->retries = -1;
11748                   }
11749                }
11750                /* Start sending our media to the transfer address, but otherwise leave the call as-is */
11751                iaxs[fr->callno]->transferring = TRANSFER_MEDIAPASS;
11752             }
11753             break;
11754          case IAX_COMMAND_RTKEY:
11755             if (!IAX_CALLENCRYPTED(iaxs[fr->callno])) {
11756                ast_log(LOG_WARNING, 
11757                   "we've been told to rotate our encryption key, "
11758                   "but this isn't an encrypted call. bad things will happen.\n"
11759                );
11760                break;
11761             }
11762 
11763             IAX_DEBUGDIGEST("Receiving", ies.challenge);
11764 
11765             ast_aes_set_decrypt_key((unsigned char *) ies.challenge, &iaxs[fr->callno]->dcx);
11766             break;
11767          case IAX_COMMAND_DPREP:
11768             complete_dpreply(iaxs[fr->callno], &ies);
11769             break;
11770          case IAX_COMMAND_UNSUPPORT:
11771             ast_log(LOG_NOTICE, "Peer did not understand our iax command '%d'\n", ies.iax_unknown);
11772             break;
11773          case IAX_COMMAND_FWDOWNL:
11774             /* Firmware download */
11775             if (!ast_test_flag64(&globalflags, IAX_ALLOWFWDOWNLOAD)) {
11776                send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_UNSUPPORT, 0, NULL, 0, -1);
11777                break;
11778             }
11779             memset(&ied0, 0, sizeof(ied0));
11780             res = iax_firmware_append(&ied0, (unsigned char *)ies.devicetype, ies.fwdesc);
11781             if (res < 0)
11782                send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
11783             else if (res > 0)
11784                send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_FWDATA, 0, ied0.buf, ied0.pos, -1);
11785             else
11786                send_command(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_FWDATA, 0, ied0.buf, ied0.pos, -1);
11787             break;
11788          case IAX_COMMAND_CALLTOKEN:
11789          {
11790             struct iax_frame *cur;
11791             /* find last sent frame */
11792             if ((cur = AST_LIST_LAST(&frame_queue[fr->callno])) && ies.calltoken && ies.calltokendata) {
11793                resend_with_token(fr->callno, cur, (char *) ies.calltokendata);
11794             }
11795             break;
11796          }
11797          default:
11798             ast_debug(1, "Unknown IAX command %d on %d/%d\n", f.subclass.integer, fr->callno, iaxs[fr->callno]->peercallno);
11799             memset(&ied0, 0, sizeof(ied0));
11800             iax_ie_append_byte(&ied0, IAX_IE_IAX_UNKNOWN, f.subclass.integer);
11801             send_command(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_UNSUPPORT, 0, ied0.buf, ied0.pos, -1);
11802          }
11803          /* Free remote variables (if any) */
11804          if (ies.vars) {
11805             ast_variables_destroy(ies.vars);
11806             ast_debug(1, "I can haz IAX vars, but they is no good :-(\n");
11807             ies.vars = NULL;
11808          }
11809 
11810          /* Don't actually pass these frames along */
11811          if ((f.subclass.integer != IAX_COMMAND_ACK) &&
11812             (f.subclass.integer != IAX_COMMAND_TXCNT) &&
11813             (f.subclass.integer != IAX_COMMAND_TXACC) &&
11814             (f.subclass.integer != IAX_COMMAND_INVAL) &&
11815             (f.subclass.integer != IAX_COMMAND_VNAK)) {
11816             if (iaxs[fr->callno] && iaxs[fr->callno]->aseqno != iaxs[fr->callno]->iseqno) {
11817                send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
11818             }
11819          }
11820          ast_mutex_unlock(&iaxsl[fr->callno]);
11821          return 1;
11822       }
11823       /* Unless this is an ACK or INVAL frame, ack it */
11824       if (iaxs[fr->callno] && iaxs[fr->callno]->aseqno != iaxs[fr->callno]->iseqno)
11825          send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
11826    } else if (minivid) {
11827       f.frametype = AST_FRAME_VIDEO;
11828       if (iaxs[fr->callno]->videoformat > 0) {
11829          if (ntohs(vh->ts) & 0x8000LL) {
11830             ast_format_set_video_mark(&f.subclass.format);
11831          }
11832          ast_format_from_old_bitfield(&f.subclass.format, iaxs[fr->callno]->videoformat);
11833       } else {
11834          ast_log(LOG_WARNING, "Received mini frame before first full video frame\n");
11835          iax2_vnak(fr->callno);
11836          ast_variables_destroy(ies.vars);
11837          ast_mutex_unlock(&iaxsl[fr->callno]);
11838          return 1;
11839       }
11840       f.datalen = res - sizeof(*vh);
11841       if (f.datalen)
11842          f.data.ptr = thread->buf + sizeof(*vh);
11843       else
11844          f.data.ptr = NULL;
11845 #ifdef IAXTESTS
11846       if (test_resync) {
11847          fr->ts = (iaxs[fr->callno]->last & 0xFFFF8000L) | ((ntohs(vh->ts) + test_resync) & 0x7fff);
11848       } else
11849 #endif /* IAXTESTS */
11850          fr->ts = (iaxs[fr->callno]->last & 0xFFFF8000L) | (ntohs(vh->ts) & 0x7fff);
11851    } else {
11852       /* A mini frame */
11853       f.frametype = AST_FRAME_VOICE;
11854       if (iaxs[fr->callno]->voiceformat > 0)
11855          ast_format_from_old_bitfield(&f.subclass.format, iaxs[fr->callno]->voiceformat);
11856       else {
11857          ast_debug(1, "Received mini frame before first full voice frame\n");
11858          iax2_vnak(fr->callno);
11859          ast_variables_destroy(ies.vars);
11860          ast_mutex_unlock(&iaxsl[fr->callno]);
11861          return 1;
11862       }
11863       f.datalen = res - sizeof(struct ast_iax2_mini_hdr);
11864       if (f.datalen < 0) {
11865          ast_log(LOG_WARNING, "Datalen < 0?\n");
11866          ast_variables_destroy(ies.vars);
11867          ast_mutex_unlock(&iaxsl[fr->callno]);
11868          return 1;
11869       }
11870       if (f.datalen)
11871          f.data.ptr = thread->buf + sizeof(*mh);
11872       else
11873          f.data.ptr = NULL;
11874 #ifdef IAXTESTS
11875       if (test_resync) {
11876          fr->ts = (iaxs[fr->callno]->last & 0xFFFF0000L) | ((ntohs(mh->ts) + test_resync) & 0xffff);
11877       } else
11878 #endif /* IAXTESTS */
11879       fr->ts = (iaxs[fr->callno]->last & 0xFFFF0000L) | ntohs(mh->ts);
11880       /* FIXME? Surely right here would be the right place to undo timestamp wraparound? */
11881    }
11882 
11883    /* Don't pass any packets until we're started */
11884    if (!iaxs[fr->callno]
11885       || !ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED)) {
11886       ast_variables_destroy(ies.vars);
11887       ast_mutex_unlock(&iaxsl[fr->callno]);
11888       return 1;
11889    }
11890 
11891    if (f.frametype == AST_FRAME_CONTROL) {
11892       if (!iax2_is_control_frame_allowed(f.subclass.integer)) {
11893          /* Control frame not allowed to come from the wire. */
11894          ast_debug(2, "Callno %u: Blocked receiving control frame %d.\n",
11895             fr->callno, f.subclass.integer);
11896          ast_variables_destroy(ies.vars);
11897          ast_mutex_unlock(&iaxsl[fr->callno]);
11898          return 1;
11899       }
11900       if (f.subclass.integer == AST_CONTROL_CONNECTED_LINE
11901          || f.subclass.integer == AST_CONTROL_REDIRECTING) {
11902          if (iaxs[fr->callno]
11903             && !ast_test_flag64(iaxs[fr->callno], IAX_RECVCONNECTEDLINE)) {
11904             /* We are not configured to allow receiving these updates. */
11905             ast_debug(2, "Callno %u: Config blocked receiving control frame %d.\n",
11906                fr->callno, f.subclass.integer);
11907             ast_variables_destroy(ies.vars);
11908             ast_mutex_unlock(&iaxsl[fr->callno]);
11909             return 1;
11910          }
11911       }
11912 
11913       iax2_lock_owner(fr->callno);
11914       if (iaxs[fr->callno] && iaxs[fr->callno]->owner) {
11915          if (f.subclass.integer == AST_CONTROL_BUSY) {
11916             ast_channel_hangupcause_set(iaxs[fr->callno]->owner, AST_CAUSE_BUSY);
11917          } else if (f.subclass.integer == AST_CONTROL_CONGESTION) {
11918             ast_channel_hangupcause_set(iaxs[fr->callno]->owner, AST_CAUSE_CONGESTION);
11919          }
11920          ast_channel_unlock(iaxs[fr->callno]->owner);
11921       }
11922    }
11923 
11924    if (f.frametype == AST_FRAME_CONTROL
11925       && f.subclass.integer == AST_CONTROL_CONNECTED_LINE
11926       && iaxs[fr->callno]) {
11927       struct ast_party_connected_line connected;
11928 
11929       /*
11930        * Process a received connected line update.
11931        *
11932        * Initialize defaults.
11933        */
11934       ast_party_connected_line_init(&connected);
11935       connected.id.number.presentation = iaxs[fr->callno]->calling_pres;
11936       connected.id.name.presentation = iaxs[fr->callno]->calling_pres;
11937 
11938       if (!ast_connected_line_parse_data(f.data.ptr, f.datalen, &connected)) {
11939          ast_string_field_set(iaxs[fr->callno], cid_num, connected.id.number.str);
11940          ast_string_field_set(iaxs[fr->callno], cid_name, connected.id.name.str);
11941          iaxs[fr->callno]->calling_pres = ast_party_id_presentation(&connected.id);
11942 
11943          iax2_lock_owner(fr->callno);
11944          if (iaxs[fr->callno] && iaxs[fr->callno]->owner) {
11945             ast_set_callerid(iaxs[fr->callno]->owner,
11946                S_COR(connected.id.number.valid, connected.id.number.str, ""),
11947                S_COR(connected.id.name.valid, connected.id.name.str, ""),
11948                NULL);
11949             ast_channel_caller(iaxs[fr->callno]->owner)->id.number.presentation = connected.id.number.presentation;
11950             ast_channel_caller(iaxs[fr->callno]->owner)->id.name.presentation = connected.id.name.presentation;
11951             ast_channel_unlock(iaxs[fr->callno]->owner);
11952          }
11953       }
11954       ast_party_connected_line_free(&connected);
11955    }
11956 
11957    /* Common things */
11958    f.src = "IAX2";
11959    f.mallocd = 0;
11960    f.offset = 0;
11961    f.len = 0;
11962    if (f.datalen && (f.frametype == AST_FRAME_VOICE)) {
11963       f.samples = ast_codec_get_samples(&f);
11964       /* We need to byteswap incoming slinear samples from network byte order */
11965       if (f.subclass.format.id == AST_FORMAT_SLINEAR)
11966          ast_frame_byteswap_be(&f);
11967    } else
11968       f.samples = 0;
11969    iax_frame_wrap(fr, &f);
11970 
11971    /* If this is our most recent packet, use it as our basis for timestamping */
11972    if (iaxs[fr->callno] && iaxs[fr->callno]->last < fr->ts) {
11973       /*iaxs[fr->callno]->last = fr->ts; (do it afterwards cos schedule/forward_delivery needs the last ts too)*/
11974       fr->outoforder = 0;
11975    } else {
11976       if (iaxdebug && iaxs[fr->callno]) {
11977          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);
11978       }
11979       fr->outoforder = -1;
11980    }
11981    fr->cacheable = ((f.frametype == AST_FRAME_VOICE) || (f.frametype == AST_FRAME_VIDEO));
11982    if (iaxs[fr->callno]) {
11983       duped_fr = iaxfrdup2(fr);
11984       if (duped_fr) {
11985          schedule_delivery(duped_fr, updatehistory, 0, &fr->ts);
11986       }
11987    }
11988    if (iaxs[fr->callno] && iaxs[fr->callno]->last < fr->ts) {
11989       iaxs[fr->callno]->last = fr->ts;
11990 #if 1
11991       if (iaxdebug)
11992          ast_debug(1, "For call=%d, set last=%d\n", fr->callno, fr->ts);
11993 #endif
11994    }
11995 
11996    /* Always run again */
11997    ast_variables_destroy(ies.vars);
11998    ast_mutex_unlock(&iaxsl[fr->callno]);
11999    return 1;
12000 }
12001 
12002 static int socket_process(struct iax2_thread *thread)
12003 {
12004    struct ast_callid *callid;
12005    int res = socket_process_helper(thread);
12006    if ((callid = ast_read_threadstorage_callid())) {
12007       ast_callid_threadassoc_remove();
12008       callid = ast_callid_unref(callid);
12009    }
12010    return res;
12011 }
12012 
12013 /* Function to clean up process thread if it is cancelled */
12014 static void iax2_process_thread_cleanup(void *data)
12015 {
12016    struct iax2_thread *thread = data;
12017    ast_mutex_destroy(&thread->lock);
12018    ast_cond_destroy(&thread->cond);
12019    ast_mutex_destroy(&thread->init_lock);
12020    ast_cond_destroy(&thread->init_cond);
12021    ast_free(thread);
12022    /* Ignore check_return warning from Coverity for ast_atomic_dec_and_test below */
12023    ast_atomic_dec_and_test(&iaxactivethreadcount);
12024 }
12025 
12026 static void *iax2_process_thread(void *data)
12027 {
12028    struct iax2_thread *thread = data;
12029    struct timeval wait;
12030    struct timespec ts;
12031    int put_into_idle = 0;
12032    int first_time = 1;
12033    int old_state;
12034 
12035    ast_atomic_fetchadd_int(&iaxactivethreadcount, 1);
12036 
12037    pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &old_state);
12038    pthread_cleanup_push(iax2_process_thread_cleanup, data);
12039 
12040    for (;;) {
12041       /* Wait for something to signal us to be awake */
12042       ast_mutex_lock(&thread->lock);
12043 
12044       if (thread->stop) {
12045          ast_mutex_unlock(&thread->lock);
12046          break;
12047       }
12048 
12049       /* Flag that we're ready to accept signals */
12050       if (first_time) {
12051          signal_condition(&thread->init_lock, &thread->init_cond);
12052          first_time = 0;
12053       }
12054 
12055       /* Put into idle list if applicable */
12056       if (put_into_idle) {
12057          insert_idle_thread(thread);
12058       }
12059 
12060       if (thread->type == IAX_THREAD_TYPE_DYNAMIC) {
12061          struct iax2_thread *t = NULL;
12062          /* Wait to be signalled or time out */
12063          wait = ast_tvadd(ast_tvnow(), ast_samp2tv(30000, 1000));
12064          ts.tv_sec = wait.tv_sec;
12065          ts.tv_nsec = wait.tv_usec * 1000;
12066          if (ast_cond_timedwait(&thread->cond, &thread->lock, &ts) == ETIMEDOUT) {
12067             /* This thread was never put back into the available dynamic
12068              * thread list, so just go away. */
12069             if (!put_into_idle || thread->stop) {
12070                ast_mutex_unlock(&thread->lock);
12071                break;
12072             }
12073             AST_LIST_LOCK(&dynamic_list);
12074             /* Account for the case where this thread is acquired *right* after a timeout */
12075             if ((t = AST_LIST_REMOVE(&dynamic_list, thread, list)))
12076                ast_atomic_fetchadd_int(&iaxdynamicthreadcount, -1);
12077             AST_LIST_UNLOCK(&dynamic_list);
12078             if (t) {
12079                /* This dynamic thread timed out waiting for a task and was
12080                 * not acquired immediately after the timeout, 
12081                 * so it's time to go away. */
12082                ast_mutex_unlock(&thread->lock);
12083                break;
12084             }
12085             /* Someone grabbed our thread *right* after we timed out.
12086              * Wait for them to set us up with something to do and signal
12087              * us to continue. */
12088             wait = ast_tvadd(ast_tvnow(), ast_samp2tv(30000, 1000));
12089             ts.tv_sec = wait.tv_sec;
12090             ts.tv_nsec = wait.tv_usec * 1000;
12091             if (ast_cond_timedwait(&thread->cond, &thread->lock, &ts) == ETIMEDOUT) {
12092                ast_mutex_unlock(&thread->lock);
12093                break;
12094             }
12095          }
12096       } else {
12097          ast_cond_wait(&thread->cond, &thread->lock);
12098       }
12099 
12100       /* Go back into our respective list */
12101       put_into_idle = 1;
12102 
12103       ast_mutex_unlock(&thread->lock);
12104 
12105       if (thread->stop) {
12106          break;
12107       }
12108 
12109       /* See what we need to do */
12110       switch (thread->iostate) {
12111       case IAX_IOSTATE_IDLE:
12112          continue;
12113       case IAX_IOSTATE_READY:
12114          thread->actions++;
12115          thread->iostate = IAX_IOSTATE_PROCESSING;
12116          socket_process(thread);
12117          handle_deferred_full_frames(thread);
12118          break;
12119       case IAX_IOSTATE_SCHEDREADY:
12120          thread->actions++;
12121          thread->iostate = IAX_IOSTATE_PROCESSING;
12122 #ifdef SCHED_MULTITHREADED
12123          thread->schedfunc(thread->scheddata);
12124 #endif      
12125          break;
12126       default:
12127          break;
12128       }
12129 
12130       /* The network thread added us to the active_thread list when we were given
12131        * frames to process, Now that we are done, we must remove ourselves from
12132        * the active list, and return to the idle list */
12133       AST_LIST_LOCK(&active_list);
12134       AST_LIST_REMOVE(&active_list, thread, list);
12135       AST_LIST_UNLOCK(&active_list);
12136 
12137       /* Make sure another frame didn't sneak in there after we thought we were done. */
12138       handle_deferred_full_frames(thread);
12139 
12140       time(&thread->checktime);
12141       thread->iostate = IAX_IOSTATE_IDLE;
12142 #ifdef DEBUG_SCHED_MULTITHREAD
12143       thread->curfunc[0]='\0';
12144 #endif
12145    }
12146 
12147    /*!
12148     * \note For some reason, idle threads are exiting without being
12149     * removed from an idle list, which is causing memory
12150     * corruption.  Forcibly remove it from the list, if it's there.
12151     */
12152    AST_LIST_LOCK(&idle_list);
12153    AST_LIST_REMOVE(&idle_list, thread, list);
12154    AST_LIST_UNLOCK(&idle_list);
12155 
12156    AST_LIST_LOCK(&dynamic_list);
12157    AST_LIST_REMOVE(&dynamic_list, thread, list);
12158    AST_LIST_UNLOCK(&dynamic_list);
12159 
12160    if (!thread->stop) {
12161       /* Nobody asked me to stop so nobody is waiting to join me. */
12162       pthread_detach(pthread_self());
12163    }
12164 
12165    /* I am exiting here on my own volition, I need to clean up my own data structures
12166    * Assume that I am no longer in any of the lists (idle, active, or dynamic)
12167    */
12168    pthread_cleanup_pop(1);
12169    return NULL;
12170 }
12171 
12172 static int iax2_do_register(struct iax2_registry *reg)
12173 {
12174    struct iax_ie_data ied;
12175    if (iaxdebug)
12176       ast_debug(1, "Sending registration request for '%s'\n", reg->username);
12177 
12178    if (reg->dnsmgr &&
12179        ((reg->regstate == REG_STATE_TIMEOUT) || !ast_sockaddr_ipv4(&reg->addr))) {
12180       /* Maybe the IP has changed, force DNS refresh */
12181       ast_dnsmgr_refresh(reg->dnsmgr);
12182    }
12183 
12184    /*
12185     * if IP has Changed, free allocated call to create a new one with new IP
12186     * call has the pointer to IP and must be updated to the new one
12187     */
12188    if (reg->dnsmgr && ast_dnsmgr_changed(reg->dnsmgr) && (reg->callno > 0)) {
12189       int callno = reg->callno;
12190       ast_mutex_lock(&iaxsl[callno]);
12191       iax2_destroy(callno);
12192       ast_mutex_unlock(&iaxsl[callno]);
12193       reg->callno = 0;
12194    }
12195    if (!ast_sockaddr_ipv4(&reg->addr)) {
12196       if (iaxdebug)
12197          ast_debug(1, "Unable to send registration request for '%s' without IP address\n", reg->username);
12198       /* Setup the next registration attempt */
12199       reg->expire = iax2_sched_replace(reg->expire, sched,
12200          (5 * reg->refresh / 6) * 1000, iax2_do_register_s, reg);
12201       return -1;
12202    }
12203 
12204    if (!reg->callno) {
12205       struct sockaddr_in reg_addr;
12206 
12207       ast_debug(3, "Allocate call number\n");
12208 
12209       ast_sockaddr_to_sin(&reg->addr, &reg_addr);
12210 
12211       reg->callno = find_callno_locked(0, 0, &reg_addr, NEW_FORCE, defaultsockfd, 0);
12212       if (reg->callno < 1) {
12213          ast_log(LOG_WARNING, "Unable to create call for registration\n");
12214          return -1;
12215       } else
12216          ast_debug(3, "Registration created on call %d\n", reg->callno);
12217       iaxs[reg->callno]->reg = reg;
12218       ast_mutex_unlock(&iaxsl[reg->callno]);
12219    }
12220    /* Setup the next registration a little early */
12221    reg->expire = iax2_sched_replace(reg->expire, sched,
12222       (5 * reg->refresh / 6) * 1000, iax2_do_register_s, reg);
12223    /* Send the request */
12224    memset(&ied, 0, sizeof(ied));
12225    iax_ie_append_str(&ied, IAX_IE_USERNAME, reg->username);
12226    iax_ie_append_short(&ied, IAX_IE_REFRESH, reg->refresh);
12227    add_empty_calltoken_ie(iaxs[reg->callno], &ied); /* this _MUST_ be the last ie added */
12228    send_command(iaxs[reg->callno],AST_FRAME_IAX, IAX_COMMAND_REGREQ, 0, ied.buf, ied.pos, -1);
12229    reg->regstate = REG_STATE_REGSENT;
12230    return 0;
12231 }
12232 
12233 static int iax2_provision(struct sockaddr_in *end, int sockfd, const char *dest, const char *template, int force)
12234 {
12235    /* Returns 1 if provisioned, -1 if not able to find destination, or 0 if no provisioning
12236       is found for template */
12237    struct iax_ie_data provdata;
12238    struct iax_ie_data ied;
12239    unsigned int sig;
12240    struct sockaddr_in sin;
12241    int callno;
12242    struct create_addr_info cai;
12243 
12244    memset(&cai, 0, sizeof(cai));
12245 
12246    ast_debug(1, "Provisioning '%s' from template '%s'\n", dest, template);
12247 
12248    if (iax_provision_build(&provdata, &sig, template, force)) {
12249       ast_debug(1, "No provisioning found for template '%s'\n", template);
12250       return 0;
12251    }
12252 
12253    if (end) {
12254       memcpy(&sin, end, sizeof(sin));
12255       cai.sockfd = sockfd;
12256    } else if (create_addr(dest, NULL, &sin, &cai))
12257       return -1;
12258 
12259    /* Build the rest of the message */
12260    memset(&ied, 0, sizeof(ied));
12261    iax_ie_append_raw(&ied, IAX_IE_PROVISIONING, provdata.buf, provdata.pos);
12262 
12263    callno = find_callno_locked(0, 0, &sin, NEW_FORCE, cai.sockfd, 0);
12264    if (!callno)
12265       return -1;
12266 
12267    if (iaxs[callno]) {
12268       /* Schedule autodestruct in case they don't ever give us anything back */
12269       iaxs[callno]->autoid = iax2_sched_replace(iaxs[callno]->autoid, 
12270          sched, 15000, auto_hangup, (void *)(long)callno);
12271       ast_set_flag64(iaxs[callno], IAX_PROVISION);
12272       /* Got a call number now, so go ahead and send the provisioning information */
12273       send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_PROVISION, 0, ied.buf, ied.pos, -1);
12274    }
12275    ast_mutex_unlock(&iaxsl[callno]);
12276 
12277    return 1;
12278 }
12279 
12280 static char *papp = "IAX2Provision";
12281 
12282 /*! iax2provision
12283 \ingroup applications
12284 */
12285 static int iax2_prov_app(struct ast_channel *chan, const char *data)
12286 {
12287    int res;
12288    char *sdata;
12289    char *opts;
12290    int force =0;
12291    unsigned short callno = PTR_TO_CALLNO(ast_channel_tech_pvt(chan));
12292    if (ast_strlen_zero(data))
12293       data = "default";
12294    sdata = ast_strdupa(data);
12295    opts = strchr(sdata, '|');
12296    if (opts)
12297       *opts='\0';
12298 
12299    if (ast_channel_tech(chan) != &iax2_tech) {
12300       ast_log(LOG_NOTICE, "Can't provision a non-IAX device!\n");
12301       return -1;
12302    } 
12303    if (!callno || !iaxs[callno] || !iaxs[callno]->addr.sin_addr.s_addr) {
12304       ast_log(LOG_NOTICE, "Can't provision something with no IP?\n");
12305       return -1;
12306    }
12307    res = iax2_provision(&iaxs[callno]->addr, iaxs[callno]->sockfd, NULL, sdata, force);
12308    ast_verb(3, "Provisioned IAXY at '%s' with '%s'= %d\n",
12309       ast_inet_ntoa(iaxs[callno]->addr.sin_addr),
12310       sdata, res);
12311    return res;
12312 }
12313 
12314 static char *handle_cli_iax2_provision(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
12315 {
12316    int force = 0;
12317    int res;
12318 
12319    switch (cmd) {
12320    case CLI_INIT:
12321       e->command = "iax2 provision";
12322       e->usage = 
12323          "Usage: iax2 provision <host> <template> [forced]\n"
12324          "       Provisions the given peer or IP address using a template\n"
12325          "       matching either 'template' or '*' if the template is not\n"
12326          "       found.  If 'forced' is specified, even empty provisioning\n"
12327          "       fields will be provisioned as empty fields.\n";
12328       return NULL;
12329    case CLI_GENERATE:
12330       if (a->pos == 3)
12331          return iax_prov_complete_template(a->line, a->word, a->pos, a->n);
12332       return NULL;
12333    }
12334 
12335    if (a->argc < 4)
12336       return CLI_SHOWUSAGE;
12337    if (a->argc > 4) {
12338       if (!strcasecmp(a->argv[4], "forced"))
12339          force = 1;
12340       else
12341          return CLI_SHOWUSAGE;
12342    }
12343    res = iax2_provision(NULL, -1, a->argv[2], a->argv[3], force);
12344    if (res < 0)
12345       ast_cli(a->fd, "Unable to find peer/address '%s'\n", a->argv[2]);
12346    else if (res < 1)
12347       ast_cli(a->fd, "No template (including wildcard) matching '%s'\n", a->argv[3]);
12348    else
12349       ast_cli(a->fd, "Provisioning '%s' with template '%s'%s\n", a->argv[2], a->argv[3], force ? ", forced" : "");
12350    return CLI_SUCCESS;
12351 }
12352 
12353 static void __iax2_poke_noanswer(const void *data)
12354 {
12355    struct iax2_peer *peer = (struct iax2_peer *)data;
12356    int callno;
12357 
12358    if (peer->lastms > -1) {
12359       ast_log(LOG_NOTICE, "Peer '%s' is now UNREACHABLE! Time: %d\n", peer->name, peer->lastms);
12360       manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: IAX2\r\nPeer: IAX2/%s\r\nPeerStatus: Unreachable\r\nTime: %d\r\n", peer->name, peer->lastms);
12361       ast_devstate_changed(AST_DEVICE_UNAVAILABLE, AST_DEVSTATE_CACHABLE, "IAX2/%s", peer->name); /* Activate notification */
12362    }
12363    if ((callno = peer->callno) > 0) {
12364       ast_mutex_lock(&iaxsl[callno]);
12365       iax2_destroy(callno);
12366       ast_mutex_unlock(&iaxsl[callno]);
12367    }
12368    peer->callno = 0;
12369    peer->lastms = -1;
12370    /* Try again quickly */
12371    peer->pokeexpire = iax2_sched_add(sched, peer->pokefreqnotok, iax2_poke_peer_s, peer_ref(peer));
12372    if (peer->pokeexpire == -1)
12373       peer_unref(peer);
12374 }
12375 
12376 static int iax2_poke_noanswer(const void *data)
12377 {
12378    struct iax2_peer *peer = (struct iax2_peer *)data;
12379    peer->pokeexpire = -1;
12380 #ifdef SCHED_MULTITHREADED
12381    if (schedule_action(__iax2_poke_noanswer, data))
12382 #endif      
12383       __iax2_poke_noanswer(data);
12384    peer_unref(peer);
12385    return 0;
12386 }
12387 
12388 static int iax2_poke_peer_cb(void *obj, void *arg, int flags)
12389 {
12390    struct iax2_peer *peer = obj;
12391 
12392    iax2_poke_peer(peer, 0);
12393 
12394    return 0;
12395 }
12396 
12397 static int iax2_poke_peer(struct iax2_peer *peer, int heldcall)
12398 {
12399    int callno;
12400    struct sockaddr_in peer_addr;
12401 
12402    if (!peer->maxms || (!ast_sockaddr_ipv4(&peer->addr) && !peer->dnsmgr)) {
12403       /* IF we have no IP without dnsmgr, or this isn't to be monitored, return
12404         immediately after clearing things out */
12405       peer->lastms = 0;
12406       peer->historicms = 0;
12407       peer->pokeexpire = -1;
12408       peer->callno = 0;
12409       return 0;
12410    }
12411 
12412    ast_sockaddr_to_sin(&peer->addr, &peer_addr);
12413 
12414    /* The peer could change the callno inside iax2_destroy, since we do deadlock avoidance */
12415    if ((callno = peer->callno) > 0) {
12416       ast_log(LOG_NOTICE, "Still have a callno...\n");
12417       ast_mutex_lock(&iaxsl[callno]);
12418       iax2_destroy(callno);
12419       ast_mutex_unlock(&iaxsl[callno]);
12420    }
12421    if (heldcall)
12422       ast_mutex_unlock(&iaxsl[heldcall]);
12423    callno = peer->callno = find_callno(0, 0, &peer_addr, NEW_FORCE, peer->sockfd, 0);
12424    if (heldcall)
12425       ast_mutex_lock(&iaxsl[heldcall]);
12426    if (peer->callno < 1) {
12427       ast_log(LOG_WARNING, "Unable to allocate call for poking peer '%s'\n", peer->name);
12428       return -1;
12429    }
12430 
12431    /* Speed up retransmission times for this qualify call */
12432    iaxs[peer->callno]->pingtime = peer->maxms / 4 + 1;
12433    iaxs[peer->callno]->peerpoke = peer;
12434 
12435    if (peer->pokeexpire > -1) {
12436       if (!AST_SCHED_DEL(sched, peer->pokeexpire)) {
12437          peer->pokeexpire = -1;
12438          peer_unref(peer);
12439       }
12440    }
12441 
12442    /* Queue up a new task to handle no reply */
12443    /* If the host is already unreachable then use the unreachable interval instead */
12444    if (peer->lastms < 0)
12445       peer->pokeexpire = iax2_sched_add(sched, peer->pokefreqnotok, iax2_poke_noanswer, peer_ref(peer));
12446    else
12447       peer->pokeexpire = iax2_sched_add(sched, DEFAULT_MAXMS * 2, iax2_poke_noanswer, peer_ref(peer));
12448 
12449    if (peer->pokeexpire == -1)
12450       peer_unref(peer);
12451 
12452    /* And send the poke */
12453    ast_mutex_lock(&iaxsl[callno]);
12454    if (iaxs[callno]) {
12455       struct iax_ie_data ied = {
12456          .buf = { 0 },
12457          .pos = 0,
12458       };
12459       add_empty_calltoken_ie(iaxs[callno], &ied); /* this _MUST_ be the last ie added */
12460       send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_POKE, 0, ied.buf, ied.pos, -1);
12461    }
12462    ast_mutex_unlock(&iaxsl[callno]);
12463 
12464    return 0;
12465 }
12466 
12467 static void free_context(struct iax2_context *con)
12468 {
12469    struct iax2_context *conl;
12470    while(con) {
12471       conl = con;
12472       con = con->next;
12473       ast_free(conl);
12474    }
12475 }
12476 
12477 static struct ast_channel *iax2_request(const char *type, struct ast_format_cap *cap, const struct ast_channel *requestor, const char *data, int *cause)
12478 {
12479    int callno;
12480    int res;
12481    struct sockaddr_in sin;
12482    struct ast_channel *c;
12483    struct parsed_dial_string pds;
12484    struct create_addr_info cai;
12485    char *tmpstr;
12486    struct ast_callid *callid;
12487 
12488    memset(&pds, 0, sizeof(pds));
12489    tmpstr = ast_strdupa(data);
12490    parse_dial_string(tmpstr, &pds);
12491 
12492    callid = ast_read_threadstorage_callid();
12493 
12494    if (ast_strlen_zero(pds.peer)) {
12495       ast_log(LOG_WARNING, "No peer provided in the IAX2 dial string '%s'\n", data);
12496       return NULL;
12497    }
12498    memset(&cai, 0, sizeof(cai));
12499    cai.capability = iax2_capability;
12500 
12501    ast_copy_flags64(&cai, &globalflags, IAX_NOTRANSFER | IAX_TRANSFERMEDIA | IAX_USEJITTERBUF | IAX_FORCEJITTERBUF | IAX_SENDCONNECTEDLINE | IAX_RECVCONNECTEDLINE);
12502 
12503    /* Populate our address from the given */
12504    if (create_addr(pds.peer, NULL, &sin, &cai)) {
12505       *cause = AST_CAUSE_UNREGISTERED;
12506       return NULL;
12507    }
12508 
12509    if (pds.port)
12510       sin.sin_port = htons(atoi(pds.port));
12511 
12512    callno = find_callno_locked(0, 0, &sin, NEW_FORCE, cai.sockfd, 0);
12513    if (callno < 1) {
12514       ast_log(LOG_WARNING, "Unable to create call\n");
12515       *cause = AST_CAUSE_CONGESTION;
12516       return NULL;
12517    }
12518 
12519    /* If this is a trunk, update it now */
12520    ast_copy_flags64(iaxs[callno], &cai, IAX_TRUNK | IAX_SENDANI | IAX_NOTRANSFER | IAX_TRANSFERMEDIA | IAX_USEJITTERBUF | IAX_FORCEJITTERBUF | IAX_SENDCONNECTEDLINE | IAX_RECVCONNECTEDLINE);
12521    if (ast_test_flag64(&cai, IAX_TRUNK)) {
12522       int new_callno;
12523       if ((new_callno = make_trunk(callno, 1)) != -1)
12524          callno = new_callno;
12525    }
12526    iaxs[callno]->maxtime = cai.maxtime;
12527    if (callid) {
12528       iax_pvt_callid_set(callno, callid);
12529    }
12530 
12531    if (cai.found) {
12532       ast_string_field_set(iaxs[callno], host, pds.peer);
12533    }
12534 
12535    c = ast_iax2_new(callno, AST_STATE_DOWN, cai.capability, requestor ? ast_channel_linkedid(requestor) : NULL, cai.found);
12536 
12537    ast_mutex_unlock(&iaxsl[callno]);
12538 
12539    if (c) {
12540       struct ast_format_cap *joint;
12541       if (callid) {
12542          ast_channel_callid_set(c, callid);
12543       }
12544 
12545       /* Choose a format we can live with */
12546       if ((joint = ast_format_cap_joint(ast_channel_nativeformats(c), cap))) {
12547          ast_format_cap_copy(ast_channel_nativeformats(c), joint);
12548          joint = ast_format_cap_destroy(joint);
12549       } else {
12550          struct ast_format best_fmt_cap;
12551          struct ast_format best_fmt_native;
12552          res = ast_translator_best_choice(cap, ast_channel_nativeformats(c), &best_fmt_cap, &best_fmt_native);
12553          if (res < 0) {
12554             char tmp[256];
12555             char tmp2[256];
12556             ast_log(LOG_WARNING, "Unable to create translator path for %s to %s on %s\n",
12557                ast_getformatname_multiple(tmp, sizeof(tmp), ast_channel_nativeformats(c)), ast_getformatname_multiple(tmp2, sizeof(tmp2), cap), ast_channel_name(c));
12558             ast_hangup(c);
12559             return NULL;
12560          }
12561          ast_format_cap_set(ast_channel_nativeformats(c), &best_fmt_native);
12562       }
12563       ast_best_codec(ast_channel_nativeformats(c), ast_channel_readformat(c));
12564       ast_format_copy(ast_channel_writeformat(c), ast_channel_readformat(c));
12565    }
12566 
12567    if (callid) {
12568       ast_callid_unref(callid);
12569    }
12570    return c;
12571 }
12572 
12573 static void *network_thread(void *ignore)
12574 {
12575    if (timer) {
12576       ast_io_add(io, ast_timer_fd(timer), timing_read, AST_IO_IN | AST_IO_PRI, NULL);
12577    }
12578 
12579    for (;;) {
12580       pthread_testcancel();
12581       /* Wake up once a second just in case SIGURG was sent while
12582        * we weren't in poll(), to make sure we don't hang when trying
12583        * to unload. */
12584       if (ast_io_wait(io, 1000) <= 0) {
12585          break;
12586       }
12587    }
12588 
12589    return NULL;
12590 }
12591 
12592 static int start_network_thread(void)
12593 {
12594    struct iax2_thread *thread;
12595    int threadcount = 0;
12596    int x;
12597    for (x = 0; x < iaxthreadcount; x++) {
12598       thread = ast_calloc(1, sizeof(*thread));
12599       if (thread) {
12600          thread->type = IAX_THREAD_TYPE_POOL;
12601          thread->threadnum = ++threadcount;
12602          ast_mutex_init(&thread->lock);
12603          ast_cond_init(&thread->cond, NULL);
12604          ast_mutex_init(&thread->init_lock);
12605          ast_cond_init(&thread->init_cond, NULL);
12606 
12607          ast_mutex_lock(&thread->init_lock);
12608 
12609          if (ast_pthread_create_background(&thread->threadid, NULL, iax2_process_thread, thread)) {
12610             ast_log(LOG_WARNING, "Failed to create new thread!\n");
12611             ast_mutex_destroy(&thread->lock);
12612             ast_cond_destroy(&thread->cond);
12613             ast_mutex_unlock(&thread->init_lock);
12614             ast_mutex_destroy(&thread->init_lock);
12615             ast_cond_destroy(&thread->init_cond);
12616             ast_free(thread);
12617             thread = NULL;
12618             continue;
12619          }
12620          /* Wait for the thread to be ready */
12621          ast_cond_wait(&thread->init_cond, &thread->init_lock);
12622 
12623          /* Done with init_lock */
12624          ast_mutex_unlock(&thread->init_lock);
12625 
12626          AST_LIST_LOCK(&idle_list);
12627          AST_LIST_INSERT_TAIL(&idle_list, thread, list);
12628          AST_LIST_UNLOCK(&idle_list);
12629       }
12630    }
12631    if (ast_pthread_create_background(&netthreadid, NULL, network_thread, NULL)) {
12632       ast_log(LOG_ERROR, "Failed to create new thread!\n");
12633       return -1;
12634    }
12635    ast_verb(2, "%d helper threads started\n", threadcount);
12636    return 0;
12637 }
12638 
12639 static struct iax2_context *build_context(const char *context)
12640 {
12641    struct iax2_context *con;
12642 
12643    if ((con = ast_calloc(1, sizeof(*con))))
12644       ast_copy_string(con->context, context, sizeof(con->context));
12645    
12646    return con;
12647 }
12648 
12649 static int get_auth_methods(const char *value)
12650 {
12651    int methods = 0;
12652    if (strstr(value, "rsa"))
12653       methods |= IAX_AUTH_RSA;
12654    if (strstr(value, "md5"))
12655       methods |= IAX_AUTH_MD5;
12656    if (strstr(value, "plaintext"))
12657       methods |= IAX_AUTH_PLAINTEXT;
12658    return methods;
12659 }
12660 
12661 
12662 /*! \brief Check if address can be used as packet source.
12663  \return 0  address available, 1  address unavailable, -1  error
12664 */
12665 static int check_srcaddr(struct ast_sockaddr *addr)
12666 {
12667    int sd;
12668 
12669    sd = socket(addr->ss.ss_family, SOCK_DGRAM, 0);
12670    if (sd < 0) {
12671       ast_log(LOG_ERROR, "Socket: %s\n", strerror(errno));
12672       return -1;
12673    }
12674 
12675    if (ast_bind(sd, addr) < 0) {
12676       ast_debug(1, "Can't bind: %s\n", strerror(errno));
12677       close(sd);
12678       return 1;
12679    }
12680 
12681    close(sd);
12682    return 0;
12683 }
12684 
12685 /*! \brief Parse the "sourceaddress" value,
12686   lookup in netsock list and set peer's sockfd. Defaults to defaultsockfd if
12687   not found. */
12688 static int peer_set_srcaddr(struct iax2_peer *peer, const char *srcaddr)
12689 {
12690    struct ast_sockaddr addr;
12691    int nonlocal = 1;
12692    int port = IAX_DEFAULT_PORTNO;
12693    int sockfd = defaultsockfd;
12694    char *tmp;
12695    char *host;
12696    char *portstr;
12697 
12698    tmp = ast_strdupa(srcaddr);
12699    ast_sockaddr_split_hostport(tmp, &host, &portstr, 0);
12700 
12701    if (portstr) {
12702       port = atoi(portstr);
12703       if (port < 1)
12704          port = IAX_DEFAULT_PORTNO;
12705    }
12706 
12707    addr.ss.ss_family = AF_INET;
12708 
12709    if (!ast_get_ip(&addr, host)) {
12710       struct ast_netsock *sock;
12711 
12712       if (check_srcaddr(&addr) == 0) {
12713          /* ip address valid. */
12714          ast_sockaddr_set_port(&addr, port);
12715 
12716          if (!(sock = ast_netsock_find(netsock, &addr)))
12717             sock = ast_netsock_find(outsock, &addr);
12718          if (sock) {
12719             sockfd = ast_netsock_sockfd(sock);
12720             nonlocal = 0;
12721          } else {
12722             /* INADDR_ANY matches anyway! */
12723             ast_sockaddr_parse(&addr, "0.0.0.0", 0);
12724             ast_sockaddr_set_port(&addr, port);
12725             if (ast_netsock_find(netsock, &addr)) {
12726                sock = ast_netsock_bind(outsock, io, srcaddr, port, qos.tos, qos.cos, socket_read, NULL);
12727                if (sock) {
12728                   sockfd = ast_netsock_sockfd(sock);
12729                   ast_netsock_unref(sock);
12730                   nonlocal = 0;
12731                } else {
12732                   nonlocal = 2;
12733                }
12734             }
12735          }
12736       }
12737    }
12738 
12739    peer->sockfd = sockfd;
12740 
12741    if (nonlocal == 1) {
12742       ast_log(LOG_WARNING,
12743          "Non-local or unbound address specified (%s) in sourceaddress for '%s', reverting to default\n",
12744          srcaddr,
12745          peer->name);
12746       return -1;
12747    } else if (nonlocal == 2) {
12748       ast_log(LOG_WARNING,
12749          "Unable to bind to sourceaddress '%s' for '%s', reverting to default\n",
12750          srcaddr,
12751          peer->name);
12752       return -1;
12753    } else {
12754       ast_debug(1, "Using sourceaddress %s for '%s'\n", srcaddr, peer->name);
12755       return 0;
12756    }
12757 }
12758 
12759 static void peer_destructor(void *obj)
12760 {
12761    struct iax2_peer *peer = obj;
12762    int callno = peer->callno;
12763 
12764    ast_free_acl_list(peer->acl);
12765 
12766    if (callno > 0) {
12767       ast_mutex_lock(&iaxsl[callno]);
12768       iax2_destroy(callno);
12769       ast_mutex_unlock(&iaxsl[callno]);
12770    }
12771 
12772    register_peer_exten(peer, 0);
12773 
12774    if (peer->dnsmgr)
12775       ast_dnsmgr_release(peer->dnsmgr);
12776 
12777    if (peer->mwi_event_sub)
12778       ast_event_unsubscribe(peer->mwi_event_sub);
12779 
12780    ast_string_field_free_memory(peer);
12781 }
12782 
12783 /*! \brief Create peer structure based on configuration */
12784 static struct iax2_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly)
12785 {
12786    struct iax2_peer *peer = NULL;
12787    struct ast_acl_list *oldacl = NULL;
12788    int maskfound = 0;
12789    int found = 0;
12790    int firstpass = 1;
12791    int subscribe_acl_change = 0;
12792 
12793    if (!temponly) {
12794       peer = ao2_find(peers, name, OBJ_KEY);
12795       if (peer && !ast_test_flag64(peer, IAX_DELME))
12796          firstpass = 0;
12797    }
12798 
12799    if (peer) {
12800       found++;
12801       if (firstpass) {
12802          oldacl = peer->acl;
12803          peer->acl = NULL;
12804       }
12805       unlink_peer(peer);
12806    } else if ((peer = ao2_alloc(sizeof(*peer), peer_destructor))) {
12807       peer->expire = -1;
12808       peer->pokeexpire = -1;
12809       peer->sockfd = defaultsockfd;
12810       peer->addr.ss.ss_family = AF_INET;
12811       peer->addr.len = sizeof(struct sockaddr_in);
12812       if (ast_string_field_init(peer, 32))
12813          peer = peer_unref(peer);
12814    }
12815 
12816    if (peer) {
12817       if (firstpass) {
12818          ast_copy_flags64(peer, &globalflags, IAX_USEJITTERBUF | IAX_FORCEJITTERBUF | IAX_SENDCONNECTEDLINE | IAX_RECVCONNECTEDLINE | IAX_FORCE_ENCRYPT);
12819          peer->encmethods = iax2_encryption;
12820          peer->adsi = adsi;
12821          ast_string_field_set(peer,secret,"");
12822          if (!found) {
12823             ast_string_field_set(peer, name, name);
12824             ast_sockaddr_set_port(&peer->addr, IAX_DEFAULT_PORTNO);
12825             peer->expiry = min_reg_expire;
12826          }
12827          peer->prefs = prefs;
12828          peer->capability = iax2_capability;
12829          peer->smoothing = 0;
12830          peer->pokefreqok = DEFAULT_FREQ_OK;
12831          peer->pokefreqnotok = DEFAULT_FREQ_NOTOK;
12832          peer->maxcallno = 0;
12833          peercnt_modify((unsigned char) 0, 0, &peer->addr);
12834          peer->calltoken_required = CALLTOKEN_DEFAULT;
12835          ast_string_field_set(peer,context,"");
12836          ast_string_field_set(peer,peercontext,"");
12837          ast_clear_flag64(peer, IAX_HASCALLERID);
12838          ast_string_field_set(peer, cid_name, "");
12839          ast_string_field_set(peer, cid_num, "");
12840          ast_string_field_set(peer, mohinterpret, mohinterpret);
12841          ast_string_field_set(peer, mohsuggest, mohsuggest);
12842       }
12843 
12844       if (!v) {
12845          v = alt;
12846          alt = NULL;
12847       }
12848       while(v) {
12849          if (!strcasecmp(v->name, "secret")) {
12850             ast_string_field_set(peer, secret, v->value);
12851          } else if (!strcasecmp(v->name, "mailbox")) {
12852             ast_string_field_set(peer, mailbox, v->value);
12853          } else if (!strcasecmp(v->name, "hasvoicemail")) {
12854             if (ast_true(v->value) && ast_strlen_zero(peer->mailbox)) {
12855                ast_string_field_set(peer, mailbox, name);
12856             }
12857          } else if (!strcasecmp(v->name, "mohinterpret")) {
12858             ast_string_field_set(peer, mohinterpret, v->value);
12859          } else if (!strcasecmp(v->name, "mohsuggest")) {
12860             ast_string_field_set(peer, mohsuggest, v->value);
12861          } else if (!strcasecmp(v->name, "dbsecret")) {
12862             ast_string_field_set(peer, dbsecret, v->value);
12863          } else if (!strcasecmp(v->name, "description")) {
12864             ast_string_field_set(peer, description, v->value);
12865          } else if (!strcasecmp(v->name, "trunk")) {
12866             ast_set2_flag64(peer, ast_true(v->value), IAX_TRUNK); 
12867             if (ast_test_flag64(peer, IAX_TRUNK) && !timer) {
12868                ast_log(LOG_WARNING, "Unable to support trunking on peer '%s' without a timing interface\n", peer->name);
12869                ast_clear_flag64(peer, IAX_TRUNK);
12870             }
12871          } else if (!strcasecmp(v->name, "auth")) {
12872             peer->authmethods = get_auth_methods(v->value);
12873          } else if (!strcasecmp(v->name, "encryption")) {
12874             peer->encmethods |= get_encrypt_methods(v->value);
12875             if (!peer->encmethods) {
12876                ast_clear_flag64(peer, IAX_FORCE_ENCRYPT);
12877             }
12878          } else if (!strcasecmp(v->name, "forceencryption")) {
12879             if (ast_false(v->value)) {
12880                ast_clear_flag64(peer, IAX_FORCE_ENCRYPT);
12881             } else {
12882                peer->encmethods |= get_encrypt_methods(v->value);
12883                if (peer->encmethods) {
12884                   ast_set_flag64(peer, IAX_FORCE_ENCRYPT);
12885                }
12886             }
12887          } else if (!strcasecmp(v->name, "transfer")) {
12888             if (!strcasecmp(v->value, "mediaonly")) {
12889                ast_set_flags_to64(peer, IAX_NOTRANSFER|IAX_TRANSFERMEDIA, IAX_TRANSFERMEDIA);
12890             } else if (ast_true(v->value)) {
12891                ast_set_flags_to64(peer, IAX_NOTRANSFER|IAX_TRANSFERMEDIA, 0);
12892             } else
12893                ast_set_flags_to64(peer, IAX_NOTRANSFER|IAX_TRANSFERMEDIA, IAX_NOTRANSFER);
12894          } else if (!strcasecmp(v->name, "jitterbuffer")) {
12895             ast_set2_flag64(peer, ast_true(v->value), IAX_USEJITTERBUF);
12896          } else if (!strcasecmp(v->name, "forcejitterbuffer")) {
12897             ast_set2_flag64(peer, ast_true(v->value), IAX_FORCEJITTERBUF);
12898          } else if (!strcasecmp(v->name, "host")) {
12899             if (!strcasecmp(v->value, "dynamic")) {
12900                /* They'll register with us */
12901                ast_set_flag64(peer, IAX_DYNAMIC);
12902                if (!found) {
12903                   /* Initialize stuff iff we're not found, otherwise
12904                      we keep going with what we had */
12905                   if (ast_sockaddr_port(&peer->addr)) {
12906                      peer->defaddr.sin_port = htons(ast_sockaddr_port(&peer->addr));
12907                   }
12908                   ast_sockaddr_setnull(&peer->addr);
12909                }
12910             } else {
12911                /* Non-dynamic.  Make sure we become that way if we're not */
12912                AST_SCHED_DEL(sched, peer->expire);
12913                ast_clear_flag64(peer, IAX_DYNAMIC);
12914                if (ast_dnsmgr_lookup(v->value, &peer->addr, &peer->dnsmgr, srvlookup ? "_iax._udp" : NULL))
12915                   return peer_unref(peer);
12916                if (!ast_sockaddr_port(&peer->addr)) {
12917                   ast_sockaddr_set_port(&peer->addr, IAX_DEFAULT_PORTNO);
12918                }
12919             }
12920             if (!maskfound)
12921                inet_aton("255.255.255.255", &peer->mask);
12922          } else if (!strcasecmp(v->name, "defaultip")) {
12923             struct ast_sockaddr peer_defaddr_tmp;
12924 
12925             peer_defaddr_tmp.ss.ss_family = AF_INET;
12926             if (ast_get_ip(&peer_defaddr_tmp, v->value)) {
12927                return peer_unref(peer);
12928             }
12929             ast_sockaddr_to_sin(&peer_defaddr_tmp,
12930                       &peer->defaddr);
12931          } else if (!strcasecmp(v->name, "sourceaddress")) {
12932             peer_set_srcaddr(peer, v->value);
12933          } else if (!strcasecmp(v->name, "permit") ||
12934                   !strcasecmp(v->name, "deny") ||
12935                   !strcasecmp(v->name, "acl")) {
12936             ast_append_acl(v->name, v->value, &peer->acl, NULL, &subscribe_acl_change);
12937          } else if (!strcasecmp(v->name, "mask")) {
12938             maskfound++;
12939             inet_aton(v->value, &peer->mask);
12940          } else if (!strcasecmp(v->name, "context")) {
12941             ast_string_field_set(peer, context, v->value);
12942          } else if (!strcasecmp(v->name, "regexten")) {
12943             ast_string_field_set(peer, regexten, v->value);
12944          } else if (!strcasecmp(v->name, "peercontext")) {
12945             ast_string_field_set(peer, peercontext, v->value);
12946          } else if (!strcasecmp(v->name, "port")) {
12947             if (ast_test_flag64(peer, IAX_DYNAMIC)) {
12948                peer->defaddr.sin_port = htons(atoi(v->value));
12949             } else {
12950                ast_sockaddr_set_port(&peer->addr, atoi(v->value));
12951             }
12952          } else if (!strcasecmp(v->name, "username")) {
12953             ast_string_field_set(peer, username, v->value);
12954          } else if (!strcasecmp(v->name, "allow")) {
12955             iax2_parse_allow_disallow(&peer->prefs, &peer->capability, v->value, 1);
12956          } else if (!strcasecmp(v->name, "disallow")) {
12957             iax2_parse_allow_disallow(&peer->prefs, &peer->capability, v->value, 0);
12958          } else if (!strcasecmp(v->name, "callerid")) {
12959             if (!ast_strlen_zero(v->value)) {
12960                char name2[80];
12961                char num2[80];
12962                ast_callerid_split(v->value, name2, sizeof(name2), num2, sizeof(num2));
12963                ast_string_field_set(peer, cid_name, name2);
12964                ast_string_field_set(peer, cid_num, num2);
12965             } else {
12966                ast_string_field_set(peer, cid_name, "");
12967                ast_string_field_set(peer, cid_num, "");
12968             }
12969             ast_set_flag64(peer, IAX_HASCALLERID);
12970          } else if (!strcasecmp(v->name, "fullname")) {
12971             ast_string_field_set(peer, cid_name, S_OR(v->value, ""));
12972             ast_set_flag64(peer, IAX_HASCALLERID);
12973          } else if (!strcasecmp(v->name, "cid_number")) {
12974             ast_string_field_set(peer, cid_num, S_OR(v->value, ""));
12975             ast_set_flag64(peer, IAX_HASCALLERID);
12976          } else if (!strcasecmp(v->name, "sendani")) {
12977             ast_set2_flag64(peer, ast_true(v->value), IAX_SENDANI);
12978          } else if (!strcasecmp(v->name, "inkeys")) {
12979             ast_string_field_set(peer, inkeys, v->value);
12980          } else if (!strcasecmp(v->name, "outkey")) {
12981             ast_string_field_set(peer, outkey, v->value);
12982          } else if (!strcasecmp(v->name, "qualify")) {
12983             if (!strcasecmp(v->value, "no")) {
12984                peer->maxms = 0;
12985             } else if (!strcasecmp(v->value, "yes")) {
12986                peer->maxms = DEFAULT_MAXMS;
12987             } else if (sscanf(v->value, "%30d", &peer->maxms) != 1) {
12988                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);
12989                peer->maxms = 0;
12990             }
12991          } else if (!strcasecmp(v->name, "qualifysmoothing")) {
12992             peer->smoothing = ast_true(v->value);
12993          } else if (!strcasecmp(v->name, "qualifyfreqok")) {
12994             if (sscanf(v->value, "%30d", &peer->pokefreqok) != 1) {
12995                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);
12996             }
12997          } else if (!strcasecmp(v->name, "qualifyfreqnotok")) {
12998             if (sscanf(v->value, "%30d", &peer->pokefreqnotok) != 1) {
12999                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);
13000             }
13001          } else if (!strcasecmp(v->name, "timezone")) {
13002             ast_string_field_set(peer, zonetag, v->value);
13003          } else if (!strcasecmp(v->name, "adsi")) {
13004             peer->adsi = ast_true(v->value);
13005          } else if (!strcasecmp(v->name, "connectedline")) {
13006             if (ast_true(v->value)) {
13007                ast_set_flag64(peer, IAX_SENDCONNECTEDLINE | IAX_RECVCONNECTEDLINE);
13008             } else if (!strcasecmp(v->value, "send")) {
13009                ast_clear_flag64(peer, IAX_RECVCONNECTEDLINE);
13010                ast_set_flag64(peer, IAX_SENDCONNECTEDLINE);
13011             } else if (!strcasecmp(v->value, "receive")) {
13012                ast_clear_flag64(peer, IAX_SENDCONNECTEDLINE);
13013                ast_set_flag64(peer, IAX_RECVCONNECTEDLINE);
13014             } else {
13015                ast_clear_flag64(peer, IAX_SENDCONNECTEDLINE | IAX_RECVCONNECTEDLINE);
13016             }
13017          } else if (!strcasecmp(v->name, "maxcallnumbers")) {
13018             if (sscanf(v->value, "%10hu", &peer->maxcallno) != 1) {
13019                ast_log(LOG_WARNING, "maxcallnumbers must be set to a valid number. %s is not valid at line %d.\n", v->value, v->lineno);
13020             } else {
13021                peercnt_modify((unsigned char) 1, peer->maxcallno, &peer->addr);
13022             }
13023          } else if (!strcasecmp(v->name, "requirecalltoken")) {
13024             /* default is required unless in optional ip list */
13025             if (ast_false(v->value)) {
13026                peer->calltoken_required = CALLTOKEN_NO;
13027             } else if (!strcasecmp(v->value, "auto")) {
13028                peer->calltoken_required = CALLTOKEN_AUTO;
13029             } else if (ast_true(v->value)) {
13030                peer->calltoken_required = CALLTOKEN_YES;
13031             } else {
13032                ast_log(LOG_WARNING, "requirecalltoken must be set to a valid value. at line %d\n", v->lineno);
13033             }
13034          } /* else if (strcasecmp(v->name,"type")) */
13035          /* ast_log(LOG_WARNING, "Ignoring %s\n", v->name); */
13036          v = v->next;
13037          if (!v) {
13038             v = alt;
13039             alt = NULL;
13040          }
13041       }
13042       if (!peer->authmethods)
13043          peer->authmethods = IAX_AUTH_MD5 | IAX_AUTH_PLAINTEXT;
13044       ast_clear_flag64(peer, IAX_DELME);
13045    }
13046 
13047    if (oldacl)
13048       ast_free_acl_list(oldacl);
13049 
13050    if (!ast_strlen_zero(peer->mailbox)) {
13051       char *mailbox, *context;
13052       context = mailbox = ast_strdupa(peer->mailbox);
13053       strsep(&context, "@");
13054       if (ast_strlen_zero(context))
13055          context = "default";
13056       peer->mwi_event_sub = ast_event_subscribe(AST_EVENT_MWI, mwi_event_cb, "IAX MWI subscription", NULL,
13057          AST_EVENT_IE_MAILBOX, AST_EVENT_IE_PLTYPE_STR, mailbox,
13058          AST_EVENT_IE_CONTEXT, AST_EVENT_IE_PLTYPE_STR, context,
13059          AST_EVENT_IE_END);
13060    }
13061 
13062    if (subscribe_acl_change) {
13063       acl_change_event_subscribe();
13064    }
13065 
13066    return peer;
13067 }
13068 
13069 static void user_destructor(void *obj)
13070 {
13071    struct iax2_user *user = obj;
13072 
13073    ast_free_acl_list(user->acl);
13074    free_context(user->contexts);
13075    if(user->vars) {
13076       ast_variables_destroy(user->vars);
13077       user->vars = NULL;
13078    }
13079    ast_string_field_free_memory(user);
13080 }
13081 
13082 /*! \brief Create in-memory user structure from configuration */
13083 static struct iax2_user *build_user(const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly)
13084 {
13085    struct iax2_user *user = NULL;
13086    struct iax2_context *con, *conl = NULL;
13087    struct ast_acl_list *oldacl = NULL;
13088    struct iax2_context *oldcon = NULL;
13089    int format;
13090    int firstpass=1;
13091    int oldcurauthreq = 0;
13092    int subscribe_acl_change = 0;
13093    char *varname = NULL, *varval = NULL;
13094    struct ast_variable *tmpvar = NULL;
13095 
13096    if (!temponly) {
13097       user = ao2_find(users, name, OBJ_KEY);
13098       if (user && !ast_test_flag64(user, IAX_DELME))
13099          firstpass = 0;
13100    }
13101 
13102    if (user) {
13103       if (firstpass) {
13104          oldcurauthreq = user->curauthreq;
13105          oldacl = user->acl;
13106          oldcon = user->contexts;
13107          user->acl = NULL;
13108          user->contexts = NULL;
13109       }
13110       /* Already in the list, remove it and it will be added back (or FREE'd) */
13111       ao2_unlink(users, user);
13112    } else {
13113       user = ao2_alloc(sizeof(*user), user_destructor);
13114    }
13115    
13116    if (user) {
13117       if (firstpass) {
13118          ast_string_field_free_memory(user);
13119          memset(user, 0, sizeof(struct iax2_user));
13120          if (ast_string_field_init(user, 32)) {
13121             user = user_unref(user);
13122             goto cleanup;
13123          }
13124          user->maxauthreq = maxauthreq;
13125          user->curauthreq = oldcurauthreq;
13126          user->prefs = prefs;
13127          user->capability = iax2_capability;
13128          user->encmethods = iax2_encryption;
13129          user->adsi = adsi;
13130          user->calltoken_required = CALLTOKEN_DEFAULT;
13131          ast_string_field_set(user, name, name);
13132          ast_string_field_set(user, language, language);
13133          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);
13134          ast_clear_flag64(user, IAX_HASCALLERID);
13135          ast_string_field_set(user, cid_name, "");
13136          ast_string_field_set(user, cid_num, "");
13137          ast_string_field_set(user, accountcode, accountcode);
13138          ast_string_field_set(user, mohinterpret, mohinterpret);
13139          ast_string_field_set(user, mohsuggest, mohsuggest);
13140       }
13141       if (!v) {
13142          v = alt;
13143          alt = NULL;
13144       }
13145       while(v) {
13146          if (!strcasecmp(v->name, "context")) {
13147             con = build_context(v->value);
13148             if (con) {
13149                if (conl)
13150                   conl->next = con;
13151                else
13152                   user->contexts = con;
13153                conl = con;
13154             }
13155          } else if (!strcasecmp(v->name, "permit") ||
13156                   !strcasecmp(v->name, "deny") ||
13157                   !strcasecmp(v->name, "acl")) {
13158             ast_append_acl(v->name, v->value, &user->acl, NULL, &subscribe_acl_change);
13159          } else if (!strcasecmp(v->name, "setvar")) {
13160             varname = ast_strdupa(v->value);
13161             if ((varval = strchr(varname, '='))) {
13162                *varval = '\0';
13163                varval++;
13164                if((tmpvar = ast_variable_new(varname, varval, ""))) {
13165                   tmpvar->next = user->vars; 
13166                   user->vars = tmpvar;
13167                }
13168             }
13169          } else if (!strcasecmp(v->name, "allow")) {
13170             iax2_parse_allow_disallow(&user->prefs, &user->capability, v->value, 1);
13171          } else if (!strcasecmp(v->name, "disallow")) {
13172             iax2_parse_allow_disallow(&user->prefs, &user->capability,v->value, 0);
13173          } else if (!strcasecmp(v->name, "trunk")) {
13174             ast_set2_flag64(user, ast_true(v->value), IAX_TRUNK); 
13175             if (ast_test_flag64(user, IAX_TRUNK) && !timer) {
13176                ast_log(LOG_WARNING, "Unable to support trunking on user '%s' without a timing interface\n", user->name);
13177                ast_clear_flag64(user, IAX_TRUNK);
13178             }
13179          } else if (!strcasecmp(v->name, "auth")) {
13180             user->authmethods = get_auth_methods(v->value);
13181          } else if (!strcasecmp(v->name, "encryption")) {
13182             user->encmethods |= get_encrypt_methods(v->value);
13183             if (!user->encmethods) {
13184                ast_clear_flag64(user, IAX_FORCE_ENCRYPT);
13185             }
13186          } else if (!strcasecmp(v->name, "forceencryption")) {
13187             if (ast_false(v->value)) {
13188                ast_clear_flag64(user, IAX_FORCE_ENCRYPT);
13189             } else {
13190                user->encmethods |= get_encrypt_methods(v->value);
13191                if (user->encmethods) {
13192                   ast_set_flag64(user, IAX_FORCE_ENCRYPT);
13193                }
13194             }
13195          } else if (!strcasecmp(v->name, "transfer")) {
13196             if (!strcasecmp(v->value, "mediaonly")) {
13197                ast_set_flags_to64(user, IAX_NOTRANSFER|IAX_TRANSFERMEDIA, IAX_TRANSFERMEDIA);
13198             } else if (ast_true(v->value)) {
13199                ast_set_flags_to64(user, IAX_NOTRANSFER|IAX_TRANSFERMEDIA, 0);
13200             } else
13201                ast_set_flags_to64(user, IAX_NOTRANSFER|IAX_TRANSFERMEDIA, IAX_NOTRANSFER);
13202          } else if (!strcasecmp(v->name, "codecpriority")) {
13203             if(!strcasecmp(v->value, "caller"))
13204                ast_set_flag64(user, IAX_CODEC_USER_FIRST);
13205             else if(!strcasecmp(v->value, "disabled"))
13206                ast_set_flag64(user, IAX_CODEC_NOPREFS);
13207             else if(!strcasecmp(v->value, "reqonly")) {
13208                ast_set_flag64(user, IAX_CODEC_NOCAP);
13209                ast_set_flag64(user, IAX_CODEC_NOPREFS);
13210             }
13211          } else if (!strcasecmp(v->name, "immediate")) {
13212             ast_set2_flag64(user, ast_true(v->value), IAX_IMMEDIATE);
13213          } else if (!strcasecmp(v->name, "jitterbuffer")) {
13214             ast_set2_flag64(user, ast_true(v->value), IAX_USEJITTERBUF);
13215          } else if (!strcasecmp(v->name, "forcejitterbuffer")) {
13216             ast_set2_flag64(user, ast_true(v->value), IAX_FORCEJITTERBUF);
13217          } else if (!strcasecmp(v->name, "dbsecret")) {
13218             ast_string_field_set(user, dbsecret, v->value);
13219          } else if (!strcasecmp(v->name, "secret")) {
13220             if (!ast_strlen_zero(user->secret)) {
13221                char *old = ast_strdupa(user->secret);
13222 
13223                ast_string_field_build(user, secret, "%s;%s", old, v->value);
13224             } else
13225                ast_string_field_set(user, secret, v->value);
13226          } else if (!strcasecmp(v->name, "callerid")) {
13227             if (!ast_strlen_zero(v->value) && strcasecmp(v->value, "asreceived")) {
13228                char name2[80];
13229                char num2[80];
13230                ast_callerid_split(v->value, name2, sizeof(name2), num2, sizeof(num2));
13231                ast_string_field_set(user, cid_name, name2);
13232                ast_string_field_set(user, cid_num, num2);
13233                ast_set_flag64(user, IAX_HASCALLERID);
13234             } else {
13235                ast_clear_flag64(user, IAX_HASCALLERID);
13236                ast_string_field_set(user, cid_name, "");
13237                ast_string_field_set(user, cid_num, "");
13238             }
13239          } else if (!strcasecmp(v->name, "fullname")) {
13240             if (!ast_strlen_zero(v->value)) {
13241                ast_string_field_set(user, cid_name, v->value);
13242                ast_set_flag64(user, IAX_HASCALLERID);
13243             } else {
13244                ast_string_field_set(user, cid_name, "");
13245                if (ast_strlen_zero(user->cid_num))
13246                   ast_clear_flag64(user, IAX_HASCALLERID);
13247             }
13248          } else if (!strcasecmp(v->name, "cid_number")) {
13249             if (!ast_strlen_zero(v->value)) {
13250                ast_string_field_set(user, cid_num, v->value);
13251                ast_set_flag64(user, IAX_HASCALLERID);
13252             } else {
13253                ast_string_field_set(user, cid_num, "");
13254                if (ast_strlen_zero(user->cid_name))
13255                   ast_clear_flag64(user, IAX_HASCALLERID);
13256             }
13257          } else if (!strcasecmp(v->name, "accountcode")) {
13258             ast_string_field_set(user, accountcode, v->value);
13259          } else if (!strcasecmp(v->name, "mohinterpret")) {
13260             ast_string_field_set(user, mohinterpret, v->value);
13261          } else if (!strcasecmp(v->name, "mohsuggest")) {
13262             ast_string_field_set(user, mohsuggest, v->value);
13263          } else if (!strcasecmp(v->name, "parkinglot")) {
13264             ast_string_field_set(user, parkinglot, v->value);
13265          } else if (!strcasecmp(v->name, "language")) {
13266             ast_string_field_set(user, language, v->value);
13267          } else if (!strcasecmp(v->name, "amaflags")) {
13268             format = ast_cdr_amaflags2int(v->value);
13269             if (format < 0) {
13270                ast_log(LOG_WARNING, "Invalid AMA Flags: %s at line %d\n", v->value, v->lineno);
13271             } else {
13272                user->amaflags = format;
13273             }
13274          } else if (!strcasecmp(v->name, "inkeys")) {
13275             ast_string_field_set(user, inkeys, v->value);
13276          } else if (!strcasecmp(v->name, "maxauthreq")) {
13277             user->maxauthreq = atoi(v->value);
13278             if (user->maxauthreq < 0)
13279                user->maxauthreq = 0;
13280          } else if (!strcasecmp(v->name, "adsi")) {
13281             user->adsi = ast_true(v->value);
13282          } else if (!strcasecmp(v->name, "connectedline")) {
13283             if (ast_true(v->value)) {
13284                ast_set_flag64(user, IAX_SENDCONNECTEDLINE | IAX_RECVCONNECTEDLINE);
13285             } else if (!strcasecmp(v->value, "send")) {
13286                ast_clear_flag64(user, IAX_RECVCONNECTEDLINE);
13287                ast_set_flag64(user, IAX_SENDCONNECTEDLINE);
13288             } else if (!strcasecmp(v->value, "receive")) {
13289                ast_clear_flag64(user, IAX_SENDCONNECTEDLINE);
13290                ast_set_flag64(user, IAX_RECVCONNECTEDLINE);
13291             } else {
13292                ast_clear_flag64(user, IAX_SENDCONNECTEDLINE | IAX_RECVCONNECTEDLINE);
13293             }
13294          } else if (!strcasecmp(v->name, "requirecalltoken")) {
13295             /* default is required unless in optional ip list */
13296             if (ast_false(v->value)) {
13297                user->calltoken_required = CALLTOKEN_NO;
13298             } else if (!strcasecmp(v->value, "auto")) {
13299                user->calltoken_required = CALLTOKEN_AUTO;
13300             } else if (ast_true(v->value)) {
13301                user->calltoken_required = CALLTOKEN_YES;
13302             } else {
13303                ast_log(LOG_WARNING, "requirecalltoken must be set to a valid value. at line %d\n", v->lineno);
13304             }
13305          } /* else if (strcasecmp(v->name,"type")) */
13306          /* ast_log(LOG_WARNING, "Ignoring %s\n", v->name); */
13307          v = v->next;
13308          if (!v) {
13309             v = alt;
13310             alt = NULL;
13311          }
13312       }
13313       if (!user->authmethods) {
13314          if (!ast_strlen_zero(user->secret)) {
13315             user->authmethods = IAX_AUTH_MD5 | IAX_AUTH_PLAINTEXT;
13316             if (!ast_strlen_zero(user->inkeys))
13317                user->authmethods |= IAX_AUTH_RSA;
13318          } else if (!ast_strlen_zero(user->inkeys)) {
13319             user->authmethods = IAX_AUTH_RSA;
13320          } else {
13321             user->authmethods = IAX_AUTH_MD5 | IAX_AUTH_PLAINTEXT;
13322          }
13323       }
13324       ast_clear_flag64(user, IAX_DELME);
13325    }
13326 cleanup:
13327    if (oldacl) {
13328       ast_free_acl_list(oldacl);
13329    }
13330    if (oldcon) {
13331       free_context(oldcon);
13332    }
13333 
13334    if (subscribe_acl_change) {
13335       acl_change_event_subscribe();
13336    }
13337 
13338    return user;
13339 }
13340 
13341 static int peer_delme_cb(void *obj, void *arg, int flags)
13342 {
13343    struct iax2_peer *peer = obj;
13344 
13345    ast_set_flag64(peer, IAX_DELME);
13346 
13347    return 0;
13348 }
13349 
13350 static int user_delme_cb(void *obj, void *arg, int flags)
13351 {
13352    struct iax2_user *user = obj;
13353 
13354    ast_set_flag64(user, IAX_DELME);
13355 
13356    return 0;
13357 }
13358 
13359 static void delete_users(void)
13360 {
13361    struct iax2_registry *reg;
13362 
13363    ao2_callback(users, OBJ_NODATA, user_delme_cb, NULL);
13364 
13365    AST_LIST_LOCK(&registrations);
13366    while ((reg = AST_LIST_REMOVE_HEAD(&registrations, entry))) {
13367       if (sched) {
13368          AST_SCHED_DEL(sched, reg->expire);
13369       }
13370       if (reg->callno) {
13371          int callno = reg->callno;
13372          ast_mutex_lock(&iaxsl[callno]);
13373          if (iaxs[callno]) {
13374             iaxs[callno]->reg = NULL;
13375             iax2_destroy(callno);
13376          }
13377          ast_mutex_unlock(&iaxsl[callno]);
13378       }
13379       if (reg->dnsmgr)
13380          ast_dnsmgr_release(reg->dnsmgr);
13381       ast_free(reg);
13382    }
13383    AST_LIST_UNLOCK(&registrations);
13384 
13385    ao2_callback(peers, OBJ_NODATA, peer_delme_cb, NULL);
13386 }
13387 
13388 static void prune_users(void)
13389 {
13390    struct iax2_user *user;
13391    struct ao2_iterator i;
13392 
13393    i = ao2_iterator_init(users, 0);
13394    while ((user = ao2_iterator_next(&i))) {
13395       if (ast_test_flag64(user, IAX_DELME) || ast_test_flag64(user, IAX_RTCACHEFRIENDS)) {
13396          ao2_unlink(users, user);
13397       }
13398       user_unref(user);
13399    }
13400    ao2_iterator_destroy(&i);
13401 }
13402 
13403 /* Prune peers who still are supposed to be deleted */
13404 static void prune_peers(void)
13405 {
13406    struct iax2_peer *peer;
13407    struct ao2_iterator i;
13408 
13409    i = ao2_iterator_init(peers, 0);
13410    while ((peer = ao2_iterator_next(&i))) {
13411       if (ast_test_flag64(peer, IAX_DELME) || ast_test_flag64(peer, IAX_RTCACHEFRIENDS)) {
13412          unlink_peer(peer);
13413       }
13414       peer_unref(peer);
13415    }
13416    ao2_iterator_destroy(&i);
13417 }
13418 
13419 static void set_config_destroy(void)
13420 {
13421    strcpy(accountcode, "");
13422    strcpy(language, "");
13423    strcpy(mohinterpret, "");
13424    strcpy(mohsuggest, "");
13425    trunkmaxsize = MAX_TRUNKDATA;
13426    amaflags = 0;
13427    delayreject = 0;
13428    ast_clear_flag64((&globalflags), IAX_NOTRANSFER | IAX_TRANSFERMEDIA | IAX_USEJITTERBUF |
13429       IAX_FORCEJITTERBUF | IAX_SENDCONNECTEDLINE | IAX_RECVCONNECTEDLINE);
13430    delete_users();
13431    ao2_callback(callno_limits, OBJ_NODATA, addr_range_delme_cb, NULL);
13432    ao2_callback(calltoken_ignores, OBJ_NODATA, addr_range_delme_cb, NULL);
13433 }
13434 
13435 /*! \brief Load configuration */
13436 static int set_config(const char *config_file, int reload, int forced)
13437 {
13438    struct ast_config *cfg, *ucfg;
13439    iax2_format capability = iax2_capability;
13440    struct ast_variable *v;
13441    char *cat;
13442    const char *utype;
13443    const char *tosval;
13444    int format;
13445    int portno = IAX_DEFAULT_PORTNO;
13446    int  x;
13447    int mtuv;
13448    int subscribe_network_change = 1;
13449    struct iax2_user *user;
13450    struct iax2_peer *peer;
13451    struct ast_netsock *ns;
13452    struct ast_flags config_flags = { (reload && !forced) ? CONFIG_FLAG_FILEUNCHANGED : 0 };
13453 #if 0
13454    static unsigned short int last_port=0;
13455 #endif
13456 
13457    cfg = ast_config_load(config_file, config_flags);
13458 
13459    if (!cfg) {
13460       ast_log(LOG_ERROR, "Unable to load config %s\n", config_file);
13461       return -1;
13462    } else if (cfg == CONFIG_STATUS_FILEUNCHANGED) {
13463       ucfg = ast_config_load("users.conf", config_flags);
13464       if (ucfg == CONFIG_STATUS_FILEUNCHANGED)
13465          return 0;
13466       /* Otherwise we need to reread both files */
13467       ast_clear_flag(&config_flags, CONFIG_FLAG_FILEUNCHANGED);
13468       if ((cfg = ast_config_load(config_file, config_flags)) == CONFIG_STATUS_FILEINVALID) {
13469          ast_log(LOG_ERROR, "Config file %s is in an invalid format.  Aborting.\n", config_file);
13470          ast_config_destroy(ucfg);
13471          return 0;
13472       }
13473       if (!cfg) {
13474          /* should have been able to load the config here */
13475          ast_log(LOG_ERROR, "Unable to load config %s again\n", config_file);
13476          return -1;
13477       }
13478    } else if (cfg == CONFIG_STATUS_FILEINVALID) {
13479       ast_log(LOG_ERROR, "Config file %s is in an invalid format.  Aborting.\n", config_file);
13480       return 0;
13481    } else { /* iax.conf changed, gotta reread users.conf, too */
13482       ast_clear_flag(&config_flags, CONFIG_FLAG_FILEUNCHANGED);
13483       if ((ucfg = ast_config_load("users.conf", config_flags)) == CONFIG_STATUS_FILEINVALID) {
13484          ast_log(LOG_ERROR, "Config file users.conf is in an invalid format.  Aborting.\n");
13485          ast_config_destroy(cfg);
13486          return 0;
13487       }
13488    }
13489 
13490    if (reload) {
13491       set_config_destroy();
13492    }
13493 
13494    /* Reset global codec prefs */
13495    memset(&prefs, 0 , sizeof(struct ast_codec_pref));
13496 
13497    /* Reset Global Flags */
13498    memset(&globalflags, 0, sizeof(globalflags));
13499    ast_set_flag64(&globalflags, IAX_RTUPDATE);
13500    ast_set_flag64((&globalflags), IAX_SHRINKCALLERID);
13501 
13502 #ifdef SO_NO_CHECK
13503    nochecksums = 0;
13504 #endif
13505    /* Reset default parking lot */
13506    default_parkinglot[0] = '\0';
13507 
13508    min_reg_expire = IAX_DEFAULT_REG_EXPIRE;
13509    max_reg_expire = IAX_DEFAULT_REG_EXPIRE;
13510    global_max_trunk_mtu = MAX_TRUNK_MTU;
13511    global_maxcallno = DEFAULT_MAXCALLNO_LIMIT;
13512    global_maxcallno_nonval = DEFAULT_MAXCALLNO_LIMIT_NONVAL;
13513 
13514    maxauthreq = 3;
13515 
13516    srvlookup = 0;
13517 
13518    v = ast_variable_browse(cfg, "general");
13519 
13520    /* Seed initial tos value */
13521    tosval = ast_variable_retrieve(cfg, "general", "tos");
13522    if (tosval) {
13523       if (ast_str2tos(tosval, &qos.tos))
13524          ast_log(LOG_WARNING, "Invalid tos value, refer to QoS documentation\n");
13525    }
13526    /* Seed initial cos value */
13527    tosval = ast_variable_retrieve(cfg, "general", "cos");
13528    if (tosval) {
13529       if (ast_str2cos(tosval, &qos.cos))
13530          ast_log(LOG_WARNING, "Invalid cos value, refer to QoS documentation\n");
13531    }
13532    while(v) {
13533       if (!strcasecmp(v->name, "bindport")){ 
13534          if (reload)
13535             ast_log(LOG_NOTICE, "Ignoring bindport on reload\n");
13536          else
13537             portno = atoi(v->value);
13538       } else if (!strcasecmp(v->name, "pingtime")) 
13539          ping_time = atoi(v->value);
13540       else if (!strcasecmp(v->name, "iaxthreadcount")) {
13541          if (reload) {
13542             if (atoi(v->value) != iaxthreadcount)
13543                ast_log(LOG_NOTICE, "Ignoring any changes to iaxthreadcount during reload\n");
13544          } else {
13545             iaxthreadcount = atoi(v->value);
13546             if (iaxthreadcount < 1) {
13547                ast_log(LOG_NOTICE, "iaxthreadcount must be at least 1.\n");
13548                iaxthreadcount = 1;
13549             } else if (iaxthreadcount > 256) {
13550                ast_log(LOG_NOTICE, "limiting iaxthreadcount to 256\n");
13551                iaxthreadcount = 256;
13552             }
13553          }
13554       } else if (!strcasecmp(v->name, "iaxmaxthreadcount")) {
13555          if (reload) {
13556             AST_LIST_LOCK(&dynamic_list);
13557             iaxmaxthreadcount = atoi(v->value);
13558             AST_LIST_UNLOCK(&dynamic_list);
13559          } else {
13560             iaxmaxthreadcount = atoi(v->value);
13561             if (iaxmaxthreadcount < 0) {
13562                ast_log(LOG_NOTICE, "iaxmaxthreadcount must be at least 0.\n");
13563                iaxmaxthreadcount = 0;
13564             } else if (iaxmaxthreadcount > 256) {
13565                ast_log(LOG_NOTICE, "Limiting iaxmaxthreadcount to 256\n");
13566                iaxmaxthreadcount = 256;
13567             }
13568          }
13569       } else if (!strcasecmp(v->name, "nochecksums")) {
13570 #ifdef SO_NO_CHECK
13571          if (ast_true(v->value))
13572             nochecksums = 1;
13573          else
13574             nochecksums = 0;
13575 #else
13576          if (ast_true(v->value))
13577             ast_log(LOG_WARNING, "Disabling RTP checksums is not supported on this operating system!\n");
13578 #endif
13579       }
13580       else if (!strcasecmp(v->name, "maxjitterbuffer")) 
13581          maxjitterbuffer = atoi(v->value);
13582       else if (!strcasecmp(v->name, "resyncthreshold")) 
13583          resyncthreshold = atoi(v->value);
13584       else if (!strcasecmp(v->name, "maxjitterinterps")) 
13585          maxjitterinterps = atoi(v->value);
13586       else if (!strcasecmp(v->name, "jittertargetextra"))
13587          jittertargetextra = atoi(v->value);
13588       else if (!strcasecmp(v->name, "lagrqtime")) 
13589          lagrq_time = atoi(v->value);
13590       else if (!strcasecmp(v->name, "maxregexpire")) 
13591          max_reg_expire = atoi(v->value);
13592       else if (!strcasecmp(v->name, "minregexpire")) 
13593          min_reg_expire = atoi(v->value);
13594       else if (!strcasecmp(v->name, "bindaddr")) {
13595          if (reload) {
13596             ast_log(LOG_NOTICE, "Ignoring bindaddr on reload\n");
13597          } else {
13598             if (!(ns = ast_netsock_bind(netsock, io, v->value, portno, qos.tos, qos.cos, socket_read, NULL))) {
13599                ast_log(LOG_WARNING, "Unable apply binding to '%s' at line %d\n", v->value, v->lineno);
13600             } else {
13601                   if (strchr(v->value, ':'))
13602                   ast_verb(2, "Binding IAX2 to '%s'\n", v->value);
13603                   else
13604                   ast_verb(2, "Binding IAX2 to '%s:%d'\n", v->value, portno);
13605                if (defaultsockfd < 0) 
13606                   defaultsockfd = ast_netsock_sockfd(ns);
13607                ast_netsock_unref(ns);
13608             }
13609          }
13610       } else if (!strcasecmp(v->name, "authdebug")) {
13611          authdebug = ast_true(v->value);
13612       } else if (!strcasecmp(v->name, "encryption")) {
13613             iax2_encryption |= get_encrypt_methods(v->value);
13614             if (!iax2_encryption) {
13615                ast_clear_flag64((&globalflags), IAX_FORCE_ENCRYPT);
13616             }
13617       } else if (!strcasecmp(v->name, "forceencryption")) {
13618          if (ast_false(v->value)) {
13619             ast_clear_flag64((&globalflags), IAX_FORCE_ENCRYPT);
13620          } else {
13621             iax2_encryption |= get_encrypt_methods(v->value);
13622             if (iax2_encryption) {
13623                ast_set_flag64((&globalflags), IAX_FORCE_ENCRYPT);
13624             }
13625          }
13626       } else if (!strcasecmp(v->name, "transfer")) {
13627          if (!strcasecmp(v->value, "mediaonly")) {
13628             ast_set_flags_to64((&globalflags), IAX_NOTRANSFER|IAX_TRANSFERMEDIA, IAX_TRANSFERMEDIA);
13629          } else if (ast_true(v->value)) {
13630             ast_set_flags_to64((&globalflags), IAX_NOTRANSFER|IAX_TRANSFERMEDIA, 0);
13631          } else
13632             ast_set_flags_to64((&globalflags), IAX_NOTRANSFER|IAX_TRANSFERMEDIA, IAX_NOTRANSFER);
13633       } else if (!strcasecmp(v->name, "codecpriority")) {
13634          if(!strcasecmp(v->value, "caller"))
13635             ast_set_flag64((&globalflags), IAX_CODEC_USER_FIRST);
13636          else if(!strcasecmp(v->value, "disabled"))
13637             ast_set_flag64((&globalflags), IAX_CODEC_NOPREFS);
13638          else if(!strcasecmp(v->value, "reqonly")) {
13639             ast_set_flag64((&globalflags), IAX_CODEC_NOCAP);
13640             ast_set_flag64((&globalflags), IAX_CODEC_NOPREFS);
13641          }
13642       } else if (!strcasecmp(v->name, "jitterbuffer"))
13643          ast_set2_flag64((&globalflags), ast_true(v->value), IAX_USEJITTERBUF);
13644       else if (!strcasecmp(v->name, "forcejitterbuffer"))
13645          ast_set2_flag64((&globalflags), ast_true(v->value), IAX_FORCEJITTERBUF);
13646       else if (!strcasecmp(v->name, "delayreject"))
13647          delayreject = ast_true(v->value);
13648       else if (!strcasecmp(v->name, "allowfwdownload"))
13649          ast_set2_flag64((&globalflags), ast_true(v->value), IAX_ALLOWFWDOWNLOAD);
13650       else if (!strcasecmp(v->name, "rtcachefriends"))
13651          ast_set2_flag64((&globalflags), ast_true(v->value), IAX_RTCACHEFRIENDS);
13652       else if (!strcasecmp(v->name, "rtignoreregexpire"))
13653          ast_set2_flag64((&globalflags), ast_true(v->value), IAX_RTIGNOREREGEXPIRE);
13654       else if (!strcasecmp(v->name, "rtupdate"))
13655          ast_set2_flag64((&globalflags), ast_true(v->value), IAX_RTUPDATE);
13656       else if (!strcasecmp(v->name, "rtsavesysname"))
13657          ast_set2_flag64((&globalflags), ast_true(v->value), IAX_RTSAVE_SYSNAME);
13658       else if (!strcasecmp(v->name, "trunktimestamps"))
13659          ast_set2_flag64(&globalflags, ast_true(v->value), IAX_TRUNKTIMESTAMPS);
13660       else if (!strcasecmp(v->name, "rtautoclear")) {
13661          int i = atoi(v->value);
13662          if(i > 0)
13663             global_rtautoclear = i;
13664          else
13665             i = 0;
13666          ast_set2_flag64((&globalflags), i || ast_true(v->value), IAX_RTAUTOCLEAR);
13667       } else if (!strcasecmp(v->name, "trunkfreq")) {
13668          trunkfreq = atoi(v->value);
13669          if (trunkfreq < 10) {
13670             ast_log(LOG_NOTICE, "trunkfreq must be between 10ms and 1000ms, using 10ms instead.\n");
13671             trunkfreq = 10;
13672          } else if (trunkfreq > 1000) {
13673             ast_log(LOG_NOTICE, "trunkfreq must be between 10ms and 1000ms, using 1000ms instead.\n");
13674             trunkfreq = 1000;
13675          }
13676          if (timer) {
13677             ast_timer_set_rate(timer, 1000 / trunkfreq);
13678          }
13679       } else if (!strcasecmp(v->name, "trunkmtu")) {
13680          mtuv = atoi(v->value);
13681          if (mtuv  == 0 )
13682             global_max_trunk_mtu = 0;
13683          else if (mtuv >= 172 && mtuv < 4000)
13684             global_max_trunk_mtu = mtuv;
13685          else
13686             ast_log(LOG_NOTICE, "trunkmtu value out of bounds (%d) at line %d\n",
13687                mtuv, v->lineno);
13688       } else if (!strcasecmp(v->name, "trunkmaxsize")) {
13689          trunkmaxsize = atoi(v->value);
13690          if (trunkmaxsize == 0)
13691             trunkmaxsize = MAX_TRUNKDATA;
13692       } else if (!strcasecmp(v->name, "autokill")) {
13693          if (sscanf(v->value, "%30d", &x) == 1) {
13694             if (x >= 0)
13695                autokill = x;
13696             else
13697                ast_log(LOG_NOTICE, "Nice try, but autokill has to be >0 or 'yes' or 'no' at line %d\n", v->lineno);
13698          } else if (ast_true(v->value)) {
13699             autokill = DEFAULT_MAXMS;
13700          } else {
13701             autokill = 0;
13702          }
13703       } else if (!strcasecmp(v->name, "bandwidth")) {
13704          if (!strcasecmp(v->value, "low")) {
13705             capability = IAX_CAPABILITY_LOWBANDWIDTH;
13706          } else if (!strcasecmp(v->value, "medium")) {
13707             capability = IAX_CAPABILITY_MEDBANDWIDTH;
13708          } else if (!strcasecmp(v->value, "high")) {
13709             capability = IAX_CAPABILITY_FULLBANDWIDTH;
13710          } else
13711             ast_log(LOG_WARNING, "bandwidth must be either low, medium, or high\n");
13712       } else if (!strcasecmp(v->name, "allow")) {
13713          iax2_parse_allow_disallow(&prefs, &capability, v->value, 1);
13714       } else if (!strcasecmp(v->name, "disallow")) {
13715          iax2_parse_allow_disallow(&prefs, &capability, v->value, 0);
13716       } else if (!strcasecmp(v->name, "register")) {
13717          iax2_register(v->value, v->lineno);
13718       } else if (!strcasecmp(v->name, "iaxcompat")) {
13719          iaxcompat = ast_true(v->value);
13720       } else if (!strcasecmp(v->name, "regcontext")) {
13721          ast_copy_string(regcontext, v->value, sizeof(regcontext));
13722          /* Create context if it doesn't exist already */
13723          ast_context_find_or_create(NULL, NULL, regcontext, "IAX2");
13724       } else if (!strcasecmp(v->name, "tos")) {
13725          if (ast_str2tos(v->value, &qos.tos))
13726             ast_log(LOG_WARNING, "Invalid tos value at line %d, refer to QoS documentation\n", v->lineno);
13727       } else if (!strcasecmp(v->name, "cos")) {
13728          if (ast_str2cos(v->value, &qos.cos))
13729             ast_log(LOG_WARNING, "Invalid cos value at line %d, refer to QoS documentation\n", v->lineno);
13730       } else if (!strcasecmp(v->name, "parkinglot")) {
13731          ast_copy_string(default_parkinglot, v->value, sizeof(default_parkinglot));
13732       } else if (!strcasecmp(v->name, "accountcode")) {
13733          ast_copy_string(accountcode, v->value, sizeof(accountcode));
13734       } else if (!strcasecmp(v->name, "mohinterpret")) {
13735          ast_copy_string(mohinterpret, v->value, sizeof(mohinterpret));
13736       } else if (!strcasecmp(v->name, "mohsuggest")) {
13737          ast_copy_string(mohsuggest, v->value, sizeof(mohsuggest));
13738       } else if (!strcasecmp(v->name, "amaflags")) {
13739          format = ast_cdr_amaflags2int(v->value);
13740          if (format < 0) {
13741             ast_log(LOG_WARNING, "Invalid AMA Flags: %s at line %d\n", v->value, v->lineno);
13742          } else {
13743             amaflags = format;
13744          }
13745       } else if (!strcasecmp(v->name, "language")) {
13746          ast_copy_string(language, v->value, sizeof(language));
13747       } else if (!strcasecmp(v->name, "maxauthreq")) {
13748          maxauthreq = atoi(v->value);
13749          if (maxauthreq < 0)
13750             maxauthreq = 0;
13751       } else if (!strcasecmp(v->name, "adsi")) {
13752          adsi = ast_true(v->value);
13753       } else if (!strcasecmp(v->name, "srvlookup")) {
13754          srvlookup = ast_true(v->value);
13755       } else if (!strcasecmp(v->name, "connectedline")) {
13756          if (ast_true(v->value)) {
13757             ast_set_flag64((&globalflags), IAX_SENDCONNECTEDLINE | IAX_RECVCONNECTEDLINE);
13758          } else if (!strcasecmp(v->value, "send")) {
13759             ast_clear_flag64((&globalflags), IAX_RECVCONNECTEDLINE);
13760             ast_set_flag64((&globalflags), IAX_SENDCONNECTEDLINE);
13761          } else if (!strcasecmp(v->value, "receive")) {
13762             ast_clear_flag64((&globalflags), IAX_SENDCONNECTEDLINE);
13763             ast_set_flag64((&globalflags), IAX_RECVCONNECTEDLINE);
13764          } else {
13765             ast_clear_flag64((&globalflags), IAX_SENDCONNECTEDLINE | IAX_RECVCONNECTEDLINE);
13766          }
13767       } else if (!strcasecmp(v->name, "maxcallnumbers")) {
13768          if (sscanf(v->value, "%10hu", &global_maxcallno) != 1) {
13769             ast_log(LOG_WARNING, "maxcallnumbers must be set to a valid number.  %s is not valid at line %d\n", v->value, v->lineno);
13770          }
13771       } else if (!strcasecmp(v->name, "maxcallnumbers_nonvalidated")) {
13772          if (sscanf(v->value, "%10hu", &global_maxcallno_nonval) != 1) {
13773             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);
13774          }
13775       } else if (!strcasecmp(v->name, "calltokenoptional")) {
13776          if (add_calltoken_ignore(v->value)) {
13777             ast_log(LOG_WARNING, "Invalid calltokenoptional address range - '%s' line %d\n", v->value, v->lineno);
13778          }
13779       } else if (!strcasecmp(v->name, "subscribe_network_change_event")) {
13780          if (ast_true(v->value)) {
13781             subscribe_network_change = 1;
13782          } else if (ast_false(v->value)) {
13783             subscribe_network_change = 0;
13784          } else {
13785             ast_log(LOG_WARNING, "subscribe_network_change_event value %s is not valid at line %d.\n", v->value, v->lineno);
13786          }
13787       } else if (!strcasecmp(v->name, "shrinkcallerid")) {
13788          if (ast_true(v->value)) {
13789             ast_set_flag64((&globalflags), IAX_SHRINKCALLERID);
13790          } else if (ast_false(v->value)) {
13791             ast_clear_flag64((&globalflags), IAX_SHRINKCALLERID);
13792          } else {
13793             ast_log(LOG_WARNING, "shrinkcallerid value %s is not valid at line %d.\n", v->value, v->lineno);
13794          }
13795       }/*else if (strcasecmp(v->name,"type")) */
13796       /* ast_log(LOG_WARNING, "Ignoring %s\n", v->name); */
13797       v = v->next;
13798    }
13799 
13800    if (subscribe_network_change) {
13801       network_change_event_subscribe();
13802    } else {
13803       network_change_event_unsubscribe();
13804    }
13805 
13806    if (defaultsockfd < 0) {
13807       if (!(ns = ast_netsock_bind(netsock, io, "0.0.0.0", portno, qos.tos, qos.cos, socket_read, NULL))) {
13808          ast_log(LOG_ERROR, "Unable to create network socket: %s\n", strerror(errno));
13809       } else {
13810          ast_verb(2, "Binding IAX2 to default address 0.0.0.0:%d\n", portno);
13811          defaultsockfd = ast_netsock_sockfd(ns);
13812          ast_netsock_unref(ns);
13813       }
13814    }
13815    if (reload) {
13816       ast_netsock_release(outsock);
13817       outsock = ast_netsock_list_alloc();
13818       if (!outsock) {
13819          ast_log(LOG_ERROR, "Could not allocate outsock list.\n");
13820          return -1;
13821       }
13822       ast_netsock_init(outsock);
13823    }
13824 
13825    if (min_reg_expire > max_reg_expire) {
13826       ast_log(LOG_WARNING, "Minimum registration interval of %d is more than maximum of %d, resetting minimum to %d\n",
13827          min_reg_expire, max_reg_expire, max_reg_expire);
13828       min_reg_expire = max_reg_expire;
13829    }
13830    iax2_capability = capability;
13831    
13832    if (ucfg) {
13833       struct ast_variable *gen;
13834       int genhasiax;
13835       int genregisteriax;
13836       const char *hasiax, *registeriax;
13837       
13838       genhasiax = ast_true(ast_variable_retrieve(ucfg, "general", "hasiax"));
13839       genregisteriax = ast_true(ast_variable_retrieve(ucfg, "general", "registeriax"));
13840       gen = ast_variable_browse(ucfg, "general");
13841       cat = ast_category_browse(ucfg, NULL);
13842       while (cat) {
13843          if (strcasecmp(cat, "general")) {
13844             hasiax = ast_variable_retrieve(ucfg, cat, "hasiax");
13845             registeriax = ast_variable_retrieve(ucfg, cat, "registeriax");
13846             if (ast_true(hasiax) || (!hasiax && genhasiax)) {
13847                /* Start with general parameters, then specific parameters, user and peer */
13848                user = build_user(cat, gen, ast_variable_browse(ucfg, cat), 0);
13849                if (user) {
13850                   ao2_link(users, user);
13851                   user = user_unref(user);
13852                }
13853                peer = build_peer(cat, gen, ast_variable_browse(ucfg, cat), 0);
13854                if (peer) {
13855                   if (ast_test_flag64(peer, IAX_DYNAMIC))
13856                      reg_source_db(peer);
13857                   ao2_link(peers, peer);
13858                   peer = peer_unref(peer);
13859                }
13860             }
13861             if (ast_true(registeriax) || (!registeriax && genregisteriax)) {
13862                char tmp[256];
13863                const char *host = ast_variable_retrieve(ucfg, cat, "host");
13864                const char *username = ast_variable_retrieve(ucfg, cat, "username");
13865                const char *secret = ast_variable_retrieve(ucfg, cat, "secret");
13866                if (!host)
13867                   host = ast_variable_retrieve(ucfg, "general", "host");
13868                if (!username)
13869                   username = ast_variable_retrieve(ucfg, "general", "username");
13870                if (!secret)
13871                   secret = ast_variable_retrieve(ucfg, "general", "secret");
13872                if (!ast_strlen_zero(username) && !ast_strlen_zero(host)) {
13873                   if (!ast_strlen_zero(secret))
13874                      snprintf(tmp, sizeof(tmp), "%s:%s@%s", username, secret, host);
13875                   else
13876                      snprintf(tmp, sizeof(tmp), "%s@%s", username, host);
13877                   iax2_register(tmp, 0);
13878                }
13879             }
13880          }
13881          cat = ast_category_browse(ucfg, cat);
13882       }
13883       ast_config_destroy(ucfg);
13884    }
13885    
13886    cat = ast_category_browse(cfg, NULL);
13887    while(cat) {
13888       if (strcasecmp(cat, "general")) {
13889          utype = ast_variable_retrieve(cfg, cat, "type");
13890          if (!strcasecmp(cat, "callnumberlimits")) {
13891             build_callno_limits(ast_variable_browse(cfg, cat));
13892          } else if (utype) {
13893             if (!strcasecmp(utype, "user") || !strcasecmp(utype, "friend")) {
13894                user = build_user(cat, ast_variable_browse(cfg, cat), NULL, 0);
13895                if (user) {
13896                   ao2_link(users, user);
13897                   user = user_unref(user);
13898                }
13899             }
13900             if (!strcasecmp(utype, "peer") || !strcasecmp(utype, "friend")) {
13901                peer = build_peer(cat, ast_variable_browse(cfg, cat), NULL, 0);
13902                if (peer) {
13903                   if (ast_test_flag64(peer, IAX_DYNAMIC))
13904                      reg_source_db(peer);
13905                   ao2_link(peers, peer);
13906                   peer = peer_unref(peer);
13907                }
13908             } else if (strcasecmp(utype, "user")) {
13909                ast_log(LOG_WARNING, "Unknown type '%s' for '%s' in %s\n", utype, cat, config_file);
13910             }
13911          } else
13912             ast_log(LOG_WARNING, "Section '%s' lacks type\n", cat);
13913       }
13914       cat = ast_category_browse(cfg, cat);
13915    }
13916    ast_config_destroy(cfg);
13917    return 1;
13918 }
13919 
13920 static void poke_all_peers(void)
13921 {
13922    struct ao2_iterator i;
13923    struct iax2_peer *peer;
13924 
13925    i = ao2_iterator_init(peers, 0);
13926    while ((peer = ao2_iterator_next(&i))) {
13927       iax2_poke_peer(peer, 0);
13928       peer_unref(peer);
13929    }
13930    ao2_iterator_destroy(&i);
13931 }
13932 static int reload_config(int forced_reload)
13933 {
13934    static const char config[] = "iax.conf";
13935    struct iax2_registry *reg;
13936 
13937    if (set_config(config, 1, forced_reload) > 0) {
13938       prune_peers();
13939       prune_users();
13940       ao2_callback(callno_limits, OBJ_NODATA | OBJ_UNLINK | OBJ_MULTIPLE, prune_addr_range_cb, NULL);
13941       ao2_callback(calltoken_ignores, OBJ_NODATA | OBJ_UNLINK | OBJ_MULTIPLE, prune_addr_range_cb, NULL);
13942       ao2_callback(peercnts, OBJ_NODATA, set_peercnt_limit_all_cb, NULL);
13943       trunk_timed = trunk_untimed = 0; 
13944       trunk_nmaxmtu = trunk_maxmtu = 0;
13945       memset(&debugaddr, '\0', sizeof(debugaddr));
13946 
13947       AST_LIST_LOCK(&registrations);
13948       AST_LIST_TRAVERSE(&registrations, reg, entry)
13949          iax2_do_register(reg);
13950       AST_LIST_UNLOCK(&registrations);
13951 
13952       /* Qualify hosts, too */
13953       poke_all_peers();
13954    }
13955    
13956    reload_firmware(0);
13957    iax_provision_reload(1);
13958    ast_unload_realtime("iaxpeers");
13959 
13960    return 0;
13961 }
13962 
13963 static char *handle_cli_iax2_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
13964 {
13965    switch (cmd) {
13966    case CLI_INIT:
13967       e->command = "iax2 reload";
13968       e->usage =
13969          "Usage: iax2 reload\n"
13970          "       Reloads IAX configuration from iax.conf\n";
13971       return NULL;
13972    case CLI_GENERATE:
13973       return NULL;
13974    }
13975 
13976    reload_config(0);
13977 
13978    return CLI_SUCCESS;
13979 }
13980 
13981 static int reload(void)
13982 {
13983    return reload_config(0);
13984 }
13985 
13986 static int cache_get_callno_locked(const char *data)
13987 {
13988    struct sockaddr_in sin;
13989    int x;
13990    int callno;
13991    struct iax_ie_data ied;
13992    struct create_addr_info cai;
13993    struct parsed_dial_string pds;
13994    char *tmpstr;
13995 
13996    for (x = 0; x < ARRAY_LEN(iaxs); x++) {
13997       /* Look for an *exact match* call.  Once a call is negotiated, it can only
13998          look up entries for a single context */
13999       if (!ast_mutex_trylock(&iaxsl[x])) {
14000          if (iaxs[x] && !strcasecmp(data, iaxs[x]->dproot))
14001             return x;
14002          ast_mutex_unlock(&iaxsl[x]);
14003       }
14004    }
14005 
14006    /* No match found, we need to create a new one */
14007 
14008    memset(&cai, 0, sizeof(cai));
14009    memset(&ied, 0, sizeof(ied));
14010    memset(&pds, 0, sizeof(pds));
14011 
14012    tmpstr = ast_strdupa(data);
14013    parse_dial_string(tmpstr, &pds);
14014 
14015    if (ast_strlen_zero(pds.peer)) {
14016       ast_log(LOG_WARNING, "No peer provided in the IAX2 dial string '%s'\n", data);
14017       return -1;
14018    }
14019 
14020    /* Populate our address from the given */
14021    if (create_addr(pds.peer, NULL, &sin, &cai))
14022       return -1;
14023 
14024    ast_debug(1, "peer: %s, username: %s, password: %s, context: %s\n",
14025       pds.peer, pds.username, pds.password, pds.context);
14026 
14027    callno = find_callno_locked(0, 0, &sin, NEW_FORCE, cai.sockfd, 0);
14028    if (callno < 1) {
14029       ast_log(LOG_WARNING, "Unable to create call\n");
14030       return -1;
14031    }
14032 
14033    ast_string_field_set(iaxs[callno], dproot, data);
14034    iaxs[callno]->capability = IAX_CAPABILITY_FULLBANDWIDTH;
14035 
14036    iax_ie_append_short(&ied, IAX_IE_VERSION, IAX_PROTO_VERSION);
14037    iax_ie_append_str(&ied, IAX_IE_CALLED_NUMBER, "TBD");
14038    /* the string format is slightly different from a standard dial string,
14039       because the context appears in the 'exten' position
14040    */
14041    if (pds.exten)
14042       iax_ie_append_str(&ied, IAX_IE_CALLED_CONTEXT, pds.exten);
14043    if (pds.username)
14044       iax_ie_append_str(&ied, IAX_IE_USERNAME, pds.username);
14045    iax_ie_append_int(&ied, IAX_IE_FORMAT, IAX_CAPABILITY_FULLBANDWIDTH);
14046    iax_ie_append_int(&ied, IAX_IE_CAPABILITY, IAX_CAPABILITY_FULLBANDWIDTH);
14047    /* Keep password handy */
14048    if (pds.password)
14049       ast_string_field_set(iaxs[callno], secret, pds.password);
14050    if (pds.key)
14051       ast_string_field_set(iaxs[callno], outkey, pds.key);
14052    /* Start the call going */
14053    add_empty_calltoken_ie(iaxs[callno], &ied); /* this _MUST_ be the last ie added */
14054    send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_NEW, 0, ied.buf, ied.pos, -1);
14055 
14056    return callno;
14057 }
14058 
14059 static struct iax2_dpcache *find_cache(struct ast_channel *chan, const char *data, const char *context, const char *exten, int priority)
14060 {
14061    struct iax2_dpcache *dp = NULL;
14062    struct timeval now = ast_tvnow();
14063    int x, com[2], timeout, old = 0, outfd, doabort, callno;
14064    struct ast_channel *c = NULL;
14065    struct ast_frame *f = NULL;
14066 
14067    AST_LIST_TRAVERSE_SAFE_BEGIN(&dpcache, dp, cache_list) {
14068       if (ast_tvcmp(now, dp->expiry) > 0) {
14069          AST_LIST_REMOVE_CURRENT(cache_list);
14070          if ((dp->flags & CACHE_FLAG_PENDING) || dp->callno)
14071             ast_log(LOG_WARNING, "DP still has peer field or pending or callno (flags = %d, peer = blah, callno = %d)\n", dp->flags, dp->callno);
14072          else
14073             ast_free(dp);
14074          continue;
14075       }
14076       if (!strcmp(dp->peercontext, data) && !strcmp(dp->exten, exten))
14077          break;
14078    }
14079    AST_LIST_TRAVERSE_SAFE_END;
14080 
14081    if (!dp) {
14082       /* No matching entry.  Create a new one. */
14083       /* First, can we make a callno? */
14084       if ((callno = cache_get_callno_locked(data)) < 0) {
14085          ast_log(LOG_WARNING, "Unable to generate call for '%s'\n", data);
14086          return NULL;
14087       }
14088       if (!(dp = ast_calloc(1, sizeof(*dp)))) {
14089          ast_mutex_unlock(&iaxsl[callno]);
14090          return NULL;
14091       }
14092       ast_copy_string(dp->peercontext, data, sizeof(dp->peercontext));
14093       ast_copy_string(dp->exten, exten, sizeof(dp->exten));
14094       dp->expiry = ast_tvnow();
14095       dp->orig = dp->expiry;
14096       /* Expires in 30 mins by default */
14097       dp->expiry.tv_sec += iaxdefaultdpcache;
14098       dp->flags = CACHE_FLAG_PENDING;
14099       for (x = 0; x < ARRAY_LEN(dp->waiters); x++)
14100          dp->waiters[x] = -1;
14101       /* Insert into the lists */
14102       AST_LIST_INSERT_TAIL(&dpcache, dp, cache_list);
14103       AST_LIST_INSERT_TAIL(&iaxs[callno]->dpentries, dp, peer_list);
14104       /* Send the request if we're already up */
14105       if (ast_test_flag(&iaxs[callno]->state, IAX_STATE_STARTED))
14106          iax2_dprequest(dp, callno);
14107       ast_mutex_unlock(&iaxsl[callno]);
14108    }
14109 
14110    /* By here we must have a dp */
14111    if (dp->flags & CACHE_FLAG_PENDING) {
14112       struct timeval start;
14113       int ms;
14114       /* Okay, here it starts to get nasty.  We need a pipe now to wait
14115          for a reply to come back so long as it's pending */
14116       for (x = 0; x < ARRAY_LEN(dp->waiters); x++) {
14117          /* Find an empty slot */
14118          if (dp->waiters[x] < 0)
14119             break;
14120       }
14121       if (x >= ARRAY_LEN(dp->waiters)) {
14122          ast_log(LOG_WARNING, "No more waiter positions available\n");
14123          return NULL;
14124       }
14125       if (pipe(com)) {
14126          ast_log(LOG_WARNING, "Unable to create pipe for comm\n");
14127          return NULL;
14128       }
14129       dp->waiters[x] = com[1];
14130       /* Okay, now we wait */
14131       timeout = iaxdefaulttimeout * 1000;
14132       /* Temporarily unlock */
14133       AST_LIST_UNLOCK(&dpcache);
14134       /* Defer any dtmf */
14135       if (chan)
14136          old = ast_channel_defer_dtmf(chan);
14137       doabort = 0;
14138       start = ast_tvnow();
14139       while ((ms = ast_remaining_ms(start, timeout))) {
14140          c = ast_waitfor_nandfds(&chan, chan ? 1 : 0, &com[0], 1, NULL, &outfd, &ms);
14141          if (outfd > -1)
14142             break;
14143          if (!c)
14144             continue;
14145          if (!(f = ast_read(c))) {
14146             doabort = 1;
14147             break;
14148          }
14149          ast_frfree(f);
14150       }
14151       if (!ms) {
14152          ast_log(LOG_WARNING, "Timeout waiting for %s exten %s\n", data, exten);
14153       }
14154       AST_LIST_LOCK(&dpcache);
14155       dp->waiters[x] = -1;
14156       close(com[1]);
14157       close(com[0]);
14158       if (doabort) {
14159          /* Don't interpret anything, just abort.  Not sure what th epoint
14160            of undeferring dtmf on a hung up channel is but hey whatever */
14161          if (!old && chan)
14162             ast_channel_undefer_dtmf(chan);
14163          return NULL;
14164       }
14165       if (!(dp->flags & CACHE_FLAG_TIMEOUT)) {
14166          /* Now to do non-independent analysis the results of our wait */
14167          if (dp->flags & CACHE_FLAG_PENDING) {
14168             /* Still pending... It's a timeout.  Wake everybody up.  Consider it no longer
14169                pending.  Don't let it take as long to timeout. */
14170             dp->flags &= ~CACHE_FLAG_PENDING;
14171             dp->flags |= CACHE_FLAG_TIMEOUT;
14172             /* Expire after only 60 seconds now.  This is designed to help reduce backlog in heavily loaded
14173                systems without leaving it unavailable once the server comes back online */
14174             dp->expiry.tv_sec = dp->orig.tv_sec + 60;
14175             for (x = 0; x < ARRAY_LEN(dp->waiters); x++) {
14176                if (dp->waiters[x] > -1) {
14177                   if (write(dp->waiters[x], "asdf", 4) < 0) {
14178                      ast_log(LOG_WARNING, "write() failed: %s\n", strerror(errno));
14179                   }
14180                }
14181             }
14182          }
14183       }
14184       /* Our caller will obtain the rest */
14185       if (!old && chan)
14186          ast_channel_undefer_dtmf(chan);
14187    }
14188    return dp;  
14189 }
14190 
14191 /*! \brief Part of the IAX2 switch interface */
14192 static int iax2_exists(struct ast_channel *chan, const char *context, const char *exten, int priority, const char *callerid, const char *data)
14193 {
14194    int res = 0;
14195    struct iax2_dpcache *dp = NULL;
14196 #if 0
14197    ast_log(LOG_NOTICE, "iax2_exists: con: %s, exten: %s, pri: %d, cid: %s, data: %s\n", context, exten, priority, callerid ? callerid : "<unknown>", data);
14198 #endif
14199    if ((priority != 1) && (priority != 2))
14200       return 0;
14201 
14202    AST_LIST_LOCK(&dpcache);
14203    if ((dp = find_cache(chan, data, context, exten, priority))) {
14204       if (dp->flags & CACHE_FLAG_EXISTS)
14205          res = 1;
14206    } else {
14207       ast_log(LOG_WARNING, "Unable to make DP cache\n");
14208    }
14209    AST_LIST_UNLOCK(&dpcache);
14210 
14211    return res;
14212 }
14213 
14214 /*! \brief part of the IAX2 dial plan switch interface */
14215 static int iax2_canmatch(struct ast_channel *chan, const char *context, const char *exten, int priority, const char *callerid, const char *data)
14216 {
14217    int res = 0;
14218    struct iax2_dpcache *dp = NULL;
14219 #if 0
14220    ast_log(LOG_NOTICE, "iax2_canmatch: con: %s, exten: %s, pri: %d, cid: %s, data: %s\n", context, exten, priority, callerid ? callerid : "<unknown>", data);
14221 #endif
14222    if ((priority != 1) && (priority != 2))
14223       return 0;
14224 
14225    AST_LIST_LOCK(&dpcache);
14226    if ((dp = find_cache(chan, data, context, exten, priority))) {
14227       if (dp->flags & CACHE_FLAG_CANEXIST)
14228          res = 1;
14229    } else {
14230       ast_log(LOG_WARNING, "Unable to make DP cache\n");
14231    }
14232    AST_LIST_UNLOCK(&dpcache);
14233 
14234    return res;
14235 }
14236 
14237 /*! \brief Part of the IAX2 Switch interface */
14238 static int iax2_matchmore(struct ast_channel *chan, const char *context, const char *exten, int priority, const char *callerid, const char *data)
14239 {
14240    int res = 0;
14241    struct iax2_dpcache *dp = NULL;
14242 #if 0
14243    ast_log(LOG_NOTICE, "iax2_matchmore: con: %s, exten: %s, pri: %d, cid: %s, data: %s\n", context, exten, priority, callerid ? callerid : "<unknown>", data);
14244 #endif
14245    if ((priority != 1) && (priority != 2))
14246       return 0;
14247 
14248    AST_LIST_LOCK(&dpcache);
14249    if ((dp = find_cache(chan, data, context, exten, priority))) {
14250       if (dp->flags & CACHE_FLAG_MATCHMORE)
14251          res = 1;
14252    } else {
14253       ast_log(LOG_WARNING, "Unable to make DP cache\n");
14254    }
14255    AST_LIST_UNLOCK(&dpcache);
14256 
14257    return res;
14258 }
14259 
14260 /*! \brief Execute IAX2 dialplan switch */
14261 static int iax2_exec(struct ast_channel *chan, const char *context, const char *exten, int priority, const char *callerid, const char *data)
14262 {
14263    char odata[256];
14264    char req[256];
14265    char *ncontext;
14266    struct iax2_dpcache *dp = NULL;
14267    struct ast_app *dial = NULL;
14268 #if 0
14269    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);
14270 #endif
14271    if (priority == 2) {
14272       /* Indicate status, can be overridden in dialplan */
14273       const char *dialstatus = pbx_builtin_getvar_helper(chan, "DIALSTATUS");
14274       if (dialstatus) {
14275          dial = pbx_findapp(dialstatus);
14276          if (dial) 
14277             pbx_exec(chan, dial, "");
14278       }
14279       return -1;
14280    } else if (priority != 1)
14281       return -1;
14282 
14283    AST_LIST_LOCK(&dpcache);
14284    if ((dp = find_cache(chan, data, context, exten, priority))) {
14285       if (dp->flags & CACHE_FLAG_EXISTS) {
14286          ast_copy_string(odata, data, sizeof(odata));
14287          ncontext = strchr(odata, '/');
14288          if (ncontext) {
14289             *ncontext = '\0';
14290             ncontext++;
14291             snprintf(req, sizeof(req), "IAX2/%s/%s@%s", odata, exten, ncontext);
14292          } else {
14293             snprintf(req, sizeof(req), "IAX2/%s/%s", odata, exten);
14294          }
14295          ast_verb(3, "Executing Dial('%s')\n", req);
14296       } else {
14297          AST_LIST_UNLOCK(&dpcache);
14298          ast_log(LOG_WARNING, "Can't execute nonexistent extension '%s[@%s]' in data '%s'\n", exten, context, data);
14299          return -1;
14300       }
14301    }
14302    AST_LIST_UNLOCK(&dpcache);
14303 
14304    if ((dial = pbx_findapp("Dial")))
14305       return pbx_exec(chan, dial, req);
14306    else
14307       ast_log(LOG_WARNING, "No dial application registered\n");
14308 
14309    return -1;
14310 }
14311 
14312 static int function_iaxpeer(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
14313 {
14314    struct iax2_peer *peer;
14315    char *peername, *colname;
14316 
14317    peername = ast_strdupa(data);
14318 
14319    /* if our channel, return the IP address of the endpoint of current channel */
14320    if (!strcmp(peername,"CURRENTCHANNEL")) {
14321            unsigned short callno;
14322       if (!chan || ast_channel_tech(chan) != &iax2_tech) {
14323          return -1;
14324       }
14325       callno = PTR_TO_CALLNO(ast_channel_tech_pvt(chan));   
14326       ast_copy_string(buf, iaxs[callno]->addr.sin_addr.s_addr ? ast_inet_ntoa(iaxs[callno]->addr.sin_addr) : "", len);
14327       return 0;
14328    }
14329 
14330    if ((colname = strchr(peername, ',')))
14331       *colname++ = '\0';
14332    else
14333       colname = "ip";
14334 
14335    if (!(peer = find_peer(peername, 1)))
14336       return -1;
14337 
14338    if (!strcasecmp(colname, "ip")) {
14339       ast_copy_string(buf, ast_sockaddr_stringify_addr(&peer->addr), len);
14340    } else  if (!strcasecmp(colname, "status")) {
14341       peer_status(peer, buf, len); 
14342    } else  if (!strcasecmp(colname, "mailbox")) {
14343       ast_copy_string(buf, peer->mailbox, len);
14344    } else  if (!strcasecmp(colname, "context")) {
14345       ast_copy_string(buf, peer->context, len);
14346    } else  if (!strcasecmp(colname, "expire")) {
14347       snprintf(buf, len, "%d", peer->expire);
14348    } else  if (!strcasecmp(colname, "dynamic")) {
14349       ast_copy_string(buf, (ast_test_flag64(peer, IAX_DYNAMIC) ? "yes" : "no"), len);
14350    } else  if (!strcasecmp(colname, "callerid_name")) {
14351       ast_copy_string(buf, peer->cid_name, len);
14352    } else  if (!strcasecmp(colname, "callerid_num")) {
14353       ast_copy_string(buf, peer->cid_num, len);
14354    } else  if (!strcasecmp(colname, "codecs")) {
14355       iax2_getformatname_multiple(buf, len -1, peer->capability);
14356    } else  if (!strncasecmp(colname, "codec[", 6)) {
14357       char *codecnum, *ptr;
14358       struct ast_format tmpfmt;
14359 
14360       /* skip over "codec" to the '[' */
14361       codecnum = colname + 5;
14362       *codecnum = '\0';
14363       codecnum++;
14364       if ((ptr = strchr(codecnum, ']'))) {
14365          *ptr = '\0';
14366       }
14367       if((ast_codec_pref_index(&peer->prefs, atoi(codecnum), &tmpfmt))) {
14368          ast_copy_string(buf, ast_getformatname(&tmpfmt), len);
14369       } else {
14370          buf[0] = '\0';
14371       }
14372    } else {
14373       buf[0] = '\0';
14374    }
14375 
14376    peer_unref(peer);
14377 
14378    return 0;
14379 }
14380 
14381 static struct ast_custom_function iaxpeer_function = {
14382    .name = "IAXPEER",
14383    .read = function_iaxpeer,
14384 };
14385 
14386 static int acf_channel_read(struct ast_channel *chan, const char *funcname, char *args, char *buf, size_t buflen)
14387 {
14388    struct chan_iax2_pvt *pvt;
14389    unsigned int callno;
14390    int res = 0;
14391 
14392    if (!chan || ast_channel_tech(chan) != &iax2_tech) {
14393       ast_log(LOG_ERROR, "This function requires a valid IAX2 channel\n");
14394       return -1;
14395    }
14396 
14397    callno = PTR_TO_CALLNO(ast_channel_tech_pvt(chan));
14398    ast_mutex_lock(&iaxsl[callno]);
14399    if (!(pvt = iaxs[callno])) {
14400       ast_mutex_unlock(&iaxsl[callno]);
14401       return -1;
14402    }
14403 
14404    if (!strcasecmp(args, "osptoken")) {
14405       ast_copy_string(buf, pvt->osptoken, buflen);
14406    } else if (!strcasecmp(args, "peerip")) {
14407       ast_copy_string(buf, pvt->addr.sin_addr.s_addr ? ast_inet_ntoa(pvt->addr.sin_addr) : "", buflen);
14408    } else if (!strcasecmp(args, "peername")) {
14409       ast_copy_string(buf, pvt->username, buflen);
14410    } else if (!strcasecmp(args, "secure_signaling") || !strcasecmp(args, "secure_media")) {
14411       snprintf(buf, buflen, "%s", IAX_CALLENCRYPTED(pvt) ? "1" : "");
14412    } else {
14413       res = -1;
14414    }
14415 
14416    ast_mutex_unlock(&iaxsl[callno]);
14417 
14418    return res;
14419 }
14420 
14421 /*! \brief Part of the device state notification system ---*/
14422 static int iax2_devicestate(const char *data)
14423 {
14424    struct parsed_dial_string pds;
14425    char *tmp = ast_strdupa(data);
14426    struct iax2_peer *p;
14427    int res = AST_DEVICE_INVALID;
14428 
14429    memset(&pds, 0, sizeof(pds));
14430    parse_dial_string(tmp, &pds);
14431 
14432    if (ast_strlen_zero(pds.peer)) {
14433       ast_log(LOG_WARNING, "No peer provided in the IAX2 dial string '%s'\n", data);
14434       return res;
14435    }
14436 
14437    ast_debug(3, "Checking device state for device %s\n", pds.peer);
14438 
14439    /* SLD: FIXME: second call to find_peer during registration */
14440    if (!(p = find_peer(pds.peer, 1)))
14441       return res;
14442 
14443    res = AST_DEVICE_UNAVAILABLE;
14444    ast_debug(3, "Found peer. What's device state of %s? addr=%d, defaddr=%d maxms=%d, lastms=%d\n",
14445       pds.peer, ast_sockaddr_ipv4(&p->addr), p->defaddr.sin_addr.s_addr, p->maxms, p->lastms);
14446 
14447    if ((ast_sockaddr_ipv4(&p->addr) || p->defaddr.sin_addr.s_addr) &&
14448        (!p->maxms || ((p->lastms > -1) && (p->historicms <= p->maxms)))) {
14449       /* Peer is registered, or have default IP address
14450          and a valid registration */
14451       if (p->historicms == 0 || p->historicms <= p->maxms)
14452          /* let the core figure out whether it is in use or not */
14453          res = AST_DEVICE_UNKNOWN;
14454    }
14455 
14456    peer_unref(p);
14457 
14458    return res;
14459 }
14460 
14461 static struct ast_switch iax2_switch =
14462 {
14463    .name        = "IAX2",
14464    .description = "IAX Remote Dialplan Switch",
14465    .exists      = iax2_exists,
14466    .canmatch    = iax2_canmatch,
14467    .exec        = iax2_exec,
14468    .matchmore   = iax2_matchmore,
14469 };
14470 
14471 /*
14472    { { "iax2", "show", "cache", NULL },
14473    iax2_show_cache, "Display IAX cached dialplan",
14474    show_cache_usage },
14475 
14476    { { "iax2", "show", "channels", NULL },
14477    iax2_show_channels, "List active IAX channels",
14478    show_channels_usage },
14479 
14480    { { "iax2", "show", "firmware", NULL },
14481    iax2_show_firmware, "List available IAX firmwares",
14482    show_firmware_usage },
14483 
14484    { { "iax2", "show", "netstats", NULL },
14485    iax2_show_netstats, "List active IAX channel netstats",
14486    show_netstats_usage },
14487 
14488    { { "iax2", "show", "peers", NULL },
14489    iax2_show_peers, "List defined IAX peers",
14490    show_peers_usage },
14491 
14492    { { "iax2", "show", "registry", NULL },
14493    iax2_show_registry, "Display IAX registration status",
14494    show_reg_usage },
14495 
14496    { { "iax2", "show", "stats", NULL },
14497    iax2_show_stats, "Display IAX statistics",
14498    show_stats_usage },
14499 
14500    { { "iax2", "show", "threads", NULL },
14501    iax2_show_threads, "Display IAX helper thread info",
14502    show_threads_usage },
14503 
14504    { { "iax2", "unregister", NULL },
14505    iax2_unregister, "Unregister (force expiration) an IAX2 peer from the registry",
14506    unregister_usage, complete_iax2_unregister },
14507 
14508    { { "iax2", "set", "mtu", NULL },
14509    iax2_set_mtu, "Set the IAX systemwide trunking MTU",
14510    set_mtu_usage, NULL, NULL },
14511 
14512    { { "iax2", "show", "users", NULL },
14513    iax2_show_users, "List defined IAX users",
14514    show_users_usage },
14515 
14516    { { "iax2", "prune", "realtime", NULL },
14517    iax2_prune_realtime, "Prune a cached realtime lookup",
14518    prune_realtime_usage, complete_iax2_show_peer },
14519 
14520    { { "iax2", "reload", NULL },
14521    iax2_reload, "Reload IAX configuration",
14522    iax2_reload_usage },
14523 
14524    { { "iax2", "show", "peer", NULL },
14525    iax2_show_peer, "Show details on specific IAX peer",
14526    show_peer_usage, complete_iax2_show_peer },
14527 
14528    { { "iax2", "set", "debug", NULL },
14529    iax2_do_debug, "Enable IAX debugging",
14530    debug_usage },
14531 
14532    { { "iax2", "set", "debug", "trunk", NULL },
14533    iax2_do_trunk_debug, "Enable IAX trunk debugging",
14534    debug_trunk_usage },
14535 
14536    { { "iax2", "set", "debug", "jb", NULL },
14537    iax2_do_jb_debug, "Enable IAX jitterbuffer debugging",
14538    debug_jb_usage },
14539 
14540    { { "iax2", "set", "debug", "off", NULL },
14541    iax2_no_debug, "Disable IAX debugging",
14542    no_debug_usage },
14543 
14544    { { "iax2", "set", "debug", "trunk", "off", NULL },
14545    iax2_no_trunk_debug, "Disable IAX trunk debugging",
14546    no_debug_trunk_usage },
14547 
14548    { { "iax2", "set", "debug", "jb", "off", NULL },
14549    iax2_no_jb_debug, "Disable IAX jitterbuffer debugging",
14550    no_debug_jb_usage },
14551 
14552    { { "iax2", "test", "losspct", NULL },
14553    iax2_test_losspct, "Set IAX2 incoming frame loss percentage",
14554    iax2_test_losspct_usage },
14555 
14556    { { "iax2", "provision", NULL },
14557    iax2_prov_cmd, "Provision an IAX device",
14558    show_prov_usage, iax2_prov_complete_template_3rd },
14559 
14560 #ifdef IAXTESTS
14561    { { "iax2", "test", "late", NULL },
14562    iax2_test_late, "Test the receipt of a late frame",
14563    iax2_test_late_usage },
14564 
14565    { { "iax2", "test", "resync", NULL },
14566    iax2_test_resync, "Test a resync in received timestamps",
14567    iax2_test_resync_usage },
14568 
14569    { { "iax2", "test", "jitter", NULL },
14570    iax2_test_jitter, "Simulates jitter for testing",
14571    iax2_test_jitter_usage },
14572 #endif
14573 */
14574 
14575 static struct ast_cli_entry cli_iax2[] = {
14576    AST_CLI_DEFINE(handle_cli_iax2_provision,           "Provision an IAX device"),
14577    AST_CLI_DEFINE(handle_cli_iax2_prune_realtime,      "Prune a cached realtime lookup"),
14578    AST_CLI_DEFINE(handle_cli_iax2_reload,              "Reload IAX configuration"),
14579    AST_CLI_DEFINE(handle_cli_iax2_set_mtu,             "Set the IAX systemwide trunking MTU"),
14580    AST_CLI_DEFINE(handle_cli_iax2_set_debug,           "Enable/Disable IAX debugging"),
14581    AST_CLI_DEFINE(handle_cli_iax2_set_debug_trunk,     "Enable/Disable IAX trunk debugging"),
14582    AST_CLI_DEFINE(handle_cli_iax2_set_debug_jb,        "Enable/Disable IAX jitterbuffer debugging"),
14583    AST_CLI_DEFINE(handle_cli_iax2_show_cache,          "Display IAX cached dialplan"),
14584    AST_CLI_DEFINE(handle_cli_iax2_show_channels,       "List active IAX channels"),
14585    AST_CLI_DEFINE(handle_cli_iax2_show_firmware,       "List available IAX firmware"),
14586    AST_CLI_DEFINE(handle_cli_iax2_show_netstats,       "List active IAX channel netstats"),
14587    AST_CLI_DEFINE(handle_cli_iax2_show_peer,           "Show details on specific IAX peer"),
14588    AST_CLI_DEFINE(handle_cli_iax2_show_peers,          "List defined IAX peers"),
14589    AST_CLI_DEFINE(handle_cli_iax2_show_registry,       "Display IAX registration status"),
14590    AST_CLI_DEFINE(handle_cli_iax2_show_stats,          "Display IAX statistics"),
14591    AST_CLI_DEFINE(handle_cli_iax2_show_threads,        "Display IAX helper thread info"),
14592    AST_CLI_DEFINE(handle_cli_iax2_show_users,          "List defined IAX users"),
14593    AST_CLI_DEFINE(handle_cli_iax2_test_losspct,        "Set IAX2 incoming frame loss percentage"),
14594    AST_CLI_DEFINE(handle_cli_iax2_unregister,          "Unregister (force expiration) an IAX2 peer from the registry"),
14595    AST_CLI_DEFINE(handle_cli_iax2_show_callno_limits,  "Show current entries in IP call number limit table"),
14596 #ifdef IAXTESTS
14597    AST_CLI_DEFINE(handle_cli_iax2_test_jitter,         "Simulates jitter for testing"),
14598    AST_CLI_DEFINE(handle_cli_iax2_test_late,           "Test the receipt of a late frame"),
14599    AST_CLI_DEFINE(handle_cli_iax2_test_resync,         "Test a resync in received timestamps"),
14600 #endif /* IAXTESTS */
14601 };
14602 
14603 #ifdef TEST_FRAMEWORK
14604 AST_TEST_DEFINE(test_iax2_peers_get)
14605 {
14606    struct ast_data_query query = {
14607       .path = "/asterisk/channel/iax2/peers",
14608       .search = "peers/peer/name=test_peer_data_provider"
14609    };
14610    struct ast_data *node;
14611    struct iax2_peer *peer;
14612 
14613    switch (cmd) {
14614       case TEST_INIT:
14615          info->name = "iax2_peers_get_data_test";
14616          info->category = "/main/data/iax2/peers/";
14617          info->summary = "IAX2 peers data providers unit test";
14618          info->description =
14619             "Tests whether the IAX2 peers data provider implementation works as expected.";
14620          return AST_TEST_NOT_RUN;
14621       case TEST_EXECUTE:
14622          break;
14623    }
14624 
14625    /* build a test peer */
14626    peer = build_peer("test_peer_data_provider", NULL, NULL, 0);
14627    if (!peer) {
14628       return AST_TEST_FAIL;
14629    }
14630    peer->expiry= 1010;
14631    ao2_link(peers, peer);
14632 
14633    node = ast_data_get(&query);
14634    if (!node) {
14635       ao2_unlink(peers, peer);
14636       peer_unref(peer);
14637       return AST_TEST_FAIL;
14638    }
14639 
14640    /* check returned data node. */
14641    if (strcmp(ast_data_retrieve_string(node, "peer/name"), "test_peer_data_provider")) {
14642       ao2_unlink(peers, peer);
14643       peer_unref(peer);
14644       ast_data_free(node);
14645       return AST_TEST_FAIL;
14646    }
14647 
14648    if (ast_data_retrieve_int(node, "peer/expiry") != 1010) {
14649       ao2_unlink(peers, peer);
14650       peer_unref(peer);
14651       ast_data_free(node);
14652       return AST_TEST_FAIL;
14653    }
14654 
14655    /* release resources */
14656    ast_data_free(node);
14657 
14658    ao2_unlink(peers, peer);
14659    peer_unref(peer);
14660 
14661    return AST_TEST_PASS;
14662 }
14663 
14664 AST_TEST_DEFINE(test_iax2_users_get)
14665 {
14666    struct ast_data_query query = {
14667       .path = "/asterisk/channel/iax2/users",
14668       .search = "users/user/name=test_user_data_provider"
14669    };
14670    struct ast_data *node;
14671    struct iax2_user *user;
14672 
14673    switch (cmd) {
14674       case TEST_INIT:
14675          info->name = "iax2_users_get_data_test";
14676          info->category = "/main/data/iax2/users/";
14677          info->summary = "IAX2 users data providers unit test";
14678          info->description =
14679             "Tests whether the IAX2 users data provider implementation works as expected.";
14680          return AST_TEST_NOT_RUN;
14681       case TEST_EXECUTE:
14682          break;
14683    }
14684 
14685    user = build_user("test_user_data_provider", NULL, NULL, 0);
14686    if (!user) {
14687       ast_test_status_update(test, "Failed to build a test user\n");
14688       return AST_TEST_FAIL;
14689    }
14690    user->amaflags = 1010;
14691    ao2_link(users, user);
14692 
14693    node = ast_data_get(&query);
14694    if (!node) {
14695       ast_test_status_update(test, "The data query to find our test user failed\n");
14696       ao2_unlink(users, user);
14697       user_unref(user);
14698       return AST_TEST_FAIL;
14699    }
14700 
14701    if (strcmp(ast_data_retrieve_string(node, "user/name"), "test_user_data_provider")) {
14702       ast_test_status_update(test, "Our data results did not return the test user created in the previous step.\n");
14703       ao2_unlink(users, user);
14704       user_unref(user);
14705       ast_data_free(node);
14706       return AST_TEST_FAIL;
14707    }
14708 
14709    if (ast_data_retrieve_int(node, "user/amaflags/value") != 1010) {
14710       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"));
14711       ao2_unlink(users, user);
14712       user_unref(user);
14713       ast_data_free(node);
14714       return AST_TEST_FAIL;
14715    }
14716 
14717    ast_data_free(node);
14718 
14719    ao2_unlink(users, user);
14720    user_unref(user);
14721 
14722    return AST_TEST_PASS;
14723 }
14724 #endif
14725 
14726 static void cleanup_thread_list(void *head)
14727 {
14728    AST_LIST_HEAD(iax2_thread_list, iax2_thread);
14729    struct iax2_thread_list *list_head = head;
14730    struct iax2_thread *thread;
14731 
14732    AST_LIST_LOCK(list_head);
14733    while ((thread = AST_LIST_REMOVE_HEAD(list_head, list))) {
14734       pthread_t thread_id = thread->threadid;
14735 
14736       thread->stop = 1;
14737       signal_condition(&thread->lock, &thread->cond);
14738 
14739       AST_LIST_UNLOCK(list_head);
14740       pthread_join(thread_id, NULL);
14741       AST_LIST_LOCK(list_head);
14742    }
14743    AST_LIST_UNLOCK(list_head);
14744 }
14745 
14746 static int __unload_module(void)
14747 {
14748    struct ast_context *con;
14749    int x;
14750 
14751    network_change_event_unsubscribe();
14752    acl_change_event_unsubscribe();
14753 
14754    ast_manager_unregister("IAXpeers");
14755    ast_manager_unregister("IAXpeerlist");
14756    ast_manager_unregister("IAXnetstats");
14757    ast_manager_unregister("IAXregistry");
14758    ast_unregister_application(papp);
14759    ast_cli_unregister_multiple(cli_iax2, ARRAY_LEN(cli_iax2));
14760    ast_unregister_switch(&iax2_switch);
14761    ast_channel_unregister(&iax2_tech);
14762 
14763    if (netthreadid != AST_PTHREADT_NULL) {
14764       pthread_cancel(netthreadid);
14765       pthread_kill(netthreadid, SIGURG);
14766       pthread_join(netthreadid, NULL);
14767    }
14768 
14769    for (x = 0; x < ARRAY_LEN(iaxs); x++) {
14770       if (iaxs[x]) {
14771          iax2_destroy(x);
14772       }
14773    }
14774 
14775    /* Call for all threads to halt */
14776    cleanup_thread_list(&active_list);
14777    cleanup_thread_list(&dynamic_list);
14778    cleanup_thread_list(&idle_list);
14779 
14780    ast_netsock_release(netsock);
14781    ast_netsock_release(outsock);
14782    for (x = 0; x < ARRAY_LEN(iaxs); x++) {
14783       if (iaxs[x]) {
14784          iax2_destroy(x);
14785       }
14786    }
14787    ast_manager_unregister( "IAXpeers" );
14788    ast_manager_unregister( "IAXpeerlist" );
14789    ast_manager_unregister( "IAXnetstats" );
14790    ast_manager_unregister( "IAXregistry" );
14791    ast_unregister_application(papp);
14792 #ifdef TEST_FRAMEWORK
14793    AST_TEST_UNREGISTER(test_iax2_peers_get);
14794    AST_TEST_UNREGISTER(test_iax2_users_get);
14795 #endif
14796    ast_data_unregister(NULL);
14797    ast_cli_unregister_multiple(cli_iax2, ARRAY_LEN(cli_iax2));
14798    ast_unregister_switch(&iax2_switch);
14799    ast_channel_unregister(&iax2_tech);
14800    delete_users();
14801    iax_provision_unload();
14802    reload_firmware(1);
14803 
14804    for (x = 0; x < ARRAY_LEN(iaxsl); x++) {
14805       ast_mutex_destroy(&iaxsl[x]);
14806    }
14807 
14808    ao2_ref(peers, -1);
14809    ao2_ref(users, -1);
14810    ao2_ref(iax_peercallno_pvts, -1);
14811    ao2_ref(iax_transfercallno_pvts, -1);
14812    ao2_ref(peercnts, -1);
14813    ao2_ref(callno_limits, -1);
14814    ao2_ref(calltoken_ignores, -1);
14815    ao2_ref(callno_pool, -1);
14816    ao2_ref(callno_pool_trunk, -1);
14817    if (timer) {
14818       ast_timer_close(timer);
14819       timer = NULL;
14820    }
14821    transmit_processor = ast_taskprocessor_unreference(transmit_processor);
14822    ast_sched_context_destroy(sched);
14823    sched = NULL;
14824 
14825    con = ast_context_find(regcontext);
14826    if (con)
14827       ast_context_destroy(con, "IAX2");
14828    ast_unload_realtime("iaxpeers");
14829 
14830    iax2_tech.capabilities = ast_format_cap_destroy(iax2_tech.capabilities);
14831    return 0;
14832 }
14833 
14834 static int unload_module(void)
14835 {
14836    ast_custom_function_unregister(&iaxpeer_function);
14837    ast_custom_function_unregister(&iaxvar_function);
14838    return __unload_module();
14839 }
14840 
14841 static int peer_set_sock_cb(void *obj, void *arg, int flags)
14842 {
14843    struct iax2_peer *peer = obj;
14844 
14845    if (peer->sockfd < 0)
14846       peer->sockfd = defaultsockfd;
14847 
14848    return 0;
14849 }
14850 
14851 static int pvt_hash_cb(const void *obj, const int flags)
14852 {
14853    const struct chan_iax2_pvt *pvt = obj;
14854 
14855    return pvt->peercallno;
14856 }
14857 
14858 static int pvt_cmp_cb(void *obj, void *arg, int flags)
14859 {
14860    struct chan_iax2_pvt *pvt = obj, *pvt2 = arg;
14861 
14862    /* The frames_received field is used to hold whether we're matching
14863     * against a full frame or not ... */
14864 
14865    return match(&pvt2->addr, pvt2->peercallno, pvt2->callno, pvt, 
14866       pvt2->frames_received) ? CMP_MATCH | CMP_STOP : 0;
14867 }
14868 
14869 static int transfercallno_pvt_hash_cb(const void *obj, const int flags)
14870 {
14871    const struct chan_iax2_pvt *pvt = obj;
14872 
14873    return pvt->transfercallno;
14874 }
14875 
14876 static int transfercallno_pvt_cmp_cb(void *obj, void *arg, int flags)
14877 {
14878    struct chan_iax2_pvt *pvt = obj, *pvt2 = arg;
14879 
14880    /* The frames_received field is used to hold whether we're matching
14881     * against a full frame or not ... */
14882 
14883    return match(&pvt2->transfer, pvt2->transfercallno, pvt2->callno, pvt,
14884       pvt2->frames_received) ? CMP_MATCH | CMP_STOP : 0;
14885 }
14886 
14887 static int load_objects(void)
14888 {
14889    peers = users = iax_peercallno_pvts = iax_transfercallno_pvts = NULL;
14890    peercnts = callno_limits = calltoken_ignores = callno_pool = callno_pool_trunk = NULL;
14891 
14892    if (!(peers = ao2_container_alloc(MAX_PEER_BUCKETS, peer_hash_cb, peer_cmp_cb))) {
14893       goto container_fail;
14894    } else if (!(users = ao2_container_alloc(MAX_USER_BUCKETS, user_hash_cb, user_cmp_cb))) {
14895       goto container_fail;
14896    } else if (!(iax_peercallno_pvts = ao2_container_alloc(IAX_MAX_CALLS, pvt_hash_cb, pvt_cmp_cb))) {
14897       goto container_fail;
14898    } else if (!(iax_transfercallno_pvts = ao2_container_alloc(IAX_MAX_CALLS, transfercallno_pvt_hash_cb, transfercallno_pvt_cmp_cb))) {
14899       goto container_fail;
14900    } else if (!(peercnts = ao2_container_alloc(MAX_PEER_BUCKETS, peercnt_hash_cb, peercnt_cmp_cb))) {
14901       goto container_fail;
14902    } else if (!(callno_limits = ao2_container_alloc(MAX_PEER_BUCKETS, addr_range_hash_cb, addr_range_cmp_cb))) {
14903       goto container_fail;
14904    } else if (!(calltoken_ignores = ao2_container_alloc(MAX_PEER_BUCKETS, addr_range_hash_cb, addr_range_cmp_cb))) {
14905       goto container_fail;
14906    } else if (create_callno_pools()) {
14907       goto container_fail;
14908    } else if  (!(transmit_processor = ast_taskprocessor_get("iax2_transmit", TPS_REF_DEFAULT))) {
14909       goto container_fail;
14910    }
14911 
14912    return 0;
14913 
14914 container_fail:
14915    if (peers) {
14916       ao2_ref(peers, -1);
14917    }
14918    if (users) {
14919       ao2_ref(users, -1);
14920    }
14921    if (iax_peercallno_pvts) {
14922       ao2_ref(iax_peercallno_pvts, -1);
14923    }
14924    if (iax_transfercallno_pvts) {
14925       ao2_ref(iax_transfercallno_pvts, -1);
14926    }
14927    if (peercnts) {
14928       ao2_ref(peercnts, -1);
14929    }
14930    if (callno_limits) {
14931       ao2_ref(callno_limits, -1);
14932    }
14933    if (calltoken_ignores) {
14934       ao2_ref(calltoken_ignores, -1);
14935    }
14936    if (callno_pool) {
14937       ao2_ref(callno_pool, -1);
14938    }
14939    if (callno_pool_trunk) {
14940       ao2_ref(callno_pool_trunk, -1);
14941    }
14942    return AST_MODULE_LOAD_FAILURE;
14943 }
14944 
14945 
14946 #define DATA_EXPORT_IAX2_PEER(MEMBER)           \
14947    MEMBER(iax2_peer, name, AST_DATA_STRING)     \
14948    MEMBER(iax2_peer, username, AST_DATA_STRING)    \
14949    MEMBER(iax2_peer, secret, AST_DATA_PASSWORD)    \
14950    MEMBER(iax2_peer, dbsecret, AST_DATA_PASSWORD)     \
14951    MEMBER(iax2_peer, outkey, AST_DATA_STRING)      \
14952    MEMBER(iax2_peer, regexten, AST_DATA_STRING)    \
14953    MEMBER(iax2_peer, context, AST_DATA_STRING)     \
14954    MEMBER(iax2_peer, peercontext, AST_DATA_STRING)    \
14955    MEMBER(iax2_peer, mailbox, AST_DATA_STRING)     \
14956    MEMBER(iax2_peer, mohinterpret, AST_DATA_STRING)   \
14957    MEMBER(iax2_peer, mohsuggest, AST_DATA_STRING)     \
14958    MEMBER(iax2_peer, inkeys, AST_DATA_STRING)      \
14959    MEMBER(iax2_peer, cid_num, AST_DATA_STRING)     \
14960    MEMBER(iax2_peer, cid_name, AST_DATA_STRING)    \
14961    MEMBER(iax2_peer, zonetag, AST_DATA_STRING)     \
14962    MEMBER(iax2_peer, parkinglot, AST_DATA_STRING)     \
14963    MEMBER(iax2_peer, expiry, AST_DATA_SECONDS)     \
14964    MEMBER(iax2_peer, callno, AST_DATA_INTEGER)     \
14965    MEMBER(iax2_peer, lastms, AST_DATA_MILLISECONDS)   \
14966    MEMBER(iax2_peer, maxms, AST_DATA_MILLISECONDS)    \
14967    MEMBER(iax2_peer, pokefreqok, AST_DATA_MILLISECONDS)  \
14968    MEMBER(iax2_peer, pokefreqnotok, AST_DATA_MILLISECONDS)  \
14969    MEMBER(iax2_peer, historicms, AST_DATA_INTEGER)    \
14970    MEMBER(iax2_peer, smoothing, AST_DATA_BOOLEAN)     \
14971         MEMBER(iax2_peer, maxcallno, AST_DATA_INTEGER)
14972 
14973 AST_DATA_STRUCTURE(iax2_peer, DATA_EXPORT_IAX2_PEER);
14974 
14975 static int peers_data_provider_get(const struct ast_data_search *search,
14976    struct ast_data *data_root)
14977 {
14978    struct ast_data *data_peer;
14979    struct iax2_peer *peer;
14980    struct ao2_iterator i;
14981    char status[20];
14982    struct ast_str *encmethods = ast_str_alloca(256);
14983 
14984    i = ao2_iterator_init(peers, 0);
14985    while ((peer = ao2_iterator_next(&i))) {
14986       data_peer = ast_data_add_node(data_root, "peer");
14987       if (!data_peer) {
14988          peer_unref(peer);
14989          continue;
14990       }
14991 
14992       ast_data_add_structure(iax2_peer, data_peer, peer);
14993 
14994       iax2_data_add_codecs(data_peer, "codecs", peer->capability);
14995 
14996       peer_status(peer, status, sizeof(status));
14997       ast_data_add_str(data_peer, "status", status);
14998 
14999       ast_data_add_str(data_peer, "host", ast_sockaddr_stringify_host(&peer->addr));
15000 
15001       ast_data_add_str(data_peer, "mask", ast_inet_ntoa(peer->mask));
15002 
15003       ast_data_add_int(data_peer, "port", ast_sockaddr_port(&peer->addr));
15004 
15005       ast_data_add_bool(data_peer, "trunk", ast_test_flag64(peer, IAX_TRUNK));
15006 
15007       ast_data_add_bool(data_peer, "dynamic", ast_test_flag64(peer, IAX_DYNAMIC));
15008 
15009       encmethods_to_str(peer->encmethods, &encmethods);
15010       ast_data_add_str(data_peer, "encryption", peer->encmethods ? ast_str_buffer(encmethods) : "no");
15011 
15012       peer_unref(peer);
15013 
15014       if (!ast_data_search_match(search, data_peer)) {
15015          ast_data_remove_node(data_root, data_peer);
15016       }
15017    }
15018    ao2_iterator_destroy(&i);
15019 
15020    return 0;
15021 }
15022 
15023 #define DATA_EXPORT_IAX2_USER(MEMBER)              \
15024         MEMBER(iax2_user, name, AST_DATA_STRING)         \
15025         MEMBER(iax2_user, dbsecret, AST_DATA_PASSWORD)         \
15026         MEMBER(iax2_user, accountcode, AST_DATA_STRING)        \
15027         MEMBER(iax2_user, mohinterpret, AST_DATA_STRING)    \
15028         MEMBER(iax2_user, mohsuggest, AST_DATA_STRING)         \
15029         MEMBER(iax2_user, inkeys, AST_DATA_STRING)       \
15030         MEMBER(iax2_user, language, AST_DATA_STRING)        \
15031         MEMBER(iax2_user, cid_num, AST_DATA_STRING)         \
15032         MEMBER(iax2_user, cid_name, AST_DATA_STRING)        \
15033         MEMBER(iax2_user, parkinglot, AST_DATA_STRING)         \
15034         MEMBER(iax2_user, maxauthreq, AST_DATA_INTEGER)        \
15035         MEMBER(iax2_user, curauthreq, AST_DATA_INTEGER)
15036 
15037 AST_DATA_STRUCTURE(iax2_user, DATA_EXPORT_IAX2_USER);
15038 
15039 static int users_data_provider_get(const struct ast_data_search *search,
15040    struct ast_data *data_root)
15041 {
15042    struct ast_data *data_user, *data_authmethods, *data_enum_node;
15043    struct iax2_user *user;
15044    struct ao2_iterator i;
15045    char auth[90];
15046    char *pstr = "";
15047 
15048    i = ao2_iterator_init(users, 0);
15049    for (; (user = ao2_iterator_next(&i)); user_unref(user)) {
15050       data_user = ast_data_add_node(data_root, "user");
15051       if (!data_user) {
15052          continue;
15053       }
15054 
15055       ast_data_add_structure(iax2_user, data_user, user);
15056 
15057       iax2_data_add_codecs(data_user, "codecs", user->capability);
15058 
15059       if (!ast_strlen_zero(user->secret)) {
15060          ast_copy_string(auth, user->secret, sizeof(auth));
15061       } else if (!ast_strlen_zero(user->inkeys)) {
15062          snprintf(auth, sizeof(auth), "Key: %s", user->inkeys);
15063       } else {
15064          ast_copy_string(auth, "no secret", sizeof(auth));
15065       }
15066       ast_data_add_password(data_user, "secret", auth);
15067 
15068       ast_data_add_str(data_user, "context", user->contexts ? user->contexts->context : DEFAULT_CONTEXT);
15069 
15070       /* authmethods */
15071       data_authmethods = ast_data_add_node(data_user, "authmethods");
15072       if (!data_authmethods) {
15073          ast_data_remove_node(data_root, data_user);
15074          continue;
15075       }
15076       ast_data_add_bool(data_authmethods, "rsa", user->authmethods & IAX_AUTH_RSA);
15077       ast_data_add_bool(data_authmethods, "md5", user->authmethods & IAX_AUTH_MD5);
15078       ast_data_add_bool(data_authmethods, "plaintext", user->authmethods & IAX_AUTH_PLAINTEXT);
15079 
15080       /* amaflags */
15081       data_enum_node = ast_data_add_node(data_user, "amaflags");
15082       if (!data_enum_node) {
15083          ast_data_remove_node(data_root, data_user);
15084          continue;
15085       }
15086       ast_data_add_int(data_enum_node, "value", user->amaflags);
15087       ast_data_add_str(data_enum_node, "text", ast_cdr_flags2str(user->amaflags));
15088 
15089       ast_data_add_bool(data_user, "access-control", ast_acl_list_is_empty(user->acl) ? 0 : 1);
15090 
15091       if (ast_test_flag64(user, IAX_CODEC_NOCAP)) {
15092          pstr = "REQ only";
15093       } else if (ast_test_flag64(user, IAX_CODEC_NOPREFS)) {
15094          pstr = "disabled";
15095       } else {
15096          pstr = ast_test_flag64(user, IAX_CODEC_USER_FIRST) ? "caller" : "host";
15097       }
15098       ast_data_add_str(data_user, "codec-preferences", pstr);
15099 
15100       if (!ast_data_search_match(search, data_user)) {
15101          ast_data_remove_node(data_root, data_user);
15102       }
15103    }
15104    ao2_iterator_destroy(&i);
15105 
15106    return 0;
15107 }
15108 
15109 static const struct ast_data_handler peers_data_provider = {
15110    .version = AST_DATA_HANDLER_VERSION,
15111    .get = peers_data_provider_get
15112 };
15113 
15114 static const struct ast_data_handler users_data_provider = {
15115    .version = AST_DATA_HANDLER_VERSION,
15116    .get = users_data_provider_get
15117 };
15118 
15119 static const struct ast_data_entry iax2_data_providers[] = {
15120    AST_DATA_ENTRY("asterisk/channel/iax2/peers", &peers_data_provider),
15121    AST_DATA_ENTRY("asterisk/channel/iax2/users", &users_data_provider),
15122 };
15123 
15124 /*! \brief Load IAX2 module, load configuraiton ---*/
15125 static int load_module(void)
15126 {
15127    static const char config[] = "iax.conf";
15128    int x = 0;
15129    struct iax2_registry *reg = NULL;
15130 
15131    if (!(iax2_tech.capabilities = ast_format_cap_alloc())) {
15132       return AST_MODULE_LOAD_FAILURE;
15133    }
15134    ast_format_cap_add_all(iax2_tech.capabilities);
15135 
15136    if (load_objects()) {
15137       return AST_MODULE_LOAD_FAILURE;
15138    }
15139 
15140    memset(iaxs, 0, sizeof(iaxs));
15141 
15142    for (x = 0; x < ARRAY_LEN(iaxsl); x++) {
15143       ast_mutex_init(&iaxsl[x]);
15144    }
15145 
15146    if (!(sched = ast_sched_context_create())) {
15147       ast_log(LOG_ERROR, "Failed to create scheduler thread\n");
15148       return AST_MODULE_LOAD_FAILURE;
15149    }
15150 
15151    if (ast_sched_start_thread(sched)) {
15152       ast_sched_context_destroy(sched);
15153       sched = NULL;
15154       return AST_MODULE_LOAD_FAILURE;
15155    }
15156 
15157    if (!(io = io_context_create())) {
15158       ast_log(LOG_ERROR, "Failed to create I/O context\n");
15159       ast_sched_context_destroy(sched);
15160       sched = NULL;
15161       return AST_MODULE_LOAD_FAILURE;
15162    }
15163 
15164    if (!(netsock = ast_netsock_list_alloc())) {
15165       ast_log(LOG_ERROR, "Failed to create netsock list\n");
15166       io_context_destroy(io);
15167       ast_sched_context_destroy(sched);
15168       sched = NULL;
15169       return AST_MODULE_LOAD_FAILURE;
15170    }
15171    ast_netsock_init(netsock);
15172    
15173    outsock = ast_netsock_list_alloc();
15174    if (!outsock) {
15175       ast_log(LOG_ERROR, "Could not allocate outsock list.\n");
15176       io_context_destroy(io);
15177       ast_sched_context_destroy(sched);
15178       sched = NULL;
15179       return AST_MODULE_LOAD_FAILURE;
15180    }
15181    ast_netsock_init(outsock);
15182 
15183    randomcalltokendata = ast_random();
15184 
15185    iax_set_output(iax_debug_output);
15186    iax_set_error(iax_error_output);
15187    jb_setoutput(jb_error_output, jb_warning_output, NULL);
15188    
15189    if ((timer = ast_timer_open())) {
15190       ast_timer_set_rate(timer, 1000 / trunkfreq);
15191    }
15192 
15193    if (set_config(config, 0, 0) == -1) {
15194       if (timer) {
15195          ast_timer_close(timer);
15196          timer = NULL;
15197       }
15198       return AST_MODULE_LOAD_DECLINE;
15199    }
15200 
15201 #ifdef TEST_FRAMEWORK
15202    AST_TEST_REGISTER(test_iax2_peers_get);
15203    AST_TEST_REGISTER(test_iax2_users_get);
15204 #endif
15205 
15206    /* Register AstData providers */
15207    ast_data_register_multiple(iax2_data_providers, ARRAY_LEN(iax2_data_providers));
15208    ast_cli_register_multiple(cli_iax2, ARRAY_LEN(cli_iax2));
15209 
15210    ast_register_application_xml(papp, iax2_prov_app);
15211 
15212    ast_custom_function_register(&iaxpeer_function);
15213    ast_custom_function_register(&iaxvar_function);
15214 
15215    ast_manager_register_xml("IAXpeers", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_iax2_show_peers);
15216    ast_manager_register_xml("IAXpeerlist", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_iax2_show_peer_list);
15217    ast_manager_register_xml("IAXnetstats", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_iax2_show_netstats);
15218    ast_manager_register_xml("IAXregistry", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_iax2_show_registry);
15219 
15220    if (ast_channel_register(&iax2_tech)) {
15221       ast_log(LOG_ERROR, "Unable to register channel class %s\n", "IAX2");
15222       __unload_module();
15223       return AST_MODULE_LOAD_FAILURE;
15224    }
15225 
15226    if (ast_register_switch(&iax2_switch)) {
15227       ast_log(LOG_ERROR, "Unable to register IAX switch\n");
15228    }
15229 
15230    if (start_network_thread()) {
15231       ast_log(LOG_ERROR, "Unable to start network thread\n");
15232       __unload_module();
15233       return AST_MODULE_LOAD_FAILURE;
15234    } else {
15235       ast_verb(2, "IAX Ready and Listening\n");
15236    }
15237 
15238    AST_LIST_LOCK(&registrations);
15239    AST_LIST_TRAVERSE(&registrations, reg, entry)
15240       iax2_do_register(reg);
15241    AST_LIST_UNLOCK(&registrations); 
15242    
15243    ao2_callback(peers, 0, peer_set_sock_cb, NULL);
15244    ao2_callback(peers, 0, iax2_poke_peer_cb, NULL);
15245 
15246 
15247    reload_firmware(0);
15248    iax_provision_reload(0);
15249 
15250    ast_realtime_require_field("iaxpeers", "name", RQ_CHAR, 10, "ipaddr", RQ_CHAR, 15, "port", RQ_UINTEGER2, 5, "regseconds", RQ_UINTEGER2, 6, SENTINEL);
15251 
15252    network_change_event_subscribe();
15253 
15254    return AST_MODULE_LOAD_SUCCESS;
15255 }
15256 
15257 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "Inter Asterisk eXchange (Ver 2)",
15258       .load = load_module,
15259       .unload = unload_module,
15260       .reload = reload,
15261       .load_pri = AST_MODPRI_CHANNEL_DRIVER,
15262       .nonoptreq = "res_crypto",
15263       );