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