Wed Oct 28 15:47:50 2009

Asterisk developer's documentation


chan_iax2.c

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