Thu Oct 11 06:42:02 2012

Asterisk developer's documentation


chan_iax2.c

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