Sat Oct 11 06:49:55 2008

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 - 2005, Digium, Inc.
00005  *
00006  * Mark Spencer <markster@digium.com>
00007  *
00008  * See http://www.asterisk.org for more information about
00009  * the Asterisk project. Please do not directly contact
00010  * any of the maintainers of this project for assistance;
00011  * the project provides a web site, mailing lists and IRC
00012  * channels for your use.
00013  *
00014  * This program is free software, distributed under the terms of
00015  * the GNU General Public License Version 2. See the LICENSE file
00016  * at the top of the source tree.
00017  */
00018 
00019 /*! \file
00020  *
00021  * \brief Implementation of Inter-Asterisk eXchange Version 2
00022  *
00023  * \par See also
00024  * \arg \ref Config_iax
00025  *
00026  * \ingroup channel_drivers
00027  */
00028 
00029 #include <stdlib.h>
00030 #include <stdio.h>
00031 #include <sys/types.h>
00032 #include <sys/mman.h>
00033 #include <dirent.h>
00034 #include <sys/socket.h>
00035 #include <netinet/in.h>
00036 #include <arpa/inet.h>
00037 #include <netinet/in_systm.h>
00038 #include <netinet/ip.h>
00039 #include <sys/time.h>
00040 #include <sys/signal.h>
00041 #include <signal.h>
00042 #include <string.h>
00043 #include <strings.h>
00044 #include <errno.h>
00045 #include <unistd.h>
00046 #include <netdb.h>
00047 #include <fcntl.h>
00048 #include <sys/stat.h>
00049 #include <regex.h>
00050 #ifdef IAX_TRUNKING
00051 #include <sys/ioctl.h>
00052 #ifdef __linux__
00053 #include <linux/zaptel.h>
00054 #else
00055 #include <zaptel.h>
00056 #endif /* __linux__ */
00057 #endif
00058 
00059 #include "asterisk.h"
00060 
00061 ASTERISK_FILE_VERSION(__FILE__, "$Revision: 133360 $")
00062 
00063 #include "asterisk/lock.h"
00064 #include "asterisk/frame.h" 
00065 #include "asterisk/channel.h"
00066 #include "asterisk/logger.h"
00067 #include "asterisk/module.h"
00068 #include "asterisk/pbx.h"
00069 #include "asterisk/sched.h"
00070 #include "asterisk/io.h"
00071 #include "asterisk/config.h"
00072 #include "asterisk/options.h"
00073 #include "asterisk/cli.h"
00074 #include "asterisk/translate.h"
00075 #include "asterisk/md5.h"
00076 #include "asterisk/cdr.h"
00077 #include "asterisk/crypto.h"
00078 #include "asterisk/acl.h"
00079 #include "asterisk/manager.h"
00080 #include "asterisk/callerid.h"
00081 #include "asterisk/app.h"
00082 #include "asterisk/astdb.h"
00083 #include "asterisk/musiconhold.h"
00084 #include "asterisk/features.h"
00085 #include "asterisk/utils.h"
00086 #include "asterisk/causes.h"
00087 #include "asterisk/localtime.h"
00088 #include "asterisk/aes.h"
00089 #include "asterisk/dnsmgr.h"
00090 #include "asterisk/devicestate.h"
00091 #include "asterisk/netsock.h"
00092 #include "asterisk/astobj2.h"
00093 
00094 #include "iax2.h"
00095 #include "iax2-parser.h"
00096 #include "iax2-provision.h"
00097 
00098 /* Define NEWJB to use the new channel independent jitterbuffer,
00099  * otherwise, use the old jitterbuffer */
00100 #define NEWJB
00101 
00102 #ifdef NEWJB
00103 #include "../jitterbuf.h"
00104 #endif
00105 
00106 #ifndef IPTOS_MINCOST
00107 #define IPTOS_MINCOST 0x02
00108 #endif
00109 
00110 #ifdef SO_NO_CHECK
00111 static int nochecksums = 0;
00112 #endif
00113 
00114 /*
00115  * Uncomment to try experimental IAX bridge optimization,
00116  * designed to reduce latency when IAX calls cannot
00117  * be trasnferred -- obsolete
00118  */
00119 
00120 /* #define BRIDGE_OPTIMIZATION  */
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_RETRY_TIME 1000
00127 #define MEMORY_SIZE 100
00128 #define DEFAULT_DROP 3
00129 /* Flag to use with trunk calls, keeping these calls high up.  It halves our effective use
00130    but keeps the division between trunked and non-trunked better. */
00131 #define TRUNK_CALL_START   0x4000
00132 
00133 #define DEBUG_SUPPORT
00134 
00135 #define MIN_REUSE_TIME     60 /* Don't reuse a call number within 60 seconds */
00136 
00137 /* Sample over last 100 units to determine historic jitter */
00138 #define GAMMA (0.01)
00139 
00140 static struct ast_codec_pref prefs;
00141 
00142 static const char desc[] = "Inter Asterisk eXchange (Ver 2)";
00143 static const char tdesc[] = "Inter Asterisk eXchange Driver (Ver 2)";
00144 static const char channeltype[] = "IAX2";
00145 
00146 static char context[80] = "default";
00147 
00148 static char language[MAX_LANGUAGE] = "";
00149 static char regcontext[AST_MAX_CONTEXT] = "";
00150 
00151 static int maxauthreq = 0;
00152 static int max_retries = 4;
00153 static int ping_time = 20;
00154 static int lagrq_time = 10;
00155 static int maxtrunkcall = TRUNK_CALL_START;
00156 static int maxnontrunkcall = 1;
00157 static int maxjitterbuffer=1000;
00158 #ifdef NEWJB
00159 static int resyncthreshold=1000;
00160 static int maxjitterinterps=10;
00161 #endif
00162 static int jittershrinkrate=2;
00163 static int trunkfreq = 20;
00164 static int authdebug = 1;
00165 static int autokill = 0;
00166 static int iaxcompat = 0;
00167 
00168 static int iaxdefaultdpcache=10 * 60;  /* Cache dialplan entries for 10 minutes by default */
00169 
00170 static int iaxdefaulttimeout = 5;      /* Default to wait no more than 5 seconds for a reply to come back */
00171 
00172 static int tos = 0;
00173 
00174 static int min_reg_expire;
00175 static int max_reg_expire;
00176 
00177 static int timingfd = -1;           /* Timing file descriptor */
00178 
00179 static struct ast_netsock_list *netsock;
00180 static struct ast_netsock_list *outsock;     /*!< used if sourceaddress specified and bindaddr == INADDR_ANY */
00181 static int defaultsockfd = -1;
00182 
00183 static int usecnt;
00184 AST_MUTEX_DEFINE_STATIC(usecnt_lock);
00185 
00186 int (*iax2_regfunk)(char *username, int onoff) = NULL;
00187 
00188 /* Ethernet, etc */
00189 #define IAX_CAPABILITY_FULLBANDWIDTH   0xFFFF
00190 /* T1, maybe ISDN */
00191 #define IAX_CAPABILITY_MEDBANDWIDTH    (IAX_CAPABILITY_FULLBANDWIDTH &  \
00192                      ~AST_FORMAT_SLINEAR &   \
00193                      ~AST_FORMAT_ULAW &   \
00194                      ~AST_FORMAT_ALAW) 
00195 /* A modem */
00196 #define IAX_CAPABILITY_LOWBANDWIDTH    (IAX_CAPABILITY_MEDBANDWIDTH &   \
00197                      ~AST_FORMAT_G726 &   \
00198                      ~AST_FORMAT_ADPCM)
00199 
00200 #define IAX_CAPABILITY_LOWFREE      (IAX_CAPABILITY_LOWBANDWIDTH &      \
00201                       ~AST_FORMAT_G723_1)
00202 
00203 
00204 #define DEFAULT_MAXMS      2000     /* Must be faster than 2 seconds by default */
00205 #define DEFAULT_FREQ_OK    60 * 1000   /* How often to check for the host to be up */
00206 #define DEFAULT_FREQ_NOTOK 10 * 1000   /* How often to check, if the host is down... */
00207 
00208 static   struct io_context *io;
00209 static   struct sched_context *sched;
00210 
00211 static int iax2_capability = IAX_CAPABILITY_FULLBANDWIDTH;
00212 
00213 static int iax2_dropcount = DEFAULT_DROP;
00214 
00215 static int iaxdebug = 0;
00216 
00217 static int iaxtrunkdebug = 0;
00218 
00219 static int test_losspct = 0;
00220 #ifdef IAXTESTS
00221 static int test_late = 0;
00222 static int test_resync = 0;
00223 static int test_jit = 0;
00224 static int test_jitpct = 0;
00225 #endif /* IAXTESTS */
00226 
00227 static char accountcode[AST_MAX_ACCOUNT_CODE];
00228 static int amaflags = 0;
00229 static int delayreject = 0;
00230 static int iax2_encryption = 0;
00231 
00232 static struct ast_flags globalflags = { 0 };
00233 
00234 static pthread_t netthreadid = AST_PTHREADT_NULL;
00235 
00236 enum {
00237    IAX_STATE_STARTED =     (1 << 0),
00238    IAX_STATE_AUTHENTICATED =  (1 << 1),
00239    IAX_STATE_TBD =      (1 << 2)
00240 } iax2_state;
00241 
00242 struct iax2_context {
00243    char context[AST_MAX_CONTEXT];
00244    struct iax2_context *next;
00245 };
00246 
00247 enum {
00248    IAX_HASCALLERID =    (1 << 0),   /*!< CallerID has been specified */
00249    IAX_DELME =    (1 << 1),   /*!< Needs to be deleted */
00250    IAX_TEMPONLY =    (1 << 2),   /*!< Temporary (realtime) */
00251    IAX_TRUNK =    (1 << 3),   /*!< Treat as a trunk */
00252    IAX_NOTRANSFER =  (1 << 4),   /*!< Don't native bridge */
00253    IAX_USEJITTERBUF =   (1 << 5),   /*!< Use jitter buffer */
00254    IAX_DYNAMIC =     (1 << 6),   /*!< dynamic peer */
00255    IAX_SENDANI =     (1 << 7),   /*!< Send ANI along with CallerID */
00256    IAX_MESSAGEDETAIL =  (1 << 8),   /*!< Show exact numbers */
00257    IAX_ALREADYGONE = (1 << 9),   /*!< Already disconnected */
00258    IAX_PROVISION =      (1 << 10),  /*!< This is a provisioning request */
00259    IAX_QUELCH =      (1 << 11),  /*!< Whether or not we quelch audio */
00260    IAX_ENCRYPTED =      (1 << 12),  /*!< Whether we should assume encrypted tx/rx */
00261    IAX_KEYPOPULATED =   (1 << 13),  /*!< Whether we have a key populated */
00262    IAX_CODEC_USER_FIRST =  (1 << 14),  /*!< are we willing to let the other guy choose the codec? */
00263    IAX_CODEC_NOPREFS =     (1 << 15),  /*!< Force old behaviour by turning off prefs */
00264    IAX_CODEC_NOCAP =    (1 << 16),  /*!< only consider requested format and ignore capabilities*/
00265    IAX_RTCACHEFRIENDS =    (1 << 17),  /*!< let realtime stay till your reload */
00266    IAX_RTUPDATE =       (1 << 18),  /*!< Send a realtime update */
00267    IAX_RTAUTOCLEAR =    (1 << 19),  /*!< erase me on expire */ 
00268    IAX_FORCEJITTERBUF = (1 << 20),  /*!< Force jitterbuffer, even when bridged to a channel that can take jitter */ 
00269    IAX_RTIGNOREREGEXPIRE = (1 << 21),  /*!< When using realtime, ignore registration expiration */
00270    IAX_TRUNKTIMESTAMPS =   (1 << 22),  /*!< Send trunk timestamps */
00271    IAX_MAXAUTHREQ =        (1 << 23),      /*!< Maximum outstanding AUTHREQ restriction is in place */
00272    IAX_DELAYPBXSTART =  (1 << 25),  /*!< Don't start a PBX on the channel until the peer sends us a
00273                        response, so that we've achieved a three-way handshake with
00274                        them before sending voice or anything else*/
00275    IAX_ALLOWFWDOWNLOAD = (1 << 26), /*!< Allow the FWDOWNL command? */
00276 } iax2_flags;
00277 
00278 static int global_rtautoclear = 120;
00279 
00280 static int reload_config(void);
00281 static int iax2_reload(int fd, int argc, char *argv[]);
00282 
00283 
00284 struct iax2_user {
00285    char name[80];
00286    char secret[80];
00287    char dbsecret[80];
00288    int authmethods;
00289    int encmethods;
00290    char accountcode[AST_MAX_ACCOUNT_CODE];
00291    char inkeys[80];           /*!< Key(s) this user can use to authenticate to us */
00292    char language[MAX_LANGUAGE];
00293    int amaflags;
00294    unsigned int flags;
00295    int capability;
00296    int maxauthreq; /*!< Maximum allowed outstanding AUTHREQs */
00297    int curauthreq; /*!< Current number of outstanding AUTHREQs */
00298    char cid_num[AST_MAX_EXTENSION];
00299    char cid_name[AST_MAX_EXTENSION];
00300    struct ast_codec_pref prefs;
00301    struct ast_ha *ha;
00302    struct iax2_context *contexts;
00303    struct iax2_user *next;
00304    struct ast_variable *vars;
00305 };
00306 
00307 struct iax2_peer {
00308    char name[80];
00309    char username[80];      
00310    char secret[80];
00311    char dbsecret[80];
00312    char outkey[80];           /*!< What key we use to talk to this peer */
00313    char context[AST_MAX_CONTEXT];         /*!< For transfers only */
00314    char regexten[AST_MAX_EXTENSION];      /*!< Extension to register (if regcontext is used) */
00315    char peercontext[AST_MAX_EXTENSION];      /*!< Context to pass to peer */
00316    char mailbox[AST_MAX_EXTENSION];    /*!< Mailbox */
00317    struct ast_codec_pref prefs;
00318    struct ast_dnsmgr_entry *dnsmgr;    /*!< DNS refresh manager */
00319    struct sockaddr_in addr;
00320    int formats;
00321    int sockfd;             /*!< Socket to use for transmission */
00322    struct in_addr mask;
00323    unsigned int flags;
00324 
00325    /* Dynamic Registration fields */
00326    struct sockaddr_in defaddr;         /*!< Default address if there is one */
00327    int authmethods;           /*!< Authentication methods (IAX_AUTH_*) */
00328    int encmethods;               /*!< Encryption methods (IAX_ENCRYPT_*) */
00329    char inkeys[80];           /*!< Key(s) this peer can use to authenticate to us */
00330 
00331    /* Suggested caller id if registering */
00332    char cid_num[AST_MAX_EXTENSION];
00333    char cid_name[AST_MAX_EXTENSION];
00334    
00335    int expire;             /*!< Schedule entry for expiry */
00336    int expiry;             /*!< How soon to expire */
00337    int capability;               /*!< Capability */
00338    char zonetag[80];          /*!< Time Zone */
00339 
00340    /* Qualification */
00341    int callno;             /*!< Call number of POKE request */
00342    int pokeexpire;               /*!< When to expire poke */
00343    int lastms;             /*!< How long last response took (in ms), or -1 for no response */
00344    int maxms;              /*!< Max ms we will accept for the host to be up, 0 to not monitor */
00345 
00346    int pokefreqok;               /*!< How often to check if the host is up */
00347    int pokefreqnotok;            /*!< How often to check when the host has been determined to be down */
00348    int historicms;               /*!< How long recent average responses took */
00349    int smoothing;             /*!< Sample over how many units to determine historic ms */
00350    
00351    struct ast_ha *ha;
00352    struct iax2_peer *next;
00353 };
00354 
00355 #define IAX2_TRUNK_PREFACE (sizeof(struct iax_frame) + sizeof(struct ast_iax2_meta_hdr) + sizeof(struct ast_iax2_meta_trunk_hdr))
00356 
00357 static struct iax2_trunk_peer {
00358    ast_mutex_t lock;
00359    int sockfd;
00360    struct sockaddr_in addr;
00361    struct timeval txtrunktime;      /*!< Transmit trunktime */
00362    struct timeval rxtrunktime;      /*!< Receive trunktime */
00363    struct timeval lasttxtime;    /*!< Last transmitted trunktime */
00364    struct timeval trunkact;      /*!< Last trunk activity */
00365    unsigned int lastsent;        /*!< Last sent time */
00366    /* Trunk data and length */
00367    unsigned char *trunkdata;
00368    unsigned int trunkdatalen;
00369    unsigned int trunkdataalloc;
00370    struct iax2_trunk_peer *next;
00371    int trunkerror;
00372    int calls;
00373 } *tpeers = NULL;
00374 
00375 AST_MUTEX_DEFINE_STATIC(tpeerlock);
00376 
00377 struct iax_firmware {
00378    struct iax_firmware *next;
00379    int fd;
00380    int mmaplen;
00381    int dead;
00382    struct ast_iax2_firmware_header *fwh;
00383    unsigned char *buf;
00384 };
00385 
00386 enum iax_reg_state {
00387    REG_STATE_UNREGISTERED = 0,
00388    REG_STATE_REGSENT,
00389    REG_STATE_AUTHSENT,
00390    REG_STATE_REGISTERED,
00391    REG_STATE_REJECTED,
00392    REG_STATE_TIMEOUT,
00393    REG_STATE_NOAUTH
00394 };
00395 
00396 enum iax_transfer_state {
00397    TRANSFER_NONE = 0,
00398    TRANSFER_BEGIN,
00399    TRANSFER_READY,
00400    TRANSFER_RELEASED,
00401    TRANSFER_PASSTHROUGH
00402 };
00403 
00404 struct iax2_registry {
00405    struct sockaddr_in addr;      /*!< Who we connect to for registration purposes */
00406    char username[80];
00407    char secret[80];        /*!< Password or key name in []'s */
00408    char random[80];
00409    int expire;          /*!< Sched ID of expiration */
00410    int refresh;            /*!< How often to refresh */
00411    enum iax_reg_state regstate;
00412    int messages;           /*!< Message count */
00413    int callno;          /*!< Associated call number if applicable */
00414    struct sockaddr_in us;        /*!< Who the server thinks we are */
00415    struct iax2_registry *next;
00416 };
00417 
00418 static struct iax2_registry *registrations;
00419 AST_MUTEX_DEFINE_STATIC(reg_lock);
00420 
00421 /* Don't retry more frequently than every 10 ms, or less frequently than every 5 seconds */
00422 #define MIN_RETRY_TIME     100
00423 #define MAX_RETRY_TIME     10000
00424 
00425 #define MAX_JITTER_BUFFER  50
00426 #define MIN_JITTER_BUFFER  10
00427 
00428 #define DEFAULT_TRUNKDATA  640 * 10 /*!< 40ms, uncompressed linear * 10 channels */
00429 #define MAX_TRUNKDATA      640 * 200   /*!< 40ms, uncompressed linear * 200 channels */
00430 
00431 #define MAX_TIMESTAMP_SKEW 160      /*!< maximum difference between actual and predicted ts for sending */
00432 
00433 /* If consecutive voice frame timestamps jump by more than this many milliseconds, then jitter buffer will resync */
00434 #define TS_GAP_FOR_JB_RESYNC  5000
00435 
00436 /* If we have more than this much excess real jitter buffer, shrink it. */
00437 static int max_jitter_buffer = MAX_JITTER_BUFFER;
00438 /* If we have less than this much excess real jitter buffer, enlarge it. */
00439 static int min_jitter_buffer = MIN_JITTER_BUFFER;
00440 
00441 struct iax_rr {
00442    int jitter;
00443    int losspct;
00444    int losscnt;
00445    int packets;
00446    int delay;
00447    int dropped;
00448    int ooo;
00449 };
00450 
00451 struct chan_iax2_pvt {
00452    /*! Socket to send/receive on for this call */
00453    int sockfd;
00454    /*! Last received voice format */
00455    int voiceformat;
00456    /*! Last received video format */
00457    int videoformat;
00458    /*! Last sent voice format */
00459    int svoiceformat;
00460    /*! Last sent video format */
00461    int svideoformat;
00462    /*! What we are capable of sending */
00463    int capability;
00464    /*! Last received timestamp */
00465    unsigned int last;
00466    /*! Last sent timestamp - never send the same timestamp twice in a single call */
00467    unsigned int lastsent;
00468    /*! Next outgoing timestamp if everything is good */
00469    unsigned int nextpred;
00470    /*! True if the last voice we transmitted was not silence/CNG */
00471    int notsilenttx;
00472    /*! Ping time */
00473    unsigned int pingtime;
00474    /*! Max time for initial response */
00475    int maxtime;
00476    /*! Peer Address */
00477    struct sockaddr_in addr;
00478    /*! Actual used codec preferences */
00479    struct ast_codec_pref prefs;
00480    /*! Requested codec preferences */
00481    struct ast_codec_pref rprefs;
00482    /*! Our call number */
00483    unsigned short callno;
00484    /*! Peer callno */
00485    unsigned short peercallno;
00486    /*! Negotiated format, this is only used to remember what format was
00487        chosen for an unauthenticated call so that the channel can get
00488        created later using the right format */
00489    int chosenformat;
00490    /*! Peer selected format */
00491    int peerformat;
00492    /*! Peer capability */
00493    int peercapability;
00494    /*! timeval that we base our transmission on */
00495    struct timeval offset;
00496    /*! timeval that we base our delivery on */
00497    struct timeval rxcore;
00498 #ifdef NEWJB
00499    /*! The jitterbuffer */
00500         jitterbuf *jb;
00501    /*! active jb read scheduler id */
00502         int jbid;                       
00503 #else
00504    /*! Historical delivery time */
00505    int history[MEMORY_SIZE];
00506    /*! Current base jitterbuffer */
00507    int jitterbuffer;
00508    /*! Current jitter measure */
00509    int jitter;
00510    /*! Historic jitter value */
00511    int historicjitter;
00512 #endif
00513    /*! LAG */
00514    int lag;
00515    /*! Error, as discovered by the manager */
00516    int error;
00517    /*! Owner if we have one */
00518    struct ast_channel *owner;
00519    /*! What's our state? */
00520    struct ast_flags state;
00521    /*! Expiry (optional) */
00522    int expiry;
00523    /*! Next outgoing sequence number */
00524    unsigned char oseqno;
00525    /*! Next sequence number they have not yet acknowledged */
00526    unsigned char rseqno;
00527    /*! Next incoming sequence number */
00528    unsigned char iseqno;
00529    /*! Last incoming sequence number we have acknowledged */
00530    unsigned char aseqno;
00531    /*! Peer name */
00532    char peer[80];
00533    /*! Default Context */
00534    char context[80];
00535    /*! Caller ID if available */
00536    char cid_num[80];
00537    char cid_name[80];
00538    /*! Hidden Caller ID (i.e. ANI) if appropriate */
00539    char ani[80];
00540    /*! DNID */
00541    char dnid[80];
00542    /*! Requested Extension */
00543    char exten[AST_MAX_EXTENSION];
00544    /*! Expected Username */
00545    char username[80];
00546    /*! Expected Secret */
00547    char secret[80];
00548    /*! permitted authentication methods */
00549    int authmethods;
00550    /*! permitted encryption methods */
00551    int encmethods;
00552    /*! MD5 challenge */
00553    char challenge[10];
00554    /*! Public keys permitted keys for incoming authentication */
00555    char inkeys[80];
00556    /*! Private key for outgoing authentication */
00557    char outkey[80];
00558    /*! Encryption AES-128 Key */
00559    aes_encrypt_ctx ecx;
00560    /*! Decryption AES-128 Key */
00561    aes_decrypt_ctx dcx;
00562    /*! 32 bytes of semi-random data */
00563    unsigned char semirand[32];
00564    /*! Preferred language */
00565    char language[MAX_LANGUAGE];
00566    /*! Hostname/peername for naming purposes */
00567    char host[80];
00568    /*! Associated registry */
00569    struct iax2_registry *reg;
00570    /*! Associated peer for poking */
00571    struct iax2_peer *peerpoke;
00572    /*! IAX_ flags */
00573    unsigned int flags;
00574 
00575    /*! Transferring status */
00576    enum iax_transfer_state transferring;
00577    /*! Transfer identifier */
00578    int transferid;
00579    /*! Who we are IAX transfering to */
00580    struct sockaddr_in transfer;
00581    /*! What's the new call number for the transfer */
00582    unsigned short transfercallno;
00583    /*! Transfer decrypt AES-128 Key */
00584    aes_encrypt_ctx tdcx;
00585 
00586    /*! Status of knowledge of peer ADSI capability */
00587    int peeradsicpe;
00588    
00589    /*! Who we are bridged to */
00590    unsigned short bridgecallno;
00591    unsigned int bridgesfmt;
00592    struct ast_trans_pvt *bridgetrans;
00593    
00594    int pingid;       /*!< Transmit PING request */
00595    int lagid;        /*!< Retransmit lag request */
00596    int autoid;       /*!< Auto hangup for Dialplan requestor */
00597    int authid;       /*!< Authentication rejection ID */
00598    int authfail;        /*!< Reason to report failure */
00599    int initid;       /*!< Initial peer auto-congest ID (based on qualified peers) */
00600    int calling_ton;
00601    int calling_tns;
00602    int calling_pres;
00603    char dproot[AST_MAX_EXTENSION];
00604    char accountcode[AST_MAX_ACCOUNT_CODE];
00605    int amaflags;
00606    struct iax2_dpcache *dpentries;
00607    struct ast_variable *vars;
00608    /*! last received remote rr */
00609    struct iax_rr remote_rr;
00610    /*! Current base time: (just for stats) */
00611    int min;
00612    /*! Dropped frame count: (just for stats) */
00613    int frames_dropped;
00614    /*! received frame count: (just for stats) */
00615    int frames_received;
00616 };
00617 
00618 static struct ast_iax2_queue {
00619    struct iax_frame *head;
00620    struct iax_frame *tail;
00621    int count;
00622    ast_mutex_t lock;
00623 } iaxq;
00624 
00625 static struct ast_user_list {
00626    struct iax2_user *users;
00627    ast_mutex_t lock;
00628 } userl;
00629 
00630 static struct ast_peer_list {
00631    struct iax2_peer *peers;
00632    ast_mutex_t lock;
00633 } peerl;
00634 
00635 static struct ast_firmware_list {
00636    struct iax_firmware *wares;
00637    ast_mutex_t lock;
00638 } waresl;
00639 
00640 /*! Extension exists */
00641 #define CACHE_FLAG_EXISTS     (1 << 0)
00642 /*! Extension is nonexistent */
00643 #define CACHE_FLAG_NONEXISTENT      (1 << 1)
00644 /*! Extension can exist */
00645 #define CACHE_FLAG_CANEXIST      (1 << 2)
00646 /*! Waiting to hear back response */
00647 #define CACHE_FLAG_PENDING    (1 << 3)
00648 /*! Timed out */
00649 #define CACHE_FLAG_TIMEOUT    (1 << 4)
00650 /*! Request transmitted */
00651 #define CACHE_FLAG_TRANSMITTED      (1 << 5)
00652 /*! Timeout */
00653 #define CACHE_FLAG_UNKNOWN    (1 << 6)
00654 /*! Matchmore */
00655 #define CACHE_FLAG_MATCHMORE     (1 << 7)
00656 
00657 static struct iax2_dpcache {
00658    char peercontext[AST_MAX_CONTEXT];
00659    char exten[AST_MAX_EXTENSION];
00660    struct timeval orig;
00661    struct timeval expiry;
00662    int flags;
00663    unsigned short callno;
00664    int waiters[256];
00665    struct iax2_dpcache *next;
00666    struct iax2_dpcache *peer; /*!< For linking in peers */
00667 } *dpcache;
00668 
00669 AST_MUTEX_DEFINE_STATIC(dpcache_lock);
00670 
00671 static void reg_source_db(struct iax2_peer *p);
00672 static struct iax2_peer *realtime_peer(const char *peername, struct sockaddr_in *sin);
00673 
00674 static void destroy_peer(struct iax2_peer *peer);
00675 static int ast_cli_netstats(int fd, int limit_fmt);
00676 
00677 #ifdef __AST_DEBUG_MALLOC
00678 static void FREE(void *ptr)
00679 {
00680    free(ptr);
00681 }
00682 #else
00683 #define FREE free
00684 #endif
00685 
00686 static void iax_debug_output(const char *data)
00687 {
00688    if (iaxdebug)
00689       ast_verbose("%s", data);
00690 }
00691 
00692 static void iax_error_output(const char *data)
00693 {
00694    ast_log(LOG_WARNING, "%s", data);
00695 }
00696 
00697 #ifdef NEWJB
00698 static void jb_error_output(const char *fmt, ...)
00699 {
00700    va_list args;
00701    char buf[1024];
00702 
00703    va_start(args, fmt);
00704    vsnprintf(buf, 1024, fmt, args);
00705    va_end(args);
00706 
00707    ast_log(LOG_ERROR, buf);
00708 }
00709 
00710 static void jb_warning_output(const char *fmt, ...)
00711 {
00712    va_list args;
00713    char buf[1024];
00714 
00715    va_start(args, fmt);
00716    vsnprintf(buf, 1024, fmt, args);
00717    va_end(args);
00718 
00719    ast_log(LOG_WARNING, buf);
00720 }
00721 
00722 static void jb_debug_output(const char *fmt, ...)
00723 {
00724    va_list args;
00725    char buf[1024];
00726 
00727    va_start(args, fmt);
00728    vsnprintf(buf, 1024, fmt, args);
00729    va_end(args);
00730 
00731    ast_verbose(buf);
00732 }
00733 #endif
00734 
00735 
00736 /* XXX We probably should use a mutex when working with this XXX */
00737 static struct chan_iax2_pvt *iaxs[IAX_MAX_CALLS];
00738 static ast_mutex_t iaxsl[IAX_MAX_CALLS];
00739 static struct timeval lastused[IAX_MAX_CALLS];
00740 
00741 /*!
00742  * \brief Another container of iax2_pvt structures
00743  *
00744  * Active IAX2 pvt structs are also stored in this container, if they are a part
00745  * of an active call where we know the remote side's call number.  The reason
00746  * for this is that incoming media frames do not contain our call number.  So,
00747  * instead of having to iterate the entire iaxs array, we use this container to
00748  * look up calls where the remote side is using a given call number.
00749  */
00750 static struct ao2_container *iax_peercallno_pvts;
00751 
00752 static int send_command(struct chan_iax2_pvt *,