Wed Oct 28 11:45:30 2009

Asterisk developer's documentation


chan_iax2.c

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