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