Sat Mar 26 11:06:59 2011

Asterisk developer's documentation


chan_iax2.c

Go to the documentation of this file.
00001 /*
00002  * Asterisk -- An open source telephony toolkit.
00003  *
00004  * Copyright (C) 1999 - 2006, Digium, Inc.
00005  *
00006  * Mark Spencer <markster@digium.com>
00007  *
00008  * See http://www.asterisk.org for more information about
00009  * the Asterisk project. Please do not directly contact
00010  * any of the maintainers of this project for assistance;
00011  * the project provides a web site, mailing lists and IRC
00012  * channels for your use.
00013  *
00014  * This program is free software, distributed under the terms of
00015  * the GNU General Public License Version 2. See the LICENSE file
00016  * at the top of the source tree.
00017  */
00018 
00019 /*! \file
00020  *
00021  * \brief Implementation of Inter-Asterisk eXchange Version 2
00022  *        as specified in RFC 5456
00023  *
00024  * \author Mark Spencer <markster@digium.com>
00025  *
00026  * \par See also
00027  * \arg \ref Config_iax
00028  *
00029  * \ingroup channel_drivers
00030  * 
00031  * \todo Implement musicclass settings for IAX2 devices
00032  */
00033 
00034 /*** MODULEINFO
00035    <use>crypto</use>
00036  ***/
00037 
00038 #include "asterisk.h"
00039 
00040 ASTERISK_FILE_VERSION(__FILE__, "$Revision: 290506 $")
00041 
00042 #include <sys/mman.h>
00043 #include <dirent.h>
00044 #include <sys/socket.h>
00045 #include <netinet/in.h>
00046 #include <arpa/inet.h>
00047 #include <netinet/in_systm.h>
00048 #include <netinet/ip.h>
00049 #include <sys/time.h>
00050 #include <sys/signal.h>
00051 #include <signal.h>
00052 #include <strings.h>
00053 #include <netdb.h>
00054 #include <fcntl.h>
00055 #include <sys/stat.h>
00056 #include <regex.h>
00057 
00058 #include "asterisk/paths.h"   /* need ast_config_AST_DATA_DIR for firmware */
00059 
00060 #include "asterisk/lock.h"
00061 #include "asterisk/frame.h" 
00062 #include "asterisk/channel.h"
00063 #include "asterisk/module.h"
00064 #include "asterisk/pbx.h"
00065 #include "asterisk/sched.h"
00066 #include "asterisk/io.h"
00067 #include "asterisk/config.h"
00068 #include "asterisk/cli.h"
00069 #include "asterisk/translate.h"
00070 #include "asterisk/md5.h"
00071 #include "asterisk/cdr.h"
00072 #include "asterisk/crypto.h"
00073 #include "asterisk/acl.h"
00074 #include "asterisk/manager.h"
00075 #include "asterisk/callerid.h"
00076 #include "asterisk/app.h"
00077 #include "asterisk/astdb.h"
00078 #include "asterisk/musiconhold.h"
00079 #include "asterisk/features.h"
00080 #include "asterisk/utils.h"
00081 #include "asterisk/causes.h"
00082 #include "asterisk/localtime.h"
00083 #include "asterisk/dnsmgr.h"
00084 #include "asterisk/devicestate.h"
00085 #include "asterisk/netsock.h"
00086 #include "asterisk/stringfields.h"
00087 #include "asterisk/linkedlists.h"
00088 #include "asterisk/event.h"
00089 #include "asterisk/astobj2.h"
00090 #include "asterisk/timing.h"
00091 #include "asterisk/taskprocessor.h"
00092 #include "asterisk/test.h"
00093 #include "asterisk/data.h"
00094 #include "asterisk/netsock2.h"
00095 
00096 #include "iax2.h"
00097 #include "iax2-parser.h"
00098 #include "iax2-provision.h"
00099 #include "jitterbuf.h"
00100 
00101 /*** DOCUMENTATION
00102    <application name="IAX2Provision" language="en_US">
00103       <synopsis>
00104          Provision a calling IAXy with a given template.
00105       </synopsis>
00106       <syntax>
00107          <parameter name="template">
00108             <para>If not specified, defaults to <literal>default</literal>.</para>
00109          </parameter>
00110       </syntax>
00111       <description>
00112          <para>Provisions the calling IAXy (assuming the calling entity is in fact an IAXy) with the
00113          given <replaceable>template</replaceable>. Returns <literal>-1</literal> on error
00114          or <literal>0</literal> on success.</para>
00115       </description>
00116    </application>
00117    <function name="IAXPEER" language="en_US">
00118       <synopsis>
00119          Gets IAX peer information.
00120       </synopsis>
00121       <syntax>
00122          <parameter name="peername" required="true">
00123             <enumlist>
00124                <enum name="CURRENTCHANNEL">
00125                   <para>If <replaceable>peername</replaceable> is specified to this value, return the IP address of the
00126                   endpoint of the current channel</para>
00127                </enum>
00128             </enumlist>
00129          </parameter>
00130          <parameter name="item">
00131             <para>If <replaceable>peername</replaceable> is specified, valid items are:</para>
00132             <enumlist>
00133                <enum name="ip">
00134                   <para>(default) The IP address.</para>
00135                </enum>
00136                <enum name="status">
00137                   <para>The peer's status (if <literal>qualify=yes</literal>)</para>
00138                </enum>
00139                <enum name="mailbox">
00140                   <para>The configured mailbox.</para>
00141                </enum>
00142                <enum name="context">
00143                   <para>The configured context.</para>
00144                </enum>
00145                <enum name="expire">
00146                   <para>The epoch time of the next expire.</para>
00147                </enum>
00148                <enum name="dynamic">
00149                   <para>Is it dynamic? (yes/no).</para>
00150                </enum>
00151                <enum name="callerid_name">
00152                   <para>The configured Caller ID name.</para>
00153                </enum>
00154                <enum name="callerid_num">
00155                   <para>The configured Caller ID number.</para>
00156                </enum>
00157                <enum name="codecs">
00158                   <para>The configured codecs.</para>
00159                </enum>
00160                <enum name="codec[x]">
00161                   <para>Preferred codec index number <replaceable>x</replaceable> (beginning
00162                   with <literal>0</literal>)</para>
00163                </enum>
00164             </enumlist>
00165          </parameter>
00166       </syntax>
00167       <description />
00168       <see-also>
00169          <ref type="function">SIPPEER</ref>
00170       </see-also>
00171    </function>
00172    <function name="IAXVAR" language="en_US">
00173       <synopsis>
00174          Sets or retrieves a remote variable.
00175       </synopsis>
00176       <syntax>
00177          <parameter name="varname" required="true" />
00178       </syntax>
00179       <description />
00180    </function>
00181    <manager name="IAXpeers" language="en_US">
00182       <synopsis>
00183          List IAX peers.
00184       </synopsis>
00185       <syntax>
00186          <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
00187       </syntax>
00188       <description>
00189       </description>
00190    </manager>
00191    <manager name="IAXpeerlist" language="en_US">
00192       <synopsis>
00193          List IAX Peers.
00194       </synopsis>
00195       <syntax>
00196          <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
00197       </syntax>
00198       <description>
00199          <para>List all the IAX peers.</para>
00200       </description>
00201    </manager>
00202    <manager name="IAXnetstats" language="en_US">
00203       <synopsis>
00204          Show IAX Netstats.
00205       </synopsis>
00206       <syntax />
00207       <description>
00208          <para>Show IAX channels network statistics.</para>
00209       </description>
00210    </manager>
00211    <manager name="IAXregistry" language="en_US">
00212       <synopsis>
00213          Show IAX registrations.
00214       </synopsis>
00215       <syntax>
00216          <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
00217       </syntax>
00218       <description>
00219          <para>Show IAX registrations.</para>
00220       </description>
00221    </manager>
00222  ***/
00223 
00224 /* Define SCHED_MULTITHREADED to run the scheduler in a special
00225    multithreaded mode. */
00226 #define SCHED_MULTITHREADED
00227 
00228 /* Define DEBUG_SCHED_MULTITHREADED to keep track of where each
00229    thread is actually doing. */
00230 #define DEBUG_SCHED_MULTITHREAD
00231 
00232 
00233 #ifdef SO_NO_CHECK
00234 static int nochecksums = 0;
00235 #endif
00236 
00237 #define PTR_TO_CALLNO(a) ((unsigned short)(unsigned long)(a))
00238 #define CALLNO_TO_PTR(a) ((void *)(unsigned long)(a))
00239 
00240 #define DEFAULT_THREAD_COUNT 10
00241 #define DEFAULT_MAX_THREAD_COUNT 100
00242 #define DEFAULT_RETRY_TIME 1000
00243 #define MEMORY_SIZE 100
00244 #define DEFAULT_DROP 3
00245 
00246 #define DEBUG_SUPPORT
00247 
00248 #define MIN_REUSE_TIME     60 /* Don't reuse a call number within 60 seconds */
00249 
00250 /* Sample over last 100 units to determine historic jitter */
00251 #define GAMMA (0.01)
00252 
00253 static struct ast_codec_pref prefs;
00254 
00255 static const char tdesc[] = "Inter Asterisk eXchange Driver (Ver 2)";
00256 
00257 
00258 /*! \brief Maximum transmission unit for the UDP packet in the trunk not to be
00259     fragmented. This is based on 1516 - ethernet - ip - udp - iax minus one g711 frame = 1240 */
00260 #define MAX_TRUNK_MTU 1240
00261 
00262 static int global_max_trunk_mtu; /*!< Maximum MTU, 0 if not used */
00263 static int trunk_timed, trunk_untimed, trunk_maxmtu, trunk_nmaxmtu ; /*!< Trunk MTU statistics */
00264 
00265 #define DEFAULT_CONTEXT "default"
00266 
00267 static char default_parkinglot[AST_MAX_CONTEXT];
00268 
00269 static char language[MAX_LANGUAGE] = "";
00270 static char regcontext[AST_MAX_CONTEXT] = "";
00271 
00272 static struct ast_event_sub *network_change_event_subscription; /*!< subscription id for network change events */
00273 static int network_change_event_sched_id = -1;
00274 
00275 static int maxauthreq = 3;
00276 static int max_retries = 4;
00277 static int ping_time = 21;
00278 static int lagrq_time = 10;
00279 static int maxjitterbuffer=1000;
00280 static int resyncthreshold=1000;
00281 static int maxjitterinterps=10;
00282 static int jittertargetextra = 40; /* number of milliseconds the new jitter buffer adds on to its size */
00283 
00284 #define MAX_TRUNKDATA           640 * 200       /*!< 40ms, uncompressed linear * 200 channels */
00285 
00286 static int trunkfreq = 20;
00287 static int trunkmaxsize = MAX_TRUNKDATA;
00288 
00289 static int authdebug = 1;
00290 static int autokill = 0;
00291 static int iaxcompat = 0;
00292 static int last_authmethod = 0;
00293 
00294 static int iaxdefaultdpcache=10 * 60;  /* Cache dialplan entries for 10 minutes by default */
00295 
00296 static int iaxdefaulttimeout = 5;      /* Default to wait no more than 5 seconds for a reply to come back */
00297 
00298 static struct {
00299    unsigned int tos;
00300    unsigned int cos;
00301 } qos = { 0, 0 };
00302 
00303 static int min_reg_expire;
00304 static int max_reg_expire;
00305 
00306 static int srvlookup = 0;
00307 
00308 static struct ast_timer *timer;           /* Timer for trunking */
00309 
00310 static struct ast_netsock_list *netsock;
00311 static struct ast_netsock_list *outsock;     /*!< used if sourceaddress specified and bindaddr == INADDR_ANY */
00312 static int defaultsockfd = -1;
00313 
00314 static int (*iax2_regfunk)(const char *username, int onoff) = NULL;
00315 
00316 /* Ethernet, etc */
00317 #define IAX_CAPABILITY_FULLBANDWIDTH   0xFFFF
00318 /* T1, maybe ISDN */
00319 #define IAX_CAPABILITY_MEDBANDWIDTH (IAX_CAPABILITY_FULLBANDWIDTH & \
00320                      ~AST_FORMAT_SLINEAR &      \
00321                      ~AST_FORMAT_SLINEAR16 &    \
00322                      ~AST_FORMAT_SIREN7 &       \
00323                      ~AST_FORMAT_SIREN14 &      \
00324                      ~AST_FORMAT_G719 &         \
00325                      ~AST_FORMAT_ULAW &         \
00326                      ~AST_FORMAT_ALAW &         \
00327                      ~AST_FORMAT_G722)
00328 /* A modem */
00329 #define IAX_CAPABILITY_LOWBANDWIDTH (IAX_CAPABILITY_MEDBANDWIDTH & \
00330                      ~AST_FORMAT_G726 &         \
00331                      ~AST_FORMAT_G726_AAL2 &    \
00332                      ~AST_FORMAT_ADPCM)
00333 
00334 #define IAX_CAPABILITY_LOWFREE      (IAX_CAPABILITY_LOWBANDWIDTH & \
00335                      ~AST_FORMAT_G723_1)
00336 
00337 
00338 #define DEFAULT_MAXMS      2000     /* Must be faster than 2 seconds by default */
00339 #define DEFAULT_FREQ_OK    60 * 1000   /* How often to check for the host to be up */
00340 #define DEFAULT_FREQ_NOTOK 10 * 1000   /* How often to check, if the host is down... */
00341 
00342 /* if a pvt has encryption setup done and is running on the call */
00343 #define IAX_CALLENCRYPTED(pvt) \
00344    (ast_test_flag64(pvt, IAX_ENCRYPTED) && ast_test_flag64(pvt, IAX_KEYPOPULATED))
00345 
00346 #define IAX_DEBUGDIGEST(msg, key) do { \
00347       int idx; \
00348       char digest[33] = ""; \
00349       \
00350       if (!iaxdebug) \
00351          break; \
00352       \
00353       for (idx = 0; idx < 16; idx++) \
00354          sprintf(digest + (idx << 1), "%2.2x", (unsigned char) key[idx]); \
00355       \
00356       ast_log(LOG_NOTICE, msg " IAX_COMMAND_RTKEY to rotate key to '%s'\n", digest); \
00357    } while(0)
00358 
00359 static   struct io_context *io;
00360 static   struct ast_sched_thread *sched;
00361 
00362 #define DONT_RESCHEDULE -2
00363 
00364 static format_t iax2_capability = IAX_CAPABILITY_FULLBANDWIDTH;
00365 
00366 static int iaxdebug = 0;
00367 
00368 static int iaxtrunkdebug = 0;
00369 
00370 static int test_losspct = 0;
00371 #ifdef IAXTESTS
00372 static int test_late = 0;
00373 static int test_resync = 0;
00374 static int test_jit = 0;
00375 static int test_jitpct = 0;
00376 #endif /* IAXTESTS */
00377 
00378 static char accountcode[AST_MAX_ACCOUNT_CODE];
00379 static char mohinterpret[MAX_MUSICCLASS];
00380 static char mohsuggest[MAX_MUSICCLASS];
00381 static int amaflags = 0;
00382 static int adsi = 0;
00383 static int delayreject = 0;
00384 static int iax2_encryption = 0;
00385 
00386 static struct ast_flags64 globalflags = { 0 };
00387 
00388 static pthread_t netthreadid = AST_PTHREADT_NULL;
00389 
00390 enum iax2_state {
00391    IAX_STATE_STARTED =        (1 << 0),
00392    IAX_STATE_AUTHENTICATED =  (1 << 1),
00393    IAX_STATE_TBD =            (1 << 2),
00394 };
00395 
00396 struct iax2_context {
00397    char context[AST_MAX_CONTEXT];
00398    struct iax2_context *next;
00399 };
00400 
00401 
00402 #define  IAX_HASCALLERID         (uint64_t)(1 << 0)    /*!< CallerID has been specified */
00403 #define IAX_DELME               (uint64_t)(1 << 1)    /*!< Needs to be deleted */
00404 #define IAX_TEMPONLY            (uint64_t)(1 << 2)    /*!< Temporary (realtime) */
00405 #define IAX_TRUNK               (uint64_t)(1 << 3)    /*!< Treat as a trunk */
00406 #define IAX_NOTRANSFER          (uint64_t)(1 << 4)    /*!< Don't native bridge */
00407 #define IAX_USEJITTERBUF        (uint64_t)(1 << 5)    /*!< Use jitter buffer */
00408 #define IAX_DYNAMIC             (uint64_t)(1 << 6)    /*!< dynamic peer */
00409 #define IAX_SENDANI             (uint64_t)(1 << 7)    /*!< Send ANI along with CallerID */
00410 #define IAX_RTSAVE_SYSNAME      (uint64_t)(1 << 8)    /*!< Save Systname on Realtime Updates */
00411 #define IAX_ALREADYGONE         (uint64_t)(1 << 9)    /*!< Already disconnected */
00412 #define IAX_PROVISION           (uint64_t)(1 << 10)   /*!< This is a provisioning request */
00413 #define IAX_QUELCH              (uint64_t)(1 << 11)   /*!< Whether or not we quelch audio */
00414 #define IAX_ENCRYPTED           (uint64_t)(1 << 12)   /*!< Whether we should assume encrypted tx/rx */
00415 #define IAX_KEYPOPULATED        (uint64_t)(1 << 13)   /*!< Whether we have a key populated */
00416 #define IAX_CODEC_USER_FIRST    (uint64_t)(1 << 14)   /*!< are we willing to let the other guy choose the codec? */
00417 #define IAX_CODEC_NOPREFS       (uint64_t)(1 << 15)   /*!< Force old behaviour by turning off prefs */
00418 #define IAX_CODEC_NOCAP         (uint64_t)(1 << 16)   /*!< only consider requested format and ignore capabilities*/
00419 #define IAX_RTCACHEFRIENDS      (uint64_t)(1 << 17)   /*!< let realtime stay till your reload */
00420 #define IAX_RTUPDATE            (uint64_t)(1 << 18)   /*!< Send a realtime update */
00421 #define IAX_RTAUTOCLEAR         (uint64_t)(1 << 19)   /*!< erase me on expire */
00422 #define IAX_FORCEJITTERBUF      (uint64_t)(1 << 20)   /*!< Force jitterbuffer, even when bridged to a channel that can take jitter */
00423 #define IAX_RTIGNOREREGEXPIRE   (uint64_t)(1 << 21)   /*!< When using realtime, ignore registration expiration */
00424 #define IAX_TRUNKTIMESTAMPS     (uint64_t)(1 << 22)   /*!< Send trunk timestamps */
00425 #define IAX_TRANSFERMEDIA       (uint64_t)(1 << 23)   /*!< When doing IAX2 transfers, transfer media only */
00426 #define IAX_MAXAUTHREQ          (uint64_t)(1 << 24)   /*!< Maximum outstanding AUTHREQ restriction is in place */
00427 #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 */
00428 #define IAX_ALLOWFWDOWNLOAD     (uint64_t)(1 << 26)   /*!< Allow the FWDOWNL command? */
00429 #define IAX_IMMEDIATE           (uint64_t)(1 << 27)   /*!< Allow immediate off-hook to extension s */
00430 #define IAX_SENDCONNECTEDLINE   (uint64_t)(1 << 28)   /*!< Allow sending of connected line updates */
00431 #define IAX_RECVCONNECTEDLINE   (uint64_t)(1 << 29)   /*!< Allow receiving of connected line updates */
00432 #define IAX_FORCE_ENCRYPT       (uint64_t)(1 << 30)   /*!< Forces call encryption, if encryption not possible hangup */
00433 #define IAX_SHRINKCALLERID      (uint64_t)(1 << 31)   /*!< Turn on and off caller id shrinking */
00434 static int global_rtautoclear = 120;
00435 
00436 static int reload_config(void);
00437 
00438 /*!
00439  * \brief Call token validation settings.
00440  */
00441 enum calltoken_peer_enum {
00442    /*! \brief Default calltoken required unless the ip is in the ignorelist */
00443    CALLTOKEN_DEFAULT = 0,
00444    /*! \brief Require call token validation. */
00445    CALLTOKEN_YES = 1,
00446    /*! \brief Require call token validation after a successful registration
00447     *         using call token validation occurs. */
00448    CALLTOKEN_AUTO = 2,
00449    /*! \brief Do not require call token validation. */
00450    CALLTOKEN_NO = 3,
00451 };
00452 
00453 struct iax2_user {
00454    AST_DECLARE_STRING_FIELDS(
00455       AST_STRING_FIELD(name);
00456       AST_STRING_FIELD(secret);
00457       AST_STRING_FIELD(dbsecret);
00458       AST_STRING_FIELD(accountcode);
00459       AST_STRING_FIELD(mohinterpret);
00460       AST_STRING_FIELD(mohsuggest);
00461       AST_STRING_FIELD(inkeys);               /*!< Key(s) this user can use to authenticate to us */
00462       AST_STRING_FIELD(language);
00463       AST_STRING_FIELD(cid_num);
00464       AST_STRING_FIELD(cid_name);
00465       AST_STRING_FIELD(parkinglot);           /*!< Default parkinglot for device */
00466    );
00467 
00468    int authmethods;
00469    int encmethods;
00470    int amaflags;
00471    int adsi;
00472    uint64_t flags;
00473    format_t capability;
00474    int maxauthreq; /*!< Maximum allowed outstanding AUTHREQs */
00475    int curauthreq; /*!< Current number of outstanding AUTHREQs */
00476    struct ast_codec_pref prefs;
00477    struct ast_ha *ha;
00478    struct iax2_context *contexts;
00479    struct ast_variable *vars;
00480    enum calltoken_peer_enum calltoken_required;        /*!< Is calltoken validation required or not, can be YES, NO, or AUTO */
00481 };
00482 
00483 struct iax2_peer {
00484    AST_DECLARE_STRING_FIELDS(
00485       AST_STRING_FIELD(name);
00486       AST_STRING_FIELD(username);
00487       AST_STRING_FIELD(secret);
00488       AST_STRING_FIELD(dbsecret);
00489       AST_STRING_FIELD(outkey);      /*!< What key we use to talk to this peer */
00490 
00491       AST_STRING_FIELD(regexten);     /*!< Extension to register (if regcontext is used) */
00492       AST_STRING_FIELD(context);      /*!< For transfers only */
00493       AST_STRING_FIELD(peercontext);  /*!< Context to pass to peer */
00494       AST_STRING_FIELD(mailbox);     /*!< Mailbox */
00495       AST_STRING_FIELD(mohinterpret);
00496       AST_STRING_FIELD(mohsuggest);
00497       AST_STRING_FIELD(inkeys);     /*!< Key(s) this peer can use to authenticate to us */
00498       /* Suggested caller id if registering */
00499       AST_STRING_FIELD(cid_num);    /*!< Default context (for transfer really) */
00500       AST_STRING_FIELD(cid_name);      /*!< Default context (for transfer really) */
00501       AST_STRING_FIELD(zonetag);    /*!< Time Zone */
00502       AST_STRING_FIELD(parkinglot);   /*!< Default parkinglot for device */
00503    );
00504    struct ast_codec_pref prefs;
00505    struct ast_dnsmgr_entry *dnsmgr;    /*!< DNS refresh manager */
00506    struct ast_sockaddr addr;
00507    int formats;
00508    int sockfd;             /*!< Socket to use for transmission */
00509    struct in_addr mask;
00510    int adsi;
00511    uint64_t flags;
00512 
00513    /* Dynamic Registration fields */
00514    struct sockaddr_in defaddr;         /*!< Default address if there is one */
00515    int authmethods;           /*!< Authentication methods (IAX_AUTH_*) */
00516    int encmethods;               /*!< Encryption methods (IAX_ENCRYPT_*) */
00517 
00518    int expire;             /*!< Schedule entry for expiry */
00519    int expiry;             /*!< How soon to expire */
00520    format_t capability;        /*!< Capability */
00521 
00522    /* Qualification */
00523    int callno;             /*!< Call number of POKE request */
00524    int pokeexpire;               /*!< Scheduled qualification-related task (ie iax2_poke_peer_s or iax2_poke_noanswer) */
00525    int lastms;             /*!< How long last response took (in ms), or -1 for no response */
00526    int maxms;              /*!< Max ms we will accept for the host to be up, 0 to not monitor */
00527 
00528    int pokefreqok;               /*!< How often to check if the host is up */
00529    int pokefreqnotok;            /*!< How often to check when the host has been determined to be down */
00530    int historicms;               /*!< How long recent average responses took */
00531    int smoothing;             /*!< Sample over how many units to determine historic ms */
00532    uint16_t maxcallno;              /*!< Max call number limit for this peer.  Set on registration */
00533 
00534    struct ast_event_sub *mwi_event_sub;
00535 
00536    struct ast_ha *ha;
00537    enum calltoken_peer_enum calltoken_required;        /*!< Is calltoken validation required or not, can be YES, NO, or AUTO */
00538 };
00539 
00540 #define IAX2_TRUNK_PREFACE (sizeof(struct iax_frame) + sizeof(struct ast_iax2_meta_hdr) + sizeof(struct ast_iax2_meta_trunk_hdr))
00541 
00542 struct iax2_trunk_peer {
00543    ast_mutex_t lock;
00544    int sockfd;
00545    struct sockaddr_in addr;
00546    struct timeval txtrunktime;      /*!< Transmit trunktime */
00547    struct timeval rxtrunktime;      /*!< Receive trunktime */
00548    struct timeval lasttxtime;    /*!< Last transmitted trunktime */
00549    struct timeval trunkact;      /*!< Last trunk activity */
00550    unsigned int lastsent;        /*!< Last sent time */
00551    /* Trunk data and length */
00552    unsigned char *trunkdata;
00553    unsigned int trunkdatalen;
00554    unsigned int trunkdataalloc;
00555    int trunkmaxmtu;
00556    int trunkerror;
00557    int calls;
00558    AST_LIST_ENTRY(iax2_trunk_peer) list;
00559 };
00560 
00561 static AST_LIST_HEAD_STATIC(tpeers, iax2_trunk_peer);
00562 
00563 struct iax_firmware {
00564    AST_LIST_ENTRY(iax_firmware) list;
00565    int fd;
00566    int mmaplen;
00567    int dead;
00568    struct ast_iax2_firmware_header *fwh;
00569    unsigned char *buf;
00570 };
00571 
00572 enum iax_reg_state {
00573    REG_STATE_UNREGISTERED = 0,
00574    REG_STATE_REGSENT,
00575    REG_STATE_AUTHSENT,
00576    REG_STATE_REGISTERED,
00577    REG_STATE_REJECTED,
00578    REG_STATE_TIMEOUT,
00579    REG_STATE_NOAUTH
00580 };
00581 
00582 enum iax_transfer_state {
00583    TRANSFER_NONE = 0,
00584    TRANSFER_BEGIN,
00585    TRANSFER_READY,
00586    TRANSFER_RELEASED,
00587    TRANSFER_PASSTHROUGH,
00588    TRANSFER_MBEGIN,
00589    TRANSFER_MREADY,
00590    TRANSFER_MRELEASED,
00591    TRANSFER_MPASSTHROUGH,
00592    TRANSFER_MEDIA,
00593    TRANSFER_MEDIAPASS
00594 };
00595 
00596 struct iax2_registry {
00597    struct ast_sockaddr addr;     /*!< Who we connect to for registration purposes */
00598    char username[80];
00599    char secret[80];        /*!< Password or key name in []'s */
00600    int expire;          /*!< Sched ID of expiration */
00601    int refresh;            /*!< How often to refresh */
00602    enum iax_reg_state regstate;
00603    int messages;           /*!< Message count, low 8 bits = new, high 8 bits = old */
00604    int callno;          /*!< Associated call number if applicable */
00605    struct sockaddr_in us;        /*!< Who the server thinks we are */
00606    struct ast_dnsmgr_entry *dnsmgr; /*!< DNS refresh manager */
00607    AST_LIST_ENTRY(iax2_registry) entry;
00608 };
00609 
00610 static AST_LIST_HEAD_STATIC(registrations, iax2_registry);
00611 
00612 /* Don't retry more frequently than every 10 ms, or less frequently than every 5 seconds */
00613 #define MIN_RETRY_TIME     100
00614 #define MAX_RETRY_TIME     10000
00615 
00616 #define MAX_JITTER_BUFFER  50
00617 #define MIN_JITTER_BUFFER  10
00618 
00619 #define DEFAULT_TRUNKDATA  640 * 10 /*!< 40ms, uncompressed linear * 10 channels */
00620 
00621 #define MAX_TIMESTAMP_SKEW 160      /*!< maximum difference between actual and predicted ts for sending */
00622 
00623 /* If consecutive voice frame timestamps jump by more than this many milliseconds, then jitter buffer will resync */
00624 #define TS_GAP_FOR_JB_RESYNC  5000
00625 
00626 /* used for first_iax_message and last_iax_message.  If this bit is set it was TX, else RX */
00627 #define MARK_IAX_SUBCLASS_TX  0x8000
00628 
00629 static int iaxthreadcount = DEFAULT_THREAD_COUNT;
00630 static int iaxmaxthreadcount = DEFAULT_MAX_THREAD_COUNT;
00631 static int iaxdynamicthreadcount = 0;
00632 static int iaxdynamicthreadnum = 0;
00633 static int iaxactivethreadcount = 0;
00634 
00635 struct iax_rr {
00636    int jitter;
00637    int losspct;
00638    int losscnt;
00639    int packets;
00640    int delay;
00641    int dropped;
00642    int ooo;
00643 };
00644 
00645 struct iax2_pvt_ref;
00646 
00647 struct chan_iax2_pvt {
00648    /*! Socket to send/receive on for this call */
00649    int sockfd;
00650    /*! Last received voice format */
00651    format_t voiceformat;
00652    /*! Last received video format */
00653    format_t videoformat;
00654    /*! Last sent voice format */
00655    format_t svoiceformat;
00656    /*! Last sent video format */
00657    format_t svideoformat;
00658    /*! What we are capable of sending */
00659    format_t capability;
00660    /*! Last received timestamp */
00661    unsigned int last;
00662    /*! Last sent timestamp - never send the same timestamp twice in a single call */
00663    unsigned int lastsent;
00664    /*! Timestamp of the last video frame sent */
00665    unsigned int lastvsent;
00666    /*! Next outgoing timestamp if everything is good */
00667    unsigned int nextpred;
00668    /*! iax frame subclass that began iax2_pvt entry. 0x8000 bit is set on TX */
00669    int first_iax_message;
00670    /*! Last iax frame subclass sent or received for a iax2_pvt. 0x8000 bit is set on TX */
00671    int last_iax_message;
00672    /*! True if the last voice we transmitted was not silence/CNG */
00673    unsigned int notsilenttx:1;
00674    /*! Ping time */
00675    unsigned int pingtime;
00676    /*! Max time for initial response */
00677    int maxtime;
00678    /*! Peer Address */
00679    struct sockaddr_in addr;
00680    /*! Actual used codec preferences */
00681    struct ast_codec_pref prefs;
00682    /*! Requested codec preferences */
00683    struct ast_codec_pref rprefs;
00684    /*! Our call number */
00685    unsigned short callno;
00686    /*! Our callno_entry entry */
00687    struct callno_entry *callno_entry;
00688    /*! Peer callno */
00689    unsigned short peercallno;
00690    /*! Negotiated format, this is only used to remember what format was
00691        chosen for an unauthenticated call so that the channel can get
00692        created later using the right format */
00693    format_t chosenformat;
00694    /*! Peer selected format */
00695    format_t peerformat;
00696    /*! Peer capability */
00697    format_t peercapability;
00698    /*! timeval that we base our transmission on */
00699    struct timeval offset;
00700    /*! timeval that we base our delivery on */
00701    struct timeval rxcore;
00702    /*! The jitterbuffer */
00703    jitterbuf *jb;
00704    /*! active jb read scheduler id */
00705    int jbid;
00706    /*! LAG */
00707    int lag;
00708    /*! Error, as discovered by the manager */
00709    int error;
00710    /*! Owner if we have one */
00711    struct ast_channel *owner;
00712    /*! What's our state? */
00713    struct ast_flags state;
00714    /*! Expiry (optional) */
00715    int expiry;
00716    /*! Next outgoing sequence number */
00717    unsigned char oseqno;
00718    /*! Next sequence number they have not yet acknowledged */
00719    unsigned char rseqno;
00720    /*! Next incoming sequence number */
00721    unsigned char iseqno;
00722    /*! Last incoming sequence number we have acknowledged */
00723    unsigned char aseqno;
00724 
00725    AST_DECLARE_STRING_FIELDS(
00726       /*! Peer name */
00727       AST_STRING_FIELD(peer);
00728       /*! Default Context */
00729       AST_STRING_FIELD(context);
00730       /*! Caller ID if available */
00731       AST_STRING_FIELD(cid_num);
00732       AST_STRING_FIELD(cid_name);
00733       /*! Hidden Caller ID (i.e. ANI) if appropriate */
00734       AST_STRING_FIELD(ani);
00735       /*! DNID */
00736       AST_STRING_FIELD(dnid);
00737       /*! RDNIS */
00738       AST_STRING_FIELD(rdnis);
00739       /*! Requested Extension */
00740       AST_STRING_FIELD(exten);
00741       /*! Expected Username */
00742       AST_STRING_FIELD(username);
00743       /*! Expected Secret */
00744       AST_STRING_FIELD(secret);
00745       /*! MD5 challenge */
00746       AST_STRING_FIELD(challenge);
00747       /*! Public keys permitted keys for incoming authentication */
00748       AST_STRING_FIELD(inkeys);
00749       /*! Private key for outgoing authentication */
00750       AST_STRING_FIELD(outkey);
00751       /*! Preferred language */
00752       AST_STRING_FIELD(language);
00753       /*! Hostname/peername for naming purposes */
00754       AST_STRING_FIELD(host);
00755 
00756       AST_STRING_FIELD(dproot);
00757       AST_STRING_FIELD(accountcode);
00758       AST_STRING_FIELD(mohinterpret);
00759       AST_STRING_FIELD(mohsuggest);
00760       /*! received OSP token */
00761       AST_STRING_FIELD(osptoken);
00762       /*! Default parkinglot */
00763       AST_STRING_FIELD(parkinglot);
00764    );
00765    /*! AUTHREJ all AUTHREP frames */
00766    int authrej;
00767    /*! permitted authentication methods */
00768    int authmethods;
00769    /*! permitted encryption methods */
00770    int encmethods;
00771    /*! Encryption AES-128 Key */
00772    ast_aes_encrypt_key ecx;
00773    /*! Decryption AES-128 Key corresponding to ecx */
00774    ast_aes_decrypt_key mydcx;
00775    /*! Decryption AES-128 Key used to decrypt peer frames */
00776    ast_aes_decrypt_key dcx;
00777    /*! scheduler id associated with iax_key_rotate 
00778     * for encrypted calls*/
00779    int keyrotateid;
00780    /*! 32 bytes of semi-random data */
00781    unsigned char semirand[32];
00782    /*! Associated registry */
00783    struct iax2_registry *reg;
00784    /*! Associated peer for poking */
00785    struct iax2_peer *peerpoke;
00786    /*! IAX_ flags */
00787    uint64_t flags;
00788    int adsi;
00789 
00790    /*! Transferring status */
00791    enum iax_transfer_state transferring;
00792    /*! Transfer identifier */
00793    int transferid;
00794    /*! Who we are IAX transferring to */
00795    struct sockaddr_in transfer;
00796    /*! What's the new call number for the transfer */
00797    unsigned short transfercallno;
00798    /*! Transfer encrypt AES-128 Key */
00799    ast_aes_encrypt_key tdcx;
00800 
00801    /*! Status of knowledge of peer ADSI capability */
00802    int peeradsicpe;
00803 
00804    /*! Who we are bridged to */
00805    unsigned short bridgecallno;
00806 
00807    int pingid;       /*!< Transmit PING request */
00808    int lagid;        /*!< Retransmit lag request */
00809    int autoid;       /*!< Auto hangup for Dialplan requestor */
00810    int authid;       /*!< Authentication rejection ID */
00811    int authfail;        /*!< Reason to report failure */
00812    int initid;       /*!< Initial peer auto-congest ID (based on qualified peers) */
00813    int calling_ton;
00814    int calling_tns;
00815    int calling_pres;
00816    int amaflags;
00817    AST_LIST_HEAD_NOLOCK(, iax2_dpcache) dpentries;
00818    /*! variables inherited from the user definition */
00819    struct ast_variable *vars;
00820    /*! variables transmitted in a NEW packet */
00821    struct ast_variable *iaxvars;
00822    /*! last received remote rr */
00823    struct iax_rr remote_rr;
00824    /*! Current base time: (just for stats) */
00825    int min;
00826    /*! Dropped frame count: (just for stats) */
00827    int frames_dropped;
00828    /*! received frame count: (just for stats) */
00829    int frames_received;
00830    /*! num bytes used for calltoken ie, even an empty ie should contain 2 */
00831    unsigned char calltoken_ie_len;
00832    /*! hold all signaling frames from the pbx thread until we have a destination callno */
00833    char hold_signaling;
00834    /*! frame queue for signaling frames from pbx thread waiting for destination callno */
00835    AST_LIST_HEAD_NOLOCK(signaling_queue, signaling_queue_entry) signaling_queue;
00836 };
00837 
00838 struct signaling_queue_entry {
00839    struct ast_frame f;
00840    AST_LIST_ENTRY(signaling_queue_entry) next;
00841 };
00842 
00843 /*! table of available call numbers */
00844 static struct ao2_container *callno_pool;
00845 
00846 /*! table of available trunk call numbers */
00847 static struct ao2_container *callno_pool_trunk;
00848 
00849 static const unsigned int CALLNO_POOL_BUCKETS = 2699;
00850 
00851 /*!
00852  * \brief a list of frames that may need to be retransmitted
00853  *
00854  * \note The contents of this list do not need to be explicitly destroyed
00855  * on module unload.  This is because all active calls are destroyed, and
00856  * all frames in this queue will get destroyed as a part of that process.
00857  *
00858  * \note Contents protected by the iaxsl[] locks
00859  */
00860 static AST_LIST_HEAD_NOLOCK(, iax_frame) frame_queue[IAX_MAX_CALLS + 1];
00861 
00862 static struct ast_taskprocessor *transmit_processor;
00863 
00864 static int randomcalltokendata;
00865 
00866 static const time_t MAX_CALLTOKEN_DELAY = 10;
00867 
00868 /*!
00869  * This module will get much higher performance when doing a lot of
00870  * user and peer lookups if the number of buckets is increased from 1.
00871  * However, to maintain old behavior for Asterisk 1.4, these are set to
00872  * 1 by default.  When using multiple buckets, search order through these
00873  * containers is considered random, so you will not be able to depend on
00874  * the order the entires are specified in iax.conf for matching order. */
00875 #ifdef LOW_MEMORY
00876 #define MAX_PEER_BUCKETS 17
00877 #else
00878 #define MAX_PEER_BUCKETS 563
00879 #endif
00880 static struct ao2_container *peers;
00881 
00882 #define MAX_USER_BUCKETS MAX_PEER_BUCKETS
00883 static struct ao2_container *users;
00884 
00885 /*! Table containing peercnt objects for every ip address consuming a callno */
00886 static struct ao2_container *peercnts;
00887 
00888 /*! Table containing custom callno limit rules for a range of ip addresses. */
00889 static struct ao2_container *callno_limits;
00890 
00891 /*! Table containing ip addresses not requiring calltoken validation */
00892 static struct ao2_container *calltoken_ignores;
00893 
00894 static uint16_t DEFAULT_MAXCALLNO_LIMIT = 2048;
00895 
00896 static uint16_t DEFAULT_MAXCALLNO_LIMIT_NONVAL = 8192;
00897 
00898 static uint16_t global_maxcallno;
00899 
00900 /*! Total num of call numbers allowed to be allocated without calltoken validation */
00901 static uint16_t global_maxcallno_nonval;
00902 
00903 static uint16_t total_nonval_callno_used = 0;
00904 
00905 /*! peer connection private, keeps track of all the call numbers
00906  *  consumed by a single ip address */
00907 struct peercnt {
00908    /*! ip address consuming call numbers */
00909    unsigned long addr;
00910    /*! Number of call numbers currently used by this ip address */
00911    uint16_t cur;
00912    /*! Max call numbers allowed for this ip address */
00913    uint16_t limit;
00914    /*! Specifies whether limit is set by a registration or not, if so normal
00915     *  limit setting rules do not apply to this address. */
00916    unsigned char reg;
00917 };
00918 
00919 /*! used by both callno_limits and calltoken_ignores containers */
00920 struct addr_range {
00921    /*! ip address range for custom callno limit rule */
00922    struct ast_ha ha;
00923    /*! callno limit for this ip address range, only used in callno_limits container */
00924    uint16_t limit;
00925    /*! delete me marker for reloads */
00926    unsigned char delme;
00927 };
00928 
00929 struct callno_entry {
00930    /*! callno used for this entry */
00931    uint16_t callno;
00932    /*! was this callno calltoken validated or not */
00933    unsigned char validated;
00934 };
00935 
00936 static AST_LIST_HEAD_STATIC(firmwares, iax_firmware);
00937 
00938 enum {
00939    /*! Extension exists */
00940    CACHE_FLAG_EXISTS      = (1 << 0),
00941    /*! Extension is nonexistent */
00942    CACHE_FLAG_NONEXISTENT = (1 << 1),
00943    /*! Extension can exist */
00944    CACHE_FLAG_CANEXIST    = (1 << 2),
00945    /*! Waiting to hear back response */
00946    CACHE_FLAG_PENDING     = (1 << 3),
00947    /*! Timed out */
00948    CACHE_FLAG_TIMEOUT     = (1 << 4),
00949    /*! Request transmitted */
00950    CACHE_FLAG_TRANSMITTED = (1 << 5),
00951    /*! Timeout */
00952    CACHE_FLAG_UNKNOWN     = (1 << 6),
00953    /*! Matchmore */
00954    CACHE_FLAG_MATCHMORE   = (1 << 7),
00955 };
00956 
00957 struct iax2_dpcache {
00958    char peercontext[AST_MAX_CONTEXT];
00959    char exten[AST_MAX_EXTENSION];
00960    struct timeval orig;
00961    struct timeval expiry;
00962    int flags;
00963    unsigned short callno;
00964    int waiters[256];
00965    AST_LIST_ENTRY(iax2_dpcache) cache_list;
00966    AST_LIST_ENTRY(iax2_dpcache) peer_list;
00967 };
00968 
00969 static AST_LIST_HEAD_STATIC(dpcache, iax2_dpcache);
00970 
00971 static void reg_source_db(struct iax2_peer *p);
00972 static struct iax2_peer *realtime_peer(const char *peername, struct sockaddr_in *sin);
00973 static struct iax2_user *realtime_user(const char *username, struct sockaddr_in *sin);
00974 
00975 static int ast_cli_netstats(struct mansession *s, int fd, int limit_fmt);
00976 static char *complete_iax2_peers(const char *line, const char *word, int pos, int state, uint64_t flags);
00977 static char *complete_iax2_unregister(const char *line, const char *word, int pos, int state);
00978 
00979 enum iax2_thread_iostate {
00980    IAX_IOSTATE_IDLE,
00981    IAX_IOSTATE_READY,
00982    IAX_IOSTATE_PROCESSING,
00983    IAX_IOSTATE_SCHEDREADY,
00984 };
00985 
00986 enum iax2_thread_type {
00987    IAX_THREAD_TYPE_POOL,
00988    IAX_THREAD_TYPE_DYNAMIC,
00989 };
00990 
00991 struct iax2_pkt_buf {
00992    AST_LIST_ENTRY(iax2_pkt_buf) entry;
00993    size_t len;
00994    unsigned char buf[1];
00995 };
00996 
00997 struct iax2_thread {
00998    AST_LIST_ENTRY(iax2_thread) list;
00999    enum iax2_thread_type type;
01000    enum iax2_thread_iostate iostate;
01001 #ifdef SCHED_MULTITHREADED
01002    void (*schedfunc)(const void *);
01003    const void *scheddata;
01004 #endif
01005 #ifdef DEBUG_SCHED_MULTITHREAD
01006    char curfunc[80];
01007 #endif   
01008    int actions;
01009    pthread_t threadid;
01010    int threadnum;
01011    struct sockaddr_in iosin;
01012    unsigned char readbuf[4096]; 
01013    unsigned char *buf;
01014    ssize_t buf_len;
01015    size_t buf_size;
01016    int iofd;
01017    time_t checktime;
01018    ast_mutex_t lock;
01019    ast_cond_t cond;
01020    ast_mutex_t init_lock;
01021    ast_cond_t init_cond;
01022    /*! if this thread is processing a full frame,
01023      some information about that frame will be stored
01024      here, so we can avoid dispatching any more full
01025      frames for that callno to other threads */
01026    struct {
01027       unsigned short callno;
01028       struct sockaddr_in sin;
01029       unsigned char type;
01030       unsigned char csub;
01031    } ffinfo;
01032    /*! Queued up full frames for processing.  If more full frames arrive for
01033     *  a call which this thread is already processing a full frame for, they
01034     *  are queued up here. */
01035    AST_LIST_HEAD_NOLOCK(, iax2_pkt_buf) full_frames;
01036    unsigned char stop;
01037 };
01038 
01039 /* Thread lists */
01040 static AST_LIST_HEAD_STATIC(idle_list, iax2_thread);
01041 static AST_LIST_HEAD_STATIC(active_list, iax2_thread);
01042 static AST_LIST_HEAD_STATIC(dynamic_list, iax2_thread);
01043 
01044 static void *iax2_process_thread(void *data);
01045 static void iax2_destroy(int callno);
01046 
01047 static void signal_condition(ast_mutex_t *lock, ast_cond_t *cond)
01048 {
01049    ast_mutex_lock(lock);
01050    ast_cond_signal(cond);
01051    ast_mutex_unlock(lock);
01052 }
01053 
01054 /*!
01055  * \brief an array of iax2 pvt structures
01056  *
01057  * The container for active chan_iax2_pvt structures is implemented as an
01058  * array for extremely quick direct access to the correct pvt structure
01059  * based on the local call number.  The local call number is used as the
01060  * index into the array where the associated pvt structure is stored.
01061  */
01062 static struct chan_iax2_pvt *iaxs[IAX_MAX_CALLS + 1];
01063 
01064 /*!
01065  * \brief Another container of iax2_pvt structures
01066  *
01067  * Active IAX2 pvt structs are also stored in this container, if they are a part
01068  * of an active call where we know the remote side's call number.  The reason
01069  * for this is that incoming media frames do not contain our call number.  So,
01070  * instead of having to iterate the entire iaxs array, we use this container to
01071  * look up calls where the remote side is using a given call number.
01072  */
01073 static struct ao2_container *iax_peercallno_pvts;
01074 
01075 /*!
01076  * \brief chan_iax2_pvt structure locks
01077  *
01078  * These locks are used when accessing a pvt structure in the iaxs array.
01079  * The index used here is the same as used in the iaxs array.  It is the
01080  * local call number for the associated pvt struct.
01081  */
01082 static ast_mutex_t iaxsl[ARRAY_LEN(iaxs)];
01083 
01084 /*!
01085  *  * \brief Another container of iax2_pvt structures
01086  *  
01087  *  Active IAX2 pvt stucts used during transfering a call are stored here.  
01088  */
01089 static struct ao2_container *iax_transfercallno_pvts;
01090 
01091 /* Flag to use with trunk calls, keeping these calls high up.  It halves our effective use
01092    but keeps the division between trunked and non-trunked better. */
01093 #define TRUNK_CALL_START   IAX_MAX_CALLS / 2
01094 
01095 /* Debug routines... */
01096 static struct sockaddr_in debugaddr;
01097 
01098 static void iax_outputframe(struct iax_frame *f, struct ast_iax2_full_hdr *fhi, int rx, struct sockaddr_in *sin, int datalen)
01099 {
01100    if (iaxdebug ||
01101        (sin && debugaddr.sin_addr.s_addr && 
01102         (!ntohs(debugaddr.sin_port) ||
01103          debugaddr.sin_port == sin->sin_port) &&
01104         debugaddr.sin_addr.s_addr == sin->sin_addr.s_addr)) {
01105       if (iaxdebug) {
01106          iax_showframe(f, fhi, rx, sin, datalen);
01107       } else {
01108          iaxdebug = 1;
01109          iax_showframe(f, fhi, rx, sin, datalen);
01110          iaxdebug = 0;
01111       }
01112    }
01113 }
01114 
01115 static void iax_debug_output(const char *data)
01116 {
01117    if (iaxdebug)
01118       ast_verbose("%s", data);
01119 }
01120 
01121 static void iax_error_output(const char *data)
01122 {
01123    ast_log(LOG_WARNING, "%s", data);
01124 }
01125 
01126 static void __attribute__((format(printf, 1, 2))) jb_error_output(const char *fmt, ...)
01127 {
01128    va_list args;
01129    char buf[1024];
01130 
01131    va_start(args, fmt);
01132    vsnprintf(buf, sizeof(buf), fmt, args);
01133    va_end(args);
01134 
01135    ast_log(LOG_ERROR, "%s", buf);
01136 }
01137 
01138 static void __attribute__((format(printf, 1, 2))) jb_warning_output(const char *fmt, ...)
01139 {
01140    va_list args;
01141    char buf[1024];
01142 
01143    va_start(args, fmt);
01144    vsnprintf(buf, sizeof(buf), fmt, args);
01145    va_end(args);
01146 
01147    ast_log(LOG_WARNING, "%s", buf);
01148 }
01149 
01150 static void __attribute__((format(printf, 1, 2))) jb_debug_output(const char *fmt, ...)
01151 {
01152    va_list args;
01153    char buf[1024];
01154 
01155    va_start(args, fmt);
01156    vsnprintf(buf, sizeof(buf), fmt, args);
01157    va_end(args);
01158 
01159    ast_verbose("%s", buf);
01160 }
01161 
01162 static int maxtrunkcall = TRUNK_CALL_START;
01163 static int maxnontrunkcall = 1;
01164 
01165 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);
01166 static int expire_registry(const void *data);
01167 static int iax2_answer(struct ast_channel *c);
01168 static int iax2_call(struct ast_channel *c, char *dest, int timeout);
01169 static int iax2_devicestate(void *data);
01170 static int iax2_digit_begin(struct ast_channel *c, char digit);
01171 static int iax2_digit_end(struct ast_channel *c, char digit, unsigned int duration);
01172 static int iax2_do_register(struct iax2_registry *reg);
01173 static int iax2_fixup(struct ast_channel *oldchannel, struct ast_channel *newchan);
01174 static int iax2_hangup(struct ast_channel *c);
01175 static int iax2_indicate(struct ast_channel *c, int condition, const void *data, size_t datalen);
01176 static int iax2_poke_peer(struct iax2_peer *peer, int heldcall);
01177 static int iax2_provision(struct sockaddr_in *end, int sockfd, const char *dest, const char *template, int force);
01178 static int iax2_send(struct chan_iax2_pvt *pvt, struct ast_frame *f, unsigned int ts, int seqno, int now, int transfer, int final);
01179 static int iax2_sendhtml(struct ast_channel *c, int subclass, const char *data, int datalen);
01180 static int iax2_sendimage(struct ast_channel *c, struct ast_frame *img);
01181 static int iax2_sendtext(struct ast_channel *c, const char *text);
01182 static int iax2_setoption(struct ast_channel *c, int option, void *data, int datalen);
01183 static int iax2_queryoption(struct ast_channel *c, int option, void *data, int *datalen);
01184 static int iax2_transfer(struct ast_channel *c, const char *dest);
01185 static int iax2_write(struct ast_channel *c, struct ast_frame *f);
01186 static int iax2_sched_add(struct ast_sched_thread *st, int when, ast_sched_cb callback, const void *data);
01187 
01188 static int send_trunk(struct iax2_trunk_peer *tpeer, struct timeval *now);
01189 static int send_command(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
01190 static int send_command_final(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
01191 static int send_command_immediate(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
01192 static int send_command_locked(unsigned short callno, char, int, unsigned int, const unsigned char *, int, int);
01193 static int send_command_transfer(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int);
01194 static struct ast_channel *iax2_request(const char *type, format_t format, const struct ast_channel *requestor, void *data, int *cause);
01195 static struct ast_frame *iax2_read(struct ast_channel *c);
01196 static struct iax2_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly);
01197 static struct iax2_user *build_user(const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly);
01198 static void realtime_update_peer(const char *peername, struct ast_sockaddr *sockaddr, time_t regtime);
01199 static void *iax2_dup_variable_datastore(void *);
01200 static void prune_peers(void);
01201 static void prune_users(void);
01202 static void iax2_free_variable_datastore(void *);
01203 
01204 static int acf_channel_read(struct ast_channel *chan, const char *funcname, char *preparse, char *buf, size_t buflen);
01205 static int decode_frame(ast_aes_decrypt_key *dcx, struct ast_iax2_full_hdr *fh, struct ast_frame *f, int *datalen);
01206 static int encrypt_frame(ast_aes_encrypt_key *ecx, struct ast_iax2_full_hdr *fh, unsigned char *poo, int *datalen);
01207 static void build_ecx_key(const unsigned char *digest, struct chan_iax2_pvt *pvt);
01208 static void build_rand_pad(unsigned char *buf, ssize_t len);
01209 static struct callno_entry *get_unused_callno(int trunk, int validated);
01210 static int replace_callno(const void *obj);
01211 static void sched_delay_remove(struct sockaddr_in *sin, struct callno_entry *callno_entry);
01212 static void network_change_event_cb(const struct ast_event *, void *);
01213 
01214 static const struct ast_channel_tech iax2_tech = {
01215    .type = "IAX2",
01216    .description = tdesc,
01217    .capabilities = IAX_CAPABILITY_FULLBANDWIDTH,
01218    .properties = AST_CHAN_TP_WANTSJITTER,
01219    .requester = iax2_request,
01220    .devicestate = iax2_devicestate,
01221    .send_digit_begin = iax2_digit_begin,
01222    .send_digit_end = iax2_digit_end,
01223    .send_text = iax2_sendtext,
01224    .send_image = iax2_sendimage,
01225    .send_html = iax2_sendhtml,
01226    .call = iax2_call,
01227    .hangup = iax2_hangup,
01228    .answer = iax2_answer,
01229    .read = iax2_read,
01230    .write = iax2_write,
01231    .write_video = iax2_write,
01232    .indicate = iax2_indicate,
01233    .setoption = iax2_setoption,
01234    .queryoption = iax2_queryoption,
01235    .bridge = iax2_bridge,
01236    .transfer = iax2_transfer,
01237    .fixup = iax2_fixup,
01238    .func_channel_read = acf_channel_read,
01239 };
01240 
01241 /*!
01242  * \internal
01243  * \brief Obtain the owner channel lock if the owner exists.
01244  *
01245  * \param callno IAX2 call id.
01246  *
01247  * \note Assumes the iaxsl[callno] lock is already obtained.
01248  *
01249  * \note
01250  * IMPORTANT NOTE!!!  Any time this function is used, even if
01251  * iaxs[callno] was valid before calling it, it may no longer be
01252  * valid after calling it.  This function may unlock and lock
01253  * the mutex associated with this callno, meaning that another
01254  * thread may grab it and destroy the call.
01255  *
01256  * \return Nothing
01257  */
01258 static void iax2_lock_owner(int callno)
01259 {
01260    for (;;) {
01261       if (!iaxs[callno] || !iaxs[callno]->owner) {
01262          /* There is no owner lock to get. */
01263          break;
01264       }
01265       if (!ast_channel_trylock(iaxs[callno]->owner)) {
01266          /* We got the lock */
01267          break;
01268       }
01269       /* Avoid deadlock by pausing and trying again */
01270       DEADLOCK_AVOIDANCE(&iaxsl[callno]);
01271    }
01272 }
01273 
01274 static void mwi_event_cb(const struct ast_event *event, void *userdata)
01275 {
01276    /* The MWI subscriptions exist just so the core knows we care about those
01277     * mailboxes.  However, we just grab the events out of the cache when it
01278     * is time to send MWI, since it is only sent with a REGACK. */
01279 }
01280 
01281 static void network_change_event_subscribe(void)
01282 {
01283    if (!network_change_event_subscription) {
01284       network_change_event_subscription = ast_event_subscribe(AST_EVENT_NETWORK_CHANGE,
01285          network_change_event_cb,
01286          "SIP Network Change ",
01287          NULL,
01288          AST_EVENT_IE_END);
01289    }
01290 }
01291 
01292 static void network_change_event_unsubscribe(void)
01293 {
01294    if (network_change_event_subscription) {
01295       network_change_event_subscription = ast_event_unsubscribe(network_change_event_subscription);
01296    }
01297 }
01298 
01299 static int network_change_event_sched_cb(const void *data)
01300 {
01301    struct iax2_registry *reg;
01302    network_change_event_sched_id = -1;
01303    AST_LIST_LOCK(&registrations);
01304    AST_LIST_TRAVERSE(&registrations, reg, entry) {
01305       iax2_do_register(reg);
01306    }
01307    AST_LIST_UNLOCK(&registrations);
01308 
01309    return 0;
01310 }
01311 
01312 static void network_change_event_cb(const struct ast_event *event, void *userdata)
01313 {
01314    ast_debug(1, "IAX, got a network change event, renewing all IAX registrations.\n");
01315    if (network_change_event_sched_id == -1) {
01316       network_change_event_sched_id = iax2_sched_add(sched, 1000, network_change_event_sched_cb, NULL);
01317    }
01318 
01319 }
01320 
01321 
01322 /*! \brief Send manager event at call setup to link between Asterisk channel name
01323    and IAX2 call identifiers */
01324 static void iax2_ami_channelupdate(struct chan_iax2_pvt *pvt) 
01325 {
01326    manager_event(EVENT_FLAG_SYSTEM, "ChannelUpdate",
01327       "Channel: %s\r\nChanneltype: IAX2\r\nIAX2-callno-local: %d\r\nIAX2-callno-remote: %d\r\nIAX2-peer: %s\r\n",
01328       pvt->owner ? pvt->owner->name : "",
01329       pvt->callno, pvt->peercallno, pvt->peer ? pvt->peer : "");
01330 }
01331 
01332 static struct ast_datastore_info iax2_variable_datastore_info = {
01333    .type = "IAX2_VARIABLE",
01334    .duplicate = iax2_dup_variable_datastore,
01335    .destroy = iax2_free_variable_datastore,
01336 };
01337 
01338 static void *iax2_dup_variable_datastore(void *old)
01339 {
01340    AST_LIST_HEAD(, ast_var_t) *oldlist = old, *newlist;
01341    struct ast_var_t *oldvar, *newvar;
01342 
01343    newlist = ast_calloc(sizeof(*newlist), 1);
01344    if (!newlist) {
01345       ast_log(LOG_ERROR, "Unable to duplicate iax2 variables\n");
01346       return NULL;
01347    }
01348 
01349    AST_LIST_HEAD_INIT(newlist);
01350    AST_LIST_LOCK(oldlist);
01351    AST_LIST_TRAVERSE(oldlist, oldvar, entries) {
01352       newvar = ast_var_assign(ast_var_name(oldvar), ast_var_value(oldvar));
01353       if (newvar)
01354          AST_LIST_INSERT_TAIL(newlist, newvar, entries);
01355       else
01356          ast_log(LOG_ERROR, "Unable to duplicate iax2 variable '%s'\n", ast_var_name(oldvar));
01357    }
01358    AST_LIST_UNLOCK(oldlist);
01359    return newlist;
01360 }
01361 
01362 static void iax2_free_variable_datastore(void *old)
01363 {
01364    AST_LIST_HEAD(, ast_var_t) *oldlist = old;
01365    struct ast_var_t *oldvar;
01366 
01367    AST_LIST_LOCK(oldlist);
01368    while ((oldvar = AST_LIST_REMOVE_HEAD(oldlist, entries))) {
01369       ast_free(oldvar);
01370    }
01371    AST_LIST_UNLOCK(oldlist);
01372    AST_LIST_HEAD_DESTROY(oldlist);
01373    ast_free(oldlist);
01374 }
01375 
01376 
01377 /* WARNING: insert_idle_thread should only ever be called within the
01378  * context of an iax2_process_thread() thread.
01379  */
01380 static void insert_idle_thread(struct iax2_thread *thread)
01381 {
01382    if (thread->type == IAX_THREAD_TYPE_DYNAMIC) {
01383       AST_LIST_LOCK(&dynamic_list);
01384       AST_LIST_INSERT_TAIL(&dynamic_list, thread, list);
01385       AST_LIST_UNLOCK(&dynamic_list);
01386    } else {
01387       AST_LIST_LOCK(&idle_list);
01388       AST_LIST_INSERT_TAIL(&idle_list, thread, list);
01389       AST_LIST_UNLOCK(&idle_list);
01390    }
01391 
01392    return;
01393 }
01394 
01395 static struct iax2_thread *find_idle_thread(void)
01396 {
01397    struct iax2_thread *thread = NULL;
01398 
01399    /* Pop the head of the idle list off */
01400    AST_LIST_LOCK(&idle_list);
01401    thread = AST_LIST_REMOVE_HEAD(&idle_list, list);
01402    AST_LIST_UNLOCK(&idle_list);
01403 
01404    /* If we popped a thread off the idle list, just return it */
01405    if (thread) {
01406       memset(&thread->ffinfo, 0, sizeof(thread->ffinfo));
01407       return thread;
01408    }
01409 
01410    /* Pop the head of the dynamic list off */
01411    AST_LIST_LOCK(&dynamic_list);
01412    thread = AST_LIST_REMOVE_HEAD(&dynamic_list, list);
01413    AST_LIST_UNLOCK(&dynamic_list);
01414 
01415    /* If we popped a thread off the dynamic list, just return it */
01416    if (thread) {
01417       memset(&thread->ffinfo, 0, sizeof(thread->ffinfo));
01418       return thread;
01419    }
01420 
01421    /* If we can't create a new dynamic thread for any reason, return no thread at all */
01422    if (iaxdynamicthreadcount >= iaxmaxthreadcount || !(thread = ast_calloc(1, sizeof(*thread))))
01423       return NULL;
01424 
01425    /* Set default values */
01426    ast_atomic_fetchadd_int(&iaxdynamicthreadcount, 1);
01427    thread->threadnum = ast_atomic_fetchadd_int(&iaxdynamicthreadnum, 1);
01428    thread->type = IAX_THREAD_TYPE_DYNAMIC;
01429 
01430    /* Initialize lock and condition */
01431    ast_mutex_init(&thread->lock);
01432    ast_cond_init(&thread->cond, NULL);
01433    ast_mutex_init(&thread->init_lock);
01434    ast_cond_init(&thread->init_cond, NULL);
01435    ast_mutex_lock(&thread->init_lock);
01436 
01437    /* Create thread and send it on it's way */
01438    if (ast_pthread_create_background(&thread->threadid, NULL, iax2_process_thread, thread)) {
01439       ast_cond_destroy(&thread->cond);
01440       ast_mutex_destroy(&thread->lock);
01441       ast_free(thread);
01442       return NULL;
01443    }
01444 
01445    /* this thread is not processing a full frame (since it is idle),
01446       so ensure that the field for the full frame call number is empty */
01447    memset(&thread->ffinfo, 0, sizeof(thread->ffinfo));
01448 
01449    /* Wait for the thread to be ready before returning it to the caller */
01450    ast_cond_wait(&thread->init_cond, &thread->init_lock);
01451 
01452    /* Done with init_lock */
01453    ast_mutex_unlock(&thread->init_lock);
01454 
01455    return thread;
01456 }
01457 
01458 #ifdef SCHED_MULTITHREADED
01459 static int __schedule_action(void (*func)(const void *data), const void *data, const char *funcname)
01460 {
01461    struct iax2_thread *thread = NULL;
01462    static time_t lasterror;
01463    static time_t t;
01464 
01465    thread = find_idle_thread();
01466 
01467    if (thread != NULL) {
01468       thread->schedfunc = func;
01469       thread->scheddata = data;
01470       thread->iostate = IAX_IOSTATE_SCHEDREADY;
01471 #ifdef DEBUG_SCHED_MULTITHREAD
01472       ast_copy_string(thread->curfunc, funcname, sizeof(thread->curfunc));
01473 #endif
01474       signal_condition(&thread->lock, &thread->cond);
01475       return 0;
01476    }
01477    time(&t);
01478    if (t != lasterror) 
01479       ast_debug(1, "Out of idle IAX2 threads for scheduling!\n");
01480    lasterror = t;
01481 
01482    return -1;
01483 }
01484 #define schedule_action(func, data) __schedule_action(func, data, __PRETTY_FUNCTION__)
01485 #endif
01486 
01487 static int iax2_sched_replace(int id, struct ast_sched_thread *st, int when, 
01488       ast_sched_cb callback, const void *data)
01489 {
01490    ast_sched_thread_del(st, id);
01491 
01492    return ast_sched_thread_add(st, when, callback, data);
01493 }
01494 
01495 static int iax2_sched_add(struct ast_sched_thread *st, int when, 
01496       ast_sched_cb callback, const void *data)
01497 {
01498    return ast_sched_thread_add(st, when, callback, data);
01499 }
01500 
01501 static int send_ping(const void *data);
01502 
01503 static void __send_ping(const void *data)
01504 {
01505    int callno = (long) data;
01506 
01507    ast_mutex_lock(&iaxsl[callno]);
01508 
01509    if (iaxs[callno]) {
01510       if (iaxs[callno]->peercallno) {
01511          send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_PING, 0, NULL, 0, -1);
01512          if (iaxs[callno]->pingid != DONT_RESCHEDULE) {
01513             iaxs[callno]->pingid = iax2_sched_add(sched, ping_time * 1000, send_ping, data);
01514          }
01515       }
01516    } else {
01517       ast_debug(1, "I was supposed to send a PING with callno %d, but no such call exists.\n", callno);
01518    }
01519 
01520    ast_mutex_unlock(&iaxsl[callno]);
01521 }
01522 
01523 static int send_ping(const void *data)
01524 {
01525    int callno = (long) data;
01526    ast_mutex_lock(&iaxsl[callno]);
01527    if (iaxs[callno] && iaxs[callno]->pingid != DONT_RESCHEDULE) {
01528       iaxs[callno]->pingid = -1;
01529    }
01530    ast_mutex_unlock(&iaxsl[callno]);
01531 
01532 #ifdef SCHED_MULTITHREADED
01533    if (schedule_action(__send_ping, data))
01534 #endif
01535       __send_ping(data);
01536 
01537    return 0;
01538 }
01539 
01540 static void encmethods_to_str(int e, struct ast_str *buf)
01541 {
01542    ast_str_set(&buf, 0, "(");
01543    if (e & IAX_ENCRYPT_AES128) {
01544       ast_str_append(&buf, 0, "aes128");
01545    }
01546    if (e & IAX_ENCRYPT_KEYROTATE) {
01547       ast_str_append(&buf, 0, ",keyrotate");
01548    }
01549    if (ast_str_strlen(buf) > 1) {
01550       ast_str_append(&buf, 0, ")");
01551    } else {
01552       ast_str_set(&buf, 0, "No");
01553    }
01554 }
01555 
01556 static int get_encrypt_methods(const char *s)
01557 {
01558    int e;
01559    if (!strcasecmp(s, "aes128"))
01560       e = IAX_ENCRYPT_AES128 | IAX_ENCRYPT_KEYROTATE;
01561    else if (ast_true(s))
01562       e = IAX_ENCRYPT_AES128 | IAX_ENCRYPT_KEYROTATE;
01563    else
01564       e = 0;
01565    return e;
01566 }
01567 
01568 static int send_lagrq(const void *data);
01569 
01570 static void __send_lagrq(const void *data)
01571 {
01572    int callno = (long) data;
01573 
01574    ast_mutex_lock(&iaxsl[callno]);
01575 
01576    if (iaxs[callno]) {
01577       if (iaxs[callno]->peercallno) {
01578          send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_LAGRQ, 0, NULL, 0, -1);
01579          if (iaxs[callno]->lagid != DONT_RESCHEDULE) {
01580             iaxs[callno]->lagid = iax2_sched_add(sched, lagrq_time * 1000, send_lagrq, data);
01581          }
01582       }
01583    } else {
01584       ast_debug(1, "I was supposed to send a LAGRQ with callno %d, but no such call exists.\n", callno);
01585    }
01586 
01587    ast_mutex_unlock(&iaxsl[callno]);
01588 }
01589 
01590 static int send_lagrq(const void *data)
01591 {
01592    int callno = (long) data;
01593    ast_mutex_lock(&iaxsl[callno]);
01594    if (iaxs[callno] && iaxs[callno]->lagid != DONT_RESCHEDULE) {
01595       iaxs[callno]->lagid = -1;
01596    }
01597    ast_mutex_unlock(&iaxsl[callno]);
01598 
01599 #ifdef SCHED_MULTITHREADED
01600    if (schedule_action(__send_lagrq, data))
01601 #endif
01602       __send_lagrq(data);
01603    return 0;
01604 }
01605 
01606 static unsigned char compress_subclass(format_t subclass)
01607 {
01608    int x;
01609    int power=-1;
01610    /* If it's 64 or smaller, just return it */
01611    if (subclass < IAX_FLAG_SC_LOG)
01612       return subclass;
01613    /* Otherwise find its power */
01614    for (x = 0; x < IAX_MAX_SHIFT; x++) {
01615       if (subclass & (1LL << x)) {
01616          if (power > -1) {
01617             ast_log(LOG_WARNING, "Can't compress subclass %lld\n", (long long) subclass);
01618             return 0;
01619          } else
01620             power = x;
01621       }
01622    }
01623    return power | IAX_FLAG_SC_LOG;
01624 }
01625 
01626 static format_t uncompress_subclass(unsigned char csub)
01627 {
01628    /* If the SC_LOG flag is set, return 2^csub otherwise csub */
01629    if (csub & IAX_FLAG_SC_LOG) {
01630       /* special case for 'compressed' -1 */
01631       if (csub == 0xff)
01632          return -1;
01633       else
01634          return 1LL << (csub & ~IAX_FLAG_SC_LOG & IAX_MAX_SHIFT);
01635    }
01636    else
01637       return csub;
01638 }
01639 
01640 /*!
01641  * \note The only member of the peer passed here guaranteed to be set is the name field
01642  */
01643 static int peer_hash_cb(const void *obj, const int flags)
01644 {
01645    const struct iax2_peer *peer = obj;
01646 
01647    return ast_str_hash(peer->name);
01648 }
01649 
01650 /*!
01651  * \note The only member of the peer passed here guaranteed to be set is the name field
01652  */
01653 static int peer_cmp_cb(void *obj, void *arg, int flags)
01654 {
01655    struct iax2_peer *peer = obj, *peer2 = arg;
01656 
01657    return !strcmp(peer->name, peer2->name) ? CMP_MATCH | CMP_STOP : 0;
01658 }
01659 
01660 /*!
01661  * \note The only member of the user passed here guaranteed to be set is the name field
01662  */
01663 static int user_hash_cb(const void *obj, const int flags)
01664 {
01665    const struct iax2_user *user = obj;
01666 
01667    return ast_str_hash(user->name);
01668 }
01669 
01670 /*!
01671  * \note The only member of the user passed here guaranteed to be set is the name field
01672  */
01673 static int user_cmp_cb(void *obj, void *arg, int flags)
01674 {
01675    struct iax2_user *user = obj, *user2 = arg;
01676 
01677    return !strcmp(user->name, user2->name) ? CMP_MATCH | CMP_STOP : 0;
01678 }
01679 
01680 /*!
01681  * \note This funtion calls realtime_peer -> reg_source_db -> iax2_poke_peer -> find_callno,
01682  *       so do not call it with a pvt lock held.
01683  */
01684 static struct iax2_peer *find_peer(const char *name, int realtime) 
01685 {
01686    struct iax2_peer *peer = NULL;
01687    struct iax2_peer tmp_peer = {
01688       .name = name,
01689    };
01690 
01691    peer = ao2_find(peers, &tmp_peer, OBJ_POINTER);
01692 
01693    /* Now go for realtime if applicable */
01694    if(!peer && realtime)
01695       peer = realtime_peer(name, NULL);
01696 
01697    return peer;
01698 }
01699 
01700 static struct iax2_peer *peer_ref(struct iax2_peer *peer)
01701 {
01702    ao2_ref(peer, +1);
01703    return peer;
01704 }
01705 
01706 static inline struct iax2_peer *peer_unref(struct iax2_peer *peer)
01707 {
01708    ao2_ref(peer, -1);
01709    return NULL;
01710 }
01711 
01712 static struct iax2_user *find_user(const char *name)
01713 {
01714    struct iax2_user tmp_user = {
01715       .name = name,
01716    };
01717 
01718    return ao2_find(users, &tmp_user, OBJ_POINTER);
01719 }
01720 static inline struct iax2_user *user_ref(struct iax2_user *user)
01721 {
01722    ao2_ref(user, +1);
01723    return user;
01724 }
01725 
01726 static inline struct iax2_user *user_unref(struct iax2_user *user)
01727 {
01728    ao2_ref(user, -1);
01729    return NULL;
01730 }
01731 
01732 static int iax2_getpeername(struct sockaddr_in sin, char *host, int len)
01733 {
01734    struct iax2_peer *peer = NULL;
01735    int res = 0;
01736    struct ao2_iterator i;
01737 
01738    i = ao2_iterator_init(peers, 0);
01739    while ((peer = ao2_iterator_next(&i))) {
01740       struct sockaddr_in peer_addr;
01741 
01742       ast_sockaddr_to_sin(&peer->addr, &peer_addr);
01743 
01744       if ((peer_addr.sin_addr.s_addr == sin.sin_addr.s_addr) &&
01745           (peer_addr.sin_port == sin.sin_port)) {
01746          ast_copy_string(host, peer->name, len);
01747          peer_unref(peer);
01748          res = 1;
01749          break;
01750       }
01751       peer_unref(peer);
01752    }
01753    ao2_iterator_destroy(&i);
01754 
01755    if (!peer) {
01756       peer = realtime_peer(NULL, &sin);
01757       if (peer) {
01758          ast_copy_string(host, peer->name, len);
01759          peer_unref(peer);
01760          res = 1;
01761       }
01762    }
01763 
01764    return res;
01765 }
01766 
01767 /*!\note Assumes the lock on the pvt is already held, when
01768  * iax2_destroy_helper() is called. */
01769 static void iax2_destroy_helper(struct chan_iax2_pvt *pvt)
01770 {
01771    /* Decrement AUTHREQ count if needed */
01772    if (ast_test_flag64(pvt, IAX_MAXAUTHREQ)) {
01773       struct iax2_user *user;
01774       struct iax2_user tmp_user = {
01775          .name = pvt->username,
01776       };
01777 
01778       user = ao2_find(users, &tmp_user, OBJ_POINTER);
01779       if (user) {
01780          ast_atomic_fetchadd_int(&user->curauthreq, -1);
01781          user_unref(user);
01782       }
01783 
01784       ast_clear_flag64(pvt, IAX_MAXAUTHREQ);
01785    }
01786    /* No more pings or lagrq's */
01787    AST_SCHED_DEL_SPINLOCK(ast_sched_thread_get_context(sched), pvt->pingid, &iaxsl[pvt->callno]);
01788    pvt->pingid = DONT_RESCHEDULE;
01789    AST_SCHED_DEL_SPINLOCK(ast_sched_thread_get_context(sched), pvt->lagid, &iaxsl[pvt->callno]);
01790    pvt->lagid = DONT_RESCHEDULE;
01791    ast_sched_thread_del(sched, pvt->autoid);
01792    ast_sched_thread_del(sched, pvt->authid);
01793    ast_sched_thread_del(sched, pvt->initid);
01794    ast_sched_thread_del(sched, pvt->jbid);
01795    ast_sched_thread_del(sched, pvt->keyrotateid);
01796 }
01797 
01798 static void iax2_frame_free(struct iax_frame *fr)
01799 {
01800    ast_sched_thread_del(sched, fr->retrans);
01801    iax_frame_free(fr);
01802 }
01803 
01804 static int scheduled_destroy(const void *vid)
01805 {
01806    unsigned short callno = PTR_TO_CALLNO(vid);
01807    ast_mutex_lock(&iaxsl[callno]);
01808    if (iaxs[callno]) {
01809       if (option_debug) {
01810          ast_log(LOG_DEBUG, "Really destroying %d now...\n", callno);
01811       }
01812       iax2_destroy(callno);
01813    }
01814    ast_mutex_unlock(&iaxsl[callno]);
01815    return 0;
01816 }
01817 
01818 static void free_signaling_queue_entry(struct signaling_queue_entry *s)
01819 {
01820    ast_free(s->f.data.ptr);
01821    ast_free(s);
01822 }
01823 
01824 /*! \brief This function must be called once we are sure the other side has
01825  *  given us a call number.  All signaling is held here until that point. */
01826 static void send_signaling(struct chan_iax2_pvt *pvt)
01827 {
01828    struct signaling_queue_entry *s = NULL;
01829 
01830    while ((s = AST_LIST_REMOVE_HEAD(&pvt->signaling_queue, next))) {
01831       iax2_send(pvt, &s->f, 0, -1, 0, 0, 0);
01832       free_signaling_queue_entry(s);
01833    }
01834    pvt->hold_signaling = 0;
01835 }
01836 
01837 /*! \brief All frames other than that of type AST_FRAME_IAX must be held until
01838  *  we have received a destination call number. */
01839 static int queue_signalling(struct chan_iax2_pvt *pvt, struct ast_frame *f)
01840 {
01841    struct signaling_queue_entry *new;
01842 
01843    if (f->frametype == AST_FRAME_IAX || !pvt->hold_signaling) {
01844       return 1; /* do not queue this frame */
01845    } else if (!(new = ast_calloc(1, sizeof(struct signaling_queue_entry)))) {
01846       return -1;  /* out of memory */
01847    }
01848 
01849    memcpy(&new->f, f, sizeof(new->f)); /* copy ast_frame into our queue entry */
01850 
01851    if (new->f.datalen) { /* if there is data in this frame copy it over as well */
01852       if (!(new->f.data.ptr = ast_calloc(1, new->f.datalen))) {
01853          free_signaling_queue_entry(new);
01854          return -1;
01855       }
01856       memcpy(new->f.data.ptr, f->data.ptr, sizeof(*new->f.data.ptr));
01857    }
01858    AST_LIST_INSERT_TAIL(&pvt->signaling_queue, new, next);
01859 
01860    return 0;
01861 }
01862 
01863 static void pvt_destructor(void *obj)
01864 {
01865    struct chan_iax2_pvt *pvt = obj;
01866    struct iax_frame *cur = NULL;
01867    struct signaling_queue_entry *s = NULL;
01868 
01869    ast_mutex_lock(&iaxsl[pvt->callno]);
01870 
01871    iax2_destroy_helper(pvt);
01872 
01873    sched_delay_remove(&pvt->addr, pvt->callno_entry);
01874    pvt->callno_entry = NULL;
01875 
01876    /* Already gone */
01877    ast_set_flag64(pvt, IAX_ALREADYGONE);
01878 
01879    AST_LIST_TRAVERSE(&frame_queue[pvt->callno], cur, list) {
01880       /* Cancel any pending transmissions */
01881       cur->retries = -1;
01882    }
01883 
01884    ast_mutex_unlock(&iaxsl[pvt->callno]);
01885 
01886    while ((s = AST_LIST_REMOVE_HEAD(&pvt->signaling_queue, next))) {
01887       free_signaling_queue_entry(s);
01888    }
01889 
01890    if (pvt->reg) {
01891       pvt->reg->callno = 0;
01892    }
01893 
01894    if (!pvt->owner) {
01895       jb_frame frame;
01896       if (pvt->vars) {
01897           ast_variables_destroy(pvt->vars);
01898           pvt->vars = NULL;
01899       }
01900 
01901       while (jb_getall(pvt->jb, &frame) == JB_OK) {
01902          iax2_frame_free(frame.data);
01903       }
01904 
01905       jb_destroy(pvt->jb);
01906       ast_string_field_free_memory(pvt);
01907    }
01908 }
01909 
01910 static struct chan_iax2_pvt *new_iax(struct sockaddr_in *sin, const char *host)
01911 {
01912    struct chan_iax2_pvt *tmp;
01913    jb_conf jbconf;
01914 
01915    if (!(tmp = ao2_alloc(sizeof(*tmp), pvt_destructor))) {
01916       return NULL;
01917    }
01918 
01919    if (ast_string_field_init(tmp, 32)) {
01920       ao2_ref(tmp, -1);
01921       tmp = NULL;
01922       return NULL;
01923    }
01924       
01925    tmp->prefs = prefs;
01926    tmp->pingid = -1;
01927    tmp->lagid = -1;
01928    tmp->autoid = -1;
01929    tmp->authid = -1;
01930    tmp->initid = -1;
01931    tmp->keyrotateid = -1;
01932 
01933    ast_string_field_set(tmp,exten, "s");
01934    ast_string_field_set(tmp,host, host);
01935 
01936    tmp->jb = jb_new();
01937    tmp->jbid = -1;
01938    jbconf.max_jitterbuf = maxjitterbuffer;
01939    jbconf.resync_threshold = resyncthreshold;
01940    jbconf.max_contig_interp = maxjitterinterps;
01941    jbconf.target_extra = jittertargetextra;
01942    jb_setconf(tmp->jb,&jbconf);
01943 
01944    AST_LIST_HEAD_INIT_NOLOCK(&tmp->dpentries);
01945 
01946    tmp->hold_signaling = 1;
01947    AST_LIST_HEAD_INIT_NOLOCK(&tmp->signaling_queue);
01948 
01949    return tmp;
01950 }
01951 
01952 static struct iax_frame *iaxfrdup2(struct iax_frame *fr)
01953 {
01954    struct iax_frame *new = iax_frame_new(DIRECTION_INGRESS, fr->af.datalen, fr->cacheable);
01955    if (new) {
01956       size_t afdatalen = new->afdatalen;
01957       memcpy(new, fr, sizeof(*new));
01958       iax_frame_wrap(new, &fr->af);
01959       new->afdatalen = afdatalen;
01960       new->data = NULL;
01961       new->datalen = 0;
01962       new->direction = DIRECTION_INGRESS;
01963       new->retrans = -1;
01964    }
01965    return new;
01966 }
01967 /* keep these defined in this order.  They are used in find_callno to
01968  * determine whether or not a new call number should be allowed. */
01969 enum {
01970    /* do not allow a new call number, only search ones in use for match */
01971    NEW_PREVENT = 0,
01972    /* search for match first, then allow a new one to be allocated */
01973    NEW_ALLOW = 1,
01974    /* do not search for match, force a new call number */
01975    NEW_FORCE = 2,
01976    /* do not search for match, force a new call number.  Signifies call number
01977     * has been calltoken validated */
01978    NEW_ALLOW_CALLTOKEN_VALIDATED = 3,
01979 };
01980 
01981 static int match(struct sockaddr_in *sin, unsigned short callno, unsigned short dcallno, const struct chan_iax2_pvt *cur, int check_dcallno)
01982 {
01983    if ((cur->addr.sin_addr.s_addr == sin->sin_addr.s_addr) &&
01984       (cur->addr.sin_port == sin->sin_port)) {
01985       /* This is the main host */
01986       if ( (cur->peercallno == 0 || cur->peercallno == callno) &&
01987           (check_dcallno ? dcallno == cur->callno : 1) ) {
01988          /* That's us.  Be sure we keep track of the peer call number */
01989          return 1;
01990       }
01991    }
01992    if ((cur->transfer.sin_addr.s_addr == sin->sin_addr.s_addr) &&
01993        (cur->transfer.sin_port == sin->sin_port) && (cur->transferring)) {
01994       /* We're transferring */
01995       if ((dcallno == cur->callno) || (cur->transferring == TRANSFER_MEDIAPASS && cur->transfercallno == callno))
01996          return 1;
01997    }
01998    return 0;
01999 }
02000 
02001 static void update_max_trunk(void)
02002 {
02003    int max = TRUNK_CALL_START;
02004    int x;
02005 
02006    /* XXX Prolly don't need locks here XXX */
02007    for (x = TRUNK_CALL_START; x < ARRAY_LEN(iaxs) - 1; x++) {
02008       if (iaxs[x]) {
02009          max = x + 1;
02010       }
02011    }
02012 
02013    maxtrunkcall = max;
02014    if (iaxdebug)
02015       ast_debug(1, "New max trunk callno is %d\n", max);
02016 }
02017 
02018 static void update_max_nontrunk(void)
02019 {
02020    int max = 1;
02021    int x;
02022    /* XXX Prolly don't need locks here XXX */
02023    for (x=1;x<TRUNK_CALL_START - 1; x++) {
02024       if (iaxs[x])
02025          max = x + 1;
02026    }
02027    maxnontrunkcall = max;
02028    if (iaxdebug)
02029       ast_debug(1, "New max nontrunk callno is %d\n", max);
02030 }
02031 
02032 static int make_trunk(unsigned short callno, int locked)
02033 {
02034    int x;
02035    int res= 0;
02036    struct callno_entry *callno_entry;
02037    if (iaxs[callno]->oseqno) {
02038       ast_log(LOG_WARNING, "Can't make trunk once a call has started!\n");
02039       return -1;
02040    }
02041    if (callno & TRUNK_CALL_START) {
02042       ast_log(LOG_WARNING, "Call %d is already a trunk\n", callno);
02043       return -1;
02044    }
02045 
02046    if (!(callno_entry = get_unused_callno(1, iaxs[callno]->callno_entry->validated))) {
02047       ast_log(LOG_WARNING, "Unable to trunk call: Insufficient space\n");
02048       return -1;
02049    }
02050 
02051    x = callno_entry->callno;
02052    ast_mutex_lock(&iaxsl[x]);
02053 
02054    /*!
02055     * \note We delete these before switching the slot, because if
02056     * they fire in the meantime, they will generate a warning.
02057     */
02058    ast_sched_thread_del(sched, iaxs[callno]->pingid);
02059    ast_sched_thread_del(sched, iaxs[callno]->lagid);
02060    iaxs[callno]->lagid = iaxs[callno]->pingid = -1;
02061    iaxs[x] = iaxs[callno];
02062    iaxs[x]->callno = x;
02063 
02064    /* since we copied over the pvt from a different callno, make sure the old entry is replaced
02065     * before assigning the new one */
02066    if (iaxs[x]->callno_entry) {
02067       iax2_sched_add(sched, MIN_REUSE_TIME * 1000, replace_callno, iaxs[x]->callno_entry);
02068    }
02069    iaxs[x]->callno_entry = callno_entry;
02070 
02071    iaxs[callno] = NULL;
02072    /* Update the two timers that should have been started */
02073    iaxs[x]->pingid = iax2_sched_add(sched, 
02074       ping_time * 1000, send_ping, (void *)(long)x);
02075    iaxs[x]->lagid = iax2_sched_add(sched, 
02076       lagrq_time * 1000, send_lagrq, (void *)(long)x);
02077 
02078    if (locked)
02079       ast_mutex_unlock(&iaxsl[callno]);
02080    res = x;
02081    if (!locked)
02082       ast_mutex_unlock(&iaxsl[x]);
02083 
02084    ast_debug(1, "Made call %d into trunk call %d\n", callno, x);
02085    /* We move this call from a non-trunked to a trunked call */
02086    update_max_trunk();
02087    update_max_nontrunk();
02088    return res;
02089 }
02090 
02091 static void store_by_transfercallno(struct chan_iax2_pvt *pvt)
02092 {
02093    if (!pvt->transfercallno) {
02094       ast_log(LOG_ERROR, "This should not be called without a transfer call number.\n");
02095       return;
02096    }
02097 
02098    ao2_link(iax_transfercallno_pvts, pvt);
02099 }
02100 
02101 static void remove_by_transfercallno(struct chan_iax2_pvt *pvt)
02102 {
02103    if (!pvt->transfercallno) {
02104       ast_log(LOG_ERROR, "This should not be called without a transfer call number.\n");
02105       return;
02106    }
02107 
02108    ao2_unlink(iax_transfercallno_pvts, pvt);
02109 }
02110 static void store_by_peercallno(struct chan_iax2_pvt *pvt)
02111 {
02112    if (!pvt->peercallno) {
02113       ast_log(LOG_ERROR, "This should not be called without a peer call number.\n");
02114       return;
02115    }
02116 
02117    ao2_link(iax_peercallno_pvts, pvt);
02118 }
02119 
02120 static void remove_by_peercallno(struct chan_iax2_pvt *pvt)
02121 {
02122    if (!pvt->peercallno) {
02123       ast_log(LOG_ERROR, "This should not be called without a peer call number.\n");
02124       return;
02125    }
02126 
02127    ao2_unlink(iax_peercallno_pvts, pvt);
02128 }
02129 
02130 static int addr_range_delme_cb(void *obj, void *arg, int flags)
02131 {
02132    struct addr_range *lim = obj;
02133    lim->delme = 1;
02134    return 0;
02135 }
02136 
02137 static int addr_range_hash_cb(const void *obj, const int flags)
02138 {
02139    const struct addr_range *lim = obj;
02140    struct sockaddr_in sin;
02141    ast_sockaddr_to_sin(&lim->ha.addr, &sin);
02142    return abs((int) sin.sin_addr.s_addr);
02143 }
02144 
02145 static int addr_range_cmp_cb(void *obj, void *arg, int flags)
02146 {
02147    struct addr_range *lim1 = obj, *lim2 = arg;
02148    return (!(ast_sockaddr_cmp_addr(&lim1->ha.addr, &lim2->ha.addr)) &&
02149          !(ast_sockaddr_cmp_addr(&lim1->ha.netmask, &lim2->ha.netmask))) ?
02150          CMP_MATCH | CMP_STOP : 0;
02151 }
02152 
02153 static int peercnt_hash_cb(const void *obj, const int flags)
02154 {
02155    const struct peercnt *peercnt = obj;
02156    return abs((int) peercnt->addr);
02157 }
02158 
02159 static int peercnt_cmp_cb(void *obj, void *arg, int flags)
02160 {
02161    struct peercnt *peercnt1 = obj, *peercnt2 = arg;
02162    return (peercnt1->addr == peercnt2->addr) ? CMP_MATCH | CMP_STOP : 0;
02163 }
02164 
02165 static int addr_range_match_address_cb(void *obj, void *arg, int flags)
02166 {
02167    struct addr_range *addr_range = obj;
02168    struct sockaddr_in *sin = arg;
02169    struct sockaddr_in ha_netmask_sin;
02170    struct sockaddr_in ha_addr_sin;
02171 
02172    ast_sockaddr_to_sin(&addr_range->ha.netmask, &ha_netmask_sin);
02173    ast_sockaddr_to_sin(&addr_range->ha.addr, &ha_addr_sin);
02174 
02175    if ((sin->sin_addr.s_addr & ha_netmask_sin.sin_addr.s_addr) == ha_addr_sin.sin_addr.s_addr) {
02176       return CMP_MATCH | CMP_STOP;
02177    }
02178    return 0;
02179 }
02180 
02181 /*! 
02182  * \internal
02183  *
02184  * \brief compares sin to calltoken_ignores table to determine if validation is required.
02185  */
02186 static int calltoken_required(struct sockaddr_in *sin, const char *name, int subclass)
02187 {
02188    struct addr_range *addr_range;
02189    struct iax2_peer *peer = NULL;
02190    struct iax2_user *user = NULL;
02191    /* if no username is given, check for guest accounts */
02192    const char *find = S_OR(name, "guest");
02193    int res = 1;  /* required by default */
02194    int optional = 0;
02195    enum calltoken_peer_enum calltoken_required = CALLTOKEN_DEFAULT;
02196    /* There are only two cases in which calltoken validation is not required.
02197     * Case 1. sin falls within the list of address ranges specified in the calltoken optional table and
02198     *         the peer definition has not set the requirecalltoken option.
02199     * Case 2. Username is a valid peer/user, and that peer has requirecalltoken set either auto or no.
02200     */
02201 
02202    /* ----- Case 1 ----- */
02203    if ((addr_range = ao2_callback(calltoken_ignores, 0, addr_range_match_address_cb, sin))) {
02204       ao2_ref(addr_range, -1);
02205       optional = 1;
02206    }
02207 
02208    /* ----- Case 2 ----- */
02209    if ((subclass == IAX_COMMAND_NEW) && (user = find_user(find))) {
02210       calltoken_required = user->calltoken_required;
02211    } else if ((subclass == IAX_COMMAND_NEW) && (user = realtime_user(find, sin))) {
02212       calltoken_required = user->calltoken_required;
02213    } else if ((subclass != IAX_COMMAND_NEW) && (peer = find_peer(find, 0))) {
02214       calltoken_required = peer->calltoken_required;
02215    } else if ((subclass != IAX_COMMAND_NEW) && (peer = realtime_peer(find, sin))) {
02216       calltoken_required = peer->calltoken_required;
02217    }
02218 
02219    if (peer) {
02220       peer_unref(peer);
02221    }
02222    if (user) {
02223       user_unref(user);
02224    }
02225 
02226    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);
02227    if (((calltoken_required == CALLTOKEN_NO) || (calltoken_required == CALLTOKEN_AUTO)) ||
02228       (optional && (calltoken_required == CALLTOKEN_DEFAULT))) {
02229       res = 0;
02230    }
02231 
02232    return res;
02233 }
02234 
02235 /*! 
02236  * \internal
02237  *
02238  * \brief set peercnt callno limit.
02239  *
02240  * \details 
02241  * First looks in custom definitions. If not found, global limit
02242  * is used.  Entries marked as reg already have
02243  * a custom limit set by a registration and are not modified.
02244  */
02245 static void set_peercnt_limit(struct peercnt *peercnt)
02246 {
02247    uint16_t limit = global_maxcallno;
02248    struct addr_range *addr_range;
02249    struct sockaddr_in sin = {
02250       .sin_addr.s_addr = peercnt->addr,
02251    };
02252 
02253 
02254    if (peercnt->reg && peercnt->limit) {
02255       return; /* this peercnt has a custom limit set by a registration */
02256    }
02257 
02258    if ((addr_range = ao2_callback(callno_limits, 0, addr_range_match_address_cb, &sin))) {
02259       limit = addr_range->limit;
02260       ast_debug(1, "custom addr_range %d found for %s\n", limit, ast_inet_ntoa(sin.sin_addr));
02261       ao2_ref(addr_range, -1);
02262    }
02263 
02264    peercnt->limit = limit;
02265 }
02266 
02267 /*! 
02268  * \internal
02269  * \brief sets limits for all peercnts in table. done on reload to reflect changes in conf.
02270  */
02271 static int set_peercnt_limit_all_cb(void *obj, void *arg, int flags)
02272 {
02273    struct peercnt *peercnt = obj;
02274 
02275    set_peercnt_limit(peercnt);
02276    ast_debug(1, "Reset limits for peercnts table\n");
02277 
02278    return 0;
02279 }
02280 
02281 /*! 
02282  * \internal
02283  * \brief returns match if delme is set. 
02284  */
02285 static int prune_addr_range_cb(void *obj, void *arg, int flags)
02286 {
02287    struct addr_range *addr_range = obj;
02288 
02289    return addr_range->delme ? CMP_MATCH : 0;
02290 }
02291 
02292 /*! 
02293  * \internal
02294  * \brief modifies peercnt entry in peercnts table. Used to set custom limit or mark a registered ip
02295  */
02296 static void peercnt_modify(unsigned char reg, uint16_t limit, struct ast_sockaddr *sockaddr)
02297 {
02298    /* this function turns off and on custom callno limits set by peer registration */
02299    struct peercnt *peercnt;
02300    struct peercnt tmp = {
02301       .addr = 0,
02302    };
02303    struct sockaddr_in sin;
02304 
02305    ast_sockaddr_to_sin(sockaddr, &sin);
02306 
02307    tmp.addr = sin.sin_addr.s_addr;
02308 
02309    if ((peercnt = ao2_find(peercnts, &tmp, OBJ_POINTER))) {
02310       peercnt->reg = reg;
02311       if (limit) {
02312          peercnt->limit = limit;
02313       } else {
02314          set_peercnt_limit(peercnt);
02315       }
02316       ast_debug(1, "peercnt entry %s modified limit:%d registered:%d", ast_inet_ntoa(sin.sin_addr), peercnt->limit, peercnt->reg);
02317       ao2_ref(peercnt, -1); /* decrement ref from find */
02318    }
02319 }
02320 
02321 /*! 
02322  * \internal
02323  * \brief adds an ip to the peercnts table, increments connection count if it already exists
02324  *
02325  * \details First searches for the address in the peercnts table.  If found
02326  * the current count is incremented.  If not found a new peercnt is allocated
02327  * and linked into the peercnts table with a call number count of 1.
02328  */
02329 static int peercnt_add(struct sockaddr_in *sin)
02330 {
02331    struct peercnt *peercnt;
02332    unsigned long addr = sin->sin_addr.s_addr;
02333    int res = 0;
02334    struct peercnt tmp = {
02335       .addr = addr,
02336    };
02337 
02338    /* Reasoning for peercnts container lock:  Two identical ip addresses
02339     * could be added by different threads at the "same time". Without the container
02340     * lock, both threads could alloc space for the same object and attempt
02341     * to link to table.  With the lock, one would create the object and link
02342     * to table while the other would find the already created peercnt object
02343     * rather than creating a new one. */
02344    ao2_lock(peercnts);
02345    if ((peercnt = ao2_find(peercnts, &tmp, OBJ_POINTER))) {
02346       ao2_lock(peercnt);
02347    } else if ((peercnt = ao2_alloc(sizeof(*peercnt), NULL))) {
02348       ao2_lock(peercnt);
02349       /* create and set defaults */
02350       peercnt->addr = addr;
02351       set_peercnt_limit(peercnt);
02352       /* guarantees it does not go away after unlocking table
02353        * ao2_find automatically adds this */
02354       ao2_link(peercnts, peercnt);
02355    } else {
02356       ao2_unlock(peercnts);
02357       return -1;
02358    }
02359 
02360    /* check to see if the address has hit its callno limit.  If not increment cur. */
02361    if (peercnt->limit > peercnt->cur) {
02362       peercnt->cur++;
02363       ast_debug(1, "ip callno count incremented to %d for %s\n", peercnt->cur, ast_inet_ntoa(sin->sin_addr));
02364    } else { /* max num call numbers for this peer has been reached! */
02365       ast_log(LOG_ERROR, "maxcallnumber limit of %d for %s has been reached!\n", peercnt->limit, ast_inet_ntoa(sin->sin_addr));
02366       res = -1;
02367    }
02368 
02369    /* clean up locks and ref count */
02370    ao2_unlock(peercnt);
02371    ao2_unlock(peercnts);
02372    ao2_ref(peercnt, -1); /* decrement ref from find/alloc, only the container ref remains. */
02373 
02374    return res;
02375 }
02376 
02377 /*! 
02378  * \internal
02379  * \brief decrements a peercnts table entry
02380  */
02381 static void peercnt_remove(struct peercnt *peercnt)
02382 {
02383    struct sockaddr_in sin = {
02384       .sin_addr.s_addr = peercnt->addr,
02385    };
02386 
02387    if (peercnt) {
02388       /* Container locked here since peercnt may be unlinked from list.  If left unlocked,
02389        * peercnt_add could try and grab this entry from the table and modify it at the
02390        * "same time" this thread attemps to unlink it.*/
02391       ao2_lock(peercnts);
02392       peercnt->cur--;
02393       ast_debug(1, "ip callno count decremented to %d for %s\n", peercnt->cur, ast_inet_ntoa(sin.sin_addr));
02394       /* if this was the last connection from the peer remove it from table */
02395       if (peercnt->cur == 0) {
02396          ao2_unlink(peercnts, peercnt);/* decrements ref from table, last ref is left to scheduler */
02397       }
02398       ao2_unlock(peercnts);
02399    }
02400 }
02401 
02402 /*! 
02403  * \internal
02404  * \brief called by scheduler to decrement object
02405  */
02406 static int peercnt_remove_cb(const void *obj)
02407 {
02408    struct peercnt *peercnt = (struct peercnt *) obj;
02409 
02410    peercnt_remove(peercnt);
02411    ao2_ref(peercnt, -1); /* decrement ref from scheduler */
02412 
02413    return 0;
02414 }
02415 
02416 /*! 
02417  * \internal
02418  * \brief decrements peercnts connection count, finds by addr
02419  */
02420 static int peercnt_remove_by_addr(struct sockaddr_in *sin)
02421 {
02422    struct peercnt *peercnt;
02423    struct peercnt tmp = {
02424       .addr = sin->sin_addr.s_addr,
02425    };
02426 
02427    if ((peercnt = ao2_find(peercnts, &tmp, OBJ_POINTER))) {
02428       peercnt_remove(peercnt);
02429       ao2_ref(peercnt, -1); /* decrement ref from find */
02430    }
02431    return 0;
02432 }
02433 
02434 /*! 
02435  * \internal
02436  * \brief Create callno_limit entry based on configuration
02437  */
02438 static void build_callno_limits(struct ast_variable *v)
02439 {
02440    struct addr_range *addr_range = NULL;
02441    struct addr_range tmp;
02442    struct ast_ha *ha;
02443    int limit;
02444    int error;
02445    int found;
02446 
02447    for (; v; v = v->next) {
02448       limit = -1;
02449       error = 0;
02450       found = 0;
02451       ha = ast_append_ha("permit", v->name, NULL, &error);
02452 
02453       /* check for valid config information */
02454       if (error) {
02455          ast_log(LOG_ERROR, "Call number limit for %s could not be added, Invalid address range\n.", v->name);
02456          continue;
02457       } else if ((sscanf(v->value, "%d", &limit) != 1) || (limit < 0)) {
02458          ast_log(LOG_ERROR, "Call number limit for %s could not be added. Invalid limit %s\n.", v->name, v->value);
02459          ast_free_ha(ha);
02460          continue;
02461       }
02462 
02463       ast_copy_ha(ha, &tmp.ha);
02464       /* find or create the addr_range */
02465       if ((addr_range = ao2_find(callno_limits, &tmp, OBJ_POINTER))) {
02466          ao2_lock(addr_range);
02467          found = 1;
02468       } else if (!(addr_range = ao2_alloc(sizeof(*addr_range), NULL))) {
02469          ast_free_ha(ha);
02470          return; /* out of memory */
02471       }
02472 
02473       /* copy over config data into addr_range object */
02474       ast_copy_ha(ha, &addr_range->ha); /* this is safe because only one ha is possible for each limit */
02475       ast_free_ha(ha); /* cleanup the tmp ha */
02476       addr_range->limit = limit;
02477       addr_range->delme = 0;
02478 
02479       /* cleanup */
02480       if (found) {
02481          ao2_unlock(addr_range);
02482       } else {
02483          ao2_link(callno_limits, addr_range);
02484       }
02485       ao2_ref(addr_range, -1); /* decrement ref from ao2_find and ao2_alloc, only container ref remains */
02486    }
02487 }
02488 
02489 /*! 
02490  * \internal
02491  * \brief Create calltoken_ignores entry based on configuration
02492  */
02493 static int add_calltoken_ignore(const char *addr)
02494 {
02495    struct addr_range tmp;
02496    struct addr_range *addr_range = NULL;
02497    struct ast_ha *ha = NULL;
02498    int error = 0;
02499 
02500    if (ast_strlen_zero(addr)) {
02501       ast_log(LOG_WARNING, "invalid calltokenoptional %s\n", addr);
02502       return -1;
02503    }
02504 
02505    ha = ast_append_ha("permit", addr, NULL, &error);
02506 
02507    /* check for valid config information */
02508    if (error) {
02509       ast_log(LOG_WARNING, "Error %d creating calltokenoptional entry %s\n", error, addr);
02510       return -1;
02511    }
02512 
02513    ast_copy_ha(ha, &tmp.ha);
02514    /* find or create the addr_range */
02515    if ((addr_range = ao2_find(calltoken_ignores, &tmp, OBJ_POINTER))) {
02516       ao2_lock(addr_range);
02517       addr_range->delme = 0;
02518       ao2_unlock(addr_range);
02519    } else if ((addr_range = ao2_alloc(sizeof(*addr_range), NULL))) {
02520       /* copy over config data into addr_range object */
02521       ast_copy_ha(ha, &addr_range->ha); /* this is safe because only one ha is possible */
02522       ao2_link(calltoken_ignores, addr_range);
02523    } else {
02524       ast_free_ha(ha);
02525       return -1;
02526    }
02527 
02528    ast_free_ha(ha);
02529    ao2_ref(addr_range, -1); /* decrement ref from ao2_find and ao2_alloc, only container ref remains */
02530 
02531    return 0;
02532 }
02533 
02534 static char *handle_cli_iax2_show_callno_limits(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
02535 {
02536    struct ao2_iterator i;
02537    struct peercnt *peercnt;
02538    struct sockaddr_in sin;
02539    int found = 0;
02540 
02541    switch (cmd) {
02542    case CLI_INIT:
02543       e->command = "iax2 show callnumber usage";
02544       e->usage =
02545          "Usage: iax2 show callnumber usage [IP address]\n"
02546          "       Shows current IP addresses which are consuming iax2 call numbers\n";
02547       return NULL;
02548    case CLI_GENERATE:
02549       return NULL;
02550    case CLI_HANDLER:
02551       if (a->argc < 4 || a->argc > 5)
02552          return CLI_SHOWUSAGE;
02553 
02554       ast_cli(a->fd, "%-15s %-12s %-12s\n", "Address", "Callno Usage", "Callno Limit");
02555       i = ao2_iterator_init(peercnts, 0);
02556       while ((peercnt = ao2_iterator_next(&i))) {
02557          sin.sin_addr.s_addr = peercnt->addr;
02558          if (a->argc == 5 && (!strcasecmp(a->argv[4], ast_inet_ntoa(sin.sin_addr)))) {
02559                ast_cli(a->fd, "%-15s %-12d %-12d\n", ast_inet_ntoa(sin.sin_addr), peercnt->cur, peercnt->limit);
02560                found = 1;
02561                break;
02562          } else {
02563             ast_cli(a->fd, "%-15s %-12d %-12d\n", ast_inet_ntoa(sin.sin_addr), peercnt->cur, peercnt->limit);
02564          }
02565          ao2_ref(peercnt, -1);
02566       }
02567       ao2_iterator_destroy(&i);
02568 
02569       if (a->argc == 4) {
02570          ast_cli(a->fd, "\nNon-CallToken Validation Callno Limit: %d\n"
02571                           "Non-CallToken Validated Callno Used:   %d\n",
02572             global_maxcallno_nonval,
02573             total_nonval_callno_used);
02574 
02575          ast_cli(a->fd,   "Total Available Callno:                %d\n"
02576                           "Regular Callno Available:              %d\n"
02577                           "Trunk Callno Available:                %d\n",
02578             ao2_container_count(callno_pool) + ao2_container_count(callno_pool_trunk),
02579             ao2_container_count(callno_pool),
02580             ao2_container_count(callno_pool_trunk));
02581       } else if (a->argc == 5 && !found) {
02582          ast_cli(a->fd, "No callnumber table entries for %s found\n", a->argv[4] );
02583       }
02584 
02585 
02586       return CLI_SUCCESS;
02587    default:
02588       return NULL;
02589    }
02590 }
02591 
02592 static struct callno_entry *get_unused_callno(int trunk, int validated)
02593 {
02594    struct callno_entry *callno_entry = NULL;
02595    if ((!ao2_container_count(callno_pool) && !trunk) || (!ao2_container_count(callno_pool_trunk) && trunk)) {
02596       ast_log(LOG_WARNING, "Out of CallNumbers\n");
02597       /* Minor optimization for the extreme case. */
02598       return NULL;
02599    }
02600 
02601    /* the callno_pool container is locked here primarily to ensure thread
02602     * safety of the total_nonval_callno_used check and increment */
02603    ao2_lock(callno_pool);
02604 
02605    /* only a certain number of nonvalidated call numbers should be allocated.
02606     * If there ever is an attack, this separates the calltoken validating
02607     * users from the non calltoken validating users. */
02608    if (!validated && (total_nonval_callno_used >= global_maxcallno_nonval)) {
02609       ast_log(LOG_WARNING, "NON-CallToken callnumber limit is reached. Current:%d Max:%d\n", total_nonval_callno_used, global_maxcallno_nonval);
02610       ao2_unlock(callno_pool);
02611       return NULL;
02612    }
02613 
02614    /* unlink the object from the container, taking over ownership
02615     * of the reference the container had to the object */
02616    callno_entry = ao2_find((trunk ? callno_pool_trunk : callno_pool), NULL, OBJ_POINTER | OBJ_UNLINK | OBJ_CONTINUE);
02617 
02618    if (callno_entry) {
02619       callno_entry->validated = validated;
02620       if (!validated) {
02621          total_nonval_callno_used++;
02622       }
02623    }
02624 
02625    ao2_unlock(callno_pool);
02626    return callno_entry;
02627 }
02628 
02629 static int replace_callno(const void *obj)
02630 {
02631    struct callno_entry *callno_entry = (struct callno_entry *) obj;
02632 
02633    /* the callno_pool container is locked here primarily to ensure thread
02634     * safety of the total_nonval_callno_used check and decrement */
02635    ao2_lock(callno_pool);
02636 
02637    if (!callno_entry->validated && (total_nonval_callno_used != 0)) {
02638       total_nonval_callno_used--;
02639    } else if (!callno_entry->validated && (total_nonval_callno_used == 0)) {
02640       ast_log(LOG_ERROR, "Attempted to decrement total non calltoken validated callnumbers below zero... Callno is:%d \n", callno_entry->callno);
02641    }
02642 
02643    if (callno_entry->callno < TRUNK_CALL_START) {
02644       ao2_link(callno_pool, callno_entry);
02645    } else {
02646       ao2_link(callno_pool_trunk, callno_entry);
02647    }
02648    ao2_ref(callno_entry, -1); /* only container ref remains */
02649 
02650    ao2_unlock(callno_pool);
02651    return 0;
02652 }
02653 
02654 static int callno_hash(const void *obj, const int flags)
02655 {
02656    return abs(ast_random());
02657 }
02658 
02659 static int create_callno_pools(void)
02660 {
02661    uint16_t i;
02662 
02663    if (!(callno_pool = ao2_container_alloc(CALLNO_POOL_BUCKETS, callno_hash, NULL))) {
02664       return -1;
02665    }
02666 
02667    if (!(callno_pool_trunk = ao2_container_alloc(CALLNO_POOL_BUCKETS, callno_hash, NULL))) {
02668       return -1;
02669    }
02670 
02671    /* start at 2, 0 and 1 are reserved */
02672    for (i = 2; i <= IAX_MAX_CALLS; i++) {
02673       struct callno_entry *callno_entry;
02674 
02675       if (!(callno_entry = ao2_alloc(sizeof(*callno_entry), NULL))) {
02676          return -1;
02677       }
02678 
02679       callno_entry->callno = i;
02680 
02681       if (i < TRUNK_CALL_START) {
02682          ao2_link(callno_pool, callno_entry);
02683       } else {
02684          ao2_link(callno_pool_trunk, callno_entry);
02685       }
02686 
02687       ao2_ref(callno_entry, -1);
02688    }
02689 
02690    return 0;
02691 }
02692 
02693 /*!
02694  * \internal
02695  * \brief Schedules delayed removal of iax2_pvt call number data
02696  *
02697  * \note After MIN_REUSE_TIME has passed for a destroyed iax2_pvt, the callno is
02698  * avaliable again, and the address from the previous connection must be decremented
02699  * from the peercnts table.  This function schedules these operations to take place.
02700  */
02701 static void sched_delay_remove(struct sockaddr_in *sin, struct callno_entry *callno_entry)
02702 {
02703    int i;
02704    struct peercnt *peercnt;
02705    struct peercnt tmp = {
02706       .addr = sin->sin_addr.s_addr,
02707    };
02708 
02709    if ((peercnt = ao2_find(peercnts, &tmp, OBJ_POINTER))) {
02710       /* refcount is incremented with ao2_find.  keep that ref for the scheduler */
02711       ast_debug(1, "schedule decrement of callno used for %s in %d seconds\n", ast_inet_ntoa(sin->sin_addr), MIN_REUSE_TIME);
02712       i = iax2_sched_add(sched, MIN_REUSE_TIME * 1000, peercnt_remove_cb, peercnt);
02713       if (i == -1) {
02714          ao2_ref(peercnt, -1);
02715       }
02716    }
02717 
02718    iax2_sched_add(sched, MIN_REUSE_TIME * 1000, replace_callno, callno_entry);
02719 }
02720 
02721 /*! 
02722  * \internal
02723  * \brief returns whether or not a frame is capable of starting a new IAX2 dialog. 
02724  *
02725  * \note For this implementation, inbound pokes should _NOT_ be capable of allocating
02726  * a new callno.
02727  */
02728 static inline int attribute_pure iax2_allow_new(int frametype, int subclass, int inbound)
02729 {
02730    if (frametype != AST_FRAME_IAX) {
02731       return 0;
02732    }
02733    switch (subclass) {
02734    case IAX_COMMAND_NEW:
02735    case IAX_COMMAND_REGREQ:
02736    case IAX_COMMAND_FWDOWNL:
02737    case IAX_COMMAND_REGREL:
02738       return 1;
02739    case IAX_COMMAND_POKE:
02740       if (!inbound) {
02741          return 1;
02742       }
02743       break;
02744    }
02745    return 0;
02746 }
02747 
02748 /*
02749  * \note Calling this function while holding another pvt lock can cause a deadlock.
02750  */
02751 static int __find_callno(unsigned short callno, unsigned short dcallno, struct sockaddr_in *sin, int new, int sockfd, int return_locked, int check_dcallno)
02752 {
02753    int res = 0;
02754    int x;
02755    /* this call is calltoken validated as long as it is either NEW_FORCE
02756     * or NEW_ALLOW_CALLTOKEN_VALIDATED */
02757    int validated = (new > NEW_ALLOW) ? 1 : 0;
02758    char host[80];
02759 
02760    if (new <= NEW_ALLOW) {
02761       if (callno) {
02762          struct chan_iax2_pvt *pvt;
02763          struct chan_iax2_pvt tmp_pvt = {
02764             .callno = dcallno,
02765             .peercallno = callno,
02766             .transfercallno = callno,
02767             /* hack!! */
02768             .frames_received = check_dcallno,
02769          };
02770 
02771          memcpy(&tmp_pvt.addr, sin, sizeof(tmp_pvt.addr));
02772          /* this works for finding normal call numbers not involving transfering */ 
02773          if ((pvt = ao2_find(iax_peercallno_pvts, &tmp_pvt, OBJ_POINTER))) {
02774             if (return_locked) {
02775                ast_mutex_lock(&iaxsl[pvt->callno]);
02776             }
02777             res = pvt->callno;
02778             ao2_ref(pvt, -1);
02779             pvt = NULL;
02780             return res;
02781          }
02782          /* this searches for transfer call numbers that might not get caught otherwise */
02783          memset(&tmp_pvt.addr, 0, sizeof(tmp_pvt.addr));
02784          memcpy(&tmp_pvt.transfer, sin, sizeof(tmp_pvt.transfer));
02785          if ((pvt = ao2_find(iax_transfercallno_pvts, &tmp_pvt, OBJ_POINTER))) {
02786             if (return_locked) {
02787                ast_mutex_lock(&iaxsl[pvt->callno]);
02788             }
02789             res = pvt->callno;
02790             ao2_ref(pvt, -1);
02791             pvt = NULL;
02792             return res;
02793          }
02794       }
02795          /* This will occur on the first response to a message that we initiated,
02796        * such as a PING. */
02797       if (dcallno) {
02798          ast_mutex_lock(&iaxsl[dcallno]);
02799       }
02800       if (callno && dcallno && iaxs[dcallno] && !iaxs[dcallno]->peercallno && match(sin, callno, dcallno, iaxs[dcallno], check_dcallno)) {
02801          iaxs[dcallno]->peercallno = callno;
02802          res = dcallno;
02803          store_by_peercallno(iaxs[dcallno]);
02804          if (!res || !return_locked) {
02805             ast_mutex_unlock(&iaxsl[dcallno]);
02806          }
02807          return res;
02808       }
02809       if (dcallno) {
02810          ast_mutex_unlock(&iaxsl[dcallno]);
02811       }
02812 #ifdef IAX_OLD_FIND
02813       /* If we get here, we SHOULD NOT find a call structure for this
02814          callno; if we do, it means that there is a call structure that
02815          has a peer callno but did NOT get entered into the hash table,
02816          which is bad.
02817 
02818          If we find a call structure using this old, slow method, output a log
02819          message so we'll know about it. After a few months of leaving this in
02820          place, if we don't hear about people seeing these messages, we can
02821          remove this code for good.
02822       */
02823 
02824       for (x = 1; !res && x < maxnontrunkcall; x++) {
02825          ast_mutex_lock(&iaxsl[x]);
02826          if (iaxs[x]) {
02827             /* Look for an exact match */
02828             if (match(sin, callno, dcallno, iaxs[x], check_dcallno)) {
02829                res = x;
02830             }
02831          }
02832          if (!res || !return_locked)
02833             ast_mutex_unlock(&iaxsl[x]);
02834       }
02835       for (x = TRUNK_CALL_START; !res && x < maxtrunkcall; x++) {
02836          ast_mutex_lock(&iaxsl[x]);
02837          if (iaxs[x]) {
02838             /* Look for an exact match */
02839             if (match(sin, callno, dcallno, iaxs[x], check_dcallno)) {
02840                res = x;
02841             }
02842          }
02843          if (!res || !return_locked)
02844             ast_mutex_unlock(&iaxsl[x]);
02845       }
02846 #endif
02847    }
02848    if (!res && (new >= NEW_ALLOW)) {
02849       struct callno_entry *callno_entry;
02850       /* It may seem odd that we look through the peer list for a name for
02851        * this *incoming* call.  Well, it is weird.  However, users don't
02852        * have an IP address/port number that we can match against.  So,
02853        * this is just checking for a peer that has that IP/port and
02854        * assuming that we have a user of the same name.  This isn't always
02855        * correct, but it will be changed if needed after authentication. */
02856       if (!iax2_getpeername(*sin, host, sizeof(host)))
02857          snprintf(host, sizeof(host), "%s:%d", ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
02858 
02859       if (peercnt_add(sin)) {
02860          /* This address has hit its callnumber limit.  When the limit
02861           * is reached, the connection is not added to the peercnts table.*/
02862          return 0;
02863       }
02864 
02865       if (!(callno_entry = get_unused_callno(0, validated))) {
02866          /* since we ran out of space, remove the peercnt
02867           * entry we added earlier */
02868          peercnt_remove_by_addr(sin);
02869          ast_log(LOG_WARNING, "No more space\n");
02870          return 0;
02871       }
02872       x = callno_entry->callno;
02873       ast_mutex_lock(&iaxsl[x]);
02874 
02875       iaxs[x] = new_iax(sin, host);
02876       update_max_nontrunk();
02877       if (iaxs[x]) {
02878          if (iaxdebug)
02879             ast_debug(1, "Creating new call structure %d\n", x);
02880          iaxs[x]->callno_entry = callno_entry;
02881          iaxs[x]->sockfd = sockfd;
02882          iaxs[x]->addr.sin_port = sin->sin_port;
02883          iaxs[x]->addr.sin_family = sin->sin_family;
02884          iaxs[x]->addr.sin_addr.s_addr = sin->sin_addr.s_addr;
02885          iaxs[x]->peercallno = callno;
02886          iaxs[x]->callno = x;
02887          iaxs[x]->pingtime = DEFAULT_RETRY_TIME;
02888          iaxs[x]->expiry = min_reg_expire;
02889          iaxs[x]->pingid = iax2_sched_add(sched, ping_time * 1000, send_ping, (void *)(long)x);
02890          iaxs[x]->lagid = iax2_sched_add(sched, lagrq_time * 1000, send_lagrq, (void *)(long)x);
02891          iaxs[x]->amaflags = amaflags;
02892          ast_copy_flags64(iaxs[x], &globalflags, IAX_NOTRANSFER | IAX_TRANSFERMEDIA | IAX_USEJITTERBUF | IAX_FORCEJITTERBUF | IAX_SENDCONNECTEDLINE | IAX_RECVCONNECTEDLINE | IAX_FORCE_ENCRYPT);
02893          ast_string_field_set(iaxs[x], accountcode, accountcode);
02894          ast_string_field_set(iaxs[x], mohinterpret, mohinterpret);
02895          ast_string_field_set(iaxs[x], mohsuggest, mohsuggest);
02896          ast_string_field_set(iaxs[x], parkinglot, default_parkinglot);
02897 
02898          if (iaxs[x]->peercallno) {
02899             store_by_peercallno(iaxs[x]);
02900          }
02901       } else {
02902          ast_log(LOG_WARNING, "Out of resources\n");
02903          ast_mutex_unlock(&iaxsl[x]);
02904          replace_callno(callno_entry);
02905          return 0;
02906       }
02907       if (!return_locked)
02908          ast_mutex_unlock(&iaxsl[x]);
02909       res = x;
02910    }
02911    return res;
02912 }
02913 
02914 static int find_callno(unsigned short callno, unsigned short dcallno, struct sockaddr_in *sin, int new, int sockfd, int full_frame) { 
02915    return __find_callno(callno, dcallno, sin, new, sockfd, 0, full_frame);
02916 }
02917 
02918 static int find_callno_locked(unsigned short callno, unsigned short dcallno, struct sockaddr_in *sin, int new, int sockfd, int full_frame) {
02919 
02920    return __find_callno(callno, dcallno, sin, new, sockfd, 1, full_frame);
02921 }
02922 
02923 /*!
02924  * \brief Queue a frame to a call's owning asterisk channel
02925  *
02926  * \pre This function assumes that iaxsl[callno] is locked when called.
02927  *
02928  * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
02929  * was valid before calling it, it may no longer be valid after calling it.
02930  * This function may unlock and lock the mutex associated with this callno,
02931  * meaning that another thread may grab it and destroy the call.
02932  */
02933 static int iax2_queue_frame(int callno, struct ast_frame *f)
02934 {
02935    iax2_lock_owner(callno);
02936    if (iaxs[callno] && iaxs[callno]->owner) {
02937       ast_queue_frame(iaxs[callno]->owner, f);
02938       ast_channel_unlock(iaxs[callno]->owner);
02939    }
02940    return 0;
02941 }
02942 
02943 /*!
02944  * \brief Queue a hangup frame on the ast_channel owner
02945  *
02946  * This function queues a hangup frame on the owner of the IAX2 pvt struct that
02947  * is active for the given call number.
02948  *
02949  * \pre Assumes lock for callno is already held.
02950  *
02951  * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
02952  * was valid before calling it, it may no longer be valid after calling it.
02953  * This function may unlock and lock the mutex associated with this callno,
02954  * meaning that another thread may grab it and destroy the call.
02955  */
02956 static int iax2_queue_hangup(int callno)
02957 {
02958    iax2_lock_owner(callno);
02959    if (iaxs[callno] && iaxs[callno]->owner) {
02960       ast_queue_hangup(iaxs[callno]->owner);
02961       ast_channel_unlock(iaxs[callno]->owner);
02962    }
02963    return 0;
02964 }
02965 
02966 /*!
02967  * \brief Queue a control frame on the ast_channel owner
02968  *
02969  * This function queues a control frame on the owner of the IAX2 pvt struct that
02970  * is active for the given call number.
02971  *
02972  * \pre Assumes lock for callno is already held.
02973  *
02974  * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
02975  * was valid before calling it, it may no longer be valid after calling it.
02976  * This function may unlock and lock the mutex associated with this callno,
02977  * meaning that another thread may grab it and destroy the call.
02978  */
02979 static int iax2_queue_control_data(int callno, 
02980    enum ast_control_frame_type control, const void *data, size_t datalen)
02981 {
02982    iax2_lock_owner(callno);
02983    if (iaxs[callno] && iaxs[callno]->owner) {
02984       ast_queue_control_data(iaxs[callno]->owner, control, data, datalen);
02985       ast_channel_unlock(iaxs[callno]->owner);
02986    }
02987    return 0;
02988 }
02989 static void destroy_firmware(struct iax_firmware *cur)
02990 {
02991    /* Close firmware */
02992    if (cur->fwh) {
02993       munmap((void*)cur->fwh, ntohl(cur->fwh->datalen) + sizeof(*(cur->fwh)));
02994    }
02995    close(cur->fd);
02996    ast_free(cur);
02997 }
02998 
02999 static int try_firmware(char *s)
03000 {
03001    struct stat stbuf;
03002    struct iax_firmware *cur = NULL;
03003    int ifd, fd, res, len, chunk;
03004    struct ast_iax2_firmware_header *fwh, fwh2;
03005    struct MD5Context md5;
03006    unsigned char sum[16], buf[1024];
03007    char *s2, *last;
03008 
03009    if (!(s2 = alloca(strlen(s) + 100))) {
03010       ast_log(LOG_WARNING, "Alloca failed!\n");
03011       return -1;
03012    }
03013 
03014    last = strrchr(s, '/');
03015    if (last)
03016       last++;
03017    else
03018       last = s;
03019 
03020    snprintf(s2, strlen(s) + 100, "/var/tmp/%s-%ld", last, (unsigned long)ast_random());
03021 
03022    if ((res = stat(s, &stbuf) < 0)) {
03023       ast_log(LOG_WARNING, "Failed to stat '%s': %s\n", s, strerror(errno));
03024       return -1;
03025    }
03026 
03027    /* Make sure it's not a directory */
03028    if (S_ISDIR(stbuf.st_mode))
03029       return -1;
03030    ifd = open(s, O_RDONLY);
03031    if (ifd < 0) {
03032       ast_log(LOG_WARNING, "Cannot open '%s': %s\n", s, strerror(errno));
03033       return -1;
03034    }
03035    fd = open(s2, O_RDWR | O_CREAT | O_EXCL, AST_FILE_MODE);
03036    if (fd < 0) {
03037       ast_log(LOG_WARNING, "Cannot open '%s' for writing: %s\n", s2, strerror(errno));
03038       close(ifd);
03039       return -1;
03040    }
03041    /* Unlink our newly created file */
03042    unlink(s2);
03043    
03044    /* Now copy the firmware into it */
03045    len = stbuf.st_size;
03046    while(len) {
03047       chunk = len;
03048       if (chunk > sizeof(buf))
03049          chunk = sizeof(buf);
03050       res = read(ifd, buf, chunk);
03051       if (res != chunk) {
03052          ast_log(LOG_WARNING, "Only read %d of %d bytes of data :(: %s\n", res, chunk, strerror(errno));
03053          close(ifd);
03054          close(fd);
03055          return -1;
03056       }
03057       res = write(fd, buf, chunk);
03058       if (res != chunk) {
03059          ast_log(LOG_WARNING, "Only write %d of %d bytes of data :(: %s\n", res, chunk, strerror(errno));
03060          close(ifd);
03061          close(fd);
03062          return -1;
03063       }
03064       len -= chunk;
03065    }
03066    close(ifd);
03067    /* Return to the beginning */
03068    lseek(fd, 0, SEEK_SET);
03069    if ((res = read(fd, &fwh2, sizeof(fwh2))) != sizeof(fwh2)) {
03070       ast_log(LOG_WARNING, "Unable to read firmware header in '%s'\n", s);
03071       close(fd);
03072       return -1;
03073    }
03074    if (ntohl(fwh2.magic) != IAX_FIRMWARE_MAGIC) {
03075       ast_log(LOG_WARNING, "'%s' is not a valid firmware file\n", s);
03076       close(fd);
03077       return -1;
03078    }
03079    if (ntohl(fwh2.datalen) != (stbuf.st_size - sizeof(fwh2))) {
03080       ast_log(LOG_WARNING, "Invalid data length in firmware '%s'\n", s);
03081       close(fd);
03082       return -1;
03083    }
03084    if (fwh2.devname[sizeof(fwh2.devname) - 1] || ast_strlen_zero((char *)fwh2.devname)) {
03085       ast_log(LOG_WARNING, "No or invalid device type specified for '%s'\n", s);
03086       close(fd);
03087       return -1;
03088    }
03089    fwh = (struct ast_iax2_firmware_header*)mmap(NULL, stbuf.st_size, PROT_READ, MAP_PRIVATE, fd, 0); 
03090    if (fwh == MAP_FAILED) {
03091       ast_log(LOG_WARNING, "mmap failed: %s\n", strerror(errno));
03092       close(fd);
03093       return -1;
03094    }
03095    MD5Init(&md5);
03096    MD5Update(&md5, fwh->data, ntohl(fwh->datalen));
03097    MD5Final(sum, &md5);
03098    if (memcmp(sum, fwh->chksum, sizeof(sum))) {
03099       ast_log(LOG_WARNING, "Firmware file '%s' fails checksum\n", s);
03100       munmap((void*)fwh, stbuf.st_size);
03101       close(fd);
03102       return -1;
03103    }
03104 
03105    AST_LIST_TRAVERSE(&firmwares, cur, list) {
03106       if (!strcmp((char *)cur->fwh->devname, (char *)fwh->devname)) {
03107          /* Found a candidate */
03108          if (cur->dead || (ntohs(cur->fwh->version) < ntohs(fwh->version)))
03109             /* The version we have on loaded is older, load this one instead */
03110             break;
03111          /* This version is no newer than what we have.  Don't worry about it.
03112             We'll consider it a proper load anyhow though */
03113          munmap((void*)fwh, stbuf.st_size);
03114          close(fd);
03115          return 0;
03116       }
03117    }
03118    
03119    if (!cur && ((cur = ast_calloc(1, sizeof(*cur))))) {
03120       cur->fd = -1;
03121       AST_LIST_INSERT_TAIL(&firmwares, cur, list);
03122    }
03123    
03124    if (cur) {
03125       if (cur->fwh)
03126          munmap((void*)cur->fwh, cur->mmaplen);
03127       if (cur->fd > -1)
03128          close(cur->fd);
03129       cur->fwh = fwh;
03130       cur->fd = fd;
03131       cur->mmaplen = stbuf.st_size;
03132       cur->dead = 0;
03133    }
03134    
03135    return 0;
03136 }
03137 
03138 static int iax_check_version(char *dev)
03139 {
03140    int res = 0;
03141    struct iax_firmware *cur = NULL;
03142 
03143    if (ast_strlen_zero(dev))
03144       return 0;
03145 
03146    AST_LIST_LOCK(&firmwares);
03147    AST_LIST_TRAVERSE(&firmwares, cur, list) {
03148       if (!strcmp(dev, (char *)cur->fwh->devname)) {
03149          res = ntohs(cur->fwh->version);
03150          break;
03151       }
03152    }
03153    AST_LIST_UNLOCK(&firmwares);
03154 
03155    return res;
03156 }
03157 
03158 static int iax_firmware_append(struct iax_ie_data *ied, const unsigned char *dev, unsigned int desc)
03159 {
03160    int res = -1;
03161    unsigned int bs = desc & 0xff;
03162    unsigned int start = (desc >> 8) & 0xffffff;
03163    unsigned int bytes;
03164    struct iax_firmware *cur;
03165 
03166    if (ast_strlen_zero((char *)dev) || !bs)
03167       return -1;
03168 
03169    start *= bs;
03170    
03171    AST_LIST_LOCK(&firmwares);
03172    AST_LIST_TRAVERSE(&firmwares, cur, list) {
03173       if (strcmp((char *)dev, (char *)cur->fwh->devname))
03174          continue;
03175       iax_ie_append_int(ied, IAX_IE_FWBLOCKDESC, desc);
03176       if (start < ntohl(cur->fwh->datalen)) {
03177          bytes = ntohl(cur->fwh->datalen) - start;
03178          if (bytes > bs)
03179             bytes = bs;
03180          iax_ie_append_raw(ied, IAX_IE_FWBLOCKDATA, cur->fwh->data + start, bytes);
03181       } else {
03182          bytes = 0;
03183          iax_ie_append(ied, IAX_IE_FWBLOCKDATA);
03184       }
03185       if (bytes == bs)
03186          res = 0;
03187       else
03188          res = 1;
03189       break;
03190    }
03191    AST_LIST_UNLOCK(&firmwares);
03192 
03193    return res;
03194 }
03195 
03196 
03197 static void reload_firmware(int unload)
03198 {
03199    struct iax_firmware *cur = NULL;
03200    DIR *fwd;
03201    struct dirent *de;
03202    char dir[256], fn[256];
03203 
03204    AST_LIST_LOCK(&firmwares);
03205 
03206    /* Mark all as dead */
03207    AST_LIST_TRAVERSE(&firmwares, cur, list)
03208       cur->dead = 1;
03209 
03210    /* Now that we have marked them dead... load new ones */
03211    if (!unload) {
03212       snprintf(dir, sizeof(dir), "%s/firmware/iax", ast_config_AST_DATA_DIR);
03213       fwd = opendir(dir);
03214       if (fwd) {
03215          while((de = readdir(fwd))) {
03216             if (de->d_name[0] != '.') {
03217                snprintf(fn, sizeof(fn), "%s/%s", dir, de->d_name);
03218                if (!try_firmware(fn)) {
03219                   ast_verb(2, "Loaded firmware '%s'\n", de->d_name);
03220                }
03221             }
03222          }
03223          closedir(fwd);
03224       } else 
03225          ast_log(LOG_WARNING, "Error opening firmware directory '%s': %s\n", dir, strerror(errno));
03226    }
03227 
03228    /* Clean up leftovers */
03229    AST_LIST_TRAVERSE_SAFE_BEGIN(&firmwares, cur, list) {
03230       if (!cur->dead)
03231          continue;
03232       AST_LIST_REMOVE_CURRENT(list);
03233       destroy_firmware(cur);
03234    }
03235    AST_LIST_TRAVERSE_SAFE_END;
03236 
03237    AST_LIST_UNLOCK(&firmwares);
03238 }
03239 
03240 /*!
03241  * \note This function assumes that iaxsl[callno] is locked when called.
03242  *
03243  * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
03244  * was valid before calling it, it may no longer be valid after calling it.
03245  * This function calls iax2_queue_frame(), which may unlock and lock the mutex 
03246  * associated with this callno, meaning that another thread may grab it and destroy the call.
03247  */
03248 static int __do_deliver(void *data)
03249 {
03250    /* Just deliver the packet by using queueing.  This is called by
03251      the IAX thread with the iaxsl lock held. */
03252    struct iax_frame *fr = data;
03253    fr->retrans = -1;
03254    ast_clear_flag(&fr->af, AST_FRFLAG_HAS_TIMING_INFO);
03255    if (iaxs[fr->callno] && !ast_test_flag64(iaxs[fr->callno], IAX_ALREADYGONE))
03256       iax2_queue_frame(fr->callno, &fr->af);
03257    /* Free our iax frame */
03258    iax2_frame_free(fr);
03259    /* And don't run again */
03260    return 0;
03261 }
03262 
03263 static int handle_error(void)
03264 {
03265    /* XXX Ideally we should figure out why an error occurred and then abort those
03266       rather than continuing to try.  Unfortunately, the published interface does
03267       not seem to work XXX */
03268 #if 0
03269    struct sockaddr_in *sin;
03270    int res;
03271    struct msghdr m;
03272    struct sock_extended_err e;
03273    m.msg_name = NULL;
03274    m.msg_namelen = 0;
03275    m.msg_iov = NULL;
03276    m.msg_control = &e;
03277    m.msg_controllen = sizeof(e);
03278    m.msg_flags = 0;
03279    res = recvmsg(netsocket, &m, MSG_ERRQUEUE);
03280    if (res < 0)
03281       ast_log(LOG_WARNING, "Error detected, but unable to read error: %s\n", strerror(errno));
03282    else {
03283       if (m.msg_controllen) {
03284          sin = (struct sockaddr_in *)SO_EE_OFFENDER(&e);
03285          if (sin) 
03286             ast_log(LOG_WARNING, "Receive error from %s\n", ast_inet_ntoa(sin->sin_addr));
03287          else
03288             ast_log(LOG_WARNING, "No address detected??\n");
03289       } else {
03290          ast_log(LOG_WARNING, "Local error: %s\n", strerror(e.ee_errno));
03291       }
03292    }
03293 #endif
03294    return 0;
03295 }
03296 
03297 static int transmit_trunk(struct iax_frame *f, struct sockaddr_in *sin, int sockfd)
03298 {
03299    int res;
03300    res = sendto(sockfd, f->data, f->datalen, 0,(struct sockaddr *)sin,
03301                sizeof(*sin));
03302    if (res < 0) {
03303       ast_debug(1, "Received error: %s\n", strerror(errno));
03304       handle_error();
03305    } else
03306       res = 0;
03307    return res;
03308 }
03309 
03310 static int send_packet(struct iax_frame *f)
03311 {
03312    int res;
03313    int callno = f->callno;
03314 
03315    /* Don't send if there was an error, but return error instead */
03316    if (!callno || !iaxs[callno] || iaxs[callno]->error)
03317        return -1;
03318    
03319    /* Called with iaxsl held */
03320    if (iaxdebug)
03321       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));
03322    
03323    if (f->transfer) {
03324       if (iaxdebug)
03325          iax_showframe(f, NULL, 0, &iaxs[callno]->transfer, f->datalen - sizeof(struct ast_iax2_full_hdr));
03326       res = sendto(iaxs[callno]->sockfd, f->data, f->datalen, 0,(struct sockaddr *)&iaxs[callno]->transfer, sizeof(iaxs[callno]->transfer));
03327    } else {
03328       if (iaxdebug)
03329          iax_showframe(f, NULL, 0, &iaxs[callno]->addr, f->datalen - sizeof(struct ast_iax2_full_hdr));
03330       res = sendto(iaxs[callno]->sockfd, f->data, f->datalen, 0,(struct sockaddr *)&iaxs[callno]->addr, sizeof(iaxs[callno]->addr));
03331    }
03332    if (res < 0) {
03333       if (iaxdebug)
03334          ast_debug(1, "Received error: %s\n", strerror(errno));
03335       handle_error();
03336    } else
03337       res = 0;
03338 
03339    return res;
03340 }
03341 
03342 /*!
03343  * \note Since this function calls iax2_queue_hangup(), the pvt struct
03344  *       for the given call number may disappear during its execution.
03345  */
03346 static int iax2_predestroy(int callno)
03347 {
03348    struct ast_channel *c = NULL;
03349    struct chan_iax2_pvt *pvt = iaxs[callno];
03350 
03351    if (!pvt)
03352       return -1;
03353 
03354    if (!ast_test_flag64(pvt, IAX_ALREADYGONE)) {
03355       iax2_destroy_helper(pvt);
03356       ast_set_flag64(pvt, IAX_ALREADYGONE);
03357    }
03358 
03359    if ((c = pvt->owner)) {
03360       c->tech_pvt = NULL;
03361       iax2_queue_hangup(callno);
03362       pvt->owner = NULL;
03363       ast_module_unref(ast_module_info->self);
03364    }
03365 
03366    return 0;
03367 }
03368 
03369 static void iax2_destroy(int callno)
03370 {
03371    struct chan_iax2_pvt *pvt = NULL;
03372    struct ast_channel *owner = NULL;
03373 
03374 retry:
03375    if ((pvt = iaxs[callno])) {
03376 #if 0
03377       /* iax2_destroy_helper gets called from this function later on.  When
03378        * called twice, we get the (previously) familiar FRACK! errors in
03379        * devmode, from the scheduler.  An alternative to this approach is to
03380        * reset the scheduler entries to -1 when they're deleted in
03381        * iax2_destroy_helper().  That approach was previously decided to be
03382        * "wrong" because "the memory is going to be deallocated anyway.  Why
03383        * should we be resetting those values?" */
03384       iax2_destroy_helper(pvt);
03385 #endif
03386    }
03387 
03388    owner = pvt ? pvt->owner : NULL;
03389 
03390    if (owner) {
03391       if (ast_channel_trylock(owner)) {
03392          ast_debug(3, "Avoiding IAX destroy deadlock\n");
03393          DEADLOCK_AVOIDANCE(&iaxsl[callno]);
03394          goto retry;
03395       }
03396    }
03397 
03398    if (!owner) {
03399       iaxs[callno] = NULL;
03400    }
03401 
03402    if (pvt) {
03403       if (!owner) {
03404          pvt->owner = NULL;
03405       } else {
03406          /* If there's an owner, prod it to give up */
03407          /* It is ok to use ast_queue_hangup() here instead of iax2_queue_hangup()
03408           * because we already hold the owner channel lock. */
03409          ast_queue_hangup(owner);
03410       }
03411 
03412       if (pvt->peercallno) {
03413          remove_by_peercallno(pvt);
03414       }
03415 
03416       if (pvt->transfercallno) {
03417          remove_by_transfercallno(pvt);
03418       }
03419 
03420       if (!owner) {
03421          ao2_ref(pvt, -1);
03422          pvt = NULL;
03423       }
03424    }
03425 
03426    if (owner) {
03427       ast_channel_unlock(owner);
03428    }
03429 
03430    if (callno & 0x4000) {
03431       update_max_trunk();
03432    }
03433 }
03434 
03435 static int update_packet(struct iax_frame *f)
03436 {
03437    /* Called with iaxsl lock held, and iaxs[callno] non-NULL */
03438    struct ast_iax2_full_hdr *fh = f->data;
03439    struct ast_frame af;
03440 
03441    /* if frame is encrypted. decrypt before updating it. */
03442    if (f->encmethods) {
03443       decode_frame(&f->mydcx, fh, &af, &f->datalen);
03444    }
03445    /* Mark this as a retransmission */
03446    fh->dcallno = ntohs(IAX_FLAG_RETRANS | f->dcallno);
03447    /* Update iseqno */
03448    f->iseqno = iaxs[f->callno]->iseqno;
03449    fh->iseqno = f->iseqno;
03450 
03451    /* Now re-encrypt the frame */
03452    if (f->encmethods) {
03453    /* since this is a retransmit frame, create a new random padding
03454     * before re-encrypting. */
03455       build_rand_pad(f->semirand, sizeof(f->semirand));
03456       encrypt_frame(&f->ecx, fh, f->semirand, &f->datalen);
03457    }
03458    return 0;
03459 }
03460 
03461 static int attempt_transmit(const void *data);
03462 static void __attempt_transmit(const void *data)
03463 {
03464    /* Attempt to transmit the frame to the remote peer...
03465       Called without iaxsl held. */
03466    struct iax_frame *f = (struct iax_frame *)data;
03467    int freeme = 0;
03468    int callno = f->callno;
03469    /* Make sure this call is still active */
03470    if (callno) 
03471       ast_mutex_lock(&iaxsl[callno]);
03472    if (callno && iaxs[callno]) {
03473       if ((f->retries < 0) /* Already ACK'd */ ||
03474           (f->retries >= max_retries) /* Too many attempts */) {
03475             /* Record an error if we've transmitted too many times */
03476             if (f->retries >= max_retries) {
03477                if (f->transfer) {
03478                   /* Transfer timeout */
03479                   send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_TXREJ, 0, NULL, 0, -1);
03480                } else if (f->final) {
03481                   iax2_destroy(callno);
03482                } else {
03483                   if (iaxs[callno]->owner)
03484                      ast_log(LOG_WARNING, "Max retries exceeded to host %s on %s (type = %d, subclass = %u, ts=%d, seqno=%d)\n", ast_inet_ntoa(iaxs[f->callno]->addr.sin_addr),iaxs[f->callno]->owner->name , f->af.frametype, f->af.subclass.integer, f->ts, f->oseqno);
03485                   iaxs[callno]->error = ETIMEDOUT;
03486                   if (iaxs[callno]->owner) {
03487                      struct ast_frame fr = { AST_FRAME_CONTROL, { AST_CONTROL_HANGUP }, .data.uint32 = AST_CAUSE_DESTINATION_OUT_OF_ORDER };
03488                      /* Hangup the fd */
03489                      iax2_queue_frame(callno, &fr); /* XXX */
03490                      /* Remember, owner could disappear */
03491                      if (iaxs[callno] && iaxs[callno]->owner)
03492                         iaxs[callno]->owner->hangupcause = AST_CAUSE_DESTINATION_OUT_OF_ORDER;
03493                   } else {
03494                      if (iaxs[callno]->reg) {
03495                         memset(&iaxs[callno]->reg->us, 0, sizeof(iaxs[callno]->reg->us));
03496                         iaxs[callno]->reg->regstate = REG_STATE_TIMEOUT;
03497                         iaxs[callno]->reg->refresh = IAX_DEFAULT_REG_EXPIRE;
03498                      }
03499                      iax2_destroy(callno);
03500                   }
03501                }
03502 
03503             }
03504             freeme = 1;
03505       } else {
03506          /* Update it if it needs it */
03507          update_packet(f);
03508          /* Attempt transmission */
03509          send_packet(f);
03510          f->retries++;
03511          /* Try again later after 10 times as long */
03512          f->retrytime *= 10;
03513          if (f->retrytime > MAX_RETRY_TIME)
03514             f->retrytime = MAX_RETRY_TIME;
03515          /* Transfer messages max out at one second */
03516          if (f->transfer && (f->retrytime > 1000))
03517             f->retrytime = 1000;
03518          f->retrans = iax2_sched_add(sched, f->retrytime, attempt_transmit, f);
03519       }
03520    } else {
03521       /* Make sure it gets freed */
03522       f->retries = -1;
03523       freeme = 1;
03524    }
03525 
03526    if (freeme) {
03527       /* Don't attempt delivery, just remove it from the queue */
03528       AST_LIST_REMOVE(&frame_queue[callno], f, list);
03529       ast_mutex_unlock(&iaxsl[callno]);
03530       f->retrans = -1; /* this is safe because this is the scheduled function */
03531       /* Free the IAX frame */
03532       iax2_frame_free(f);
03533    } else if (callno) {
03534       ast_mutex_unlock(&iaxsl[callno]);
03535    }
03536 }
03537 
03538 static int attempt_transmit(const void *data)
03539 {
03540 #ifdef SCHED_MULTITHREADED
03541    if (schedule_action(__attempt_transmit, data))
03542 #endif      
03543       __attempt_transmit(data);
03544    return 0;
03545 }
03546 
03547 static char *handle_cli_iax2_prune_realtime(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
03548 {
03549    struct iax2_peer *peer = NULL;
03550    struct iax2_user *user = NULL;
03551    static const char * const choices[] = { "all", NULL };
03552    char *cmplt;
03553 
03554    switch (cmd) {
03555    case CLI_INIT:
03556       e->command = "iax2 prune realtime";
03557       e->usage =
03558          "Usage: iax2 prune realtime [<peername>|all]\n"
03559          "       Prunes object(s) from the cache\n";
03560       return NULL;
03561    case CLI_GENERATE:
03562       if (a->pos == 3) {
03563          cmplt = ast_cli_complete(a->word, choices, a->n);
03564          if (!cmplt)
03565             cmplt = complete_iax2_peers(a->line, a->word, a->pos, a->n - sizeof(choices), IAX_RTCACHEFRIENDS);
03566          return cmplt;
03567       }
03568       return NULL;
03569    }
03570    if (a->argc != 4)
03571       return CLI_SHOWUSAGE;
03572    if (!strcmp(a->argv[3], "all")) {
03573       prune_users();
03574       prune_peers();
03575       ast_cli(a->fd, "Cache flushed successfully.\n");
03576       return CLI_SUCCESS;
03577    }
03578    peer = find_peer(a->argv[3], 0);
03579    user = find_user(a->argv[3]);
03580    if (peer || user) {
03581       if (peer) {
03582          if (ast_test_flag64(peer, IAX_RTCACHEFRIENDS)) {
03583             ast_set_flag64(peer, IAX_RTAUTOCLEAR);
03584             expire_registry(peer_ref(peer));
03585             ast_cli(a->fd, "Peer %s was removed from the cache.\n", a->argv[3]);
03586          } else {
03587             ast_cli(a->fd, "Peer %s is not eligible for this operation.\n", a->argv[3]);
03588          }
03589          peer_unref(peer);
03590       }
03591       if (user) {
03592          if (ast_test_flag64(user, IAX_RTCACHEFRIENDS)) {
03593             ast_set_flag64(user, IAX_RTAUTOCLEAR);
03594             ast_cli(a->fd, "User %s was removed from the cache.\n", a->argv[3]);
03595          } else {
03596             ast_cli(a->fd, "User %s is not eligible for this operation.\n", a->argv[3]);
03597          }
03598          ao2_unlink(users,user);
03599          user_unref(user);
03600       }
03601    } else {
03602       ast_cli(a->fd, "%s was not found in the cache.\n", a->argv[3]);
03603    }
03604 
03605    return CLI_SUCCESS;
03606 }
03607 
03608 static char *handle_cli_iax2_test_losspct(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
03609 {
03610    switch (cmd) {
03611    case CLI_INIT:
03612       e->command = "iax2 test losspct";
03613       e->usage =
03614          "Usage: iax2 test losspct <percentage>\n"
03615          "       For testing, throws away <percentage> percent of incoming packets\n";
03616       return NULL;
03617    case CLI_GENERATE:
03618       return NULL;
03619    }
03620    if (a->argc != 4)
03621       return CLI_SHOWUSAGE;
03622 
03623    test_losspct = atoi(a->argv[3]);
03624 
03625    return CLI_SUCCESS;
03626 }
03627 
03628 #ifdef IAXTESTS
03629 static char *handle_cli_iax2_test_late(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
03630 {
03631    switch (cmd) {
03632    case CLI_INIT:
03633       e->command = "iax2 test late";
03634       e->usage =
03635          "Usage: iax2 test late <ms>\n"
03636          "       For testing, count the next frame as <ms> ms late\n";
03637       return NULL;
03638    case CLI_GENERATE:
03639       return NULL;
03640    }
03641 
03642    if (a->argc != 4)
03643       return CLI_SHOWUSAGE;
03644 
03645    test_late = atoi(a->argv[3]);
03646 
03647    return CLI_SUCCESS;
03648 }
03649 
03650 static char *handle_cli_iax2_test_resync(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
03651 {
03652    switch (cmd) {
03653    case CLI_INIT:
03654       e->command = "iax2 test resync";
03655       e->usage =
03656          "Usage: iax2 test resync <ms>\n"
03657          "       For testing, adjust all future frames by <ms> ms\n";
03658       return NULL;
03659    case CLI_GENERATE:
03660       return NULL;
03661    }
03662 
03663    if (a->argc != 4)
03664       return CLI_SHOWUSAGE;
03665 
03666    test_resync = atoi(a->argv[3]);
03667 
03668    return CLI_SUCCESS;
03669 }
03670 
03671 static char *handle_cli_iax2_test_jitter(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
03672 {
03673    switch (cmd) {
03674    case CLI_INIT:
03675       e->command = "iax2 test jitter";
03676       e->usage =
03677          "Usage: iax2 test jitter <ms> <pct>\n"
03678          "       For testing, simulate maximum jitter of +/- <ms> on <pct>\n"
03679          "       percentage of packets. If <pct> is not specified, adds\n"
03680          "       jitter to all packets.\n";
03681       return NULL;
03682    case CLI_GENERATE:
03683       return NULL;
03684    }
03685 
03686    if (a->argc < 4 || a->argc > 5)
03687       return CLI_SHOWUSAGE;
03688 
03689    test_jit = atoi(a->argv[3]);
03690    if (a->argc == 5)
03691       test_jitpct = atoi(a->argv[4]);
03692 
03693    return CLI_SUCCESS;
03694 }
03695 #endif /* IAXTESTS */
03696 
03697 /*! \brief  peer_status: Report Peer status in character string */
03698 /*    returns 1 if peer is online, -1 if unmonitored */
03699 static int peer_status(struct iax2_peer *peer, char *status, int statuslen)
03700 {
03701    int res = 0;
03702    if (peer->maxms) {
03703       if (peer->lastms < 0) {
03704          ast_copy_string(status, "UNREACHABLE", statuslen);
03705       } else if (peer->lastms > peer->maxms) {
03706          snprintf(status, statuslen, "LAGGED (%d ms)", peer->lastms);
03707          res = 1;
03708       } else if (peer->lastms) {
03709          snprintf(status, statuslen, "OK (%d ms)", peer->lastms);
03710          res = 1;
03711       } else {
03712          ast_copy_string(status, "UNKNOWN", statuslen);
03713       }
03714    } else { 
03715       ast_copy_string(status, "Unmonitored", statuslen);
03716       res = -1;
03717    }
03718    return res;
03719 }
03720 
03721 /*! \brief Show one peer in detail */
03722 static char *handle_cli_iax2_show_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
03723 {
03724    char status[30];
03725    char cbuf[256];
03726    struct iax2_peer *peer;
03727    char codec_buf[512];
03728    struct ast_str *encmethods = ast_str_alloca(256);
03729    int x = 0, codec = 0, load_realtime = 0;
03730 
03731    switch (cmd) {
03732    case CLI_INIT:
03733       e->command = "iax2 show peer";
03734       e->usage =
03735          "Usage: iax2 show peer <name>\n"
03736          "       Display details on specific IAX peer\n";
03737       return NULL;
03738    case CLI_GENERATE:
03739       if (a->pos == 3)
03740          return complete_iax2_peers(a->line, a->word, a->pos, a->n, 0);
03741       return NULL;
03742    }
03743 
03744    if (a->argc < 4)
03745       return CLI_SHOWUSAGE;
03746 
03747    load_realtime = (a->argc == 5 && !strcmp(a->argv[4], "load")) ? 1 : 0;
03748 
03749    peer = find_peer(a->argv[3], load_realtime);
03750    if (peer) {
03751       struct sockaddr_in peer_addr;
03752 
03753       ast_sockaddr_to_sin(&peer->addr, &peer_addr);
03754 
03755       encmethods_to_str(peer->encmethods, encmethods);
03756       ast_cli(a->fd, "\n\n");
03757       ast_cli(a->fd, "  * Name       : %s\n", peer->name);
03758       ast_cli(a->fd, "  Secret       : %s\n", ast_strlen_zero(peer->secret) ? "<Not set>" : "<Set>");
03759       ast_cli(a->fd, "  Context      : %s\n", peer->context);
03760       ast_cli(a->fd, "  Parking lot  : %s\n", peer->parkinglot);
03761       ast_cli(a->fd, "  Mailbox      : %s\n", peer->mailbox);
03762       ast_cli(a->fd, "  Dynamic      : %s\n", ast_test_flag64(peer, IAX_DYNAMIC) ? "Yes" : "No");
03763       ast_cli(a->fd, "  Callnum limit: %d\n", peer->maxcallno);
03764       ast_cli(a->fd, "  Calltoken req: %s\n", (peer->calltoken_required == CALLTOKEN_YES) ? "Yes" : ((peer->calltoken_required == CALLTOKEN_AUTO) ? "Auto" : "No"));
03765       ast_cli(a->fd, "  Trunk        : %s\n", ast_test_flag64(peer, IAX_TRUNK) ? "Yes" : "No");
03766       ast_cli(a->fd, "  Encryption   : %s\n", peer->encmethods ? ast_str_buffer(encmethods) : "No");
03767       ast_cli(a->fd, "  Callerid     : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, "<unspecified>"));
03768       ast_cli(a->fd, "  Expire       : %d\n", peer->expire);
03769       ast_cli(a->fd, "  ACL          : %s\n", (peer->ha ? "Yes" : "No"));
03770       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));
03771       ast_cli(a->fd, "  Defaddr->IP  : %s Port %d\n", ast_inet_ntoa(peer->defaddr.sin_addr), ntohs(peer->defaddr.sin_port));
03772       ast_cli(a->fd, "  Username     : %s\n", peer->username);
03773       ast_cli(a->fd, "  Codecs       : ");
03774       ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, peer->capability);
03775       ast_cli(a->fd, "%s\n", codec_buf);
03776 
03777       ast_cli(a->fd, "  Codec Order  : (");
03778       for(x = 0; x < 32 ; x++) {
03779          codec = ast_codec_pref_index(&peer->prefs,x);
03780          if(!codec)
03781             break;
03782          ast_cli(a->fd, "%s", ast_getformatname(codec));
03783          if(x < 31 && ast_codec_pref_index(&peer->prefs,x+1))
03784             ast_cli(a->fd, "|");
03785       }
03786 
03787       if (!x)
03788          ast_cli(a->fd, "none");
03789       ast_cli(a->fd, ")\n");
03790 
03791       ast_cli(a->fd, "  Status       : ");
03792       peer_status(peer, status, sizeof(status));   
03793       ast_cli(a->fd, "%s\n",status);
03794       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");
03795       ast_cli(a->fd, "\n");
03796       peer_unref(peer);
03797    } else {
03798       ast_cli(a->fd, "Peer %s not found.\n", a->argv[3]);
03799       ast_cli(a->fd, "\n");
03800    }
03801 
03802    return CLI_SUCCESS;
03803 }
03804 
03805 static char *complete_iax2_peers(const char *line, const char *word, int pos, int state, uint64_t flags)
03806 {
03807    int which = 0;
03808    struct iax2_peer *peer;
03809    char *res = NULL;
03810    int wordlen = strlen(word);
03811    struct ao2_iterator i;
03812 
03813    i = ao2_iterator_init(peers, 0);
03814    while ((peer = ao2_iterator_next(&i))) {
03815       if (!strncasecmp(peer->name, word, wordlen) && ++which > state
03816          && (!flags || ast_test_flag64(peer, flags))) {
03817          res = ast_strdup(peer->name);
03818          peer_unref(peer);
03819          break;
03820       }
03821       peer_unref(peer);
03822    }
03823    ao2_iterator_destroy(&i);
03824 
03825    return res;
03826 }
03827 
03828 static char *handle_cli_iax2_show_stats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
03829 {
03830    struct iax_frame *cur;
03831    int cnt = 0, dead = 0, final = 0, i = 0;
03832 
03833    switch (cmd) {
03834    case CLI_INIT:
03835       e->command = "iax2 show stats";
03836       e->usage =
03837          "Usage: iax2 show stats\n"
03838          "       Display statistics on IAX channel driver.\n";
03839       return NULL;
03840    case CLI_GENERATE:
03841       return NULL;
03842    }
03843 
03844    if (a->argc != 3)
03845       return CLI_SHOWUSAGE;
03846 
03847    for (i = 0; i < ARRAY_LEN(frame_queue); i++) {
03848       ast_mutex_lock(&iaxsl[i]);
03849       AST_LIST_TRAVERSE(&frame_queue[i], cur, list) {
03850          if (cur->retries < 0)
03851             dead++;
03852          if (cur->final)
03853             final++;
03854          cnt++;
03855       }
03856       ast_mutex_unlock(&iaxsl[i]);
03857    }
03858 
03859    ast_cli(a->fd, "    IAX Statistics\n");
03860    ast_cli(a->fd, "---------------------\n");
03861    ast_cli(a->fd, "Outstanding frames: %d (%d ingress, %d egress)\n", iax_get_frames(), iax_get_iframes(), iax_get_oframes());
03862    ast_cli(a->fd, "%d timed and %d untimed transmits; MTU %d/%d/%d\n", trunk_timed, trunk_untimed,
03863       trunk_maxmtu, trunk_nmaxmtu, global_max_trunk_mtu);
03864    ast_cli(a->fd, "Packets in transmit queue: %d dead, %d final, %d total\n\n", dead, final, cnt);
03865 
03866    trunk_timed = trunk_untimed = 0;
03867    if (trunk_maxmtu > trunk_nmaxmtu)
03868       trunk_nmaxmtu = trunk_maxmtu;
03869 
03870    return CLI_SUCCESS;
03871 }
03872 
03873 /*! \brief Set trunk MTU from CLI */
03874 static char *handle_cli_iax2_set_mtu(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
03875 {
03876    int mtuv;
03877 
03878    switch (cmd) {
03879    case CLI_INIT:
03880       e->command = "iax2 set mtu";
03881       e->usage =
03882          "Usage: iax2 set mtu <value>\n"
03883          "       Set the system-wide IAX IP mtu to <value> bytes net or\n"
03884          "       zero to disable. Disabling means that the operating system\n"
03885          "       must handle fragmentation of UDP packets when the IAX2 trunk\n"
03886          "       packet exceeds the UDP payload size. This is substantially\n"
03887          "       below the IP mtu. Try 1240 on ethernets. Must be 172 or\n"
03888          "       greater for G.711 samples.\n";
03889       return NULL;
03890    case CLI_GENERATE:
03891       return NULL;
03892    }
03893 
03894    if (a->argc != 4)
03895       return CLI_SHOWUSAGE; 
03896    if (strncasecmp(a->argv[3], "default", strlen(a->argv[3])) == 0)
03897       mtuv = MAX_TRUNK_MTU;
03898    else
03899       mtuv = atoi(a->argv[3]);
03900 
03901    if (mtuv == 0) {
03902       ast_cli(a->fd, "Trunk MTU control disabled (mtu was %d)\n", global_max_trunk_mtu); 
03903       global_max_trunk_mtu = 0; 
03904       return CLI_SUCCESS; 
03905    }
03906    if (mtuv < 172 || mtuv > 4000) {
03907       ast_cli(a->fd, "Trunk MTU must be between 172 and 4000\n"); 
03908       return CLI_SHOWUSAGE; 
03909    }
03910    ast_cli(a->fd, "Trunk MTU changed from %d to %d\n", global_max_trunk_mtu, mtuv); 
03911    global_max_trunk_mtu = mtuv; 
03912    return CLI_SUCCESS;
03913 }
03914 
03915 static char *handle_cli_iax2_show_cache(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
03916 {
03917    struct iax2_dpcache *dp = NULL;
03918    char tmp[1024], *pc = NULL;
03919    int s, x, y;
03920    struct timeval now = ast_tvnow();
03921 
03922    switch (cmd) {
03923    case CLI_INIT:
03924       e->command = "iax2 show cache";
03925       e->usage =
03926          "Usage: iax2 show cache\n"
03927          "       Display currently cached IAX Dialplan results.\n";
03928       return NULL;
03929    case CLI_GENERATE:
03930       return NULL;
03931    }
03932 
03933    AST_LIST_LOCK(&dpcache);
03934 
03935    ast_cli(a->fd, "%-20.20s %-12.12s %-9.9s %-8.8s %s\n", "Peer/Context", "Exten", "Exp.", "Wait.", "Flags");
03936 
03937    AST_LIST_TRAVERSE(&dpcache, dp, cache_list) {
03938       s = dp->expiry.tv_sec - now.tv_sec;
03939       tmp[0] = '\0';
03940       if (dp->flags & CACHE_FLAG_EXISTS)
03941          strncat(tmp, "EXISTS|", sizeof(tmp) - strlen(tmp) - 1);
03942       if (dp->flags & CACHE_FLAG_NONEXISTENT)
03943          strncat(tmp, "NONEXISTENT|", sizeof(tmp) - strlen(tmp) - 1);
03944       if (dp->flags & CACHE_FLAG_CANEXIST)
03945          strncat(tmp, "CANEXIST|", sizeof(tmp) - strlen(tmp) - 1);
03946       if (dp->flags & CACHE_FLAG_PENDING)
03947          strncat(tmp, "PENDING|", sizeof(tmp) - strlen(tmp) - 1);
03948       if (dp->flags & CACHE_FLAG_TIMEOUT)
03949          strncat(tmp, "TIMEOUT|", sizeof(tmp) - strlen(tmp) - 1);
03950       if (dp->flags & CACHE_FLAG_TRANSMITTED)
03951          strncat(tmp, "TRANSMITTED|", sizeof(tmp) - strlen(tmp) - 1);
03952       if (dp->flags & CACHE_FLAG_MATCHMORE)
03953          strncat(tmp, "MATCHMORE|", sizeof(tmp) - strlen(tmp) - 1);
03954       if (dp->flags & CACHE_FLAG_UNKNOWN)
03955          strncat(tmp, "UNKNOWN|", sizeof(tmp) - strlen(tmp) - 1);
03956       /* Trim trailing pipe */
03957       if (!ast_strlen_zero(tmp)) {
03958          tmp[strlen(tmp) - 1] = '\0';
03959       } else {
03960          ast_copy_string(tmp, "(none)", sizeof(tmp));
03961       }
03962       y = 0;
03963       pc = strchr(dp->peercontext, '@');
03964       if (!pc) {
03965          pc = dp->peercontext;
03966       } else {
03967          pc++;
03968       }
03969       for (x = 0; x < ARRAY_LEN(dp->waiters); x++) {
03970          if (dp->waiters[x] > -1)
03971             y++;
03972       }
03973       if (s > 0) {
03974          ast_cli(a->fd, "%-20.20s %-12.12s %-9d %-8d %s\n", pc, dp->exten, s, y, tmp);
03975       } else {
03976          ast_cli(a->fd, "%-20.20s %-12.12s %-9.9s %-8d %s\n", pc, dp->exten, "(expired)", y, tmp);
03977       }
03978    }
03979 
03980    AST_LIST_UNLOCK(&dpcache);
03981 
03982    return CLI_SUCCESS;
03983 }
03984 
03985 static unsigned int calc_rxstamp(struct chan_iax2_pvt *p, unsigned int offset);
03986 
03987 static void unwrap_timestamp(struct iax_frame *fr)
03988 {
03989    /* Video mini frames only encode the lower 15 bits of the session
03990     * timestamp, but other frame types (e.g. audio) encode 16 bits. */
03991    const int ts_shift = (fr->af.frametype == AST_FRAME_VIDEO) ? 15 : 16;
03992    const int lower_mask = (1 << ts_shift) - 1;
03993    const int upper_mask = ~lower_mask;
03994    const int last_upper = iaxs[fr->callno]->last & upper_mask;
03995 
03996    if ( (fr->ts & upper_mask) == last_upper ) {
03997       const int x = fr->ts - iaxs[fr->callno]->last;
03998       const int threshold = (ts_shift == 15) ? 25000 : 50000;
03999 
04000       if (x < -threshold) {
04001          /* Sudden big jump backwards in timestamp:
04002             What likely happened here is that miniframe timestamp has circled but we haven't
04003             gotten the update from the main packet.  We'll just pretend that we did, and
04004             update the timestamp appropriately. */
04005          fr->ts = (last_upper + (1 << ts_shift)) | (fr->ts & lower_mask);
04006          if (iaxdebug)
04007             ast_debug(1, "schedule_delivery: pushed forward timestamp\n");
04008       } else if (x > threshold) {
04009          /* Sudden apparent big jump forwards in timestamp:
04010             What's likely happened is this is an old miniframe belonging to the previous
04011             top 15 or 16-bit timestamp that has turned up out of order.
04012             Adjust the timestamp appropriately. */
04013          fr->ts = (last_upper - (1 << ts_shift)) | (fr->ts & lower_mask);
04014          if (iaxdebug)
04015             ast_debug(1, "schedule_delivery: pushed back timestamp\n");
04016       }
04017    }
04018 }
04019 
04020 static int get_from_jb(const void *p);
04021 
04022 static void update_jbsched(struct chan_iax2_pvt *pvt)
04023 {
04024    int when;
04025    
04026    when = ast_tvdiff_ms(ast_tvnow(), pvt->rxcore);
04027    
04028    when = jb_next(pvt->jb) - when;
04029 
04030    if (when <= 0) {
04031       /* XXX should really just empty until when > 0.. */
04032       when = 1;
04033    }
04034    
04035    pvt->jbid = iax2_sched_replace(pvt->jbid, sched, when, get_from_jb, 
04036       CALLNO_TO_PTR(pvt->callno));
04037 }
04038 
04039 static void __get_from_jb(const void *p) 
04040 {
04041    int callno = PTR_TO_CALLNO(p);
04042    struct chan_iax2_pvt *pvt = NULL;
04043    struct iax_frame *fr;
04044    jb_frame frame;
04045    int ret;
04046    long ms;
04047    long next;
04048    struct timeval now = ast_tvnow();
04049    
04050    /* Make sure we have a valid private structure before going on */
04051    ast_mutex_lock(&iaxsl[callno]);
04052    pvt = iaxs[callno];
04053    if (!pvt) {
04054       /* No go! */
04055       ast_mutex_unlock(&iaxsl[callno]);
04056       return;
04057    }
04058 
04059    pvt->jbid = -1;
04060    
04061    /* round up a millisecond since ast_sched_runq does; */
04062    /* prevents us from spinning while waiting for our now */
04063    /* to catch up with runq's now */
04064    now.tv_usec += 1000;
04065    
04066    ms = ast_tvdiff_ms(now, pvt->rxcore);
04067    
04068    if(ms >= (next = jb_next(pvt->jb))) {
04069       ret = jb_get(pvt->jb,&frame,ms,ast_codec_interp_len(pvt->voiceformat));
04070       switch(ret) {
04071       case JB_OK:
04072          fr = frame.data;
04073          __do_deliver(fr);
04074          /* __do_deliver() can cause the call to disappear */
04075          pvt = iaxs[callno];
04076          break;
04077       case JB_INTERP:
04078       {
04079          struct ast_frame af = { 0, };
04080          
04081          /* create an interpolation frame */
04082          af.frametype = AST_FRAME_VOICE;
04083          af.subclass.codec = pvt->voiceformat;
04084          af.samples  = frame.ms * (ast_format_rate(pvt->voiceformat) / 1000);
04085          af.src  = "IAX2 JB interpolation";
04086          af.delivery = ast_tvadd(pvt->rxcore, ast_samp2tv(next, 1000));
04087          af.offset = AST_FRIENDLY_OFFSET;
04088          
04089          /* queue the frame:  For consistency, we would call __do_deliver here, but __do_deliver wants an iax_frame,
04090           * which we'd need to malloc, and then it would free it.  That seems like a drag */
04091          if (!ast_test_flag64(iaxs[callno], IAX_ALREADYGONE)) {
04092             iax2_queue_frame(callno, &af);
04093             /* iax2_queue_frame() could cause the call to disappear */
04094             pvt = iaxs[callno];
04095          }
04096       }
04097          break;
04098       case JB_DROP:
04099          iax2_frame_free(frame.data);
04100          break;
04101       case JB_NOFRAME:
04102       case JB_EMPTY:
04103          /* do nothing */
04104          break;
04105       default:
04106          /* shouldn't happen */
04107          break;
04108       }
04109    }
04110    if (pvt)
04111       update_jbsched(pvt);
04112    ast_mutex_unlock(&iaxsl[callno]);
04113 }
04114 
04115 static int get_from_jb(const void *data)
04116 {
04117 #ifdef SCHED_MULTITHREADED
04118    if (schedule_action(__get_from_jb, data))
04119 #endif      
04120       __get_from_jb(data);
04121    return 0;
04122 }
04123 
04124 /*!
04125  * \note This function assumes fr->callno is locked
04126  *
04127  * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
04128  * was valid before calling it, it may no longer be valid after calling it.
04129  */
04130 static int schedule_delivery(struct iax_frame *fr, int updatehistory, int fromtrunk, unsigned int *tsout)
04131 {
04132    int type, len;
04133    int ret;
04134    int needfree = 0;
04135    struct ast_channel *owner = NULL;
04136    struct ast_channel *bridge = NULL;
04137    
04138    /* Attempt to recover wrapped timestamps */
04139    unwrap_timestamp(fr);
04140 
04141    /* delivery time is sender's sent timestamp converted back into absolute time according to our clock */
04142    if ( !fromtrunk && !ast_tvzero(iaxs[fr->callno]->rxcore))
04143       fr->af.delivery = ast_tvadd(iaxs[fr->callno]->rxcore, ast_samp2tv(fr->ts, 1000));
04144    else {
04145 #if 0
04146       ast_debug(1, "schedule_delivery: set delivery to 0 as we don't have an rxcore yet, or frame is from trunk.\n");
04147 #endif
04148       fr->af.delivery = ast_tv(0,0);
04149    }
04150 
04151    type = JB_TYPE_CONTROL;
04152    len = 0;
04153 
04154    if(fr->af.frametype == AST_FRAME_VOICE) {
04155       type = JB_TYPE_VOICE;
04156       len = ast_codec_get_samples(&fr->af) / (ast_format_rate(fr->af.subclass.codec) / 1000);
04157    } else if(fr->af.frametype == AST_FRAME_CNG) {
04158       type = JB_TYPE_SILENCE;
04159    }
04160 
04161    if ( (!ast_test_flag64(iaxs[fr->callno], IAX_USEJITTERBUF)) ) {
04162       if (tsout)
04163          *tsout = fr->ts;
04164       __do_deliver(fr);
04165       return -1;
04166    }
04167 
04168    iax2_lock_owner(fr->callno);
04169    if (!iaxs[fr->callno]) {
04170       /* The call dissappeared so discard this frame that we could not send. */
04171       iax2_frame_free(fr);
04172       return -1;
04173    }
04174    if ((owner = iaxs[fr->callno]->owner))
04175       bridge = ast_bridged_channel(owner);
04176 
04177    /* if the user hasn't requested we force the use of the jitterbuffer, and we're bridged to
04178     * a channel that can accept jitter, then flush and suspend the jb, and send this frame straight through */
04179    if ( (!ast_test_flag64(iaxs[fr->callno], IAX_FORCEJITTERBUF)) && owner && bridge && (bridge->tech->properties & AST_CHAN_TP_WANTSJITTER) ) {
04180       jb_frame frame;
04181 
04182       ast_channel_unlock(owner);
04183 
04184       /* deliver any frames in the jb */
04185       while (jb_getall(iaxs[fr->callno]->jb, &frame) == JB_OK) {
04186          __do_deliver(frame.data);
04187          /* __do_deliver() can make the call disappear */
04188          if (!iaxs[fr->callno])
04189             return -1;
04190       }
04191 
04192       jb_reset(iaxs[fr->callno]->jb);
04193 
04194       ast_sched_thread_del(sched, iaxs[fr->callno]->jbid);
04195 
04196       /* deliver this frame now */
04197       if (tsout)
04198          *tsout = fr->ts;
04199       __do_deliver(fr);
04200       return -1;
04201    }
04202    if (owner) {
04203       ast_channel_unlock(owner);
04204    }
04205 
04206    /* insert into jitterbuffer */
04207    /* TODO: Perhaps we could act immediately if it's not droppable and late */
04208    ret = jb_put(iaxs[fr->callno]->jb, fr, type, len, fr->ts,
04209          calc_rxstamp(iaxs[fr->callno],fr->ts));
04210    if (ret == JB_DROP) {
04211       needfree++;
04212    } else if (ret == JB_SCHED) {
04213       update_jbsched(iaxs[fr->callno]);
04214    }
04215    if (tsout)
04216       *tsout = fr->ts;
04217    if (needfree) {
04218       /* Free our iax frame */
04219       iax2_frame_free(fr);
04220       return -1;
04221    }
04222    return 0;
04223 }
04224 
04225 static int transmit_frame(void *data)
04226 {
04227    struct iax_frame *fr = data;
04228 
04229    ast_mutex_lock(&iaxsl[fr->callno]);
04230 
04231    fr->sentyet = 1;
04232 
04233    if (iaxs[fr->callno]) {
04234       send_packet(fr);
04235    }
04236 
04237    if (fr->retries < 0) {
04238       ast_mutex_unlock(&iaxsl[fr->callno]);
04239       /* No retransmit requested */
04240       iax_frame_free(fr);
04241    } else {
04242       /* We need reliable delivery.  Schedule a retransmission */
04243       AST_LIST_INSERT_TAIL(&frame_queue[fr->callno], fr, list);
04244       fr->retries++;
04245       fr->retrans = iax2_sched_add(sched, fr->retrytime, attempt_transmit, fr);
04246       ast_mutex_unlock(&iaxsl[fr->callno]);
04247    }
04248 
04249    return 0;
04250 }
04251 
04252 static int iax2_transmit(struct iax_frame *fr)
04253 {
04254    fr->sentyet = 0;
04255 
04256    return ast_taskprocessor_push(transmit_processor, transmit_frame, fr);
04257 }
04258 
04259 static int iax2_digit_begin(struct ast_channel *c, char digit)
04260 {
04261    return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_DTMF_BEGIN, digit, 0, NULL, 0, -1);
04262 }
04263 
04264 static int iax2_digit_end(struct ast_channel *c, char digit, unsigned int duration)
04265 {
04266    return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_DTMF_END, digit, 0, NULL, 0, -1);
04267 }
04268 
04269 static int iax2_sendtext(struct ast_channel *c, const char *text)
04270 {
04271    
04272    return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_TEXT,
04273       0, 0, (unsigned char *)text, strlen(text) + 1, -1);
04274 }
04275 
04276 static int iax2_sendimage(struct ast_channel *c, struct ast_frame *img)
04277 {
04278    return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_IMAGE, img->subclass.integer, 0, img->data.ptr, img->datalen, -1);
04279 }
04280 
04281 static int iax2_sendhtml(struct ast_channel *c, int subclass, const char *data, int datalen)
04282 {
04283    return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_HTML, subclass, 0, (unsigned char *)data, datalen, -1);
04284 }
04285 
04286 static int iax2_fixup(struct ast_channel *oldchannel, struct ast_channel *newchan)
04287 {
04288    unsigned short callno = PTR_TO_CALLNO(newchan->tech_pvt);
04289    ast_mutex_lock(&iaxsl[callno]);
04290    if (iaxs[callno])
04291       iaxs[callno]->owner = newchan;
04292    else
04293       ast_log(LOG_WARNING, "Uh, this isn't a good sign...\n");
04294    ast_mutex_unlock(&iaxsl[callno]);
04295    return 0;
04296 }
04297 
04298 /*!
04299  * \note This function calls reg_source_db -> iax2_poke_peer -> find_callno,
04300  *       so do not call this with a pvt lock held.
04301  */
04302 static struct iax2_peer *realtime_peer(const char *peername, struct sockaddr_in *sin)
04303 {
04304    struct ast_variable *var = NULL;
04305    struct ast_variable *tmp;
04306    struct iax2_peer *peer=NULL;
04307    time_t regseconds = 0, nowtime;
04308    int dynamic=0;
04309 
04310    if (peername) {
04311       var = ast_load_realtime("iaxpeers", "name", peername, "host", "dynamic", SENTINEL);
04312       if (!var && sin)
04313          var = ast_load_realtime("iaxpeers", "name", peername, "host", ast_inet_ntoa(sin->sin_addr), SENTINEL);
04314    } else if (sin) {
04315       char porta[25];
04316       sprintf(porta, "%d", ntohs(sin->sin_port));
04317       var = ast_load_realtime("iaxpeers", "ipaddr", ast_inet_ntoa(sin->sin_addr), "port", porta, SENTINEL);
04318       if (var) {
04319          /* We'll need the peer name in order to build the structure! */
04320          for (tmp = var; tmp; tmp = tmp->next) {
04321             if (!strcasecmp(tmp->name, "name"))
04322                peername = tmp->value;
04323          }
04324       }
04325    }
04326    if (!var && peername) { /* Last ditch effort */
04327       var = ast_load_realtime("iaxpeers", "name", peername, SENTINEL);
04328       /*!\note
04329        * If this one loaded something, then we need to ensure that the host
04330        * field matched.  The only reason why we can't have this as a criteria
04331        * is because we only have the IP address and the host field might be
04332        * set as a name (and the reverse PTR might not match).
04333        */
04334       if (var && sin) {
04335          for (tmp = var; tmp; tmp = tmp->next) {
04336             if (!strcasecmp(tmp->name, "host")) {
04337                struct ast_hostent ahp;
04338                struct hostent *hp;
04339                if (!(hp = ast_gethostbyname(tmp->value, &ahp)) || (memcmp(hp->h_addr, &sin->sin_addr, sizeof(hp->h_addr)))) {
04340                   /* No match */
04341                   ast_variables_destroy(var);
04342                   var = NULL;
04343                }
04344                break;
04345             }
04346          }
04347       }
04348    }
04349    if (!var)
04350       return NULL;
04351 
04352    peer = build_peer(peername, var, NULL, ast_test_flag64((&globalflags), IAX_RTCACHEFRIENDS) ? 0 : 1);
04353 
04354    if (!peer) {
04355       ast_variables_destroy(var);
04356       return NULL;
04357    }
04358 
04359    for (tmp = var; tmp; tmp = tmp->next) {
04360       /* Make sure it's not a user only... */
04361       if (!strcasecmp(tmp->name, "type")) {
04362          if (strcasecmp(tmp->value, "friend") &&
04363              strcasecmp(tmp->value, "peer")) {
04364             /* Whoops, we weren't supposed to exist! */
04365             peer = peer_unref(peer);
04366             break;
04367          } 
04368       } else if (!strcasecmp(tmp->name, "regseconds")) {
04369          ast_get_time_t(tmp->value, &regseconds, 0, NULL);
04370       } else if (!strcasecmp(tmp->name, "ipaddr")) {
04371          ast_sockaddr_parse(&peer->addr, tmp->value, PARSE_PORT_IGNORE);
04372       } else if (!strcasecmp(tmp->name, "port")) {
04373          ast_sockaddr_set_port(&peer->addr, atoi(tmp->value));
04374       } else if (!strcasecmp(tmp->name, "host")) {
04375          if (!strcasecmp(tmp->value, "dynamic"))
04376             dynamic = 1;
04377       }
04378    }
04379 
04380    ast_variables_destroy(var);
04381 
04382    if (!peer)
04383       return NULL;
04384 
04385    if (ast_test_flag64((&globalflags), IAX_RTCACHEFRIENDS)) {
04386       ast_copy_flags64(peer, &globalflags, IAX_RTAUTOCLEAR|IAX_RTCACHEFRIENDS);
04387       if (ast_test_flag64(peer, IAX_RTAUTOCLEAR)) {
04388          if (peer->expire > -1) {
04389             if (!ast_sched_thread_del(sched, peer->expire)) {
04390                peer->expire = -1;
04391                peer_unref(peer);
04392             }
04393          }
04394          peer->expire = iax2_sched_add(sched, (global_rtautoclear) * 1000, expire_registry, peer_ref(peer));
04395          if (peer->expire == -1)
04396             peer_unref(peer);
04397       }
04398       ao2_link(peers, peer);
04399       if (ast_test_flag64(peer, IAX_DYNAMIC))
04400          reg_source_db(peer);
04401    } else {
04402       ast_set_flag64(peer, IAX_TEMPONLY);
04403    }
04404 
04405    if (!ast_test_flag64(&globalflags, IAX_RTIGNOREREGEXPIRE) && dynamic) {
04406       time(&nowtime);
04407       if ((nowtime - regseconds) > IAX_DEFAULT_REG_EXPIRE) {
04408          memset(&peer->addr, 0, sizeof(peer->addr));
04409          realtime_update_peer(peer->name, &peer->addr, 0);
04410          ast_debug(1, "realtime_peer: Bah, '%s' is expired (%d/%d/%d)!\n",
04411             peername, (int)(nowtime - regseconds), (int)regseconds, (int)nowtime);
04412       }
04413       else {
04414          ast_debug(1, "realtime_peer: Registration for '%s' still active (%d/%d/%d)!\n",
04415             peername, (int)(nowtime - regseconds), (int)regseconds, (int)nowtime);
04416       }
04417    }
04418 
04419    return peer;
04420 }
04421 
04422 static struct iax2_user *realtime_user(const char *username, struct sockaddr_in *sin)
04423 {
04424    struct ast_variable *var;
04425    struct ast_variable *tmp;
04426    struct iax2_user *user=NULL;
04427 
04428    var = ast_load_realtime("iaxusers", "name", username, "host", "dynamic", SENTINEL);
04429    if (!var)
04430       var = ast_load_realtime("iaxusers", "name", username, "host", ast_inet_ntoa(sin->sin_addr), SENTINEL);
04431    if (!var && sin) {
04432       char porta[6];
04433       snprintf(porta, sizeof(porta), "%d", ntohs(sin->sin_port));
04434       var = ast_load_realtime("iaxusers", "name", username, "ipaddr", ast_inet_ntoa(sin->sin_addr), "port", porta, SENTINEL);
04435       if (!var)
04436          var = ast_load_realtime("iaxusers", "ipaddr", ast_inet_ntoa(sin->sin_addr), "port", porta, SENTINEL);
04437    }
04438    if (!var) { /* Last ditch effort */
04439       var = ast_load_realtime("iaxusers", "name", username, SENTINEL);
04440       /*!\note
04441        * If this one loaded something, then we need to ensure that the host
04442        * field matched.  The only reason why we can't have this as a criteria
04443        * is because we only have the IP address and the host field might be
04444        * set as a name (and the reverse PTR might not match).
04445        */
04446       if (var) {
04447          for (tmp = var; tmp; tmp = tmp->next) {
04448             if (!strcasecmp(tmp->name, "host")) {
04449                struct ast_hostent ahp;
04450                struct hostent *hp;
04451                if (!(hp = ast_gethostbyname(tmp->value, &ahp)) || (memcmp(hp->h_addr, &sin->sin_addr, sizeof(hp->h_addr)))) {
04452                   /* No match */
04453                   ast_variables_destroy(var);
04454                   var = NULL;
04455                }
04456                break;
04457             }
04458          }
04459       }
04460    }
04461    if (!var)
04462       return NULL;
04463 
04464    tmp = var;
04465    while(tmp) {
04466       /* Make sure it's not a peer only... */
04467       if (!strcasecmp(tmp->name, "type")) {
04468          if (strcasecmp(tmp->value, "friend") &&
04469              strcasecmp(tmp->value, "user")) {
04470             return NULL;
04471          } 
04472       }
04473       tmp = tmp->next;
04474    }
04475 
04476    user = build_user(username, var, NULL, !ast_test_flag64((&globalflags), IAX_RTCACHEFRIENDS));
04477 
04478    ast_variables_destroy(var);
04479 
04480    if (!user)
04481       return NULL;
04482 
04483    if (ast_test_flag64((&globalflags), IAX_RTCACHEFRIENDS)) {
04484       ast_set_flag64(user, IAX_RTCACHEFRIENDS);
04485       ao2_link(users, user);
04486    } else {
04487       ast_set_flag64(user, IAX_TEMPONLY);
04488    }
04489 
04490    return user;
04491 }
04492 
04493 static void realtime_update_peer(const char *peername, struct ast_sockaddr *sockaddr, time_t regtime)
04494 {
04495    char port[10];
04496    char regseconds[20];
04497    const char *sysname = ast_config_AST_SYSTEM_NAME;
04498    char *syslabel = NULL;
04499 
04500    if (ast_strlen_zero(sysname)) /* No system name, disable this */
04501       sysname = NULL;
04502    else if (ast_test_flag64(&globalflags, IAX_RTSAVE_SYSNAME))
04503       syslabel = "regserver";
04504 
04505    snprintf(regseconds, sizeof(regseconds), "%d", (int)regtime);
04506    snprintf(port, sizeof(port), "%d", ast_sockaddr_port(sockaddr));
04507    ast_update_realtime("iaxpeers", "name", peername, 
04508       "ipaddr", ast_sockaddr_stringify_addr(sockaddr), "port", port, 
04509       "regseconds", regseconds, syslabel, sysname, SENTINEL); /* note syslable can be NULL */
04510 }
04511 
04512 struct create_addr_info {
04513    format_t capability;
04514    uint64_t flags;
04515    int maxtime;
04516    int encmethods;
04517    int found;
04518    int sockfd;
04519    int adsi;
04520    char username[80];
04521    char secret[80];
04522    char outkey[80];
04523    char timezone[80];
04524    char prefs[32];
04525    char cid_num[80];
04526    char cid_name[80];
04527    char context[AST_MAX_CONTEXT];
04528    char peercontext[AST_MAX_CONTEXT];
04529    char mohinterpret[MAX_MUSICCLASS];
04530    char mohsuggest[MAX_MUSICCLASS];
04531 };
04532 
04533 static int create_addr(const char *peername, struct ast_channel *c, struct sockaddr_in *sin, struct create_addr_info *cai)
04534 {
04535    struct iax2_peer *peer;
04536    int res = -1;
04537    struct ast_codec_pref ourprefs;
04538    struct sockaddr_in peer_addr;
04539 
04540    ast_clear_flag64(cai, IAX_SENDANI | IAX_TRUNK);
04541    cai->sockfd = defaultsockfd;
04542    cai->maxtime = 0;
04543    sin->sin_family = AF_INET;
04544 
04545    if (!(peer = find_peer(peername, 1))) {
04546       struct ast_sockaddr sin_tmp;
04547 
04548       cai->found = 0;
04549       sin_tmp.ss.ss_family = AF_INET;
04550       if (ast_get_ip_or_srv(&sin_tmp, peername, srvlookup ? "_iax._udp" : NULL)) {
04551          ast_log(LOG_WARNING, "No such host: %s\n", peername);
04552          return -1;
04553       }
04554       ast_sockaddr_to_sin(&sin_tmp, sin);
04555       sin->sin_port = htons(IAX_DEFAULT_PORTNO);
04556       /* use global iax prefs for unknown peer/user */
04557       /* But move the calling channel's native codec to the top of the preference list */
04558       memcpy(&ourprefs, &prefs, sizeof(ourprefs));
04559       if (c)
04560          ast_codec_pref_prepend(&ourprefs, c->nativeformats, 1);
04561       ast_codec_pref_convert(&ourprefs, cai->prefs, sizeof(cai->prefs), 1);
04562       return 0;
04563    }
04564 
04565    cai->found = 1;
04566 
04567    ast_sockaddr_to_sin(&peer->addr, &peer_addr);
04568 
04569    /* if the peer has no address (current or default), return failure */
04570    if (!(peer_addr.sin_addr.s_addr || peer->defaddr.sin_addr.s_addr)) {
04571       goto return_unref;
04572    }
04573 
04574    /* if the peer is being monitored and is currently unreachable, return failure */
04575    if (peer->maxms && ((peer->lastms > peer->maxms) || (peer->lastms < 0)))
04576       goto return_unref;
04577 
04578    ast_copy_flags64(cai, peer, IAX_SENDANI | IAX_TRUNK | IAX_NOTRANSFER | IAX_TRANSFERMEDIA | IAX_USEJITTERBUF | IAX_FORCEJITTERBUF | IAX_SENDCONNECTEDLINE | IAX_RECVCONNECTEDLINE | IAX_FORCE_ENCRYPT);
04579    cai->maxtime = peer->maxms;
04580    cai->capability = peer->capability;
04581    cai->encmethods = peer->encmethods;
04582    cai->sockfd = peer->sockfd;
04583    cai->adsi = peer->adsi;
04584    memcpy(&ourprefs, &peer->prefs, sizeof(ourprefs));
04585    /* Move the calling channel's native codec to the top of the preference list */
04586    if (c) {
04587       ast_debug(1, "prepending %llx to prefs\n", (unsigned long long) c->nativeformats);
04588       ast_codec_pref_prepend(&ourprefs, c->nativeformats, 1);
04589    }
04590    ast_codec_pref_convert(&ourprefs, cai->prefs, sizeof(cai->prefs), 1);
04591    ast_copy_string(cai->context, peer->context, sizeof(cai->context));
04592    ast_copy_string(cai->peercontext, peer->peercontext, sizeof(cai->peercontext));
04593    ast_copy_string(cai->username, peer->username, sizeof(cai->username));
04594    ast_copy_string(cai->timezone, peer->zonetag, sizeof(cai->timezone));
04595    ast_copy_string(cai->outkey, peer->outkey, sizeof(cai->outkey));
04596    ast_copy_string(cai->cid_num, peer->cid_num, sizeof(cai->cid_num));
04597    ast_copy_string(cai->cid_name, peer->cid_name, sizeof(cai->cid_name));
04598    ast_copy_string(cai->mohinterpret, peer->mohinterpret, sizeof(cai->mohinterpret));
04599    ast_copy_string(cai->mohsuggest, peer->mohsuggest, sizeof(cai->mohsuggest));
04600    if (ast_strlen_zero(peer->dbsecret)) {
04601       ast_copy_string(cai->secret, peer->secret, sizeof(cai->secret));
04602    } else {
04603       char *family;
04604       char *key = NULL;
04605 
04606       family = ast_strdupa(peer->dbsecret);
04607       key = strchr(family, '/');
04608       if (key)
04609          *key++ = '\0';
04610       if (!key || ast_db_get(family, key, cai->secret, sizeof(cai->secret))) {
04611          ast_log(LOG_WARNING, "Unable to retrieve database password for family/key '%s'!\n", peer->dbsecret);
04612          goto return_unref;
04613       }
04614    }
04615 
04616    if (peer_addr.sin_addr.s_addr) {
04617       sin->sin_addr = peer_addr.sin_addr;
04618       sin->sin_port = peer_addr.sin_port;
04619    } else {
04620       sin->sin_addr = peer->defaddr.sin_addr;
04621       sin->sin_port = peer->defaddr.sin_port;
04622    }
04623 
04624    res = 0;
04625 
04626 return_unref:
04627    peer_unref(peer);
04628 
04629    return res;
04630 }
04631 
04632 static void __auto_congest(const void *nothing)
04633 {
04634    int callno = PTR_TO_CALLNO(nothing);
04635    struct ast_frame f = { AST_FRAME_CONTROL, { AST_CONTROL_CONGESTION } };
04636    ast_mutex_lock(&iaxsl[callno]);
04637    if (iaxs[callno]) {
04638       iaxs[callno]->initid = -1;
04639       iax2_queue_frame(callno, &f);
04640       ast_log(LOG_NOTICE, "Auto-congesting call due to slow response\n");
04641    }
04642    ast_mutex_unlock(&iaxsl[callno]);
04643 }
04644 
04645 static int auto_congest(const void *data)
04646 {
04647 #ifdef SCHED_MULTITHREADED
04648    if (schedule_action(__auto_congest, data))
04649 #endif      
04650       __auto_congest(data);
04651    return 0;
04652 }
04653 
04654 static unsigned int iax2_datetime(const char *tz)
04655 {
04656    struct timeval t = ast_tvnow();
04657    struct ast_tm tm;
04658    unsigned int tmp;
04659    ast_localtime(&t, &tm, ast_strlen_zero(tz) ? NULL : tz);
04660    tmp  = (tm.tm_sec >> 1) & 0x1f;        /* 5 bits of seconds */
04661    tmp |= (tm.tm_min & 0x3f) << 5;        /* 6 bits of minutes */
04662    tmp |= (tm.tm_hour & 0x1f) << 11;      /* 5 bits of hours */
04663    tmp |= (tm.tm_mday & 0x1f) << 16;      /* 5 bits of day of month */
04664    tmp |= ((tm.tm_mon + 1) & 0xf) << 21;     /* 4 bits of month */
04665    tmp |= ((tm.tm_year - 100) & 0x7f) << 25; /* 7 bits of year */
04666    return tmp;
04667 }
04668 
04669 struct parsed_dial_string {
04670    char *username;
04671    char *password;
04672    char *key;
04673    char *peer;
04674    char *port;
04675    char *exten;
04676    char *context;
04677    char *options;
04678 };
04679 
04680 static int send_apathetic_reply(unsigned short callno, unsigned short dcallno,
04681       struct sockaddr_in *sin, int command, int ts, unsigned char seqno,
04682       int sockfd, struct iax_ie_data *ied)
04683 {
04684    struct {
04685       struct ast_iax2_full_hdr f;
04686       struct iax_ie_data ied;
04687    } data;
04688    size_t size = sizeof(struct ast_iax2_full_hdr);
04689 
04690    if (ied) {
04691       size += ied->pos;
04692       memcpy(&data.ied, ied->buf, ied->pos);
04693    }
04694 
04695    data.f.scallno = htons(0x8000 | callno);
04696    data.f.dcallno = htons(dcallno);
04697    data.f.ts = htonl(ts);
04698    data.f.iseqno = seqno;
04699    data.f.oseqno = 0;
04700    data.f.type = AST_FRAME_IAX;
04701    data.f.csub = compress_subclass(command);
04702 
04703    return sendto(sockfd, &data, size, 0, (struct sockaddr *)sin, sizeof(*sin));
04704 }
04705 
04706 static void add_empty_calltoken_ie(struct chan_iax2_pvt *pvt, struct iax_ie_data *ied)
04707 {
04708    /* first make sure their are two empty bytes left in ied->buf */
04709    if (pvt && ied && (2 < ((int) sizeof(ied->buf) - ied->pos))) {
04710       ied->buf[ied->pos++] = IAX_IE_CALLTOKEN;  /* type */
04711       ied->buf[ied->pos++] = 0;   /* data size,  ZERO in this case */
04712       pvt->calltoken_ie_len = 2;
04713    }
04714 }
04715 
04716 static void resend_with_token(int callno, struct iax_frame *f, const char *newtoken)
04717 {
04718    struct chan_iax2_pvt *pvt = iaxs[callno];
04719    int frametype = f->af.frametype;
04720    int subclass = f->af.subclass.integer;
04721    struct {
04722       struct ast_iax2_full_hdr fh;
04723       struct iax_ie_data ied;
04724    } data = {
04725       .ied.buf = { 0 },
04726       .ied.pos = 0,
04727    };
04728    /* total len - header len gives us the frame's IE len */
04729    int ie_data_pos = f->datalen - sizeof(struct ast_iax2_full_hdr);
04730 
04731    if (!pvt) {
04732       return;  /* this should not be possible if called from socket_process() */
04733    }
04734 
04735    /* 
04736     * Check to make sure last frame sent is valid for call token resend
04737     * 1. Frame should _NOT_ be encrypted since it starts the IAX dialog 
04738     * 2. Frame should _NOT_ already have a destination callno
04739     * 3. Frame must be a valid iax_frame subclass capable of starting dialog
04740     * 4. Pvt must have a calltoken_ie_len which represents the number of
04741     *    bytes at the end of the frame used for the previous calltoken ie.
04742     * 5. Pvt's calltoken_ie_len must be _LESS_ than the total IE length
04743     * 6. Total length of f->data must be _LESS_ than size of our data struct
04744     *    because f->data must be able to fit within data. 
04745     */
04746    if (f->encmethods || f->dcallno || !iax2_allow_new(frametype, subclass, 0)
04747       || !pvt->calltoken_ie_len || (pvt->calltoken_ie_len > ie_data_pos) ||
04748       (f->datalen > sizeof(data))) {
04749 
04750       return;  /* ignore resend, token was not valid for the dialog */
04751    }
04752 
04753    /* token is valid
04754     * 1. Copy frame data over
04755     * 2. Redo calltoken IE, it will always be the last ie in the frame.
04756     *    NOTE: Having the ie always be last is not protocol specified,
04757     *    it is only an implementation choice.  Since we only expect the ie to
04758     *    be last for frames we have sent, this can no way be affected by
04759     *    another end point.
04760     * 3. Remove frame from queue
04761     * 4. Free old frame
04762     * 5. Clear previous seqnos
04763     * 6. Resend with CALLTOKEN ie.
04764     */
04765 
04766    /* ---1.--- */
04767    memcpy(&data, f->data, f->datalen);
04768    data.ied.pos = ie_data_pos;
04769 
04770    /* ---2.--- */
04771    /* move to the beginning of the calltoken ie so we can write over it */
04772    data.ied.pos -= pvt->calltoken_ie_len;
04773    iax_ie_append_str(&data.ied, IAX_IE_CALLTOKEN, newtoken);
04774 
04775    /* make sure to update token length incase it ever has to be stripped off again */
04776    pvt->calltoken_ie_len = data.ied.pos - ie_data_pos; /* new pos minus old pos tells how big token ie is */
04777 
04778    /* ---3.--- */
04779    AST_LIST_REMOVE(&frame_queue[callno], f, list);
04780 
04781    /* ---4.--- */
04782    iax2_frame_free(f);
04783 
04784    /* ---5.--- */
04785    pvt->oseqno = 0;
04786    pvt->rseqno = 0;
04787    pvt->iseqno = 0;
04788    pvt->aseqno = 0;
04789    if (pvt->peercallno) {
04790       remove_by_peercallno(pvt);
04791       pvt->peercallno = 0;
04792    }
04793 
04794    /* ---6.--- */
04795    send_command(pvt, AST_FRAME_IAX, subclass, 0, data.ied.buf, data.ied.pos, -1);
04796 }
04797 
04798 static void requirecalltoken_mark_auto(const char *name, int subclass)
04799 {
04800    struct iax2_user *user = NULL;
04801    struct iax2_peer *peer = NULL;
04802 
04803    if (ast_strlen_zero(name)) {
04804       return; /* no username given */
04805    }
04806 
04807    if ((subclass == IAX_COMMAND_NEW) && (user = find_user(name)) && (user->calltoken_required == CALLTOKEN_AUTO)) {
04808       user->calltoken_required = CALLTOKEN_YES;
04809    } else if ((subclass != IAX_COMMAND_NEW) && (peer = find_peer(name, 1)) && (peer->calltoken_required == CALLTOKEN_AUTO)) {
04810       peer->calltoken_required = CALLTOKEN_YES;
04811    }
04812 
04813    if (peer) {
04814       peer_unref(peer);
04815    }
04816    if (user) {
04817       user_unref(user);
04818    }
04819 }
04820 
04821 /*!
04822  * \internal
04823  *
04824  * \brief handles calltoken logic for a received iax_frame.
04825  * 
04826  * \note frametype must be AST_FRAME_IAX.
04827  * 
04828  * \note
04829  * Three different cases are possible here.
04830  * Case 1. An empty calltoken is provided. This means the client supports
04831  *         calltokens but has not yet received one from us.  In this case
04832  *         a full calltoken IE is created and sent in a calltoken fullframe.
04833  * Case 2. A full calltoken is received and must be checked for validity.
04834  * Case 3. No calltoken is received indicating that the client does not
04835  *         support calltokens.  In this case it is up to the configuration
04836  *         to decide how this should be handled (reject or permit without calltoken)
04837  */
04838 static int handle_call_token(struct ast_iax2_full_hdr *fh, struct iax_ies *ies,
04839       struct sockaddr_in *sin, int fd)
04840 {
04841 #define CALLTOKEN_HASH_FORMAT "%s%d%u%d"  /* address + port + ts + randomcalldata */
04842 #define CALLTOKEN_IE_FORMAT   "%u?%s"     /* time + ? + (40 char hash) */
04843    struct ast_str *buf = ast_str_alloca(256);
04844    time_t t = time(NULL);
04845    char hash[41]; /* 40 char sha1 hash */
04846    int subclass = uncompress_subclass(fh->csub);
04847 
04848    /* ----- Case 1 ----- */
04849    if (ies->calltoken && !ies->calltokendata) {  /* empty calltoken is provided, client supports calltokens */
04850       struct iax_ie_data ied = {
04851          .buf = { 0 },
04852          .pos = 0,
04853       };
04854 
04855       /* create the hash with their address data and our timestamp */
04856       ast_str_set(&buf, 0, CALLTOKEN_HASH_FORMAT, ast_inet_ntoa(sin->sin_addr), sin->sin_port, (unsigned int) t, randomcalltokendata);
04857       ast_sha1_hash(hash, ast_str_buffer(buf));
04858 
04859       ast_str_set(&buf, 0, CALLTOKEN_IE_FORMAT, (unsigned int) t, hash);
04860       iax_ie_append_str(&ied, IAX_IE_CALLTOKEN, ast_str_buffer(buf));
04861       send_apathetic_reply(1, ntohs(fh->scallno), sin, IAX_COMMAND_CALLTOKEN, ntohl(fh->ts), fh->iseqno + 1, fd, &ied);
04862 
04863       return 1;
04864 
04865    /* ----- Case 2 ----- */
04866    } else if (ies->calltoken && ies->calltokendata) { /* calltoken received, check to see if it is valid */
04867       char *rec_hash = NULL;    /* the received hash, make sure it matches with ours. */
04868       char *rec_ts = NULL;      /* received timestamp */
04869       unsigned int rec_time;  /* received time_t */
04870 
04871       /* split the timestamp from the hash data */
04872       rec_hash = strchr((char *) ies->calltokendata, '?');
04873       if (rec_hash) {
04874          *rec_hash++ = '\0';
04875          rec_ts = (char *) ies->calltokendata;
04876       }
04877 
04878       /* check that we have valid data before we do any comparisons */
04879       if (!rec_hash || !rec_ts) {
04880          goto reject;
04881       } else if (sscanf(rec_ts, "%u", &rec_time) != 1) {
04882          goto reject;
04883       }
04884 
04885       /* create a hash with their address and the _TOKEN'S_ timestamp */
04886       ast_str_set(&buf, 0, CALLTOKEN_HASH_FORMAT, ast_inet_ntoa(sin->sin_addr), sin->sin_port, (unsigned int) rec_time, randomcalltokendata);
04887       ast_sha1_hash(hash, ast_str_buffer(buf));
04888 
04889       /* compare hashes and then check timestamp delay */
04890       if (strcmp(hash, rec_hash)) {
04891          ast_log(LOG_WARNING, "Address %s failed CallToken hash inspection\n", ast_inet_ntoa(sin->sin_addr));
04892          goto reject; /* received hash does not match ours, reject */
04893       } else if ((t < rec_time) || ((t - rec_time) >= MAX_CALLTOKEN_DELAY)) {
04894          ast_log(LOG_WARNING, "Too much delay in IAX2 calltoken timestamp from address %s\n", ast_inet_ntoa(sin->sin_addr));
04895          goto reject; /* too much delay, reject */
04896       }
04897 
04898       /* at this point the call token is valid, returning 0 
04899        * will allow socket_process to continue as usual */
04900       requirecalltoken_mark_auto(ies->username, subclass);
04901       return 0;
04902 
04903    /* ----- Case 3 ----- */
04904    } else { /* calltokens are not supported for this client, how do we respond? */
04905       if (calltoken_required(sin, ies->username, subclass)) {
04906          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"));
04907          goto reject;
04908       }
04909       return 0; /* calltoken is not required for this addr, so permit it. */
04910    }
04911 
04912 reject:
04913    /* received frame has failed calltoken inspection, send apathetic reject messages */
04914    if (subclass == IAX_COMMAND_REGREQ || subclass == IAX_COMMAND_REGREL) {
04915       send_apathetic_reply(1, ntohs(fh->scallno), sin, IAX_COMMAND_REGREJ, ntohl(fh->ts), fh->iseqno + 1, fd, NULL);
04916    } else {
04917       send_apathetic_reply(1, ntohs(fh->scallno), sin, IAX_COMMAND_REJECT, ntohl(fh->ts), fh->iseqno + 1, fd, NULL);
04918    }
04919 
04920    return 1;
04921 }
04922 
04923 /*!
04924  * \brief Parses an IAX dial string into its component parts.
04925  * \param data the string to be parsed
04926  * \param pds pointer to a \c struct \c parsed_dial_string to be filled in
04927  * \return nothing
04928  *
04929  * This function parses the string and fills the structure
04930  * with pointers to its component parts. The input string
04931  * will be modified.
04932  *
04933  * \note This function supports both plaintext passwords and RSA
04934  * key names; if the password string is formatted as '[keyname]',
04935  * then the keyname will be placed into the key field, and the
04936  * password field will be set to NULL.
04937  *
04938  * \note The dial string format is:
04939  *       [username[:password]@]peer[:port][/exten[@@context]][/options]
04940  */
04941 static void parse_dial_string(char *data, struct parsed_dial_string *pds)
04942 {
04943    if (ast_strlen_zero(data))
04944       return;
04945 
04946    pds->peer = strsep(&data, "/");
04947    pds->exten = strsep(&data, "/");
04948    pds->options = data;
04949 
04950    if (pds->exten) {
04951       data = pds->exten;
04952       pds->exten = strsep(&data, "@");
04953       pds->context = data;
04954    }
04955 
04956    if (strchr(pds->peer, '@')) {
04957       data = pds->peer;
04958       pds->username = strsep(&data, "@");
04959       pds->peer = data;
04960    }
04961 
04962    if (pds->username) {
04963       data = pds->username;
04964       pds->username = strsep(&data, ":");
04965       pds->password = data;
04966    }
04967 
04968    data = pds->peer;
04969    pds->peer = strsep(&data, ":");
04970    pds->port = data;
04971 
04972    /* check for a key name wrapped in [] in the secret position, if found,
04973       move it to the key field instead
04974    */
04975    if (pds->password && (pds->password[0] == '[')) {
04976       pds->key = ast_strip_quoted(pds->password, "[", "]");
04977       pds->password = NULL;
04978    }
04979 }
04980 
04981 static int iax2_call(struct ast_channel *c, char *dest, int timeout)
04982 {
04983    struct sockaddr_in sin;
04984    char *l=NULL, *n=NULL, *tmpstr;
04985    struct iax_ie_data ied;
04986    char *defaultrdest = "s";
04987    unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
04988    struct parsed_dial_string pds;
04989    struct create_addr_info cai;
04990    struct ast_var_t *var;
04991    struct ast_datastore *variablestore = ast_channel_datastore_find(c, &iax2_variable_datastore_info, NULL);
04992    const char* osp_token_ptr;
04993    unsigned int osp_token_length;
04994    unsigned char osp_block_index;
04995    unsigned int osp_block_length;
04996    unsigned char osp_buffer[256];
04997 
04998    if ((c->_state != AST_STATE_DOWN) && (c->_state != AST_STATE_RESERVED)) {
04999       ast_log(LOG_WARNING, "Channel is already in use (%s)?\n", c->name);
05000       return -1;
05001    }
05002 
05003    memset(&cai, 0, sizeof(cai));
05004    cai.encmethods = iax2_encryption;
05005 
05006    memset(&pds, 0, sizeof(pds));
05007    tmpstr = ast_strdupa(dest);
05008    parse_dial_string(tmpstr, &pds);
05009 
05010    if (ast_strlen_zero(pds.peer)) {
05011       ast_log(LOG_WARNING, "No peer provided in the IAX2 dial string '%s'\n", dest);
05012       return -1;
05013    }
05014    if (!pds.exten) {
05015       pds.exten = defaultrdest;
05016    }
05017    if (create_addr(pds.peer, c, &sin, &cai)) {
05018       ast_log(LOG_WARNING, "No address associated with '%s'\n", pds.peer);
05019       return -1;
05020    }
05021    if (ast_test_flag64(iaxs[callno], IAX_FORCE_ENCRYPT) && !cai.encmethods) {
05022       ast_log(LOG_WARNING, "Encryption forced for call, but not enabled\n");
05023       c->hangupcause = AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
05024       return -1;
05025    }
05026    if (ast_strlen_zero(cai.secret) && ast_test_flag64(iaxs[callno], IAX_FORCE_ENCRYPT)) {
05027       ast_log(LOG_WARNING, "Call terminated. No secret given and force encrypt enabled\n");
05028       return -1;
05029    }
05030    if (!pds.username && !ast_strlen_zero(cai.username))
05031       pds.username = cai.username;
05032    if (!pds.password && !ast_strlen_zero(cai.secret))
05033       pds.password = cai.secret;
05034    if (!pds.key && !ast_strlen_zero(cai.outkey))
05035       pds.key = cai.outkey;
05036    if (!pds.context && !ast_strlen_zero(cai.peercontext))
05037       pds.context = cai.peercontext;
05038 
05039    /* Keep track of the context for outgoing calls too */
05040    ast_copy_string(c->context, cai.context, sizeof(c->context));
05041 
05042    if (pds.port)
05043       sin.sin_port = htons(atoi(pds.port));
05044 
05045    l = c->connected.id.number.valid ? c->connected.id.number.str : NULL;
05046    n = c->connected.id.name.valid ? c->connected.id.name.str : NULL;
05047 
05048    /* Now build request */ 
05049    memset(&ied, 0, sizeof(ied));
05050 
05051    /* On new call, first IE MUST be IAX version of caller */
05052    iax_ie_append_short(&ied, IAX_IE_VERSION, IAX_PROTO_VERSION);
05053    iax_ie_append_str(&ied, IAX_IE_CALLED_NUMBER, pds.exten);
05054    if (pds.options && strchr(pds.options, 'a')) {
05055       /* Request auto answer */
05056       iax_ie_append(&ied, IAX_IE_AUTOANSWER);
05057    }
05058 
05059    /* WARNING: this breaks down at 190 bits! */
05060    iax_ie_append_str(&ied, IAX_IE_CODEC_PREFS, cai.prefs);
05061 
05062    if (l) {
05063       iax_ie_append_str(&ied, IAX_IE_CALLING_NUMBER, l);
05064       iax_ie_append_byte(&ied, IAX_IE_CALLINGPRES,
05065          ast_party_id_presentation(&c->connected.id));
05066    } else if (n) {
05067       iax_ie_append_byte(&ied, IAX_IE_CALLINGPRES,
05068          ast_party_id_presentation(&c->connected.id));
05069    } else {
05070       iax_ie_append_byte(&ied, IAX_IE_CALLINGPRES, AST_PRES_NUMBER_NOT_AVAILABLE);
05071    }
05072 
05073    iax_ie_append_byte(&ied, IAX_IE_CALLINGTON, c->connected.id.number.plan);
05074    iax_ie_append_short(&ied, IAX_IE_CALLINGTNS, c->dialed.transit_network_select);
05075 
05076    if (n)
05077       iax_ie_append_str(&ied, IAX_IE_CALLING_NAME, n);
05078    if (ast_test_flag64(iaxs[callno], IAX_SENDANI)
05079       && c->connected.ani.number.valid
05080       && c->connected.ani.number.str) {
05081       iax_ie_append_str(&ied, IAX_IE_CALLING_ANI, c->connected.ani.number.str);
05082    }
05083 
05084    if (!ast_strlen_zero(c->language))
05085       iax_ie_append_str(&ied, IAX_IE_LANGUAGE, c->language);
05086    if (!ast_strlen_zero(c->dialed.number.str)) {
05087       iax_ie_append_str(&ied, IAX_IE_DNID, c->dialed.number.str);
05088    }
05089    if (c->redirecting.from.number.valid
05090       && !ast_strlen_zero(c->redirecting.from.number.str)) {
05091       iax_ie_append_str(&ied, IAX_IE_RDNIS, c->redirecting.from.number.str);
05092    }
05093 
05094    if (pds.context)
05095       iax_ie_append_str(&ied, IAX_IE_CALLED_CONTEXT, pds.context);
05096 
05097    if (pds.username)
05098       iax_ie_append_str(&ied, IAX_IE_USERNAME, pds.username);
05099 
05100    if (cai.encmethods)
05101       iax_ie_append_short(&ied, IAX_IE_ENCRYPTION, cai.encmethods);
05102 
05103    ast_mutex_lock(&iaxsl[callno]);
05104 
05105    if (!ast_strlen_zero(c->context))
05106       ast_string_field_set(iaxs[callno], context, c->context);
05107 
05108    if (pds.username)
05109       ast_string_field_set(iaxs[callno], username, pds.username);
05110 
05111    iaxs[callno]->encmethods = cai.encmethods;
05112 
05113    iaxs[callno]->adsi = cai.adsi;
05114    
05115    ast_string_field_set(iaxs[callno], mohinterpret, cai.mohinterpret);
05116    ast_string_field_set(iaxs[callno], mohsuggest, cai.mohsuggest);
05117 
05118    if (pds.key)
05119       ast_string_field_set(iaxs[callno], outkey, pds.key);
05120    if (pds.password)
05121       ast_string_field_set(iaxs[callno], secret, pds.password);
05122 
05123    iax_ie_append_int(&ied, IAX_IE_FORMAT, (int) c->nativeformats);
05124    iax_ie_append_versioned_uint64(&ied, IAX_IE_FORMAT2, 0, c->nativeformats);
05125    iax_ie_append_int(&ied, IAX_IE_CAPABILITY, (int) iaxs[callno]->capability);
05126    iax_ie_append_versioned_uint64(&ied, IAX_IE_CAPABILITY2, 0, iaxs[callno]->capability);
05127    iax_ie_append_short(&ied, IAX_IE_ADSICPE, c->adsicpe);
05128    iax_ie_append_int(&ied, IAX_IE_DATETIME, iax2_datetime(cai.timezone));
05129 
05130    if (iaxs[callno]->maxtime) {
05131       /* Initialize pingtime and auto-congest time */
05132       iaxs[callno]->pingtime = iaxs[callno]->maxtime / 2;
05133       iaxs[callno]->initid = iax2_sched_add(sched, iaxs[callno]->maxtime * 2, auto_congest, CALLNO_TO_PTR(callno));
05134    } else if (autokill) {
05135       iaxs[callno]->pingtime = autokill / 2;
05136       iaxs[callno]->initid = iax2_sched_add(sched, autokill * 2, auto_congest, CALLNO_TO_PTR(callno));
05137    }
05138 
05139    /* Check if there is an OSP token */
05140    osp_token_ptr = pbx_builtin_getvar_helper(c, "IAX2OSPTOKEN");
05141    if (!ast_strlen_zero(osp_token_ptr)) {
05142       if ((osp_token_length = strlen(osp_token_ptr)) <= IAX_MAX_OSPTOKEN_SIZE) {
05143          osp_block_index = 0;
05144          while (osp_token_length > 0) {
05145             osp_block_length = IAX_MAX_OSPBLOCK_SIZE < osp_token_length ? IAX_MAX_OSPBLOCK_SIZE : osp_token_length;
05146             osp_buffer[0] = osp_block_index;
05147             memcpy(osp_buffer + 1, osp_token_ptr, osp_block_length);
05148             iax_ie_append_raw(&ied, IAX_IE_OSPTOKEN, osp_buffer, osp_block_length + 1);
05149             osp_block_index++;
05150             osp_token_ptr += osp_block_length;
05151             osp_token_length -= osp_block_length;
05152          } 
05153       } else
05154          ast_log(LOG_WARNING, "OSP token is too long\n");
05155    } else if (iaxdebug)
05156       ast_debug(1, "OSP token is undefined\n");
05157 
05158    /* send the command using the appropriate socket for this peer */
05159    iaxs[callno]->sockfd = cai.sockfd;
05160 
05161    /* Add remote vars */
05162    if (variablestore) {
05163       AST_LIST_HEAD(, ast_var_t) *variablelist = variablestore->data;
05164       ast_debug(1, "Found an IAX variable store on this channel\n");
05165       AST_LIST_LOCK(variablelist);
05166       AST_LIST_TRAVERSE(variablelist, var, entries) {
05167          char tmp[256];
05168          int i;
05169          ast_debug(1, "Found IAXVAR '%s' with value '%s' (to transmit)\n", ast_var_name(var), ast_var_value(var));
05170          /* Automatically divide the value up into sized chunks */
05171          for (i = 0; i < strlen(ast_var_value(var)); i += 255 - (strlen(ast_var_name(var)) + 1)) {
05172             snprintf(tmp, sizeof(tmp), "%s=%s", ast_var_name(var), ast_var_value(var) + i);
05173             iax_ie_append_str(&ied, IAX_IE_VARIABLE, tmp);
05174          }
05175       }
05176       AST_LIST_UNLOCK(variablelist);
05177    }
05178 
05179    /* Transmit the string in a "NEW" request */
05180    add_empty_calltoken_ie(iaxs[callno], &ied); /* this _MUST_ be the last ie added */
05181    send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_NEW, 0, ied.buf, ied.pos, -1);
05182 
05183    ast_mutex_unlock(&iaxsl[callno]);
05184    ast_setstate(c, AST_STATE_RINGING);
05185 
05186    return 0;
05187 }
05188 
05189 static int iax2_hangup(struct ast_channel *c) 
05190 {
05191    unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
05192    struct iax_ie_data ied;
05193    int alreadygone;
05194    memset(&ied, 0, sizeof(ied));
05195    ast_mutex_lock(&iaxsl[callno]);
05196    if (callno && iaxs[callno]) {
05197       ast_debug(1, "We're hanging up %s now...\n", c->name);
05198       alreadygone = ast_test_flag64(iaxs[callno], IAX_ALREADYGONE);
05199       /* Send the hangup unless we have had a transmission error or are already gone */
05200       iax_ie_append_byte(&ied, IAX_IE_CAUSECODE, (unsigned char)c->hangupcause);
05201       if (!iaxs[callno]->error && !alreadygone) {
05202          if (send_command_final(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_HANGUP, 0, ied.buf, ied.pos, -1)) {
05203             ast_log(LOG_WARNING, "No final packet could be sent for callno %d\n", callno);
05204          }
05205          if (!iaxs[callno]) {
05206             ast_mutex_unlock(&iaxsl[callno]);
05207             return 0;
05208          }
05209       }
05210       /* Explicitly predestroy it */
05211       iax2_predestroy(callno);
05212       /* If we were already gone to begin with, destroy us now */
05213       if (iaxs[callno] && alreadygone) {
05214          ast_debug(1, "Really destroying %s now...\n", c->name);
05215          iax2_destroy(callno);
05216       } else if (iaxs[callno]) {
05217          if (ast_sched_thread_add(sched, 10000, scheduled_destroy, CALLNO_TO_PTR(callno)) < 0) {
05218             ast_log(LOG_ERROR, "Unable to schedule iax2 callno %d destruction?!!  Destroying immediately.\n", callno);
05219             iax2_destroy(callno);
05220          }
05221       }
05222    } else if (c->tech_pvt) {
05223       /* If this call no longer exists, but the channel still
05224        * references it we need to set the channel's tech_pvt to null
05225        * to avoid ast_channel_free() trying to free it.
05226        */
05227       c->tech_pvt = NULL;
05228    }
05229    ast_mutex_unlock(&iaxsl[callno]);
05230    ast_verb(3, "Hungup '%s'\n", c->name);
05231    return 0;
05232 }
05233 
05234 /*!
05235  * \note expects the pvt to be locked
05236  */
05237 static int wait_for_peercallno(struct chan_iax2_pvt *pvt)
05238 {
05239    unsigned short callno = pvt->callno;
05240 
05241    if (!pvt->peercallno) {
05242       /* We don't know the remote side's call number, yet.  :( */
05243       int count = 10;
05244       while (count-- && pvt && !pvt->peercallno) {
05245          DEADLOCK_AVOIDANCE(&iaxsl[callno]);
05246          pvt = iaxs[callno];
05247       }
05248       if (!pvt->peercallno) {
05249          return -1;
05250       }
05251    }
05252 
05253    return 0;
05254 }
05255 
05256 static int iax2_setoption(struct ast_channel *c, int option, void *data, int datalen)
05257 {
05258    struct ast_option_header *h;
05259    int res;
05260 
05261    switch (option) {
05262    case AST_OPTION_TXGAIN:
05263    case AST_OPTION_RXGAIN:
05264       /* these two cannot be sent, because they require a result */
05265       errno = ENOSYS;
05266       return -1;
05267    case AST_OPTION_FORMAT_READ:
05268    case AST_OPTION_FORMAT_WRITE:
05269    case AST_OPTION_MAKE_COMPATIBLE:
05270       return -1;
05271    case AST_OPTION_OPRMODE:
05272       errno = EINVAL;
05273       return -1;
05274    case AST_OPTION_SECURE_SIGNALING:
05275    case AST_OPTION_SECURE_MEDIA:
05276    {
05277       unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
05278       ast_mutex_lock(&iaxsl[callno]);
05279       if ((*(int *) data)) {
05280          ast_set_flag64(iaxs[callno], IAX_FORCE_ENCRYPT);
05281       } else {
05282          ast_clear_flag64(iaxs[callno], IAX_FORCE_ENCRYPT);
05283       }
05284       ast_mutex_unlock(&iaxsl[callno]);
05285       return 0;
05286    }
05287    default:
05288    {
05289       unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
05290       struct chan_iax2_pvt *pvt;
05291 
05292       ast_mutex_lock(&iaxsl[callno]);
05293       pvt = iaxs[callno];
05294 
05295       if (wait_for_peercallno(pvt)) {
05296          ast_mutex_unlock(&iaxsl[callno]);
05297          return -1;
05298       }
05299 
05300       ast_mutex_unlock(&iaxsl[callno]);
05301 
05302       if (!(h = ast_malloc(datalen + sizeof(*h)))) {
05303          return -1;
05304       }
05305 
05306       h->flag = AST_OPTION_FLAG_REQUEST;
05307       h->option = htons(option);
05308       memcpy(h->data, data, datalen);
05309       res = send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_CONTROL,
05310                  AST_CONTROL_OPTION, 0, (unsigned char *) h,
05311                  datalen + sizeof(*h), -1);
05312       ast_free(h);
05313       return res;
05314    }
05315    }
05316 }
05317 
05318 static int iax2_queryoption(struct ast_channel *c, int option, void *data, int *datalen)
05319 {
05320    switch (option) {
05321    case AST_OPTION_SECURE_SIGNALING:
05322    case AST_OPTION_SECURE_MEDIA:
05323    {
05324       unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
05325       ast_mutex_lock(&iaxsl[callno]);
05326       *((int *) data) = ast_test_flag64(iaxs[callno], IAX_FORCE_ENCRYPT) ? 1 : 0;
05327       ast_mutex_unlock(&iaxsl[callno]);
05328       return 0;
05329    }
05330    default:
05331       return -1;
05332    }
05333 }
05334 
05335 static struct ast_frame *iax2_read(struct ast_channel *c) 
05336 {
05337    ast_log(LOG_NOTICE, "I should never be called!\n");
05338    return &ast_null_frame;
05339 }
05340 
05341 static int iax2_key_rotate(const void *vpvt)
05342 {
05343    int res = 0;
05344    struct chan_iax2_pvt *pvt = (void *) vpvt;
05345    struct MD5Context md5;
05346    char key[17] = "";
05347    struct iax_ie_data ied = {
05348       .pos = 0,   
05349    };
05350    
05351    ast_mutex_lock(&iaxsl[pvt->callno]);
05352    pvt->keyrotateid = 
05353       ast_sched_thread_add(sched, 120000 + (ast_random() % 180001), iax2_key_rotate, vpvt);
05354 
05355    snprintf(key, sizeof(key), "%lX", ast_random());
05356 
05357    MD5Init(&md5);
05358    MD5Update(&md5, (unsigned char *) key, strlen(key));
05359    MD5Final((unsigned char *) key, &md5);
05360 
05361    IAX_DEBUGDIGEST("Sending", key);
05362 
05363    iax_ie_append_raw(&ied, IAX_IE_CHALLENGE, key, 16);
05364 
05365    res = send_command(pvt, AST_FRAME_IAX, IAX_COMMAND_RTKEY, 0, ied.buf, ied.pos, -1);
05366 
05367    build_ecx_key((unsigned char *) key, pvt);
05368 
05369    ast_mutex_unlock(&iaxsl[pvt->callno]);
05370 
05371    return res;
05372 }
05373 
05374 static int iax2_start_transfer(unsigned short callno0, unsigned short callno1, int mediaonly)
05375 {
05376    int res;
05377    struct iax_ie_data ied0;
05378    struct iax_ie_data ied1;
05379    unsigned int transferid = (unsigned int)ast_random();
05380 
05381    if (IAX_CALLENCRYPTED(iaxs[callno0]) || IAX_CALLENCRYPTED(iaxs[callno1])) {
05382       ast_debug(1, "transfers are not supported for encrypted calls at this time");
05383       ast_set_flag64(iaxs[callno0], IAX_NOTRANSFER);
05384       ast_set_flag64(iaxs[callno1], IAX_NOTRANSFER);
05385       return 0;
05386    }
05387 
05388    memset(&ied0, 0, sizeof(ied0));
05389    iax_ie_append_addr(&ied0, IAX_IE_APPARENT_ADDR, &iaxs[callno1]->addr);
05390    iax_ie_append_short(&ied0, IAX_IE_CALLNO, iaxs[callno1]->peercallno);
05391    iax_ie_append_int(&ied0, IAX_IE_TRANSFERID, transferid);
05392 
05393    memset(&ied1, 0, sizeof(ied1));
05394    iax_ie_append_addr(&ied1, IAX_IE_APPARENT_ADDR, &iaxs[callno0]->addr);
05395    iax_ie_append_short(&ied1, IAX_IE_CALLNO, iaxs[callno0]->peercallno);
05396    iax_ie_append_int(&ied1, IAX_IE_TRANSFERID, transferid);
05397    
05398    res = send_command(iaxs[callno0], AST_FRAME_IAX, IAX_COMMAND_TXREQ, 0, ied0.buf, ied0.pos, -1);
05399    if (res)
05400       return -1;
05401    res = send_command(iaxs[callno1], AST_FRAME_IAX, IAX_COMMAND_TXREQ, 0, ied1.buf, ied1.pos, -1);
05402    if (res)
05403       return -1;
05404    iaxs[callno0]->transferring = mediaonly ? TRANSFER_MBEGIN : TRANSFER_BEGIN;
05405    iaxs[callno1]->transferring = mediaonly ? TRANSFER_MBEGIN : TRANSFER_BEGIN;
05406    return 0;
05407 }
05408 
05409 static void lock_both(unsigned short callno0, unsigned short callno1)
05410 {
05411    ast_mutex_lock(&iaxsl[callno0]);
05412    while (ast_mutex_trylock(&iaxsl[callno1])) {
05413       DEADLOCK_AVOIDANCE(&iaxsl[callno0]);
05414    }
05415 }
05416 
05417 static void unlock_both(unsigned short callno0, unsigned short callno1)
05418 {
05419    ast_mutex_unlock(&iaxsl[callno1]);
05420    ast_mutex_unlock(&iaxsl[callno0]);
05421 }
05422 
05423 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)
05424 {
05425    struct ast_channel *cs[3];
05426    struct ast_channel *who, *other;
05427    int to = -1;
05428    int res = -1;
05429    int transferstarted=0;
05430    struct ast_frame *f;
05431    unsigned short callno0 = PTR_TO_CALLNO(c0->tech_pvt);
05432    unsigned short callno1 = PTR_TO_CALLNO(c1->tech_pvt);
05433    struct timeval waittimer = {0, 0};
05434 
05435    /* We currently do not support native bridging if a timeoutms value has been provided */
05436    if (timeoutms > 0) {
05437       return AST_BRIDGE_FAILED;
05438    }
05439 
05440    timeoutms = -1;
05441 
05442    lock_both(callno0, callno1);
05443    if (!iaxs[callno0] || !iaxs[callno1]) {
05444       unlock_both(callno0, callno1);
05445       return AST_BRIDGE_FAILED;
05446    }
05447    /* Put them in native bridge mode */
05448    if (!(flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1))) {
05449       iaxs[callno0]->bridgecallno = callno1;
05450       iaxs[callno1]->bridgecallno = callno0;
05451    }
05452    unlock_both(callno0, callno1);
05453 
05454    /* If not, try to bridge until we can execute a transfer, if we can */
05455    cs[0] = c0;
05456    cs[1] = c1;
05457    for (/* ever */;;) {
05458       /* Check in case we got masqueraded into */
05459       if ((c0->tech != &iax2_tech) || (c1->tech != &iax2_tech)) {
05460          ast_verb(3, "Can't masquerade, we're different...\n");
05461          /* Remove from native mode */
05462          if (c0->tech == &iax2_tech) {
05463             ast_mutex_lock(&iaxsl[callno0]);
05464             iaxs[callno0]->bridgecallno = 0;
05465             ast_mutex_unlock(&iaxsl[callno0]);
05466          }
05467          if (c1->tech == &iax2_tech) {
05468             ast_mutex_lock(&iaxsl[callno1]);
05469             iaxs[callno1]->bridgecallno = 0;
05470             ast_mutex_unlock(&iaxsl[callno1]);
05471          }
05472          return AST_BRIDGE_FAILED_NOWARN;
05473       }
05474       if (c0->nativeformats != c1->nativeformats) {
05475          char buf0[256];
05476          char buf1[256];
05477          ast_getformatname_multiple(buf0, sizeof(buf0), c0->nativeformats);
05478          ast_getformatname_multiple(buf1, sizeof(buf1), c1->nativeformats);
05479          ast_verb(3, "Operating with different codecs [%s] [%s] , can't native bridge...\n", buf0, buf1);
05480          /* Remove from native mode */
05481          lock_both(callno0, callno1);
05482          if (iaxs[callno0])
05483             iaxs[callno0]->bridgecallno = 0;
05484          if (iaxs[callno1])
05485             iaxs[callno1]->bridgecallno = 0;
05486          unlock_both(callno0, callno1);
05487          return AST_BRIDGE_FAILED_NOWARN;
05488       }
05489       /* check if transfered and if we really want native bridging */
05490       if (!transferstarted && !ast_test_flag64(iaxs[callno0], IAX_NOTRANSFER) && !ast_test_flag64(iaxs[callno1], IAX_NOTRANSFER)) {
05491          /* Try the transfer */
05492          if (iax2_start_transfer(callno0, callno1, (flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1)) ||
05493                      ast_test_flag64(iaxs[callno0], IAX_TRANSFERMEDIA) | ast_test_flag64(iaxs[callno1], IAX_TRANSFERMEDIA)))
05494             ast_log(LOG_WARNING, "Unable to start the transfer\n");
05495          transferstarted = 1;
05496       }
05497       if ((iaxs[callno0]->transferring == TRANSFER_RELEASED) && (iaxs[callno1]->transferring == TRANSFER_RELEASED)) {
05498          /* Call has been transferred.  We're no longer involved */
05499          struct timeval now = ast_tvnow();
05500          if (ast_tvzero(waittimer)) {
05501             waittimer = now;
05502          } else if (now.tv_sec - waittimer.tv_sec > IAX_LINGER_TIMEOUT) {
05503             c0->_softhangup |= AST_SOFTHANGUP_DEV;
05504             c1->_softhangup |= AST_SOFTHANGUP_DEV;
05505             *fo = NULL;
05506             *rc = c0;
05507             res = AST_BRIDGE_COMPLETE;
05508             break;
05509          }
05510       }
05511       to = 1000;
05512       who = ast_waitfor_n(cs, 2, &to);
05513       if (timeoutms > -1) {
05514          timeoutms -= (1000 - to);
05515          if (timeoutms < 0)
05516             timeoutms = 0;
05517       }
05518       if (!who) {
05519          if (!timeoutms) {
05520             res = AST_BRIDGE_RETRY;
05521             break;
05522          }
05523          if (ast_check_hangup(c0) || ast_check_hangup(c1)) {
05524             res = AST_BRIDGE_FAILED;
05525             break;
05526          }
05527          continue;
05528       }
05529       f = ast_read(who);
05530       if (!f) {
05531          *fo = NULL;
05532          *rc = who;
05533          res = AST_BRIDGE_COMPLETE;
05534          break;
05535       }
05536       if ((f->frametype == AST_FRAME_CONTROL) && !(flags & AST_BRIDGE_IGNORE_SIGS) && (f->subclass.integer != AST_CONTROL_SRCUPDATE)) {
05537          *fo = f;
05538          *rc = who;
05539          res =  AST_BRIDGE_COMPLETE;
05540          break;
05541       }
05542       other = (who == c0) ? c1 : c0;  /* the 'other' channel */
05543       if ((f->frametype == AST_FRAME_VOICE) ||
05544          (f->frametype == AST_FRAME_TEXT) ||
05545          (f->frametype == AST_FRAME_VIDEO) || 
05546          (f->frametype == AST_FRAME_IMAGE) ||
05547          (f->frametype == AST_FRAME_DTMF) ||
05548          (f->frametype == AST_FRAME_CONTROL)) {
05549          /* monitored dtmf take out of the bridge.
05550           * check if we monitor the specific source.
05551           */
05552          int monitored_source = (who == c0) ? AST_BRIDGE_DTMF_CHANNEL_0 : AST_BRIDGE_DTMF_CHANNEL_1;
05553          if (f->frametype == AST_FRAME_DTMF && (flags & monitored_source)) {
05554             *rc = who;
05555             *fo = f;
05556             res = AST_BRIDGE_COMPLETE;
05557             /* Remove from native mode */
05558             break;
05559          }
05560          /* everything else goes to the other side */
05561          ast_write(other, f);
05562       }
05563       ast_frfree(f);
05564       /* Swap who gets priority */
05565       cs[2] = cs[0];
05566       cs[0] = cs[1];
05567       cs[1] = cs[2];
05568    }
05569    lock_both(callno0, callno1);
05570    if(iaxs[callno0])
05571       iaxs[callno0]->bridgecallno = 0;
05572    if(iaxs[callno1])
05573       iaxs[callno1]->bridgecallno = 0;
05574    unlock_both(callno0, callno1);
05575    return res;
05576 }
05577 
05578 static int iax2_answer(struct ast_channel *c)
05579 {
05580    unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
05581    ast_debug(1, "Answering IAX2 call\n");
05582    ast_mutex_lock(&iaxsl[callno]);
05583    if (iaxs[callno])
05584       iax2_ami_channelupdate(iaxs[callno]);
05585    ast_mutex_unlock(&iaxsl[callno]);
05586    return send_command_locked(callno, AST_FRAME_CONTROL, AST_CONTROL_ANSWER, 0, NULL, 0, -1);
05587 }
05588 
05589 static int iax2_indicate(struct ast_channel *c, int condition, const void *data, size_t datalen)
05590 {
05591    unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
05592    struct chan_iax2_pvt *pvt;
05593    int res = 0;
05594 
05595    if (iaxdebug)
05596       ast_debug(1, "Indicating condition %d\n", condition);
05597 
05598    ast_mutex_lock(&iaxsl[callno]);
05599    pvt = iaxs[callno];
05600 
05601    if (wait_for_peercallno(pvt)) {
05602       res = -1;
05603       goto done;
05604    }
05605 
05606    switch (condition) {
05607    case AST_CONTROL_HOLD:
05608       if (strcasecmp(pvt->mohinterpret, "passthrough")) {
05609          ast_moh_start(c, data, pvt->mohinterpret);
05610          goto done;
05611       }
05612       break;
05613    case AST_CONTROL_UNHOLD:
05614       if (strcasecmp(pvt->mohinterpret, "passthrough")) {
05615          ast_moh_stop(c);
05616          goto done;
05617       }
05618       break;
05619    case AST_CONTROL_CONNECTED_LINE:
05620       if (!ast_test_flag64(pvt, IAX_SENDCONNECTEDLINE))
05621          goto done;
05622       break;
05623    }
05624 
05625    res = send_command(pvt, AST_FRAME_CONTROL, condition, 0, data, datalen, -1);
05626 
05627 done:
05628    ast_mutex_unlock(&iaxsl[callno]);
05629 
05630    return res;
05631 }
05632    
05633 static int iax2_transfer(struct ast_channel *c, const char *dest)
05634 {
05635    unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
05636    struct iax_ie_data ied = { "", };
05637    char tmp[256], *context;
05638    enum ast_control_transfer message = AST_TRANSFER_SUCCESS;
05639    ast_copy_string(tmp, dest, sizeof(tmp));
05640    context = strchr(tmp, '@');
05641    if (context) {
05642       *context = '\0';
05643       context++;
05644    }
05645    iax_ie_append_str(&ied, IAX_IE_CALLED_NUMBER, tmp);
05646    if (context)
05647       iax_ie_append_str(&ied, IAX_IE_CALLED_CONTEXT, context);
05648    ast_debug(1, "Transferring '%s' to '%s'\n", c->name, dest);
05649    ast_queue_control_data(c, AST_CONTROL_TRANSFER, &message, sizeof(message));
05650    return send_command_locked(callno, AST_FRAME_IAX, IAX_COMMAND_TRANSFER, 0, ied.buf, ied.pos, -1);
05651 }
05652    
05653 static int iax2_getpeertrunk(struct sockaddr_in sin)
05654 {
05655    struct iax2_peer *peer;
05656    int res = 0;
05657    struct ao2_iterator i;
05658 
05659    i = ao2_iterator_init(peers, 0);
05660    while ((peer = ao2_iterator_next(&i))) {
05661       struct sockaddr_in peer_addr;
05662 
05663       ast_sockaddr_to_sin(&peer->addr, &peer_addr);
05664 
05665       if ((peer_addr.sin_addr.s_addr == sin.sin_addr.s_addr) &&
05666           (peer_addr.sin_port == sin.sin_port)) {
05667          res = ast_test_flag64(peer, IAX_TRUNK);
05668          peer_unref(peer);
05669          break;
05670       }
05671       peer_unref(peer);
05672    }
05673    ao2_iterator_destroy(&i);
05674 
05675    return res;
05676 }
05677 
05678 /*! \brief  Create new call, interface with the PBX core */
05679 static struct ast_channel *ast_iax2_new(int callno, int state, format_t capability, const char *linkedid)
05680 {
05681    struct ast_channel *tmp;
05682    struct chan_iax2_pvt *i;
05683    struct ast_variable *v = NULL;
05684 
05685    if (!(i = iaxs[callno])) {
05686       ast_log(LOG_WARNING, "No IAX2 pvt found for callno '%d' !\n", callno);
05687       return NULL;
05688    }
05689 
05690    /* Don't hold call lock */
05691    ast_mutex_unlock(&iaxsl[callno]);
05692    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);
05693    ast_mutex_lock(&iaxsl[callno]);
05694    if (i != iaxs[callno]) {
05695       if (tmp) {
05696          /* unlock and relock iaxsl[callno] to preserve locking order */
05697          ast_mutex_unlock(&iaxsl[callno]);
05698          tmp = ast_channel_release(tmp);
05699          ast_mutex_lock(&iaxsl[callno]);
05700       }
05701       return NULL;
05702    }
05703    iax2_ami_channelupdate(i);
05704    if (!tmp)
05705       return NULL;
05706    tmp->tech = &iax2_tech;
05707    /* We can support any format by default, until we get restricted */
05708    tmp->nativeformats = capability;
05709    tmp->readformat = tmp->rawreadformat = ast_best_codec(capability);
05710    tmp->writeformat = tmp->rawwriteformat = ast_best_codec(capability);
05711    tmp->tech_pvt = CALLNO_TO_PTR(i->callno);
05712 
05713    if (!ast_strlen_zero(i->parkinglot))
05714       ast_string_field_set(tmp, parkinglot, i->parkinglot);
05715    /* Don't use ast_set_callerid() here because it will
05716     * generate a NewCallerID event before the NewChannel event */
05717    if (!ast_strlen_zero(i->ani)) {
05718       tmp->caller.ani.number.valid = 1;
05719       tmp->caller.ani.number.str = ast_strdup(i->ani);
05720    } else if (!ast_strlen_zero(i->cid_num)) {
05721       tmp->caller.ani.number.valid = 1;
05722       tmp->caller.ani.number.str = ast_strdup(i->cid_num);
05723    }
05724    tmp->dialed.number.str = ast_strdup(i->dnid);
05725    tmp->redirecting.from.number.valid = 1;
05726    tmp->redirecting.from.number.str = ast_strdup(i->rdnis);
05727    tmp->caller.id.name.presentation = i->calling_pres;
05728    tmp->caller.id.number.presentation = i->calling_pres;
05729    tmp->caller.id.number.plan = i->calling_ton;
05730    tmp->dialed.transit_network_select = i->calling_tns;
05731    if (!ast_strlen_zero(i->language))
05732       ast_string_field_set(tmp, language, i->language);
05733    if (!ast_strlen_zero(i->accountcode))
05734       ast_string_field_set(tmp, accountcode, i->accountcode);
05735    if (i->amaflags)
05736       tmp->amaflags = i->amaflags;
05737    ast_copy_string(tmp->context, i->context, sizeof(tmp->context));
05738    ast_copy_string(tmp->exten, i->exten, sizeof(tmp->exten));
05739    if (i->adsi)
05740       tmp->adsicpe = i->peeradsicpe;
05741    else
05742       tmp->adsicpe = AST_ADSI_UNAVAILABLE;
05743    i->owner = tmp;
05744    i->capability = capability;
05745 
05746    /* Set inherited variables */
05747    if (i->vars) {
05748       for (v = i->vars ; v ; v = v->next)
05749          pbx_builtin_setvar_helper(tmp, v->name, v->value);
05750    }
05751    if (i->iaxvars) {
05752       struct ast_datastore *variablestore;
05753       struct ast_variable *var, *prev = NULL;
05754       AST_LIST_HEAD(, ast_var_t) *varlist;
05755       ast_debug(1, "Loading up the channel with IAXVARs\n");
05756       varlist = ast_calloc(1, sizeof(*varlist));
05757       variablestore = ast_datastore_alloc(&iax2_variable_datastore_info, NULL);
05758       if (variablestore && varlist) {
05759          variablestore->data = varlist;
05760          variablestore->inheritance = DATASTORE_INHERIT_FOREVER;
05761          AST_LIST_HEAD_INIT(varlist);
05762          for (var = i->iaxvars; var; var = var->next) {
05763             struct ast_var_t *newvar = ast_var_assign(var->name, var->value);
05764             if (prev)
05765                ast_free(prev);
05766             prev = var;
05767             if (!newvar) {
05768                /* Don't abort list traversal, as this would leave i->iaxvars in an inconsistent state. */
05769                ast_log(LOG_ERROR, "Memory allocation error while processing IAX2 variables\n");
05770             } else {
05771                AST_LIST_INSERT_TAIL(varlist, newvar, entries);
05772             }
05773          }
05774          if (prev)
05775             ast_free(prev);
05776          i->iaxvars = NULL;
05777          ast_channel_datastore_add(i->owner, variablestore);
05778       } else {
05779          if (variablestore) {
05780             ast_datastore_free(variablestore);
05781          }
05782          if (varlist) {
05783             ast_free(varlist);
05784          }
05785       }
05786    }
05787 
05788    if (state != AST_STATE_DOWN) {
05789       if (ast_pbx_start(tmp)) {
05790          ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
05791          ast_hangup(tmp);
05792          i->owner = NULL;
05793          return NULL;
05794       }
05795    }
05796 
05797    ast_module_ref(ast_module_info->self);
05798    return tmp;
05799 }
05800 
05801 static unsigned int calc_txpeerstamp(struct iax2_trunk_peer *tpeer, int sampms, struct timeval *now)
05802 {
05803    unsigned long int mssincetx; /* unsigned to handle overflows */
05804    long int ms, pred;
05805 
05806    tpeer->trunkact = *now;
05807    mssincetx = ast_tvdiff_ms(*now, tpeer->lasttxtime);
05808    if (mssincetx > 5000 || ast_tvzero(tpeer->txtrunktime)) {
05809       /* If it's been at least 5 seconds since the last time we transmitted on this trunk, reset our timers */
05810       tpeer->txtrunktime = *now;
05811       tpeer->lastsent = 999999;
05812    }
05813    /* Update last transmit time now */
05814    tpeer->lasttxtime = *now;
05815    
05816    /* Calculate ms offset */
05817    ms = ast_tvdiff_ms(*now, tpeer->txtrunktime);
05818    /* Predict from last value */
05819    pred = tpeer->lastsent + sampms;
05820    if (abs(ms - pred) < MAX_TIMESTAMP_SKEW)
05821       ms = pred;
05822    
05823    /* We never send the same timestamp twice, so fudge a little if we must */
05824    if (ms == tpeer->lastsent)
05825       ms = tpeer->lastsent + 1;
05826    tpeer->lastsent = ms;
05827    return ms;
05828 }
05829 
05830 static unsigned int fix_peerts(struct timeval *rxtrunktime, int callno, unsigned int ts)
05831 {
05832    long ms; /* NOT unsigned */
05833    if (ast_tvzero(iaxs[callno]->rxcore)) {
05834       /* Initialize rxcore time if appropriate */
05835       iaxs[callno]->rxcore = ast_tvnow();
05836       /* Round to nearest 20ms so traces look pretty */
05837       iaxs[callno]->rxcore.tv_usec -= iaxs[callno]->rxcore.tv_usec % 20000;
05838    }
05839    /* Calculate difference between trunk and channel */
05840    ms = ast_tvdiff_ms(*rxtrunktime, iaxs[callno]->rxcore);
05841    /* Return as the sum of trunk time and the difference between trunk and real time */
05842    return ms + ts;
05843 }
05844 
05845 static unsigned int calc_timestamp(struct chan_iax2_pvt *p, unsigned int ts, struct ast_frame *f)
05846 {
05847    int ms;
05848    int voice = 0;
05849    int genuine = 0;
05850    int adjust;
05851    int rate = ast_format_rate(f->subclass.codec) / 1000;
05852    struct timeval *delivery = NULL;
05853 
05854 
05855    /* What sort of frame do we have?: voice is self-explanatory
05856       "genuine" means an IAX frame - things like LAGRQ/RP, PING/PONG, ACK
05857       non-genuine frames are CONTROL frames [ringing etc], DTMF
05858       The "genuine" distinction is needed because genuine frames must get a clock-based timestamp,
05859       the others need a timestamp slaved to the voice frames so that they go in sequence
05860    */
05861    if (f) {
05862       if (f->frametype == AST_FRAME_VOICE) {
05863          voice = 1;
05864          delivery = &f->delivery;
05865       } else if (f->frametype == AST_FRAME_IAX) {
05866          genuine = 1;
05867       } else if (f->frametype == AST_FRAME_CNG) {
05868          p->notsilenttx = 0;  
05869       }
05870    }
05871    if (ast_tvzero(p->offset)) {
05872       p->offset = ast_tvnow();
05873       /* Round to nearest 20ms for nice looking traces */
05874       p->offset.tv_usec -= p->offset.tv_usec % 20000;
05875    }
05876    /* If the timestamp is specified, just send it as is */
05877    if (ts)
05878       return ts;
05879    /* If we have a time that the frame arrived, always use it to make our timestamp */
05880    if (delivery && !ast_tvzero(*delivery)) {
05881       ms = ast_tvdiff_ms(*delivery, p->offset);
05882       if (ms < 0) {
05883          ms = 0;
05884       }
05885       if (iaxdebug)
05886          ast_debug(3, "calc_timestamp: call %d/%d: Timestamp slaved to delivery time\n", p->callno, iaxs[p->callno]->peercallno);
05887    } else {
05888       ms = ast_tvdiff_ms(ast_tvnow(), p->offset);
05889       if (ms < 0)
05890          ms = 0;
05891       if (voice) {
05892          /* On a voice frame, use predicted values if appropriate */
05893          if (p->notsilenttx && abs(ms - p->nextpred) <= MAX_TIMESTAMP_SKEW) {
05894             /* Adjust our txcore, keeping voice and non-voice synchronized */
05895             /* AN EXPLANATION:
05896                When we send voice, we usually send "calculated" timestamps worked out
05897                on the basis of the number of samples sent. When we send other frames,
05898                we usually send timestamps worked out from the real clock.
05899                The problem is that they can tend to drift out of step because the 
05900                   source channel's clock and our clock may not be exactly at the same rate.
05901                We fix this by continuously "tweaking" p->offset.  p->offset is "time zero"
05902                for this call.  Moving it adjusts timestamps for non-voice frames.
05903                We make the adjustment in the style of a moving average.  Each time we
05904                adjust p->offset by 10% of the difference between our clock-derived
05905                timestamp and the predicted timestamp.  That's why you see "10000"
05906                below even though IAX2 timestamps are in milliseconds.
05907                The use of a moving average avoids offset moving too radically.
05908                Generally, "adjust" roams back and forth around 0, with offset hardly
05909                changing at all.  But if a consistent different starts to develop it
05910                will be eliminated over the course of 10 frames (200-300msecs) 
05911             */
05912             adjust = (ms - p->nextpred);
05913             if (adjust < 0)
05914                p->offset = ast_tvsub(p->offset, ast_samp2tv(abs(adjust), 10000));
05915             else if (adjust > 0)
05916                p->offset = ast_tvadd(p->offset, ast_samp2tv(adjust, 10000));
05917 
05918             if (!p->nextpred) {
05919                p->nextpred = ms; /*f->samples / rate;*/
05920                if (p->nextpred <= p->lastsent)
05921                   p->nextpred = p->lastsent + 3;
05922             }
05923             ms = p->nextpred;
05924          } else {
05925                 /* in this case, just use the actual
05926             * time, since we're either way off
05927             * (shouldn't happen), or we're  ending a
05928             * silent period -- and seed the next
05929             * predicted time.  Also, round ms to the
05930             * next multiple of frame size (so our
05931             * silent periods are multiples of
05932             * frame size too) */
05933 
05934             if (iaxdebug && abs(ms - p->nextpred) > MAX_TIMESTAMP_SKEW )
05935                ast_debug(1, "predicted timestamp skew (%u) > max (%u), using real ts instead.\n",
05936                   abs(ms - p->nextpred), MAX_TIMESTAMP_SKEW);
05937 
05938             if (f->samples >= rate) /* check to make sure we don't core dump */
05939             {
05940                int diff = ms % (f->samples / rate);
05941                if (diff)
05942                    ms += f->samples/rate - diff;
05943             }
05944 
05945             p->nextpred = ms;
05946             p->notsilenttx = 1;
05947          }
05948       } else if ( f->frametype == AST_FRAME_VIDEO ) {
05949          /*
05950          * IAX2 draft 03 says that timestamps MUST be in order.
05951          * It does not say anything about several frames having the same timestamp
05952          * When transporting video, we can have a frame that spans multiple iax packets
05953          * (so called slices), so it would make sense to use the same timestamp for all of
05954          * them
05955          * We do want to make sure that frames don't go backwards though
05956          */
05957          if ( (unsigned int)ms < p->lastsent )
05958             ms = p->lastsent;
05959       } else {
05960          /* On a dataframe, use last value + 3 (to accomodate jitter buffer shrinking) if appropriate unless
05961             it's a genuine frame */
05962          if (genuine) {
05963             /* genuine (IAX LAGRQ etc) must keep their clock-based stamps */
05964             if (ms <= p->lastsent)
05965                ms = p->lastsent + 3;
05966          } else if (abs(ms - p->lastsent) <= MAX_TIMESTAMP_SKEW) {
05967             /* non-genuine frames (!?) (DTMF, CONTROL) should be pulled into the predicted stream stamps */
05968             ms = p->lastsent + 3;
05969          }
05970       }
05971    }
05972    p->lastsent = ms;
05973    if (voice)
05974       p->nextpred = p->nextpred + f->samples / rate;
05975    return ms;
05976 }
05977 
05978 static unsigned int calc_rxstamp(struct chan_iax2_pvt *p, unsigned int offset)
05979 {
05980    /* Returns where in "receive time" we are.  That is, how many ms
05981       since we received (or would have received) the frame with timestamp 0 */
05982    int ms;
05983 #ifdef IAXTESTS
05984    int jit;
05985 #endif /* IAXTESTS */
05986    /* Setup rxcore if necessary */
05987    if (ast_tvzero(p->rxcore)) {
05988       p->rxcore = ast_tvnow();
05989       if (iaxdebug)
05990          ast_debug(1, "calc_rxstamp: call=%d: rxcore set to %d.%6.6d - %dms\n",
05991                p->callno, (int)(p->rxcore.tv_sec), (int)(p->rxcore.tv_usec), offset);
05992       p->rxcore = ast_tvsub(p->rxcore, ast_samp2tv(offset, 1000));
05993 #if 1
05994       if (iaxdebug)
05995          ast_debug(1, "calc_rxstamp: call=%d: works out as %d.%6.6d\n",
05996                p->callno, (int)(p->rxcore.tv_sec),(int)( p->rxcore.tv_usec));
05997 #endif
05998    }
05999 
06000    ms = ast_tvdiff_ms(ast_tvnow(), p->rxcore);
06001 #ifdef IAXTESTS
06002    if (test_jit) {
06003       if (!test_jitpct || ((100.0 * ast_random() / (RAND_MAX + 1.0)) < test_jitpct)) {
06004          jit = (int)((float)test_jit * ast_random() / (RAND_MAX + 1.0));
06005          if ((int)(2.0 * ast_random() / (RAND_MAX + 1.0)))
06006             jit = -jit;
06007          ms += jit;
06008       }
06009    }
06010    if (test_late) {
06011       ms += test_late;
06012       test_late = 0;
06013    }
06014 #endif /* IAXTESTS */
06015    return ms;
06016 }
06017 
06018 static struct iax2_trunk_peer *find_tpeer(struct sockaddr_in *sin, int fd)
06019 {
06020    struct iax2_trunk_peer *tpeer = NULL;
06021    
06022    /* Finds and locks trunk peer */
06023    AST_LIST_LOCK(&tpeers);
06024 
06025    AST_LIST_TRAVERSE(&tpeers, tpeer, list) {
06026       if (!inaddrcmp(&tpeer->addr, sin)) {
06027          ast_mutex_lock(&tpeer->lock);
06028          break;
06029       }
06030    }
06031 
06032    if (!tpeer) {
06033       if ((tpeer = ast_calloc(1, sizeof(*tpeer)))) {
06034          ast_mutex_init(&tpeer->lock);
06035          tpeer->lastsent = 9999;
06036          memcpy(&tpeer->addr, sin, sizeof(tpeer->addr));
06037          tpeer->trunkact = ast_tvnow();
06038          ast_mutex_lock(&tpeer->lock);
06039          tpeer->sockfd = fd;
06040 #ifdef SO_NO_CHECK
06041          setsockopt(tpeer->sockfd, SOL_SOCKET, SO_NO_CHECK, &nochecksums, sizeof(nochecksums));
06042 #endif
06043          ast_debug(1, "Created trunk peer for '%s:%d'\n", ast_inet_ntoa(tpeer->addr.sin_addr), ntohs(tpeer->addr.sin_port));
06044          AST_LIST_INSERT_TAIL(&tpeers, tpeer, list);
06045       }
06046    }
06047 
06048    AST_LIST_UNLOCK(&tpeers);
06049 
06050    return tpeer;
06051 }
06052 
06053 static int iax2_trunk_queue(struct chan_iax2_pvt *pvt, struct iax_frame *fr)
06054 {
06055    struct ast_frame *f;
06056    struct iax2_trunk_peer *tpeer;
06057    void *tmp, *ptr;
06058    struct timeval now;
06059    int res; 
06060    struct ast_iax2_meta_trunk_entry *met;
06061    struct ast_iax2_meta_trunk_mini *mtm;
06062 
06063    f = &fr->af;
06064    tpeer = find_tpeer(&pvt->addr, pvt->sockfd);
06065    if (tpeer) {
06066       if (tpeer->trunkdatalen + f->datalen + 4 >= tpeer->trunkdataalloc) {
06067          /* Need to reallocate space */
06068          if (tpeer->trunkdataalloc < trunkmaxsize) {
06069             if (!(tmp = ast_realloc(tpeer->trunkdata, tpeer->trunkdataalloc + DEFAULT_TRUNKDATA + IAX2_TRUNK_PREFACE))) {
06070                ast_mutex_unlock(&tpeer->lock);
06071                return -1;
06072             }
06073             
06074             tpeer->trunkdataalloc += DEFAULT_TRUNKDATA;
06075             tpeer->trunkdata = tmp;
06076             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);
06077          } else {
06078             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));
06079             ast_mutex_unlock(&tpeer->lock);
06080             return -1;
06081          }
06082       }
06083 
06084       /* Append to meta frame */
06085       ptr = tpeer->trunkdata + IAX2_TRUNK_PREFACE + tpeer->trunkdatalen;
06086       if (ast_test_flag64(&globalflags, IAX_TRUNKTIMESTAMPS)) {
06087          mtm = (struct ast_iax2_meta_trunk_mini *)ptr;
06088          mtm->len = htons(f->datalen);
06089          mtm->mini.callno = htons(pvt->callno);
06090          mtm->mini.ts = htons(0xffff & fr->ts);
06091          ptr += sizeof(struct ast_iax2_meta_trunk_mini);
06092          tpeer->trunkdatalen += sizeof(struct ast_iax2_meta_trunk_mini);
06093       } else {
06094          met = (struct ast_iax2_meta_trunk_entry *)ptr;
06095          /* Store call number and length in meta header */
06096          met->callno = htons(pvt->callno);
06097          met->len = htons(f->datalen);
06098          /* Advance pointers/decrease length past trunk entry header */
06099          ptr += sizeof(struct ast_iax2_meta_trunk_entry);
06100          tpeer->trunkdatalen += sizeof(struct ast_iax2_meta_trunk_entry);
06101       }
06102       /* Copy actual trunk data */
06103       memcpy(ptr, f->data.ptr, f->datalen);
06104       tpeer->trunkdatalen += f->datalen;
06105 
06106       tpeer->calls++;
06107 
06108       /* track the largest mtu we actually have sent */
06109       if (tpeer->trunkdatalen + f->datalen + 4 > trunk_maxmtu) 
06110          trunk_maxmtu = tpeer->trunkdatalen + f->datalen + 4 ; 
06111 
06112       /* if we have enough for a full MTU, ship it now without waiting */
06113       if (global_max_trunk_mtu > 0 && tpeer->trunkdatalen + f->datalen + 4 >= global_max_trunk_mtu) {
06114          now = ast_tvnow();
06115          res = send_trunk(tpeer, &now); 
06116          trunk_untimed ++; 
06117       }
06118 
06119       ast_mutex_unlock(&tpeer->lock);
06120    }
06121    return 0;
06122 }
06123 
06124 /* IAX2 encryption requires 16 to 32 bytes of random padding to be present
06125  * before the encryption data.  This function randomizes that data. */
06126 static void build_rand_pad(unsigned char *buf, ssize_t len)
06127 {
06128    long tmp;
06129    for (tmp = ast_random(); len > 0; tmp = ast_random()) {
06130       memcpy(buf, (unsigned char *) &tmp, (len > sizeof(tmp)) ? sizeof(tmp) : len);
06131       buf += sizeof(tmp);
06132       len -= sizeof(tmp);
06133    }
06134 }
06135 
06136 static void build_encryption_keys(const unsigned char *digest, struct chan_iax2_pvt *pvt)
06137 {
06138    build_ecx_key(digest, pvt);
06139    ast_aes_set_decrypt_key(digest, &pvt->dcx);
06140 }
06141 
06142 static void build_ecx_key(const unsigned char *digest, struct chan_iax2_pvt *pvt)
06143 {
06144    /* it is required to hold the corresponding decrypt key to our encrypt key
06145     * in the pvt struct because queued frames occasionally need to be decrypted and
06146     * re-encrypted when updated for a retransmission */
06147    build_rand_pad(pvt->semirand, sizeof(pvt->semirand));
06148    ast_aes_set_encrypt_key(digest, &pvt->ecx);
06149    ast_aes_set_decrypt_key(digest, &pvt->mydcx);
06150 }
06151 
06152 static void memcpy_decrypt(unsigned char *dst, const unsigned char *src, int len, ast_aes_decrypt_key *dcx)
06153 {
06154 #if 0
06155    /* Debug with "fake encryption" */
06156    int x;
06157    if (len % 16)
06158       ast_log(LOG_WARNING, "len should be multiple of 16, not %d!\n", len);
06159    for (x=0;x<len;x++)
06160       dst[x] = src[x] ^ 0xff;
06161 #else 
06162    unsigned char lastblock[16] = { 0 };
06163    int x;
06164    while(len > 0) {
06165       ast_aes_decrypt(src, dst, dcx);
06166       for (x=0;x<16;x++)
06167          dst[x] ^= lastblock[x];
06168       memcpy(lastblock, src, sizeof(lastblock));
06169       dst += 16;
06170       src += 16;
06171       len -= 16;
06172    }
06173 #endif
06174 }
06175 
06176 static void memcpy_encrypt(unsigned char *dst, const unsigned char *src, int len, ast_aes_encrypt_key *ecx)
06177 {
06178 #if 0
06179    /* Debug with "fake encryption" */
06180    int x;
06181    if (len % 16)
06182       ast_log(LOG_WARNING, "len should be multiple of 16, not %d!\n", len);
06183    for (x=0;x<len;x++)
06184       dst[x] = src[x] ^ 0xff;
06185 #else
06186    unsigned char curblock[16] = { 0 };
06187    int x;
06188    while(len > 0) {
06189       for (x=0;x<16;x++)
06190          curblock[x] ^= src[x];
06191       ast_aes_encrypt(curblock, dst, ecx);
06192       memcpy(curblock, dst, sizeof(curblock)); 
06193       dst += 16;
06194       src += 16;
06195       len -= 16;
06196    }
06197 #endif
06198 }
06199 
06200 static int decode_frame(ast_aes_decrypt_key *dcx, struct ast_iax2_full_hdr *fh, struct ast_frame *f, int *datalen)
06201 {
06202    int padding;
06203    unsigned char *workspace;
06204 
06205    workspace = alloca(*datalen);
06206    memset(f, 0, sizeof(*f));
06207    if (ntohs(fh->scallno) & IAX_FLAG_FULL) {
06208       struct ast_iax2_full_enc_hdr *efh = (struct ast_iax2_full_enc_hdr *)fh;
06209       if (*datalen < 16 + sizeof(struct ast_iax2_full_hdr))
06210          return -1;
06211       /* Decrypt */
06212       memcpy_decrypt(workspace, efh->encdata, *datalen - sizeof(struct ast_iax2_full_enc_hdr), dcx);
06213 
06214       padding = 16 + (workspace[15] & 0x0f);
06215       if (iaxdebug)
06216          ast_debug(1, "Decoding full frame with length %d (padding = %d) (15=%02x)\n", *datalen, padding, workspace[15]);
06217       if (*datalen < padding + sizeof(struct ast_iax2_full_hdr))
06218          return -1;
06219 
06220       *datalen -= padding;
06221       memcpy(efh->encdata, workspace + padding, *datalen - sizeof(struct ast_iax2_full_enc_hdr));
06222       f->frametype = fh->type;
06223       if (f->frametype == AST_FRAME_VIDEO) {
06224          f->subclass.codec = uncompress_subclass(fh->csub & ~0x40) | ((fh->csub >> 6) & 0x1);
06225       } else if (f->frametype == AST_FRAME_VOICE) {
06226          f->subclass.codec = uncompress_subclass(fh->csub);
06227       } else {
06228          f->subclass.integer = uncompress_subclass(fh->csub);
06229       }
06230    } else {
06231       struct ast_iax2_mini_enc_hdr *efh = (struct ast_iax2_mini_enc_hdr *)fh;
06232       if (iaxdebug)
06233          ast_debug(1, "Decoding mini with length %d\n", *datalen);
06234       if (*datalen < 16 + sizeof(struct ast_iax2_mini_hdr))
06235          return -1;
06236       /* Decrypt */
06237       memcpy_decrypt(workspace, efh->encdata, *datalen - sizeof(struct ast_iax2_mini_enc_hdr), dcx);
06238       padding = 16 + (workspace[15] & 0x0f);
06239       if (*datalen < padding + sizeof(struct ast_iax2_mini_hdr))
06240          return -1;
06241       *datalen -= padding;
06242       memcpy(efh->encdata, workspace + padding, *datalen - sizeof(struct ast_iax2_mini_enc_hdr));
06243    }
06244    return 0;
06245 }
06246 
06247 static int encrypt_frame(ast_aes_encrypt_key *ecx, struct ast_iax2_full_hdr *fh, unsigned char *poo, int *datalen)
06248 {
06249    int padding;
06250    unsigned char *workspace;
06251    workspace = alloca(*datalen + 32);
06252    if (!workspace)
06253       return -1;
06254    if (ntohs(fh->scallno) & IAX_FLAG_FULL) {
06255       struct ast_iax2_full_enc_hdr *efh = (struct ast_iax2_full_enc_hdr *)fh;
06256       if (iaxdebug)
06257          ast_debug(1, "Encoding full frame %d/%d with length %d\n", fh->type, fh->csub, *datalen);
06258       padding = 16 - ((*datalen - sizeof(struct ast_iax2_full_enc_hdr)) % 16);
06259       padding = 16 + (padding & 0xf);
06260       memcpy(workspace, poo, padding);
06261       memcpy(workspace + padding, efh->encdata, *datalen - sizeof(struct ast_iax2_full_enc_hdr));
06262       workspace[15] &= 0xf0;
06263       workspace[15] |= (padding & 0xf);
06264       if (iaxdebug)
06265          ast_debug(1, "Encoding full frame %d/%d with length %d + %d padding (15=%02x)\n", fh->type, fh->csub, *datalen, padding, workspace[15]);
06266       *datalen += padding;
06267       memcpy_encrypt(efh->encdata, workspace, *datalen - sizeof(struct ast_iax2_full_enc_hdr), ecx);
06268       if (*datalen >= 32 + sizeof(struct ast_iax2_full_enc_hdr))
06269          memcpy(poo, workspace + *datalen - 32, 32);
06270    } else {
06271       struct ast_iax2_mini_enc_hdr *efh = (struct ast_iax2_mini_enc_hdr *)fh;
06272       if (iaxdebug)
06273          ast_debug(1, "Encoding mini frame with length %d\n", *datalen);
06274       padding = 16 - ((*datalen - sizeof(struct ast_iax2_mini_enc_hdr)) % 16);
06275       padding = 16 + (padding & 0xf);
06276       memcpy(workspace, poo, padding);
06277       memcpy(workspace + padding, efh->encdata, *datalen - sizeof(struct ast_iax2_mini_enc_hdr));
06278       workspace[15] &= 0xf0;
06279       workspace[15] |= (padding & 0x0f);
06280       *datalen += padding;
06281       memcpy_encrypt(efh->encdata, workspace, *datalen - sizeof(struct ast_iax2_mini_enc_hdr), ecx);
06282       if (*datalen >= 32 + sizeof(struct ast_iax2_mini_enc_hdr))
06283          memcpy(poo, workspace + *datalen - 32, 32);
06284    }
06285    return 0;
06286 }
06287 
06288 static int decrypt_frame(int callno, struct ast_iax2_full_hdr *fh, struct ast_frame *f, int *datalen)
06289 {
06290    int res=-1;
06291    if (!ast_test_flag64(iaxs[callno], IAX_KEYPOPULATED)) {
06292       /* Search for possible keys, given secrets */
06293       struct MD5Context md5;
06294       unsigned char digest[16];
06295       char *tmppw, *stringp;
06296       
06297       tmppw = ast_strdupa(iaxs[callno]->secret);
06298       stringp = tmppw;
06299       while ((tmppw = strsep(&stringp, ";"))) {
06300          MD5Init(&md5);
06301          MD5Update(&md5, (unsigned char *)iaxs[callno]->challenge, strlen(iaxs[callno]->challenge));
06302          MD5Update(&md5, (unsigned char *)tmppw, strlen(tmppw));
06303          MD5Final(digest, &md5);
06304          build_encryption_keys(digest, iaxs[callno]);
06305          res = decode_frame(&iaxs[callno]->dcx, fh, f, datalen);
06306          if (!res) {
06307             ast_set_flag64(iaxs[callno], IAX_KEYPOPULATED);
06308             break;
06309          }
06310       }
06311    } else 
06312       res = decode_frame(&iaxs[callno]->dcx, fh, f, datalen);
06313    return res;
06314 }
06315 
06316 static int iax2_send(struct chan_iax2_pvt *pvt, struct ast_frame *f, unsigned int ts, int seqno, int now, int transfer, int final)
06317 {
06318    /* Queue a packet for delivery on a given private structure.  Use "ts" for
06319       timestamp, or calculate if ts is 0.  Send immediately without retransmission
06320       or delayed, with retransmission */
06321    struct ast_iax2_full_hdr *fh;
06322    struct ast_iax2_mini_hdr *mh;
06323    struct ast_iax2_video_hdr *vh;
06324    struct {
06325       struct iax_frame fr2;
06326       unsigned char buffer[4096];
06327    } frb;
06328    struct iax_frame *fr;
06329    int res;
06330    int sendmini=0;
06331    unsigned int lastsent;
06332    unsigned int fts;
06333 
06334    frb.fr2.afdatalen = sizeof(frb.buffer);
06335 
06336    if (!pvt) {
06337       ast_log(LOG_WARNING, "No private structure for packet?\n");
06338       return -1;
06339    }
06340    
06341    lastsent = pvt->lastsent;
06342 
06343    /* Calculate actual timestamp */
06344    fts = calc_timestamp(pvt, ts, f);
06345 
06346    /* Bail here if this is an "interp" frame; we don't want or need to send these placeholders out
06347     * (the endpoint should detect the lost packet itself).  But, we want to do this here, so that we
06348     * increment the "predicted timestamps" for voice, if we're predicting */
06349    if(f->frametype == AST_FRAME_VOICE && f->datalen == 0)
06350       return 0;
06351 #if 0
06352    ast_log(LOG_NOTICE, 
06353       "f->frametype %c= AST_FRAME_VOICE, %sencrypted, %srotation scheduled...\n",
06354       *("=!" + (f->frametype == AST_FRAME_VOICE)),
06355       IAX_CALLENCRYPTED(pvt) ? "" : "not ",
06356       pvt->keyrotateid != -1 ? "" : "no "
06357    );
06358 #endif
06359    if (pvt->keyrotateid == -1 && f->frametype == AST_FRAME_VOICE && IAX_CALLENCRYPTED(pvt)) {
06360       iax2_key_rotate(pvt);
06361    }
06362 
06363    if ((ast_test_flag64(pvt, IAX_TRUNK) || 
06364          (((fts & 0xFFFF0000L) == (lastsent & 0xFFFF0000L)) ||
06365          ((fts & 0xFFFF0000L) == ((lastsent + 0x10000) & 0xFFFF0000L))))
06366       /* High two bytes are the same on timestamp, or sending on a trunk */ &&
06367        (f->frametype == AST_FRAME_VOICE) 
06368       /* is a voice frame */ &&
06369       (f->subclass.codec == pvt->svoiceformat) 
06370       /* is the same type */ ) {
06371          /* Force immediate rather than delayed transmission */
06372          now = 1;
06373          /* Mark that mini-style frame is appropriate */
06374          sendmini = 1;
06375    }
06376    if ( f->frametype == AST_FRAME_VIDEO ) {
06377       /*
06378        * If the lower 15 bits of the timestamp roll over, or if
06379        * the video format changed then send a full frame.
06380        * Otherwise send a mini video frame
06381        */
06382       if (((fts & 0xFFFF8000L) == (pvt->lastvsent & 0xFFFF8000L)) &&
06383           ((f->subclass.codec & ~0x1LL) == pvt->svideoformat)
06384          ) {
06385          now = 1;
06386          sendmini = 1;
06387       } else {
06388          now = 0;
06389          sendmini = 0;
06390       }
06391       pvt->lastvsent = fts;
06392    }
06393    if (f->frametype == AST_FRAME_IAX) {
06394       /* 0x8000 marks this message as TX:, this bit will be stripped later */
06395       pvt->last_iax_message = f->subclass.integer | MARK_IAX_SUBCLASS_TX;
06396       if (!pvt->first_iax_message) {
06397          pvt->first_iax_message = pvt->last_iax_message;
06398       }
06399    }
06400    /* Allocate an iax_frame */
06401    if (now) {
06402       fr = &frb.fr2;
06403    } else
06404       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));
06405    if (!fr) {
06406       ast_log(LOG_WARNING, "Out of memory\n");
06407       return -1;
06408    }
06409    /* Copy our prospective frame into our immediate or retransmitted wrapper */
06410    iax_frame_wrap(fr, f);
06411 
06412    fr->ts = fts;
06413    fr->callno = pvt->callno;
06414    fr->transfer = transfer;
06415    fr->final = final;
06416    fr->encmethods = 0;
06417    if (!sendmini) {
06418       /* We need a full frame */
06419       if (seqno > -1)
06420          fr->oseqno = seqno;
06421       else
06422          fr->oseqno = pvt->oseqno++;
06423       fr->iseqno = pvt->iseqno;
06424       fh = (struct ast_iax2_full_hdr *)(fr->af.data.ptr - sizeof(struct ast_iax2_full_hdr));
06425       fh->scallno = htons(fr->callno | IAX_FLAG_FULL);
06426       fh->ts = htonl(fr->ts);
06427       fh->oseqno = fr->oseqno;
06428       if (transfer) {
06429          fh->iseqno = 0;
06430       } else
06431          fh->iseqno = fr->iseqno;
06432       /* Keep track of the last thing we've acknowledged */
06433       if (!transfer)
06434          pvt->aseqno = fr->iseqno;
06435       fh->type = fr->af.frametype & 0xFF;
06436 
06437       if (fr->af.frametype == AST_FRAME_VIDEO) {
06438          fh->csub = compress_subclass(fr->af.subclass.codec & ~0x1LL) | ((fr->af.subclass.codec & 0x1LL) << 6);
06439       } else if (fr->af.frametype == AST_FRAME_VOICE) {
06440          fh->csub = compress_subclass(fr->af.subclass.codec);
06441       } else {
06442          fh->csub = compress_subclass(fr->af.subclass.integer);
06443       }
06444 
06445       if (transfer) {
06446          fr->dcallno = pvt->transfercallno;
06447       } else
06448          fr->dcallno = pvt->peercallno;
06449       fh->dcallno = htons(fr->dcallno);
06450       fr->datalen = fr->af.datalen + sizeof(struct ast_iax2_full_hdr);
06451       fr->data = fh;
06452       fr->retries = 0;
06453       /* Retry after 2x the ping time has passed */
06454       fr->retrytime = pvt->pingtime * 2;
06455       if (fr->retrytime < MIN_RETRY_TIME)
06456          fr->retrytime = MIN_RETRY_TIME;
06457       if (fr->retrytime > MAX_RETRY_TIME)
06458          fr->retrytime = MAX_RETRY_TIME;
06459       /* Acks' don't get retried */
06460       if ((f->frametype == AST_FRAME_IAX) && (f->subclass.integer == IAX_COMMAND_ACK))
06461          fr->retries = -1;
06462       else if (f->frametype == AST_FRAME_VOICE)
06463          pvt->svoiceformat = f->subclass.codec;
06464       else if (f->frametype == AST_FRAME_VIDEO)
06465          pvt->svideoformat = f->subclass.codec & ~0x1LL;
06466       if (ast_test_flag64(pvt, IAX_ENCRYPTED)) {
06467          if (ast_test_flag64(pvt, IAX_KEYPOPULATED)) {
06468             if (fr->transfer)
06469                iax_outputframe(fr, NULL, 2, &pvt->transfer, fr->datalen - sizeof(struct ast_iax2_full_hdr));
06470             else
06471                iax_outputframe(fr, NULL, 2, &pvt->addr, fr->datalen - sizeof(struct ast_iax2_full_hdr));
06472             encrypt_frame(&pvt->ecx, fh, pvt->semirand, &fr->datalen);
06473             fr->encmethods = pvt->encmethods;
06474             fr->ecx = pvt->ecx;
06475             fr->mydcx = pvt->mydcx;
06476             memcpy(fr->semirand, pvt->semirand, sizeof(fr->semirand));
06477          } else
06478             ast_log(LOG_WARNING, "Supposed to send packet encrypted, but no key?\n");
06479       }
06480 
06481       if (now) {
06482          res = send_packet(fr);
06483       } else
06484          res = iax2_transmit(fr);
06485    } else {
06486       if (ast_test_flag64(pvt, IAX_TRUNK)) {
06487          iax2_trunk_queue(pvt, fr);
06488          res = 0;
06489       } else if (fr->af.frametype == AST_FRAME_VIDEO) {
06490          /* Video frame have no sequence number */
06491          fr->oseqno = -1;
06492          fr->iseqno = -1;
06493          vh = (struct ast_iax2_video_hdr *)(fr->af.data.ptr - sizeof(struct ast_iax2_video_hdr));
06494          vh->zeros = 0;
06495          vh->callno = htons(0x8000 | fr->callno);
06496          vh->ts = htons((fr->ts & 0x7FFF) | (fr->af.subclass.codec & 0x1LL ? 0x8000 : 0));
06497          fr->datalen = fr->af.datalen + sizeof(struct ast_iax2_video_hdr);
06498          fr->data = vh;
06499          fr->retries = -1;
06500          res = send_packet(fr);
06501       } else {
06502          /* Mini-frames have no sequence number */
06503          fr->oseqno = -1;
06504          fr->iseqno = -1;
06505          /* Mini frame will do */
06506          mh = (struct ast_iax2_mini_hdr *)(fr->af.data.ptr - sizeof(struct ast_iax2_mini_hdr));
06507          mh->callno = htons(fr->callno);
06508          mh->ts = htons(fr->ts & 0xFFFF);
06509          fr->datalen = fr->af.datalen + sizeof(struct ast_iax2_mini_hdr);
06510          fr->data = mh;
06511          fr->retries = -1;
06512          if (pvt->transferring == TRANSFER_MEDIAPASS)
06513             fr->transfer = 1;
06514          if (ast_test_flag64(pvt, IAX_ENCRYPTED)) {
06515             if (ast_test_flag64(pvt, IAX_KEYPOPULATED)) {
06516                encrypt_frame(&pvt->ecx, (struct ast_iax2_full_hdr *)mh, pvt->semirand, &fr->datalen);
06517             } else
06518                ast_log(LOG_WARNING, "Supposed to send packet encrypted, but no key?\n");
06519          }
06520          res = send_packet(fr);
06521       }
06522    }
06523    return res;
06524 }
06525 
06526 static char *handle_cli_iax2_show_users(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
06527 {
06528    regex_t regexbuf;
06529    int havepattern = 0;
06530 
06531 #define FORMAT "%-15.15s  %-20.20s  %-15.15s  %-15.15s  %-5.5s  %-5.10s\n"
06532 #define FORMAT2 "%-15.15s  %-20.20s  %-15.15d  %-15.15s  %-5.5s  %-5.10s\n"
06533 
06534    struct iax2_user *user = NULL;
06535    char auth[90];
06536    char *pstr = "";
06537    struct ao2_iterator i;
06538 
06539    switch (cmd) {
06540    case CLI_INIT:
06541       e->command = "iax2 show users [like]";
06542       e->usage =
06543          "Usage: iax2 show users [like <pattern>]\n"
06544          "       Lists all known IAX2 users.\n"
06545          "       Optional regular expression pattern is used to filter the user list.\n";
06546       return NULL;
06547    case CLI_GENERATE:
06548       return NULL;
06549    }
06550 
06551    switch (a->argc) {
06552    case 5:
06553       if (!strcasecmp(a->argv[3], "like")) {
06554          if (regcomp(&regexbuf, a->argv[4], REG_EXTENDED | REG_NOSUB))
06555             return CLI_SHOWUSAGE;
06556          havepattern = 1;
06557       } else
06558          return CLI_SHOWUSAGE;
06559    case 3:
06560       break;
06561    default:
06562       return CLI_SHOWUSAGE;
06563    }
06564 
06565    ast_cli(a->fd, FORMAT, "Username", "Secret", "Authen", "Def.Context", "A/C","Codec Pref");
06566    i = ao2_iterator_init(users, 0);
06567    for (user = ao2_iterator_next(&i); user; 
06568       user_unref(user), user = ao2_iterator_next(&i)) {
06569       if (havepattern && regexec(&regexbuf, user->name, 0, NULL, 0))
06570          continue;
06571 
06572       if (!ast_strlen_zero(user->secret)) {
06573          ast_copy_string(auth,user->secret, sizeof(auth));
06574       } else if (!ast_strlen_zero(user->inkeys)) {
06575          snprintf(auth, sizeof(auth), "Key: %-15.15s ", user->inkeys);
06576       } else
06577          ast_copy_string(auth, "-no secret-", sizeof(auth));
06578 
06579       if(ast_test_flag64(user, IAX_CODEC_NOCAP))
06580          pstr = "REQ Only";
06581       else if(ast_test_flag64(user, IAX_CODEC_NOPREFS))
06582          pstr = "Disabled";
06583       else
06584          pstr = ast_test_flag64(user, IAX_CODEC_USER_FIRST) ? "Caller" : "Host";
06585 
06586       ast_cli(a->fd, FORMAT2, user->name, auth, user->authmethods, 
06587          user->contexts ? user->contexts->context : DEFAULT_CONTEXT,
06588          user->ha ? "Yes" : "No", pstr);
06589    }
06590    ao2_iterator_destroy(&i);
06591 
06592    if (havepattern)
06593       regfree(&regexbuf);
06594 
06595    return CLI_SUCCESS;
06596 #undef FORMAT
06597 #undef FORMAT2
06598 }
06599 
06600 static int __iax2_show_peers(int fd, int *total, struct mansession *s, const int argc, const char * const argv[])
06601 {
06602    regex_t regexbuf;
06603    int havepattern = 0;
06604    int total_peers = 0;
06605    int online_peers = 0;
06606    int offline_peers = 0;
06607    int unmonitored_peers = 0;
06608    struct ao2_iterator i;
06609 
06610 #define FORMAT2 "%-15.15s  %-15.15s %s  %-15.15s  %-8s  %s %-10s\n"
06611 #define FORMAT "%-15.15s  %-15.15s %s  %-15.15s  %-5d%s  %s %-10s\n"
06612 
06613    struct iax2_peer *peer = NULL;
06614    char name[256];
06615    struct ast_str *encmethods = ast_str_alloca(256);
06616    int registeredonly=0;
06617    char idtext[256] = "";
06618    switch (argc) {
06619    case 6:
06620       if (!strcasecmp(argv[3], "registered"))
06621          registeredonly = 1;
06622       else
06623          return RESULT_SHOWUSAGE;
06624       if (!strcasecmp(argv[4], "like")) {
06625          if (regcomp(&regexbuf, argv[5], REG_EXTENDED | REG_NOSUB))
06626             return RESULT_SHOWUSAGE;
06627          havepattern = 1;
06628       } else
06629          return RESULT_SHOWUSAGE;
06630       break;
06631    case 5:
06632       if (!strcasecmp(argv[3], "like")) {
06633          if (regcomp(&regexbuf, argv[4], REG_EXTENDED | REG_NOSUB))
06634             return RESULT_SHOWUSAGE;
06635          havepattern = 1;
06636       } else
06637          return RESULT_SHOWUSAGE;
06638       break;
06639    case 4:
06640       if (!strcasecmp(argv[3], "registered"))
06641          registeredonly = 1;
06642       else
06643          return RESULT_SHOWUSAGE;
06644       break;
06645    case 3:
06646       break;
06647    default:
06648       return RESULT_SHOWUSAGE;
06649    }
06650 
06651 
06652    if (!s)
06653       ast_cli(fd, FORMAT2, "Name/Username", "Host", "   ", "Mask", "Port", "   ", "Status");
06654 
06655    i = ao2_iterator_init(peers, 0);
06656    for (peer = ao2_iterator_next(&i); peer;
06657       peer_unref(peer), peer = ao2_iterator_next(&i)) {
06658       char nm[20];
06659       char status[20];
06660       int retstatus;
06661       struct sockaddr_in peer_addr;
06662 
06663       ast_sockaddr_to_sin(&peer->addr, &peer_addr);
06664 
06665       if (registeredonly && !peer_addr.sin_addr.s_addr) {
06666          continue;
06667       }
06668       if (havepattern && regexec(&regexbuf, peer->name, 0, NULL, 0)) {
06669          continue;
06670       }
06671 
06672       if (!ast_strlen_zero(peer->username))
06673          snprintf(name, sizeof(name), "%s/%s", peer->name, peer->username);
06674       else
06675          ast_copy_string(name, peer->name, sizeof(name));
06676 
06677       encmethods_to_str(peer->encmethods, encmethods);
06678       retstatus = peer_status(peer, status, sizeof(status));
06679       if (retstatus > 0)
06680          online_peers++;
06681       else if (!retstatus)
06682          offline_peers++;
06683       else
06684          unmonitored_peers++;
06685 
06686       ast_copy_string(nm, ast_inet_ntoa(peer->mask), sizeof(nm));
06687 
06688       if (s) {
06689          astman_append(s,
06690             "Event: PeerEntry\r\n%s"
06691             "Channeltype: IAX2\r\n"
06692             "ObjectName: %s\r\n"
06693             "ChanObjectType: peer\r\n"
06694             "IPaddress: %s\r\n"
06695             "IPport: %d\r\n"
06696             "Dynamic: %s\r\n"
06697             "Trunk: %s\r\n"
06698             "Encryption: %s\r\n"
06699             "Status: %s\r\n\r\n",
06700             idtext,
06701             name,
06702             ast_sockaddr_stringify_addr(&peer->addr),
06703             ast_sockaddr_port(&peer->addr),
06704             ast_test_flag64(peer, IAX_DYNAMIC) ? "yes" : "no",
06705             ast_test_flag64(peer, IAX_TRUNK) ? "yes" : "no",
06706             peer->encmethods ? ast_str_buffer(encmethods) : "no",
06707             status);
06708       } else {
06709          ast_cli(fd, FORMAT, name,
06710             ast_sockaddr_stringify_addr(&peer->addr),
06711             ast_test_flag64(peer, IAX_DYNAMIC) ? "(D)" : "(S)",
06712             nm,
06713             ast_sockaddr_port(&peer->addr),
06714             ast_test_flag64(peer, IAX_TRUNK) ? "(T)" : "   ",
06715             peer->encmethods ? "(E)" : "   ",
06716             status);
06717       }
06718       total_peers++;
06719    }
06720    ao2_iterator_destroy(&i);
06721 
06722    if (!s)
06723       ast_cli(fd,"%d iax2 peers [%d online, %d offline, %d unmonitored]\n",
06724          total_peers, online_peers, offline_peers, unmonitored_peers);
06725 
06726    if (havepattern)
06727       regfree(&regexbuf);
06728 
06729    if (total)
06730       *total = total_peers;
06731 
06732    return RESULT_SUCCESS;
06733 #undef FORMAT
06734 #undef FORMAT2
06735 }
06736 
06737 static char *handle_cli_iax2_show_threads(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
06738 {
06739    struct iax2_thread *thread = NULL;
06740    time_t t;
06741    int threadcount = 0, dynamiccount = 0;
06742    char type;
06743 
06744    switch (cmd) {
06745    case CLI_INIT:
06746       e->command = "iax2 show threads";
06747       e->usage =
06748          "Usage: iax2 show threads\n"
06749          "       Lists status of IAX helper threads\n";
06750       return NULL;
06751    case CLI_GENERATE:
06752       return NULL;
06753    }
06754    if (a->argc != 3)
06755       return CLI_SHOWUSAGE;
06756       
06757    ast_cli(a->fd, "IAX2 Thread Information\n");
06758    time(&t);
06759    ast_cli(a->fd, "Idle Threads:\n");
06760    AST_LIST_LOCK(&idle_list);
06761    AST_LIST_TRAVERSE(&idle_list, thread, list) {
06762 #ifdef DEBUG_SCHED_MULTITHREAD
06763       ast_cli(a->fd, "Thread %d: state=%d, update=%d, actions=%d, func='%s'\n", 
06764          thread->threadnum, thread->iostate, (int)(t - thread->checktime), thread->actions, thread->curfunc);
06765 #else
06766       ast_cli(a->fd, "Thread %d: state=%d, update=%d, actions=%d\n", 
06767          thread->threadnum, thread->iostate, (int)(t - thread->checktime), thread->actions);
06768 #endif
06769       threadcount++;
06770    }
06771    AST_LIST_UNLOCK(&idle_list);
06772    ast_cli(a->fd, "Active Threads:\n");
06773    AST_LIST_LOCK(&active_list);
06774    AST_LIST_TRAVERSE(&active_list, thread, list) {
06775       if (thread->type == IAX_THREAD_TYPE_DYNAMIC)
06776          type = 'D';
06777       else
06778          type = 'P';
06779 #ifdef DEBUG_SCHED_MULTITHREAD
06780       ast_cli(a->fd, "Thread %c%d: state=%d, update=%d, actions=%d, func='%s'\n", 
06781          type, thread->threadnum, thread->iostate, (int)(t - thread->checktime), thread->actions, thread->curfunc);
06782 #else
06783       ast_cli(a->fd, "Thread %c%d: state=%d, update=%d, actions=%d\n", 
06784          type, thread->threadnum, thread->iostate, (int)(t - thread->checktime), thread->actions);
06785 #endif
06786       threadcount++;
06787    }
06788    AST_LIST_UNLOCK(&active_list);
06789    ast_cli(a->fd, "Dynamic Threads:\n");
06790    AST_LIST_LOCK(&dynamic_list);
06791    AST_LIST_TRAVERSE(&dynamic_list, thread, list) {
06792 #ifdef DEBUG_SCHED_MULTITHREAD
06793       ast_cli(a->fd, "Thread %d: state=%d, update=%d, actions=%d, func='%s'\n",
06794          thread->threadnum, thread->iostate, (int)(t - thread->checktime), thread->actions, thread->curfunc);
06795 #else
06796       ast_cli(a->fd, "Thread %d: state=%d, update=%d, actions=%d\n",
06797          thread->threadnum, thread->iostate, (int)(t - thread->checktime), thread->actions);
06798 #endif
06799       dynamiccount++;
06800    }
06801    AST_LIST_UNLOCK(&dynamic_list);
06802    ast_cli(a->fd, "%d of %d threads accounted for with %d dynamic threads\n", threadcount, iaxthreadcount, dynamiccount);
06803    return CLI_SUCCESS;
06804 }
06805 
06806 static char *handle_cli_iax2_unregister(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
06807 {
06808    struct iax2_peer *p;
06809 
06810    switch (cmd) {
06811    case CLI_INIT:
06812       e->command = "iax2 unregister";
06813       e->usage =
06814          "Usage: iax2 unregister <peername>\n"
06815          "       Unregister (force expiration) an IAX2 peer from the registry.\n";
06816       return NULL;
06817    case CLI_GENERATE:
06818       return complete_iax2_unregister(a->line, a->word, a->pos, a->n);
06819    }
06820 
06821    if (a->argc != 3)
06822       return CLI_SHOWUSAGE;
06823 
06824    p = find_peer(a->argv[2], 1);
06825    if (p) {
06826       if (p->expire > 0) {
06827          struct iax2_peer tmp_peer = {
06828             .name = a->argv[2],
06829          };
06830          struct iax2_peer *peer;
06831 
06832          peer = ao2_find(peers, &tmp_peer, OBJ_POINTER);
06833          if (peer) {
06834             expire_registry(peer_ref(peer)); /* will release its own reference when done */
06835             peer_unref(peer); /* ref from ao2_find() */
06836             ast_cli(a->fd, "Peer %s unregistered\n", a->argv[2]);
06837          } else {
06838             ast_cli(a->fd, "Peer %s not found\n", a->argv[2]);
06839          }
06840       } else {
06841          ast_cli(a->fd, "Peer %s not registered\n", a->argv[2]);
06842       }
06843    } else {
06844       ast_cli(a->fd, "Peer unknown: %s. Not unregistered\n", a->argv[2]);
06845    }
06846    return CLI_SUCCESS;
06847 }
06848 
06849 static char *complete_iax2_unregister(const char *line, const char *word, int pos, int state)
06850 {
06851    int which = 0;
06852    struct iax2_peer *p = NULL;
06853    char *res = NULL;
06854    int wordlen = strlen(word);
06855 
06856    /* 0 - iax2; 1 - unregister; 2 - <peername> */
06857    if (pos == 2) {
06858       struct ao2_iterator i = ao2_iterator_init(peers, 0);
06859       while ((p = ao2_iterator_next(&i))) {
06860          if (!strncasecmp(p->name, word, wordlen) && 
06861             ++which > state && p->expire > 0) {
06862             res = ast_strdup(p->name);
06863             peer_unref(p);
06864             break;
06865          }
06866          peer_unref(p);
06867       }
06868       ao2_iterator_destroy(&i);
06869    }
06870 
06871    return res;
06872 }
06873 
06874 static char *handle_cli_iax2_show_peers(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
06875 {
06876    switch (cmd) {
06877    case CLI_INIT:
06878       e->command = "iax2 show peers";
06879       e->usage =
06880          "Usage: iax2 show peers [registered] [like <pattern>]\n"
06881          "       Lists all known IAX2 peers.\n"
06882          "       Optional 'registered' argument lists only peers with known addresses.\n"
06883          "       Optional regular expression pattern is used to filter the peer list.\n";
06884       return NULL;
06885    case CLI_GENERATE:
06886       return NULL;
06887    }
06888 
06889    switch (__iax2_show_peers(a->fd, NULL, NULL, a->argc, a->argv)) {
06890    case RESULT_SHOWUSAGE:
06891       return CLI_SHOWUSAGE;
06892    case RESULT_FAILURE:
06893       return CLI_FAILURE;
06894    default:
06895       return CLI_SUCCESS;
06896    }
06897 }
06898 
06899 static int manager_iax2_show_netstats(struct mansession *s, const struct message *m)
06900 {
06901    ast_cli_netstats(s, -1, 0);
06902    astman_append(s, "\r\n");
06903    return RESULT_SUCCESS;
06904 }
06905 
06906 static char *handle_cli_iax2_show_firmware(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
06907 {
06908    struct iax_firmware *cur = NULL;
06909 
06910    switch (cmd) {
06911    case CLI_INIT:
06912       e->command = "iax2 show firmware";
06913       e->usage =
06914          "Usage: iax2 show firmware\n"
06915          "       Lists all known IAX firmware images.\n";
06916       return NULL;
06917    case CLI_GENERATE:
06918       return NULL;
06919    }
06920 
06921    if (a->argc != 3 && a->argc != 4)
06922       return CLI_SHOWUSAGE;
06923 
06924    ast_cli(a->fd, "%-15.15s  %-15.15s %-15.15s\n", "Device", "Version", "Size");
06925    AST_LIST_LOCK(&firmwares);
06926    AST_LIST_TRAVERSE(&firmwares, cur, list) {
06927       if ((a->argc == 3) || (!strcasecmp(a->argv[3], (char *) cur->fwh->devname)))  {
06928          ast_cli(a->fd, "%-15.15s  %-15d %-15d\n", cur->fwh->devname, 
06929             ntohs(cur->fwh->version), (int)ntohl(cur->fwh->datalen));
06930       }
06931    }
06932    AST_LIST_UNLOCK(&firmwares);
06933 
06934    return CLI_SUCCESS;
06935 }
06936 
06937 /*! \brief callback to display iax peers in manager */
06938 static int manager_iax2_show_peers(struct mansession *s, const struct message *m)
06939 {
06940    static const char * const a[] = { "iax2", "show", "peers" };
06941    const char *id = astman_get_header(m,"ActionID");
06942    char idtext[256] = "";
06943    int total = 0;
06944 
06945    if (!ast_strlen_zero(id))
06946       snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
06947 
06948    astman_send_listack(s, m, "Peer status list will follow", "start");
06949         /* List the peers in separate manager events */
06950    __iax2_show_peers(-1, &total, s, 3, a);
06951         /* Send final confirmation */
06952         astman_append(s,
06953         "Event: PeerlistComplete\r\n"
06954         "EventList: Complete\r\n"
06955         "ListItems: %d\r\n"
06956         "%s"
06957         "\r\n", total, idtext);
06958         return 0;
06959 }
06960 
06961 /*! \brief callback to display iax peers in manager format */
06962 static int manager_iax2_show_peer_list(struct mansession *s, const struct message *m)
06963 {
06964    struct iax2_peer *peer = NULL;
06965    int peer_count = 0;
06966    char nm[20];
06967    char status[20];
06968    const char *id = astman_get_header(m,"ActionID");
06969    char idtext[256] = "";
06970    struct ast_str *encmethods = ast_str_alloca(256);
06971    struct ao2_iterator i;
06972 
06973    if (!ast_strlen_zero(id))
06974       snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
06975 
06976    astman_append(s, "Response: Success\r\n%sMessage: IAX Peer status list will follow\r\n\r\n", idtext);
06977 
06978 
06979    i = ao2_iterator_init(peers, 0);
06980    for (peer = ao2_iterator_next(&i); peer; peer_unref(peer), peer = ao2_iterator_next(&i)) {
06981       encmethods_to_str(peer->encmethods, encmethods);
06982       astman_append(s, "Event: PeerEntry\r\n%sChanneltype: IAX\r\n", idtext);
06983       if (!ast_strlen_zero(peer->username)) {
06984          astman_append(s, "ObjectName: %s\r\nObjectUsername: %s\r\n", peer->name, peer->username);
06985       } else {
06986          astman_append(s, "ObjectName: %s\r\n", peer->name);
06987       }
06988       astman_append(s, "ChanObjectType: peer\r\n");
06989       astman_append(s, "IPaddress: %s\r\n", ast_sockaddr_stringify_addr(&peer->addr));
06990       ast_copy_string(nm, ast_inet_ntoa(peer->mask), sizeof(nm));
06991       astman_append(s, "Mask: %s\r\n", nm);
06992       astman_append(s, "Port: %d\r\n", ast_sockaddr_port(&peer->addr));
06993       astman_append(s, "Dynamic: %s\r\n", ast_test_flag64(peer, IAX_DYNAMIC) ? "Yes" : "No");
06994       astman_append(s, "Trunk: %s\r\n", ast_test_flag64(peer, IAX_TRUNK) ? "Yes" : "No");
06995       astman_append(s, "Encryption: %s\r\n", peer->encmethods ? ast_str_buffer(encmethods) : "No");
06996       peer_status(peer, status, sizeof(status));
06997       astman_append(s, "Status: %s\r\n\r\n", status);
06998       peer_count++;
06999    }
07000    ao2_iterator_destroy(&i);
07001 
07002    astman_append(s, "Event: PeerlistComplete\r\n%sListItems: %d\r\n\r\n", idtext, peer_count);
07003    return RESULT_SUCCESS;
07004 }
07005 
07006 
07007 static char *regstate2str(int regstate)
07008 {
07009    switch(regstate) {
07010    case REG_STATE_UNREGISTERED:
07011       return "Unregistered";
07012    case REG_STATE_REGSENT:
07013       return "Request Sent";
07014    case REG_STATE_AUTHSENT:
07015       return "Auth. Sent";
07016    case REG_STATE_REGISTERED:
07017       return "Registered";
07018    case REG_STATE_REJECTED:
07019       return "Rejected";
07020    case REG_STATE_TIMEOUT:
07021       return "Timeout";
07022    case REG_STATE_NOAUTH:
07023       return "No Authentication";
07024    default:
07025       return "Unknown";
07026    }
07027 }
07028 
07029 static char *handle_cli_iax2_show_registry(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
07030 {
07031 #define FORMAT2 "%-20.20s  %-6.6s  %-10.10s  %-20.20s %8.8s  %s\n"
07032 #define FORMAT  "%-20.20s  %-6.6s  %-10.10s  %-20.20s %8d  %s\n"
07033    struct iax2_registry *reg = NULL;
07034    char host[80];
07035    char perceived[80];
07036    int counter = 0;
07037 
07038    switch (cmd) {
07039    case CLI_INIT:
07040       e->command = "iax2 show registry";
07041       e->usage =
07042          "Usage: iax2 show registry\n"
07043          "       Lists all registration requests and status.\n";
07044       return NULL;
07045    case CLI_GENERATE:
07046       return NULL;
07047    }
07048    if (a->argc != 3)
07049       return CLI_SHOWUSAGE;
07050    ast_cli(a->fd, FORMAT2, "Host", "dnsmgr", "Username", "Perceived", "Refresh", "State");
07051    AST_LIST_LOCK(&registrations);
07052    AST_LIST_TRAVERSE(&registrations, reg, entry) {
07053       snprintf(host, sizeof(host), "%s", ast_sockaddr_stringify(&reg->addr));
07054       if (reg->us.sin_addr.s_addr) 
07055          snprintf(perceived, sizeof(perceived), "%s:%d", ast_inet_ntoa(reg->us.sin_addr), ntohs(reg->us.sin_port));
07056       else
07057          ast_copy_string(perceived, "<Unregistered>", sizeof(perceived));
07058       ast_cli(a->fd, FORMAT, host, 
07059                (reg->dnsmgr) ? "Y" : "N", 
07060                reg->username, perceived, reg->refresh, regstate2str(reg->regstate));
07061       counter++;
07062    }
07063    AST_LIST_UNLOCK(&registrations);
07064    ast_cli(a->fd, "%d IAX2 registrations.\n", counter);
07065    return CLI_SUCCESS;
07066 #undef FORMAT
07067 #undef FORMAT2
07068 }
07069 
07070 static int manager_iax2_show_registry(struct mansession *s, const struct message *m)
07071 {
07072    const char *id = astman_get_header(m, "ActionID");
07073    struct iax2_registry *reg = NULL;
07074    char idtext[256] = "";
07075    char host[80] = "";
07076    char perceived[80] = "";
07077    int total = 0;
07078 
07079    if (!ast_strlen_zero(id))
07080       snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
07081 
07082    astman_send_listack(s, m, "Registrations will follow", "start");
07083 
07084    AST_LIST_LOCK(&registrations);
07085    AST_LIST_TRAVERSE(&registrations, reg, entry) {
07086       snprintf(host, sizeof(host), "%s", ast_sockaddr_stringify(&reg->addr));
07087       
07088       if (reg->us.sin_addr.s_addr) {
07089          snprintf(perceived, sizeof(perceived), "%s:%d", ast_inet_ntoa(reg->us.sin_addr), ntohs(reg->us.sin_port));
07090       } else {
07091          ast_copy_string(perceived, "<Unregistered>", sizeof(perceived));
07092       }
07093       
07094       astman_append(s,
07095          "Event: RegistryEntry\r\n"
07096          "%s"
07097          "Host: %s\r\n"
07098          "DNSmanager: %s\r\n"
07099          "Username: %s\r\n"
07100          "Perceived: %s\r\n"
07101          "Refresh: %d\r\n"
07102          "State: %s\r\n"
07103          "\r\n", idtext, host, (reg->dnsmgr) ? "Y" : "N", reg->username, perceived, 
07104          reg->refresh, regstate2str(reg->regstate));
07105 
07106       total++;
07107    }
07108    AST_LIST_UNLOCK(&registrations);
07109 
07110    astman_append(s,
07111       "Event: RegistrationsComplete\r\n"
07112       "EventList: Complete\r\n"
07113       "ListItems: %d\r\n"
07114       "%s"
07115       "\r\n", total, idtext);
07116    
07117    return 0;
07118 }
07119 
07120 static char *handle_cli_iax2_show_channels(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
07121 {
07122 #define FORMAT2 "%-20.20s  %-15.15s  %-10.10s  %-11.11s  %-11.11s  %-7.7s  %-6.6s  %-6.6s  %s  %s  %9s\n"
07123 #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"
07124 #define FORMATB "%-20.20s  %-15.15s  %-10.10s  %5.5d/%5.5d  %5.5d/%5.5d  [Native Bridged to ID=%5.5d]\n"
07125    int x;
07126    int numchans = 0;
07127    char first_message[10] = { 0, };
07128    char last_message[10] = { 0, };
07129 
07130    switch (cmd) {
07131    case CLI_INIT:
07132       e->command = "iax2 show channels";
07133       e->usage =
07134          "Usage: iax2 show channels\n"
07135          "       Lists all currently active IAX channels.\n";
07136       return NULL;
07137    case CLI_GENERATE:
07138       return NULL;
07139    }
07140 
07141    if (a->argc != 3)
07142       return CLI_SHOWUSAGE;
07143    ast_cli(a->fd, FORMAT2, "Channel", "Peer", "Username", "ID (Lo/Rem)", "Seq (Tx/Rx)", "Lag", "Jitter", "JitBuf", "Format", "FirstMsg", "LastMsg");
07144    for (x = 0; x < ARRAY_LEN(iaxs); x++) {
07145       ast_mutex_lock(&iaxsl[x]);
07146       if (iaxs[x]) {
07147          int lag, jitter, localdelay;
07148          jb_info jbinfo;
07149          if (ast_test_flag64(iaxs[x], IAX_USEJITTERBUF)) {
07150             jb_getinfo(iaxs[x]->jb, &jbinfo);
07151             jitter = jbinfo.jitter;
07152             localdelay = jbinfo.current - jbinfo.min;
07153          } else {
07154             jitter = -1;
07155             localdelay = 0;
07156          }
07157 
07158          iax_frame_subclass2str(iaxs[x]->first_iax_message & ~MARK_IAX_SUBCLASS_TX, first_message, sizeof(first_message));
07159          iax_frame_subclass2str(iaxs[x]->last_iax_message & ~MARK_IAX_SUBCLASS_TX, last_message, sizeof(last_message));
07160          lag = iaxs[x]->remote_rr.delay;
07161          ast_cli(a->fd, FORMAT,
07162             iaxs[x]->owner ? iaxs[x]->owner->name : "(None)",
07163             ast_inet_ntoa(iaxs[x]->addr.sin_addr),
07164             S_OR(iaxs[x]->username, "(None)"),
07165             iaxs[x]->callno, iaxs[x]->peercallno,
07166             iaxs[x]->oseqno, iaxs[x]->iseqno,
07167             lag,
07168             jitter,
07169             localdelay,
07170             ast_getformatname(iaxs[x]->voiceformat),
07171             (iaxs[x]->first_iax_message & MARK_IAX_SUBCLASS_TX) ? "Tx:" : "Rx:",
07172             first_message,
07173             (iaxs[x]->last_iax_message & MARK_IAX_SUBCLASS_TX) ? "Tx:" : "Rx:",
07174             last_message);
07175          numchans++;
07176       }
07177       ast_mutex_unlock(&iaxsl[x]);
07178    }
07179    ast_cli(a->fd, "%d active IAX channel%s\n", numchans, (numchans != 1) ? "s" : "");
07180    return CLI_SUCCESS;
07181 #undef FORMAT
07182 #undef FORMAT2
07183 #undef FORMATB
07184 }
07185 
07186 static int ast_cli_netstats(struct mansession *s, int fd, int limit_fmt)
07187 {
07188    int x;
07189    int numchans = 0;
07190    char first_message[10] = { 0, };
07191    char last_message[10] = { 0, };
07192 #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"
07193 #define ACN_FORMAT2 "%s %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %s%s %s%s\n"
07194    for (x = 0; x < ARRAY_LEN(iaxs); x++) {
07195       ast_mutex_lock(&iaxsl[x]);
07196       if (iaxs[x]) {
07197          int localjitter, localdelay, locallost, locallosspct, localdropped, localooo;
07198          jb_info jbinfo;
07199          iax_frame_subclass2str(iaxs[x]->first_iax_message & ~MARK_IAX_SUBCLASS_TX, first_message, sizeof(first_message));
07200          iax_frame_subclass2str(iaxs[x]->last_iax_message & ~MARK_IAX_SUBCLASS_TX, last_message, sizeof(last_message));
07201 
07202          if(ast_test_flag64(iaxs[x], IAX_USEJITTERBUF)) {
07203             jb_getinfo(iaxs[x]->jb, &jbinfo);
07204             localjitter = jbinfo.jitter;
07205             localdelay = jbinfo.current - jbinfo.min;
07206             locallost = jbinfo.frames_lost;
07207             locallosspct = jbinfo.losspct/1000;
07208             localdropped = jbinfo.frames_dropped;
07209             localooo = jbinfo.frames_ooo;
07210          } else {
07211             localjitter = -1;
07212             localdelay = 0;
07213             locallost = -1;
07214             locallosspct = -1;
07215             localdropped = 0;
07216             localooo = -1;
07217          }
07218          if (s)
07219             astman_append(s, limit_fmt ? ACN_FORMAT1 : ACN_FORMAT2,
07220                iaxs[x]->owner ? iaxs[x]->owner->name : "(None)",
07221                iaxs[x]->pingtime,
07222                localjitter,
07223                localdelay,
07224                locallost,
07225                locallosspct,
07226                localdropped,
07227                localooo,
07228                iaxs[x]->frames_received/1000,
07229                iaxs[x]->remote_rr.jitter,
07230                iaxs[x]->remote_rr.delay,
07231                iaxs[x]->remote_rr.losscnt,
07232                iaxs[x]->remote_rr.losspct,
07233                iaxs[x]->remote_rr.dropped,
07234                iaxs[x]->remote_rr.ooo,
07235                iaxs[x]->remote_rr.packets/1000,
07236                (iaxs[x]->first_iax_message & MARK_IAX_SUBCLASS_TX) ? "Tx:" : "Rx:",
07237                first_message,
07238                (iaxs[x]->last_iax_message & MARK_IAX_SUBCLASS_TX) ? "Tx:" : "Rx:",
07239                last_message);
07240          else
07241             ast_cli(fd, limit_fmt ? ACN_FORMAT1 : ACN_FORMAT2,
07242                iaxs[x]->owner ? iaxs[x]->owner->name : "(None)",
07243                iaxs[x]->pingtime,
07244                localjitter,
07245                localdelay,
07246                locallost,
07247                locallosspct,
07248                localdropped,
07249                localooo,
07250                iaxs[x]->frames_received/1000,
07251                iaxs[x]->remote_rr.jitter,
07252                iaxs[x]->remote_rr.delay,
07253                iaxs[x]->remote_rr.losscnt,
07254                iaxs[x]->remote_rr.losspct,
07255                iaxs[x]->remote_rr.dropped,
07256                iaxs[x]->remote_rr.ooo,
07257                iaxs[x]->remote_rr.packets/1000,
07258                (iaxs[x]->first_iax_message & MARK_IAX_SUBCLASS_TX) ? "Tx:" : "Rx:",
07259                first_message,
07260                (iaxs[x]->last_iax_message & MARK_IAX_SUBCLASS_TX) ? "Tx:" : "Rx:",
07261                last_message);
07262          numchans++;
07263       }
07264       ast_mutex_unlock(&iaxsl[x]);
07265    }
07266 
07267    return numchans;
07268 }
07269 
07270 static char *handle_cli_iax2_show_netstats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
07271 {
07272    int numchans = 0;
07273 
07274    switch (cmd) {
07275    case CLI_INIT:
07276       e->command = "iax2 show netstats";
07277       e->usage =
07278          "Usage: iax2 show netstats\n"
07279          "       Lists network status for all currently active IAX channels.\n";
07280       return NULL;
07281    case CLI_GENERATE:
07282       return NULL;
07283    }
07284    if (a->argc != 3)
07285       return CLI_SHOWUSAGE;
07286    ast_cli(a->fd, "                           -------- LOCAL ---------------------  -------- REMOTE --------------------\n");
07287    ast_cli(a->fd, "Channel               RTT  Jit  Del  Lost   %%  Drop  OOO  Kpkts  Jit  Del  Lost   %%  Drop  OOO  Kpkts FirstMsg    LastMsg\n");
07288    numchans = ast_cli_netstats(NULL, a->fd, 1);
07289    ast_cli(a->fd, "%d active IAX channel%s\n", numchans, (numchans != 1) ? "s" : "");
07290    return CLI_SUCCESS;
07291 }
07292 
07293 static char *handle_cli_iax2_set_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
07294 {
07295    switch (cmd) {
07296    case CLI_INIT:
07297       e->command = "iax2 set debug {on|off|peer}";
07298       e->usage =
07299          "Usage: iax2 set debug {on|off|peer peername}\n"
07300          "       Enables/Disables dumping of IAX packets for debugging purposes.\n";
07301       return NULL;
07302    case CLI_GENERATE:
07303       if (a->pos == 4 && !strcasecmp(a->argv[3], "peer"))
07304          return complete_iax2_peers(a->line, a->word, a->pos, a->n, 0);
07305       return NULL;
07306    }
07307 
07308    if (a->argc < e->args  || a->argc > e->args + 1)
07309       return CLI_SHOWUSAGE;
07310 
07311    if (!strcasecmp(a->argv[3], "peer")) {
07312       struct iax2_peer *peer;
07313       struct sockaddr_in peer_addr;
07314 
07315 
07316       if (a->argc != e->args + 1)
07317          return CLI_SHOWUSAGE;
07318 
07319       peer = find_peer(a->argv[4], 1);
07320 
07321       if (!peer) {
07322          ast_cli(a->fd, "IAX2 peer '%s' does not exist\n", a->argv[e->args-1]);
07323          return CLI_FAILURE;
07324       }
07325 
07326       ast_sockaddr_to_sin(&peer->addr, &peer_addr);
07327 
07328       debugaddr.sin_addr = peer_addr.sin_addr;
07329       debugaddr.sin_port = peer_addr.sin_port;
07330 
07331       ast_cli(a->fd, "IAX2 Debugging Enabled for IP: %s:%d\n",
07332          ast_inet_ntoa(debugaddr.sin_addr), ntohs(debugaddr.sin_port));
07333 
07334       ao2_ref(peer, -1);
07335    } else if (!strncasecmp(a->argv[3], "on", 2)) {
07336       iaxdebug = 1;
07337       ast_cli(a->fd, "IAX2 Debugging Enabled\n");
07338    } else {
07339       iaxdebug = 0;
07340       memset(&debugaddr, 0, sizeof(debugaddr));
07341       ast_cli(a->fd, "IAX2 Debugging Disabled\n");
07342    }
07343    return CLI_SUCCESS;
07344 }
07345 
07346 static char *handle_cli_iax2_set_debug_trunk(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
07347 {
07348    switch (cmd) {
07349    case CLI_INIT:
07350       e->command = "iax2 set debug trunk {on|off}";
07351       e->usage =
07352          "Usage: iax2 set debug trunk {on|off}\n"
07353          "       Enables/Disables debugging of IAX trunking\n";
07354       return NULL;
07355    case CLI_GENERATE:
07356       return NULL;
07357    }
07358 
07359    if (a->argc != e->args)
07360       return CLI_SHOWUSAGE;
07361 
07362    if (!strncasecmp(a->argv[e->args - 1], "on", 2)) {
07363       iaxtrunkdebug = 1;
07364       ast_cli(a->fd, "IAX2 Trunk Debugging Enabled\n");
07365    } else {
07366       iaxtrunkdebug = 0;
07367       ast_cli(a->fd, "IAX2 Trunk Debugging Disabled\n");
07368    }
07369    return CLI_SUCCESS;
07370 }
07371 
07372 static char *handle_cli_iax2_set_debug_jb(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
07373 {
07374    switch (cmd) {
07375    case CLI_INIT:
07376       e->command = "iax2 set debug jb {on|off}";
07377       e->usage =
07378          "Usage: iax2 set debug jb {on|off}\n"
07379          "       Enables/Disables jitterbuffer debugging information\n";
07380       return NULL;
07381    case CLI_GENERATE:
07382       return NULL;
07383    }
07384 
07385    if (a->argc != e->args)
07386       return CLI_SHOWUSAGE;
07387    
07388    if (!strncasecmp(a->argv[e->args -1], "on", 2)) {
07389       jb_setoutput(jb_error_output, jb_warning_output, jb_debug_output);
07390       ast_cli(a->fd, "IAX2 Jitterbuffer Debugging Enabled\n");
07391    } else {
07392       jb_setoutput(jb_error_output, jb_warning_output, NULL);
07393       ast_cli(a->fd, "IAX2 Jitterbuffer Debugging Disabled\n");
07394    }
07395    return CLI_SUCCESS;
07396 }
07397 
07398 static int iax2_write(struct ast_channel *c, struct ast_frame *f)
07399 {
07400    unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
07401    int res = -1;
07402    ast_mutex_lock(&iaxsl[callno]);
07403    if (iaxs[callno]) {
07404    /* If there's an outstanding error, return failure now */
07405       if (!iaxs[callno]->error) {
07406          if (ast_test_flag64(iaxs[callno], IAX_ALREADYGONE))
07407             res = 0;
07408             /* Don't waste bandwidth sending null frames */
07409          else if (f->frametype == AST_FRAME_NULL)
07410             res = 0;
07411          else if ((f->frametype == AST_FRAME_VOICE) && ast_test_flag64(iaxs[callno], IAX_QUELCH))
07412             res = 0;
07413          else if (!ast_test_flag(&iaxs[callno]->state, IAX_STATE_STARTED))
07414             res = 0;
07415          else
07416          /* Simple, just queue for transmission */
07417             res = iax2_send(iaxs[callno], f, 0, -1, 0, 0, 0);
07418       } else {
07419          ast_debug(1, "Write error: %s\n", strerror(errno));
07420       }
07421    }
07422    /* If it's already gone, just return */
07423    ast_mutex_unlock(&iaxsl[callno]);
07424    return res;
07425 }
07426 
07427 static int __send_command(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, const unsigned char *data, int datalen, int seqno, 
07428       int now, int transfer, int final)
07429 {
07430    struct ast_frame f = { 0, };
07431    int res = 0;
07432 
07433    f.frametype = type;
07434    f.subclass.integer = command;
07435    f.datalen = datalen;
07436    f.src = __FUNCTION__;
07437    f.data.ptr = (void *) data;
07438 
07439    if ((res = queue_signalling(i, &f)) <= 0) {
07440       return res;
07441    }
07442 
07443    return iax2_send(i, &f, ts, seqno, now, transfer, final);
07444 }
07445 
07446 static int send_command(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, const unsigned char *data, int datalen, int seqno)
07447 {
07448    return __send_command(i, type, command, ts, data, datalen, seqno, 0, 0, 0);
07449 }
07450 
07451 static int send_command_locked(unsigned short callno, char type, int command, unsigned int ts, const unsigned char *data, int datalen, int seqno)
07452 {
07453    int res;
07454    ast_mutex_lock(&iaxsl[callno]);
07455    res = send_command(iaxs[callno], type, command, ts, data, datalen, seqno);
07456    ast_mutex_unlock(&iaxsl[callno]);
07457    return res;
07458 }
07459 
07460 /*!
07461  * \note Since this function calls iax2_predestroy() -> iax2_queue_hangup(),
07462  *       the pvt struct for the given call number may disappear during its 
07463  *       execution.
07464  */
07465 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)
07466 {
07467    int call_num = i->callno;
07468    /* It is assumed that the callno has already been locked */
07469    iax2_predestroy(i->callno);
07470    if (!iaxs[call_num])
07471       return -1;
07472    return __send_command(i, type, command, ts, data, datalen, seqno, 0, 0, 1);
07473 }
07474 
07475 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)
07476 {
07477    return __send_command(i, type, command, ts, data, datalen, seqno, 1, 0, 0);
07478 }
07479 
07480 static int send_command_transfer(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, const unsigned char *data, int datalen)
07481 {
07482    return __send_command(i, type, command, ts, data, datalen, 0, 0, 1, 0);
07483 }
07484 
07485 static int apply_context(struct iax2_context *con, const char *context)
07486 {
07487    while(con) {
07488       if (!strcmp(con->context, context) || !strcmp(con->context, "*"))
07489          return -1;
07490       con = con->next;
07491    }
07492    return 0;
07493 }
07494 
07495 
07496 static int check_access(int callno, struct sockaddr_in *sin, struct iax_ies *ies)
07497 {
07498    /* Start pessimistic */
07499    int res = -1;
07500    int version = 2;
07501    struct iax2_user *user = NULL, *best = NULL;
07502    int bestscore = 0;
07503    int gotcapability = 0;
07504    struct ast_variable *v = NULL, *tmpvar = NULL;
07505    struct ao2_iterator i;
07506    struct ast_sockaddr addr;
07507 
07508    if (!iaxs[callno])
07509       return res;
07510    if (ies->called_number)
07511       ast_string_field_set(iaxs[callno], exten, ies->called_number);
07512    if (ies->calling_number) {
07513       if (ast_test_flag64(&globalflags, IAX_SHRINKCALLERID)) { 
07514          ast_shrink_phone_number(ies->calling_number);
07515       }
07516       ast_string_field_set(iaxs[callno], cid_num, ies->calling_number);
07517    }
07518    if (ies->calling_name)
07519       ast_string_field_set(iaxs[callno], cid_name, ies->calling_name);
07520    if (ies->calling_ani)
07521       ast_string_field_set(iaxs[callno], ani, ies->calling_ani);
07522    if (ies->dnid)
07523       ast_string_field_set(iaxs[callno], dnid, ies->dnid);
07524    if (ies->rdnis)
07525       ast_string_field_set(iaxs[callno], rdnis, ies->rdnis);
07526    if (ies->called_context)
07527       ast_string_field_set(iaxs[callno], context, ies->called_context);
07528    if (ies->language)
07529       ast_string_field_set(iaxs[callno], language, ies->language);
07530    if (ies->username)
07531       ast_string_field_set(iaxs[callno], username, ies->username);
07532    if (ies->calling_ton > -1)
07533       iaxs[callno]->calling_ton = ies->calling_ton;
07534    if (ies->calling_tns > -1)
07535       iaxs[callno]->calling_tns = ies->calling_tns;
07536    if (ies->calling_pres > -1)
07537       iaxs[callno]->calling_pres = ies->calling_pres;
07538    if (ies->format)
07539       iaxs[callno]->peerformat = ies->format;
07540    if (ies->adsicpe)
07541       iaxs[callno]->peeradsicpe = ies->adsicpe;
07542    if (ies->capability) {
07543       gotcapability = 1;
07544       iaxs[callno]->peercapability = ies->capability;
07545    } 
07546    if (ies->version)
07547       version = ies->version;
07548 
07549    /* Use provided preferences until told otherwise for actual preferences */
07550    if (ies->codec_prefs) {
07551       ast_codec_pref_convert(&iaxs[callno]->rprefs, ies->codec_prefs, 32, 0);
07552       ast_codec_pref_convert(&iaxs[callno]->prefs, ies->codec_prefs, 32, 0);
07553    }
07554 
07555    if (!gotcapability) 
07556       iaxs[callno]->peercapability = iaxs[callno]->peerformat;
07557    if (version > IAX_PROTO_VERSION) {
07558       ast_log(LOG_WARNING, "Peer '%s' has too new a protocol version (%d) for me\n", 
07559          ast_inet_ntoa(sin->sin_addr), version);
07560       return res;
07561    }
07562    /* Search the userlist for a compatible entry, and fill in the rest */
07563    i = ao2_iterator_init(users, 0);
07564    ast_sockaddr_from_sin(&addr, sin);
07565    while ((user = ao2_iterator_next(&i))) {
07566       if ((ast_strlen_zero(iaxs[callno]->username) ||          /* No username specified */
07567          !strcmp(iaxs[callno]->username, user->name)) /* Or this username specified */
07568          && ast_apply_ha(user->ha, &addr)    /* Access is permitted from this IP */
07569          && (ast_strlen_zero(iaxs[callno]->context) ||         /* No context specified */
07570               apply_context(user->contexts, iaxs[callno]->context))) {        /* Context is permitted */
07571          if (!ast_strlen_zero(iaxs[callno]->username)) {
07572             /* Exact match, stop right now. */
07573             if (best)
07574                user_unref(best);
07575             best = user;
07576             break;
07577          } else if (ast_strlen_zero(user->secret) && ast_strlen_zero(user->dbsecret) && ast_strlen_zero(user->inkeys)) {
07578             /* No required authentication */
07579             if (user->ha) {
07580                /* There was host authentication and we passed, bonus! */
07581                if (bestscore < 4) {
07582                   bestscore = 4;
07583                   if (best)
07584                      user_unref(best);
07585                   best = user;
07586                   continue;
07587                }
07588             } else {
07589                /* No host access, but no secret, either, not bad */
07590                if (bestscore < 3) {
07591                   bestscore = 3;
07592                   if (best)
07593                      user_unref(best);
07594                   best = user;
07595                   continue;
07596                }
07597             }
07598          } else {
07599             if (user->ha) {
07600                /* Authentication, but host access too, eh, it's something.. */
07601                if (bestscore < 2) {
07602                   bestscore = 2;
07603                   if (best)
07604                      user_unref(best);
07605                   best = user;
07606                   continue;
07607                }
07608             } else {
07609                /* Authentication and no host access...  This is our baseline */
07610                if (bestscore < 1) {
07611                   bestscore = 1;
07612                   if (best)
07613                      user_unref(best);
07614                   best = user;
07615                   continue;
07616                }
07617             }
07618          }
07619       }
07620       user_unref(user);
07621    }
07622    ao2_iterator_destroy(&i);
07623    user = best;
07624    if (!user && !ast_strlen_zero(iaxs[callno]->username)) {
07625       user = realtime_user(iaxs[callno]->username, sin);
07626       if (user && !ast_strlen_zero(iaxs[callno]->context) &&         /* No context specified */
07627           !apply_context(user->contexts, iaxs[callno]->context)) {      /* Context is permitted */
07628          user = user_unref(user);
07629       }
07630    }
07631    if (user) {
07632       /* We found our match (use the first) */
07633       /* copy vars */
07634       for (v = user->vars ; v ; v = v->next) {
07635          if((tmpvar = ast_variable_new(v->name, v->value, v->file))) {
07636             tmpvar->next = iaxs[callno]->vars; 
07637             iaxs[callno]->vars = tmpvar;
07638          }
07639       }
07640       /* If a max AUTHREQ restriction is in place, activate it */
07641       if (user->maxauthreq > 0)
07642          ast_set_flag64(iaxs[callno], IAX_MAXAUTHREQ);
07643       iaxs[callno]->prefs = user->prefs;
07644       ast_copy_flags64(iaxs[callno], user, IAX_CODEC_USER_FIRST | IAX_IMMEDIATE | IAX_CODEC_NOPREFS | IAX_CODEC_NOCAP | IAX_FORCE_ENCRYPT);
07645       iaxs[callno]->encmethods = user->encmethods;
07646       /* Store the requested username if not specified */
07647       if (ast_strlen_zero(iaxs[callno]->username))
07648          ast_string_field_set(iaxs[callno], username, user->name);
07649       /* Store whether this is a trunked call, too, of course, and move if appropriate */
07650       ast_copy_flags64(iaxs[callno], user, IAX_TRUNK);
07651       iaxs[callno]->capability = user->capability;
07652       /* And use the default context */
07653       if (ast_strlen_zero(iaxs[callno]->context)) {
07654          if (user->contexts)
07655             ast_string_field_set(iaxs[callno], context, user->contexts->context);
07656          else
07657             ast_string_field_set(iaxs[callno], context, DEFAULT_CONTEXT);
07658       }
07659       /* And any input keys */
07660       ast_string_field_set(iaxs[callno], inkeys, user->inkeys);
07661       /* And the permitted authentication methods */
07662       iaxs[callno]->authmethods = user->authmethods;
07663       iaxs[callno]->adsi = user->adsi;
07664       /* If the user has callerid, override the remote caller id. */
07665       if (ast_test_flag64(user, IAX_HASCALLERID)) {
07666          iaxs[callno]->calling_tns = 0;
07667          iaxs[callno]->calling_ton = 0;
07668          ast_string_field_set(iaxs[callno], cid_num, user->cid_num);
07669          ast_string_field_set(iaxs[callno], cid_name, user->cid_name);
07670          ast_string_field_set(iaxs[callno], ani, user->cid_num);
07671          iaxs[callno]->calling_pres = AST_PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN;
07672       } else if (ast_strlen_zero(iaxs[callno]->cid_num) && ast_strlen_zero(iaxs[callno]->cid_name)) {
07673          iaxs[callno]->calling_pres = AST_PRES_NUMBER_NOT_AVAILABLE;
07674       } /* else user is allowed to set their own CID settings */
07675       if (!ast_strlen_zero(user->accountcode))
07676          ast_string_field_set(iaxs[callno], accountcode, user->accountcode);
07677       if (!ast_strlen_zero(user->mohinterpret))
07678          ast_string_field_set(iaxs[callno], mohinterpret, user->mohinterpret);
07679       if (!ast_strlen_zero(user->mohsuggest))
07680          ast_string_field_set(iaxs[callno], mohsuggest, user->mohsuggest);
07681       if (!ast_strlen_zero(user->parkinglot))
07682          ast_string_field_set(iaxs[callno], parkinglot, user->parkinglot);
07683       if (user->amaflags)
07684          iaxs[callno]->amaflags = user->amaflags;
07685       if (!ast_strlen_zero(user->language))
07686          ast_string_field_set(iaxs[callno], language, user->language);
07687       ast_copy_flags64(iaxs[callno], user, IAX_NOTRANSFER | IAX_TRANSFERMEDIA | IAX_USEJITTERBUF | IAX_FORCEJITTERBUF | IAX_SENDCONNECTEDLINE | IAX_RECVCONNECTEDLINE); 
07688       /* Keep this check last */
07689       if (!ast_strlen_zero(user->dbsecret)) {
07690          char *family, *key=NULL;
07691          char buf[80];
07692          family = ast_strdupa(user->dbsecret);
07693          key = strchr(family, '/');
07694          if (key) {
07695             *key = '\0';
07696             key++;
07697          }
07698          if (!key || ast_db_get(family, key, buf, sizeof(buf)))
07699             ast_log(LOG_WARNING, "Unable to retrieve database password for family/key '%s'!\n", user->dbsecret);
07700          else
07701             ast_string_field_set(iaxs[callno], secret, buf);
07702       } else
07703          ast_string_field_set(iaxs[callno], secret, user->secret);
07704       res = 0;
07705       user = user_unref(user);
07706    } else {
07707        /* user was not found, but we should still fake an AUTHREQ.
07708         * Set authmethods to the last known authmethod used by the system
07709         * Set a fake secret, it's not looked at, just required to attempt authentication.
07710         * Set authrej so the AUTHREP is rejected without even looking at its contents */
07711       iaxs[callno]->authmethods = last_authmethod ? last_authmethod : (IAX_AUTH_MD5 | IAX_AUTH_PLAINTEXT);
07712       ast_string_field_set(iaxs[callno], secret, "badsecret");
07713       iaxs[callno]->authrej = 1;
07714       if (!ast_strlen_zero(iaxs[callno]->username)) {
07715          /* only send the AUTHREQ if a username was specified. */
07716          res = 0;
07717       }
07718    }
07719    ast_set2_flag64(iaxs[callno], iax2_getpeertrunk(*sin), IAX_TRUNK);
07720    return res;
07721 }
07722 
07723 static int raw_hangup(struct sockaddr_in *sin, unsigned short src, unsigned short dst, int sockfd)
07724 {
07725    struct ast_iax2_full_hdr fh;
07726    fh.scallno = htons(src | IAX_FLAG_FULL);
07727    fh.dcallno = htons(dst);
07728    fh.ts = 0;
07729    fh.oseqno = 0;
07730    fh.iseqno = 0;
07731    fh.type = AST_FRAME_IAX;
07732    fh.csub = compress_subclass(IAX_COMMAND_INVAL);
07733    iax_outputframe(NULL, &fh, 0, sin, 0);
07734 #if 0
07735    if (option_debug)
07736 #endif   
07737       ast_debug(1, "Raw Hangup %s:%d, src=%d, dst=%d\n",
07738          ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port), src, dst);
07739    return sendto(sockfd, &fh, sizeof(fh), 0, (struct sockaddr *)sin, sizeof(*sin));
07740 }
07741 
07742 static void merge_encryption(struct chan_iax2_pvt *p, unsigned int enc)
07743 {
07744    /* Select exactly one common encryption if there are any */
07745    p->encmethods &= enc;
07746    if (p->encmethods) {
07747       if (!(p->encmethods & IAX_ENCRYPT_KEYROTATE)){ /* if key rotation is not supported, turn off keyrotation. */
07748          p->keyrotateid = -2;
07749       }
07750       if (p->encmethods & IAX_ENCRYPT_AES128)
07751          p->encmethods = IAX_ENCRYPT_AES128;
07752       else
07753          p->encmethods = 0;
07754    }
07755 }
07756 
07757 /*!
07758  * \pre iaxsl[call_num] is locked
07759  *
07760  * \note Since this function calls send_command_final(), the pvt struct for the given
07761  *       call number may disappear while executing this function.
07762  */
07763 static int authenticate_request(int call_num)
07764 {
07765    struct iax_ie_data ied;
07766    int res = -1, authreq_restrict = 0;
07767    char challenge[10];
07768    struct chan_iax2_pvt *p = iaxs[call_num];
07769 
07770    memset(&ied, 0, sizeof(ied));
07771 
07772    /* If an AUTHREQ restriction is in place, make sure we can send an AUTHREQ back */
07773    if (ast_test_flag64(p, IAX_MAXAUTHREQ)) {
07774       struct iax2_user *user, tmp_user = {
07775          .name = p->username, 
07776       };
07777 
07778       user = ao2_find(users, &tmp_user, OBJ_POINTER);
07779       if (user) {
07780          if (user->curauthreq == user->maxauthreq)
07781             authreq_restrict = 1;
07782          else
07783             user->curauthreq++;
07784          user = user_unref(user);
07785       }
07786    }
07787 
07788    /* If the AUTHREQ limit test failed, send back an error */
07789    if (authreq_restrict) {
07790       iax_ie_append_str(&ied, IAX_IE_CAUSE, "Unauthenticated call limit reached");
07791       iax_ie_append_byte(&ied, IAX_IE_CAUSECODE, AST_CAUSE_CALL_REJECTED);
07792       send_command_final(p, AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied.buf, ied.pos, -1);
07793       return 0;
07794    }
07795 
07796    iax_ie_append_short(&ied, IAX_IE_AUTHMETHODS, p->authmethods);
07797    if (p->authmethods & (IAX_AUTH_MD5 | IAX_AUTH_RSA)) {
07798       snprintf(challenge, sizeof(challenge), "%d", (int)ast_random());
07799       ast_string_field_set(p, challenge, challenge);
07800       /* snprintf(p->challenge, sizeof(p->challenge), "%d", (int)ast_random()); */
07801       iax_ie_append_str(&ied, IAX_IE_CHALLENGE, p->challenge);
07802    }
07803    if (p->encmethods)
07804       iax_ie_append_short(&ied, IAX_IE_ENCRYPTION, p->encmethods);
07805 
07806    iax_ie_append_str(&ied,IAX_IE_USERNAME, p->username);
07807 
07808    res = send_command(p, AST_FRAME_IAX, IAX_COMMAND_AUTHREQ, 0, ied.buf, ied.pos, -1);
07809 
07810    if (p->encmethods)
07811       ast_set_flag64(p, IAX_ENCRYPTED);
07812 
07813    return res;
07814 }
07815 
07816 static int authenticate_verify(struct chan_iax2_pvt *p, struct iax_ies *ies)
07817 {
07818    char requeststr[256];
07819    char md5secret[256] = "";
07820    char secret[256] = "";
07821    char rsasecret[256] = "";
07822    int res = -1; 
07823    int x;
07824    struct iax2_user *user, tmp_user = {
07825       .name = p->username, 
07826    };
07827 
07828    if (p->authrej) {
07829       return res;
07830    }
07831    user = ao2_find(users, &tmp_user, OBJ_POINTER);
07832    if (user) {
07833       if (ast_test_flag64(p, IAX_MAXAUTHREQ)) {
07834          ast_atomic_fetchadd_int(&user->curauthreq, -1);
07835          ast_clear_flag64(p, IAX_MAXAUTHREQ);
07836       }
07837       ast_string_field_set(p, host, user->name);
07838       user = user_unref(user);
07839    }
07840    if (ast_test_flag64(p, IAX_FORCE_ENCRYPT) && !p->encmethods) { 
07841       ast_log(LOG_NOTICE, "Call Terminated, Incoming call is unencrypted while force encrypt is enabled.");
07842       return res;
07843    }
07844    if (!ast_test_flag(&p->state, IAX_STATE_AUTHENTICATED))
07845       return res;
07846    if (ies->password)
07847       ast_copy_string(secret, ies->password, sizeof(secret));
07848    if (ies->md5_result)
07849       ast_copy_string(md5secret, ies->md5_result, sizeof(md5secret));
07850    if (ies->rsa_result)
07851       ast_copy_string(rsasecret, ies->rsa_result, sizeof(rsasecret));
07852    if ((p->authmethods & IAX_AUTH_RSA) && !ast_strlen_zero(rsasecret) && !ast_strlen_zero(p->inkeys)) {
07853       struct ast_key *key;
07854       char *keyn;
07855       char tmpkey[256];
07856       char *stringp=NULL;
07857       ast_copy_string(tmpkey, p->inkeys, sizeof(tmpkey));
07858       stringp=tmpkey;
07859       keyn = strsep(&stringp, ":");
07860       while(keyn) {
07861          key = ast_key_get(keyn, AST_KEY_PUBLIC);
07862          if (key && !ast_check_signature(key, p->challenge, rsasecret)) {
07863             res = 0;
07864             break;
07865          } else if (!key)
07866             ast_log(LOG_WARNING, "requested inkey '%s' for RSA authentication does not exist\n", keyn);
07867          keyn = strsep(&stringp, ":");
07868       }
07869    } else if (p->authmethods & IAX_AUTH_MD5) {
07870       struct MD5Context md5;
07871       unsigned char digest[16];
07872       char *tmppw, *stringp;
07873       
07874       tmppw = ast_strdupa(p->secret);
07875       stringp = tmppw;
07876       while((tmppw = strsep(&stringp, ";"))) {
07877          MD5Init(&md5);
07878          MD5Update(&md5, (unsigned char *)p->challenge, strlen(p->challenge));
07879          MD5Update(&md5, (unsigned char *)tmppw, strlen(tmppw));
07880          MD5Final(digest, &md5);
07881          /* If they support md5, authenticate with it.  */
07882          for (x=0;x<16;x++)
07883             sprintf(requeststr + (x << 1), "%2.2x", digest[x]); /* safe */
07884          if (!strcasecmp(requeststr, md5secret)) {
07885             res = 0;
07886             break;
07887          }
07888       }
07889    } else if (p->authmethods & IAX_AUTH_PLAINTEXT) {
07890       if (!strcmp(secret, p->secret))
07891          res = 0;
07892    }
07893    return res;
07894 }
07895 
07896 /*! \brief Verify inbound registration */
07897 static int register_verify(int callno, struct sockaddr_in *sin, struct iax_ies *ies)
07898 {
07899    char requeststr[256] = "";
07900    char peer[256] = "";
07901    char md5secret[256] = "";
07902    char rsasecret[256] = "";
07903    char secret[256] = "";
07904    struct iax2_peer *p = NULL;
07905    struct ast_key *key;
07906    char *keyn;
07907    int x;
07908    int expire = 0;
07909    int res = -1;
07910    struct ast_sockaddr addr;
07911 
07912    ast_clear_flag(&iaxs[callno]->state, IAX_STATE_AUTHENTICATED);
07913    /* iaxs[callno]->peer[0] = '\0'; not necc. any more-- stringfield is pre-inited to null string */
07914    if (ies->username)
07915       ast_copy_string(peer, ies->username, sizeof(peer));
07916    if (ies->password)
07917       ast_copy_string(secret, ies->password, sizeof(secret));
07918    if (ies->md5_result)
07919       ast_copy_string(md5secret, ies->md5_result, sizeof(md5secret));
07920    if (ies->rsa_result)
07921       ast_copy_string(rsasecret, ies->rsa_result, sizeof(rsasecret));
07922    if (ies->refresh)
07923       expire = ies->refresh;
07924 
07925    if (ast_strlen_zero(peer)) {
07926       ast_log(LOG_NOTICE, "Empty registration from %s\n", ast_inet_ntoa(sin->sin_addr));
07927       return -1;
07928    }
07929 
07930    /* SLD: first call to lookup peer during registration */
07931    ast_mutex_unlock(&iaxsl[callno]);
07932    p = find_peer(peer, 1);
07933    ast_mutex_lock(&iaxsl[callno]);
07934    if (!p || !iaxs[callno]) {
07935       if (iaxs[callno]) {
07936          int plaintext = ((last_authmethod & IAX_AUTH_PLAINTEXT) | (iaxs[callno]->authmethods & IAX_AUTH_PLAINTEXT));
07937          /* Anything, as long as it's non-blank */
07938          ast_string_field_set(iaxs[callno], secret, "badsecret");
07939          /* An AUTHREQ must be sent in response to a REGREQ of an invalid peer unless
07940           * 1. A challenge already exists indicating a AUTHREQ was already sent out.
07941           * 2. A plaintext secret is present in ie as result of a previous AUTHREQ requesting it.
07942           * 3. A plaintext secret is present in the ie and the last_authmethod used by a peer happened
07943           *    to be plaintext, indicating it is an authmethod used by other peers on the system. 
07944           *
07945           * If none of these cases exist, res will be returned as 0 without authentication indicating
07946           * an AUTHREQ needs to be sent out. */
07947 
07948          if (ast_strlen_zero(iaxs[callno]->challenge) &&
07949             !(!ast_strlen_zero(secret) && plaintext)) {
07950             /* by setting res to 0, an REGAUTH will be sent */
07951             res = 0;
07952          }
07953       }
07954       if (authdebug && !p)
07955          ast_log(LOG_NOTICE, "No registration for peer '%s' (from %s)\n", peer, ast_inet_ntoa(sin->sin_addr));
07956       goto return_unref;
07957    }
07958 
07959    if (!ast_test_flag64(p, IAX_DYNAMIC)) {
07960       if (authdebug)
07961          ast_log(LOG_NOTICE, "Peer '%s' is not dynamic (from %s)\n", peer, ast_inet_ntoa(sin->sin_addr));
07962       goto return_unref;
07963    }
07964 
07965    ast_sockaddr_from_sin(&addr, sin);
07966    if (!ast_apply_ha(p->ha, &addr)) {
07967       if (authdebug)
07968          ast_log(LOG_NOTICE, "Host %s denied access to register peer '%s'\n", ast_inet_ntoa(sin->sin_addr), p->name);
07969       goto return_unref;
07970    }
07971    ast_string_field_set(iaxs[callno], secret, p->secret);
07972    ast_string_field_set(iaxs[callno], inkeys, p->inkeys);
07973    /* Check secret against what we have on file */
07974    if (!ast_strlen_zero(rsasecret) && (p->authmethods & IAX_AUTH_RSA) && !ast_strlen_zero(iaxs[callno]->challenge)) {
07975       if (!ast_strlen_zero(p->inkeys)) {
07976          char tmpkeys[256];
07977          char *stringp=NULL;
07978          ast_copy_string(tmpkeys, p->inkeys, sizeof(tmpkeys));
07979          stringp=tmpkeys;
07980          keyn = strsep(&stringp, ":");
07981          while(keyn) {
07982             key = ast_key_get(keyn, AST_KEY_PUBLIC);
07983             if (key && !ast_check_signature(key, iaxs[callno]->challenge, rsasecret)) {
07984                ast_set_flag(&iaxs[callno]->state, IAX_STATE_AUTHENTICATED);
07985                break;
07986             } else if (!key)
07987                ast_log(LOG_WARNING, "requested inkey '%s' does not exist\n", keyn);
07988             keyn = strsep(&stringp, ":");
07989          }
07990          if (!keyn) {
07991             if (authdebug)
07992                ast_log(LOG_NOTICE, "Host %s failed RSA authentication with inkeys '%s'\n", peer, p->inkeys);
07993             goto return_unref;
07994          }
07995       } else {
07996          if (authdebug)
07997             ast_log(LOG_NOTICE, "Host '%s' trying to do RSA authentication, but we have no inkeys\n", peer);
07998          goto return_unref;
07999       }
08000    } else if (!ast_strlen_zero(md5secret) && (p->authmethods & IAX_AUTH_MD5) && !ast_strlen_zero(iaxs[callno]->challenge)) {
08001       struct MD5Context md5;
08002       unsigned char digest[16];
08003       char *tmppw, *stringp;
08004 
08005       tmppw = ast_strdupa(p->secret);
08006       stringp = tmppw;
08007       while((tmppw = strsep(&stringp, ";"))) {
08008          MD5Init(&md5);
08009          MD5Update(&md5, (unsigned char *)iaxs[callno]->challenge, strlen(iaxs[callno]->challenge));
08010          MD5Update(&md5, (unsigned char *)tmppw, strlen(tmppw));
08011          MD5Final(digest, &md5);
08012          for (x=0;x<16;x++)
08013             sprintf(requeststr + (x << 1), "%2.2x", digest[x]); /* safe */
08014          if (!strcasecmp(requeststr, md5secret))
08015             break;
08016       }
08017       if (tmppw) {
08018          ast_set_flag(&iaxs[callno]->state, IAX_STATE_AUTHENTICATED);
08019       } else {
08020          if (authdebug)
08021             ast_log(LOG_NOTICE, "Host %s failed MD5 authentication for '%s' (%s != %s)\n", ast_inet_ntoa(sin->sin_addr), p->name, requeststr, md5secret);
08022          goto return_unref;
08023       }
08024    } else if (!ast_strlen_zero(secret) && (p->authmethods & IAX_AUTH_PLAINTEXT)) {
08025       /* They've provided a plain text password and we support that */
08026       if (strcmp(secret, p->secret)) {
08027          if (authdebug)
08028             ast_log(LOG_NOTICE, "Host %s did not provide proper plaintext password for '%s'\n", ast_inet_ntoa(sin->sin_addr), p->name);
08029          goto return_unref;
08030       } else
08031          ast_set_flag(&iaxs[callno]->state, IAX_STATE_AUTHENTICATED);
08032    } else if (!ast_strlen_zero(iaxs[callno]->challenge) && ast_strlen_zero(md5secret) && ast_strlen_zero(rsasecret)) {
08033       /* if challenge has been sent, but no challenge response if given, reject. */
08034       goto return_unref;
08035    }
08036    ast_devstate_changed(AST_DEVICE_UNKNOWN, "IAX2/%s", p->name); /* Activate notification */
08037 
08038    /* either Authentication has taken place, or a REGAUTH must be sent before verifying registration */
08039    res = 0;
08040 
08041 return_unref:
08042    if (iaxs[callno]) {
08043       ast_string_field_set(iaxs[callno], peer, peer);
08044 
08045       /* Choose lowest expiry number */
08046       if (expire && (expire < iaxs[callno]->expiry)) {
08047          iaxs[callno]->expiry = expire;
08048       }
08049    }
08050 
08051    if (p) {
08052       peer_unref(p);
08053    }
08054    return res;
08055 }
08056 
08057 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)
08058 {
08059    int res = -1;
08060    int x;
08061    if (!ast_strlen_zero(keyn)) {
08062       if (!(authmethods & IAX_AUTH_RSA)) {
08063          if (ast_strlen_zero(secret)) 
08064             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));
08065       } else if (ast_strlen_zero(challenge)) {
08066          ast_log(LOG_NOTICE, "No challenge provided for RSA authentication to %s\n", ast_inet_ntoa(sin->sin_addr));
08067       } else {
08068          char sig[256];
08069          struct ast_key *key;
08070          key = ast_key_get(keyn, AST_KEY_PRIVATE);
08071          if (!key) {
08072             ast_log(LOG_NOTICE, "Unable to find private key '%s'\n", keyn);
08073          } else {
08074             if (ast_sign(key, (char*)challenge, sig)) {
08075                ast_log(LOG_NOTICE, "Unable to sign challenge with key\n");
08076                res = -1;
08077             } else {
08078                iax_ie_append_str(ied, IAX_IE_RSA_RESULT, sig);
08079                res = 0;
08080             }
08081          }
08082       }
08083    } 
08084    /* Fall back */
08085    if (res && !ast_strlen_zero(secret)) {
08086       if ((authmethods & IAX_AUTH_MD5) && !ast_strlen_zero(challenge)) {
08087          struct MD5Context md5;
08088          unsigned char digest[16];
08089          char digres[128];
08090          MD5Init(&md5);
08091          MD5Update(&md5, (unsigned char *)challenge, strlen(challenge));
08092          MD5Update(&md5, (unsigned char *)secret, strlen(secret));
08093          MD5Final(digest, &md5);
08094          /* If they support md5, authenticate with it.  */
08095          for (x=0;x<16;x++)
08096             sprintf(digres + (x << 1),  "%2.2x", digest[x]); /* safe */
08097          if (pvt) {
08098             build_encryption_keys(digest, pvt);
08099          }
08100          iax_ie_append_str(ied, IAX_IE_MD5_RESULT, digres);
08101          res = 0;
08102       } else if (authmethods & IAX_AUTH_PLAINTEXT) {
08103          iax_ie_append_str(ied, IAX_IE_PASSWORD, secret);
08104          res = 0;
08105       } else
08106          ast_log(LOG_NOTICE, "No way to send secret to peer '%s' (their methods: %d)\n", ast_inet_ntoa(sin->sin_addr), authmethods);
08107    }
08108    return res;
08109 }
08110 
08111 /*!
08112  * \note This function calls realtime_peer -> reg_source_db -> iax2_poke_peer -> find_callno,
08113  *       so do not call this function with a pvt lock held.
08114  */
08115 static int authenticate_reply(struct chan_iax2_pvt *p, struct sockaddr_in *sin, struct iax_ies *ies, const char *override, const char *okey)
08116 {
08117    struct iax2_peer *peer = NULL;
08118    /* Start pessimistic */
08119    int res = -1;
08120    int authmethods = 0;
08121    struct iax_ie_data ied;
08122    uint16_t callno = p->callno;
08123 
08124    memset(&ied, 0, sizeof(ied));
08125    
08126    if (ies->username)
08127       ast_string_field_set(p, username, ies->username);
08128    if (ies->challenge)
08129       ast_string_field_set(p, challenge, ies->challenge);
08130    if (ies->authmethods)
08131       authmethods = ies->authmethods;
08132    if (authmethods & IAX_AUTH_MD5)
08133       merge_encryption(p, ies->encmethods);
08134    else
08135       p->encmethods = 0;
08136 
08137    /* Check for override RSA authentication first */
08138    if (!ast_strlen_zero(override) || !ast_strlen_zero(okey)) {
08139       /* Normal password authentication */
08140       res = authenticate(p->challenge, override, okey, authmethods, &ied, sin, p);
08141    } else {
08142       struct ao2_iterator i = ao2_iterator_init(peers, 0);
08143       while ((peer = ao2_iterator_next(&i))) {
08144          struct sockaddr_in peer_addr;
08145 
08146          ast_sockaddr_to_sin(&peer->addr, &peer_addr);
08147 
08148          if ((ast_strlen_zero(p->peer) || !strcmp(p->peer, peer->name)) 
08149              /* No peer specified at our end, or this is the peer */
08150              && (ast_strlen_zero(peer->username) || (!strcmp(peer->username, p->username)))
08151              /* No username specified in peer rule, or this is the right username */
08152              && (!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)))
08153              /* No specified host, or this is our host */
08154             ) {
08155             res = authenticate(p->challenge, peer->secret, peer->outkey, authmethods, &ied, sin, p);
08156             if (!res) {
08157                peer_unref(peer);
08158                break;
08159             }
08160          }
08161          peer_unref(peer);
08162       }
08163       ao2_iterator_destroy(&i);
08164       if (!peer) {
08165          /* We checked our list and didn't find one.  It's unlikely, but possible, 
08166             that we're trying to authenticate *to* a realtime peer */
08167          const char *peer_name = ast_strdupa(p->peer);
08168          ast_mutex_unlock(&iaxsl[callno]);
08169          if ((peer = realtime_peer(peer_name, NULL))) {
08170             ast_mutex_lock(&iaxsl[callno]);
08171             if (!(p = iaxs[callno])) {
08172                peer_unref(peer);
08173                return -1;
08174             }
08175             res = authenticate(p->challenge, peer->secret,peer->outkey, authmethods, &ied, sin, p);
08176             peer_unref(peer);
08177          }
08178          if (!peer) {
08179             ast_mutex_lock(&iaxsl[callno]);
08180             if (!(p = iaxs[callno]))
08181                return -1;
08182          }
08183       }
08184    }
08185 
08186    if (ies->encmethods) {
08187       ast_set_flag64(p, IAX_ENCRYPTED | IAX_KEYPOPULATED);
08188    } else if (ast_test_flag64(iaxs[callno], IAX_FORCE_ENCRYPT)) {
08189       ast_log(LOG_NOTICE, "Call initiated without encryption while forceencryption=yes option is set");
08190       return -1;             /* if force encryption is yes, and no encryption methods, then return -1 to hangup */
08191    }
08192    if (!res) {
08193       struct ast_datastore *variablestore;
08194       struct ast_variable *var, *prev = NULL;
08195       AST_LIST_HEAD(, ast_var_t) *varlist;
08196       varlist = ast_calloc(1, sizeof(*varlist));
08197       variablestore = ast_datastore_alloc(&iax2_variable_datastore_info, NULL);
08198       if (variablestore && varlist && p->owner) {
08199          variablestore->data = varlist;
08200          variablestore->inheritance = DATASTORE_INHERIT_FOREVER;
08201          AST_LIST_HEAD_INIT(varlist);
08202          for (var = ies->vars; var; var = var->next) {
08203             struct ast_var_t *newvar = ast_var_assign(var->name, var->value);
08204             if (prev)
08205                ast_free(prev);
08206             prev = var;
08207             if (!newvar) {
08208                /* Don't abort list traversal, as this would leave ies->vars in an inconsistent state. */
08209                ast_log(LOG_ERROR, "Memory allocation error while processing IAX2 variables\n");
08210             } else {
08211                AST_LIST_INSERT_TAIL(varlist, newvar, entries);
08212             }
08213          }
08214          if (prev)
08215             ast_free(prev);
08216          ies->vars = NULL;
08217          ast_channel_datastore_add(p->owner, variablestore);
08218       } else {
08219          if (p->owner)
08220             ast_log(LOG_ERROR, "Memory allocation error while processing IAX2 variables\n");
08221          if (variablestore)
08222             ast_datastore_free(variablestore);
08223          if (varlist)
08224             ast_free(varlist);
08225       }
08226    }
08227 
08228    if (!res)
08229       res = send_command(p, AST_FRAME_IAX, IAX_COMMAND_AUTHREP, 0, ied.buf, ied.pos, -1);
08230    return res;
08231 }
08232 
08233 static int iax2_do_register(struct iax2_registry *reg);
08234 
08235 static void __iax2_do_register_s(const void *data)
08236 {
08237    struct iax2_registry *reg = (struct iax2_registry *)data;
08238    reg->expire = -1;
08239    iax2_do_register(reg);
08240 }
08241 
08242 static int iax2_do_register_s(const void *data)
08243 {
08244 #ifdef SCHED_MULTITHREADED
08245    if (schedule_action(__iax2_do_register_s, data))
08246 #endif      
08247       __iax2_do_register_s(data);
08248    return 0;
08249 }
08250 
08251 static int try_transfer(struct chan_iax2_pvt *pvt, struct iax_ies *ies)
08252 {
08253    int newcall = 0;
08254    char newip[256];
08255    struct iax_ie_data ied;
08256    struct sockaddr_in new;
08257    
08258    
08259    memset(&ied, 0, sizeof(ied));
08260    if (ies->apparent_addr)
08261       memmove(&new, ies->apparent_addr, sizeof(new));
08262    if (ies->callno)
08263       newcall = ies->callno;
08264    if (!newcall || !new.sin_addr.s_addr || !new.sin_port) {
08265       ast_log(LOG_WARNING, "Invalid transfer request\n");
08266       return -1;
08267    }
08268    pvt->transfercallno = newcall;
08269    memcpy(&pvt->transfer, &new, sizeof(pvt->transfer));
08270    inet_aton(newip, &pvt->transfer.sin_addr);
08271    pvt->transfer.sin_family = AF_INET;
08272    pvt->transferid = ies->transferid;
08273    /* only store by transfercallno if this is a new transfer,
08274     * just in case we get a duplicate TXREQ */
08275    if (pvt->transferring == TRANSFER_NONE) {
08276       store_by_transfercallno(pvt);
08277    }
08278    pvt->transferring = TRANSFER_BEGIN;
08279 
08280    if (ies->transferid)
08281       iax_ie_append_int(&ied, IAX_IE_TRANSFERID, ies->transferid);
08282    send_command_transfer(pvt, AST_FRAME_IAX, IAX_COMMAND_TXCNT, 0, ied.buf, ied.pos);
08283    return 0;
08284 }
08285 
08286 static int complete_dpreply(struct chan_iax2_pvt *pvt, struct iax_ies *ies)
08287 {
08288    char exten[256] = "";
08289    int status = CACHE_FLAG_UNKNOWN, expiry = iaxdefaultdpcache, x, matchmore = 0;
08290    struct iax2_dpcache *dp = NULL;
08291    
08292    if (ies->called_number)
08293       ast_copy_string(exten, ies->called_number, sizeof(exten));
08294    
08295    if (ies->dpstatus & IAX_DPSTATUS_EXISTS)
08296       status = CACHE_FLAG_EXISTS;
08297    else if (ies->dpstatus & IAX_DPSTATUS_CANEXIST)
08298       status = CACHE_FLAG_CANEXIST;
08299    else if (ies->dpstatus & IAX_DPSTATUS_NONEXISTENT)
08300       status = CACHE_FLAG_NONEXISTENT;
08301 
08302    if (ies->refresh)
08303       expiry = ies->refresh;
08304    if (ies->dpstatus & IAX_DPSTATUS_MATCHMORE)
08305       matchmore = CACHE_FLAG_MATCHMORE;
08306    
08307    AST_LIST_LOCK(&dpcache);
08308    AST_LIST_TRAVERSE_SAFE_BEGIN(&dpcache, dp, peer_list) {
08309       if (strcmp(dp->exten, exten))
08310          continue;
08311       AST_LIST_REMOVE_CURRENT(peer_list);
08312       dp->callno = 0;
08313       dp->expiry.tv_sec = dp->orig.tv_sec + expiry;
08314       if (dp->flags & CACHE_FLAG_PENDING) {
08315          dp->flags &= ~CACHE_FLAG_PENDING;
08316          dp->flags |= status;
08317          dp->flags |= matchmore;
08318       }
08319       /* Wake up waiters */
08320       for (x = 0; x < ARRAY_LEN(dp->waiters); x++) {
08321          if (dp->waiters[x] > -1) {
08322             if (write(dp->waiters[x], "asdf", 4) < 0) {
08323             }
08324          }
08325       }
08326    }
08327    AST_LIST_TRAVERSE_SAFE_END;
08328    AST_LIST_UNLOCK(&dpcache);
08329 
08330    return 0;
08331 }
08332 
08333 static int complete_transfer(int callno, struct iax_ies *ies)
08334 {
08335    int peercallno = 0;
08336    struct chan_iax2_pvt *pvt = iaxs[callno];
08337    struct iax_frame *cur;
08338    jb_frame frame;
08339 
08340    if (ies->callno)
08341       peercallno = ies->callno;
08342 
08343    if (peercallno < 1) {
08344       ast_log(LOG_WARNING, "Invalid transfer request\n");
08345       return -1;
08346    }
08347    remove_by_transfercallno(pvt);
08348    /* since a transfer has taken place, the address will change.
08349     * This must be accounted for in the peercnts table.  Remove
08350     * the old address and add the new one */
08351    peercnt_remove_by_addr(&pvt->addr);
08352    peercnt_add(&pvt->transfer);
08353    /* now copy over the new address */
08354    memcpy(&pvt->addr, &pvt->transfer, sizeof(pvt->addr));
08355    memset(&pvt->transfer, 0, sizeof(pvt->transfer));
08356    /* Reset sequence numbers */
08357    pvt->oseqno = 0;
08358    pvt->rseqno = 0;
08359    pvt->iseqno = 0;
08360    pvt->aseqno = 0;
08361 
08362    if (pvt->peercallno) {
08363       remove_by_peercallno(pvt);
08364    }
08365    pvt->peercallno = peercallno;
08366    /*this is where the transfering call swiches hash tables */
08367    store_by_peercallno(pvt);
08368    pvt->transferring = TRANSFER_NONE;
08369    pvt->svoiceformat = -1;
08370    pvt->voiceformat = 0;
08371    pvt->svideoformat = -1;
08372    pvt->videoformat = 0;
08373    pvt->transfercallno = 0;
08374    memset(&pvt->rxcore, 0, sizeof(pvt->rxcore));
08375    memset(&pvt->offset, 0, sizeof(pvt->offset));
08376    /* reset jitterbuffer */
08377    while(jb_getall(pvt->jb,&frame) == JB_OK)
08378       iax2_frame_free(frame.data);
08379    jb_reset(pvt->jb);
08380    pvt->lag = 0;
08381    pvt->last = 0;
08382    pvt->lastsent = 0;
08383    pvt->nextpred = 0;
08384    pvt->pingtime = DEFAULT_RETRY_TIME;
08385    AST_LIST_TRAVERSE(&frame_queue[callno], cur, list) {
08386       /* We must cancel any packets that would have been transmitted
08387          because now we're talking to someone new.  It's okay, they
08388          were transmitted to someone that didn't care anyway. */
08389       cur->retries = -1;
08390    }
08391    return 0;
08392 }
08393 
08394 /*! \brief Acknowledgment received for OUR registration */
08395 static int iax2_ack_registry(struct iax_ies *ies, struct sockaddr_in *sin, int callno)
08396 {
08397    struct iax2_registry *reg;
08398    /* Start pessimistic */
08399    char peer[256] = "";
08400    char msgstatus[60];
08401    int refresh = 60;
08402    char ourip[256] = "<Unspecified>";
08403    struct sockaddr_in oldus;
08404    struct sockaddr_in us;
08405    int oldmsgs;
08406    struct sockaddr_in reg_addr;
08407 
08408    memset(&us, 0, sizeof(us));
08409    if (ies->apparent_addr)
08410       memmove(&us, ies->apparent_addr, sizeof(us));
08411    if (ies->username)
08412       ast_copy_string(peer, ies->username, sizeof(peer));
08413    if (ies->refresh)
08414       refresh = ies->refresh;
08415    if (ies->calling_number) {
08416       /* We don't do anything with it really, but maybe we should */
08417    }
08418    reg = iaxs[callno]->reg;
08419    if (!reg) {
08420       ast_log(LOG_WARNING, "Registry acknowledge on unknown registry '%s'\n", peer);
08421       return -1;
08422    }
08423    memcpy(&oldus, &reg->us, sizeof(oldus));
08424    oldmsgs = reg->messages;
08425    ast_sockaddr_to_sin(&reg->addr, &reg_addr);
08426    if (inaddrcmp(&reg_addr, sin)) {
08427       ast_log(LOG_WARNING, "Received unsolicited registry ack from '%s'\n", ast_inet_ntoa(sin->sin_addr));
08428       return -1;
08429    }
08430    memcpy(&reg->us, &us, sizeof(reg->us));
08431    if (ies->msgcount >= 0)
08432       reg->messages = ies->msgcount & 0xffff;      /* only low 16 bits are used in the transmission of the IE */
08433    /* always refresh the registration at the interval requested by the server
08434       we are registering to
08435    */
08436    reg->refresh = refresh;
08437    reg->expire = iax2_sched_replace(reg->expire, sched, 
08438       (5 * reg->refresh / 6) * 1000, iax2_do_register_s, reg);
08439    if (inaddrcmp(&oldus, &reg->us) || (reg->messages != oldmsgs)) {
08440          if (reg->messages > 255)
08441             snprintf(msgstatus, sizeof(msgstatus), " with %d new and %d old messages waiting", reg->messages & 0xff, reg->messages >> 8);
08442          else if (reg->messages > 1)
08443             snprintf(msgstatus, sizeof(msgstatus), " with %d new messages waiting\n", reg->messages);
08444          else if (reg->messages > 0)
08445             ast_copy_string(msgstatus, " with 1 new message waiting\n", sizeof(msgstatus));
08446          else
08447             ast_copy_string(msgstatus, " with no messages waiting\n", sizeof(msgstatus));
08448          snprintf(ourip, sizeof(ourip), "%s:%d", ast_inet_ntoa(reg->us.sin_addr), ntohs(reg->us.sin_port));
08449       ast_verb(3, "Registered IAX2 to '%s', who sees us as %s%s\n", ast_inet_ntoa(sin->sin_addr), ourip, msgstatus);
08450       manager_event(EVENT_FLAG_SYSTEM, "Registry", "ChannelType: IAX2\r\nDomain: %s\r\nStatus: Registered\r\n", ast_inet_ntoa(sin->sin_addr));
08451    }
08452    reg->regstate = REG_STATE_REGISTERED;
08453    return 0;
08454 }
08455 
08456 static int iax2_append_register(const char *hostname, const char *username,
08457    const char *secret, const char *porta)
08458 {
08459    struct iax2_registry *reg;
08460 
08461    if (!(reg = ast_calloc(1, sizeof(*reg))))
08462       return -1;
08463 
08464    if (ast_dnsmgr_lookup(hostname, &reg->addr, &reg->dnsmgr, srvlookup ? "_iax._udp" : NULL) < 0) {
08465       ast_free(reg);
08466       return -1;
08467    }
08468 
08469    ast_copy_string(reg->username, username, sizeof(reg->username));
08470 
08471    if (secret)
08472       ast_copy_string(reg->secret, secret, sizeof(reg->secret));
08473 
08474    reg->expire = -1;
08475    reg->refresh = IAX_DEFAULT_REG_EXPIRE;
08476    ast_sockaddr_set_port(&reg->addr, porta ? atoi(porta) : IAX_DEFAULT_PORTNO);
08477 
08478    AST_LIST_LOCK(&registrations);
08479    AST_LIST_INSERT_HEAD(&registrations, reg, entry);
08480    AST_LIST_UNLOCK(&registrations);
08481    
08482    return 0;
08483 }
08484 
08485 static int iax2_register(const char *value, int lineno)
08486 {
08487    char copy[256];
08488    char *username, *hostname, *secret;
08489    char *porta;
08490    char *stringp=NULL;
08491    
08492    if (!value)
08493       return -1;
08494 
08495    ast_copy_string(copy, value, sizeof(copy));
08496    stringp = copy;
08497    username = strsep(&stringp, "@");
08498    hostname = strsep(&stringp, "@");
08499 
08500    if (!hostname) {
08501       ast_log(LOG_WARNING, "Format for registration is user[:secret]@host[:port] at line %d\n", lineno);
08502       return -1;
08503    }
08504 
08505    stringp = username;
08506    username = strsep(&stringp, ":");
08507    secret = strsep(&stringp, ":");
08508    stringp = hostname;
08509    hostname = strsep(&stringp, ":");
08510    porta = strsep(&stringp, ":");
08511    
08512    if (porta && !atoi(porta)) {
08513       ast_log(LOG_WARNING, "%s is not a valid port number at line %d\n", porta, lineno);
08514       return -1;
08515    }
08516 
08517    return iax2_append_register(hostname, username, secret, porta);
08518 }
08519 
08520 
08521 static void register_peer_exten(struct iax2_peer *peer, int onoff)
08522 {
08523    char multi[256];
08524    char *stringp, *ext;
08525    if (!ast_strlen_zero(regcontext)) {
08526       ast_copy_string(multi, S_OR(peer->regexten, peer->name), sizeof(multi));
08527       stringp = multi;
08528       while((ext = strsep(&stringp, "&"))) {
08529          if (onoff) {
08530             if (!ast_exists_extension(NULL, regcontext, ext, 1, NULL))
08531                ast_add_extension(regcontext, 1, ext, 1, NULL, NULL,
08532                        "Noop", ast_strdup(peer->name), ast_free_ptr, "IAX2");
08533          } else
08534             ast_context_remove_extension(regcontext, ext, 1, NULL);
08535       }
08536    }
08537 }
08538 static void prune_peers(void);
08539 
08540 static void unlink_peer(struct iax2_peer *peer)
08541 {
08542    if (peer->expire > -1) {
08543       if (!ast_sched_thread_del(sched, peer->expire)) {
08544          peer->expire = -1;
08545          peer_unref(peer);
08546       }
08547    }
08548 
08549    if (peer->pokeexpire > -1) {
08550       if (!ast_sched_thread_del(sched, peer->pokeexpire)) {
08551          peer->pokeexpire = -1;
08552          peer_unref(peer);
08553       }
08554    }
08555 
08556    ao2_unlink(peers, peer);
08557 }
08558 
08559 static void __expire_registry(const void *data)
08560 {
08561    struct iax2_peer *peer = (struct iax2_peer *) data;
08562 
08563    if (!peer)
08564       return;
08565 
08566    peer->expire = -1;
08567 
08568    ast_debug(1, "Expiring registration for peer '%s'\n", peer->name);
08569    if (ast_test_flag64((&globalflags), IAX_RTUPDATE) && (ast_test_flag64(peer, IAX_TEMPONLY|IAX_RTCACHEFRIENDS)))
08570       realtime_update_peer(peer->name, &peer->addr, 0);
08571    manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: IAX2\r\nPeer: IAX2/%s\r\nPeerStatus: Unregistered\r\nCause: Expired\r\n", peer->name);
08572    /* modify entry in peercnts table as _not_ registered */
08573    peercnt_modify(0, 0, &peer->addr);
08574    /* Reset the address */
08575    memset(&peer->addr, 0, sizeof(peer->addr));
08576    /* Reset expiry value */
08577    peer->expiry = min_reg_expire;
08578    if (!ast_test_flag64(peer, IAX_TEMPONLY))
08579       ast_db_del("IAX/Registry", peer->name);
08580    register_peer_exten(peer, 0);
08581    ast_devstate_changed(AST_DEVICE_UNAVAILABLE, "IAX2/%s", peer->name); /* Activate notification */
08582    if (iax2_regfunk)
08583       iax2_regfunk(peer->name, 0);
08584 
08585    if (ast_test_flag64(peer, IAX_RTAUTOCLEAR))
08586       unlink_peer(peer);
08587 
08588    peer_unref(peer);
08589 }
08590 
08591 static int expire_registry(const void *data)
08592 {
08593 #ifdef SCHED_MULTITHREADED
08594    if (schedule_action(__expire_registry, data))
08595 #endif      
08596       __expire_registry(data);
08597    return 0;
08598 }
08599 
08600 static int iax2_poke_peer(struct iax2_peer *peer, int heldcall);
08601 
08602 static void reg_source_db(struct iax2_peer *p)
08603 {
08604    char data[80];
08605    char *expiry;
08606 
08607    if (ast_test_flag64(p, IAX_TEMPONLY) || ast_db_get("IAX/Registry", p->name, data, sizeof(data))) {
08608       return;
08609    }
08610 
08611    expiry = strrchr(data, ':');
08612    if (!expiry) {
08613       ast_log(LOG_NOTICE, "IAX/Registry astdb entry missing expiry: '%s'\n", data);
08614    }
08615    *expiry++ = '\0';
08616 
08617    if (ast_sockaddr_parse(&p->addr, data, PARSE_PORT_REQUIRE)) {
08618       ast_log(LOG_NOTICE, "IAX/Registry astdb host:port invalid - '%s'\n", data);
08619       return;
08620    }
08621 
08622    p->expiry = atoi(expiry);
08623 
08624    ast_verb(3, "Seeding '%s' at %s for %d\n", p->name,
08625       ast_sockaddr_stringify(&p->addr), p->expiry);
08626 
08627    iax2_poke_peer(p, 0);
08628    if (p->expire > -1) {
08629       if (!ast_sched_thread_del(sched, p->expire)) {
08630          p->expire = -1;
08631          peer_unref(p);
08632       }
08633    }
08634 
08635    ast_devstate_changed(AST_DEVICE_UNKNOWN, "IAX2/%s", p->name); /* Activate notification */
08636 
08637    p->expire = iax2_sched_add(sched, (p->expiry + 10) * 1000, expire_registry, peer_ref(p));
08638    if (p->expire == -1) {
08639       peer_unref(p);
08640    }
08641 
08642    if (iax2_regfunk) {
08643       iax2_regfunk(p->name, 1);
08644    }
08645 
08646    register_peer_exten(p, 1);
08647 }
08648 
08649 /*!
08650  * \pre iaxsl[callno] is locked
08651  *
08652  * \note Since this function calls send_command_final(), the pvt struct for
08653  *       the given call number may disappear while executing this function.
08654  */
08655 static int update_registry(struct sockaddr_in *sin, int callno, char *devtype, int fd, unsigned short refresh)
08656 {
08657    /* Called from IAX thread only, with proper iaxsl lock */
08658    struct iax_ie_data ied = {
08659       .pos = 0,
08660    };
08661    struct iax2_peer *p;
08662    int msgcount;
08663    char data[80];
08664    int version;
08665    const char *peer_name;
08666    int res = -1;
08667    struct ast_sockaddr sockaddr;
08668 
08669    ast_sockaddr_from_sin(&sockaddr, sin);
08670 
08671    peer_name = ast_strdupa(iaxs[callno]->peer);
08672 
08673    /* SLD: Another find_peer call during registration - this time when we are really updating our registration */
08674    ast_mutex_unlock(&iaxsl[callno]);
08675    if (!(p = find_peer(peer_name, 1))) {
08676       ast_mutex_lock(&iaxsl[callno]);
08677       ast_log(LOG_WARNING, "No such peer '%s'\n", peer_name);
08678       return -1;
08679    }
08680    ast_mutex_lock(&iaxsl[callno]);
08681    if (!iaxs[callno])
08682       goto return_unref;
08683 
08684    if (ast_test_flag64((&globalflags), IAX_RTUPDATE) && (ast_test_flag64(p, IAX_TEMPONLY|IAX_RTCACHEFRIENDS))) {
08685       if (sin->sin_addr.s_addr) {
08686          time_t nowtime;
08687          time(&nowtime);
08688          realtime_update_peer(peer_name, &sockaddr, nowtime);
08689       } else {
08690          realtime_update_peer(peer_name, &sockaddr, 0);
08691       }
08692    }
08693 
08694    if (ast_sockaddr_cmp(&p->addr, &sockaddr)) {
08695       if (iax2_regfunk) {
08696          iax2_regfunk(p->name, 1);
08697       }
08698 
08699       /* modify entry in peercnts table as _not_ registered */
08700       peercnt_modify(0, 0, &p->addr);
08701 
08702       /* Stash the IP address from which they registered */
08703       memcpy(&p->addr, sin, sizeof(p->addr));
08704 
08705       snprintf(data, sizeof(data), "%s:%d:%d", ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port), p->expiry);
08706       if (!ast_test_flag64(p, IAX_TEMPONLY) && sin->sin_addr.s_addr) {
08707          ast_db_put("IAX/Registry", p->name, data);
08708          ast_verb(3, "Registered IAX2 '%s' (%s) at %s:%d\n", p->name,
08709                    ast_test_flag(&iaxs[callno]->state, IAX_STATE_AUTHENTICATED) ? "AUTHENTICATED" : "UNAUTHENTICATED", ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
08710          manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: IAX2\r\nPeer: IAX2/%s\r\nPeerStatus: Registered\r\n", p->name);
08711          register_peer_exten(p, 1);
08712          ast_devstate_changed(AST_DEVICE_UNKNOWN, "IAX2/%s", p->name); /* Activate notification */
08713       } else if (!ast_test_flag64(p, IAX_TEMPONLY)) {
08714          ast_verb(3, "Unregistered IAX2 '%s' (%s)\n", p->name,
08715                    ast_test_flag(&iaxs[callno]->state, IAX_STATE_AUTHENTICATED) ? "AUTHENTICATED" : "UNAUTHENTICATED");
08716          manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: IAX2\r\nPeer: IAX2/%s\r\nPeerStatus: Unregistered\r\n", p->name);
08717          register_peer_exten(p, 0);
08718          ast_db_del("IAX/Registry", p->name);
08719          ast_devstate_changed(AST_DEVICE_UNAVAILABLE, "IAX2/%s", p->name); /* Activate notification */
08720       }
08721       /* Update the host */
08722       /* Verify that the host is really there */
08723       iax2_poke_peer(p, callno);
08724    }
08725 
08726    /* modify entry in peercnts table as registered */
08727    if (p->maxcallno) {
08728       peercnt_modify(1, p->maxcallno, &p->addr);
08729    }
08730 
08731    /* Make sure our call still exists, an INVAL at the right point may make it go away */
08732    if (!iaxs[callno]) {
08733       res = -1;
08734       goto return_unref;
08735    }
08736 
08737    /* Store socket fd */
08738    p->sockfd = fd;
08739    /* Setup the expiry */
08740    if (p->expire > -1) {
08741       if (!ast_sched_thread_del(sched, p->expire)) {
08742          p->expire = -1;
08743          peer_unref(p);
08744       }
08745    }
08746    /* treat an unspecified refresh interval as the minimum */
08747    if (!refresh)
08748       refresh = min_reg_expire;
08749    if (refresh > max_reg_expire) {
08750       ast_log(LOG_NOTICE, "Restricting registration for peer '%s' to %d seconds (requested %d)\n",
08751          p->name, max_reg_expire, refresh);
08752       p->expiry = max_reg_expire;
08753    } else if (refresh < min_reg_expire) {
08754       ast_log(LOG_NOTICE, "Restricting registration for peer '%s' to %d seconds (requested %d)\n",
08755          p->name, min_reg_expire, refresh);
08756       p->expiry = min_reg_expire;
08757    } else {
08758       p->expiry = refresh;
08759    }
08760    if (p->expiry && sin->sin_addr.s_addr) {
08761       p->expire = iax2_sched_add(sched, (p->expiry + 10) * 1000, expire_registry, peer_ref(p));
08762       if (p->expire == -1)
08763          peer_unref(p);
08764    }
08765    iax_ie_append_str(&ied, IAX_IE_USERNAME, p->name);
08766    iax_ie_append_int(&ied, IAX_IE_DATETIME, iax2_datetime(p->zonetag));
08767    if (sin->sin_addr.s_addr) {
08768       struct sockaddr_in peer_addr;
08769 
08770       ast_sockaddr_to_sin(&p->addr, &peer_addr);
08771 
08772       iax_ie_append_short(&ied, IAX_IE_REFRESH, p->expiry);
08773       iax_ie_append_addr(&ied, IAX_IE_APPARENT_ADDR, &peer_addr);
08774       if (!ast_strlen_zero(p->mailbox)) {
08775          struct ast_event *event;
08776          int new, old;
08777          char *mailbox, *context;
08778 
08779          context = mailbox = ast_strdupa(p->mailbox);
08780          strsep(&context, "@");
08781          if (ast_strlen_zero(context))
08782             context = "default";
08783 
08784          event = ast_event_get_cached(AST_EVENT_MWI,
08785             AST_EVENT_IE_MAILBOX, AST_EVENT_IE_PLTYPE_STR, mailbox,
08786             AST_EVENT_IE_CONTEXT, AST_EVENT_IE_PLTYPE_STR, context,
08787             AST_EVENT_IE_END);
08788          if (event) {
08789             new = ast_event_get_ie_uint(event, AST_EVENT_IE_NEWMSGS);
08790             old = ast_event_get_ie_uint(event, AST_EVENT_IE_OLDMSGS);
08791             ast_event_destroy(event);
08792          } else { /* Fall back on checking the mailbox directly */
08793             ast_app_inboxcount(p->mailbox, &new, &old);
08794          }
08795 
08796          if (new > 255) {
08797             new = 255;
08798          }
08799          if (old > 255) {
08800             old = 255;
08801          }
08802          msgcount = (old << 8) | new;
08803 
08804          iax_ie_append_short(&ied, IAX_IE_MSGCOUNT, msgcount);
08805       }
08806       if (ast_test_flag64(p, IAX_HASCALLERID)) {
08807          iax_ie_append_str(&ied, IAX_IE_CALLING_NUMBER, p->cid_num);
08808          iax_ie_append_str(&ied, IAX_IE_CALLING_NAME, p->cid_name);
08809       }
08810    }
08811    version = iax_check_version(devtype);
08812    if (version) 
08813       iax_ie_append_short(&ied, IAX_IE_FIRMWAREVER, version);
08814 
08815    res = 0;
08816 
08817 return_unref:
08818    peer_unref(p);
08819 
08820    return res ? res : send_command_final(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_REGACK, 0, ied.buf, ied.pos, -1);
08821 }
08822 
08823 static int registry_authrequest(int callno)
08824 {
08825    struct iax_ie_data ied;
08826    struct iax2_peer *p;
08827    char challenge[10];
08828    const char *peer_name;
08829    int sentauthmethod;
08830 
08831    peer_name = ast_strdupa(iaxs[callno]->peer);
08832 
08833    /* SLD: third call to find_peer in registration */
08834    ast_mutex_unlock(&iaxsl[callno]);
08835    if ((p = find_peer(peer_name, 1))) {
08836       last_authmethod = p->authmethods;
08837    }
08838 
08839    ast_mutex_lock(&iaxsl[callno]);
08840    if (!iaxs[callno])
08841       goto return_unref;
08842 
08843    memset(&ied, 0, sizeof(ied));
08844    /* The selection of which delayed reject is sent may leak information,
08845     * if it sets a static response.  For example, if a host is known to only
08846     * use MD5 authentication, then an RSA response would indicate that the
08847     * peer does not exist, and vice-versa.
08848     * Therefore, we use whatever the last peer used (which may vary over the
08849     * course of a server, which should leak minimal information). */
08850    sentauthmethod = p ? p->authmethods : last_authmethod ? last_authmethod : (IAX_AUTH_MD5 | IAX_AUTH_PLAINTEXT);
08851    if (!p) {
08852       iaxs[callno]->authmethods = sentauthmethod;
08853    }
08854    iax_ie_append_short(&ied, IAX_IE_AUTHMETHODS, sentauthmethod);
08855    if (sentauthmethod & (IAX_AUTH_RSA | IAX_AUTH_MD5)) {
08856       /* Build the challenge */
08857       snprintf(challenge, sizeof(challenge), "%d", (int)ast_random());
08858       ast_string_field_set(iaxs[callno], challenge, challenge);
08859       iax_ie_append_str(&ied, IAX_IE_CHALLENGE, iaxs[callno]->challenge);
08860    }
08861    iax_ie_append_str(&ied, IAX_IE_USERNAME, peer_name);
08862 
08863 return_unref:
08864    if (p) {
08865       peer_unref(p);
08866    }
08867 
08868    return iaxs[callno] ? send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_REGAUTH, 0, ied.buf, ied.pos, -1) : -1;
08869 }
08870 
08871 static int registry_rerequest(struct iax_ies *ies, int callno, struct sockaddr_in *sin)
08872 {
08873    struct iax2_registry *reg;
08874    /* Start pessimistic */
08875    struct iax_ie_data ied;
08876    char peer[256] = "";
08877    char challenge[256] = "";
08878    int res;
08879    int authmethods = 0;
08880    if (ies->authmethods)
08881       authmethods = ies->authmethods;
08882    if (ies->username)
08883       ast_copy_string(peer, ies->username, sizeof(peer));
08884    if (ies->challenge)
08885       ast_copy_string(challenge, ies->challenge, sizeof(challenge));
08886    memset(&ied, 0, sizeof(ied));
08887    reg = iaxs[callno]->reg;
08888    if (reg) {
08889       struct sockaddr_in reg_addr;
08890 
08891       ast_sockaddr_to_sin(&reg->addr, &reg_addr);
08892 
08893       if (inaddrcmp(&reg_addr, sin)) {
08894          ast_log(LOG_WARNING, "Received unsolicited registry authenticate request from '%s'\n", ast_inet_ntoa(sin->sin_addr));
08895          return -1;
08896       }
08897       if (ast_strlen_zero(reg->secret)) {
08898          ast_log(LOG_NOTICE, "No secret associated with peer '%s'\n", reg->username);
08899          reg->regstate = REG_STATE_NOAUTH;
08900          return -1;
08901       }
08902       iax_ie_append_str(&ied, IAX_IE_USERNAME, reg->username);
08903       iax_ie_append_short(&ied, IAX_IE_REFRESH, reg->refresh);
08904       if (reg->secret[0] == '[') {
08905          char tmpkey[256];
08906          ast_copy_string(tmpkey, reg->secret + 1, sizeof(tmpkey));
08907          tmpkey[strlen(tmpkey) - 1] = '\0';
08908          res = authenticate(challenge, NULL, tmpkey, authmethods, &ied, sin, NULL);
08909       } else
08910          res = authenticate(challenge, reg->secret, NULL, authmethods, &ied, sin, NULL);
08911       if (!res) {
08912          reg->regstate = REG_STATE_AUTHSENT;
08913          add_empty_calltoken_ie(iaxs[callno], &ied); /* this _MUST_ be the last ie added */
08914          return send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_REGREQ, 0, ied.buf, ied.pos, -1);
08915       } else
08916          return -1;
08917       ast_log(LOG_WARNING, "Registry acknowledge on unknown registery '%s'\n", peer);
08918    } else   
08919       ast_log(LOG_NOTICE, "Can't reregister without a reg\n");
08920    return -1;
08921 }
08922 
08923 static void stop_stuff(int callno)
08924 {
08925    iax2_destroy_helper(iaxs[callno]);
08926 }
08927 
08928 static void __auth_reject(const void *nothing)
08929 {
08930    /* Called from IAX thread only, without iaxs lock */
08931    int callno = (int)(long)(nothing);
08932    struct iax_ie_data ied;
08933    ast_mutex_lock(&iaxsl[callno]);
08934    if (iaxs[callno]) {
08935       memset(&ied, 0, sizeof(ied));
08936       if (iaxs[callno]->authfail == IAX_COMMAND_REGREJ) {
08937          iax_ie_append_str(&ied, IAX_IE_CAUSE, "Registration Refused");
08938          iax_ie_append_byte(&ied, IAX_IE_CAUSECODE, AST_CAUSE_FACILITY_REJECTED);
08939       } else if (iaxs[callno]->authfail == IAX_COMMAND_REJECT) {
08940          iax_ie_append_str(&ied, IAX_IE_CAUSE, "No authority found");
08941          iax_ie_append_byte(&ied, IAX_IE_CAUSECODE, AST_CAUSE_FACILITY_NOT_SUBSCRIBED);
08942       }
08943       send_command_final(iaxs[callno], AST_FRAME_IAX, iaxs[callno]->authfail, 0, ied.buf, ied.pos, -1);
08944    }
08945    ast_mutex_unlock(&iaxsl[callno]);
08946 }
08947 
08948 static int auth_reject(const void *data)
08949 {
08950    int callno = (int)(long)(data);
08951    ast_mutex_lock(&iaxsl[callno]);
08952    if (iaxs[callno])
08953       iaxs[callno]->authid = -1;
08954    ast_mutex_unlock(&iaxsl[callno]);
08955 #ifdef SCHED_MULTITHREADED
08956    if (schedule_action(__auth_reject, data))
08957 #endif      
08958       __auth_reject(data);
08959    return 0;
08960 }
08961 
08962 static int auth_fail(int callno, int failcode)
08963 {
08964    /* Schedule sending the authentication failure in one second, to prevent
08965       guessing */
08966    if (iaxs[callno]) {
08967       iaxs[callno]->authfail = failcode;
08968       if (delayreject) {
08969          iaxs[callno]->authid = iax2_sched_replace(iaxs[callno]->authid, 
08970             sched, 1000, auth_reject, (void *)(long)callno);
08971       } else
08972          auth_reject((void *)(long)callno);
08973    }
08974    return 0;
08975 }
08976 
08977 static void __auto_hangup(const void *nothing)
08978 {
08979    /* Called from IAX thread only, without iaxs lock */
08980    int callno = (int)(long)(nothing);
08981    struct iax_ie_data ied;
08982    ast_mutex_lock(&iaxsl[callno]);
08983    if (iaxs[callno]) {
08984       memset(&ied, 0, sizeof(ied));
08985       iax_ie_append_str(&ied, IAX_IE_CAUSE, "Timeout");
08986       iax_ie_append_byte(&ied, IAX_IE_CAUSECODE, AST_CAUSE_NO_USER_RESPONSE);
08987       send_command_final(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_HANGUP, 0, ied.buf, ied.pos, -1);
08988    }
08989    ast_mutex_unlock(&iaxsl[callno]);
08990 }
08991 
08992 static int auto_hangup(const void *data)
08993 {
08994    int callno = (int)(long)(data);
08995    ast_mutex_lock(&iaxsl[callno]);
08996    if (iaxs[callno]) {
08997       iaxs[callno]->autoid = -1;
08998    }
08999    ast_mutex_unlock(&iaxsl[callno]);
09000 #ifdef SCHED_MULTITHREADED
09001    if (schedule_action(__auto_hangup, data))
09002 #endif      
09003       __auto_hangup(data);
09004    return 0;
09005 }
09006 
09007 static void iax2_dprequest(struct iax2_dpcache *dp, int callno)
09008 {
09009    struct iax_ie_data ied;
09010    /* Auto-hangup with 30 seconds of inactivity */
09011    iaxs[callno]->autoid = iax2_sched_replace(iaxs[callno]->autoid, 
09012       sched, 30000, auto_hangup, (void *)(long)callno);
09013    memset(&ied, 0, sizeof(ied));
09014    iax_ie_append_str(&ied, IAX_IE_CALLED_NUMBER, dp->exten);
09015    send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_DPREQ, 0, ied.buf, ied.pos, -1);
09016    dp->flags |= CACHE_FLAG_TRANSMITTED;
09017 }
09018 
09019 static int iax2_vnak(int callno)
09020 {
09021    return send_command_immediate(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_VNAK, 0, NULL, 0, iaxs[callno]->iseqno);
09022 }
09023 
09024 static void vnak_retransmit(int callno, int last)
09025 {
09026    struct iax_frame *f;
09027 
09028    AST_LIST_TRAVERSE(&frame_queue[callno], f, list) {
09029       /* Send a copy immediately */
09030       if (((unsigned char) (f->oseqno - last) < 128) &&
09031             (f->retries >= 0)) {
09032          send_packet(f);
09033       }
09034    }
09035 }
09036 
09037 static void __iax2_poke_peer_s(const void *data)
09038 {
09039    struct iax2_peer *peer = (struct iax2_peer *)data;
09040    iax2_poke_peer(peer, 0);
09041    peer_unref(peer);
09042 }
09043 
09044 static int iax2_poke_peer_s(const void *data)
09045 {
09046    struct iax2_peer *peer = (struct iax2_peer *)data;
09047    peer->pokeexpire = -1;
09048 #ifdef SCHED_MULTITHREADED
09049    if (schedule_action(__iax2_poke_peer_s, data))
09050 #endif      
09051       __iax2_poke_peer_s(data);
09052    return 0;
09053 }
09054 
09055 static int send_trunk(struct iax2_trunk_peer *tpeer, struct timeval *now)
09056 {
09057    int res = 0;
09058    struct iax_frame *fr;
09059    struct ast_iax2_meta_hdr *meta;
09060    struct ast_iax2_meta_trunk_hdr *mth;
09061    int calls = 0;
09062    
09063    /* Point to frame */
09064    fr = (struct iax_frame *)tpeer->trunkdata;
09065    /* Point to meta data */
09066    meta = (struct ast_iax2_meta_hdr *)fr->afdata;
09067    mth = (struct ast_iax2_meta_trunk_hdr *)meta->data;
09068    if (tpeer->trunkdatalen) {
09069       /* We're actually sending a frame, so fill the meta trunk header and meta header */
09070       meta->zeros = 0;
09071       meta->metacmd = IAX_META_TRUNK;
09072       if (ast_test_flag64(&globalflags, IAX_TRUNKTIMESTAMPS))
09073          meta->cmddata = IAX_META_TRUNK_MINI;
09074       else
09075          meta->cmddata = IAX_META_TRUNK_SUPERMINI;
09076       mth->ts = htonl(calc_txpeerstamp(tpeer, trunkfreq, now));
09077       /* And the rest of the ast_iax2 header */
09078       fr->direction = DIRECTION_OUTGRESS;
09079       fr->retrans = -1;
09080       fr->transfer = 0;
09081       /* Any appropriate call will do */
09082       fr->data = fr->afdata;
09083       fr->datalen = tpeer->trunkdatalen + sizeof(struct ast_iax2_meta_hdr) + sizeof(struct ast_iax2_meta_trunk_hdr);
09084       res = transmit_trunk(fr, &tpeer->addr, tpeer->sockfd);
09085       calls = tpeer->calls;
09086 #if 0
09087       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));
09088 #endif      
09089       /* Reset transmit trunk side data */
09090       tpeer->trunkdatalen = 0;
09091       tpeer->calls = 0;
09092    }
09093    if (res < 0)
09094       return res;
09095    return calls;
09096 }
09097 
09098 static inline int iax2_trunk_expired(struct iax2_trunk_peer *tpeer, struct timeval *now)
09099 {
09100    /* Drop when trunk is about 5 seconds idle */
09101    if (now->tv_sec > tpeer->trunkact.tv_sec + 5) 
09102       return 1;
09103    return 0;
09104 }
09105 
09106 static int timing_read(int *id, int fd, short events, void *cbdata)
09107 {
09108    int res, processed = 0, totalcalls = 0;
09109    struct iax2_trunk_peer *tpeer = NULL, *drop = NULL;
09110    struct timeval now = ast_tvnow();
09111 
09112    if (iaxtrunkdebug)
09113       ast_verbose("Beginning trunk processing. Trunk queue ceiling is %d bytes per host\n", trunkmaxsize);
09114 
09115    if (timer) { 
09116       ast_timer_ack(timer, 1);
09117    }
09118 
09119    /* For each peer that supports trunking... */
09120    AST_LIST_LOCK(&tpeers);
09121    AST_LIST_TRAVERSE_SAFE_BEGIN(&tpeers, tpeer, list) {
09122       processed++;
09123       res = 0;
09124       ast_mutex_lock(&tpeer->lock);
09125       /* We can drop a single tpeer per pass.  That makes all this logic
09126          substantially easier */
09127       if (!drop && iax2_trunk_expired(tpeer, &now)) {
09128          /* Take it out of the list, but don't free it yet, because it
09129             could be in use */
09130          AST_LIST_REMOVE_CURRENT(list);
09131          drop = tpeer;
09132       } else {
09133          res = send_trunk(tpeer, &now);
09134          trunk_timed++; 
09135          if (iaxtrunkdebug)
09136             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);
09137       }     
09138       totalcalls += res;   
09139       res = 0;
09140       ast_mutex_unlock(&tpeer->lock);
09141    }
09142    AST_LIST_TRAVERSE_SAFE_END;
09143    AST_LIST_UNLOCK(&tpeers);
09144 
09145    if (drop) {
09146       ast_mutex_lock(&drop->lock);
09147       /* Once we have this lock, we're sure nobody else is using it or could use it once we release it, 
09148          because by the time they could get tpeerlock, we've already grabbed it */
09149       ast_debug(1, "Dropping unused iax2 trunk peer '%s:%d'\n", ast_inet_ntoa(drop->addr.sin_addr), ntohs(drop->addr.sin_port));
09150       if (drop->trunkdata) {
09151          ast_free(drop->trunkdata);
09152          drop->trunkdata = NULL;
09153       }
09154       ast_mutex_unlock(&drop->lock);
09155       ast_mutex_destroy(&drop->lock);
09156       ast_free(drop);
09157       
09158    }
09159 
09160    if (iaxtrunkdebug)
09161       ast_verbose("Ending trunk processing with %d peers and %d call chunks processed\n", processed, totalcalls);
09162    iaxtrunkdebug = 0;
09163 
09164    return 1;
09165 }
09166 
09167 struct dpreq_data {
09168    int callno;
09169    char context[AST_MAX_EXTENSION];
09170    char callednum[AST_MAX_EXTENSION];
09171    char *callerid;
09172 };
09173 
09174 static void dp_lookup(int callno, const char *context, const char *callednum, const char *callerid, int skiplock)
09175 {
09176    unsigned short dpstatus = 0;
09177    struct iax_ie_data ied1;
09178    int mm;
09179 
09180    memset(&ied1, 0, sizeof(ied1));
09181    mm = ast_matchmore_extension(NULL, context, callednum, 1, callerid);
09182    /* Must be started */
09183    if (ast_parking_ext_valid(callednum, NULL, context) || ast_exists_extension(NULL, context, callednum, 1, callerid)) {
09184       dpstatus = IAX_DPSTATUS_EXISTS;
09185    } else if (ast_canmatch_extension(NULL, context, callednum, 1, callerid)) {
09186       dpstatus = IAX_DPSTATUS_CANEXIST;
09187    } else {
09188       dpstatus = IAX_DPSTATUS_NONEXISTENT;
09189    }
09190    if (ast_ignore_pattern(context, callednum))
09191       dpstatus |= IAX_DPSTATUS_IGNOREPAT;
09192    if (mm)
09193       dpstatus |= IAX_DPSTATUS_MATCHMORE;
09194    if (!skiplock)
09195       ast_mutex_lock(&iaxsl[callno]);
09196    if (iaxs[callno]) {
09197       iax_ie_append_str(&ied1, IAX_IE_CALLED_NUMBER, callednum);
09198       iax_ie_append_short(&ied1, IAX_IE_DPSTATUS, dpstatus);
09199       iax_ie_append_short(&ied1, IAX_IE_REFRESH, iaxdefaultdpcache);
09200       send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_DPREP, 0, ied1.buf, ied1.pos, -1);
09201    }
09202    if (!skiplock)
09203       ast_mutex_unlock(&iaxsl[callno]);
09204 }
09205 
09206 static void *dp_lookup_thread(void *data)
09207 {
09208    /* Look up for dpreq */
09209    struct dpreq_data *dpr = data;
09210    dp_lookup(dpr->callno, dpr->context, dpr->callednum, dpr->callerid, 0);
09211    if (dpr->callerid)
09212       ast_free(dpr->callerid);
09213    ast_free(dpr);
09214    return NULL;
09215 }
09216 
09217 static void spawn_dp_lookup(int callno, const char *context, const char *callednum, const char *callerid)
09218 {
09219    pthread_t newthread;
09220    struct dpreq_data *dpr;
09221    
09222    if (!(dpr = ast_calloc(1, sizeof(*dpr))))
09223       return;
09224 
09225    dpr->callno = callno;
09226    ast_copy_string(dpr->context, context, sizeof(dpr->context));
09227    ast_copy_string(dpr->callednum, callednum, sizeof(dpr->callednum));
09228    if (callerid)
09229       dpr->callerid = ast_strdup(callerid);
09230    if (ast_pthread_create_detached(&newthread, NULL, dp_lookup_thread, dpr)) {
09231       ast_log(LOG_WARNING, "Unable to start lookup thread!\n");
09232    }
09233 }
09234 
09235 struct iax_dual {
09236    struct ast_channel *chan1;
09237    struct ast_channel *chan2;
09238    const char *parkexten;
09239 };
09240 
09241 static void *iax_park_thread(void *stuff)
09242 {
09243    struct ast_channel *chan1, *chan2;
09244    struct iax_dual *d;
09245    struct ast_frame *f;
09246    int ext;
09247    int res;
09248    d = stuff;
09249    chan1 = d->chan1;
09250    chan2 = d->chan2;
09251    ast_free(d);
09252    f = ast_read(chan1);
09253    if (f)
09254       ast_frfree(f);
09255    res = ast_park_call(chan1, chan2, 0, d->parkexten, &ext);
09256    ast_hangup(chan2);
09257    ast_log(LOG_NOTICE, "Parked on extension '%d'\n", ext);
09258    return NULL;
09259 }
09260 
09261 static int iax_park(struct ast_channel *chan1, struct ast_channel *chan2, const char *parkexten)
09262 {
09263    struct iax_dual *d;
09264    struct ast_channel *chan1m, *chan2m;
09265    pthread_t th;
09266    chan1m = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, chan2->accountcode, chan1->exten, chan1->context, chan1->linkedid, chan1->amaflags, "Parking/%s", chan1->name);
09267    chan2m = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, chan2->accountcode, chan2->exten, chan2->context, chan2->linkedid, chan2->amaflags, "IAXPeer/%s", chan2->name);
09268    if (chan2m && chan1m) {
09269       /* Make formats okay */
09270       chan1m->readformat = chan1->readformat;
09271       chan1m->writeformat = chan1->writeformat;
09272       ast_channel_masquerade(chan1m, chan1);
09273       /* Setup the extensions and such */
09274       ast_copy_string(chan1m->context, chan1->context, sizeof(chan1m->context));
09275       ast_copy_string(chan1m->exten, chan1->exten, sizeof(chan1m->exten));
09276       chan1m->priority = chan1->priority;
09277       
09278       /* We make a clone of the peer channel too, so we can play
09279          back the announcement */
09280       /* Make formats okay */
09281       chan2m->readformat = chan2->readformat;
09282       chan2m->writeformat = chan2->writeformat;
09283       ast_channel_masquerade(chan2m, chan2);
09284       /* Setup the extensions and such */
09285       ast_copy_string(chan2m->context, chan2->context, sizeof(chan2m->context));
09286       ast_copy_string(chan2m->exten, chan2->exten, sizeof(chan2m->exten));
09287       chan2m->priority = chan2->priority;
09288       if (ast_do_masquerade(chan2m)) {
09289          ast_log(LOG_WARNING, "Masquerade failed :(\n");
09290          ast_hangup(chan2m);
09291          return -1;
09292       }
09293    } else {
09294       if (chan1m)
09295          ast_hangup(chan1m);
09296       if (chan2m)
09297          ast_hangup(chan2m);
09298       return -1;
09299    }
09300    if ((d = ast_calloc(1, sizeof(*d)))) {
09301       d->chan1 = chan1m;
09302       d->chan2 = chan2m;
09303       d->parkexten = parkexten;
09304       if (!ast_pthread_create_detached_background(&th, NULL, iax_park_thread, d)) {
09305          return 0;
09306       }
09307       ast_free(d);
09308    }
09309    return -1;
09310 }
09311 
09312 static int check_provisioning(struct sockaddr_in *sin, int sockfd, char *si, unsigned int ver)
09313 {
09314    unsigned int ourver;
09315    char rsi[80];
09316    snprintf(rsi, sizeof(rsi), "si-%s", si);
09317    if (iax_provision_version(&ourver, rsi, 1))
09318       return 0;
09319    ast_debug(1, "Service identifier '%s', we think '%08x', they think '%08x'\n", si, ourver, ver);
09320    if (ourver != ver) 
09321       iax2_provision(sin, sockfd, NULL, rsi, 1);
09322    return 0;
09323 }
09324 
09325 static void construct_rr(struct chan_iax2_pvt *pvt, struct iax_ie_data *iep) 
09326 {
09327    jb_info stats;
09328    jb_getinfo(pvt->jb, &stats);
09329    
09330    memset(iep, 0, sizeof(*iep));
09331 
09332    iax_ie_append_int(iep,IAX_IE_RR_JITTER, stats.jitter);
09333    if(stats.frames_in == 0) stats.frames_in = 1;
09334    iax_ie_append_int(iep,IAX_IE_RR_LOSS, ((0xff & (stats.losspct/1000)) << 24 | (stats.frames_lost & 0x00ffffff)));
09335    iax_ie_append_int(iep,IAX_IE_RR_PKTS, stats.frames_in);
09336    iax_ie_append_short(iep,IAX_IE_RR_DELAY, stats.current - stats.min);
09337    iax_ie_append_int(iep,IAX_IE_RR_DROPPED, stats.frames_dropped);
09338    iax_ie_append_int(iep,IAX_IE_RR_OOO, stats.frames_ooo);
09339 }
09340 
09341 static void save_rr(struct iax_frame *fr, struct iax_ies *ies) 
09342 {
09343    iaxs[fr->callno]->remote_rr.jitter = ies->rr_jitter;
09344    iaxs[fr->callno]->remote_rr.losspct = ies->rr_loss >> 24;
09345    iaxs[fr->callno]->remote_rr.losscnt = ies->rr_loss & 0xffffff;
09346    iaxs[fr->callno]->remote_rr.packets = ies->rr_pkts;
09347    iaxs[fr->callno]->remote_rr.delay = ies->rr_delay;
09348    iaxs[fr->callno]->remote_rr.dropped = ies->rr_dropped;
09349    iaxs[fr->callno]->remote_rr.ooo = ies->rr_ooo;
09350 }
09351 
09352 static void save_osptoken(struct iax_frame *fr, struct iax_ies *ies) 
09353 {
09354    int i;
09355    unsigned int length, offset = 0;
09356    char full_osptoken[IAX_MAX_OSPBUFF_SIZE];
09357 
09358    for (i = 0; i < IAX_MAX_OSPBLOCK_NUM; i++) {
09359       length = ies->ospblocklength[i];
09360       if (length != 0) {
09361          if (length > IAX_MAX_OSPBLOCK_SIZE) {
09362             /* OSP token block length wrong, clear buffer */
09363             offset = 0;
09364             break;
09365          } else {
09366             memcpy(full_osptoken + offset, ies->osptokenblock[i], length);
09367             offset += length;
09368          }
09369       } else {
09370          break;
09371       }
09372    }
09373    *(full_osptoken + offset) = '\0';
09374    if (strlen(full_osptoken) != offset) {
09375       /* OSP token length wrong, clear buffer */
09376       *full_osptoken = '\0';
09377    }
09378 
09379    ast_string_field_set(iaxs[fr->callno], osptoken, full_osptoken);
09380 }
09381 
09382 static void log_jitterstats(unsigned short callno)
09383 {
09384    int localjitter = -1, localdelay = 0, locallost = -1, locallosspct = -1, localdropped = 0, localooo = -1, localpackets = -1;
09385    jb_info jbinfo;
09386 
09387    ast_mutex_lock(&iaxsl[callno]);
09388    if (iaxs[callno] && iaxs[callno]->owner && iaxs[callno]->owner->name) {
09389       if(ast_test_flag64(iaxs[callno], IAX_USEJITTERBUF)) {
09390          jb_getinfo(iaxs[callno]->jb, &jbinfo);
09391          localjitter = jbinfo.jitter;
09392          localdelay = jbinfo.current - jbinfo.min;
09393          locallost = jbinfo.frames_lost;
09394          locallosspct = jbinfo.losspct/1000;
09395          localdropped = jbinfo.frames_dropped;
09396          localooo = jbinfo.frames_ooo;
09397          localpackets = jbinfo.frames_in;
09398       }
09399       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",
09400          iaxs[callno]->owner->name,
09401          iaxs[callno]->pingtime,
09402          localjitter,
09403          localdelay,
09404          locallost,
09405          locallosspct,
09406          localdropped,
09407          localooo,
09408          localpackets,
09409          iaxs[callno]->remote_rr.jitter,
09410          iaxs[callno]->remote_rr.delay,
09411          iaxs[callno]->remote_rr.losscnt,
09412          iaxs[callno]->remote_rr.losspct/1000,
09413          iaxs[callno]->remote_rr.dropped,
09414          iaxs[callno]->remote_rr.ooo,
09415          iaxs[callno]->remote_rr.packets);
09416       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",
09417          iaxs[callno]->owner->name,
09418          iaxs[callno]->pingtime,
09419          localjitter,
09420          localdelay,
09421          locallost,
09422          locallosspct,
09423          localdropped,
09424          localooo,
09425          localpackets,
09426          iaxs[callno]->remote_rr.jitter,
09427          iaxs[callno]->remote_rr.delay,
09428          iaxs[callno]->remote_rr.losscnt,
09429          iaxs[callno]->remote_rr.losspct/1000,
09430          iaxs[callno]->remote_rr.dropped,
09431          iaxs[callno]->remote_rr.ooo,
09432          iaxs[callno]->remote_rr.packets);
09433    }
09434    ast_mutex_unlock(&iaxsl[callno]);
09435 }
09436 
09437 static int socket_process(struct iax2_thread *thread);
09438 
09439 /*!
09440  * \brief Handle any deferred full frames for this thread
09441  */
09442 static void handle_deferred_full_frames(struct iax2_thread *thread)
09443 {
09444    struct iax2_pkt_buf *pkt_buf;
09445 
09446    ast_mutex_lock(&thread->lock);
09447 
09448    while ((pkt_buf = AST_LIST_REMOVE_HEAD(&thread->full_frames, entry))) {
09449       ast_mutex_unlock(&thread->lock);
09450 
09451       thread->buf = pkt_buf->buf;
09452       thread->buf_len = pkt_buf->len;
09453       thread->buf_size = pkt_buf->len + 1;
09454       
09455       socket_process(thread);
09456 
09457       thread->buf = NULL;
09458       ast_free(pkt_buf);
09459 
09460       ast_mutex_lock(&thread->lock);
09461    }
09462 
09463    ast_mutex_unlock(&thread->lock);
09464 }
09465 
09466 /*!
09467  * \brief Queue the last read full frame for processing by a certain thread
09468  *
09469  * If there are already any full frames queued, they are sorted
09470  * by sequence number.
09471  */
09472 static void defer_full_frame(struct iax2_thread *from_here, struct iax2_thread *to_here)
09473 {
09474    struct iax2_pkt_buf *pkt_buf, *cur_pkt_buf;
09475    struct ast_iax2_full_hdr *fh, *cur_fh;
09476 
09477    if (!(pkt_buf = ast_calloc(1, sizeof(*pkt_buf) + from_here->buf_len)))
09478       return;
09479 
09480    pkt_buf->len = from_here->buf_len;
09481    memcpy(pkt_buf->buf, from_here->buf, pkt_buf->len);
09482 
09483    fh = (struct ast_iax2_full_hdr *) pkt_buf->buf;
09484    ast_mutex_lock(&to_here->lock);
09485    AST_LIST_TRAVERSE_SAFE_BEGIN(&to_here->full_frames, cur_pkt_buf, entry) {
09486       cur_fh = (struct ast_iax2_full_hdr *) cur_pkt_buf->buf;
09487       if (fh->oseqno < cur_fh->oseqno) {
09488          AST_LIST_INSERT_BEFORE_CURRENT(pkt_buf, entry);
09489          break;
09490       }
09491    }
09492    AST_LIST_TRAVERSE_SAFE_END
09493 
09494    if (!cur_pkt_buf)
09495       AST_LIST_INSERT_TAIL(&to_here->full_frames, pkt_buf, entry);
09496    
09497    ast_mutex_unlock(&to_here->lock);
09498 }
09499 
09500 static int socket_read(int *id, int fd, short events, void *cbdata)
09501 {
09502    struct iax2_thread *thread;
09503    socklen_t len;
09504    time_t t;
09505    static time_t last_errtime = 0;
09506    struct ast_iax2_full_hdr *fh;
09507 
09508    if (!(thread = find_idle_thread())) {
09509       time(&t);
09510       if (t != last_errtime)
09511          ast_debug(1, "Out of idle IAX2 threads for I/O, pausing!\n");
09512       last_errtime = t;
09513       usleep(1);
09514       return 1;
09515    }
09516 
09517    len = sizeof(thread->iosin);
09518    thread->iofd = fd;
09519    thread->buf_len = recvfrom(fd, thread->readbuf, sizeof(thread->readbuf), 0, (struct sockaddr *) &thread->iosin, &len);
09520    thread->buf_size = sizeof(thread->readbuf);
09521    thread->buf = thread->readbuf;
09522    if (thread->buf_len < 0) {
09523       if (errno != ECONNREFUSED && errno != EAGAIN)
09524          ast_log(LOG_WARNING, "Error: %s\n", strerror(errno));
09525       handle_error();
09526       thread->iostate = IAX_IOSTATE_IDLE;
09527       signal_condition(&thread->lock, &thread->cond);
09528       return 1;
09529    }
09530    if (test_losspct && ((100.0 * ast_random() / (RAND_MAX + 1.0)) < test_losspct)) { /* simulate random loss condition */
09531       thread->iostate = IAX_IOSTATE_IDLE;
09532       signal_condition(&thread->lock, &thread->cond);
09533       return 1;
09534    }
09535    
09536    /* Determine if this frame is a full frame; if so, and any thread is currently
09537       processing a full frame for the same callno from this peer, then drop this
09538       frame (and the peer will retransmit it) */
09539    fh = (struct ast_iax2_full_hdr *) thread->buf;
09540    if (ntohs(fh->scallno) & IAX_FLAG_FULL) {
09541       struct iax2_thread *cur = NULL;
09542       uint16_t callno = ntohs(fh->scallno) & ~IAX_FLAG_FULL;
09543       
09544       AST_LIST_LOCK(&active_list);
09545       AST_LIST_TRAVERSE(&active_list, cur, list) {
09546          if ((cur->ffinfo.callno == callno) &&
09547              !inaddrcmp(&cur->ffinfo.sin, &thread->iosin))
09548             break;
09549       }
09550       if (cur) {
09551          /* we found another thread processing a full frame for this call,
09552             so queue it up for processing later. */
09553          defer_full_frame(thread, cur);
09554          AST_LIST_UNLOCK(&active_list);
09555          thread->iostate = IAX_IOSTATE_IDLE;
09556          signal_condition(&thread->lock, &thread->cond);
09557          return 1;
09558       } else {
09559          /* this thread is going to process this frame, so mark it */
09560          thread->ffinfo.callno = callno;
09561          memcpy(&thread->ffinfo.sin, &thread->iosin, sizeof(thread->ffinfo.sin));
09562          thread->ffinfo.type = fh->type;
09563          thread->ffinfo.csub = fh->csub;
09564          AST_LIST_INSERT_HEAD(&active_list, thread, list);
09565       }
09566       AST_LIST_UNLOCK(&active_list);
09567    }
09568    
09569    /* Mark as ready and send on its way */
09570    thread->iostate = IAX_IOSTATE_READY;
09571 #ifdef DEBUG_SCHED_MULTITHREAD
09572    ast_copy_string(thread->curfunc, "socket_process", sizeof(thread->curfunc));
09573 #endif
09574    signal_condition(&thread->lock, &thread->cond);
09575 
09576    return 1;
09577 }
09578 
09579 static int socket_process_meta(int packet_len, struct ast_iax2_meta_hdr *meta, struct sockaddr_in *sin, int sockfd,
09580    struct iax_frame *fr)
09581 {
09582    unsigned char metatype;
09583    struct ast_iax2_meta_trunk_mini *mtm;
09584    struct ast_iax2_meta_trunk_hdr *mth;
09585    struct ast_iax2_meta_trunk_entry *mte;
09586    struct iax2_trunk_peer *tpeer;
09587    unsigned int ts;
09588    void *ptr;
09589    struct timeval rxtrunktime;
09590    struct ast_frame f = { 0, };
09591 
09592    if (packet_len < sizeof(*meta)) {
09593       ast_log(LOG_WARNING, "Rejecting packet from '%s.%d' that is flagged as a meta frame but is too short\n", 
09594          ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
09595       return 1;
09596    }
09597 
09598    if (meta->metacmd != IAX_META_TRUNK)
09599       return 1;
09600 
09601    if (packet_len < (sizeof(*meta) + sizeof(*mth))) {
09602       ast_log(LOG_WARNING, "midget meta trunk packet received (%d of %d min)\n", packet_len,
09603          (int) (sizeof(*meta) + sizeof(*mth)));
09604       return 1;
09605    }
09606    mth = (struct ast_iax2_meta_trunk_hdr *)(meta->data);
09607    ts = ntohl(mth->ts);
09608    metatype = meta->cmddata;
09609    packet_len -= (sizeof(*meta) + sizeof(*mth));
09610    ptr = mth->data;
09611    tpeer = find_tpeer(sin, sockfd);
09612    if (!tpeer) {
09613       ast_log(LOG_WARNING, "Unable to accept trunked packet from '%s:%d': No matching peer\n", 
09614          ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
09615       return 1;
09616    }
09617    tpeer->trunkact = ast_tvnow();
09618    if (!ts || ast_tvzero(tpeer->rxtrunktime))
09619       tpeer->rxtrunktime = tpeer->trunkact;
09620    rxtrunktime = tpeer->rxtrunktime;
09621    ast_mutex_unlock(&tpeer->lock);
09622    while (packet_len >= sizeof(*mte)) {
09623       /* Process channels */
09624       unsigned short callno, trunked_ts, len;
09625 
09626       if (metatype == IAX_META_TRUNK_MINI) {
09627          mtm = (struct ast_iax2_meta_trunk_mini *) ptr;
09628          ptr += sizeof(*mtm);
09629          packet_len -= sizeof(*mtm);
09630          len = ntohs(mtm->len);
09631          callno = ntohs(mtm->mini.callno);
09632          trunked_ts = ntohs(mtm->mini.ts);
09633       } else if (metatype == IAX_META_TRUNK_SUPERMINI) {
09634          mte = (struct ast_iax2_meta_trunk_entry *)ptr;
09635          ptr += sizeof(*mte);
09636          packet_len -= sizeof(*mte);
09637          len = ntohs(mte->len);
09638          callno = ntohs(mte->callno);
09639          trunked_ts = 0;
09640       } else {
09641          ast_log(LOG_WARNING, "Unknown meta trunk cmd from '%s:%d': dropping\n", ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
09642          break;
09643       }
09644       /* Stop if we don't have enough data */
09645       if (len > packet_len)
09646          break;
09647       fr->callno = find_callno_locked(callno & ~IAX_FLAG_FULL, 0, sin, NEW_PREVENT, sockfd, 0);
09648       if (!fr->callno)
09649          continue;
09650 
09651       /* If it's a valid call, deliver the contents.  If not, we
09652          drop it, since we don't have a scallno to use for an INVAL */
09653       /* Process as a mini frame */
09654       memset(&f, 0, sizeof(f));
09655       f.frametype = AST_FRAME_VOICE;
09656       if (!iaxs[fr->callno]) {
09657          /* drop it */
09658       } else if (iaxs[fr->callno]->voiceformat == 0) {
09659          ast_log(LOG_WARNING, "Received trunked frame before first full voice frame\n");
09660          iax2_vnak(fr->callno);
09661       } else {
09662          f.subclass.codec = iaxs[fr->callno]->voiceformat;
09663          f.datalen = len;
09664          if (f.datalen >= 0) {
09665             if (f.datalen)
09666                f.data.ptr = ptr;
09667             else
09668                f.data.ptr = NULL;
09669             if (trunked_ts)
09670                fr->ts = (iaxs[fr->callno]->last & 0xFFFF0000L) | (trunked_ts & 0xffff);
09671             else
09672                fr->ts = fix_peerts(&rxtrunktime, fr->callno, ts);
09673             /* Don't pass any packets until we're started */
09674             if (ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED)) {
09675                struct iax_frame *duped_fr;
09676 
09677                /* Common things */
09678                f.src = "IAX2";
09679                f.mallocd = 0;
09680                f.offset = 0;
09681                if (f.datalen && (f.frametype == AST_FRAME_VOICE)) 
09682                   f.samples = ast_codec_get_samples(&f);
09683                else
09684                   f.samples = 0;
09685                fr->outoforder = 0;
09686                iax_frame_wrap(fr, &f);
09687                duped_fr = iaxfrdup2(fr);
09688                if (duped_fr)
09689                   schedule_delivery(duped_fr, 1, 1, &fr->ts);
09690                if (iaxs[fr->callno] && iaxs[fr->callno]->last < fr->ts)
09691                   iaxs[fr->callno]->last = fr->ts;
09692             }
09693          } else {
09694             ast_log(LOG_WARNING, "Datalen < 0?\n");
09695          }
09696       }
09697       ast_mutex_unlock(&iaxsl[fr->callno]);
09698       ptr += len;
09699       packet_len -= len;
09700    }
09701 
09702    return 1;
09703 }
09704 
09705 static int acf_iaxvar_read(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
09706 {
09707    struct ast_datastore *variablestore = ast_channel_datastore_find(chan, &iax2_variable_datastore_info, NULL);
09708    AST_LIST_HEAD(, ast_var_t) *varlist;
09709    struct ast_var_t *var;
09710 
09711    if (!variablestore) {
09712       *buf = '\0';
09713       return 0;
09714    }
09715    varlist = variablestore->data;
09716 
09717    AST_LIST_LOCK(varlist);
09718    AST_LIST_TRAVERSE(varlist, var, entries) {
09719       if (strcmp(var->name, data) == 0) {
09720          ast_copy_string(buf, var->value, len);
09721          break;
09722       }
09723    }
09724    AST_LIST_UNLOCK(varlist);
09725    return 0;
09726 }
09727 
09728 static int acf_iaxvar_write(struct ast_channel *chan, const char *cmd, char *data, const char *value)
09729 {
09730    struct ast_datastore *variablestore = ast_channel_datastore_find(chan, &iax2_variable_datastore_info, NULL);
09731    AST_LIST_HEAD(, ast_var_t) *varlist;
09732    struct ast_var_t *var;
09733 
09734    if (!variablestore) {
09735       variablestore = ast_datastore_alloc(&iax2_variable_datastore_info, NULL);
09736       if (!variablestore) {
09737          ast_log(LOG_ERROR, "Memory allocation error\n");
09738          return -1;
09739       }
09740       varlist = ast_calloc(1, sizeof(*varlist));
09741       if (!varlist) {
09742          ast_log(LOG_ERROR, "Unable to assign new variable '%s'\n", data);
09743          return -1;
09744       }
09745 
09746       AST_LIST_HEAD_INIT(varlist);
09747       variablestore->data = varlist;
09748       variablestore->inheritance = DATASTORE_INHERIT_FOREVER;
09749       ast_channel_datastore_add(chan, variablestore);
09750    } else
09751       varlist = variablestore->data;
09752 
09753    AST_LIST_LOCK(varlist);
09754    AST_LIST_TRAVERSE_SAFE_BEGIN(varlist, var, entries) {
09755       if (strcmp(var->name, data) == 0) {
09756          AST_LIST_REMOVE_CURRENT(entries);
09757          ast_var_delete(var);
09758          break;
09759       }
09760    }
09761    AST_LIST_TRAVERSE_SAFE_END;
09762    var = ast_var_assign(data, value);
09763    if (var)
09764       AST_LIST_INSERT_TAIL(varlist, var, entries);
09765    else
09766       ast_log(LOG_ERROR, "Unable to assign new variable '%s'\n", data);
09767    AST_LIST_UNLOCK(varlist);
09768    return 0;
09769 }
09770 
09771 static struct ast_custom_function iaxvar_function = {
09772    .name = "IAXVAR",
09773    .read = acf_iaxvar_read,
09774    .write = acf_iaxvar_write,
09775 };
09776 
09777 static void set_hangup_source_and_cause(int callno, unsigned char causecode)
09778 {
09779    iax2_lock_owner(callno);
09780    if (iaxs[callno] && iaxs[callno]->owner) {
09781       if (causecode) {
09782          iaxs[callno]->owner->hangupcause = causecode;
09783       }
09784       ast_set_hangupsource(iaxs[callno]->owner, iaxs[callno]->owner->name, 0);
09785       ast_channel_unlock(iaxs[callno]->owner);
09786    }
09787 }
09788 
09789 static int socket_process(struct iax2_thread *thread)
09790 {
09791    struct sockaddr_in sin;
09792    int res;
09793    int updatehistory=1;
09794    int new = NEW_PREVENT;
09795    int dcallno = 0;
09796    char decrypted = 0;
09797    struct ast_iax2_full_hdr *fh = (struct ast_iax2_full_hdr *)thread->buf;
09798    struct ast_iax2_mini_hdr *mh = (struct ast_iax2_mini_hdr *)thread->buf;
09799    struct ast_iax2_meta_hdr *meta = (struct ast_iax2_meta_hdr *)thread->buf;
09800    struct ast_iax2_video_hdr *vh = (struct ast_iax2_video_hdr *)thread->buf;
09801    struct iax_frame *fr;
09802    struct iax_frame *cur;
09803    struct ast_frame f = { 0, };
09804    struct ast_channel *c = NULL;
09805    struct iax2_dpcache *dp;
09806    struct iax2_peer *peer;
09807    struct iax_ies ies;
09808    struct iax_ie_data ied0, ied1;
09809    format_t format;
09810    int fd;
09811    int exists;
09812    int minivid = 0;
09813    char empty[32]="";      /* Safety measure */
09814    struct iax_frame *duped_fr;
09815    char host_pref_buf[128];
09816    char caller_pref_buf[128];
09817    struct ast_codec_pref pref;
09818    char *using_prefs = "mine";
09819 
09820    /* allocate an iax_frame with 4096 bytes of data buffer */
09821    fr = alloca(sizeof(*fr) + 4096);
09822    memset(fr, 0, sizeof(*fr));
09823    fr->afdatalen = 4096; /* From alloca() above */
09824 
09825    /* Copy frequently used parameters to the stack */
09826    res = thread->buf_len;
09827    fd = thread->iofd;
09828    memcpy(&sin, &thread->iosin, sizeof(sin));
09829 
09830    if (res < sizeof(*mh)) {
09831       ast_log(LOG_WARNING, "midget packet received (%d of %d min)\n", res, (int) sizeof(*mh));
09832       return 1;
09833    }
09834    if ((vh->zeros == 0) && (ntohs(vh->callno) & 0x8000)) {
09835       if (res < sizeof(*vh)) {
09836          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));
09837          return 1;
09838       }
09839 
09840       /* This is a video frame, get call number */
09841       fr->callno = find_callno(ntohs(vh->callno) & ~0x8000, dcallno, &sin, new, fd, 0);
09842       minivid = 1;
09843    } else if ((meta->zeros == 0) && !(ntohs(meta->metacmd) & 0x8000))
09844       return socket_process_meta(res, meta, &sin, fd, fr);
09845 
09846 #ifdef DEBUG_SUPPORT
09847    if (res >= sizeof(*fh))
09848       iax_outputframe(NULL, fh, 1, &sin, res - sizeof(*fh));
09849 #endif
09850    if (ntohs(mh->callno) & IAX_FLAG_FULL) {
09851       if (res < sizeof(*fh)) {
09852          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));
09853          return 1;
09854       }
09855 
09856       /* Get the destination call number */
09857       dcallno = ntohs(fh->dcallno) & ~IAX_FLAG_RETRANS;
09858 
09859 
09860       /* check to make sure this full frame isn't encrypted before we attempt
09861        * to look inside of it. If it is encrypted, decrypt it first. Its ok if the
09862        * callno is not found here, that just means one hasn't been allocated for
09863        * this connection yet. */
09864       if ((dcallno != 1) && (fr->callno = find_callno(ntohs(mh->callno) & ~IAX_FLAG_FULL, dcallno, &sin, NEW_PREVENT, fd, 1))) {
09865          ast_mutex_lock(&iaxsl[fr->callno]);
09866          if (iaxs[fr->callno] && ast_test_flag64(iaxs[fr->callno], IAX_ENCRYPTED)) {
09867             if (decrypt_frame(fr->callno, fh, &f, &res)) {
09868                ast_log(LOG_NOTICE, "Packet Decrypt Failed!\n");
09869                ast_mutex_unlock(&iaxsl[fr->callno]);
09870                return 1;
09871             }
09872             decrypted = 1;
09873          }
09874          ast_mutex_unlock(&iaxsl[fr->callno]);
09875       }
09876 
09877       /* Retrieve the type and subclass */
09878       f.frametype = fh->type;
09879       if (f.frametype == AST_FRAME_VIDEO) {
09880          f.subclass.codec = uncompress_subclass(fh->csub & ~0x40) | ((fh->csub >> 6) & 0x1);
09881       } else if (f.frametype == AST_FRAME_VOICE) {
09882          f.subclass.codec = uncompress_subclass(fh->csub);
09883       } else {
09884          f.subclass.integer = uncompress_subclass(fh->csub);
09885       }
09886 
09887       /* Deal with POKE/PONG without allocating a callno */
09888       if (f.frametype == AST_FRAME_IAX && f.subclass.integer == IAX_COMMAND_POKE) {
09889          /* Reply back with a PONG, but don't care about the result. */
09890          send_apathetic_reply(1, ntohs(fh->scallno), &sin, IAX_COMMAND_PONG, ntohl(fh->ts), fh->iseqno + 1, fd, NULL);
09891          return 1;
09892       } else if (f.frametype == AST_FRAME_IAX && f.subclass.integer == IAX_COMMAND_ACK && dcallno == 1) {
09893          /* Ignore */
09894          return 1;
09895       }
09896 
09897       f.datalen = res - sizeof(*fh);
09898       if (f.datalen) {
09899          if (f.frametype == AST_FRAME_IAX) {
09900             if (iax_parse_ies(&ies, thread->buf + sizeof(struct ast_iax2_full_hdr), f.datalen)) {
09901                ast_log(LOG_WARNING, "Undecodable frame received from '%s'\n", ast_inet_ntoa(sin.sin_addr));
09902                ast_variables_destroy(ies.vars);
09903                return 1;
09904             }
09905             f.data.ptr = NULL;
09906             f.datalen = 0;
09907          } else {
09908             f.data.ptr = thread->buf + sizeof(struct ast_iax2_full_hdr);
09909             memset(&ies, 0, sizeof(ies));
09910          }
09911       } else {
09912          if (f.frametype == AST_FRAME_IAX)
09913             f.data.ptr = NULL;
09914          else
09915             f.data.ptr = empty;
09916          memset(&ies, 0, sizeof(ies));
09917       }
09918 
09919       if (!dcallno && iax2_allow_new(f.frametype, f.subclass.integer, 1)) {
09920          /* only set NEW_ALLOW if calltoken checks out */
09921          if (handle_call_token(fh, &ies, &sin, fd)) {
09922             ast_variables_destroy(ies.vars);
09923             return 1;
09924          }
09925 
09926          if (ies.calltoken && ies.calltokendata) {
09927             /* if we've gotten this far, and the calltoken ie data exists,
09928              * then calltoken validation _MUST_ have taken place.  If calltoken
09929              * data is provided, it is always validated reguardless of any
09930              * calltokenoptional or requirecalltoken options */
09931             new = NEW_ALLOW_CALLTOKEN_VALIDATED;
09932          } else {
09933             new = NEW_ALLOW;
09934          }
09935       }
09936    } else {
09937       /* Don't know anything about it yet */
09938       f.frametype = AST_FRAME_NULL;
09939       f.subclass.integer = 0;
09940       memset(&ies, 0, sizeof(ies));
09941    }
09942 
09943    if (!fr->callno) {
09944       int check_dcallno = 0;
09945 
09946       /*
09947        * We enforce accurate destination call numbers for ACKs.  This forces the other
09948        * end to know the destination call number before call setup can complete.
09949        *
09950        * Discussed in the following thread:
09951        *    http://lists.digium.com/pipermail/asterisk-dev/2008-May/033217.html 
09952        */
09953 
09954       if ((ntohs(mh->callno) & IAX_FLAG_FULL) && ((f.frametype == AST_FRAME_IAX) && (f.subclass.integer == IAX_COMMAND_ACK))) {
09955          check_dcallno = 1;
09956       }
09957 
09958       if (!(fr->callno = find_callno(ntohs(mh->callno) & ~IAX_FLAG_FULL, dcallno, &sin, new, fd, check_dcallno))) {
09959          if (f.frametype == AST_FRAME_IAX && f.subclass.integer == IAX_COMMAND_NEW) {
09960             send_apathetic_reply(1, ntohs(fh->scallno), &sin, IAX_COMMAND_REJECT, ntohl(fh->ts), fh->iseqno + 1, fd, NULL);
09961          } else if (f.frametype == AST_FRAME_IAX && (f.subclass.integer == IAX_COMMAND_REGREQ || f.subclass.integer == IAX_COMMAND_REGREL)) {
09962             send_apathetic_reply(1, ntohs(fh->scallno), &sin, IAX_COMMAND_REGREJ, ntohl(fh->ts), fh->iseqno + 1, fd, NULL);
09963          }
09964          ast_variables_destroy(ies.vars);
09965          return 1;
09966       }
09967    }
09968 
09969    if (fr->callno > 0)
09970       ast_mutex_lock(&iaxsl[fr->callno]);
09971 
09972    if (!fr->callno || !iaxs[fr->callno]) {
09973       /* A call arrived for a nonexistent destination.  Unless it's an "inval"
09974          frame, reply with an inval */
09975       if (ntohs(mh->callno) & IAX_FLAG_FULL) {
09976          /* We can only raw hangup control frames */
09977          if (((f.subclass.integer != IAX_COMMAND_INVAL) &&
09978              (f.subclass.integer != IAX_COMMAND_TXCNT) &&
09979              (f.subclass.integer != IAX_COMMAND_TXACC) &&
09980              (f.subclass.integer != IAX_COMMAND_FWDOWNL))||
09981              (f.frametype != AST_FRAME_IAX))
09982             raw_hangup(&sin, ntohs(fh->dcallno) & ~IAX_FLAG_RETRANS, ntohs(mh->callno) & ~IAX_FLAG_FULL,
09983             fd);
09984       }
09985       if (fr->callno > 0) 
09986          ast_mutex_unlock(&iaxsl[fr->callno]);
09987       ast_variables_destroy(ies.vars);
09988       return 1;
09989    }
09990    if (ast_test_flag64(iaxs[fr->callno], IAX_ENCRYPTED) && !decrypted) {
09991       if (decrypt_frame(fr->callno, fh, &f, &res)) {
09992          ast_log(LOG_NOTICE, "Packet Decrypt Failed!\n");
09993          ast_variables_destroy(ies.vars);
09994          ast_mutex_unlock(&iaxsl[fr->callno]);
09995          return 1;
09996       }
09997       decrypted = 1;
09998    }
09999 
10000 #ifdef DEBUG_SUPPORT
10001    if (decrypted) {
10002       iax_outputframe(NULL, fh, 3, &sin, res - sizeof(*fh));
10003    }
10004 #endif
10005 
10006 
10007    /* count this frame */
10008    iaxs[fr->callno]->frames_received++;
10009 
10010    if (!inaddrcmp(&sin, &iaxs[fr->callno]->addr) && !minivid &&
10011       f.subclass.integer != IAX_COMMAND_TXCNT &&      /* for attended transfer */
10012       f.subclass.integer != IAX_COMMAND_TXACC) {      /* for attended transfer */
10013       unsigned short new_peercallno;
10014       
10015       new_peercallno = (unsigned short) (ntohs(mh->callno) & ~IAX_FLAG_FULL);
10016       if (new_peercallno && new_peercallno != iaxs[fr->callno]->peercallno) {
10017          if (iaxs[fr->callno]->peercallno) {
10018             remove_by_peercallno(iaxs[fr->callno]);
10019          }
10020          iaxs[fr->callno]->peercallno = new_peercallno;
10021          store_by_peercallno(iaxs[fr->callno]);
10022       }
10023    }
10024    if (ntohs(mh->callno) & IAX_FLAG_FULL) {
10025       if (iaxdebug)
10026          ast_debug(1, "Received packet %d, (%d, %u)\n", fh->oseqno, f.frametype, f.subclass.integer);
10027       /* Check if it's out of order (and not an ACK or INVAL) */
10028       fr->oseqno = fh->oseqno;
10029       fr->iseqno = fh->iseqno;
10030       fr->ts = ntohl(fh->ts);
10031 #ifdef IAXTESTS
10032       if (test_resync) {
10033          ast_debug(1, "Simulating frame ts resync, was %u now %u\n", fr->ts, fr->ts + test_resync);
10034          fr->ts += test_resync;
10035       }
10036 #endif /* IAXTESTS */
10037 #if 0
10038       if ( (ntohs(fh->dcallno) & IAX_FLAG_RETRANS) ||
10039            ( (f.frametype != AST_FRAME_VOICE) && ! (f.frametype == AST_FRAME_IAX &&
10040                         (f.subclass == IAX_COMMAND_NEW ||
10041                          f.subclass == IAX_COMMAND_AUTHREQ ||
10042                          f.subclass == IAX_COMMAND_ACCEPT ||
10043                          f.subclass == IAX_COMMAND_REJECT))      ) )
10044 #endif
10045       if ((ntohs(fh->dcallno) & IAX_FLAG_RETRANS) || (f.frametype != AST_FRAME_VOICE))
10046          updatehistory = 0;
10047       if ((iaxs[fr->callno]->iseqno != fr->oseqno) &&
10048          (iaxs[fr->callno]->iseqno ||
10049             ((f.subclass.integer != IAX_COMMAND_TXCNT) &&
10050             (f.subclass.integer != IAX_COMMAND_TXREADY) &&     /* for attended transfer */
10051             (f.subclass.integer != IAX_COMMAND_TXREL) &&    /* for attended transfer */
10052             (f.subclass.integer != IAX_COMMAND_UNQUELCH ) &&   /* for attended transfer */
10053             (f.subclass.integer != IAX_COMMAND_TXACC)) ||
10054             (f.frametype != AST_FRAME_IAX))) {
10055          if (
10056           ((f.subclass.integer != IAX_COMMAND_ACK) &&
10057            (f.subclass.integer != IAX_COMMAND_INVAL) &&
10058            (f.subclass.integer != IAX_COMMAND_TXCNT) &&
10059            (f.subclass.integer != IAX_COMMAND_TXREADY) &&      /* for attended transfer */
10060            (f.subclass.integer != IAX_COMMAND_TXREL) &&     /* for attended transfer */
10061            (f.subclass.integer != IAX_COMMAND_UNQUELCH ) && /* for attended transfer */
10062            (f.subclass.integer != IAX_COMMAND_TXACC) &&
10063            (f.subclass.integer != IAX_COMMAND_VNAK)) ||
10064            (f.frametype != AST_FRAME_IAX)) {
10065             /* If it's not an ACK packet, it's out of order. */
10066             ast_debug(1, "Packet arrived out of order (expecting %d, got %d) (frametype = %d, subclass = %d)\n", 
10067                iaxs[fr->callno]->iseqno, fr->oseqno, f.frametype, f.subclass.integer);
10068             /* Check to see if we need to request retransmission,
10069              * and take sequence number wraparound into account */
10070             if ((unsigned char) (iaxs[fr->callno]->iseqno - fr->oseqno) < 128) {
10071                /* If we've already seen it, ack it XXX There's a border condition here XXX */
10072                if ((f.frametype != AST_FRAME_IAX) || 
10073                      ((f.subclass.integer != IAX_COMMAND_ACK) && (f.subclass.integer != IAX_COMMAND_INVAL))) {
10074                   ast_debug(1, "Acking anyway\n");
10075                   /* XXX Maybe we should handle its ack to us, but then again, it's probably outdated anyway, and if
10076                      we have anything to send, we'll retransmit and get an ACK back anyway XXX */
10077                   send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
10078                }
10079             } else {
10080                /* Send a VNAK requesting retransmission */
10081                iax2_vnak(fr->callno);
10082             }
10083             ast_variables_destroy(ies.vars);
10084             ast_mutex_unlock(&iaxsl[fr->callno]);
10085             return 1;
10086          }
10087       } else {
10088          /* Increment unless it's an ACK or VNAK */
10089          if (((f.subclass.integer != IAX_COMMAND_ACK) &&
10090              (f.subclass.integer != IAX_COMMAND_INVAL) &&
10091              (f.subclass.integer != IAX_COMMAND_TXCNT) &&
10092              (f.subclass.integer != IAX_COMMAND_TXACC) &&
10093             (f.subclass.integer != IAX_COMMAND_VNAK)) ||
10094              (f.frametype != AST_FRAME_IAX))
10095             iaxs[fr->callno]->iseqno++;
10096       }
10097       /* Ensure text frames are NULL-terminated */
10098       if (f.frametype == AST_FRAME_TEXT && thread->buf[res - 1] != '\0') {
10099          if (res < thread->buf_size)
10100             thread->buf[res++] = '\0';
10101          else /* Trims one character from the text message, but that's better than overwriting the end of the buffer. */
10102             thread->buf[res - 1] = '\0';
10103       }
10104 
10105       /* Handle implicit ACKing unless this is an INVAL, and only if this is 
10106          from the real peer, not the transfer peer */
10107       if (!inaddrcmp(&sin, &iaxs[fr->callno]->addr) && 
10108           ((f.subclass.integer != IAX_COMMAND_INVAL) ||
10109            (f.frametype != AST_FRAME_IAX))) {
10110          unsigned char x;
10111          int call_to_destroy;
10112          /* First we have to qualify that the ACKed value is within our window */
10113          if (iaxs[fr->callno]->rseqno >= iaxs[fr->callno]->oseqno || (fr->iseqno >= iaxs[fr->callno]->rseqno && fr->iseqno < iaxs[fr->callno]->oseqno))
10114             x = fr->iseqno;
10115          else 
10116             x = iaxs[fr->callno]->oseqno;
10117          if ((x != iaxs[fr->callno]->oseqno) || (iaxs[fr->callno]->oseqno == fr->iseqno)) {
10118             /* The acknowledgement is within our window.  Time to acknowledge everything
10119                that it says to */
10120             for (x=iaxs[fr->callno]->rseqno; x != fr->iseqno; x++) {
10121                /* Ack the packet with the given timestamp */
10122                if (iaxdebug)
10123                   ast_debug(1, "Cancelling transmission of packet %d\n", x);
10124                call_to_destroy = 0;
10125                AST_LIST_TRAVERSE(&frame_queue[fr->callno], cur, list) {
10126                   /* If it's our call, and our timestamp, mark -1 retries */
10127                   if (x == cur->oseqno) {
10128                      cur->retries = -1;
10129                      /* Destroy call if this is the end */
10130                      if (cur->final)
10131                         call_to_destroy = fr->callno;
10132                   }
10133                }
10134                if (call_to_destroy) {
10135                   if (iaxdebug)
10136                      ast_debug(1, "Really destroying %d, having been acked on final message\n", call_to_destroy);
10137                   ast_mutex_lock(&iaxsl[call_to_destroy]);
10138                   iax2_destroy(call_to_destroy);
10139                   ast_mutex_unlock(&iaxsl[call_to_destroy]);
10140                }
10141             }
10142             /* Note how much we've received acknowledgement for */
10143             if (iaxs[fr->callno])
10144                iaxs[fr->callno]->rseqno = fr->iseqno;
10145             else {
10146                /* Stop processing now */
10147                ast_variables_destroy(ies.vars);
10148                ast_mutex_unlock(&iaxsl[fr->callno]);
10149                return 1;
10150             }
10151          } else {
10152             ast_debug(1, "Received iseqno %d not within window %d->%d\n", fr->iseqno, iaxs[fr->callno]->rseqno, iaxs[fr->callno]->oseqno);
10153          }
10154       }
10155       if (inaddrcmp(&sin, &iaxs[fr->callno]->addr) && 
10156          ((f.frametype != AST_FRAME_IAX) || 
10157           ((f.subclass.integer != IAX_COMMAND_TXACC) &&
10158            (f.subclass.integer != IAX_COMMAND_TXCNT)))) {
10159          /* Only messages we accept from a transfer host are TXACC and TXCNT */
10160          ast_variables_destroy(ies.vars);
10161          ast_mutex_unlock(&iaxsl[fr->callno]);
10162          return 1;
10163       }
10164 
10165       /* when we receive the first full frame for a new incoming channel,
10166          it is safe to start the PBX on the channel because we have now
10167          completed a 3-way handshake with the peer */
10168       if ((f.frametype == AST_FRAME_VOICE) ||
10169           (f.frametype == AST_FRAME_VIDEO) ||
10170           (f.frametype == AST_FRAME_IAX)) {
10171          if (ast_test_flag64(iaxs[fr->callno], IAX_DELAYPBXSTART)) {
10172             ast_clear_flag64(iaxs[fr->callno], IAX_DELAYPBXSTART);
10173             if (!ast_iax2_new(fr->callno, AST_STATE_RING, iaxs[fr->callno]->chosenformat, NULL)) {
10174                ast_variables_destroy(ies.vars);
10175                ast_mutex_unlock(&iaxsl[fr->callno]);
10176                return 1;
10177             }
10178          }
10179 
10180          if (ies.vars) {
10181             struct ast_datastore *variablestore = NULL;
10182             struct ast_variable *var, *prev = NULL;
10183             AST_LIST_HEAD(, ast_var_t) *varlist;
10184 
10185             iax2_lock_owner(fr->callno);
10186             if (!iaxs[fr->callno]) {
10187                ast_variables_destroy(ies.vars);
10188                ast_mutex_unlock(&iaxsl[fr->callno]);
10189                return 1;
10190             }
10191             if ((c = iaxs[fr->callno]->owner)) {
10192                varlist = ast_calloc(1, sizeof(*varlist));
10193                variablestore = ast_datastore_alloc(&iax2_variable_datastore_info, NULL);
10194 
10195                if (variablestore && varlist) {
10196                   variablestore->data = varlist;
10197                   variablestore->inheritance = DATASTORE_INHERIT_FOREVER;
10198                   AST_LIST_HEAD_INIT(varlist);
10199                   ast_debug(1, "I can haz IAX vars?\n");
10200                   for (var = ies.vars; var; var = var->next) {
10201                      struct ast_var_t *newvar = ast_var_assign(var->name, var->value);
10202                      if (prev) {
10203                         ast_free(prev);
10204                      }
10205                      prev = var;
10206                      if (!newvar) {
10207                         /* Don't abort list traversal, as this would leave ies.vars in an inconsistent state. */
10208                         ast_log(LOG_ERROR, "Memory allocation error while processing IAX2 variables\n");
10209                      } else {
10210                         AST_LIST_INSERT_TAIL(varlist, newvar, entries);
10211                      }
10212                   }
10213                   if (prev) {
10214                      ast_free(prev);
10215                   }
10216                   ies.vars = NULL;
10217                   ast_channel_datastore_add(c, variablestore);
10218                } else {
10219                   ast_log(LOG_ERROR, "Memory allocation error while processing IAX2 variables\n");
10220                   if (variablestore) {
10221                      ast_datastore_free(variablestore);
10222                   }
10223                   if (varlist) {
10224                      ast_free(varlist);
10225                   }
10226                }
10227                ast_channel_unlock(c);
10228             } else {
10229                /* No channel yet, so transfer the variables directly over to the pvt,
10230                 * for later inheritance. */
10231                ast_debug(1, "No channel, so populating IAXVARs to the pvt, as an intermediate step.\n");
10232                for (var = ies.vars; var && var->next; var = var->next);
10233                if (var) {
10234                   var->next = iaxs[fr->callno]->iaxvars;
10235                   iaxs[fr->callno]->iaxvars = ies.vars;
10236                   ies.vars = NULL;
10237                }
10238             }
10239          }
10240 
10241          if (ies.vars) {
10242             ast_debug(1, "I have IAX variables, but they were not processed\n");
10243          }
10244       }
10245 
10246       /* once we receive our first IAX Full Frame that is not CallToken related, send all
10247        * queued signaling frames that were being held. */
10248       if ((f.frametype == AST_FRAME_IAX) && (f.subclass.integer != IAX_COMMAND_CALLTOKEN) && iaxs[fr->callno]->hold_signaling) {
10249          send_signaling(iaxs[fr->callno]);
10250       }
10251 
10252       if (f.frametype == AST_FRAME_VOICE) {
10253          if (f.subclass.codec != iaxs[fr->callno]->voiceformat) {
10254                iaxs[fr->callno]->voiceformat = f.subclass.codec;
10255                ast_debug(1, "Ooh, voice format changed to '%s'\n", ast_getformatname(f.subclass.codec));
10256                if (iaxs[fr->callno]->owner) {
10257                   iax2_lock_owner(fr->callno);
10258                   if (iaxs[fr->callno]) {
10259                      if (iaxs[fr->callno]->owner) {
10260                         format_t orignative;
10261 
10262                         orignative = iaxs[fr->callno]->owner->nativeformats;
10263                         iaxs[fr->callno]->owner->nativeformats = f.subclass.codec;
10264                         if (iaxs[fr->callno]->owner->readformat)
10265                            ast_set_read_format(iaxs[fr->callno]->owner, iaxs[fr->callno]->owner->readformat);
10266                         iaxs[fr->callno]->owner->nativeformats = orignative;
10267                         ast_channel_unlock(iaxs[fr->callno]->owner);
10268                      }
10269                   } else {
10270                      ast_debug(1, "Neat, somebody took away the channel at a magical time but i found it!\n");
10271                      /* Free remote variables (if any) */
10272                      if (ies.vars) {
10273                         ast_variables_destroy(ies.vars);
10274                         ast_debug(1, "I can haz iaxvars, but they is no good.  :-(\n");
10275                         ies.vars = NULL;
10276                      }
10277                      ast_mutex_unlock(&iaxsl[fr->callno]);
10278                      return 1;
10279                   }
10280                }
10281          }
10282       }
10283       if (f.frametype == AST_FRAME_VIDEO) {
10284          if (f.subclass.codec != iaxs[fr->callno]->videoformat) {
10285             ast_debug(1, "Ooh, video format changed to %s\n", ast_getformatname(f.subclass.codec & ~0x1LL));
10286             iaxs[fr->callno]->videoformat = f.subclass.codec & ~0x1LL;
10287          }
10288       }
10289       if (f.frametype == AST_FRAME_CONTROL && iaxs[fr->callno]->owner) {
10290          if (f.subclass.integer == AST_CONTROL_BUSY) {
10291             iaxs[fr->callno]->owner->hangupcause = AST_CAUSE_BUSY;
10292          } else if (f.subclass.integer == AST_CONTROL_CONGESTION) {
10293             iaxs[fr->callno]->owner->hangupcause = AST_CAUSE_CONGESTION;
10294          }
10295       }
10296       if (f.frametype == AST_FRAME_IAX) {
10297          ast_sched_thread_del(sched, iaxs[fr->callno]->initid);
10298          /* Handle the IAX pseudo frame itself */
10299          if (iaxdebug)
10300             ast_debug(1, "IAX subclass %d received\n", f.subclass.integer);
10301 
10302                         /* Update last ts unless the frame's timestamp originated with us. */
10303          if (iaxs[fr->callno]->last < fr->ts &&
10304                             f.subclass.integer != IAX_COMMAND_ACK &&
10305                             f.subclass.integer != IAX_COMMAND_PONG &&
10306                             f.subclass.integer != IAX_COMMAND_LAGRP) {
10307             iaxs[fr->callno]->last = fr->ts;
10308             if (iaxdebug)
10309                ast_debug(1, "For call=%d, set last=%d\n", fr->callno, fr->ts);
10310          }
10311          iaxs[fr->callno]->last_iax_message = f.subclass.integer;
10312          if (!iaxs[fr->callno]->first_iax_message) {
10313             iaxs[fr->callno]->first_iax_message = f.subclass.integer;
10314          }
10315          switch(f.subclass.integer) {
10316          case IAX_COMMAND_ACK:
10317             /* Do nothing */
10318             break;
10319          case IAX_COMMAND_QUELCH:
10320             if (ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED)) {
10321                     /* Generate Manager Hold event, if necessary*/
10322                if (iaxs[fr->callno]->owner) {
10323                   ast_manager_event(iaxs[fr->callno]->owner, EVENT_FLAG_CALL, "Hold",
10324                      "Status: On\r\n"
10325                      "Channel: %s\r\n"
10326                      "Uniqueid: %s\r\n",
10327                      iaxs[fr->callno]->owner->name,
10328                      iaxs[fr->callno]->owner->uniqueid);
10329                }
10330 
10331                ast_set_flag64(iaxs[fr->callno], IAX_QUELCH);
10332                if (ies.musiconhold) {
10333                   iax2_lock_owner(fr->callno);
10334                   if (!iaxs[fr->callno] || !iaxs[fr->callno]->owner) {
10335                      break;
10336                   }
10337                   if (ast_bridged_channel(iaxs[fr->callno]->owner)) {
10338                      const char *moh_suggest = iaxs[fr->callno]->mohsuggest;
10339 
10340                      /*
10341                       * We already hold the owner lock so we do not
10342                       * need to check iaxs[fr->callno] after it returns.
10343                       */
10344                      iax2_queue_control_data(fr->callno, AST_CONTROL_HOLD, 
10345                         S_OR(moh_suggest, NULL),
10346                         !ast_strlen_zero(moh_suggest) ? strlen(moh_suggest) + 1 : 0);
10347                   }
10348                   ast_channel_unlock(iaxs[fr->callno]->owner);
10349                }
10350             }
10351             break;
10352          case IAX_COMMAND_UNQUELCH:
10353             if (ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED)) {
10354                iax2_lock_owner(fr->callno);
10355                if (!iaxs[fr->callno]) {
10356                   break;
10357                }
10358                /* Generate Manager Unhold event, if necessary */
10359                if (iaxs[fr->callno]->owner && ast_test_flag64(iaxs[fr->callno], IAX_QUELCH)) {
10360                   ast_manager_event(iaxs[fr->callno]->owner, EVENT_FLAG_CALL, "Hold",
10361                      "Status: Off\r\n"
10362                      "Channel: %s\r\n"
10363                      "Uniqueid: %s\r\n",
10364                      iaxs[fr->callno]->owner->name,
10365                      iaxs[fr->callno]->owner->uniqueid);
10366                }
10367 
10368                ast_clear_flag64(iaxs[fr->callno], IAX_QUELCH);
10369                if (!iaxs[fr->callno]->owner) {
10370                   break;
10371                }
10372                if (ast_bridged_channel(iaxs[fr->callno]->owner)) {
10373                   /*
10374                    * We already hold the owner lock so we do not
10375                    * need to check iaxs[fr->callno] after it returns.
10376                    */
10377                   iax2_queue_control_data(fr->callno, AST_CONTROL_UNHOLD, NULL, 0);
10378                }
10379                ast_channel_unlock(iaxs[fr->callno]->owner);
10380             }
10381             break;
10382          case IAX_COMMAND_TXACC:
10383             if (iaxs[fr->callno]->transferring == TRANSFER_BEGIN) {
10384                /* Ack the packet with the given timestamp */
10385                AST_LIST_TRAVERSE(&frame_queue[fr->callno], cur, list) {
10386                   /* Cancel any outstanding txcnt's */
10387                   if (cur->transfer) {
10388                      cur->retries = -1;
10389                   }
10390                }
10391                memset(&ied1, 0, sizeof(ied1));
10392                iax_ie_append_short(&ied1, IAX_IE_CALLNO, iaxs[fr->callno]->callno);
10393                send_command(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_TXREADY, 0, ied1.buf, ied1.pos, -1);
10394                iaxs[fr->callno]->transferring = TRANSFER_READY;
10395             }
10396             break;
10397          case IAX_COMMAND_NEW:
10398             /* Ignore if it's already up */
10399             if (ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED | IAX_STATE_TBD))
10400                break;
10401             if (ies.provverpres && ies.serviceident && sin.sin_addr.s_addr) {
10402                ast_mutex_unlock(&iaxsl[fr->callno]);
10403                check_provisioning(&sin, fd, ies.serviceident, ies.provver);
10404                ast_mutex_lock(&iaxsl[fr->callno]);
10405                if (!iaxs[fr->callno]) {
10406                   break;
10407                }
10408             }
10409             /* If we're in trunk mode, do it now, and update the trunk number in our frame before continuing */
10410             if (ast_test_flag64(iaxs[fr->callno], IAX_TRUNK)) {
10411                int new_callno;
10412                if ((new_callno = make_trunk(fr->callno, 1)) != -1)
10413                   fr->callno = new_callno;
10414             }
10415             /* For security, always ack immediately */
10416             if (delayreject)
10417                send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
10418             if (check_access(fr->callno, &sin, &ies)) {
10419                /* They're not allowed on */
10420                auth_fail(fr->callno, IAX_COMMAND_REJECT);
10421                if (authdebug)
10422                   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);
10423                break;
10424             }
10425             if (ast_strlen_zero(iaxs[fr->callno]->secret) && ast_test_flag64(iaxs[fr->callno], IAX_FORCE_ENCRYPT)) {
10426                auth_fail(fr->callno, IAX_COMMAND_REJECT);
10427                ast_log(LOG_WARNING, "Rejected connect attempt.  No secret present while force encrypt enabled.\n");
10428                break;
10429             }
10430             if (strcasecmp(iaxs[fr->callno]->exten, "TBD")) {
10431                const char *context, *exten, *cid_num;
10432 
10433                context = ast_strdupa(iaxs[fr->callno]->context);
10434                exten = ast_strdupa(iaxs[fr->callno]->exten);
10435                cid_num = ast_strdupa(iaxs[fr->callno]->cid_num);
10436 
10437                /* This might re-enter the IAX code and need the lock */
10438                ast_mutex_unlock(&iaxsl[fr->callno]);
10439                exists = ast_exists_extension(NULL, context, exten, 1, cid_num);
10440                ast_mutex_lock(&iaxsl[fr->callno]);
10441 
10442                if (!iaxs[fr->callno]) {
10443                   break;
10444                }
10445             } else
10446                exists = 0;
10447             /* Get OSP token if it does exist */
10448             save_osptoken(fr, &ies);
10449             if (ast_strlen_zero(iaxs[fr->callno]->secret) && ast_strlen_zero(iaxs[fr->callno]->inkeys)) {
10450                if (strcmp(iaxs[fr->callno]->exten, "TBD") && !exists) {
10451                   memset(&ied0, 0, sizeof(ied0));
10452                   iax_ie_append_str(&ied0, IAX_IE_CAUSE, "No such context/extension");
10453                   iax_ie_append_byte(&ied0, IAX_IE_CAUSECODE, AST_CAUSE_NO_ROUTE_DESTINATION);
10454                   send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
10455                   if (!iaxs[fr->callno]) {
10456                      break;
10457                   }
10458                   if (authdebug)
10459                      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);
10460                } else {
10461                   /* Select an appropriate format */
10462 
10463                   if(ast_test_flag64(iaxs[fr->callno], IAX_CODEC_NOPREFS)) {
10464                      if(ast_test_flag64(iaxs[fr->callno], IAX_CODEC_NOCAP)) {
10465                         using_prefs = "reqonly";
10466                      } else {
10467                         using_prefs = "disabled";
10468                      }
10469                      format = iaxs[fr->callno]->peerformat & iaxs[fr->callno]->capability;
10470                      memset(&pref, 0, sizeof(pref));
10471                      strcpy(caller_pref_buf, "disabled");
10472                      strcpy(host_pref_buf, "disabled");
10473                   } else {
10474                      using_prefs = "mine";
10475                      /* If the information elements are in here... use them */
10476                      if (ies.codec_prefs)
10477                         ast_codec_pref_convert(&iaxs[fr->callno]->rprefs, ies.codec_prefs, 32, 0);
10478                      if (ast_codec_pref_index(&iaxs[fr->callno]->rprefs, 0)) {
10479                         /* If we are codec_first_choice we let the caller have the 1st shot at picking the codec.*/
10480                         if (ast_test_flag64(iaxs[fr->callno], IAX_CODEC_USER_FIRST)) {
10481                            pref = iaxs[fr->callno]->rprefs;
10482                            using_prefs = "caller";
10483                         } else {
10484                            pref = iaxs[fr->callno]->prefs;
10485                         }
10486                      } else
10487                         pref = iaxs[fr->callno]->prefs;
10488 
10489                      format = ast_codec_choose(&pref, iaxs[fr->callno]->capability & iaxs[fr->callno]->peercapability, 0);
10490                      ast_codec_pref_string(&iaxs[fr->callno]->rprefs, caller_pref_buf, sizeof(caller_pref_buf) - 1);
10491                      ast_codec_pref_string(&iaxs[fr->callno]->prefs, host_pref_buf, sizeof(host_pref_buf) - 1);
10492                   }
10493                   if (!format) {
10494                      if(!ast_test_flag64(iaxs[fr->callno], IAX_CODEC_NOCAP))
10495                         format = iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability;
10496                      if (!format) {
10497                         memset(&ied0, 0, sizeof(ied0));
10498                         iax_ie_append_str(&ied0, IAX_IE_CAUSE, "Unable to negotiate codec");
10499                         iax_ie_append_byte(&ied0, IAX_IE_CAUSECODE, AST_CAUSE_BEARERCAPABILITY_NOTAVAIL);
10500                         send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
10501                         if (!iaxs[fr->callno]) {
10502                            break;
10503                         }
10504                         if (authdebug) {
10505                            char tmp[256], tmp2[256], tmp3[256];
10506                            if (ast_test_flag64(iaxs[fr->callno], IAX_CODEC_NOCAP)) {
10507                               ast_log(LOG_NOTICE, "Rejected connect attempt from %s, requested '%s' incompatible with our capability '%s'.\n",
10508                                  ast_inet_ntoa(sin.sin_addr),
10509                                  ast_getformatname_multiple(tmp, sizeof(tmp), iaxs[fr->callno]->peerformat),
10510                                  ast_getformatname_multiple(tmp2, sizeof(tmp2), iaxs[fr->callno]->capability));
10511                            } else {
10512                               ast_log(LOG_NOTICE, "Rejected connect attempt from %s, requested/capability '%s'/'%s' incompatible with our capability '%s'.\n",
10513                                  ast_inet_ntoa(sin.sin_addr),
10514                                  ast_getformatname_multiple(tmp, sizeof(tmp), iaxs[fr->callno]->peerformat),
10515                                  ast_getformatname_multiple(tmp2, sizeof(tmp2), iaxs[fr->callno]->peercapability),
10516                                  ast_getformatname_multiple(tmp3, sizeof(tmp3), iaxs[fr->callno]->capability));
10517                            }
10518                         }
10519                      } else {
10520                         /* Pick one... */
10521                         if(ast_test_flag64(iaxs[fr->callno], IAX_CODEC_NOCAP)) {
10522                            if(!(iaxs[fr->callno]->peerformat & iaxs[fr->callno]->capability))
10523                               format = 0;
10524                         } else {
10525                            if(ast_test_flag64(iaxs[fr->callno], IAX_CODEC_NOPREFS)) {
10526                               using_prefs = ast_test_flag64(iaxs[fr->callno], IAX_CODEC_NOCAP) ? "reqonly" : "disabled";
10527                               memset(&pref, 0, sizeof(pref));
10528                               format = ast_best_codec(iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability);
10529                               strcpy(caller_pref_buf,"disabled");
10530                               strcpy(host_pref_buf,"disabled");
10531                            } else {
10532                               using_prefs = "mine";
10533                               if (ast_codec_pref_index(&iaxs[fr->callno]->rprefs, 0)) {
10534                                  /* Do the opposite of what we tried above. */
10535                                  if (ast_test_flag64(iaxs[fr->callno], IAX_CODEC_USER_FIRST)) {
10536                                     pref = iaxs[fr->callno]->prefs;
10537                                  } else {
10538                                     pref = iaxs[fr->callno]->rprefs;
10539                                     using_prefs = "caller";
10540                                  }
10541                                  format = ast_codec_choose(&pref, iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability, 1);
10542                               } else /* if no codec_prefs IE do it the old way */
10543                                  format = ast_best_codec(iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability);
10544                            }
10545                         }
10546 
10547                         if (!format) {
10548                            char tmp[256], tmp2[256], tmp3[256];
10549                            memset(&ied0, 0, sizeof(ied0));
10550                            iax_ie_append_str(&ied0, IAX_IE_CAUSE, "Unable to negotiate codec");
10551                            iax_ie_append_byte(&ied0, IAX_IE_CAUSECODE, AST_CAUSE_BEARERCAPABILITY_NOTAVAIL);
10552                            ast_log(LOG_ERROR, "No best format in '%s'???\n", ast_getformatname_multiple(tmp, sizeof(tmp), iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability));
10553                            send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
10554                            if (!iaxs[fr->callno]) {
10555                               break;
10556                            }
10557                            if (authdebug) {
10558                               ast_log(LOG_NOTICE, "Rejected connect attempt from %s, requested/capability '%s'/'%s' incompatible with our capability '%s'.\n",
10559                                  ast_inet_ntoa(sin.sin_addr),
10560                                  ast_getformatname_multiple(tmp, sizeof(tmp), iaxs[fr->callno]->peerformat),
10561                                  ast_getformatname_multiple(tmp2, sizeof(tmp2), iaxs[fr->callno]->peercapability),
10562                                  ast_getformatname_multiple(tmp3, sizeof(tmp3), iaxs[fr->callno]->capability));
10563                            }
10564                            ast_set_flag64(iaxs[fr->callno], IAX_ALREADYGONE);
10565                            break;
10566                         }
10567                      }
10568                   }
10569                   if (format) {
10570                      /* No authentication required, let them in */
10571                      memset(&ied1, 0, sizeof(ied1));
10572                      iax_ie_append_int(&ied1, IAX_IE_FORMAT, format);
10573                      iax_ie_append_versioned_uint64(&ied1, IAX_IE_FORMAT2, 0, format);
10574                      send_command(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACCEPT, 0, ied1.buf, ied1.pos, -1);
10575                      if (strcmp(iaxs[fr->callno]->exten, "TBD")) {
10576                         ast_set_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED);
10577                         ast_verb(3, "Accepting UNAUTHENTICATED call from %s:\n"
10578                                     "%srequested format = %s,\n"
10579                                     "%srequested prefs = %s,\n"
10580                                     "%sactual format = %s,\n"
10581                                     "%shost prefs = %s,\n"
10582                                     "%spriority = %s\n",
10583                                     ast_inet_ntoa(sin.sin_addr), 
10584                                     VERBOSE_PREFIX_4,
10585                                     ast_getformatname(iaxs[fr->callno]->peerformat), 
10586                                     VERBOSE_PREFIX_4,
10587                                     caller_pref_buf,
10588                                     VERBOSE_PREFIX_4,
10589                                     ast_getformatname(format), 
10590                                     VERBOSE_PREFIX_4,
10591                                     host_pref_buf, 
10592                                     VERBOSE_PREFIX_4,
10593                                     using_prefs);
10594 
10595                         iaxs[fr->callno]->chosenformat = format;
10596                         ast_set_flag64(iaxs[fr->callno], IAX_DELAYPBXSTART);
10597                      } else {
10598                         ast_set_flag(&iaxs[fr->callno]->state, IAX_STATE_TBD);
10599                         /* If this is a TBD call, we're ready but now what...  */
10600                         ast_verb(3, "Accepted unauthenticated TBD call from %s\n", ast_inet_ntoa(sin.sin_addr));
10601                      }
10602                   }
10603                }
10604                break;
10605             }
10606             if (iaxs[fr->callno]->authmethods & IAX_AUTH_MD5)
10607                merge_encryption(iaxs[fr->callno],ies.encmethods);
10608             else
10609                iaxs[fr->callno]->encmethods = 0;
10610             if (!authenticate_request(fr->callno) && iaxs[fr->callno])
10611                ast_set_flag(&iaxs[fr->callno]->state, IAX_STATE_AUTHENTICATED);
10612             break;
10613          case IAX_COMMAND_DPREQ:
10614             /* Request status in the dialplan */
10615             if (ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_TBD) &&
10616                !ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED) && ies.called_number) {
10617                if (iaxcompat) {
10618                   /* Spawn a thread for the lookup */
10619                   spawn_dp_lookup(fr->callno, iaxs[fr->callno]->context, ies.called_number, iaxs[fr->callno]->cid_num);
10620                } else {
10621                   /* Just look it up */
10622                   dp_lookup(fr->callno, iaxs[fr->callno]->context, ies.called_number, iaxs[fr->callno]->cid_num, 1);
10623                }
10624             }
10625             break;
10626          case IAX_COMMAND_HANGUP:
10627             ast_set_flag64(iaxs[fr->callno], IAX_ALREADYGONE);
10628             ast_debug(1, "Immediately destroying %d, having received hangup\n", fr->callno);
10629             /* Set hangup cause according to remote and hangupsource */
10630             if (iaxs[fr->callno]->owner) {
10631                set_hangup_source_and_cause(fr->callno, ies.causecode);
10632                if (!iaxs[fr->callno]) {
10633                   break;
10634                }
10635             }
10636 
10637             /* Send ack immediately, before we destroy */
10638             send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
10639             iax2_destroy(fr->callno);
10640             break;
10641          case IAX_COMMAND_REJECT:
10642             /* Set hangup cause according to remote and hangup source */
10643             if (iaxs[fr->callno]->owner) {
10644                set_hangup_source_and_cause(fr->callno, ies.causecode);
10645                if (!iaxs[fr->callno]) {
10646                   break;
10647                }
10648             }
10649 
10650             if (!ast_test_flag64(iaxs[fr->callno], IAX_PROVISION)) {
10651                if (iaxs[fr->callno]->owner && authdebug)
10652                   ast_log(LOG_WARNING, "Call rejected by %s: %s\n",
10653                      ast_inet_ntoa(iaxs[fr->callno]->addr.sin_addr),
10654                      ies.cause ? ies.cause : "<Unknown>");
10655                ast_debug(1, "Immediately destroying %d, having received reject\n",
10656                   fr->callno);
10657             }
10658             /* Send ack immediately, before we destroy */
10659             send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK,
10660                          fr->ts, NULL, 0, fr->iseqno);
10661             if (!ast_test_flag64(iaxs[fr->callno], IAX_PROVISION))
10662                iaxs[fr->callno]->error = EPERM;
10663             iax2_destroy(fr->callno);
10664             break;
10665          case IAX_COMMAND_TRANSFER:
10666          {
10667             struct ast_channel *bridged_chan;
10668             struct ast_channel *owner;
10669 
10670             iax2_lock_owner(fr->callno);
10671             if (!iaxs[fr->callno]) {
10672                /* Initiating call went away before we could transfer. */
10673                break;
10674             }
10675             owner = iaxs[fr->callno]->owner;
10676             bridged_chan = owner ? ast_bridged_channel(owner) : NULL;
10677             if (bridged_chan && ies.called_number) {
10678                ast_mutex_unlock(&iaxsl[fr->callno]);
10679 
10680                /* Set BLINDTRANSFER channel variables */
10681                pbx_builtin_setvar_helper(owner, "BLINDTRANSFER", bridged_chan->name);
10682                pbx_builtin_setvar_helper(bridged_chan, "BLINDTRANSFER", owner->name);
10683 
10684                if (ast_parking_ext_valid(ies.called_number, c, iaxs[fr->callno]->context)) {
10685                   ast_debug(1, "Parking call '%s'\n", bridged_chan->name);
10686                   if (iax_park(bridged_chan, owner, ies.called_number)) {
10687                      ast_log(LOG_WARNING, "Failed to park call '%s'\n",
10688                         bridged_chan->name);
10689                   }
10690                   ast_mutex_lock(&iaxsl[fr->callno]);
10691                } else {
10692                   ast_mutex_lock(&iaxsl[fr->callno]);
10693 
10694                   if (iaxs[fr->callno]) {
10695                      if (ast_async_goto(bridged_chan, iaxs[fr->callno]->context,
10696                         ies.called_number, 1)) {
10697                         ast_log(LOG_WARNING,
10698                            "Async goto of '%s' to '%s@%s' failed\n",
10699                            bridged_chan->name, ies.called_number,
10700                            iaxs[fr->callno]->context);
10701                      } else {
10702                         ast_debug(1, "Async goto of '%s' to '%s@%s' started\n",
10703                            bridged_chan->name, ies.called_number,
10704                            iaxs[fr->callno]->context);
10705                      }
10706                   } else {
10707                      /* Initiating call went away before we could transfer. */
10708                   }
10709                }
10710             } else {
10711                ast_debug(1, "Async goto not applicable on call %d\n", fr->callno);
10712             }
10713             if (owner) {
10714                ast_channel_unlock(owner);
10715             }
10716 
10717             break;
10718          }
10719          case IAX_COMMAND_ACCEPT:
10720             /* Ignore if call is already up or needs authentication or is a TBD */
10721             if (ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED | IAX_STATE_TBD | IAX_STATE_AUTHENTICATED))
10722                break;
10723             if (ast_test_flag64(iaxs[fr->callno], IAX_PROVISION)) {
10724                /* Send ack immediately, before we destroy */
10725                send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
10726                iax2_destroy(fr->callno);
10727                break;
10728             }
10729             if (ies.format) {
10730                iaxs[fr->callno]->peerformat = ies.format;
10731             } else {
10732                if (iaxs[fr->callno]->owner)
10733                   iaxs[fr->callno]->peerformat = iaxs[fr->callno]->owner->nativeformats;
10734                else
10735                   iaxs[fr->callno]->peerformat = iaxs[fr->callno]->capability;
10736             }
10737             ast_verb(3, "Call accepted by %s (format %s)\n", ast_inet_ntoa(iaxs[fr->callno]->addr.sin_addr), ast_getformatname(iaxs[fr->callno]->peerformat));
10738             if (!(iaxs[fr->callno]->peerformat & iaxs[fr->callno]->capability)) {
10739                memset(&ied0, 0, sizeof(ied0));
10740                iax_ie_append_str(&ied0, IAX_IE_CAUSE, "Unable to negotiate codec");
10741                iax_ie_append_byte(&ied0, IAX_IE_CAUSECODE, AST_CAUSE_BEARERCAPABILITY_NOTAVAIL);
10742                send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
10743                if (!iaxs[fr->callno]) {
10744                   break;
10745                }
10746                if (authdebug) {
10747                   char tmp1[256], tmp2[256];
10748                   ast_log(LOG_NOTICE, "Rejected call to %s, format %s incompatible with our capability %s.\n",
10749                      ast_inet_ntoa(sin.sin_addr),
10750                      ast_getformatname_multiple(tmp1, sizeof(tmp1), iaxs[fr->callno]->peerformat),
10751                      ast_getformatname_multiple(tmp2, sizeof(tmp2), iaxs[fr->callno]->capability));
10752                }
10753             } else {
10754                ast_set_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED);
10755                iax2_lock_owner(fr->callno);
10756                if (iaxs[fr->callno] && iaxs[fr->callno]->owner) {
10757                   /* Switch us to use a compatible format */
10758                   iaxs[fr->callno]->owner->nativeformats = iaxs[fr->callno]->peerformat;
10759                   ast_verb(3, "Format for call is %s\n", ast_getformatname(iaxs[fr->callno]->owner->nativeformats));
10760 
10761                   /* Setup read/write formats properly. */
10762                   if (iaxs[fr->callno]->owner->writeformat)
10763                      ast_set_write_format(iaxs[fr->callno]->owner, iaxs[fr->callno]->owner->writeformat);   
10764                   if (iaxs[fr->callno]->owner->readformat)
10765                      ast_set_read_format(iaxs[fr->callno]->owner, iaxs[fr->callno]->owner->readformat);  
10766                   ast_channel_unlock(iaxs[fr->callno]->owner);
10767                }
10768             }
10769             if (iaxs[fr->callno]) {
10770                AST_LIST_LOCK(&dpcache);
10771                AST_LIST_TRAVERSE(&iaxs[fr->callno]->dpentries, dp, peer_list)
10772                   if (!(dp->flags & CACHE_FLAG_TRANSMITTED))
10773                      iax2_dprequest(dp, fr->callno);
10774                AST_LIST_UNLOCK(&dpcache);
10775             }
10776             break;
10777          case IAX_COMMAND_POKE:
10778             /* Send back a pong packet with the original timestamp */
10779             send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_PONG, fr->ts, NULL, 0, -1);
10780             break;
10781          case IAX_COMMAND_PING:
10782          {
10783             struct iax_ie_data pingied;
10784             construct_rr(iaxs[fr->callno], &pingied);
10785             /* Send back a pong packet with the original timestamp */
10786             send_command(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_PONG, fr->ts, pingied.buf, pingied.pos, -1);
10787          }
10788             break;
10789          case IAX_COMMAND_PONG:
10790             /* Calculate ping time */
10791             iaxs[fr->callno]->pingtime =  calc_timestamp(iaxs[fr->callno], 0, &f) - fr->ts;
10792             /* save RR info */
10793             save_rr(fr, &ies);
10794 
10795             /* Good time to write jb stats for this call */
10796             log_jitterstats(fr->callno);
10797 
10798             if (iaxs[fr->callno]->peerpoke) {
10799                peer = iaxs[fr->callno]->peerpoke;
10800                if ((peer->lastms < 0)  || (peer->historicms > peer->maxms)) {
10801                   if (iaxs[fr->callno]->pingtime <= peer->maxms) {
10802                      ast_log(LOG_NOTICE, "Peer '%s' is now REACHABLE! Time: %d\n", peer->name, iaxs[fr->callno]->pingtime);
10803                      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); 
10804                      ast_devstate_changed(AST_DEVICE_NOT_INUSE, "IAX2/%s", peer->name); /* Activate notification */
10805                   }
10806                } else if ((peer->historicms > 0) && (peer->historicms <= peer->maxms)) {
10807                   if (iaxs[fr->callno]->pingtime > peer->maxms) {
10808                      ast_log(LOG_NOTICE, "Peer '%s' is now TOO LAGGED (%d ms)!\n", peer->name, iaxs[fr->callno]->pingtime);
10809                      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); 
10810                      ast_devstate_changed(AST_DEVICE_UNAVAILABLE, "IAX2/%s", peer->name); /* Activate notification */
10811                   }
10812                }
10813                peer->lastms = iaxs[fr->callno]->pingtime;
10814                if (peer->smoothing && (peer->lastms > -1))
10815                   peer->historicms = (iaxs[fr->callno]->pingtime + peer->historicms) / 2;
10816                else if (peer->smoothing && peer->lastms < 0)
10817                   peer->historicms = (0 + peer->historicms) / 2;
10818                else              
10819                   peer->historicms = iaxs[fr->callno]->pingtime;
10820 
10821                /* Remove scheduled iax2_poke_noanswer */
10822                if (peer->pokeexpire > -1) {
10823                   if (!ast_sched_thread_del(sched, peer->pokeexpire)) {
10824                      peer_unref(peer);
10825                      peer->pokeexpire = -1;
10826                   }
10827                }
10828                /* Schedule the next cycle */
10829                if ((peer->lastms < 0)  || (peer->historicms > peer->maxms)) 
10830                   peer->pokeexpire = iax2_sched_add(sched, peer->pokefreqnotok, iax2_poke_peer_s, peer_ref(peer));
10831                else
10832                   peer->pokeexpire = iax2_sched_add(sched, peer->pokefreqok, iax2_poke_peer_s, peer_ref(peer));
10833                if (peer->pokeexpire == -1)
10834                   peer_unref(peer);
10835                /* and finally send the ack */
10836                send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
10837                /* And wrap up the qualify call */
10838                iax2_destroy(fr->callno);
10839                peer->callno = 0;
10840                ast_debug(1, "Peer %s: got pong, lastms %d, historicms %d, maxms %d\n", peer->name, peer->lastms, peer->historicms, peer->maxms);
10841             }
10842             break;
10843          case IAX_COMMAND_LAGRQ:
10844          case IAX_COMMAND_LAGRP:
10845             f.src = "LAGRQ";
10846             f.mallocd = 0;
10847             f.offset = 0;
10848             f.samples = 0;
10849             iax_frame_wrap(fr, &f);
10850             if (f.subclass.integer == IAX_COMMAND_LAGRQ) {
10851                /* Received a LAGRQ - echo back a LAGRP */
10852                fr->af.subclass.integer = IAX_COMMAND_LAGRP;
10853                iax2_send(iaxs[fr->callno], &fr->af, fr->ts, -1, 0, 0, 0);
10854             } else {
10855                /* Received LAGRP in response to our LAGRQ */
10856                unsigned int ts;
10857                /* This is a reply we've been given, actually measure the difference */
10858                ts = calc_timestamp(iaxs[fr->callno], 0, &fr->af);
10859                iaxs[fr->callno]->lag = ts - fr->ts;
10860                if (iaxdebug)
10861                   ast_debug(1, "Peer %s lag measured as %dms\n",
10862                      ast_inet_ntoa(iaxs[fr->callno]->addr.sin_addr), iaxs[fr->callno]->lag);
10863             }
10864             break;
10865          case IAX_COMMAND_AUTHREQ:
10866             if (ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED | IAX_STATE_TBD)) {
10867                ast_log(LOG_WARNING, "Call on %s is already up, can't start on it\n", iaxs[fr->callno]->owner ? iaxs[fr->callno]->owner->name : "<Unknown>");
10868                break;
10869             }
10870             if (authenticate_reply(iaxs[fr->callno], &iaxs[fr->callno]->addr, &ies, iaxs[fr->callno]->secret, iaxs[fr->callno]->outkey)) {
10871                struct ast_frame hangup_fr = { .frametype = AST_FRAME_CONTROL,
10872                         .subclass.integer = AST_CONTROL_HANGUP,
10873                };
10874                ast_log(LOG_WARNING, 
10875                   "I don't know how to authenticate %s to %s\n", 
10876                   ies.username ? ies.username : "<unknown>", ast_inet_ntoa(iaxs[fr->callno]->addr.sin_addr));
10877                iax2_queue_frame(fr->callno, &hangup_fr);
10878             }
10879             break;
10880          case IAX_COMMAND_AUTHREP:
10881             /* For security, always ack immediately */
10882             if (delayreject)
10883                send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
10884             /* Ignore once we've started */
10885             if (ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED | IAX_STATE_TBD)) {
10886                ast_log(LOG_WARNING, "Call on %s is already up, can't start on it\n", iaxs[fr->callno]->owner ? iaxs[fr->callno]->owner->name : "<Unknown>");
10887                break;
10888             }
10889             if (authenticate_verify(iaxs[fr->callno], &ies)) {
10890                if (authdebug)
10891                   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);
10892                memset(&ied0, 0, sizeof(ied0));
10893                auth_fail(fr->callno, IAX_COMMAND_REJECT);
10894                break;
10895             }
10896             if (strcasecmp(iaxs[fr->callno]->exten, "TBD")) {
10897                /* This might re-enter the IAX code and need the lock */
10898                exists = ast_exists_extension(NULL, iaxs[fr->callno]->context, iaxs[fr->callno]->exten, 1, iaxs[fr->callno]->cid_num);
10899             } else
10900                exists = 0;
10901             if (strcmp(iaxs[fr->callno]->exten, "TBD") && !exists) {
10902                if (authdebug)
10903                   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);
10904                memset(&ied0, 0, sizeof(ied0));
10905                iax_ie_append_str(&ied0, IAX_IE_CAUSE, "No such context/extension");
10906                iax_ie_append_byte(&ied0, IAX_IE_CAUSECODE, AST_CAUSE_NO_ROUTE_DESTINATION);
10907                send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
10908                if (!iaxs[fr->callno]) {
10909                   break;
10910                }
10911             } else {
10912                /* Select an appropriate format */
10913                if(ast_test_flag64(iaxs[fr->callno], IAX_CODEC_NOPREFS)) {
10914                   if(ast_test_flag64(iaxs[fr->callno], IAX_CODEC_NOCAP)) {
10915                      using_prefs = "reqonly";
10916                   } else {
10917                      using_prefs = "disabled";
10918                   }
10919                   format = iaxs[fr->callno]->peerformat & iaxs[fr->callno]->capability;
10920                   memset(&pref, 0, sizeof(pref));
10921                   strcpy(caller_pref_buf, "disabled");
10922                   strcpy(host_pref_buf, "disabled");
10923                } else {
10924                   using_prefs = "mine";
10925                   if (ies.codec_prefs)
10926                      ast_codec_pref_convert(&iaxs[fr->callno]->rprefs, ies.codec_prefs, 32, 0);
10927                   if (ast_codec_pref_index(&iaxs[fr->callno]->rprefs, 0)) {
10928                      if (ast_test_flag64(iaxs[fr->callno], IAX_CODEC_USER_FIRST)) {
10929                         pref = iaxs[fr->callno]->rprefs;
10930                         using_prefs = "caller";
10931                      } else {
10932                         pref = iaxs[fr->callno]->prefs;
10933                      }
10934                   } else /* if no codec_prefs IE do it the old way */
10935                      pref = iaxs[fr->callno]->prefs;
10936                   format = ast_codec_choose(&pref, iaxs[fr->callno]->capability & iaxs[fr->callno]->peercapability, 0);
10937                   ast_codec_pref_string(&iaxs[fr->callno]->rprefs, caller_pref_buf, sizeof(caller_pref_buf) - 1);
10938                   ast_codec_pref_string(&iaxs[fr->callno]->prefs, host_pref_buf, sizeof(host_pref_buf) - 1);
10939                }
10940                if (!format) {
10941                   char tmp1[256], tmp2[256], tmp3[256];
10942                   if(!ast_test_flag64(iaxs[fr->callno], IAX_CODEC_NOCAP)) {
10943                      ast_debug(1, "We don't do requested format %s, falling back to peer capability '%s'\n",
10944                         ast_getformatname(iaxs[fr->callno]->peerformat),
10945                         ast_getformatname_multiple(tmp1, sizeof(tmp1), iaxs[fr->callno]->peercapability));
10946                      format = iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability;
10947                   }
10948                   if (!format) {
10949                      if (authdebug) {
10950                         if (ast_test_flag64(iaxs[fr->callno], IAX_CODEC_NOCAP)) {
10951                            ast_log(LOG_NOTICE, "Rejected connect attempt from %s, requested '%s' incompatible with our capability '%s'.\n", ast_inet_ntoa(sin.sin_addr),
10952                               ast_getformatname_multiple(tmp1, sizeof(tmp1), iaxs[fr->callno]->peerformat),
10953                               ast_getformatname_multiple(tmp2, sizeof(tmp2), iaxs[fr->callno]->capability));
10954                         } else {
10955                            ast_log(LOG_NOTICE, "Rejected connect attempt from %s, requested/capability '%s'/'%s' incompatible with our capability '%s'.\n",
10956                               ast_inet_ntoa(sin.sin_addr),
10957                               ast_getformatname_multiple(tmp1, sizeof(tmp1), iaxs[fr->callno]->peerformat),
10958                               ast_getformatname_multiple(tmp2, sizeof(tmp2), iaxs[fr->callno]->peercapability),
10959                               ast_getformatname_multiple(tmp3, sizeof(tmp3), iaxs[fr->callno]->capability));
10960                         }
10961                      }
10962                      memset(&ied0, 0, sizeof(ied0));
10963                      iax_ie_append_str(&ied0, IAX_IE_CAUSE, "Unable to negotiate codec");
10964                      iax_ie_append_byte(&ied0, IAX_IE_CAUSECODE, AST_CAUSE_BEARERCAPABILITY_NOTAVAIL);
10965                      send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
10966                      if (!iaxs[fr->callno]) {
10967                         break;
10968                      }
10969                   } else {
10970                      /* Pick one... */
10971                      if(ast_test_flag64(iaxs[fr->callno], IAX_CODEC_NOCAP)) {
10972                         if(!(iaxs[fr->callno]->peerformat & iaxs[fr->callno]->capability))
10973                            format = 0;
10974                      } else {
10975                         if(ast_test_flag64(iaxs[fr->callno], IAX_CODEC_NOPREFS)) {
10976                            using_prefs = ast_test_flag64(iaxs[fr->callno], IAX_CODEC_NOCAP) ? "reqonly" : "disabled";
10977                            memset(&pref, 0, sizeof(pref));
10978                            format = ast_test_flag64(iaxs[fr->callno], IAX_CODEC_NOCAP) ?
10979                               iaxs[fr->callno]->peerformat : ast_best_codec(iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability);
10980                            strcpy(caller_pref_buf,"disabled");
10981                            strcpy(host_pref_buf,"disabled");
10982                         } else {
10983                            using_prefs = "mine";
10984                            if (ast_codec_pref_index(&iaxs[fr->callno]->rprefs, 0)) {
10985                               /* Do the opposite of what we tried above. */
10986                               if (ast_test_flag64(iaxs[fr->callno], IAX_CODEC_USER_FIRST)) {
10987                                  pref = iaxs[fr->callno]->prefs;
10988                               } else {
10989                                  pref = iaxs[fr->callno]->rprefs;
10990                                  using_prefs = "caller";
10991                               }
10992                               format = ast_codec_choose(&pref, iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability, 1);
10993                            } else /* if no codec_prefs IE do it the old way */
10994                               format = ast_best_codec(iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability); 
10995                         }
10996                      }
10997                      if (!format) {
10998                         char tmp1[256], tmp2[256], tmp3[256];
10999                         ast_log(LOG_ERROR, "No best format in %s???\n",
11000                            ast_getformatname_multiple(tmp1, sizeof(tmp1), iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability));
11001                         if (authdebug) {
11002                            if (ast_test_flag64(iaxs[fr->callno], IAX_CODEC_NOCAP)) {
11003                               ast_log(LOG_NOTICE, "Rejected connect attempt from %s, requested '%s' incompatible with our capability '%s'.\n",
11004                                  ast_inet_ntoa(sin.sin_addr),
11005                                  ast_getformatname_multiple(tmp1, sizeof(tmp1), iaxs[fr->callno]->peerformat),
11006                                  ast_getformatname_multiple(tmp2, sizeof(tmp2), iaxs[fr->callno]->capability));
11007                            } else {
11008                               ast_log(LOG_NOTICE, "Rejected connect attempt from %s, requested/capability '%s'/'%s' incompatible with our capability '%s'.\n",
11009                                  ast_inet_ntoa(sin.sin_addr),
11010                                  ast_getformatname_multiple(tmp1, sizeof(tmp1), iaxs[fr->callno]->peerformat),
11011                                  ast_getformatname_multiple(tmp2, sizeof(tmp2), iaxs[fr->callno]->peercapability),
11012                                  ast_getformatname_multiple(tmp3, sizeof(tmp3), iaxs[fr->callno]->capability));
11013                            }
11014                         }
11015                         memset(&ied0, 0, sizeof(ied0));
11016                         iax_ie_append_str(&ied0, IAX_IE_CAUSE, "Unable to negotiate codec");
11017                         iax_ie_append_byte(&ied0, IAX_IE_CAUSECODE, AST_CAUSE_BEARERCAPABILITY_NOTAVAIL);
11018                         send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
11019                         if (!iaxs[fr->callno]) {
11020                            break;
11021                         }
11022                      }
11023                   }
11024                }
11025                if (format) {
11026                   /* Authentication received */
11027                   memset(&ied1, 0, sizeof(ied1));
11028                   iax_ie_append_int(&ied1, IAX_IE_FORMAT, format);
11029                   iax_ie_append_versioned_uint64(&ied1, IAX_IE_FORMAT2, 0, format);
11030                   send_command(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACCEPT, 0, ied1.buf, ied1.pos, -1);
11031                   if (strcmp(iaxs[fr->callno]->exten, "TBD")) {
11032                      ast_set_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED);
11033                      ast_verb(3, "Accepting AUTHENTICATED call from %s:\n"
11034                                  "%srequested format = %s,\n"
11035                                  "%srequested prefs = %s,\n"
11036                                  "%sactual format = %s,\n"
11037                                  "%shost prefs = %s,\n"
11038                                  "%spriority = %s\n", 
11039                                  ast_inet_ntoa(sin.sin_addr), 
11040                                  VERBOSE_PREFIX_4,
11041                                  ast_getformatname(iaxs[fr->callno]->peerformat),
11042                                  VERBOSE_PREFIX_4,
11043                                  caller_pref_buf,
11044                                  VERBOSE_PREFIX_4,
11045                                  ast_getformatname(format),
11046                                  VERBOSE_PREFIX_4,
11047                                  host_pref_buf,
11048                                  VERBOSE_PREFIX_4,
11049                                  using_prefs);
11050 
11051                      ast_set_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED);
11052                      if (!(c = ast_iax2_new(fr->callno, AST_STATE_RING, format, NULL)))
11053                         iax2_destroy(fr->callno);
11054                      else if (ies.vars) {
11055                         struct ast_datastore *variablestore;
11056                         struct ast_variable *var, *prev = NULL;
11057                         AST_LIST_HEAD(, ast_var_t) *varlist;
11058                         varlist = ast_calloc(1, sizeof(*varlist));
11059                         variablestore = ast_datastore_alloc(&iax2_variable_datastore_info, NULL);
11060                         if (variablestore && varlist) {
11061                            variablestore->data = varlist;
11062                            variablestore->inheritance = DATASTORE_INHERIT_FOREVER;
11063                            AST_LIST_HEAD_INIT(varlist);
11064                            ast_debug(1, "I can haz IAX vars? w00t\n");
11065                            for (var = ies.vars; var; var = var->next) {
11066                               struct ast_var_t *newvar = ast_var_assign(var->name, var->value);
11067                               if (prev)
11068                                  ast_free(prev);
11069                               prev = var;
11070                               if (!newvar) {
11071                                  /* Don't abort list traversal, as this would leave ies.vars in an inconsistent state. */
11072                                  ast_log(LOG_ERROR, "Memory allocation error while processing IAX2 variables\n");
11073                               } else {
11074                                  AST_LIST_INSERT_TAIL(varlist, newvar, entries);
11075                               }
11076                            }
11077                            if (prev)
11078                               ast_free(prev);
11079                            ies.vars = NULL;
11080                            ast_channel_datastore_add(c, variablestore);
11081                         } else {
11082                            ast_log(LOG_ERROR, "Memory allocation error while processing IAX2 variables\n");
11083                            if (variablestore)
11084                               ast_datastore_free(variablestore);
11085                            if (varlist)
11086                               ast_free(varlist);
11087                         }
11088                      }
11089                   } else {
11090                      ast_set_flag(&iaxs[fr->callno]->state, IAX_STATE_TBD);
11091                      /* If this is a TBD call, we're ready but now what...  */
11092                      ast_verb(3, "Accepted AUTHENTICATED TBD call from %s\n", ast_inet_ntoa(sin.sin_addr));
11093                      if (ast_test_flag64(iaxs[fr->callno], IAX_IMMEDIATE)) {
11094                         goto immediatedial;
11095                      }
11096                   }
11097                }
11098             }
11099             break;
11100          case IAX_COMMAND_DIAL:
11101 immediatedial:
11102             if (ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_TBD)) {
11103                ast_clear_flag(&iaxs[fr->callno]->state, IAX_STATE_TBD);
11104                ast_string_field_set(iaxs[fr->callno], exten, ies.called_number ? ies.called_number : "s");
11105                if (!ast_exists_extension(NULL, iaxs[fr->callno]->context, iaxs[fr->callno]->exten, 1, iaxs[fr->callno]->cid_num)) {
11106                   if (authdebug)
11107                      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);
11108                   memset(&ied0, 0, sizeof(ied0));
11109                   iax_ie_append_str(&ied0, IAX_IE_CAUSE, "No such context/extension");
11110                   iax_ie_append_byte(&ied0, IAX_IE_CAUSECODE, AST_CAUSE_NO_ROUTE_DESTINATION);
11111                   send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
11112                   if (!iaxs[fr->callno]) {
11113                      break;
11114                   }
11115                } else {
11116                   char tmp[256];
11117                   ast_set_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED);
11118                   ast_verb(3, "Accepting DIAL from %s, formats = %s\n",
11119                      ast_inet_ntoa(sin.sin_addr),
11120                      ast_getformatname_multiple(tmp, sizeof(tmp), iaxs[fr->callno]->peerformat));
11121                   ast_set_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED);
11122                   send_command(iaxs[fr->callno], AST_FRAME_CONTROL, AST_CONTROL_PROGRESS, 0, NULL, 0, -1);
11123                   if (!(c = ast_iax2_new(fr->callno, AST_STATE_RING, iaxs[fr->callno]->peerformat, NULL)))
11124                      iax2_destroy(fr->callno);
11125                   else if (ies.vars) {
11126                      struct ast_datastore *variablestore;
11127                      struct ast_variable *var, *prev = NULL;
11128                      AST_LIST_HEAD(, ast_var_t) *varlist;
11129                      varlist = ast_calloc(1, sizeof(*varlist));
11130                      variablestore = ast_datastore_alloc(&iax2_variable_datastore_info, NULL);
11131                      ast_debug(1, "I can haz IAX vars? w00t\n");
11132                      if (variablestore && varlist) {
11133                         variablestore->data = varlist;
11134                         variablestore->inheritance = DATASTORE_INHERIT_FOREVER;
11135                         AST_LIST_HEAD_INIT(varlist);
11136                         for (var = ies.vars; var; var = var->next) {
11137                            struct ast_var_t *newvar = ast_var_assign(var->name, var->value);
11138                            if (prev)
11139                               ast_free(prev);
11140                            prev = var;
11141                            if (!newvar) {
11142                               /* Don't abort list traversal, as this would leave ies.vars in an inconsistent state. */
11143                               ast_log(LOG_ERROR, "Memory allocation error while processing IAX2 variables\n");
11144                            } else {
11145                               AST_LIST_INSERT_TAIL(varlist, newvar, entries);
11146                            }
11147                         }
11148                         if (prev)
11149                            ast_free(prev);
11150                         ies.vars = NULL;
11151                         ast_channel_datastore_add(c, variablestore);
11152                      } else {
11153                         ast_log(LOG_ERROR, "Memory allocation error while processing IAX2 variables\n");
11154                         if (variablestore)
11155                            ast_datastore_free(variablestore);
11156                         if (varlist)
11157                            ast_free(varlist);
11158                      }
11159                   }
11160                }
11161             }
11162             break;
11163          case IAX_COMMAND_INVAL:
11164             iaxs[fr->callno]->error = ENOTCONN;
11165             ast_debug(1, "Immediately destroying %d, having received INVAL\n", fr->callno);
11166             iax2_destroy(fr->callno);
11167             ast_debug(1, "Destroying call %d\n", fr->callno);
11168             break;
11169          case IAX_COMMAND_VNAK:
11170             ast_debug(1, "Received VNAK: resending outstanding frames\n");
11171             /* Force retransmission */
11172             vnak_retransmit(fr->callno, fr->iseqno);
11173             break;
11174          case IAX_COMMAND_REGREQ:
11175          case IAX_COMMAND_REGREL:
11176             /* For security, always ack immediately */
11177             if (delayreject)
11178                send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
11179             if (register_verify(fr->callno, &sin, &ies)) {
11180                if (!iaxs[fr->callno]) {
11181                   break;
11182                }
11183                /* Send delayed failure */
11184                auth_fail(fr->callno, IAX_COMMAND_REGREJ);
11185                break;
11186             }
11187             if (!iaxs[fr->callno]) {
11188                break;
11189             }
11190             if ((ast_strlen_zero(iaxs[fr->callno]->secret) && ast_strlen_zero(iaxs[fr->callno]->inkeys)) ||
11191                   ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_AUTHENTICATED)) {
11192 
11193                if (f.subclass.integer == IAX_COMMAND_REGREL)
11194                   memset(&sin, 0, sizeof(sin));
11195                if (update_registry(&sin, fr->callno, ies.devicetype, fd, ies.refresh))
11196                   ast_log(LOG_WARNING, "Registry error\n");
11197                if (!iaxs[fr->callno]) {
11198                   break;
11199                }
11200                if (ies.provverpres && ies.serviceident && sin.sin_addr.s_addr) {
11201                   ast_mutex_unlock(&iaxsl[fr->callno]);
11202                   check_provisioning(&sin, fd, ies.serviceident, ies.provver);
11203                   ast_mutex_lock(&iaxsl[fr->callno]);
11204                }
11205                break;
11206             }
11207             registry_authrequest(fr->callno);
11208             break;
11209          case IAX_COMMAND_REGACK:
11210             if (iax2_ack_registry(&ies, &sin, fr->callno)) 
11211                ast_log(LOG_WARNING, "Registration failure\n");
11212             /* Send ack immediately, before we destroy */
11213             send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
11214             iax2_destroy(fr->callno);
11215             break;
11216          case IAX_COMMAND_REGREJ:
11217             if (iaxs[fr->callno]->reg) {
11218                if (authdebug) {
11219                   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));
11220                   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>");
11221                }
11222                iaxs[fr->callno]->reg->regstate = REG_STATE_REJECTED;
11223             }
11224             /* Send ack immediately, before we destroy */
11225             send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
11226             iax2_destroy(fr->callno);
11227             break;
11228          case IAX_COMMAND_REGAUTH:
11229             /* Authentication request */
11230             if (registry_rerequest(&ies, fr->callno, &sin)) {
11231                memset(&ied0, 0, sizeof(ied0));
11232                iax_ie_append_str(&ied0, IAX_IE_CAUSE, "No authority found");
11233                iax_ie_append_byte(&ied0, IAX_IE_CAUSECODE, AST_CAUSE_FACILITY_NOT_SUBSCRIBED);
11234                send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
11235             }
11236             break;
11237          case IAX_COMMAND_TXREJ:
11238             iaxs[fr->callno]->transferring = 0;
11239             ast_verb(3, "Channel '%s' unable to transfer\n", iaxs[fr->callno]->owner ? iaxs[fr->callno]->owner->name : "<Unknown>");
11240             memset(&iaxs[fr->callno]->transfer, 0, sizeof(iaxs[fr->callno]->transfer));
11241             if (iaxs[fr->callno]->bridgecallno) {
11242                if (iaxs[iaxs[fr->callno]->bridgecallno]->transferring) {
11243                   iaxs[iaxs[fr->callno]->bridgecallno]->transferring = 0;
11244                   send_command(iaxs[iaxs[fr->callno]->bridgecallno], AST_FRAME_IAX, IAX_COMMAND_TXREJ, 0, NULL, 0, -1);
11245                }
11246             }
11247             break;
11248          case IAX_COMMAND_TXREADY:
11249             if ((iaxs[fr->callno]->transferring == TRANSFER_BEGIN) ||
11250                 (iaxs[fr->callno]->transferring == TRANSFER_MBEGIN)) {
11251                if (iaxs[fr->callno]->transferring == TRANSFER_MBEGIN)
11252                   iaxs[fr->callno]->transferring = TRANSFER_MREADY;
11253                else
11254                   iaxs[fr->callno]->transferring = TRANSFER_READY;
11255                ast_verb(3, "Channel '%s' ready to transfer\n", iaxs[fr->callno]->owner ? iaxs[fr->callno]->owner->name : "<Unknown>");
11256                if (iaxs[fr->callno]->bridgecallno) {
11257                   if ((iaxs[iaxs[fr->callno]->bridgecallno]->transferring == TRANSFER_READY) ||
11258                       (iaxs[iaxs[fr->callno]->bridgecallno]->transferring == TRANSFER_MREADY)) {
11259                      /* They're both ready, now release them. */
11260                      if (iaxs[fr->callno]->transferring == TRANSFER_MREADY) {
11261                         ast_verb(3, "Attempting media bridge of %s and %s\n", iaxs[fr->callno]->owner ? iaxs[fr->callno]->owner->name : "<Unknown>",
11262                               iaxs[iaxs[fr->callno]->bridgecallno]->owner ? iaxs[iaxs[fr->callno]->bridgecallno]->owner->name : "<Unknown>");
11263 
11264                         iaxs[iaxs[fr->callno]->bridgecallno]->transferring = TRANSFER_MEDIA;
11265                         iaxs[fr->callno]->transferring = TRANSFER_MEDIA;
11266 
11267                         memset(&ied0, 0, sizeof(ied0));
11268                         memset(&ied1, 0, sizeof(ied1));
11269                         iax_ie_append_short(&ied0, IAX_IE_CALLNO, iaxs[iaxs[fr->callno]->bridgecallno]->peercallno);
11270                         iax_ie_append_short(&ied1, IAX_IE_CALLNO, iaxs[fr->callno]->peercallno);
11271                         send_command(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_TXMEDIA, 0, ied0.buf, ied0.pos, -1);
11272                         send_command(iaxs[iaxs[fr->callno]->bridgecallno], AST_FRAME_IAX, IAX_COMMAND_TXMEDIA, 0, ied1.buf, ied1.pos, -1);
11273                      } else {
11274                         ast_verb(3, "Releasing %s and %s\n", iaxs[fr->callno]->owner ? iaxs[fr->callno]->owner->name : "<Unknown>",
11275                               iaxs[iaxs[fr->callno]->bridgecallno]->owner ? iaxs[iaxs[fr->callno]->bridgecallno]->owner->name : "<Unknown>");
11276 
11277                         iaxs[iaxs[fr->callno]->bridgecallno]->transferring = TRANSFER_RELEASED;
11278                         iaxs[fr->callno]->transferring = TRANSFER_RELEASED;
11279                         ast_set_flag64(iaxs[iaxs[fr->callno]->bridgecallno], IAX_ALREADYGONE);
11280                         ast_set_flag64(iaxs[fr->callno], IAX_ALREADYGONE);
11281 
11282                         /* Stop doing lag & ping requests */
11283                         stop_stuff(fr->callno);
11284                         stop_stuff(iaxs[fr->callno]->bridgecallno);
11285 
11286                         memset(&ied0, 0, sizeof(ied0));
11287                         memset(&ied1, 0, sizeof(ied1));
11288                         iax_ie_append_short(&ied0, IAX_IE_CALLNO, iaxs[iaxs[fr->callno]->bridgecallno]->peercallno);
11289                         iax_ie_append_short(&ied1, IAX_IE_CALLNO, iaxs[fr->callno]->peercallno);
11290                         send_command(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_TXREL, 0, ied0.buf, ied0.pos, -1);
11291                         send_command(iaxs[iaxs[fr->callno]->bridgecallno], AST_FRAME_IAX, IAX_COMMAND_TXREL, 0, ied1.buf, ied1.pos, -1);
11292                      }
11293 
11294                   }
11295                }
11296             }
11297             break;
11298          case IAX_COMMAND_TXREQ:
11299             try_transfer(iaxs[fr->callno], &ies);
11300             break;
11301          case IAX_COMMAND_TXCNT:
11302             if (iaxs[fr->callno]->transferring)
11303                send_command_transfer(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_TXACC, 0, NULL, 0);
11304             break;
11305          case IAX_COMMAND_TXREL:
11306             /* Send ack immediately, rather than waiting until we've changed addresses */
11307             send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
11308             complete_transfer(fr->callno, &ies);
11309             stop_stuff(fr->callno); /* for attended transfer to work with libiax */
11310             break;   
11311          case IAX_COMMAND_TXMEDIA:
11312             if (iaxs[fr->callno]->transferring == TRANSFER_READY) {
11313                AST_LIST_TRAVERSE(&frame_queue[fr->callno], cur, list) {
11314                   /* Cancel any outstanding frames and start anew */
11315                   if (cur->transfer) {
11316                      cur->retries = -1;
11317                   }
11318                }
11319                /* Start sending our media to the transfer address, but otherwise leave the call as-is */
11320                iaxs[fr->callno]->transferring = TRANSFER_MEDIAPASS;
11321             }
11322             break;
11323          case IAX_COMMAND_RTKEY:
11324             if (!IAX_CALLENCRYPTED(iaxs[fr->callno])) {
11325                ast_log(LOG_WARNING, 
11326                   "we've been told to rotate our encryption key, "
11327                   "but this isn't an encrypted call. bad things will happen.\n"
11328                );
11329                break;
11330             }
11331 
11332             IAX_DEBUGDIGEST("Receiving", ies.challenge);
11333 
11334             ast_aes_set_decrypt_key((unsigned char *) ies.challenge, &iaxs[fr->callno]->dcx);
11335             break;
11336          case IAX_COMMAND_DPREP:
11337             complete_dpreply(iaxs[fr->callno], &ies);
11338             break;
11339          case IAX_COMMAND_UNSUPPORT:
11340             ast_log(LOG_NOTICE, "Peer did not understand our iax command '%d'\n", ies.iax_unknown);
11341             break;
11342          case IAX_COMMAND_FWDOWNL:
11343             /* Firmware download */
11344             if (!ast_test_flag64(&globalflags, IAX_ALLOWFWDOWNLOAD)) {
11345                send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_UNSUPPORT, 0, NULL, 0, -1);
11346                break;
11347             }
11348             memset(&ied0, 0, sizeof(ied0));
11349             res = iax_firmware_append(&ied0, (unsigned char *)ies.devicetype, ies.fwdesc);
11350             if (res < 0)
11351                send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
11352             else if (res > 0)
11353                send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_FWDATA, 0, ied0.buf, ied0.pos, -1);
11354             else
11355                send_command(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_FWDATA, 0, ied0.buf, ied0.pos, -1);
11356             break;
11357          case IAX_COMMAND_CALLTOKEN:
11358          {
11359             struct iax_frame *cur;
11360             /* find last sent frame */
11361             if ((cur = AST_LIST_LAST(&frame_queue[fr->callno])) && ies.calltoken && ies.calltokendata) {
11362                resend_with_token(fr->callno, cur, (char *) ies.calltokendata);
11363             }
11364             break;
11365          }
11366          default:
11367             ast_debug(1, "Unknown IAX command %d on %d/%d\n", f.subclass.integer, fr->callno, iaxs[fr->callno]->peercallno);
11368             memset(&ied0, 0, sizeof(ied0));
11369             iax_ie_append_byte(&ied0, IAX_IE_IAX_UNKNOWN, f.subclass.integer);
11370             send_command(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_UNSUPPORT, 0, ied0.buf, ied0.pos, -1);
11371          }
11372          /* Free remote variables (if any) */
11373          if (ies.vars) {
11374             ast_variables_destroy(ies.vars);
11375             ast_debug(1, "I can haz IAX vars, but they is no good :-(\n");
11376             ies.vars = NULL;
11377          }
11378 
11379          /* Don't actually pass these frames along */
11380          if ((f.subclass.integer != IAX_COMMAND_ACK) && 
11381            (f.subclass.integer != IAX_COMMAND_TXCNT) && 
11382            (f.subclass.integer != IAX_COMMAND_TXACC) && 
11383            (f.subclass.integer != IAX_COMMAND_INVAL) &&
11384            (f.subclass.integer != IAX_COMMAND_VNAK)) { 
11385             if (iaxs[fr->callno] && iaxs[fr->callno]->aseqno != iaxs[fr->callno]->iseqno)
11386                send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
11387          }
11388          ast_mutex_unlock(&iaxsl[fr->callno]);
11389          return 1;
11390       }
11391       /* Unless this is an ACK or INVAL frame, ack it */
11392       if (iaxs[fr->callno] && iaxs[fr->callno]->aseqno != iaxs[fr->callno]->iseqno)
11393          send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
11394    } else if (minivid) {
11395       f.frametype = AST_FRAME_VIDEO;
11396       if (iaxs[fr->callno]->videoformat > 0) 
11397          f.subclass.codec = iaxs[fr->callno]->videoformat | (ntohs(vh->ts) & 0x8000LL ? 1 : 0);
11398       else {
11399          ast_log(LOG_WARNING, "Received mini frame before first full video frame\n");
11400          iax2_vnak(fr->callno);
11401          ast_variables_destroy(ies.vars);
11402          ast_mutex_unlock(&iaxsl[fr->callno]);
11403          return 1;
11404       }
11405       f.datalen = res - sizeof(*vh);
11406       if (f.datalen)
11407          f.data.ptr = thread->buf + sizeof(*vh);
11408       else
11409          f.data.ptr = NULL;
11410 #ifdef IAXTESTS
11411       if (test_resync) {
11412          fr->ts = (iaxs[fr->callno]->last & 0xFFFF8000L) | ((ntohs(vh->ts) + test_resync) & 0x7fff);
11413       } else
11414 #endif /* IAXTESTS */
11415          fr->ts = (iaxs[fr->callno]->last & 0xFFFF8000L) | (ntohs(vh->ts) & 0x7fff);
11416    } else {
11417       /* A mini frame */
11418       f.frametype = AST_FRAME_VOICE;
11419       if (iaxs[fr->callno]->voiceformat > 0)
11420          f.subclass.codec = iaxs[fr->callno]->voiceformat;
11421       else {
11422          ast_debug(1, "Received mini frame before first full voice frame\n");
11423          iax2_vnak(fr->callno);
11424          ast_variables_destroy(ies.vars);
11425          ast_mutex_unlock(&iaxsl[fr->callno]);
11426          return 1;
11427       }
11428       f.datalen = res - sizeof(struct ast_iax2_mini_hdr);
11429       if (f.datalen < 0) {
11430          ast_log(LOG_WARNING, "Datalen < 0?\n");
11431          ast_variables_destroy(ies.vars);
11432          ast_mutex_unlock(&iaxsl[fr->callno]);
11433          return 1;
11434       }
11435       if (f.datalen)
11436          f.data.ptr = thread->buf + sizeof(*mh);
11437       else
11438          f.data.ptr = NULL;
11439 #ifdef IAXTESTS
11440       if (test_resync) {
11441          fr->ts = (iaxs[fr->callno]->last & 0xFFFF0000L) | ((ntohs(mh->ts) + test_resync) & 0xffff);
11442       } else
11443 #endif /* IAXTESTS */
11444       fr->ts = (iaxs[fr->callno]->last & 0xFFFF0000L) | ntohs(mh->ts);
11445       /* FIXME? Surely right here would be the right place to undo timestamp wraparound? */
11446    }
11447    /* Don't pass any packets until we're started */
11448    if (!ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED)) {
11449       ast_variables_destroy(ies.vars);
11450       ast_mutex_unlock(&iaxsl[fr->callno]);
11451       return 1;
11452    }
11453    /* Don't allow connected line updates unless we are configured to */
11454    if (f.frametype == AST_FRAME_CONTROL && f.subclass.integer == AST_CONTROL_CONNECTED_LINE) {
11455       struct ast_party_connected_line connected;
11456 
11457       if (!ast_test_flag64(iaxs[fr->callno], IAX_RECVCONNECTEDLINE)) {
11458          ast_variables_destroy(ies.vars);
11459          ast_mutex_unlock(&iaxsl[fr->callno]);
11460          return 1;
11461       }
11462 
11463       /* Initialize defaults */
11464       ast_party_connected_line_init(&connected);
11465       connected.id.number.presentation = iaxs[fr->callno]->calling_pres;
11466       connected.id.name.presentation = iaxs[fr->callno]->calling_pres;
11467 
11468       if (!ast_connected_line_parse_data(f.data.ptr, f.datalen, &connected)) {
11469          ast_string_field_set(iaxs[fr->callno], cid_num, connected.id.number.str);
11470          ast_string_field_set(iaxs[fr->callno], cid_name, connected.id.name.str);
11471          iaxs[fr->callno]->calling_pres = ast_party_id_presentation(&connected.id);
11472 
11473          if (iaxs[fr->callno]->owner) {
11474             ast_set_callerid(iaxs[fr->callno]->owner,
11475                S_COR(connected.id.number.valid, connected.id.number.str, ""),
11476                S_COR(connected.id.name.valid, connected.id.name.str, ""),
11477                NULL);
11478             iaxs[fr->callno]->owner->caller.id.number.presentation = connected.id.number.presentation;
11479             iaxs[fr->callno]->owner->caller.id.name.presentation = connected.id.name.presentation;
11480          }
11481       }
11482       ast_party_connected_line_free(&connected);
11483    }
11484    /* Common things */
11485    f.src = "IAX2";
11486    f.mallocd = 0;
11487    f.offset = 0;
11488    f.len = 0;
11489    if (f.datalen && (f.frametype == AST_FRAME_VOICE)) {
11490       f.samples = ast_codec_get_samples(&f);
11491       /* We need to byteswap incoming slinear samples from network byte order */
11492       if (f.subclass.codec == AST_FORMAT_SLINEAR)
11493          ast_frame_byteswap_be(&f);
11494    } else
11495       f.samples = 0;
11496    iax_frame_wrap(fr, &f);
11497 
11498    /* If this is our most recent packet, use it as our basis for timestamping */
11499    if (iaxs[fr->callno] && iaxs[fr->callno]->last < fr->ts) {
11500       /*iaxs[fr->callno]->last = fr->ts; (do it afterwards cos schedule/forward_delivery needs the last ts too)*/
11501       fr->outoforder = 0;
11502    } else {
11503       if (iaxdebug && iaxs[fr->callno])
11504          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);
11505       fr->outoforder = -1;
11506    }
11507    fr->cacheable = ((f.frametype == AST_FRAME_VOICE) || (f.frametype == AST_FRAME_VIDEO));
11508    duped_fr = iaxfrdup2(fr);
11509    if (duped_fr) {
11510       schedule_delivery(duped_fr, updatehistory, 0, &fr->ts);
11511    }
11512    if (iaxs[fr->callno] && iaxs[fr->callno]->last < fr->ts) {
11513       iaxs[fr->callno]->last = fr->ts;
11514 #if 1
11515       if (iaxdebug)
11516          ast_debug(1, "For call=%d, set last=%d\n", fr->callno, fr->ts);
11517 #endif
11518    }
11519 
11520    /* Always run again */
11521    ast_variables_destroy(ies.vars);
11522    ast_mutex_unlock(&iaxsl[fr->callno]);
11523    return 1;
11524 }
11525 
11526 /* Function to clean up process thread if it is cancelled */
11527 static void iax2_process_thread_cleanup(void *data)
11528 {
11529    struct iax2_thread *thread = data;
11530    ast_mutex_destroy(&thread->lock);
11531    ast_cond_destroy(&thread->cond);
11532    ast_mutex_destroy(&thread->init_lock);
11533    ast_cond_destroy(&thread->init_cond);
11534    ast_free(thread);
11535    ast_atomic_dec_and_test(&iaxactivethreadcount);
11536 }
11537 
11538 static void *iax2_process_thread(void *data)
11539 {
11540    struct iax2_thread *thread = data;
11541    struct timeval wait;
11542    struct timespec ts;
11543    int put_into_idle = 0;
11544    int first_time = 1;
11545    int old_state;
11546 
11547    ast_atomic_fetchadd_int(&iaxactivethreadcount, 1);
11548 
11549    pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &old_state);
11550    pthread_cleanup_push(iax2_process_thread_cleanup, data);
11551 
11552    for (;;) {
11553       /* Wait for something to signal us to be awake */
11554       ast_mutex_lock(&thread->lock);
11555 
11556       if (thread->stop) {
11557          ast_mutex_unlock(&thread->lock);
11558          break;
11559       }
11560 
11561       /* Flag that we're ready to accept signals */
11562       if (first_time) {
11563          signal_condition(&thread->init_lock, &thread->init_cond);
11564          first_time = 0;
11565       }
11566 
11567       /* Put into idle list if applicable */
11568       if (put_into_idle) {
11569          insert_idle_thread(thread);
11570       }
11571 
11572       if (thread->type == IAX_THREAD_TYPE_DYNAMIC) {
11573          struct iax2_thread *t = NULL;
11574          /* Wait to be signalled or time out */
11575          wait = ast_tvadd(ast_tvnow(), ast_samp2tv(30000, 1000));
11576          ts.tv_sec = wait.tv_sec;
11577          ts.tv_nsec = wait.tv_usec * 1000;
11578          if (ast_cond_timedwait(&thread->cond, &thread->lock, &ts) == ETIMEDOUT) {
11579             /* This thread was never put back into the available dynamic
11580              * thread list, so just go away. */
11581             if (!put_into_idle || thread->stop) {
11582                ast_mutex_unlock(&thread->lock);
11583                break;
11584             }
11585             AST_LIST_LOCK(&dynamic_list);
11586             /* Account for the case where this thread is acquired *right* after a timeout */
11587             if ((t = AST_LIST_REMOVE(&dynamic_list, thread, list)))
11588                ast_atomic_fetchadd_int(&iaxdynamicthreadcount, -1);
11589             AST_LIST_UNLOCK(&dynamic_list);
11590             if (t) {
11591                /* This dynamic thread timed out waiting for a task and was
11592                 * not acquired immediately after the timeout, 
11593                 * so it's time to go away. */
11594                ast_mutex_unlock(&thread->lock);
11595                break;
11596             }
11597             /* Someone grabbed our thread *right* after we timed out.
11598              * Wait for them to set us up with something to do and signal
11599              * us to continue. */
11600             wait = ast_tvadd(ast_tvnow(), ast_samp2tv(30000, 1000));
11601             ts.tv_sec = wait.tv_sec;
11602             ts.tv_nsec = wait.tv_usec * 1000;
11603             if (ast_cond_timedwait(&thread->cond, &thread->lock, &ts) == ETIMEDOUT) {
11604                ast_mutex_unlock(&thread->lock);
11605                break;
11606             }
11607          }
11608       } else {
11609          ast_cond_wait(&thread->cond, &thread->lock);
11610       }
11611 
11612       /* Go back into our respective list */
11613       put_into_idle = 1;
11614 
11615       ast_mutex_unlock(&thread->lock);
11616 
11617       if (thread->stop) {
11618          break;
11619       }
11620 
11621       if (thread->iostate == IAX_IOSTATE_IDLE)
11622          continue;
11623 
11624       /* See what we need to do */
11625       switch (thread->iostate) {
11626       case IAX_IOSTATE_READY:
11627          thread->actions++;
11628          thread->iostate = IAX_IOSTATE_PROCESSING;
11629          socket_process(thread);
11630          handle_deferred_full_frames(thread);
11631          break;
11632       case IAX_IOSTATE_SCHEDREADY:
11633          thread->actions++;
11634          thread->iostate = IAX_IOSTATE_PROCESSING;
11635 #ifdef SCHED_MULTITHREADED
11636          thread->schedfunc(thread->scheddata);
11637 #endif      
11638       default:
11639          break;
11640       }
11641       time(&thread->checktime);
11642       thread->iostate = IAX_IOSTATE_IDLE;
11643 #ifdef DEBUG_SCHED_MULTITHREAD
11644       thread->curfunc[0]='\0';
11645 #endif      
11646 
11647       /* The network thread added us to the active_thread list when we were given
11648        * frames to process, Now that we are done, we must remove ourselves from
11649        * the active list, and return to the idle list */
11650       AST_LIST_LOCK(&active_list);
11651       AST_LIST_REMOVE(&active_list, thread, list);
11652       AST_LIST_UNLOCK(&active_list);
11653 
11654       /* Make sure another frame didn't sneak in there after we thought we were done. */
11655       handle_deferred_full_frames(thread);
11656    }
11657 
11658    /*!\note For some reason, idle threads are exiting without being removed
11659     * from an idle list, which is causing memory corruption.  Forcibly remove
11660     * it from the list, if it's there.
11661     */
11662    AST_LIST_LOCK(&idle_list);
11663    AST_LIST_REMOVE(&idle_list, thread, list);
11664    AST_LIST_UNLOCK(&idle_list);
11665 
11666    AST_LIST_LOCK(&dynamic_list);
11667    AST_LIST_REMOVE(&dynamic_list, thread, list);
11668    AST_LIST_UNLOCK(&dynamic_list);
11669 
11670    /* I am exiting here on my own volition, I need to clean up my own data structures
11671    * Assume that I am no longer in any of the lists (idle, active, or dynamic)
11672    */
11673    pthread_cleanup_pop(1);
11674    return NULL;
11675 }
11676 
11677 static int iax2_do_register(struct iax2_registry *reg)
11678 {
11679    struct iax_ie_data ied;
11680    if (iaxdebug)
11681       ast_debug(1, "Sending registration request for '%s'\n", reg->username);
11682 
11683    if (reg->dnsmgr && 
11684        ((reg->regstate == REG_STATE_TIMEOUT) || !ast_sockaddr_ipv4(&reg->addr))) {
11685       /* Maybe the IP has changed, force DNS refresh */
11686       ast_dnsmgr_refresh(reg->dnsmgr);
11687    }
11688    
11689    /*
11690     * if IP has Changed, free allocated call to create a new one with new IP
11691     * call has the pointer to IP and must be updated to the new one
11692     */
11693    if (reg->dnsmgr && ast_dnsmgr_changed(reg->dnsmgr) && (reg->callno > 0)) {
11694       int callno = reg->callno;
11695       ast_mutex_lock(&iaxsl[callno]);
11696       iax2_destroy(callno);
11697       ast_mutex_unlock(&iaxsl[callno]);
11698       reg->callno = 0;
11699    }
11700    if (!ast_sockaddr_ipv4(&reg->addr)) {
11701       if (iaxdebug)
11702          ast_debug(1, "Unable to send registration request for '%s' without IP address\n", reg->username);
11703       /* Setup the next registration attempt */
11704       reg->expire = iax2_sched_replace(reg->expire, sched, 
11705          (5 * reg->refresh / 6) * 1000, iax2_do_register_s, reg);
11706       return -1;
11707    }
11708 
11709    if (!reg->callno) {
11710       struct sockaddr_in reg_addr;
11711 
11712       ast_debug(3, "Allocate call number\n");
11713 
11714       ast_sockaddr_to_sin(&reg->addr, &reg_addr);
11715 
11716       reg->callno = find_callno_locked(0, 0, &reg_addr, NEW_FORCE, defaultsockfd, 0);
11717       if (reg->callno < 1) {
11718          ast_log(LOG_WARNING, "Unable to create call for registration\n");
11719          return -1;
11720       } else
11721          ast_debug(3, "Registration created on call %d\n", reg->callno);
11722       iaxs[reg->callno]->reg = reg;
11723       ast_mutex_unlock(&iaxsl[reg->callno]);
11724    }
11725    /* Setup the next registration a little early */
11726    reg->expire = iax2_sched_replace(reg->expire, sched, 
11727       (5 * reg->refresh / 6) * 1000, iax2_do_register_s, reg);
11728    /* Send the request */
11729    memset(&ied, 0, sizeof(ied));
11730    iax_ie_append_str(&ied, IAX_IE_USERNAME, reg->username);
11731    iax_ie_append_short(&ied, IAX_IE_REFRESH, reg->refresh);
11732    add_empty_calltoken_ie(iaxs[reg->callno], &ied); /* this _MUST_ be the last ie added */
11733    send_command(iaxs[reg->callno],AST_FRAME_IAX, IAX_COMMAND_REGREQ, 0, ied.buf, ied.pos, -1);
11734    reg->regstate = REG_STATE_REGSENT;
11735    return 0;
11736 }
11737 
11738 static int iax2_provision(struct sockaddr_in *end, int sockfd, const char *dest, const char *template, int force)
11739 {
11740    /* Returns 1 if provisioned, -1 if not able to find destination, or 0 if no provisioning
11741       is found for template */
11742    struct iax_ie_data provdata;
11743    struct iax_ie_data ied;
11744    unsigned int sig;
11745    struct sockaddr_in sin;
11746    int callno;
11747    struct create_addr_info cai;
11748 
11749    memset(&cai, 0, sizeof(cai));
11750 
11751    ast_debug(1, "Provisioning '%s' from template '%s'\n", dest, template);
11752 
11753    if (iax_provision_build(&provdata, &sig, template, force)) {
11754       ast_debug(1, "No provisioning found for template '%s'\n", template);
11755       return 0;
11756    }
11757 
11758    if (end) {
11759       memcpy(&sin, end, sizeof(sin));
11760       cai.sockfd = sockfd;
11761    } else if (create_addr(dest, NULL, &sin, &cai))
11762       return -1;
11763 
11764    /* Build the rest of the message */
11765    memset(&ied, 0, sizeof(ied));
11766    iax_ie_append_raw(&ied, IAX_IE_PROVISIONING, provdata.buf, provdata.pos);
11767 
11768    callno = find_callno_locked(0, 0, &sin, NEW_FORCE, cai.sockfd, 0);
11769    if (!callno)
11770       return -1;
11771 
11772    if (iaxs[callno]) {
11773       /* Schedule autodestruct in case they don't ever give us anything back */
11774       iaxs[callno]->autoid = iax2_sched_replace(iaxs[callno]->autoid, 
11775          sched, 15000, auto_hangup, (void *)(long)callno);
11776       ast_set_flag64(iaxs[callno], IAX_PROVISION);
11777       /* Got a call number now, so go ahead and send the provisioning information */
11778       send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_PROVISION, 0, ied.buf, ied.pos, -1);
11779    }
11780    ast_mutex_unlock(&iaxsl[callno]);
11781 
11782    return 1;
11783 }
11784 
11785 static char *papp = "IAX2Provision";
11786 
11787 /*! iax2provision
11788 \ingroup applications
11789 */
11790 static int iax2_prov_app(struct ast_channel *chan, const char *data)
11791 {
11792    int res;
11793    char *sdata;
11794    char *opts;
11795    int force =0;
11796    unsigned short callno = PTR_TO_CALLNO(chan->tech_pvt);
11797    if (ast_strlen_zero(data))
11798       data = "default";
11799    sdata = ast_strdupa(data);
11800    opts = strchr(sdata, '|');
11801    if (opts)
11802       *opts='\0';
11803 
11804    if (chan->tech != &iax2_tech) {
11805       ast_log(LOG_NOTICE, "Can't provision a non-IAX device!\n");
11806       return -1;
11807    } 
11808    if (!callno || !iaxs[callno] || !iaxs[callno]->addr.sin_addr.s_addr) {
11809       ast_log(LOG_NOTICE, "Can't provision something with no IP?\n");
11810       return -1;
11811    }
11812    res = iax2_provision(&iaxs[callno]->addr, iaxs[callno]->sockfd, NULL, sdata, force);
11813    ast_verb(3, "Provisioned IAXY at '%s' with '%s'= %d\n",
11814       ast_inet_ntoa(iaxs[callno]->addr.sin_addr),
11815       sdata, res);
11816    return res;
11817 }
11818 
11819 static char *handle_cli_iax2_provision(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
11820 {
11821    int force = 0;
11822    int res;
11823 
11824    switch (cmd) {
11825    case CLI_INIT:
11826       e->command = "iax2 provision";
11827       e->usage = 
11828          "Usage: iax2 provision <host> <template> [forced]\n"
11829          "       Provisions the given peer or IP address using a template\n"
11830          "       matching either 'template' or '*' if the template is not\n"
11831          "       found.  If 'forced' is specified, even empty provisioning\n"
11832          "       fields will be provisioned as empty fields.\n";
11833       return NULL;
11834    case CLI_GENERATE:
11835       if (a->pos == 3)
11836          return iax_prov_complete_template(a->line, a->word, a->pos, a->n);
11837       return NULL;
11838    }
11839 
11840    if (a->argc < 4)
11841       return CLI_SHOWUSAGE;
11842    if (a->argc > 4) {
11843       if (!strcasecmp(a->argv[4], "forced"))
11844          force = 1;
11845       else
11846          return CLI_SHOWUSAGE;
11847    }
11848    res = iax2_provision(NULL, -1, a->argv[2], a->argv[3], force);
11849    if (res < 0)
11850       ast_cli(a->fd, "Unable to find peer/address '%s'\n", a->argv[2]);
11851    else if (res < 1)
11852       ast_cli(a->fd, "No template (including wildcard) matching '%s'\n", a->argv[3]);
11853    else
11854       ast_cli(a->fd, "Provisioning '%s' with template '%s'%s\n", a->argv[2], a->argv[3], force ? ", forced" : "");
11855    return CLI_SUCCESS;
11856 }
11857 
11858 static void __iax2_poke_noanswer(const void *data)
11859 {
11860    struct iax2_peer *peer = (struct iax2_peer *)data;
11861    int callno;
11862 
11863    if (peer->lastms > -1) {
11864       ast_log(LOG_NOTICE, "Peer '%s' is now UNREACHABLE! Time: %d\n", peer->name, peer->lastms);
11865       manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: IAX2\r\nPeer: IAX2/%s\r\nPeerStatus: Unreachable\r\nTime: %d\r\n", peer->name, peer->lastms);
11866       ast_devstate_changed(AST_DEVICE_UNAVAILABLE, "IAX2/%s", peer->name); /* Activate notification */
11867    }
11868    if ((callno = peer->callno) > 0) {
11869       ast_mutex_lock(&iaxsl[callno]);
11870       iax2_destroy(callno);
11871       ast_mutex_unlock(&iaxsl[callno]);
11872    }
11873    peer->callno = 0;
11874    peer->lastms = -1;
11875    /* Try again quickly */
11876    peer->pokeexpire = iax2_sched_add(sched, peer->pokefreqnotok, iax2_poke_peer_s, peer_ref(peer));
11877    if (peer->pokeexpire == -1)
11878       peer_unref(peer);
11879 }
11880 
11881 static int iax2_poke_noanswer(const void *data)
11882 {
11883    struct iax2_peer *peer = (struct iax2_peer *)data;
11884    peer->pokeexpire = -1;
11885 #ifdef SCHED_MULTITHREADED
11886    if (schedule_action(__iax2_poke_noanswer, data))
11887 #endif      
11888       __iax2_poke_noanswer(data);
11889    peer_unref(peer);
11890    return 0;
11891 }
11892 
11893 static int iax2_poke_peer_cb(void *obj, void *arg, int flags)
11894 {
11895    struct iax2_peer *peer = obj;
11896 
11897    iax2_poke_peer(peer, 0);
11898 
11899    return 0;
11900 }
11901 
11902 static int iax2_poke_peer(struct iax2_peer *peer, int heldcall)
11903 {
11904    int callno;
11905    struct sockaddr_in peer_addr;
11906 
11907    if (!peer->maxms || (!ast_sockaddr_ipv4(&peer->addr) && !peer->dnsmgr)) {
11908       /* IF we have no IP without dnsmgr, or this isn't to be monitored, return
11909         immediately after clearing things out */
11910       peer->lastms = 0;
11911       peer->historicms = 0;
11912       peer->pokeexpire = -1;
11913       peer->callno = 0;
11914       return 0;
11915    }
11916 
11917    ast_sockaddr_to_sin(&peer->addr, &peer_addr);
11918 
11919    /* The peer could change the callno inside iax2_destroy, since we do deadlock avoidance */
11920    if ((callno = peer->callno) > 0) {
11921       ast_log(LOG_NOTICE, "Still have a callno...\n");
11922       ast_mutex_lock(&iaxsl[callno]);
11923       iax2_destroy(callno);
11924       ast_mutex_unlock(&iaxsl[callno]);
11925    }
11926    if (heldcall)
11927       ast_mutex_unlock(&iaxsl[heldcall]);
11928    callno = peer->callno = find_callno(0, 0, &peer_addr, NEW_FORCE, peer->sockfd, 0);
11929    if (heldcall)
11930       ast_mutex_lock(&iaxsl[heldcall]);
11931    if (peer->callno < 1) {
11932       ast_log(LOG_WARNING, "Unable to allocate call for poking peer '%s'\n", peer->name);
11933       return -1;
11934    }
11935 
11936    /* Speed up retransmission times for this qualify call */
11937    iaxs[peer->callno]->pingtime = peer->maxms / 4 + 1;
11938    iaxs[peer->callno]->peerpoke = peer;
11939 
11940    if (peer->pokeexpire > -1) {
11941       if (!ast_sched_thread_del(sched, peer->pokeexpire)) {
11942          peer->pokeexpire = -1;
11943          peer_unref(peer);
11944       }
11945    }
11946  
11947    /* Queue up a new task to handle no reply */
11948    /* If the host is already unreachable then use the unreachable interval instead */
11949    if (peer->lastms < 0)
11950       peer->pokeexpire = iax2_sched_add(sched, peer->pokefreqnotok, iax2_poke_noanswer, peer_ref(peer));
11951    else
11952       peer->pokeexpire = iax2_sched_add(sched, DEFAULT_MAXMS * 2, iax2_poke_noanswer, peer_ref(peer));
11953 
11954    if (peer->pokeexpire == -1)
11955       peer_unref(peer);
11956 
11957    /* And send the poke */
11958    ast_mutex_lock(&iaxsl[callno]);
11959    if (iaxs[callno]) {
11960       struct iax_ie_data ied = {
11961          .buf = { 0 },
11962          .pos = 0,
11963       };
11964       add_empty_calltoken_ie(iaxs[callno], &ied); /* this _MUST_ be the last ie added */
11965       send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_POKE, 0, ied.buf, ied.pos, -1);
11966    }
11967    ast_mutex_unlock(&iaxsl[callno]);
11968 
11969    return 0;
11970 }
11971 
11972 static void free_context(struct iax2_context *con)
11973 {
11974    struct iax2_context *conl;
11975    while(con) {
11976       conl = con;
11977       con = con->next;
11978       ast_free(conl);
11979    }
11980 }
11981 
11982 static struct ast_channel *iax2_request(const char *type, format_t format, const struct ast_channel *requestor, void *data, int *cause)
11983 {
11984    int callno;
11985    int res;
11986    format_t fmt, native;
11987    struct sockaddr_in sin;
11988    struct ast_channel *c;
11989    struct parsed_dial_string pds;
11990    struct create_addr_info cai;
11991    char *tmpstr;
11992 
11993    memset(&pds, 0, sizeof(pds));
11994    tmpstr = ast_strdupa(data);
11995    parse_dial_string(tmpstr, &pds);
11996 
11997    if (ast_strlen_zero(pds.peer)) {
11998       ast_log(LOG_WARNING, "No peer provided in the IAX2 dial string '%s'\n", (char *) data);
11999       return NULL;
12000    }
12001           
12002    memset(&cai, 0, sizeof(cai));
12003    cai.capability = iax2_capability;
12004 
12005    ast_copy_flags64(&cai, &globalflags, IAX_NOTRANSFER | IAX_TRANSFERMEDIA | IAX_USEJITTERBUF | IAX_FORCEJITTERBUF | IAX_SENDCONNECTEDLINE | IAX_RECVCONNECTEDLINE);
12006    
12007    /* Populate our address from the given */
12008    if (create_addr(pds.peer, NULL, &sin, &cai)) {
12009       *cause = AST_CAUSE_UNREGISTERED;
12010       return NULL;
12011    }
12012 
12013    if (pds.port)
12014       sin.sin_port = htons(atoi(pds.port));
12015 
12016    callno = find_callno_locked(0, 0, &sin, NEW_FORCE, cai.sockfd, 0);
12017    if (callno < 1) {
12018       ast_log(LOG_WARNING, "Unable to create call\n");
12019       *cause = AST_CAUSE_CONGESTION;
12020       return NULL;
12021    }
12022 
12023    /* If this is a trunk, update it now */
12024    ast_copy_flags64(iaxs[callno], &cai, IAX_TRUNK | IAX_SENDANI | IAX_NOTRANSFER | IAX_TRANSFERMEDIA | IAX_USEJITTERBUF | IAX_FORCEJITTERBUF | IAX_SENDCONNECTEDLINE | IAX_RECVCONNECTEDLINE);
12025    if (ast_test_flag64(&cai, IAX_TRUNK)) {
12026       int new_callno;
12027       if ((new_callno = make_trunk(callno, 1)) != -1)
12028          callno = new_callno;
12029    }
12030    iaxs[callno]->maxtime = cai.maxtime;
12031    if (cai.found)
12032       ast_string_field_set(iaxs[callno], host, pds.peer);
12033 
12034    c = ast_iax2_new(callno, AST_STATE_DOWN, cai.capability, requestor ? requestor->linkedid : NULL);
12035 
12036    ast_mutex_unlock(&iaxsl[callno]);
12037 
12038    if (c) {
12039       /* Choose a format we can live with */
12040       if (c->nativeformats & format) 
12041          c->nativeformats &= format;
12042       else {
12043          native = c->nativeformats;
12044          fmt = format;
12045          res = ast_translator_best_choice(&fmt, &native);
12046          if (res < 0) {
12047             ast_log(LOG_WARNING, "Unable to create translator path for %s to %s on %s\n",
12048                ast_getformatname(c->nativeformats), ast_getformatname(fmt), c->name);
12049             ast_hangup(c);
12050             return NULL;
12051          }
12052          c->nativeformats = native;
12053       }
12054       c->readformat = ast_best_codec(c->nativeformats);
12055       c->writeformat = c->readformat;
12056    }
12057 
12058    return c;
12059 }
12060 
12061 static void *network_thread(void *ignore)
12062 {
12063    if (timer) {
12064       ast_io_add(io, ast_timer_fd(timer), timing_read, AST_IO_IN | AST_IO_PRI, NULL);
12065    }
12066 
12067    for (;;) {
12068       pthread_testcancel();
12069       /* Wake up once a second just in case SIGURG was sent while
12070        * we weren't in poll(), to make sure we don't hang when trying
12071        * to unload. */
12072       ast_io_wait(io, 1000);
12073    }
12074 
12075    return NULL;
12076 }
12077 
12078 static int start_network_thread(void)
12079 {
12080    struct iax2_thread *thread;
12081    int threadcount = 0;
12082    int x;
12083    for (x = 0; x < iaxthreadcount; x++) {
12084       thread = ast_calloc(1, sizeof(*thread));
12085       if (thread) {
12086          thread->type = IAX_THREAD_TYPE_POOL;
12087          thread->threadnum = ++threadcount;
12088          ast_mutex_init(&thread->lock);
12089          ast_cond_init(&thread->cond, NULL);
12090          if (ast_pthread_create_background(&thread->threadid, NULL, iax2_process_thread, thread)) {
12091             ast_log(LOG_WARNING, "Failed to create new thread!\n");
12092             ast_free(thread);
12093             thread = NULL;
12094          }
12095          AST_LIST_LOCK(&idle_list);
12096          AST_LIST_INSERT_TAIL(&idle_list, thread, list);
12097          AST_LIST_UNLOCK(&idle_list);
12098       }
12099    }
12100    ast_pthread_create_background(&netthreadid, NULL, network_thread, NULL);
12101    ast_verb(2, "%d helper threads started\n", threadcount);
12102    return 0;
12103 }
12104 
12105 static struct iax2_context *build_context(const char *context)
12106 {
12107    struct iax2_context *con;
12108 
12109    if ((con = ast_calloc(1, sizeof(*con))))
12110       ast_copy_string(con->context, context, sizeof(con->context));
12111    
12112    return con;
12113 }
12114 
12115 static int get_auth_methods(const char *value)
12116 {
12117    int methods = 0;
12118    if (strstr(value, "rsa"))
12119       methods |= IAX_AUTH_RSA;
12120    if (strstr(value, "md5"))
12121       methods |= IAX_AUTH_MD5;
12122    if (strstr(value, "plaintext"))
12123       methods |= IAX_AUTH_PLAINTEXT;
12124    return methods;
12125 }
12126 
12127 
12128 /*! \brief Check if address can be used as packet source.
12129  \return 0  address available, 1  address unavailable, -1  error
12130 */
12131 static int check_srcaddr(struct sockaddr *sa, socklen_t salen)
12132 {
12133    int sd;
12134    int res;
12135    
12136    sd = socket(AF_INET, SOCK_DGRAM, 0);
12137    if (sd < 0) {
12138       ast_log(LOG_ERROR, "Socket: %s\n", strerror(errno));
12139       return -1;
12140    }
12141 
12142    res = bind(sd, sa, salen);
12143    if (res < 0) {
12144       ast_debug(1, "Can't bind: %s\n", strerror(errno));
12145       close(sd);
12146       return 1;
12147    }
12148 
12149    close(sd);
12150    return 0;
12151 }
12152 
12153 /*! \brief Parse the "sourceaddress" value,
12154   lookup in netsock list and set peer's sockfd. Defaults to defaultsockfd if
12155   not found. */
12156 static int peer_set_srcaddr(struct iax2_peer *peer, const char *srcaddr)
12157 {
12158    struct sockaddr_in sin;
12159    struct ast_sockaddr sin_tmp;
12160    int nonlocal = 1;
12161    int port = IAX_DEFAULT_PORTNO;
12162    int sockfd = defaultsockfd;
12163    char *tmp;
12164    char *addr;
12165    char *portstr;
12166 
12167    if (!(tmp = ast_strdupa(srcaddr)))
12168       return -1;
12169 
12170    addr = strsep(&tmp, ":");
12171    portstr = tmp;
12172 
12173    if (portstr) {
12174       port = atoi(portstr);
12175       if (port < 1)
12176          port = IAX_DEFAULT_PORTNO;
12177    }
12178    
12179    if (!ast_get_ip(&sin_tmp, addr)) {
12180       struct ast_netsock *sock;
12181       int res;
12182 
12183       ast_sockaddr_to_sin(&sin_tmp, &sin);
12184       sin.sin_port = 0;
12185       sin.sin_family = AF_INET;
12186       res = check_srcaddr((struct sockaddr *) &sin, sizeof(sin));
12187       if (res == 0) {
12188          /* ip address valid. */
12189          sin.sin_port = htons(port);
12190          if (!(sock = ast_netsock_find(netsock, &sin)))
12191             sock = ast_netsock_find(outsock, &sin);
12192          if (sock) {
12193             sockfd = ast_netsock_sockfd(sock);
12194             nonlocal = 0;
12195          } else {
12196             unsigned int orig_saddr = sin.sin_addr.s_addr;
12197             /* INADDR_ANY matches anyway! */
12198             sin.sin_addr.s_addr = INADDR_ANY;
12199             if (ast_netsock_find(netsock, &sin)) {
12200                sin.sin_addr.s_addr = orig_saddr;
12201                sock = ast_netsock_bind(outsock, io, srcaddr, port, qos.tos, qos.cos, socket_read, NULL);
12202                if (sock) {
12203                   sockfd = ast_netsock_sockfd(sock);
12204                   ast_netsock_unref(sock);
12205                   nonlocal = 0;
12206                } else {
12207                   nonlocal = 2;
12208                }
12209             }
12210          }
12211       }
12212    }
12213       
12214    peer->sockfd = sockfd;
12215 
12216    if (nonlocal == 1) {
12217       ast_log(LOG_WARNING, "Non-local or unbound address specified (%s) in sourceaddress for '%s', reverting to default\n",
12218          srcaddr, peer->name);
12219       return -1;
12220         } else if (nonlocal == 2) {
12221       ast_log(LOG_WARNING, "Unable to bind to sourceaddress '%s' for '%s', reverting to default\n",
12222          srcaddr, peer->name);
12223          return -1;
12224    } else {
12225       ast_debug(1, "Using sourceaddress %s for '%s'\n", srcaddr, peer->name);
12226       return 0;
12227    }
12228 }
12229 
12230 static void peer_destructor(void *obj)
12231 {
12232    struct iax2_peer *peer = obj;
12233    int callno = peer->callno;
12234 
12235    ast_free_ha(peer->ha);
12236 
12237    if (callno > 0) {
12238       ast_mutex_lock(&iaxsl[callno]);
12239       iax2_destroy(callno);
12240       ast_mutex_unlock(&iaxsl[callno]);
12241    }
12242 
12243    register_peer_exten(peer, 0);
12244 
12245    if (peer->dnsmgr)
12246       ast_dnsmgr_release(peer->dnsmgr);
12247 
12248    if (peer->mwi_event_sub)
12249       ast_event_unsubscribe(peer->mwi_event_sub);
12250 
12251    ast_string_field_free_memory(peer);
12252 }
12253 
12254 /*! \brief Create peer structure based on configuration */
12255 static struct iax2_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly)
12256 {
12257    struct iax2_peer *peer = NULL;
12258    struct ast_ha *oldha = NULL;
12259    int maskfound = 0;
12260    int found = 0;
12261    int firstpass = 1;
12262    struct iax2_peer tmp_peer = {
12263       .name = name,
12264    };
12265 
12266    if (!temponly) {
12267       peer = ao2_find(peers, &tmp_peer, OBJ_POINTER);
12268       if (peer && !ast_test_flag64(peer, IAX_DELME))
12269          firstpass = 0;
12270    }
12271 
12272    if (peer) {
12273       found++;
12274       if (firstpass) {
12275          oldha = peer->ha;
12276          peer->ha = NULL;
12277       }
12278       unlink_peer(peer);
12279    } else if ((peer = ao2_alloc(sizeof(*peer), peer_destructor))) {
12280       peer->expire = -1;
12281       peer->pokeexpire = -1;
12282       peer->sockfd = defaultsockfd;
12283       if (ast_string_field_init(peer, 32))
12284          peer = peer_unref(peer);
12285    }
12286 
12287    if (peer) {
12288       if (firstpass) {
12289          ast_copy_flags64(peer, &globalflags, IAX_USEJITTERBUF | IAX_FORCEJITTERBUF | IAX_SENDCONNECTEDLINE | IAX_RECVCONNECTEDLINE | IAX_FORCE_ENCRYPT);
12290          peer->encmethods = iax2_encryption;
12291          peer->adsi = adsi;
12292          ast_string_field_set(peer,secret,"");
12293          if (!found) {
12294             ast_string_field_set(peer, name, name);
12295             ast_sockaddr_set_port(&peer->addr, IAX_DEFAULT_PORTNO);
12296             peer->expiry = min_reg_expire;
12297          }
12298          peer->prefs = prefs;
12299          peer->capability = iax2_capability;
12300          peer->smoothing = 0;
12301          peer->pokefreqok = DEFAULT_FREQ_OK;
12302          peer->pokefreqnotok = DEFAULT_FREQ_NOTOK;
12303          peer->maxcallno = 0;
12304          peercnt_modify(0, 0, &peer->addr);
12305          peer->calltoken_required = CALLTOKEN_DEFAULT;
12306          ast_string_field_set(peer,context,"");
12307          ast_string_field_set(peer,peercontext,"");
12308          ast_clear_flag64(peer, IAX_HASCALLERID);
12309          ast_string_field_set(peer, cid_name, "");
12310          ast_string_field_set(peer, cid_num, "");
12311          ast_string_field_set(peer, mohinterpret, mohinterpret);
12312          ast_string_field_set(peer, mohsuggest, mohsuggest);
12313       }
12314 
12315       if (!v) {
12316          v = alt;
12317          alt = NULL;
12318       }
12319       while(v) {
12320          if (!strcasecmp(v->name, "secret")) {
12321             ast_string_field_set(peer, secret, v->value);
12322          } else if (!strcasecmp(v->name, "mailbox")) {
12323             ast_string_field_set(peer, mailbox, v->value);
12324          } else if (!strcasecmp(v->name, "hasvoicemail")) {
12325             if (ast_true(v->value) && ast_strlen_zero(peer->mailbox)) {
12326                ast_string_field_set(peer, mailbox, name);
12327             }
12328          } else if (!strcasecmp(v->name, "mohinterpret")) {
12329             ast_string_field_set(peer, mohinterpret, v->value);
12330          } else if (!strcasecmp(v->name, "mohsuggest")) {
12331             ast_string_field_set(peer, mohsuggest, v->value);
12332          } else if (!strcasecmp(v->name, "dbsecret")) {
12333             ast_string_field_set(peer, dbsecret, v->value);
12334          } else if (!strcasecmp(v->name, "trunk")) {
12335             ast_set2_flag64(peer, ast_true(v->value), IAX_TRUNK); 
12336             if (ast_test_flag64(peer, IAX_TRUNK) && !timer) {
12337                ast_log(LOG_WARNING, "Unable to support trunking on peer '%s' without a timing interface\n", peer->name);
12338                ast_clear_flag64(peer, IAX_TRUNK);
12339             }
12340          } else if (!strcasecmp(v->name, "auth")) {
12341             peer->authmethods = get_auth_methods(v->value);
12342          } else if (!strcasecmp(v->name, "encryption")) {
12343             peer->encmethods |= get_encrypt_methods(v->value);
12344             if (!peer->encmethods) {
12345                ast_clear_flag64(peer, IAX_FORCE_ENCRYPT);
12346             }
12347          } else if (!strcasecmp(v->name, "forceencryption")) {
12348             if (ast_false(v->value)) {
12349                ast_clear_flag64(peer, IAX_FORCE_ENCRYPT);
12350             } else {
12351                peer->encmethods |= get_encrypt_methods(v->value);
12352                if (peer->encmethods) {
12353                   ast_set_flag64(peer, IAX_FORCE_ENCRYPT);
12354                }
12355             }
12356          } else if (!strcasecmp(v->name, "transfer")) {
12357             if (!strcasecmp(v->value, "mediaonly")) {
12358                ast_set_flags_to64(peer, IAX_NOTRANSFER|IAX_TRANSFERMEDIA, IAX_TRANSFERMEDIA);
12359             } else if (ast_true(v->value)) {
12360                ast_set_flags_to64(peer, IAX_NOTRANSFER|IAX_TRANSFERMEDIA, 0);
12361             } else
12362                ast_set_flags_to64(peer, IAX_NOTRANSFER|IAX_TRANSFERMEDIA, IAX_NOTRANSFER);
12363          } else if (!strcasecmp(v->name, "jitterbuffer")) {
12364             ast_set2_flag64(peer, ast_true(v->value), IAX_USEJITTERBUF);
12365          } else if (!strcasecmp(v->name, "forcejitterbuffer")) {
12366             ast_set2_flag64(peer, ast_true(v->value), IAX_FORCEJITTERBUF);
12367          } else if (!strcasecmp(v->name, "host")) {
12368             if (!strcasecmp(v->value, "dynamic")) {
12369                /* They'll register with us */
12370                ast_set_flag64(peer, IAX_DYNAMIC);
12371                if (!found) {
12372                   /* Initialize stuff iff we're not found, otherwise
12373                      we keep going with what we had */
12374                   if (ast_sockaddr_port(&peer->addr)) {
12375                      peer->defaddr.sin_port = htons(ast_sockaddr_port(&peer->addr));
12376                   }
12377                   ast_sockaddr_setnull(&peer->addr);
12378                }
12379             } else {
12380                /* Non-dynamic.  Make sure we become that way if we're not */
12381                ast_sched_thread_del(sched, peer->expire);
12382                ast_clear_flag64(peer, IAX_DYNAMIC);
12383                if (ast_dnsmgr_lookup(v->value, &peer->addr, &peer->dnsmgr, srvlookup ? "_iax._udp" : NULL))
12384                   return peer_unref(peer);
12385                if (!ast_sockaddr_port(&peer->addr)) {
12386                   ast_sockaddr_set_port(&peer->addr, IAX_DEFAULT_PORTNO);
12387                }
12388             }
12389             if (!maskfound)
12390                inet_aton("255.255.255.255", &peer->mask);
12391          } else if (!strcasecmp(v->name, "defaultip")) {
12392             struct ast_sockaddr peer_defaddr_tmp;
12393 
12394             if (ast_get_ip(&peer_defaddr_tmp, v->value)) {
12395                return peer_unref(peer);
12396             }
12397             ast_sockaddr_to_sin(&peer_defaddr_tmp,
12398                       &peer->defaddr);
12399          } else if (!strcasecmp(v->name, "sourceaddress")) {
12400             peer_set_srcaddr(peer, v->value);
12401          } else if (!strcasecmp(v->name, "permit") ||
12402                   !strcasecmp(v->name, "deny")) {
12403             peer->ha = ast_append_ha(v->name, v->value, peer->ha, NULL);
12404          } else if (!strcasecmp(v->name, "mask")) {
12405             maskfound++;
12406             inet_aton(v->value, &peer->mask);
12407          } else if (!strcasecmp(v->name, "context")) {
12408             ast_string_field_set(peer, context, v->value);
12409          } else if (!strcasecmp(v->name, "regexten")) {
12410             ast_string_field_set(peer, regexten, v->value);
12411          } else if (!strcasecmp(v->name, "peercontext")) {
12412             ast_string_field_set(peer, peercontext, v->value);
12413          } else if (!strcasecmp(v->name, "port")) {
12414             if (ast_test_flag64(peer, IAX_DYNAMIC)) {
12415                peer->defaddr.sin_port = htons(atoi(v->value));
12416             } else {
12417                ast_sockaddr_set_port(&peer->addr, atoi(v->value));
12418             }
12419          } else if (!strcasecmp(v->name, "username")) {
12420             ast_string_field_set(peer, username, v->value);
12421          } else if (!strcasecmp(v->name, "allow")) {
12422             ast_parse_allow_disallow(&peer->prefs, &peer->capability, v->value, 1);
12423          } else if (!strcasecmp(v->name, "disallow")) {
12424             ast_parse_allow_disallow(&peer->prefs, &peer->capability, v->value, 0);
12425          } else if (!strcasecmp(v->name, "callerid")) {
12426             if (!ast_strlen_zero(v->value)) {
12427                char name2[80];
12428                char num2[80];
12429                ast_callerid_split(v->value, name2, sizeof(name2), num2, sizeof(num2));
12430                ast_string_field_set(peer, cid_name, name2);
12431                ast_string_field_set(peer, cid_num, num2);
12432             } else {
12433                ast_string_field_set(peer, cid_name, "");
12434                ast_string_field_set(peer, cid_num, "");
12435             }
12436             ast_set_flag64(peer, IAX_HASCALLERID);
12437          } else if (!strcasecmp(v->name, "fullname")) {
12438             ast_string_field_set(peer, cid_name, S_OR(v->value, ""));
12439             ast_set_flag64(peer, IAX_HASCALLERID);
12440          } else if (!strcasecmp(v->name, "cid_number")) {
12441             ast_string_field_set(peer, cid_num, S_OR(v->value, ""));
12442             ast_set_flag64(peer, IAX_HASCALLERID);
12443          } else if (!strcasecmp(v->name, "sendani")) {
12444             ast_set2_flag64(peer, ast_true(v->value), IAX_SENDANI);
12445          } else if (!strcasecmp(v->name, "inkeys")) {
12446             ast_string_field_set(peer, inkeys, v->value);
12447          } else if (!strcasecmp(v->name, "outkey")) {
12448             ast_string_field_set(peer, outkey, v->value);
12449          } else if (!strcasecmp(v->name, "qualify")) {
12450             if (!strcasecmp(v->value, "no")) {
12451                peer->maxms = 0;
12452             } else if (!strcasecmp(v->value, "yes")) {
12453                peer->maxms = DEFAULT_MAXMS;
12454             } else if (sscanf(v->value, "%30d", &peer->maxms) != 1) {
12455                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);
12456                peer->maxms = 0;
12457             }
12458          } else if (!strcasecmp(v->name, "qualifysmoothing")) {
12459             peer->smoothing = ast_true(v->value);
12460          } else if (!strcasecmp(v->name, "qualifyfreqok")) {
12461             if (sscanf(v->value, "%30d", &peer->pokefreqok) != 1) {
12462                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);
12463             }
12464          } else if (!strcasecmp(v->name, "qualifyfreqnotok")) {
12465             if (sscanf(v->value, "%30d", &peer->pokefreqnotok) != 1) {
12466                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);
12467             } else ast_log(LOG_WARNING, "Set peer->pokefreqnotok to %d\n", peer->pokefreqnotok);
12468          } else if (!strcasecmp(v->name, "timezone")) {
12469             ast_string_field_set(peer, zonetag, v->value);
12470          } else if (!strcasecmp(v->name, "adsi")) {
12471             peer->adsi = ast_true(v->value);
12472          } else if (!strcasecmp(v->name, "connectedline")) {
12473             if (ast_true(v->value)) {
12474                ast_set_flag64(peer, IAX_SENDCONNECTEDLINE | IAX_RECVCONNECTEDLINE);
12475             } else if (!strcasecmp(v->value, "send")) {
12476                ast_clear_flag64(peer, IAX_RECVCONNECTEDLINE);
12477                ast_set_flag64(peer, IAX_SENDCONNECTEDLINE);
12478             } else if (!strcasecmp(v->value, "receive")) {
12479                ast_clear_flag64(peer, IAX_SENDCONNECTEDLINE);
12480                ast_set_flag64(peer, IAX_RECVCONNECTEDLINE);
12481             } else {
12482                ast_clear_flag64(peer, IAX_SENDCONNECTEDLINE | IAX_RECVCONNECTEDLINE);
12483             }
12484          } else if (!strcasecmp(v->name, "maxcallnumbers")) {
12485             if (sscanf(v->value, "%10hu", &peer->maxcallno) != 1) {
12486                ast_log(LOG_WARNING, "maxcallnumbers must be set to a valid number. %s is not valid at line %d.\n", v->value, v->lineno);
12487             } else {
12488                peercnt_modify(1, peer->maxcallno, &peer->addr);
12489             }
12490          } else if (!strcasecmp(v->name, "requirecalltoken")) {
12491             /* default is required unless in optional ip list */
12492             if (ast_false(v->value)) {
12493                peer->calltoken_required = CALLTOKEN_NO;
12494             } else if (!strcasecmp(v->value, "auto")) {
12495                peer->calltoken_required = CALLTOKEN_AUTO;
12496             } else if (ast_true(v->value)) {
12497                peer->calltoken_required = CALLTOKEN_YES;
12498             } else {
12499                ast_log(LOG_WARNING, "requirecalltoken must be set to a valid value. at line %d\n", v->lineno);
12500             }
12501          } /* else if (strcasecmp(v->name,"type")) */
12502          /* ast_log(LOG_WARNING, "Ignoring %s\n", v->name); */
12503          v = v->next;
12504          if (!v) {
12505             v = alt;
12506             alt = NULL;
12507          }
12508       }
12509       if (!peer->authmethods)
12510          peer->authmethods = IAX_AUTH_MD5 | IAX_AUTH_PLAINTEXT;
12511       ast_clear_flag64(peer, IAX_DELME);
12512    }
12513 
12514    if (oldha)
12515       ast_free_ha(oldha);
12516 
12517    if (!ast_strlen_zero(peer->mailbox)) {
12518       char *mailbox, *context;
12519       context = mailbox = ast_strdupa(peer->mailbox);
12520       strsep(&context, "@");
12521       if (ast_strlen_zero(context))
12522          context = "default";
12523       peer->mwi_event_sub = ast_event_subscribe(AST_EVENT_MWI, mwi_event_cb, "IAX MWI subscription", NULL,
12524          AST_EVENT_IE_MAILBOX, AST_EVENT_IE_PLTYPE_STR, mailbox,
12525          AST_EVENT_IE_CONTEXT, AST_EVENT_IE_PLTYPE_STR, context,
12526          AST_EVENT_IE_END);
12527    }
12528 
12529    return peer;
12530 }
12531 
12532 static void user_destructor(void *obj)
12533 {
12534    struct iax2_user *user = obj;
12535 
12536    ast_free_ha(user->ha);
12537    free_context(user->contexts);
12538    if(user->vars) {
12539       ast_variables_destroy(user->vars);
12540       user->vars = NULL;
12541    }
12542    ast_string_field_free_memory(user);
12543 }
12544 
12545 /*! \brief Create in-memory user structure from configuration */
12546 static struct iax2_user *build_user(const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly)
12547 {
12548    struct iax2_user *user = NULL;
12549    struct iax2_context *con, *conl = NULL;
12550    struct ast_ha *oldha = NULL;
12551    struct iax2_context *oldcon = NULL;
12552    int format;
12553    int firstpass=1;
12554    int oldcurauthreq = 0;
12555    char *varname = NULL, *varval = NULL;
12556    struct ast_variable *tmpvar = NULL;
12557    struct iax2_user tmp_user = {
12558       .name = name,
12559    };
12560 
12561    if (!temponly) {
12562       user = ao2_find(users, &tmp_user, OBJ_POINTER);
12563       if (user && !ast_test_flag64(user, IAX_DELME))
12564          firstpass = 0;
12565    }
12566 
12567    if (user) {
12568       if (firstpass) {
12569          oldcurauthreq = user->curauthreq;
12570          oldha = user->ha;
12571          oldcon = user->contexts;
12572          user->ha = NULL;
12573          user->contexts = NULL;
12574       }
12575       /* Already in the list, remove it and it will be added back (or FREE'd) */
12576       ao2_unlink(users, user);
12577    } else {
12578       user = ao2_alloc(sizeof(*user), user_destructor);
12579    }
12580    
12581    if (user) {
12582       if (firstpass) {
12583          ast_string_field_free_memory(user);
12584          memset(user, 0, sizeof(struct iax2_user));
12585          if (ast_string_field_init(user, 32)) {
12586             user = user_unref(user);
12587             goto cleanup;
12588          }
12589          user->maxauthreq = maxauthreq;
12590          user->curauthreq = oldcurauthreq;
12591          user->prefs = prefs;
12592          user->capability = iax2_capability;
12593          user->encmethods = iax2_encryption;
12594          user->adsi = adsi;
12595          user->calltoken_required = CALLTOKEN_DEFAULT;
12596          ast_string_field_set(user, name, name);
12597          ast_string_field_set(user, language, language);
12598          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);
12599          ast_clear_flag64(user, IAX_HASCALLERID);
12600          ast_string_field_set(user, cid_name, "");
12601          ast_string_field_set(user, cid_num, "");
12602          ast_string_field_set(user, accountcode, accountcode);
12603          ast_string_field_set(user, mohinterpret, mohinterpret);
12604          ast_string_field_set(user, mohsuggest, mohsuggest);
12605       }
12606       if (!v) {
12607          v = alt;
12608          alt = NULL;
12609       }
12610       while(v) {
12611          if (!strcasecmp(v->name, "context")) {
12612             con = build_context(v->value);
12613             if (con) {
12614                if (conl)
12615                   conl->next = con;
12616                else
12617                   user->contexts = con;
12618                conl = con;
12619             }
12620          } else if (!strcasecmp(v->name, "permit") ||
12621                   !strcasecmp(v->name, "deny")) {
12622             user->ha = ast_append_ha(v->name, v->value, user->ha, NULL);
12623          } else if (!strcasecmp(v->name, "setvar")) {
12624             varname = ast_strdupa(v->value);
12625             if (varname && (varval = strchr(varname,'='))) {
12626                *varval = '\0';
12627                varval++;
12628                if((tmpvar = ast_variable_new(varname, varval, ""))) {
12629                   tmpvar->next = user->vars; 
12630                   user->vars = tmpvar;
12631                }
12632             }
12633          } else if (!strcasecmp(v->name, "allow")) {
12634             ast_parse_allow_disallow(&user->prefs, &user->capability, v->value, 1);
12635          } else if (!strcasecmp(v->name, "disallow")) {
12636             ast_parse_allow_disallow(&user->prefs, &user->capability,v->value, 0);
12637          } else if (!strcasecmp(v->name, "trunk")) {
12638             ast_set2_flag64(user, ast_true(v->value), IAX_TRUNK); 
12639             if (ast_test_flag64(user, IAX_TRUNK) && !timer) {
12640                ast_log(LOG_WARNING, "Unable to support trunking on user '%s' without a timing interface\n", user->name);
12641                ast_clear_flag64(user, IAX_TRUNK);
12642             }
12643          } else if (!strcasecmp(v->name, "auth")) {
12644             user->authmethods = get_auth_methods(v->value);
12645          } else if (!strcasecmp(v->name, "encryption")) {
12646             user->encmethods |= get_encrypt_methods(v->value);
12647             if (!user->encmethods) {
12648                ast_clear_flag64(user, IAX_FORCE_ENCRYPT);
12649             }
12650          } else if (!strcasecmp(v->name, "forceencryption")) {
12651             if (ast_false(v->value)) {
12652                ast_clear_flag64(user, IAX_FORCE_ENCRYPT);
12653             } else {
12654                user->encmethods |= get_encrypt_methods(v->value);
12655                if (user->encmethods) {
12656                   ast_set_flag64(user, IAX_FORCE_ENCRYPT);
12657                }
12658             }
12659          } else if (!strcasecmp(v->name, "transfer")) {
12660             if (!strcasecmp(v->value, "mediaonly")) {
12661                ast_set_flags_to64(user, IAX_NOTRANSFER|IAX_TRANSFERMEDIA, IAX_TRANSFERMEDIA);
12662             } else if (ast_true(v->value)) {
12663                ast_set_flags_to64(user, IAX_NOTRANSFER|IAX_TRANSFERMEDIA, 0);
12664             } else
12665                ast_set_flags_to64(user, IAX_NOTRANSFER|IAX_TRANSFERMEDIA, IAX_NOTRANSFER);
12666          } else if (!strcasecmp(v->name, "codecpriority")) {
12667             if(!strcasecmp(v->value, "caller"))
12668                ast_set_flag64(user, IAX_CODEC_USER_FIRST);
12669             else if(!strcasecmp(v->value, "disabled"))
12670                ast_set_flag64(user, IAX_CODEC_NOPREFS);
12671             else if(!strcasecmp(v->value, "reqonly")) {
12672                ast_set_flag64(user, IAX_CODEC_NOCAP);
12673                ast_set_flag64(user, IAX_CODEC_NOPREFS);
12674             }
12675          } else if (!strcasecmp(v->name, "immediate")) {
12676             ast_set2_flag64(user, ast_true(v->value), IAX_IMMEDIATE);
12677          } else if (!strcasecmp(v->name, "jitterbuffer")) {
12678             ast_set2_flag64(user, ast_true(v->value), IAX_USEJITTERBUF);
12679          } else if (!strcasecmp(v->name, "forcejitterbuffer")) {
12680             ast_set2_flag64(user, ast_true(v->value), IAX_FORCEJITTERBUF);
12681          } else if (!strcasecmp(v->name, "dbsecret")) {
12682             ast_string_field_set(user, dbsecret, v->value);
12683          } else if (!strcasecmp(v->name, "secret")) {
12684             if (!ast_strlen_zero(user->secret)) {
12685                char *old = ast_strdupa(user->secret);
12686 
12687                ast_string_field_build(user, secret, "%s;%s", old, v->value);
12688             } else
12689                ast_string_field_set(user, secret, v->value);
12690          } else if (!strcasecmp(v->name, "callerid")) {
12691             if (!ast_strlen_zero(v->value) && strcasecmp(v->value, "asreceived")) {
12692                char name2[80];
12693                char num2[80];
12694                ast_callerid_split(v->value, name2, sizeof(name2), num2, sizeof(num2));
12695                ast_string_field_set(user, cid_name, name2);
12696                ast_string_field_set(user, cid_num, num2);
12697                ast_set_flag64(user, IAX_HASCALLERID);
12698             } else {
12699                ast_clear_flag64(user, IAX_HASCALLERID);
12700                ast_string_field_set(user, cid_name, "");
12701                ast_string_field_set(user, cid_num, "");
12702             }
12703          } else if (!strcasecmp(v->name, "fullname")) {
12704             if (!ast_strlen_zero(v->value)) {
12705                ast_string_field_set(user, cid_name, v->value);
12706                ast_set_flag64(user, IAX_HASCALLERID);
12707             } else {
12708                ast_string_field_set(user, cid_name, "");
12709                if (ast_strlen_zero(user->cid_num))
12710                   ast_clear_flag64(user, IAX_HASCALLERID);
12711             }
12712          } else if (!strcasecmp(v->name, "cid_number")) {
12713             if (!ast_strlen_zero(v->value)) {
12714                ast_string_field_set(user, cid_num, v->value);
12715                ast_set_flag64(user, IAX_HASCALLERID);
12716             } else {
12717                ast_string_field_set(user, cid_num, "");
12718                if (ast_strlen_zero(user->cid_name))
12719                   ast_clear_flag64(user, IAX_HASCALLERID);
12720             }
12721          } else if (!strcasecmp(v->name, "accountcode")) {
12722             ast_string_field_set(user, accountcode, v->value);
12723          } else if (!strcasecmp(v->name, "mohinterpret")) {
12724             ast_string_field_set(user, mohinterpret, v->value);
12725          } else if (!strcasecmp(v->name, "mohsuggest")) {
12726             ast_string_field_set(user, mohsuggest, v->value);
12727          } else if (!strcasecmp(v->name, "parkinglot")) {
12728             ast_string_field_set(user, parkinglot, v->value);
12729          } else if (!strcasecmp(v->name, "language")) {
12730             ast_string_field_set(user, language, v->value);
12731          } else if (!strcasecmp(v->name, "amaflags")) {
12732             format = ast_cdr_amaflags2int(v->value);
12733             if (format < 0) {
12734                ast_log(LOG_WARNING, "Invalid AMA Flags: %s at line %d\n", v->value, v->lineno);
12735             } else {
12736                user->amaflags = format;
12737             }
12738          } else if (!strcasecmp(v->name, "inkeys")) {
12739             ast_string_field_set(user, inkeys, v->value);
12740          } else if (!strcasecmp(v->name, "maxauthreq")) {
12741             user->maxauthreq = atoi(v->value);
12742             if (user->maxauthreq < 0)
12743                user->maxauthreq = 0;
12744          } else if (!strcasecmp(v->name, "adsi")) {
12745             user->adsi = ast_true(v->value);
12746          } else if (!strcasecmp(v->name, "connectedline")) {
12747             if (ast_true(v->value)) {
12748                ast_set_flag64(user, IAX_SENDCONNECTEDLINE | IAX_RECVCONNECTEDLINE);
12749             } else if (!strcasecmp(v->value, "send")) {
12750                ast_clear_flag64(user, IAX_RECVCONNECTEDLINE);
12751                ast_set_flag64(user, IAX_SENDCONNECTEDLINE);
12752             } else if (!strcasecmp(v->value, "receive")) {
12753                ast_clear_flag64(user, IAX_SENDCONNECTEDLINE);
12754                ast_set_flag64(user, IAX_RECVCONNECTEDLINE);
12755             } else {
12756                ast_clear_flag64(user, IAX_SENDCONNECTEDLINE | IAX_RECVCONNECTEDLINE);
12757             }
12758          } else if (!strcasecmp(v->name, "requirecalltoken")) {
12759             /* default is required unless in optional ip list */
12760             if (ast_false(v->value)) {
12761                user->calltoken_required = CALLTOKEN_NO;
12762             } else if (!strcasecmp(v->value, "auto")) {
12763                user->calltoken_required = CALLTOKEN_AUTO;
12764             } else if (ast_true(v->value)) {
12765                user->calltoken_required = CALLTOKEN_YES;
12766             } else {
12767                ast_log(LOG_WARNING, "requirecalltoken must be set to a valid value. at line %d\n", v->lineno);
12768             }
12769          } /* else if (strcasecmp(v->name,"type")) */
12770          /* ast_log(LOG_WARNING, "Ignoring %s\n", v->name); */
12771          v = v->next;
12772          if (!v) {
12773             v = alt;
12774             alt = NULL;
12775          }
12776       }
12777       if (!user->authmethods) {
12778          if (!ast_strlen_zero(user->secret)) {
12779             user->authmethods = IAX_AUTH_MD5 | IAX_AUTH_PLAINTEXT;
12780             if (!ast_strlen_zero(user->inkeys))
12781                user->authmethods |= IAX_AUTH_RSA;
12782          } else if (!ast_strlen_zero(user->inkeys)) {
12783             user->authmethods = IAX_AUTH_RSA;
12784          } else {
12785             user->authmethods = IAX_AUTH_MD5 | IAX_AUTH_PLAINTEXT;
12786          }
12787       }
12788       ast_clear_flag64(user, IAX_DELME);
12789    }
12790 cleanup:
12791    if (oldha)
12792       ast_free_ha(oldha);
12793    if (oldcon)
12794       free_context(oldcon);
12795    return user;
12796 }
12797 
12798 static int peer_delme_cb(void *obj, void *arg, int flags)
12799 {
12800    struct iax2_peer *peer = obj;
12801 
12802    ast_set_flag64(peer, IAX_DELME);
12803 
12804    return 0;
12805 }
12806 
12807 static int user_delme_cb(void *obj, void *arg, int flags)
12808 {
12809    struct iax2_user *user = obj;
12810 
12811    ast_set_flag64(user, IAX_DELME);
12812 
12813    return 0;
12814 }
12815 
12816 static void delete_users(void)
12817 {
12818    struct iax2_registry *reg;
12819 
12820    ao2_callback(users, 0, user_delme_cb, NULL);
12821 
12822    AST_LIST_LOCK(&registrations);
12823    while ((reg = AST_LIST_REMOVE_HEAD(&registrations, entry))) {
12824       if (sched) {
12825          ast_sched_thread_del(sched, reg->expire);
12826       }
12827       if (reg->callno) {
12828          int callno = reg->callno;
12829          ast_mutex_lock(&iaxsl[callno]);
12830          if (iaxs[callno]) {
12831             iaxs[callno]->reg = NULL;
12832             iax2_destroy(callno);
12833          }
12834          ast_mutex_unlock(&iaxsl[callno]);
12835       }
12836       if (reg->dnsmgr)
12837          ast_dnsmgr_release(reg->dnsmgr);
12838       ast_free(reg);
12839    }
12840    AST_LIST_UNLOCK(&registrations);
12841 
12842    ao2_callback(peers, 0, peer_delme_cb, NULL);
12843 }
12844 
12845 static void prune_users(void)
12846 {
12847    struct iax2_user *user;
12848    struct ao2_iterator i;
12849 
12850    i = ao2_iterator_init(users, 0);
12851    while ((user = ao2_iterator_next(&i))) {
12852       if (ast_test_flag64(user, IAX_DELME) || ast_test_flag64(user, IAX_RTCACHEFRIENDS)) {
12853          ao2_unlink(users, user);
12854       }
12855       user_unref(user);
12856    }
12857    ao2_iterator_destroy(&i);
12858 }
12859 
12860 /* Prune peers who still are supposed to be deleted */
12861 static void prune_peers(void)
12862 {
12863    struct iax2_peer *peer;
12864    struct ao2_iterator i;
12865 
12866    i = ao2_iterator_init(peers, 0);
12867    while ((peer = ao2_iterator_next(&i))) {
12868       if (ast_test_flag64(peer, IAX_DELME) || ast_test_flag64(peer, IAX_RTCACHEFRIENDS)) {
12869          unlink_peer(peer);
12870       }
12871       peer_unref(peer);
12872    }
12873    ao2_iterator_destroy(&i);
12874 }
12875 
12876 static void set_config_destroy(void)
12877 {
12878    strcpy(accountcode, "");
12879    strcpy(language, "");
12880    strcpy(mohinterpret, "default");
12881    strcpy(mohsuggest, "");
12882    trunkmaxsize = MAX_TRUNKDATA;
12883    amaflags = 0;
12884    delayreject = 0;
12885    ast_clear_flag64((&globalflags), IAX_NOTRANSFER | IAX_TRANSFERMEDIA | IAX_USEJITTERBUF |
12886       IAX_FORCEJITTERBUF | IAX_SENDCONNECTEDLINE | IAX_RECVCONNECTEDLINE);
12887    delete_users();
12888    ao2_callback(callno_limits, OBJ_NODATA, addr_range_delme_cb, NULL);
12889    ao2_callback(calltoken_ignores, OBJ_NODATA, addr_range_delme_cb, NULL);
12890 }
12891 
12892 /*! \brief Load configuration */
12893 static int set_config(const char *config_file, int reload)
12894 {
12895    struct ast_config *cfg, *ucfg;
12896    format_t capability = iax2_capability;
12897    struct ast_variable *v;
12898    char *cat;
12899    const char *utype;
12900    const char *tosval;
12901    int format;
12902    int portno = IAX_DEFAULT_PORTNO;
12903    int  x;
12904    int mtuv;
12905    int subscribe_network_change = 1;
12906    struct iax2_user *user;
12907    struct iax2_peer *peer;
12908    struct ast_netsock *ns;
12909    struct ast_flags config_flags = { reload ? CONFIG_FLAG_FILEUNCHANGED : 0 };
12910 #if 0
12911    static unsigned short int last_port=0;
12912 #endif
12913 
12914    cfg = ast_config_load(config_file, config_flags);
12915 
12916    if (!cfg) {
12917       ast_log(LOG_ERROR, "Unable to load config %s\n", config_file);
12918       return -1;
12919    } else if (cfg == CONFIG_STATUS_FILEUNCHANGED) {
12920       ucfg = ast_config_load("users.conf", config_flags);
12921       if (ucfg == CONFIG_STATUS_FILEUNCHANGED)
12922          return 0;
12923       /* Otherwise we need to reread both files */
12924       ast_clear_flag(&config_flags, CONFIG_FLAG_FILEUNCHANGED);
12925       if ((cfg = ast_config_load(config_file, config_flags)) == CONFIG_STATUS_FILEINVALID) {
12926          ast_log(LOG_ERROR, "Config file %s is in an invalid format.  Aborting.\n", config_file);
12927          ast_config_destroy(ucfg);
12928          return 0;
12929       }
12930    } else if (cfg == CONFIG_STATUS_FILEINVALID) {
12931       ast_log(LOG_ERROR, "Config file %s is in an invalid format.  Aborting.\n", config_file);
12932       return 0;
12933    } else { /* iax.conf changed, gotta reread users.conf, too */
12934       ast_clear_flag(&config_flags, CONFIG_FLAG_FILEUNCHANGED);
12935       if ((ucfg = ast_config_load("users.conf", config_flags)) == CONFIG_STATUS_FILEINVALID) {
12936          ast_log(LOG_ERROR, "Config file users.conf is in an invalid format.  Aborting.\n");
12937          ast_config_destroy(cfg);
12938          return 0;
12939       }
12940    }
12941 
12942    if (reload) {
12943       set_config_destroy();
12944    }
12945 
12946    /* Reset global codec prefs */
12947    memset(&prefs, 0 , sizeof(struct ast_codec_pref));
12948 
12949    /* Reset Global Flags */
12950    memset(&globalflags, 0, sizeof(globalflags));
12951    ast_set_flag64(&globalflags, IAX_RTUPDATE);
12952    ast_set_flag64((&globalflags), IAX_SHRINKCALLERID);
12953 
12954 #ifdef SO_NO_CHECK
12955    nochecksums = 0;
12956 #endif
12957    /* Reset default parking lot */
12958    default_parkinglot[0] = '\0';
12959 
12960    min_reg_expire = IAX_DEFAULT_REG_EXPIRE;
12961    max_reg_expire = IAX_DEFAULT_REG_EXPIRE;
12962    global_max_trunk_mtu = MAX_TRUNK_MTU;
12963    global_maxcallno = DEFAULT_MAXCALLNO_LIMIT;
12964    global_maxcallno_nonval = DEFAULT_MAXCALLNO_LIMIT_NONVAL;
12965 
12966    maxauthreq = 3;
12967 
12968    srvlookup = 0;
12969 
12970    v = ast_variable_browse(cfg, "general");
12971 
12972    /* Seed initial tos value */
12973    tosval = ast_variable_retrieve(cfg, "general", "tos");
12974    if (tosval) {
12975       if (ast_str2tos(tosval, &qos.tos))
12976          ast_log(LOG_WARNING, "Invalid tos value, refer to QoS documentation\n");
12977    }
12978    /* Seed initial cos value */
12979    tosval = ast_variable_retrieve(cfg, "general", "cos");
12980    if (tosval) {
12981       if (ast_str2cos(tosval, &qos.cos))
12982          ast_log(LOG_WARNING, "Invalid cos value, refer to QoS documentation\n");
12983    }
12984    while(v) {
12985       if (!strcasecmp(v->name, "bindport")){ 
12986          if (reload)
12987             ast_log(LOG_NOTICE, "Ignoring bindport on reload\n");
12988          else
12989             portno = atoi(v->value);
12990       } else if (!strcasecmp(v->name, "pingtime")) 
12991          ping_time = atoi(v->value);
12992       else if (!strcasecmp(v->name, "iaxthreadcount")) {
12993          if (reload) {
12994             if (atoi(v->value) != iaxthreadcount)
12995                ast_log(LOG_NOTICE, "Ignoring any changes to iaxthreadcount during reload\n");
12996          } else {
12997             iaxthreadcount = atoi(v->value);
12998             if (iaxthreadcount < 1) {
12999                ast_log(LOG_NOTICE, "iaxthreadcount must be at least 1.\n");
13000                iaxthreadcount = 1;
13001             } else if (iaxthreadcount > 256) {
13002                ast_log(LOG_NOTICE, "limiting iaxthreadcount to 256\n");
13003                iaxthreadcount = 256;
13004             }
13005          }
13006       } else if (!strcasecmp(v->name, "iaxmaxthreadcount")) {
13007          if (reload) {
13008             AST_LIST_LOCK(&dynamic_list);
13009             iaxmaxthreadcount = atoi(v->value);
13010             AST_LIST_UNLOCK(&dynamic_list);
13011          } else {
13012             iaxmaxthreadcount = atoi(v->value);
13013             if (iaxmaxthreadcount < 0) {
13014                ast_log(LOG_NOTICE, "iaxmaxthreadcount must be at least 0.\n");
13015                iaxmaxthreadcount = 0;
13016             } else if (iaxmaxthreadcount > 256) {
13017                ast_log(LOG_NOTICE, "Limiting iaxmaxthreadcount to 256\n");
13018                iaxmaxthreadcount = 256;
13019             }
13020          }
13021       } else if (!strcasecmp(v->name, "nochecksums")) {
13022 #ifdef SO_NO_CHECK
13023          if (ast_true(v->value))
13024             nochecksums = 1;
13025          else
13026             nochecksums = 0;
13027 #else
13028          if (ast_true(v->value))
13029             ast_log(LOG_WARNING, "Disabling RTP checksums is not supported on this operating system!\n");
13030 #endif
13031       }
13032       else if (!strcasecmp(v->name, "maxjitterbuffer")) 
13033          maxjitterbuffer = atoi(v->value);
13034       else if (!strcasecmp(v->name, "resyncthreshold")) 
13035          resyncthreshold = atoi(v->value);
13036       else if (!strcasecmp(v->name, "maxjitterinterps")) 
13037          maxjitterinterps = atoi(v->value);
13038       else if (!strcasecmp(v->name, "jittertargetextra"))
13039          jittertargetextra = atoi(v->value);
13040       else if (!strcasecmp(v->name, "lagrqtime")) 
13041          lagrq_time = atoi(v->value);
13042       else if (!strcasecmp(v->name, "maxregexpire")) 
13043          max_reg_expire = atoi(v->value);
13044       else if (!strcasecmp(v->name, "minregexpire")) 
13045          min_reg_expire = atoi(v->value);
13046       else if (!strcasecmp(v->name, "bindaddr")) {
13047          if (reload) {
13048             ast_log(LOG_NOTICE, "Ignoring bindaddr on reload\n");
13049          } else {
13050             if (!(ns = ast_netsock_bind(netsock, io, v->value, portno, qos.tos, qos.cos, socket_read, NULL))) {
13051                ast_log(LOG_WARNING, "Unable apply binding to '%s' at line %d\n", v->value, v->lineno);
13052             } else {
13053                   if (strchr(v->value, ':'))
13054                   ast_verb(2, "Binding IAX2 to '%s'\n", v->value);
13055                   else
13056                   ast_verb(2, "Binding IAX2 to '%s:%d'\n", v->value, portno);
13057                if (defaultsockfd < 0) 
13058                   defaultsockfd = ast_netsock_sockfd(ns);
13059                ast_netsock_unref(ns);
13060             }
13061          }
13062       } else if (!strcasecmp(v->name, "authdebug")) {
13063          authdebug = ast_true(v->value);
13064       } else if (!strcasecmp(v->name, "encryption")) {
13065             iax2_encryption |= get_encrypt_methods(v->value);
13066             if (!iax2_encryption) {
13067                ast_clear_flag64((&globalflags), IAX_FORCE_ENCRYPT);
13068             }
13069       } else if (!strcasecmp(v->name, "forceencryption")) {
13070          if (ast_false(v->value)) {
13071             ast_clear_flag64((&globalflags), IAX_FORCE_ENCRYPT);
13072          } else {
13073             iax2_encryption |= get_encrypt_methods(v->value);
13074             if (iax2_encryption) {
13075                ast_set_flag64((&globalflags), IAX_FORCE_ENCRYPT);
13076             }
13077          }
13078       } else if (!strcasecmp(v->name, "transfer")) {
13079          if (!strcasecmp(v->value, "mediaonly")) {
13080             ast_set_flags_to64((&globalflags), IAX_NOTRANSFER|IAX_TRANSFERMEDIA, IAX_TRANSFERMEDIA);
13081          } else if (ast_true(v->value)) {
13082             ast_set_flags_to64((&globalflags), IAX_NOTRANSFER|IAX_TRANSFERMEDIA, 0);
13083          } else
13084             ast_set_flags_to64((&globalflags), IAX_NOTRANSFER|IAX_TRANSFERMEDIA, IAX_NOTRANSFER);
13085       } else if (!strcasecmp(v->name, "codecpriority")) {
13086          if(!strcasecmp(v->value, "caller"))
13087             ast_set_flag64((&globalflags), IAX_CODEC_USER_FIRST);
13088          else if(!strcasecmp(v->value, "disabled"))
13089             ast_set_flag64((&globalflags), IAX_CODEC_NOPREFS);
13090          else if(!strcasecmp(v->value, "reqonly")) {
13091             ast_set_flag64((&globalflags), IAX_CODEC_NOCAP);
13092             ast_set_flag64((&globalflags), IAX_CODEC_NOPREFS);
13093          }
13094       } else if (!strcasecmp(v->name, "jitterbuffer"))
13095          ast_set2_flag64((&globalflags), ast_true(v->value), IAX_USEJITTERBUF);
13096       else if (!strcasecmp(v->name, "forcejitterbuffer"))
13097          ast_set2_flag64((&globalflags), ast_true(v->value), IAX_FORCEJITTERBUF);
13098       else if (!strcasecmp(v->name, "delayreject"))
13099          delayreject = ast_true(v->value);
13100       else if (!strcasecmp(v->name, "allowfwdownload"))
13101          ast_set2_flag64((&globalflags), ast_true(v->value), IAX_ALLOWFWDOWNLOAD);
13102       else if (!strcasecmp(v->name, "rtcachefriends"))
13103          ast_set2_flag64((&globalflags), ast_true(v->value), IAX_RTCACHEFRIENDS);
13104       else if (!strcasecmp(v->name, "rtignoreregexpire"))
13105          ast_set2_flag64((&globalflags), ast_true(v->value), IAX_RTIGNOREREGEXPIRE);
13106       else if (!strcasecmp(v->name, "rtupdate"))
13107          ast_set2_flag64((&globalflags), ast_true(v->value), IAX_RTUPDATE);
13108       else if (!strcasecmp(v->name, "rtsavesysname"))
13109          ast_set2_flag64((&globalflags), ast_true(v->value), IAX_RTSAVE_SYSNAME);
13110       else if (!strcasecmp(v->name, "trunktimestamps"))
13111          ast_set2_flag64(&globalflags, ast_true(v->value), IAX_TRUNKTIMESTAMPS);
13112       else if (!strcasecmp(v->name, "rtautoclear")) {
13113          int i = atoi(v->value);
13114          if(i > 0)
13115             global_rtautoclear = i;
13116          else
13117             i = 0;
13118          ast_set2_flag64((&globalflags), i || ast_true(v->value), IAX_RTAUTOCLEAR);
13119       } else if (!strcasecmp(v->name, "trunkfreq")) {
13120          trunkfreq = atoi(v->value);
13121          if (trunkfreq < 10)
13122             trunkfreq = 10;
13123       } else if (!strcasecmp(v->name, "trunkmtu")) {
13124          mtuv = atoi(v->value);
13125          if (mtuv  == 0 )
13126             global_max_trunk_mtu = 0;
13127          else if (mtuv >= 172 && mtuv < 4000)
13128             global_max_trunk_mtu = mtuv;
13129          else
13130             ast_log(LOG_NOTICE, "trunkmtu value out of bounds (%d) at line %d\n",
13131                mtuv, v->lineno);
13132       } else if (!strcasecmp(v->name, "trunkmaxsize")) {
13133          trunkmaxsize = atoi(v->value);
13134          if (trunkmaxsize == 0)
13135             trunkmaxsize = MAX_TRUNKDATA;
13136       } else if (!strcasecmp(v->name, "autokill")) {
13137          if (sscanf(v->value, "%30d", &x) == 1) {
13138             if (x >= 0)
13139                autokill = x;
13140             else
13141                ast_log(LOG_NOTICE, "Nice try, but autokill has to be >0 or 'yes' or 'no' at line %d\n", v->lineno);
13142          } else if (ast_true(v->value)) {
13143             autokill = DEFAULT_MAXMS;
13144          } else {
13145             autokill = 0;
13146          }
13147       } else if (!strcasecmp(v->name, "bandwidth")) {
13148          if (!strcasecmp(v->value, "low")) {
13149             capability = IAX_CAPABILITY_LOWBANDWIDTH;
13150          } else if (!strcasecmp(v->value, "medium")) {
13151             capability = IAX_CAPABILITY_MEDBANDWIDTH;
13152          } else if (!strcasecmp(v->value, "high")) {
13153             capability = IAX_CAPABILITY_FULLBANDWIDTH;
13154          } else
13155             ast_log(LOG_WARNING, "bandwidth must be either low, medium, or high\n");
13156       } else if (!strcasecmp(v->name, "allow")) {
13157          ast_parse_allow_disallow(&prefs, &capability, v->value, 1);
13158       } else if (!strcasecmp(v->name, "disallow")) {
13159          ast_parse_allow_disallow(&prefs, &capability, v->value, 0);
13160       } else if (!strcasecmp(v->name, "register")) {
13161          iax2_register(v->value, v->lineno);
13162       } else if (!strcasecmp(v->name, "iaxcompat")) {
13163          iaxcompat = ast_true(v->value);
13164       } else if (!strcasecmp(v->name, "regcontext")) {
13165          ast_copy_string(regcontext, v->value, sizeof(regcontext));
13166          /* Create context if it doesn't exist already */
13167          ast_context_find_or_create(NULL, NULL, regcontext, "IAX2");
13168       } else if (!strcasecmp(v->name, "tos")) {
13169          if (ast_str2tos(v->value, &qos.tos))
13170             ast_log(LOG_WARNING, "Invalid tos value at line %d, refer to QoS documentation\n", v->lineno);
13171       } else if (!strcasecmp(v->name, "cos")) {
13172          if (ast_str2cos(v->value, &qos.cos))
13173             ast_log(LOG_WARNING, "Invalid cos value at line %d, refer to QoS documentation\n", v->lineno);
13174       } else if (!strcasecmp(v->name, "parkinglot")) {
13175          ast_copy_string(default_parkinglot, v->value, sizeof(default_parkinglot));
13176       } else if (!strcasecmp(v->name, "accountcode")) {
13177          ast_copy_string(accountcode, v->value, sizeof(accountcode));
13178       } else if (!strcasecmp(v->name, "mohinterpret")) {
13179          ast_copy_string(mohinterpret, v->value, sizeof(mohinterpret));
13180       } else if (!strcasecmp(v->name, "mohsuggest")) {
13181          ast_copy_string(mohsuggest, v->value, sizeof(mohsuggest));
13182       } else if (!strcasecmp(v->name, "amaflags")) {
13183          format = ast_cdr_amaflags2int(v->value);
13184          if (format < 0) {
13185             ast_log(LOG_WARNING, "Invalid AMA Flags: %s at line %d\n", v->value, v->lineno);
13186          } else {
13187             amaflags = format;
13188          }
13189       } else if (!strcasecmp(v->name, "language")) {
13190          ast_copy_string(language, v->value, sizeof(language));
13191       } else if (!strcasecmp(v->name, "maxauthreq")) {
13192          maxauthreq = atoi(v->value);
13193          if (maxauthreq < 0)
13194             maxauthreq = 0;
13195       } else if (!strcasecmp(v->name, "adsi")) {
13196          adsi = ast_true(v->value);
13197       } else if (!strcasecmp(v->name, "srvlookup")) {
13198          srvlookup = ast_true(v->value);
13199       } else if (!strcasecmp(v->name, "connectedline")) {
13200          if (ast_true(v->value)) {
13201             ast_set_flag64((&globalflags), IAX_SENDCONNECTEDLINE | IAX_RECVCONNECTEDLINE);
13202          } else if (!strcasecmp(v->value, "send")) {
13203             ast_clear_flag64((&globalflags), IAX_RECVCONNECTEDLINE);
13204             ast_set_flag64((&globalflags), IAX_SENDCONNECTEDLINE);
13205          } else if (!strcasecmp(v->value, "receive")) {
13206             ast_clear_flag64((&globalflags), IAX_SENDCONNECTEDLINE);
13207             ast_set_flag64((&globalflags), IAX_RECVCONNECTEDLINE);
13208          } else {
13209             ast_clear_flag64((&globalflags), IAX_SENDCONNECTEDLINE | IAX_RECVCONNECTEDLINE);
13210          }
13211       } else if (!strcasecmp(v->name, "maxcallnumbers")) {
13212          if (sscanf(v->value, "%10hu", &global_maxcallno) != 1) {
13213             ast_log(LOG_WARNING, "maxcallnumbers must be set to a valid number.  %s is not valid at line %d\n", v->value, v->lineno);
13214          }
13215       } else if (!strcasecmp(v->name, "maxcallnumbers_nonvalidated")) {
13216          if (sscanf(v->value, "%10hu", &global_maxcallno_nonval) != 1) {
13217             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);
13218          }
13219       } else if (!strcasecmp(v->name, "calltokenoptional")) {
13220          if (add_calltoken_ignore(v->value)) {
13221             ast_log(LOG_WARNING, "Invalid calltokenoptional address range - '%s' line %d\n", v->value, v->lineno);
13222          }
13223       } else if (!strcasecmp(v->name, "subscribe_network_change_event")) {
13224          if (ast_true(v->value)) {
13225             subscribe_network_change = 1;
13226          } else if (ast_false(v->value)) {
13227             subscribe_network_change = 0;
13228          } else {
13229             ast_log(LOG_WARNING, "subscribe_network_change_event value %s is not valid at line %d.\n", v->value, v->lineno);
13230          }
13231       } else if (!strcasecmp(v->name, "shrinkcallerid")) {
13232          if (ast_true(v->value)) {
13233             ast_set_flag64((&globalflags), IAX_SHRINKCALLERID);
13234          } else if (ast_false(v->value)) {
13235             ast_clear_flag64((&globalflags), IAX_SHRINKCALLERID);
13236          } else {
13237             ast_log(LOG_WARNING, "shrinkcallerid value %s is not valid at line %d.\n", v->value, v->lineno);
13238          }
13239       }/*else if (strcasecmp(v->name,"type")) */
13240       /* ast_log(LOG_WARNING, "Ignoring %s\n", v->name); */
13241       v = v->next;
13242    }
13243 
13244    if (subscribe_network_change) {
13245       network_change_event_subscribe();
13246    } else {
13247       network_change_event_unsubscribe();
13248    }
13249 
13250    if (defaultsockfd < 0) {
13251       if (!(ns = ast_netsock_bind(netsock, io, "0.0.0.0", portno, qos.tos, qos.cos, socket_read, NULL))) {
13252          ast_log(LOG_ERROR, "Unable to create network socket: %s\n", strerror(errno));
13253       } else {
13254          ast_verb(2, "Binding IAX2 to default address 0.0.0.0:%d\n", portno);
13255          defaultsockfd = ast_netsock_sockfd(ns);
13256          ast_netsock_unref(ns);
13257       }
13258    }
13259    if (reload) {
13260       ast_netsock_release(outsock);
13261       outsock = ast_netsock_list_alloc();
13262       if (!outsock) {
13263          ast_log(LOG_ERROR, "Could not allocate outsock list.\n");
13264          return -1;
13265       }
13266       ast_netsock_init(outsock);
13267    }
13268 
13269    if (min_reg_expire > max_reg_expire) {
13270       ast_log(LOG_WARNING, "Minimum registration interval of %d is more than maximum of %d, resetting minimum to %d\n",
13271          min_reg_expire, max_reg_expire, max_reg_expire);
13272       min_reg_expire = max_reg_expire;
13273    }
13274    iax2_capability = capability;
13275    
13276    if (ucfg) {
13277       struct ast_variable *gen;
13278       int genhasiax;
13279       int genregisteriax;
13280       const char *hasiax, *registeriax;
13281       
13282       genhasiax = ast_true(ast_variable_retrieve(ucfg, "general", "hasiax"));
13283       genregisteriax = ast_true(ast_variable_retrieve(ucfg, "general", "registeriax"));
13284       gen = ast_variable_browse(ucfg, "general");
13285       cat = ast_category_browse(ucfg, NULL);
13286       while (cat) {
13287          if (strcasecmp(cat, "general")) {
13288             hasiax = ast_variable_retrieve(ucfg, cat, "hasiax");
13289             registeriax = ast_variable_retrieve(ucfg, cat, "registeriax");
13290             if (ast_true(hasiax) || (!hasiax && genhasiax)) {
13291                /* Start with general parameters, then specific parameters, user and peer */
13292                user = build_user(cat, gen, ast_variable_browse(ucfg, cat), 0);
13293                if (user) {
13294                   ao2_link(users, user);
13295                   user = user_unref(user);
13296                }
13297                peer = build_peer(cat, gen, ast_variable_browse(ucfg, cat), 0);
13298                if (peer) {
13299                   if (ast_test_flag64(peer, IAX_DYNAMIC))
13300                      reg_source_db(peer);
13301                   ao2_link(peers, peer);
13302                   peer = peer_unref(peer);
13303                }
13304             }
13305             if (ast_true(registeriax) || (!registeriax && genregisteriax)) {
13306                char tmp[256];
13307                const char *host = ast_variable_retrieve(ucfg, cat, "host");
13308                const char *username = ast_variable_retrieve(ucfg, cat, "username");
13309                const char *secret = ast_variable_retrieve(ucfg, cat, "secret");
13310                if (!host)
13311                   host = ast_variable_retrieve(ucfg, "general", "host");
13312                if (!username)
13313                   username = ast_variable_retrieve(ucfg, "general", "username");
13314                if (!secret)
13315                   secret = ast_variable_retrieve(ucfg, "general", "secret");
13316                if (!ast_strlen_zero(username) && !ast_strlen_zero(host)) {
13317                   if (!ast_strlen_zero(secret))
13318                      snprintf(tmp, sizeof(tmp), "%s:%s@%s", username, secret, host);
13319                   else
13320                      snprintf(tmp, sizeof(tmp), "%s@%s", username, host);
13321                   iax2_register(tmp, 0);
13322                }
13323             }
13324          }
13325          cat = ast_category_browse(ucfg, cat);
13326       }
13327       ast_config_destroy(ucfg);
13328    }
13329    
13330    cat = ast_category_browse(cfg, NULL);
13331    while(cat) {
13332       if (strcasecmp(cat, "general")) {
13333          utype = ast_variable_retrieve(cfg, cat, "type");
13334          if (!strcasecmp(cat, "callnumberlimits")) {
13335             build_callno_limits(ast_variable_browse(cfg, cat));
13336          } else if (utype) {
13337             if (!strcasecmp(utype, "user") || !strcasecmp(utype, "friend")) {
13338                user = build_user(cat, ast_variable_browse(cfg, cat), NULL, 0);
13339                if (user) {
13340                   ao2_link(users, user);
13341                   user = user_unref(user);
13342                }
13343             }
13344             if (!strcasecmp(utype, "peer") || !strcasecmp(utype, "friend")) {
13345                peer = build_peer(cat, ast_variable_browse(cfg, cat), NULL, 0);
13346                if (peer) {
13347                   if (ast_test_flag64(peer, IAX_DYNAMIC))
13348                      reg_source_db(peer);
13349                   ao2_link(peers, peer);
13350                   peer = peer_unref(peer);
13351                }
13352             } else if (strcasecmp(utype, "user")) {
13353                ast_log(LOG_WARNING, "Unknown type '%s' for '%s' in %s\n", utype, cat, config_file);
13354             }
13355          } else
13356             ast_log(LOG_WARNING, "Section '%s' lacks type\n", cat);
13357       }
13358       cat = ast_category_browse(cfg, cat);
13359    }
13360    ast_config_destroy(cfg);
13361    return 1;
13362 }
13363 
13364 static void poke_all_peers(void)
13365 {
13366    struct ao2_iterator i;
13367    struct iax2_peer *peer;
13368 
13369    i = ao2_iterator_init(peers, 0);
13370    while ((peer = ao2_iterator_next(&i))) {
13371       iax2_poke_peer(peer, 0);
13372       peer_unref(peer);
13373    }
13374    ao2_iterator_destroy(&i);
13375 }
13376 static int reload_config(void)
13377 {
13378    static const char config[] = "iax.conf";
13379    struct iax2_registry *reg;
13380 
13381    if (set_config(config, 1) > 0) {
13382       prune_peers();
13383       prune_users();
13384       ao2_callback(callno_limits, OBJ_NODATA | OBJ_UNLINK | OBJ_MULTIPLE, prune_addr_range_cb, NULL);
13385       ao2_callback(calltoken_ignores, OBJ_NODATA | OBJ_UNLINK | OBJ_MULTIPLE, prune_addr_range_cb, NULL);
13386       ao2_callback(peercnts, OBJ_NODATA, set_peercnt_limit_all_cb, NULL);
13387       trunk_timed = trunk_untimed = 0; 
13388       trunk_nmaxmtu = trunk_maxmtu = 0;
13389       memset(&debugaddr, '\0', sizeof(debugaddr));
13390 
13391       AST_LIST_LOCK(&registrations);
13392       AST_LIST_TRAVERSE(&registrations, reg, entry)
13393          iax2_do_register(reg);
13394       AST_LIST_UNLOCK(&registrations);
13395 
13396       /* Qualify hosts, too */
13397       poke_all_peers();
13398    }
13399    
13400    reload_firmware(0);
13401    iax_provision_reload(1);
13402    ast_unload_realtime("iaxpeers");
13403 
13404    return 0;
13405 }
13406 
13407 static char *handle_cli_iax2_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
13408 {
13409    switch (cmd) {
13410    case CLI_INIT:
13411       e->command = "iax2 reload";
13412       e->usage =
13413          "Usage: iax2 reload\n"
13414          "       Reloads IAX configuration from iax.conf\n";
13415       return NULL;
13416    case CLI_GENERATE:
13417       return NULL;
13418    }
13419 
13420    reload_config();
13421 
13422    return CLI_SUCCESS;
13423 }
13424 
13425 static int reload(void)
13426 {
13427    return reload_config();
13428 }
13429 
13430 static int cache_get_callno_locked(const char *data)
13431 {
13432    struct sockaddr_in sin;
13433    int x;
13434    int callno;
13435    struct iax_ie_data ied;
13436    struct create_addr_info cai;
13437    struct parsed_dial_string pds;
13438    char *tmpstr;
13439 
13440    for (x = 0; x < ARRAY_LEN(iaxs); x++) {
13441       /* Look for an *exact match* call.  Once a call is negotiated, it can only
13442          look up entries for a single context */
13443       if (!ast_mutex_trylock(&iaxsl[x])) {
13444          if (iaxs[x] && !strcasecmp(data, iaxs[x]->dproot))
13445             return x;
13446          ast_mutex_unlock(&iaxsl[x]);
13447       }
13448    }
13449 
13450    /* No match found, we need to create a new one */
13451 
13452    memset(&cai, 0, sizeof(cai));
13453    memset(&ied, 0, sizeof(ied));
13454    memset(&pds, 0, sizeof(pds));
13455 
13456    tmpstr = ast_strdupa(data);
13457    parse_dial_string(tmpstr, &pds);
13458 
13459    if (ast_strlen_zero(pds.peer)) {
13460       ast_log(LOG_WARNING, "No peer provided in the IAX2 dial string '%s'\n", data);
13461       return -1;
13462    }
13463 
13464    /* Populate our address from the given */
13465    if (create_addr(pds.peer, NULL, &sin, &cai))
13466       return -1;
13467 
13468    ast_debug(1, "peer: %s, username: %s, password: %s, context: %s\n",
13469       pds.peer, pds.username, pds.password, pds.context);
13470 
13471    callno = find_callno_locked(0, 0, &sin, NEW_FORCE, cai.sockfd, 0);
13472    if (callno < 1) {
13473       ast_log(LOG_WARNING, "Unable to create call\n");
13474       return -1;
13475    }
13476 
13477    ast_string_field_set(iaxs[callno], dproot, data);
13478    iaxs[callno]->capability = IAX_CAPABILITY_FULLBANDWIDTH;
13479 
13480    iax_ie_append_short(&ied, IAX_IE_VERSION, IAX_PROTO_VERSION);
13481    iax_ie_append_str(&ied, IAX_IE_CALLED_NUMBER, "TBD");
13482    /* the string format is slightly different from a standard dial string,
13483       because the context appears in the 'exten' position
13484    */
13485    if (pds.exten)
13486       iax_ie_append_str(&ied, IAX_IE_CALLED_CONTEXT, pds.exten);
13487    if (pds.username)
13488       iax_ie_append_str(&ied, IAX_IE_USERNAME, pds.username);
13489    iax_ie_append_int(&ied, IAX_IE_FORMAT, IAX_CAPABILITY_FULLBANDWIDTH);
13490    iax_ie_append_int(&ied, IAX_IE_CAPABILITY, IAX_CAPABILITY_FULLBANDWIDTH);
13491    /* Keep password handy */
13492    if (pds.password)
13493       ast_string_field_set(iaxs[callno], secret, pds.password);
13494    if (pds.key)
13495       ast_string_field_set(iaxs[callno], outkey, pds.key);
13496    /* Start the call going */
13497    add_empty_calltoken_ie(iaxs[callno], &ied); /* this _MUST_ be the last ie added */
13498    send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_NEW, 0, ied.buf, ied.pos, -1);
13499 
13500    return callno;
13501 }
13502 
13503 static struct iax2_dpcache *find_cache(struct ast_channel *chan, const char *data, const char *context, const char *exten, int priority)
13504 {
13505    struct iax2_dpcache *dp = NULL;
13506    struct timeval now = ast_tvnow();
13507    int x, com[2], timeout, old = 0, outfd, doabort, callno;
13508    struct ast_channel *c = NULL;
13509    struct ast_frame *f = NULL;
13510 
13511    AST_LIST_TRAVERSE_SAFE_BEGIN(&dpcache, dp, cache_list) {
13512       if (ast_tvcmp(now, dp->expiry) > 0) {
13513          AST_LIST_REMOVE_CURRENT(cache_list);
13514          if ((dp->flags & CACHE_FLAG_PENDING) || dp->callno)
13515             ast_log(LOG_WARNING, "DP still has peer field or pending or callno (flags = %d, peer = blah, callno = %d)\n", dp->flags, dp->callno);
13516          else
13517             ast_free(dp);
13518          continue;
13519       }
13520       if (!strcmp(dp->peercontext, data) && !strcmp(dp->exten, exten))
13521          break;
13522    }
13523    AST_LIST_TRAVERSE_SAFE_END;
13524 
13525    if (!dp) {
13526       /* No matching entry.  Create a new one. */
13527       /* First, can we make a callno? */
13528       if ((callno = cache_get_callno_locked(data)) < 0) {
13529          ast_log(LOG_WARNING, "Unable to generate call for '%s'\n", data);
13530          return NULL;
13531       }
13532       if (!(dp = ast_calloc(1, sizeof(*dp)))) {
13533          ast_mutex_unlock(&iaxsl[callno]);
13534          return NULL;
13535       }
13536       ast_copy_string(dp->peercontext, data, sizeof(dp->peercontext));
13537       ast_copy_string(dp->exten, exten, sizeof(dp->exten));
13538       dp->expiry = ast_tvnow();
13539       dp->orig = dp->expiry;
13540       /* Expires in 30 mins by default */
13541       dp->expiry.tv_sec += iaxdefaultdpcache;
13542       dp->flags = CACHE_FLAG_PENDING;
13543       for (x = 0; x < ARRAY_LEN(dp->waiters); x++)
13544          dp->waiters[x] = -1;
13545       /* Insert into the lists */
13546       AST_LIST_INSERT_TAIL(&dpcache, dp, cache_list);
13547       AST_LIST_INSERT_TAIL(&iaxs[callno]->dpentries, dp, peer_list);
13548       /* Send the request if we're already up */
13549       if (ast_test_flag(&iaxs[callno]->state, IAX_STATE_STARTED))
13550          iax2_dprequest(dp, callno);
13551       ast_mutex_unlock(&iaxsl[callno]);
13552    }
13553 
13554    /* By here we must have a dp */
13555    if (dp->flags & CACHE_FLAG_PENDING) {
13556       /* Okay, here it starts to get nasty.  We need a pipe now to wait
13557          for a reply to come back so long as it's pending */
13558       for (x = 0; x < ARRAY_LEN(dp->waiters); x++) {
13559          /* Find an empty slot */
13560          if (dp->waiters[x] < 0)
13561             break;
13562       }
13563       if (x >= ARRAY_LEN(dp->waiters)) {
13564          ast_log(LOG_WARNING, "No more waiter positions available\n");
13565          return NULL;
13566       }
13567       if (pipe(com)) {
13568          ast_log(LOG_WARNING, "Unable to create pipe for comm\n");
13569          return NULL;
13570       }
13571       dp->waiters[x] = com[1];
13572       /* Okay, now we wait */
13573       timeout = iaxdefaulttimeout * 1000;
13574       /* Temporarily unlock */
13575       AST_LIST_UNLOCK(&dpcache);
13576       /* Defer any dtmf */
13577       if (chan)
13578          old = ast_channel_defer_dtmf(chan);
13579       doabort = 0;
13580       while(timeout) {
13581          c = ast_waitfor_nandfds(&chan, chan ? 1 : 0, &com[0], 1, NULL, &outfd, &timeout);
13582          if (outfd > -1)
13583             break;
13584          if (!c)
13585             continue;
13586          if (!(f = ast_read(c))) {
13587             doabort = 1;
13588             break;
13589          }
13590          ast_frfree(f);
13591       }
13592       if (!timeout) {
13593          ast_log(LOG_WARNING, "Timeout waiting for %s exten %s\n", data, exten);
13594       }
13595       AST_LIST_LOCK(&dpcache);
13596       dp->waiters[x] = -1;
13597       close(com[1]);
13598       close(com[0]);
13599       if (doabort) {
13600          /* Don't interpret anything, just abort.  Not sure what th epoint
13601            of undeferring dtmf on a hung up channel is but hey whatever */
13602          if (!old && chan)
13603             ast_channel_undefer_dtmf(chan);
13604          return NULL;
13605       }
13606       if (!(dp->flags & CACHE_FLAG_TIMEOUT)) {
13607          /* Now to do non-independent analysis the results of our wait */
13608          if (dp->flags & CACHE_FLAG_PENDING) {
13609             /* Still pending... It's a timeout.  Wake everybody up.  Consider it no longer
13610                pending.  Don't let it take as long to timeout. */
13611             dp->flags &= ~CACHE_FLAG_PENDING;
13612             dp->flags |= CACHE_FLAG_TIMEOUT;
13613             /* Expire after only 60 seconds now.  This is designed to help reduce backlog in heavily loaded
13614                systems without leaving it unavailable once the server comes back online */
13615             dp->expiry.tv_sec = dp->orig.tv_sec + 60;
13616             for (x = 0; x < ARRAY_LEN(dp->waiters); x++) {
13617                if (dp->waiters[x] > -1) {
13618                   if (write(dp->waiters[x], "asdf", 4) < 0) {
13619                      ast_log(LOG_WARNING, "write() failed: %s\n", strerror(errno));
13620                   }
13621                }
13622             }
13623          }
13624       }
13625       /* Our caller will obtain the rest */
13626       if (!old && chan)
13627          ast_channel_undefer_dtmf(chan);
13628    }
13629    return dp;  
13630 }
13631 
13632 /*! \brief Part of the IAX2 switch interface */
13633 static int iax2_exists(struct ast_channel *chan, const char *context, const char *exten, int priority, const char *callerid, const char *data)
13634 {
13635    int res = 0;
13636    struct iax2_dpcache *dp = NULL;
13637 #if 0
13638    ast_log(LOG_NOTICE, "iax2_exists: con: %s, exten: %s, pri: %d, cid: %s, data: %s\n", context, exten, priority, callerid ? callerid : "<unknown>", data);
13639 #endif
13640    if ((priority != 1) && (priority != 2))
13641       return 0;
13642 
13643    AST_LIST_LOCK(&dpcache);
13644    if ((dp = find_cache(chan, data, context, exten, priority))) {
13645       if (dp->flags & CACHE_FLAG_EXISTS)
13646          res = 1;
13647    } else {
13648       ast_log(LOG_WARNING, "Unable to make DP cache\n");
13649    }
13650    AST_LIST_UNLOCK(&dpcache);
13651 
13652    return res;
13653 }
13654 
13655 /*! \brief part of the IAX2 dial plan switch interface */
13656 static int iax2_canmatch(struct ast_channel *chan, const char *context, const char *exten, int priority, const char *callerid, const char *data)
13657 {
13658    int res = 0;
13659    struct iax2_dpcache *dp = NULL;
13660 #if 0
13661    ast_log(LOG_NOTICE, "iax2_canmatch: con: %s, exten: %s, pri: %d, cid: %s, data: %s\n", context, exten, priority, callerid ? callerid : "<unknown>", data);
13662 #endif
13663    if ((priority != 1) && (priority != 2))
13664       return 0;
13665 
13666    AST_LIST_LOCK(&dpcache);
13667    if ((dp = find_cache(chan, data, context, exten, priority))) {
13668       if (dp->flags & CACHE_FLAG_CANEXIST)
13669          res = 1;
13670    } else {
13671       ast_log(LOG_WARNING, "Unable to make DP cache\n");
13672    }
13673    AST_LIST_UNLOCK(&dpcache);
13674 
13675    return res;
13676 }
13677 
13678 /*! \brief Part of the IAX2 Switch interface */
13679 static int iax2_matchmore(struct ast_channel *chan, const char *context, const char *exten, int priority, const char *callerid, const char *data)
13680 {
13681    int res = 0;
13682    struct iax2_dpcache *dp = NULL;
13683 #if 0
13684    ast_log(LOG_NOTICE, "iax2_matchmore: con: %s, exten: %s, pri: %d, cid: %s, data: %s\n", context, exten, priority, callerid ? callerid : "<unknown>", data);
13685 #endif
13686    if ((priority != 1) && (priority != 2))
13687       return 0;
13688 
13689    AST_LIST_LOCK(&dpcache);
13690    if ((dp = find_cache(chan, data, context, exten, priority))) {
13691       if (dp->flags & CACHE_FLAG_MATCHMORE)
13692          res = 1;
13693    } else {
13694       ast_log(LOG_WARNING, "Unable to make DP cache\n");
13695    }
13696    AST_LIST_UNLOCK(&dpcache);
13697 
13698    return res;
13699 }
13700 
13701 /*! \brief Execute IAX2 dialplan switch */
13702 static int iax2_exec(struct ast_channel *chan, const char *context, const char *exten, int priority, const char *callerid, const char *data)
13703 {
13704    char odata[256];
13705    char req[256];
13706    char *ncontext;
13707    struct iax2_dpcache *dp = NULL;
13708    struct ast_app *dial = NULL;
13709 #if 0
13710    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);
13711 #endif
13712    if (priority == 2) {
13713       /* Indicate status, can be overridden in dialplan */
13714       const char *dialstatus = pbx_builtin_getvar_helper(chan, "DIALSTATUS");
13715       if (dialstatus) {
13716          dial = pbx_findapp(dialstatus);
13717          if (dial) 
13718             pbx_exec(chan, dial, "");
13719       }
13720       return -1;
13721    } else if (priority != 1)
13722       return -1;
13723 
13724    AST_LIST_LOCK(&dpcache);
13725    if ((dp = find_cache(chan, data, context, exten, priority))) {
13726       if (dp->flags & CACHE_FLAG_EXISTS) {
13727          ast_copy_string(odata, data, sizeof(odata));
13728          ncontext = strchr(odata, '/');
13729          if (ncontext) {
13730             *ncontext = '\0';
13731             ncontext++;
13732             snprintf(req, sizeof(req), "IAX2/%s/%s@%s", odata, exten, ncontext);
13733          } else {
13734             snprintf(req, sizeof(req), "IAX2/%s/%s", odata, exten);
13735          }
13736          ast_verb(3, "Executing Dial('%s')\n", req);
13737       } else {
13738          AST_LIST_UNLOCK(&dpcache);
13739          ast_log(LOG_WARNING, "Can't execute nonexistent extension '%s[@%s]' in data '%s'\n", exten, context, data);
13740          return -1;
13741       }
13742    }
13743    AST_LIST_UNLOCK(&dpcache);
13744 
13745    if ((dial = pbx_findapp("Dial")))
13746       return pbx_exec(chan, dial, req);
13747    else
13748       ast_log(LOG_WARNING, "No dial application registered\n");
13749 
13750    return -1;
13751 }
13752 
13753 static int function_iaxpeer(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
13754 {
13755    struct iax2_peer *peer;
13756    char *peername, *colname;
13757 
13758    peername = ast_strdupa(data);
13759 
13760    /* if our channel, return the IP address of the endpoint of current channel */
13761    if (!strcmp(peername,"CURRENTCHANNEL")) {
13762            unsigned short callno;
13763       if (chan->tech != &iax2_tech)
13764          return -1;
13765       callno = PTR_TO_CALLNO(chan->tech_pvt);   
13766       ast_copy_string(buf, iaxs[callno]->addr.sin_addr.s_addr ? ast_inet_ntoa(iaxs[callno]->addr.sin_addr) : "", len);
13767       return 0;
13768    }
13769 
13770    if ((colname = strchr(peername, ',')))
13771       *colname++ = '\0';
13772    else
13773       colname = "ip";
13774 
13775    if (!(peer = find_peer(peername, 1)))
13776       return -1;
13777 
13778    if (!strcasecmp(colname, "ip")) {
13779       ast_copy_string(buf, ast_sockaddr_stringify_addr(&peer->addr), len);
13780    } else  if (!strcasecmp(colname, "status")) {
13781       peer_status(peer, buf, len); 
13782    } else  if (!strcasecmp(colname, "mailbox")) {
13783       ast_copy_string(buf, peer->mailbox, len);
13784    } else  if (!strcasecmp(colname, "context")) {
13785       ast_copy_string(buf, peer->context, len);
13786    } else  if (!strcasecmp(colname, "expire")) {
13787       snprintf(buf, len, "%d", peer->expire);
13788    } else  if (!strcasecmp(colname, "dynamic")) {
13789       ast_copy_string(buf, (ast_test_flag64(peer, IAX_DYNAMIC) ? "yes" : "no"), len);
13790    } else  if (!strcasecmp(colname, "callerid_name")) {
13791       ast_copy_string(buf, peer->cid_name, len);
13792    } else  if (!strcasecmp(colname, "callerid_num")) {
13793       ast_copy_string(buf, peer->cid_num, len);
13794    } else  if (!strcasecmp(colname, "codecs")) {
13795       ast_getformatname_multiple(buf, len -1, peer->capability);
13796    } else  if (!strncasecmp(colname, "codec[", 6)) {
13797       char *codecnum, *ptr;
13798       int codec = 0;
13799       
13800       codecnum = strchr(colname, '[');
13801       *codecnum = '\0';
13802       codecnum++;
13803       if ((ptr = strchr(codecnum, ']'))) {
13804          *ptr = '\0';
13805       }
13806       if((codec = ast_codec_pref_index(&peer->prefs, atoi(codecnum)))) {
13807          ast_copy_string(buf, ast_getformatname(codec), len);
13808       } else {
13809          buf[0] = '\0';
13810       }
13811    } else {
13812       buf[0] = '\0';
13813    }
13814 
13815    peer_unref(peer);
13816 
13817    return 0;
13818 }
13819 
13820 static struct ast_custom_function iaxpeer_function = {
13821    .name = "IAXPEER",
13822    .read = function_iaxpeer,
13823 };
13824 
13825 static int acf_channel_read(struct ast_channel *chan, const char *funcname, char *args, char *buf, size_t buflen)
13826 {
13827    struct chan_iax2_pvt *pvt;
13828    unsigned int callno;
13829    int res = 0;
13830 
13831    if (!chan || chan->tech != &iax2_tech) {
13832       ast_log(LOG_ERROR, "This function requires a valid IAX2 channel\n");
13833       return -1;
13834    }
13835 
13836    callno = PTR_TO_CALLNO(chan->tech_pvt);
13837    ast_mutex_lock(&iaxsl[callno]);
13838    if (!(pvt = iaxs[callno])) {
13839       ast_mutex_unlock(&iaxsl[callno]);
13840       return -1;
13841    }
13842 
13843    if (!strcasecmp(args, "osptoken")) {
13844       ast_copy_string(buf, pvt->osptoken, buflen);
13845    } else if (!strcasecmp(args, "peerip")) {
13846       ast_copy_string(buf, pvt->addr.sin_addr.s_addr ? ast_inet_ntoa(pvt->addr.sin_addr) : "", buflen);
13847    } else if (!strcasecmp(args, "peername")) {
13848       ast_copy_string(buf, pvt->username, buflen);
13849    } else if (!strcasecmp(args, "secure_signaling") || !strcasecmp(args, "secure_media")) {
13850       snprintf(buf, buflen, "%s", IAX_CALLENCRYPTED(pvt) ? "1" : "");
13851    } else {
13852       res = -1;
13853    }
13854 
13855    ast_mutex_unlock(&iaxsl[callno]);
13856 
13857    return res;
13858 }
13859 
13860 /*! \brief Part of the device state notification system ---*/
13861 static int iax2_devicestate(void *data) 
13862 {
13863    struct parsed_dial_string pds;
13864    char *tmp = ast_strdupa(data);
13865    struct iax2_peer *p;
13866    int res = AST_DEVICE_INVALID;
13867 
13868    memset(&pds, 0, sizeof(pds));
13869    parse_dial_string(tmp, &pds);
13870 
13871    if (ast_strlen_zero(pds.peer)) {
13872       ast_log(LOG_WARNING, "No peer provided in the IAX2 dial string '%s'\n", (char *) data);
13873       return res;
13874    }
13875    
13876    ast_debug(3, "Checking device state for device %s\n", pds.peer);
13877 
13878    /* SLD: FIXME: second call to find_peer during registration */
13879    if (!(p = find_peer(pds.peer, 1)))
13880       return res;
13881 
13882    res = AST_DEVICE_UNAVAILABLE;
13883    ast_debug(3, "iax2_devicestate: Found peer. What's device state of %s? addr=%d, defaddr=%d maxms=%d, lastms=%d\n",
13884       pds.peer, ast_sockaddr_ipv4(&p->addr), p->defaddr.sin_addr.s_addr, p->maxms, p->lastms);
13885    
13886    if ((ast_sockaddr_ipv4(&p->addr) || p->defaddr.sin_addr.s_addr) &&
13887        (!p->maxms || ((p->lastms > -1) && (p->historicms <= p->maxms)))) {
13888       /* Peer is registered, or have default IP address
13889          and a valid registration */
13890       if (p->historicms == 0 || p->historicms <= p->maxms)
13891          /* let the core figure out whether it is in use or not */
13892          res = AST_DEVICE_UNKNOWN;  
13893    }
13894 
13895    peer_unref(p);
13896 
13897    return res;
13898 }
13899 
13900 static struct ast_switch iax2_switch = 
13901 {
13902    name:        "IAX2",
13903    description: "IAX Remote Dialplan Switch",
13904    exists:      iax2_exists,
13905    canmatch:    iax2_canmatch,
13906    exec:        iax2_exec,
13907    matchmore:   iax2_matchmore,
13908 };
13909 
13910 /*
13911    { { "iax2", "show", "cache", NULL },
13912    iax2_show_cache, "Display IAX cached dialplan",
13913    show_cache_usage },
13914 
13915    { { "iax2", "show", "channels", NULL },
13916    iax2_show_channels, "List active IAX channels",
13917    show_channels_usage },
13918 
13919    { { "iax2", "show", "firmware", NULL },
13920    iax2_show_firmware, "List available IAX firmwares",
13921    show_firmware_usage },
13922 
13923    { { "iax2", "show", "netstats", NULL },
13924    iax2_show_netstats, "List active IAX channel netstats",
13925    show_netstats_usage },
13926 
13927    { { "iax2", "show", "peers", NULL },
13928    iax2_show_peers, "List defined IAX peers",
13929    show_peers_usage },
13930 
13931    { { "iax2", "show", "registry", NULL },
13932    iax2_show_registry, "Display IAX registration status",
13933    show_reg_usage },
13934 
13935    { { "iax2", "show", "stats", NULL },
13936    iax2_show_stats, "Display IAX statistics",
13937    show_stats_usage },
13938 
13939    { { "iax2", "show", "threads", NULL },
13940    iax2_show_threads, "Display IAX helper thread info",
13941    show_threads_usage },
13942 
13943    { { "iax2", "unregister", NULL },
13944    iax2_unregister, "Unregister (force expiration) an IAX2 peer from the registry",
13945    unregister_usage, complete_iax2_unregister },
13946 
13947    { { "iax2", "set", "mtu", NULL },
13948    iax2_set_mtu, "Set the IAX systemwide trunking MTU",
13949    set_mtu_usage, NULL, NULL },
13950 
13951    { { "iax2", "show", "users", NULL },
13952    iax2_show_users, "List defined IAX users",
13953    show_users_usage },
13954 
13955    { { "iax2", "prune", "realtime", NULL },
13956    iax2_prune_realtime, "Prune a cached realtime lookup",
13957    prune_realtime_usage, complete_iax2_show_peer },
13958 
13959    { { "iax2", "reload", NULL },
13960    iax2_reload, "Reload IAX configuration",
13961    iax2_reload_usage },
13962 
13963    { { "iax2", "show", "peer", NULL },
13964    iax2_show_peer, "Show details on specific IAX peer",
13965    show_peer_usage, complete_iax2_show_peer },
13966 
13967    { { "iax2", "set", "debug", NULL },
13968    iax2_do_debug, "Enable IAX debugging",
13969    debug_usage },
13970 
13971    { { "iax2", "set", "debug", "trunk", NULL },
13972    iax2_do_trunk_debug, "Enable IAX trunk debugging",
13973    debug_trunk_usage },
13974 
13975    { { "iax2", "set", "debug", "jb", NULL },
13976    iax2_do_jb_debug, "Enable IAX jitterbuffer debugging",
13977    debug_jb_usage },
13978 
13979    { { "iax2", "set", "debug", "off", NULL },
13980    iax2_no_debug, "Disable IAX debugging",
13981    no_debug_usage },
13982 
13983    { { "iax2", "set", "debug", "trunk", "off", NULL },
13984    iax2_no_trunk_debug, "Disable IAX trunk debugging",
13985    no_debug_trunk_usage },
13986 
13987    { { "iax2", "set", "debug", "jb", "off", NULL },
13988    iax2_no_jb_debug, "Disable IAX jitterbuffer debugging",
13989    no_debug_jb_usage },
13990 
13991    { { "iax2", "test", "losspct", NULL },
13992    iax2_test_losspct, "Set IAX2 incoming frame loss percentage",
13993    iax2_test_losspct_usage },
13994 
13995    { { "iax2", "provision", NULL },
13996    iax2_prov_cmd, "Provision an IAX device",
13997    show_prov_usage, iax2_prov_complete_template_3rd },
13998 
13999 #ifdef IAXTESTS
14000    { { "iax2", "test", "late", NULL },
14001    iax2_test_late, "Test the receipt of a late frame",
14002    iax2_test_late_usage },
14003 
14004    { { "iax2", "test", "resync", NULL },
14005    iax2_test_resync, "Test a resync in received timestamps",
14006    iax2_test_resync_usage },
14007 
14008    { { "iax2", "test", "jitter", NULL },
14009    iax2_test_jitter, "Simulates jitter for testing",
14010    iax2_test_jitter_usage },
14011 #endif
14012 */
14013 
14014 static struct ast_cli_entry cli_iax2[] = {
14015    AST_CLI_DEFINE(handle_cli_iax2_provision,           "Provision an IAX device"),
14016    AST_CLI_DEFINE(handle_cli_iax2_prune_realtime,      "Prune a cached realtime lookup"),
14017    AST_CLI_DEFINE(handle_cli_iax2_reload,              "Reload IAX configuration"),
14018    AST_CLI_DEFINE(handle_cli_iax2_set_mtu,             "Set the IAX systemwide trunking MTU"),
14019    AST_CLI_DEFINE(handle_cli_iax2_set_debug,           "Enable/Disable IAX debugging"),
14020    AST_CLI_DEFINE(handle_cli_iax2_set_debug_trunk,     "Enable/Disable IAX trunk debugging"),
14021    AST_CLI_DEFINE(handle_cli_iax2_set_debug_jb,        "Enable/Disable IAX jitterbuffer debugging"),
14022    AST_CLI_DEFINE(handle_cli_iax2_show_cache,          "Display IAX cached dialplan"),
14023    AST_CLI_DEFINE(handle_cli_iax2_show_channels,       "List active IAX channels"),
14024    AST_CLI_DEFINE(handle_cli_iax2_show_firmware,       "List available IAX firmware"),
14025    AST_CLI_DEFINE(handle_cli_iax2_show_netstats,       "List active IAX channel netstats"),
14026    AST_CLI_DEFINE(handle_cli_iax2_show_peer,           "Show details on specific IAX peer"),
14027    AST_CLI_DEFINE(handle_cli_iax2_show_peers,          "List defined IAX peers"),
14028    AST_CLI_DEFINE(handle_cli_iax2_show_registry,       "Display IAX registration status"),
14029    AST_CLI_DEFINE(handle_cli_iax2_show_stats,          "Display IAX statistics"),
14030    AST_CLI_DEFINE(handle_cli_iax2_show_threads,        "Display IAX helper thread info"),
14031    AST_CLI_DEFINE(handle_cli_iax2_show_users,          "List defined IAX users"),
14032    AST_CLI_DEFINE(handle_cli_iax2_test_losspct,        "Set IAX2 incoming frame loss percentage"),
14033    AST_CLI_DEFINE(handle_cli_iax2_unregister,          "Unregister (force expiration) an IAX2 peer from the registry"),
14034    AST_CLI_DEFINE(handle_cli_iax2_show_callno_limits,  "Show current entries in IP call number limit table"),
14035 #ifdef IAXTESTS
14036    AST_CLI_DEFINE(handle_cli_iax2_test_jitter,         "Simulates jitter for testing"),
14037    AST_CLI_DEFINE(handle_cli_iax2_test_late,           "Test the receipt of a late frame"),
14038    AST_CLI_DEFINE(handle_cli_iax2_test_resync,         "Test a resync in received timestamps"),
14039 #endif /* IAXTESTS */
14040 };
14041 
14042 #ifdef TEST_FRAMEWORK
14043 AST_TEST_DEFINE(test_iax2_peers_get)
14044 {
14045    struct ast_data_query query = {
14046       .path = "/asterisk/channel/iax2/peers",
14047       .search = "peers/peer/name=test_peer_data_provider"
14048    };
14049    struct ast_data *node;
14050    struct iax2_peer *peer;
14051 
14052    switch (cmd) {
14053       case TEST_INIT:
14054          info->name = "iax2_peers_get_data_test";
14055          info->category = "/main/data/iax2/peers/";
14056          info->summary = "IAX2 peers data providers unit test";
14057          info->description =
14058             "Tests whether the IAX2 peers data provider implementation works as expected.";
14059          return AST_TEST_NOT_RUN;
14060       case TEST_EXECUTE:
14061          break;
14062    }
14063 
14064    /* build a test peer */
14065    peer = build_peer("test_peer_data_provider", NULL, NULL, 0);
14066    if (!peer) {
14067       return AST_TEST_FAIL;
14068    }
14069    peer->expiry= 1010;
14070    ao2_link(peers, peer);
14071 
14072    node = ast_data_get(&query);
14073    if (!node) {
14074       ao2_unlink(peers, peer);
14075       peer_unref(peer);
14076       return AST_TEST_FAIL;
14077    }
14078 
14079    /* check returned data node. */
14080    if (strcmp(ast_data_retrieve_string(node, "peer/name"), "test_peer_data_provider")) {
14081       ao2_unlink(peers, peer);
14082       peer_unref(peer);
14083       ast_data_free(node);
14084       return AST_TEST_FAIL;
14085    }
14086 
14087    if (ast_data_retrieve_int(node, "peer/expiry") != 1010) {
14088       ao2_unlink(peers, peer);
14089       peer_unref(peer);
14090       ast_data_free(node);
14091       return AST_TEST_FAIL;
14092    }
14093 
14094    /* release resources */
14095    ast_data_free(node);
14096 
14097    ao2_unlink(peers, peer);
14098    peer_unref(peer);
14099 
14100    return AST_TEST_PASS;
14101 }
14102 
14103 AST_TEST_DEFINE(test_iax2_users_get)
14104 {
14105    struct ast_data_query query = {
14106       .path = "/asterisk/channel/iax2/users",
14107       .search = "users/user/name=test_user_data_provider"
14108    };
14109    struct ast_data *node;
14110    struct iax2_user *user;
14111 
14112    switch (cmd) {
14113       case TEST_INIT:
14114          info->name = "iax2_users_get_data_test";
14115          info->category = "/main/data/iax2/users/";
14116          info->summary = "IAX2 users data providers unit test";
14117          info->description =
14118             "Tests whether the IAX2 users data provider implementation works as expected.";
14119          return AST_TEST_NOT_RUN;
14120       case TEST_EXECUTE:
14121          break;
14122    }
14123 
14124    user = build_user("test_user_data_provider", NULL, NULL, 0);
14125    if (!user) {
14126       ast_test_status_update(test, "Failed to build a test user\n");
14127       return AST_TEST_FAIL;
14128    }
14129    user->amaflags = 1010;
14130    ao2_link(users, user);
14131 
14132    node = ast_data_get(&query);
14133    if (!node) {
14134       ast_test_status_update(test, "The data query to find our test user failed\n");
14135       ao2_unlink(users, user);
14136       user_unref(user);
14137       return AST_TEST_FAIL;
14138    }
14139 
14140    if (strcmp(ast_data_retrieve_string(node, "user/name"), "test_user_data_provider")) {
14141       ast_test_status_update(test, "Our data results did not return the test user created in the previous step.\n");
14142       ao2_unlink(users, user);
14143       user_unref(user);
14144       ast_data_free(node);
14145       return AST_TEST_FAIL;
14146    }
14147 
14148    if (ast_data_retrieve_int(node, "user/amaflags/value") != 1010) {
14149       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"));
14150       ao2_unlink(users, user);
14151       user_unref(user);
14152       ast_data_free(node);
14153       return AST_TEST_FAIL;
14154    }
14155 
14156    ast_data_free(node);
14157 
14158    ao2_unlink(users, user);
14159    user_unref(user);
14160 
14161    return AST_TEST_PASS;
14162 }
14163 #endif
14164 
14165 static void cleanup_thread_list(void *head)
14166 {
14167    AST_LIST_HEAD(iax2_thread_list, iax2_thread);
14168    struct iax2_thread_list *list_head = head;
14169    struct iax2_thread *thread;
14170 
14171    AST_LIST_LOCK(list_head);
14172    while ((thread = AST_LIST_REMOVE_HEAD(&idle_list, list))) {
14173       pthread_t thread_id = thread->threadid;
14174 
14175       thread->stop = 1;
14176       signal_condition(&thread->lock, &thread->cond);
14177 
14178       AST_LIST_UNLOCK(list_head);
14179       pthread_join(thread_id, NULL);
14180       AST_LIST_LOCK(list_head);
14181    }
14182    AST_LIST_UNLOCK(list_head);
14183 }
14184 
14185 static int __unload_module(void)
14186 {
14187    struct ast_context *con;
14188    int x;
14189 
14190    network_change_event_unsubscribe();
14191 
14192    ast_manager_unregister("IAXpeers");
14193    ast_manager_unregister("IAXpeerlist");
14194    ast_manager_unregister("IAXnetstats");
14195    ast_manager_unregister("IAXregistry");
14196    ast_unregister_application(papp);
14197    ast_cli_unregister_multiple(cli_iax2, ARRAY_LEN(cli_iax2));
14198    ast_unregister_switch(&iax2_switch);
14199    ast_channel_unregister(&iax2_tech);
14200 
14201    if (netthreadid != AST_PTHREADT_NULL) {
14202       pthread_cancel(netthreadid);
14203       pthread_kill(netthreadid, SIGURG);
14204       pthread_join(netthreadid, NULL);
14205    }
14206 
14207    for (x = 0; x < ARRAY_LEN(iaxs); x++) {
14208       if (iaxs[x]) {
14209          iax2_destroy(x);
14210       }
14211    }
14212 
14213    /* Call for all threads to halt */
14214    cleanup_thread_list(&idle_list);
14215    cleanup_thread_list(&active_list);
14216    cleanup_thread_list(&dynamic_list);
14217 
14218    sched = ast_sched_thread_destroy(sched);
14219 
14220    ast_netsock_release(netsock);
14221    ast_netsock_release(outsock);
14222    for (x = 0; x < ARRAY_LEN(iaxs); x++) {
14223       if (iaxs[x]) {
14224          iax2_destroy(x);
14225       }
14226    }
14227    ast_manager_unregister( "IAXpeers" );
14228    ast_manager_unregister( "IAXpeerlist" );
14229    ast_manager_unregister( "IAXnetstats" );
14230    ast_manager_unregister( "IAXregistry" );
14231    ast_unregister_application(papp);
14232 #ifdef TEST_FRAMEWORK
14233    AST_TEST_UNREGISTER(test_iax2_peers_get);
14234    AST_TEST_UNREGISTER(test_iax2_users_get);
14235 #endif
14236    ast_data_unregister(NULL);
14237    ast_cli_unregister_multiple(cli_iax2, ARRAY_LEN(cli_iax2));
14238    ast_unregister_switch(&iax2_switch);
14239    ast_channel_unregister(&iax2_tech);
14240    delete_users();
14241    iax_provision_unload();
14242    reload_firmware(1);
14243 
14244    for (x = 0; x < ARRAY_LEN(iaxsl); x++) {
14245       ast_mutex_destroy(&iaxsl[x]);
14246    }
14247 
14248    ao2_ref(peers, -1);
14249    ao2_ref(users, -1);
14250    ao2_ref(iax_peercallno_pvts, -1);
14251    ao2_ref(iax_transfercallno_pvts, -1);
14252    ao2_ref(peercnts, -1);
14253    ao2_ref(callno_limits, -1);
14254    ao2_ref(calltoken_ignores, -1);
14255    ao2_ref(callno_pool, -1);
14256    ao2_ref(callno_pool_trunk, -1);
14257    if (timer) {
14258       ast_timer_close(timer);
14259    }
14260    transmit_processor = ast_taskprocessor_unreference(transmit_processor);
14261 
14262    con = ast_context_find(regcontext);
14263    if (con)
14264       ast_context_destroy(con, "IAX2");
14265    ast_unload_realtime("iaxpeers");
14266    return 0;
14267 }
14268 
14269 static int unload_module(void)
14270 {
14271    ast_custom_function_unregister(&iaxpeer_function);
14272    ast_custom_function_unregister(&iaxvar_function);
14273    return __unload_module();
14274 }
14275 
14276 static int peer_set_sock_cb(void *obj, void *arg, int flags)
14277 {
14278    struct iax2_peer *peer = obj;
14279 
14280    if (peer->sockfd < 0)
14281       peer->sockfd = defaultsockfd;
14282 
14283    return 0;
14284 }
14285 
14286 static int pvt_hash_cb(const void *obj, const int flags)
14287 {
14288    const struct chan_iax2_pvt *pvt = obj;
14289 
14290    return pvt->peercallno;
14291 }
14292 
14293 static int pvt_cmp_cb(void *obj, void *arg, int flags)
14294 {
14295    struct chan_iax2_pvt *pvt = obj, *pvt2 = arg;
14296 
14297    /* The frames_received field is used to hold whether we're matching
14298     * against a full frame or not ... */
14299 
14300    return match(&pvt2->addr, pvt2->peercallno, pvt2->callno, pvt, 
14301       pvt2->frames_received) ? CMP_MATCH | CMP_STOP : 0;
14302 }
14303 
14304 static int transfercallno_pvt_hash_cb(const void *obj, const int flags)
14305 {
14306    const struct chan_iax2_pvt *pvt = obj;
14307 
14308    return pvt->transfercallno;
14309 }
14310 
14311 static int transfercallno_pvt_cmp_cb(void *obj, void *arg, int flags)
14312 {
14313    struct chan_iax2_pvt *pvt = obj, *pvt2 = arg;
14314 
14315    /* The frames_received field is used to hold whether we're matching
14316     * against a full frame or not ... */
14317 
14318    return match(&pvt2->transfer, pvt2->transfercallno, pvt2->callno, pvt,
14319       pvt2->frames_received) ? CMP_MATCH | CMP_STOP : 0;
14320 }
14321 
14322 static int load_objects(void)
14323 {
14324    peers = users = iax_peercallno_pvts = iax_transfercallno_pvts = NULL;
14325    peercnts = callno_limits = calltoken_ignores = callno_pool = callno_pool_trunk = NULL;
14326 
14327    if (!(peers = ao2_container_alloc(MAX_PEER_BUCKETS, peer_hash_cb, peer_cmp_cb))) {
14328       goto container_fail;
14329    } else if (!(users = ao2_container_alloc(MAX_USER_BUCKETS, user_hash_cb, user_cmp_cb))) {
14330       goto container_fail;
14331    } else if (!(iax_peercallno_pvts = ao2_container_alloc(IAX_MAX_CALLS, pvt_hash_cb, pvt_cmp_cb))) {
14332       goto container_fail;
14333    } else if (!(iax_transfercallno_pvts = ao2_container_alloc(IAX_MAX_CALLS, transfercallno_pvt_hash_cb, transfercallno_pvt_cmp_cb))) {
14334       goto container_fail;
14335    } else if (!(peercnts = ao2_container_alloc(MAX_PEER_BUCKETS, peercnt_hash_cb, peercnt_cmp_cb))) {
14336       goto container_fail;
14337    } else if (!(callno_limits = ao2_container_alloc(MAX_PEER_BUCKETS, addr_range_hash_cb, addr_range_cmp_cb))) {
14338       goto container_fail;
14339    } else if (!(calltoken_ignores = ao2_container_alloc(MAX_PEER_BUCKETS, addr_range_hash_cb, addr_range_cmp_cb))) {
14340       goto container_fail;
14341    } else if (create_callno_pools()) {
14342       goto container_fail;
14343    } else if  (!(transmit_processor = ast_taskprocessor_get("iax2_transmit", TPS_REF_DEFAULT))) {
14344       goto container_fail;
14345    }
14346 
14347    return 0;
14348 
14349 container_fail:
14350    if (peers) {
14351       ao2_ref(peers, -1);
14352    }
14353    if (users) {
14354       ao2_ref(users, -1);
14355    }
14356    if (iax_peercallno_pvts) {
14357       ao2_ref(iax_peercallno_pvts, -1);
14358    }
14359    if (iax_transfercallno_pvts) {
14360       ao2_ref(iax_transfercallno_pvts, -1);
14361    }
14362    if (peercnts) {
14363       ao2_ref(peercnts, -1);
14364    }
14365    if (callno_limits) {
14366       ao2_ref(callno_limits, -1);
14367    }
14368    if (calltoken_ignores) {
14369       ao2_ref(calltoken_ignores, -1);
14370    }
14371    if (callno_pool) {
14372       ao2_ref(callno_pool, -1);
14373    }
14374    if (callno_pool_trunk) {
14375       ao2_ref(callno_pool_trunk, -1);
14376    }
14377    return AST_MODULE_LOAD_FAILURE;
14378 }
14379 
14380 
14381 #define DATA_EXPORT_IAX2_PEER(MEMBER)           \
14382    MEMBER(iax2_peer, name, AST_DATA_STRING)     \
14383    MEMBER(iax2_peer, username, AST_DATA_STRING)    \
14384    MEMBER(iax2_peer, secret, AST_DATA_PASSWORD)    \
14385    MEMBER(iax2_peer, dbsecret, AST_DATA_PASSWORD)     \
14386    MEMBER(iax2_peer, outkey, AST_DATA_STRING)      \
14387    MEMBER(iax2_peer, regexten, AST_DATA_STRING)    \
14388    MEMBER(iax2_peer, context, AST_DATA_STRING)     \
14389    MEMBER(iax2_peer, peercontext, AST_DATA_STRING)    \
14390    MEMBER(iax2_peer, mailbox, AST_DATA_STRING)     \
14391    MEMBER(iax2_peer, mohinterpret, AST_DATA_STRING)   \
14392    MEMBER(iax2_peer, mohsuggest, AST_DATA_STRING)     \
14393    MEMBER(iax2_peer, inkeys, AST_DATA_STRING)      \
14394    MEMBER(iax2_peer, cid_num, AST_DATA_STRING)     \
14395    MEMBER(iax2_peer, cid_name, AST_DATA_STRING)    \
14396    MEMBER(iax2_peer, zonetag, AST_DATA_STRING)     \
14397    MEMBER(iax2_peer, parkinglot, AST_DATA_STRING)     \
14398    MEMBER(iax2_peer, expiry, AST_DATA_SECONDS)     \
14399    MEMBER(iax2_peer, callno, AST_DATA_INTEGER)     \
14400    MEMBER(iax2_peer, lastms, AST_DATA_MILLISECONDS)   \
14401    MEMBER(iax2_peer, maxms, AST_DATA_MILLISECONDS)    \
14402    MEMBER(iax2_peer, pokefreqok, AST_DATA_MILLISECONDS)  \
14403    MEMBER(iax2_peer, pokefreqnotok, AST_DATA_MILLISECONDS)  \
14404    MEMBER(iax2_peer, historicms, AST_DATA_INTEGER)    \
14405    MEMBER(iax2_peer, smoothing, AST_DATA_BOOLEAN)     \
14406         MEMBER(iax2_peer, maxcallno, AST_DATA_INTEGER)
14407 
14408 AST_DATA_STRUCTURE(iax2_peer, DATA_EXPORT_IAX2_PEER);
14409 
14410 static int peers_data_provider_get(const struct ast_data_search *search,
14411    struct ast_data *data_root)
14412 {
14413    struct ast_data *data_peer;
14414    struct iax2_peer *peer;
14415    struct ao2_iterator i;
14416    char status[20];
14417    struct ast_str *encmethods = ast_str_alloca(256);
14418 
14419    i = ao2_iterator_init(peers, 0);
14420    while ((peer = ao2_iterator_next(&i))) {
14421       data_peer = ast_data_add_node(data_root, "peer");
14422       if (!data_peer) {
14423          peer_unref(peer);
14424          continue;
14425       }
14426 
14427       ast_data_add_structure(iax2_peer, data_peer, peer);
14428 
14429       ast_data_add_codecs(data_peer, "codecs", peer->capability);
14430 
14431       peer_status(peer, status, sizeof(status));
14432       ast_data_add_str(data_peer, "status", status);
14433 
14434       ast_data_add_str(data_peer, "host", ast_sockaddr_stringify_host(&peer->addr));
14435 
14436       ast_data_add_str(data_peer, "mask", ast_inet_ntoa(peer->mask));
14437 
14438       ast_data_add_int(data_peer, "port", ast_sockaddr_port(&peer->addr));
14439 
14440       ast_data_add_bool(data_peer, "trunk", ast_test_flag64(peer, IAX_TRUNK));
14441 
14442       ast_data_add_bool(data_peer, "dynamic", ast_test_flag64(peer, IAX_DYNAMIC));
14443 
14444       encmethods_to_str(peer->encmethods, encmethods);
14445       ast_data_add_str(data_peer, "encryption", peer->encmethods ? ast_str_buffer(encmethods) : "no");
14446 
14447       peer_unref(peer);
14448 
14449       if (!ast_data_search_match(search, data_peer)) {
14450          ast_data_remove_node(data_root, data_peer);
14451       }
14452    }
14453    ao2_iterator_destroy(&i);
14454 
14455    return 0;
14456 }
14457 
14458 #define DATA_EXPORT_IAX2_USER(MEMBER)              \
14459         MEMBER(iax2_user, name, AST_DATA_STRING)         \
14460         MEMBER(iax2_user, dbsecret, AST_DATA_PASSWORD)         \
14461         MEMBER(iax2_user, accountcode, AST_DATA_STRING)        \
14462         MEMBER(iax2_user, mohinterpret, AST_DATA_STRING)    \
14463         MEMBER(iax2_user, mohsuggest, AST_DATA_STRING)         \
14464         MEMBER(iax2_user, inkeys, AST_DATA_STRING)       \
14465         MEMBER(iax2_user, language, AST_DATA_STRING)        \
14466         MEMBER(iax2_user, cid_num, AST_DATA_STRING)         \
14467         MEMBER(iax2_user, cid_name, AST_DATA_STRING)        \
14468         MEMBER(iax2_user, parkinglot, AST_DATA_STRING)         \
14469         MEMBER(iax2_user, maxauthreq, AST_DATA_INTEGER)        \
14470         MEMBER(iax2_user, curauthreq, AST_DATA_INTEGER)
14471 
14472 AST_DATA_STRUCTURE(iax2_user, DATA_EXPORT_IAX2_USER);
14473 
14474 static int users_data_provider_get(const struct ast_data_search *search,
14475    struct ast_data *data_root)
14476 {
14477    struct ast_data *data_user, *data_authmethods, *data_enum_node;
14478    struct iax2_user *user;
14479    struct ao2_iterator i;
14480    char auth[90];
14481    char *pstr = "";
14482 
14483    i = ao2_iterator_init(users, 0);
14484    while ((user = ao2_iterator_next(&i))) {
14485       data_user = ast_data_add_node(data_root, "user");
14486       if (!data_user) {
14487          user_unref(user);
14488          continue;
14489       }
14490 
14491       ast_data_add_structure(iax2_user, data_user, user);
14492 
14493       ast_data_add_codecs(data_user, "codecs", user->capability);
14494 
14495       if (!ast_strlen_zero(user->secret)) {
14496          ast_copy_string(auth, user->secret, sizeof(auth));
14497       } else if (!ast_strlen_zero(user->inkeys)) {
14498          snprintf(auth, sizeof(auth), "Key: %s", user->inkeys);
14499       } else {
14500          ast_copy_string(auth, "no secret", sizeof(auth));
14501       }
14502       ast_data_add_password(data_user, "secret", auth);
14503 
14504       ast_data_add_str(data_user, "context", user->contexts ? user->contexts->context : DEFAULT_CONTEXT);
14505 
14506       /* authmethods */
14507       data_authmethods = ast_data_add_node(data_user, "authmethods");
14508       if (!data_authmethods) {
14509          ast_data_remove_node(data_root, data_user);
14510          continue;
14511       }
14512       ast_data_add_bool(data_authmethods, "rsa", user->authmethods & IAX_AUTH_RSA);
14513       ast_data_add_bool(data_authmethods, "md5", user->authmethods & IAX_AUTH_MD5);
14514       ast_data_add_bool(data_authmethods, "plaintext", user->authmethods & IAX_AUTH_PLAINTEXT);
14515 
14516       /* amaflags */
14517       data_enum_node = ast_data_add_node(data_user, "amaflags");
14518       if (!data_enum_node) {
14519          ast_data_remove_node(data_root, data_user);
14520          continue;
14521       }
14522       ast_data_add_int(data_enum_node, "value", user->amaflags);
14523       ast_data_add_str(data_enum_node, "text", ast_cdr_flags2str(user->amaflags));
14524 
14525       ast_data_add_bool(data_user, "access-control", user->ha ? 1 : 0);
14526 
14527       if (ast_test_flag64(user, IAX_CODEC_NOCAP)) {
14528          pstr = "REQ only";
14529       } else if (ast_test_flag64(user, IAX_CODEC_NOPREFS)) {
14530          pstr = "disabled";
14531       } else {
14532          pstr = ast_test_flag64(user, IAX_CODEC_USER_FIRST) ? "caller" : "host";
14533       }
14534       ast_data_add_str(data_user, "codec-preferences", pstr);
14535 
14536       user_unref(user);
14537 
14538       if (!ast_data_search_match(search, data_user)) {
14539          ast_data_remove_node(data_root, data_user);
14540       }
14541    }
14542    ao2_iterator_destroy(&i);
14543 
14544    return 0;
14545 }
14546 
14547 static const struct ast_data_handler peers_data_provider = {
14548    .version = AST_DATA_HANDLER_VERSION,
14549    .get = peers_data_provider_get
14550 };
14551 
14552 static const struct ast_data_handler users_data_provider = {
14553    .version = AST_DATA_HANDLER_VERSION,
14554    .get = users_data_provider_get
14555 };
14556 
14557 static const struct ast_data_entry iax2_data_providers[] = {
14558    AST_DATA_ENTRY("asterisk/channel/iax2/peers", &peers_data_provider),
14559    AST_DATA_ENTRY("asterisk/channel/iax2/users", &users_data_provider),
14560 };
14561 
14562 /*! \brief Load IAX2 module, load configuraiton ---*/
14563 static int load_module(void)
14564 {
14565    static const char config[] = "iax.conf";
14566    int x = 0;
14567    struct iax2_registry *reg = NULL;
14568 
14569    if (load_objects()) {
14570       return AST_MODULE_LOAD_FAILURE;
14571    }
14572 
14573    memset(iaxs, 0, sizeof(iaxs));
14574 
14575    for (x = 0; x < ARRAY_LEN(iaxsl); x++) {
14576       ast_mutex_init(&iaxsl[x]);
14577    }
14578 
14579    if (!(sched = ast_sched_thread_create())) {
14580       ast_log(LOG_ERROR, "Failed to create scheduler thread\n");
14581       return AST_MODULE_LOAD_FAILURE;
14582    }
14583 
14584    if (!(io = io_context_create())) {
14585       ast_log(LOG_ERROR, "Failed to create I/O context\n");
14586       sched = ast_sched_thread_destroy(sched);
14587       return AST_MODULE_LOAD_FAILURE;
14588    }
14589 
14590    if (!(netsock = ast_netsock_list_alloc())) {
14591       ast_log(LOG_ERROR, "Failed to create netsock list\n");
14592       io_context_destroy(io);
14593       sched = ast_sched_thread_destroy(sched);
14594       return AST_MODULE_LOAD_FAILURE;
14595    }
14596    ast_netsock_init(netsock);
14597    
14598    outsock = ast_netsock_list_alloc();
14599    if (!outsock) {
14600       ast_log(LOG_ERROR, "Could not allocate outsock list.\n");
14601       io_context_destroy(io);
14602       sched = ast_sched_thread_destroy(sched);
14603       return AST_MODULE_LOAD_FAILURE;
14604    }
14605    ast_netsock_init(outsock);
14606 
14607    randomcalltokendata = ast_random();
14608 
14609    iax_set_output(iax_debug_output);
14610    iax_set_error(iax_error_output);
14611    jb_setoutput(jb_error_output, jb_warning_output, NULL);
14612    
14613    if ((timer = ast_timer_open())) {
14614       ast_timer_set_rate(timer, trunkfreq);
14615    }
14616 
14617    if (set_config(config, 0) == -1) {
14618       if (timer) {
14619          ast_timer_close(timer);
14620       }
14621       return AST_MODULE_LOAD_DECLINE;
14622    }
14623 
14624 #ifdef TEST_FRAMEWORK
14625    AST_TEST_REGISTER(test_iax2_peers_get);
14626    AST_TEST_REGISTER(test_iax2_users_get);
14627 #endif
14628 
14629    /* Register AstData providers */
14630    ast_data_register_multiple(iax2_data_providers, ARRAY_LEN(iax2_data_providers));
14631    ast_cli_register_multiple(cli_iax2, ARRAY_LEN(cli_iax2));
14632 
14633    ast_register_application_xml(papp, iax2_prov_app);
14634 
14635    ast_custom_function_register(&iaxpeer_function);
14636    ast_custom_function_register(&iaxvar_function);
14637 
14638    ast_manager_register_xml("IAXpeers", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_iax2_show_peers);
14639    ast_manager_register_xml("IAXpeerlist", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_iax2_show_peer_list);
14640    ast_manager_register_xml("IAXnetstats", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_iax2_show_netstats);
14641    ast_manager_register_xml("IAXregistry", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_iax2_show_registry);
14642 
14643    if (ast_channel_register(&iax2_tech)) {
14644       ast_log(LOG_ERROR, "Unable to register channel class %s\n", "IAX2");
14645       __unload_module();
14646       return AST_MODULE_LOAD_FAILURE;
14647    }
14648 
14649    if (ast_register_switch(&iax2_switch)) {
14650       ast_log(LOG_ERROR, "Unable to register IAX switch\n");
14651    }
14652 
14653    if (start_network_thread()) {
14654       ast_log(LOG_ERROR, "Unable to start network thread\n");
14655       __unload_module();
14656       return AST_MODULE_LOAD_FAILURE;
14657    } else {
14658       ast_verb(2, "IAX Ready and Listening\n");
14659    }
14660 
14661    AST_LIST_LOCK(&registrations);
14662    AST_LIST_TRAVERSE(&registrations, reg, entry)
14663       iax2_do_register(reg);
14664    AST_LIST_UNLOCK(&registrations); 
14665    
14666    ao2_callback(peers, 0, peer_set_sock_cb, NULL);
14667    ao2_callback(peers, 0, iax2_poke_peer_cb, NULL);
14668 
14669 
14670    reload_firmware(0);
14671    iax_provision_reload(0);
14672 
14673    ast_realtime_require_field("iaxpeers", "name", RQ_CHAR, 10, "ipaddr", RQ_CHAR, 15, "port", RQ_UINTEGER2, 5, "regseconds", RQ_UINTEGER2, 6, SENTINEL);
14674 
14675    network_change_event_subscribe();
14676 
14677    return AST_MODULE_LOAD_SUCCESS;
14678 }
14679 
14680 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "Inter Asterisk eXchange (Ver 2)",
14681       .load = load_module,
14682       .unload = unload_module,
14683       .reload = reload,
14684       .load_pri = AST_MODPRI_CHANNEL_DRIVER,
14685       .nonoptreq = "res_crypto",
14686       );

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