fcd1882149cc1bd9816a51ff06191e4c4beb122a
[asterisk/asterisk.git] / channels / chan_iax2.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 1999 - 2006, Digium, Inc.
5  *
6  * Mark Spencer <markster@digium.com>
7  *
8  * See http://www.asterisk.org for more information about
9  * the Asterisk project. Please do not directly contact
10  * any of the maintainers of this project for assistance;
11  * the project provides a web site, mailing lists and IRC
12  * channels for your use.
13  *
14  * This program is free software, distributed under the terms of
15  * the GNU General Public License Version 2. See the LICENSE file
16  * at the top of the source tree.
17  */
18
19 /*! \file
20  *
21  * \brief Implementation of Inter-Asterisk eXchange Version 2
22  *
23  * \author Mark Spencer <markster@digium.com>
24  *
25  * \par See also
26  * \arg \ref Config_iax
27  *
28  * \ingroup channel_drivers
29  * 
30  * \todo Implement musicclass settings for IAX2 devices
31  */
32
33 /*** MODULEINFO
34         <use>zaptel</use>
35         <use>crypto</use>
36  ***/
37
38 #include "asterisk.h"
39
40 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
41
42 #include <sys/mman.h>
43 #include <dirent.h>
44 #include <sys/socket.h>
45 #include <netinet/in.h>
46 #include <arpa/inet.h>
47 #include <netinet/in_systm.h>
48 #include <netinet/ip.h>
49 #include <sys/time.h>
50 #include <sys/signal.h>
51 #include <signal.h>
52 #include <strings.h>
53 #include <netdb.h>
54 #include <fcntl.h>
55 #include <sys/stat.h>
56 #include <regex.h>
57
58 #include "asterisk/zapata.h"
59 #include "asterisk/paths.h"     /* need ast_config_AST_DATA_DIR for firmware */
60
61 #include "asterisk/lock.h"
62 #include "asterisk/frame.h" 
63 #include "asterisk/channel.h"
64 #include "asterisk/module.h"
65 #include "asterisk/pbx.h"
66 #include "asterisk/sched.h"
67 #include "asterisk/io.h"
68 #include "asterisk/config.h"
69 #include "asterisk/cli.h"
70 #include "asterisk/translate.h"
71 #include "asterisk/md5.h"
72 #include "asterisk/cdr.h"
73 #include "asterisk/crypto.h"
74 #include "asterisk/acl.h"
75 #include "asterisk/manager.h"
76 #include "asterisk/callerid.h"
77 #include "asterisk/app.h"
78 #include "asterisk/astdb.h"
79 #include "asterisk/musiconhold.h"
80 #include "asterisk/features.h"
81 #include "asterisk/utils.h"
82 #include "asterisk/causes.h"
83 #include "asterisk/localtime.h"
84 #include "asterisk/aes.h"
85 #include "asterisk/dnsmgr.h"
86 #include "asterisk/devicestate.h"
87 #include "asterisk/netsock.h"
88 #include "asterisk/stringfields.h"
89 #include "asterisk/linkedlists.h"
90 #include "asterisk/event.h"
91 #include "asterisk/astobj2.h"
92
93 #include "iax2.h"
94 #include "iax2-parser.h"
95 #include "iax2-provision.h"
96 #include "jitterbuf.h"
97
98 /* Define SCHED_MULTITHREADED to run the scheduler in a special
99    multithreaded mode. */
100 #define SCHED_MULTITHREADED
101
102 /* Define DEBUG_SCHED_MULTITHREADED to keep track of where each
103    thread is actually doing. */
104 #define DEBUG_SCHED_MULTITHREAD
105
106
107 #ifdef SO_NO_CHECK
108 static int nochecksums = 0;
109 #endif
110
111
112 #define PTR_TO_CALLNO(a) ((unsigned short)(unsigned long)(a))
113 #define CALLNO_TO_PTR(a) ((void *)(unsigned long)(a))
114
115 #define DEFAULT_THREAD_COUNT 10
116 #define DEFAULT_MAX_THREAD_COUNT 100
117 #define DEFAULT_RETRY_TIME 1000
118 #define MEMORY_SIZE 100
119 #define DEFAULT_DROP 3
120
121 #define DEBUG_SUPPORT
122
123 #define MIN_REUSE_TIME          60      /* Don't reuse a call number within 60 seconds */
124
125 /* Sample over last 100 units to determine historic jitter */
126 #define GAMMA (0.01)
127
128 static struct ast_codec_pref prefs;
129
130 static const char tdesc[] = "Inter Asterisk eXchange Driver (Ver 2)";
131
132
133 /*! \brief Maximum transmission unit for the UDP packet in the trunk not to be
134     fragmented. This is based on 1516 - ethernet - ip - udp - iax minus one g711 frame = 1240 */
135 #define MAX_TRUNK_MTU 1240 
136
137 static int global_max_trunk_mtu;        /*!< Maximum MTU, 0 if not used */
138 static int trunk_timed, trunk_untimed, trunk_maxmtu, trunk_nmaxmtu ;    /*!< Trunk MTU statistics */
139
140
141 static char context[80] = "default";
142 static char default_parkinglot[AST_MAX_CONTEXT];
143
144 static char language[MAX_LANGUAGE] = "";
145 static char regcontext[AST_MAX_CONTEXT] = "";
146
147 static int maxauthreq = 3;
148 static int max_retries = 4;
149 static int ping_time = 21;
150 static int lagrq_time = 10;
151 static int maxjitterbuffer=1000;
152 static int resyncthreshold=1000;
153 static int maxjitterinterps=10;
154 static int jittertargetextra = 40; /* number of milliseconds the new jitter buffer adds on to its size */
155
156 #define MAX_TRUNKDATA           640 * 200       /*!< 40ms, uncompressed linear * 200 channels */
157
158 static int trunkfreq = 20;
159 static int trunkmaxsize = MAX_TRUNKDATA;
160
161 static int authdebug = 1;
162 static int autokill = 0;
163 static int iaxcompat = 0;
164
165 static int iaxdefaultdpcache=10 * 60;   /* Cache dialplan entries for 10 minutes by default */
166
167 static int iaxdefaulttimeout = 5;               /* Default to wait no more than 5 seconds for a reply to come back */
168
169 static unsigned int tos = 0;
170
171 static unsigned int cos = 0;
172
173 static int min_reg_expire;
174 static int max_reg_expire;
175
176 static int srvlookup = 0;
177
178 static int timingfd = -1;                               /* Timing file descriptor */
179
180 static struct ast_netsock_list *netsock;
181 static struct ast_netsock_list *outsock;                /*!< used if sourceaddress specified and bindaddr == INADDR_ANY */
182 static int defaultsockfd = -1;
183
184 int (*iax2_regfunk)(const char *username, int onoff) = NULL;
185
186 /* Ethernet, etc */
187 #define IAX_CAPABILITY_FULLBANDWIDTH    0xFFFF
188 /* T1, maybe ISDN */
189 #define IAX_CAPABILITY_MEDBANDWIDTH     (IAX_CAPABILITY_FULLBANDWIDTH &         \
190                                          ~AST_FORMAT_SLINEAR &                  \
191                                          ~AST_FORMAT_ULAW &                     \
192                                          ~AST_FORMAT_ALAW &                     \
193                                          ~AST_FORMAT_G722) 
194 /* A modem */
195 #define IAX_CAPABILITY_LOWBANDWIDTH     (IAX_CAPABILITY_MEDBANDWIDTH &          \
196                                          ~AST_FORMAT_G726 &                     \
197                                          ~AST_FORMAT_G726_AAL2 &                \
198                                          ~AST_FORMAT_ADPCM)
199
200 #define IAX_CAPABILITY_LOWFREE          (IAX_CAPABILITY_LOWBANDWIDTH &          \
201                                          ~AST_FORMAT_G723_1)
202
203
204 #define DEFAULT_MAXMS           2000            /* Must be faster than 2 seconds by default */
205 #define DEFAULT_FREQ_OK         60 * 1000       /* How often to check for the host to be up */
206 #define DEFAULT_FREQ_NOTOK      10 * 1000       /* How often to check, if the host is down... */
207
208 static  struct io_context *io;
209 static  struct sched_context *sched;
210
211 static int iax2_capability = IAX_CAPABILITY_FULLBANDWIDTH;
212
213 static int iaxdebug = 0;
214
215 static int iaxtrunkdebug = 0;
216
217 static int test_losspct = 0;
218 #ifdef IAXTESTS
219 static int test_late = 0;
220 static int test_resync = 0;
221 static int test_jit = 0;
222 static int test_jitpct = 0;
223 #endif /* IAXTESTS */
224
225 static char accountcode[AST_MAX_ACCOUNT_CODE];
226 static char mohinterpret[MAX_MUSICCLASS];
227 static char mohsuggest[MAX_MUSICCLASS];
228 static int amaflags = 0;
229 static int adsi = 0;
230 static int delayreject = 0;
231 static int iax2_encryption = 0;
232
233 static struct ast_flags globalflags = { 0 };
234
235 static pthread_t netthreadid = AST_PTHREADT_NULL;
236 static pthread_t schedthreadid = AST_PTHREADT_NULL;
237 AST_MUTEX_DEFINE_STATIC(sched_lock);
238 static ast_cond_t sched_cond;
239
240 enum iax2_state {
241         IAX_STATE_STARTED =             (1 << 0),
242         IAX_STATE_AUTHENTICATED =       (1 << 1),
243         IAX_STATE_TBD =                 (1 << 2),
244         IAX_STATE_UNCHANGED =           (1 << 3),
245 };
246
247 struct iax2_context {
248         char context[AST_MAX_CONTEXT];
249         struct iax2_context *next;
250 };
251
252 enum iax2_flags {
253         IAX_HASCALLERID =       (1 << 0),       /*!< CallerID has been specified */
254         IAX_DELME =             (1 << 1),       /*!< Needs to be deleted */
255         IAX_TEMPONLY =          (1 << 2),       /*!< Temporary (realtime) */
256         IAX_TRUNK =             (1 << 3),       /*!< Treat as a trunk */
257         IAX_NOTRANSFER =        (1 << 4),       /*!< Don't native bridge */
258         IAX_USEJITTERBUF =      (1 << 5),       /*!< Use jitter buffer */
259         IAX_DYNAMIC =           (1 << 6),       /*!< dynamic peer */
260         IAX_SENDANI =           (1 << 7),       /*!< Send ANI along with CallerID */
261         /* (1 << 8) is currently unused due to the deprecation of an old option. Go ahead, take it! */
262         IAX_ALREADYGONE =       (1 << 9),       /*!< Already disconnected */
263         IAX_PROVISION =         (1 << 10),      /*!< This is a provisioning request */
264         IAX_QUELCH =            (1 << 11),      /*!< Whether or not we quelch audio */
265         IAX_ENCRYPTED =         (1 << 12),      /*!< Whether we should assume encrypted tx/rx */
266         IAX_KEYPOPULATED =      (1 << 13),      /*!< Whether we have a key populated */
267         IAX_CODEC_USER_FIRST =  (1 << 14),      /*!< are we willing to let the other guy choose the codec? */
268         IAX_CODEC_NOPREFS =     (1 << 15),      /*!< Force old behaviour by turning off prefs */
269         IAX_CODEC_NOCAP =       (1 << 16),      /*!< only consider requested format and ignore capabilities*/
270         IAX_RTCACHEFRIENDS =    (1 << 17),      /*!< let realtime stay till your reload */
271         IAX_RTUPDATE =          (1 << 18),      /*!< Send a realtime update */
272         IAX_RTAUTOCLEAR =       (1 << 19),      /*!< erase me on expire */ 
273         IAX_FORCEJITTERBUF =    (1 << 20),      /*!< Force jitterbuffer, even when bridged to a channel that can take jitter */ 
274         IAX_RTIGNOREREGEXPIRE = (1 << 21),      /*!< When using realtime, ignore registration expiration */
275         IAX_TRUNKTIMESTAMPS =   (1 << 22),      /*!< Send trunk timestamps */
276         IAX_TRANSFERMEDIA =     (1 << 23),      /*!< When doing IAX2 transfers, transfer media only */
277         IAX_MAXAUTHREQ =        (1 << 24),      /*!< Maximum outstanding AUTHREQ restriction is in place */
278         IAX_DELAYPBXSTART =     (1 << 25),      /*!< Don't start a PBX on the channel until the peer sends us a
279                                                      response, so that we've achieved a three-way handshake with
280                                                      them before sending voice or anything else*/
281 };
282
283 static int global_rtautoclear = 120;
284
285 static int reload_config(void);
286
287 struct iax2_user {
288         AST_DECLARE_STRING_FIELDS(
289                 AST_STRING_FIELD(name);
290                 AST_STRING_FIELD(secret);
291                 AST_STRING_FIELD(dbsecret);
292                 AST_STRING_FIELD(accountcode);
293                 AST_STRING_FIELD(mohinterpret);
294                 AST_STRING_FIELD(mohsuggest);
295                 AST_STRING_FIELD(inkeys);               /*!< Key(s) this user can use to authenticate to us */
296                 AST_STRING_FIELD(language);
297                 AST_STRING_FIELD(cid_num);
298                 AST_STRING_FIELD(cid_name);
299                 AST_STRING_FIELD(parkinglot);           /*!< Default parkinglot for device */
300         );
301         
302         int authmethods;
303         int encmethods;
304         int amaflags;
305         int adsi;
306         unsigned int flags;
307         int capability;
308         int maxauthreq; /*!< Maximum allowed outstanding AUTHREQs */
309         int curauthreq; /*!< Current number of outstanding AUTHREQs */
310         struct ast_codec_pref prefs;
311         struct ast_ha *ha;
312         struct iax2_context *contexts;
313         struct ast_variable *vars;
314 };
315
316 struct iax2_peer {
317         AST_DECLARE_STRING_FIELDS(
318                 AST_STRING_FIELD(name);
319                 AST_STRING_FIELD(username);
320                 AST_STRING_FIELD(secret);
321                 AST_STRING_FIELD(dbsecret);
322                 AST_STRING_FIELD(outkey);           /*!< What key we use to talk to this peer */
323
324                 AST_STRING_FIELD(regexten);     /*!< Extension to register (if regcontext is used) */
325                 AST_STRING_FIELD(context);      /*!< For transfers only */
326                 AST_STRING_FIELD(peercontext);  /*!< Context to pass to peer */
327                 AST_STRING_FIELD(mailbox);          /*!< Mailbox */
328                 AST_STRING_FIELD(mohinterpret);
329                 AST_STRING_FIELD(mohsuggest);
330                 AST_STRING_FIELD(inkeys);               /*!< Key(s) this peer can use to authenticate to us */
331                 /* Suggested caller id if registering */
332                 AST_STRING_FIELD(cid_num);              /*!< Default context (for transfer really) */
333                 AST_STRING_FIELD(cid_name);             /*!< Default context (for transfer really) */
334                 AST_STRING_FIELD(zonetag);              /*!< Time Zone */
335                 AST_STRING_FIELD(parkinglot);   /*!< Default parkinglot for device */
336         );
337         struct ast_codec_pref prefs;
338         struct ast_dnsmgr_entry *dnsmgr;                /*!< DNS refresh manager */
339         struct sockaddr_in addr;
340         int formats;
341         int sockfd;                                     /*!< Socket to use for transmission */
342         struct in_addr mask;
343         int adsi;
344         unsigned int flags;
345
346         /* Dynamic Registration fields */
347         struct sockaddr_in defaddr;                     /*!< Default address if there is one */
348         int authmethods;                                /*!< Authentication methods (IAX_AUTH_*) */
349         int encmethods;                                 /*!< Encryption methods (IAX_ENCRYPT_*) */
350
351         int expire;                                     /*!< Schedule entry for expiry */
352         int expiry;                                     /*!< How soon to expire */
353         int capability;                                 /*!< Capability */
354
355         /* Qualification */
356         int callno;                                     /*!< Call number of POKE request */
357         int pokeexpire;                                 /*!< Scheduled qualification-related task (ie iax2_poke_peer_s or iax2_poke_noanswer) */
358         int lastms;                                     /*!< How long last response took (in ms), or -1 for no response */
359         int maxms;                                      /*!< Max ms we will accept for the host to be up, 0 to not monitor */
360
361         int pokefreqok;                                 /*!< How often to check if the host is up */
362         int pokefreqnotok;                              /*!< How often to check when the host has been determined to be down */
363         int historicms;                                 /*!< How long recent average responses took */
364         int smoothing;                                  /*!< Sample over how many units to determine historic ms */
365
366         struct ast_event_sub *mwi_event_sub;
367
368         struct ast_ha *ha;
369 };
370
371 #define IAX2_TRUNK_PREFACE (sizeof(struct iax_frame) + sizeof(struct ast_iax2_meta_hdr) + sizeof(struct ast_iax2_meta_trunk_hdr))
372
373 struct iax2_trunk_peer {
374         ast_mutex_t lock;
375         int sockfd;
376         struct sockaddr_in addr;
377         struct timeval txtrunktime;             /*!< Transmit trunktime */
378         struct timeval rxtrunktime;             /*!< Receive trunktime */
379         struct timeval lasttxtime;              /*!< Last transmitted trunktime */
380         struct timeval trunkact;                /*!< Last trunk activity */
381         unsigned int lastsent;                  /*!< Last sent time */
382         /* Trunk data and length */
383         unsigned char *trunkdata;
384         unsigned int trunkdatalen;
385         unsigned int trunkdataalloc;
386         int trunkmaxmtu;
387         int trunkerror;
388         int calls;
389         AST_LIST_ENTRY(iax2_trunk_peer) list;
390 };
391
392 static AST_LIST_HEAD_STATIC(tpeers, iax2_trunk_peer);
393
394 struct iax_firmware {
395         AST_LIST_ENTRY(iax_firmware) list;
396         int fd;
397         int mmaplen;
398         int dead;
399         struct ast_iax2_firmware_header *fwh;
400         unsigned char *buf;
401 };
402
403 enum iax_reg_state {
404         REG_STATE_UNREGISTERED = 0,
405         REG_STATE_REGSENT,
406         REG_STATE_AUTHSENT,
407         REG_STATE_REGISTERED,
408         REG_STATE_REJECTED,
409         REG_STATE_TIMEOUT,
410         REG_STATE_NOAUTH
411 };
412
413 enum iax_transfer_state {
414         TRANSFER_NONE = 0,
415         TRANSFER_BEGIN,
416         TRANSFER_READY,
417         TRANSFER_RELEASED,
418         TRANSFER_MBEGIN,
419         TRANSFER_MREADY,
420         TRANSFER_MRELEASED
421 };
422
423 struct iax2_registry {
424         struct sockaddr_in addr;                /*!< Who we connect to for registration purposes */
425         char username[80];
426         char secret[80];                        /*!< Password or key name in []'s */
427         int expire;                             /*!< Sched ID of expiration */
428         int refresh;                            /*!< How often to refresh */
429         enum iax_reg_state regstate;
430         int messages;                           /*!< Message count, low 8 bits = new, high 8 bits = old */
431         int callno;                             /*!< Associated call number if applicable */
432         struct sockaddr_in us;                  /*!< Who the server thinks we are */
433         struct ast_dnsmgr_entry *dnsmgr;        /*!< DNS refresh manager */
434         AST_LIST_ENTRY(iax2_registry) entry;
435 };
436
437 static AST_LIST_HEAD_STATIC(registrations, iax2_registry);
438
439 /* Don't retry more frequently than every 10 ms, or less frequently than every 5 seconds */
440 #define MIN_RETRY_TIME          100
441 #define MAX_RETRY_TIME          10000
442
443 #define MAX_JITTER_BUFFER       50
444 #define MIN_JITTER_BUFFER       10
445
446 #define DEFAULT_TRUNKDATA       640 * 10        /*!< 40ms, uncompressed linear * 10 channels */
447
448 #define MAX_TIMESTAMP_SKEW      160             /*!< maximum difference between actual and predicted ts for sending */
449
450 /* If consecutive voice frame timestamps jump by more than this many milliseconds, then jitter buffer will resync */
451 #define TS_GAP_FOR_JB_RESYNC    5000
452
453 static int iaxthreadcount = DEFAULT_THREAD_COUNT;
454 static int iaxmaxthreadcount = DEFAULT_MAX_THREAD_COUNT;
455 static int iaxdynamicthreadcount = 0;
456 static int iaxactivethreadcount = 0;
457
458 struct iax_rr {
459         int jitter;
460         int losspct;
461         int losscnt;
462         int packets;
463         int delay;
464         int dropped;
465         int ooo;
466 };
467
468 struct iax2_pvt_ref;
469
470 struct chan_iax2_pvt {
471         /*! Socket to send/receive on for this call */
472         int sockfd;
473         /*! Last received voice format */
474         int voiceformat;
475         /*! Last received video format */
476         int videoformat;
477         /*! Last sent voice format */
478         int svoiceformat;
479         /*! Last sent video format */
480         int svideoformat;
481         /*! What we are capable of sending */
482         int capability;
483         /*! Last received timestamp */
484         unsigned int last;
485         /*! Last sent timestamp - never send the same timestamp twice in a single call */
486         unsigned int lastsent;
487         /*! Timestamp of the last video frame sent */
488         unsigned int lastvsent;
489         /*! Next outgoing timestamp if everything is good */
490         unsigned int nextpred;
491         /*! True if the last voice we transmitted was not silence/CNG */
492         unsigned int notsilenttx:1;
493         /*! Ping time */
494         unsigned int pingtime;
495         /*! Max time for initial response */
496         int maxtime;
497         /*! Peer Address */
498         struct sockaddr_in addr;
499         /*! Actual used codec preferences */
500         struct ast_codec_pref prefs;
501         /*! Requested codec preferences */
502         struct ast_codec_pref rprefs;
503         /*! Our call number */
504         unsigned short callno;
505         /*! Peer callno */
506         unsigned short peercallno;
507         /*! Negotiated format, this is only used to remember what format was
508             chosen for an unauthenticated call so that the channel can get
509             created later using the right format */
510         int chosenformat;
511         /*! Peer selected format */
512         int peerformat;
513         /*! Peer capability */
514         int peercapability;
515         /*! timeval that we base our transmission on */
516         struct timeval offset;
517         /*! timeval that we base our delivery on */
518         struct timeval rxcore;
519         /*! The jitterbuffer */
520         jitterbuf *jb;
521         /*! active jb read scheduler id */
522         int jbid;                       
523         /*! LAG */
524         int lag;
525         /*! Error, as discovered by the manager */
526         int error;
527         /*! Owner if we have one */
528         struct ast_channel *owner;
529         /*! What's our state? */
530         struct ast_flags state;
531         /*! Expiry (optional) */
532         int expiry;
533         /*! Next outgoing sequence number */
534         unsigned char oseqno;
535         /*! Next sequence number they have not yet acknowledged */
536         unsigned char rseqno;
537         /*! Next incoming sequence number */
538         unsigned char iseqno;
539         /*! Last incoming sequence number we have acknowledged */
540         unsigned char aseqno;
541
542         AST_DECLARE_STRING_FIELDS(
543                 /*! Peer name */
544                 AST_STRING_FIELD(peer);
545                 /*! Default Context */
546                 AST_STRING_FIELD(context);
547                 /*! Caller ID if available */
548                 AST_STRING_FIELD(cid_num);
549                 AST_STRING_FIELD(cid_name);
550                 /*! Hidden Caller ID (i.e. ANI) if appropriate */
551                 AST_STRING_FIELD(ani);
552                 /*! DNID */
553                 AST_STRING_FIELD(dnid);
554                 /*! RDNIS */
555                 AST_STRING_FIELD(rdnis);
556                 /*! Requested Extension */
557                 AST_STRING_FIELD(exten);
558                 /*! Expected Username */
559                 AST_STRING_FIELD(username);
560                 /*! Expected Secret */
561                 AST_STRING_FIELD(secret);
562                 /*! MD5 challenge */
563                 AST_STRING_FIELD(challenge);
564                 /*! Public keys permitted keys for incoming authentication */
565                 AST_STRING_FIELD(inkeys);
566                 /*! Private key for outgoing authentication */
567                 AST_STRING_FIELD(outkey);
568                 /*! Preferred language */
569                 AST_STRING_FIELD(language);
570                 /*! Hostname/peername for naming purposes */
571                 AST_STRING_FIELD(host);
572
573                 AST_STRING_FIELD(dproot);
574                 AST_STRING_FIELD(accountcode);
575                 AST_STRING_FIELD(mohinterpret);
576                 AST_STRING_FIELD(mohsuggest);
577                 /*! received OSP token */
578                 AST_STRING_FIELD(osptoken);
579                 /*! Default parkinglot */
580                 AST_STRING_FIELD(parkinglot);
581         );
582         
583         /*! permitted authentication methods */
584         int authmethods;
585         /*! permitted encryption methods */
586         int encmethods;
587         /*! Encryption AES-128 Key */
588         ast_aes_encrypt_key ecx;
589         /*! Decryption AES-128 Key */
590         ast_aes_decrypt_key dcx;
591         /*! 32 bytes of semi-random data */
592         unsigned char semirand[32];
593         /*! Associated registry */
594         struct iax2_registry *reg;
595         /*! Associated peer for poking */
596         struct iax2_peer *peerpoke;
597         /*! IAX_ flags */
598         unsigned int flags;
599         int adsi;
600
601         /*! Transferring status */
602         enum iax_transfer_state transferring;
603         /*! Transfer identifier */
604         int transferid;
605         /*! Who we are IAX transferring to */
606         struct sockaddr_in transfer;
607         /*! What's the new call number for the transfer */
608         unsigned short transfercallno;
609         /*! Transfer encrypt AES-128 Key */
610         ast_aes_encrypt_key tdcx;
611         
612         /*! If transfer has been attempted */
613         unsigned int triedtransfer:1;
614         /*! Whether media is released */
615         unsigned int mediareleased:1;
616         /*! If media released, the peer to send media to */
617         struct sockaddr_in media;
618
619         /*! Status of knowledge of peer ADSI capability */
620         int peeradsicpe;
621
622         /*! Who we are bridged to */
623         unsigned short bridgecallno;
624         
625         int pingid;                     /*!< Transmit PING request */
626         int lagid;                      /*!< Retransmit lag request */
627         int autoid;                     /*!< Auto hangup for Dialplan requestor */
628         int authid;                     /*!< Authentication rejection ID */
629         int authfail;                   /*!< Reason to report failure */
630         int initid;                     /*!< Initial peer auto-congest ID (based on qualified peers) */
631         int calling_ton;
632         int calling_tns;
633         int calling_pres;
634         int amaflags;
635         AST_LIST_HEAD_NOLOCK(, iax2_dpcache) dpentries;
636         struct ast_variable *vars;
637         /*! last received remote rr */
638         struct iax_rr remote_rr;
639         /*! Current base time: (just for stats) */
640         int min;
641         /*! Dropped frame count: (just for stats) */
642         int frames_dropped;
643         /*! received frame count: (just for stats) */
644         int frames_received;
645 };
646
647 /*!
648  * \brief a list of frames that may need to be retransmitted
649  *
650  * \note The contents of this list do not need to be explicitly destroyed
651  * on module unload.  This is because all active calls are destroyed, and
652  * all frames in this queue will get destroyed as a part of that process.
653  */
654 static AST_LIST_HEAD_STATIC(frame_queue, iax_frame);
655
656 /*!
657  * This module will get much higher performance when doing a lot of
658  * user and peer lookups if the number of buckets is increased from 1.
659  * However, to maintain old behavior for Asterisk 1.4, these are set to
660  * 1 by default.  When using multiple buckets, search order through these
661  * containers is considered random, so you will not be able to depend on
662  * the order the entires are specified in iax.conf for matching order. */
663 #ifdef LOW_MEMORY
664 #define MAX_PEER_BUCKETS 17
665 #else
666 #define MAX_PEER_BUCKETS 563
667 #endif
668 static struct ao2_container *peers;
669
670 #define MAX_USER_BUCKETS MAX_PEER_BUCKETS
671 static struct ao2_container *users;
672
673 static AST_LIST_HEAD_STATIC(firmwares, iax_firmware);
674
675 enum {
676         /*! Extension exists */
677         CACHE_FLAG_EXISTS      = (1 << 0),
678         /*! Extension is nonexistent */
679         CACHE_FLAG_NONEXISTENT = (1 << 1),
680         /*! Extension can exist */
681         CACHE_FLAG_CANEXIST    = (1 << 2),
682         /*! Waiting to hear back response */
683         CACHE_FLAG_PENDING     = (1 << 3),
684         /*! Timed out */
685         CACHE_FLAG_TIMEOUT     = (1 << 4),
686         /*! Request transmitted */
687         CACHE_FLAG_TRANSMITTED = (1 << 5),
688         /*! Timeout */
689         CACHE_FLAG_UNKNOWN     = (1 << 6),
690         /*! Matchmore */
691         CACHE_FLAG_MATCHMORE   = (1 << 7),
692 };
693
694 struct iax2_dpcache {
695         char peercontext[AST_MAX_CONTEXT];
696         char exten[AST_MAX_EXTENSION];
697         struct timeval orig;
698         struct timeval expiry;
699         int flags;
700         unsigned short callno;
701         int waiters[256];
702         AST_LIST_ENTRY(iax2_dpcache) cache_list;
703         AST_LIST_ENTRY(iax2_dpcache) peer_list;
704 };
705
706 static AST_LIST_HEAD_STATIC(dpcache, iax2_dpcache);
707
708 static void reg_source_db(struct iax2_peer *p);
709 static struct iax2_peer *realtime_peer(const char *peername, struct sockaddr_in *sin);
710
711 static int ast_cli_netstats(struct mansession *s, int fd, int limit_fmt);
712 static char *complete_iax2_show_peer(const char *line, const char *word, int pos, int state);
713 static char *complete_iax2_unregister(const char *line, const char *word, int pos, int state);
714
715 enum iax2_thread_iostate {
716         IAX_IOSTATE_IDLE,
717         IAX_IOSTATE_READY,
718         IAX_IOSTATE_PROCESSING,
719         IAX_IOSTATE_SCHEDREADY,
720 };
721
722 enum iax2_thread_type {
723         IAX_THREAD_TYPE_POOL,
724         IAX_THREAD_TYPE_DYNAMIC,
725 };
726
727 struct iax2_pkt_buf {
728         AST_LIST_ENTRY(iax2_pkt_buf) entry;
729         size_t len;
730         unsigned char buf[1];
731 };
732
733 struct iax2_thread {
734         AST_LIST_ENTRY(iax2_thread) list;
735         enum iax2_thread_type type;
736         enum iax2_thread_iostate iostate;
737 #ifdef SCHED_MULTITHREADED
738         void (*schedfunc)(const void *);
739         const void *scheddata;
740 #endif
741 #ifdef DEBUG_SCHED_MULTITHREAD
742         char curfunc[80];
743 #endif  
744         int actions;
745         pthread_t threadid;
746         int threadnum;
747         struct sockaddr_in iosin;
748         unsigned char readbuf[4096]; 
749         unsigned char *buf;
750         ssize_t buf_len;
751         size_t buf_size;
752         int iofd;
753         time_t checktime;
754         ast_mutex_t lock;
755         ast_cond_t cond;
756         unsigned int ready_for_signal:1;
757         /*! if this thread is processing a full frame,
758           some information about that frame will be stored
759           here, so we can avoid dispatching any more full
760           frames for that callno to other threads */
761         struct {
762                 unsigned short callno;
763                 struct sockaddr_in sin;
764                 unsigned char type;
765                 unsigned char csub;
766         } ffinfo;
767         /*! Queued up full frames for processing.  If more full frames arrive for
768          *  a call which this thread is already processing a full frame for, they
769          *  are queued up here. */
770         AST_LIST_HEAD_NOLOCK(, iax2_pkt_buf) full_frames;
771 };
772
773 /* Thread lists */
774 static AST_LIST_HEAD_STATIC(idle_list, iax2_thread);
775 static AST_LIST_HEAD_STATIC(active_list, iax2_thread);
776 static AST_LIST_HEAD_STATIC(dynamic_list, iax2_thread);
777
778 static void *iax2_process_thread(void *data);
779
780 static void signal_condition(ast_mutex_t *lock, ast_cond_t *cond)
781 {
782         ast_mutex_lock(lock);
783         ast_cond_signal(cond);
784         ast_mutex_unlock(lock);
785 }
786
787 static void iax_debug_output(const char *data)
788 {
789         if (iaxdebug)
790                 ast_verbose("%s", data);
791 }
792
793 static void iax_error_output(const char *data)
794 {
795         ast_log(LOG_WARNING, "%s", data);
796 }
797
798 static void __attribute__((format (printf, 1, 2))) jb_error_output(const char *fmt, ...)
799 {
800         va_list args;
801         char buf[1024];
802
803         va_start(args, fmt);
804         vsnprintf(buf, sizeof(buf), fmt, args);
805         va_end(args);
806
807         ast_log(LOG_ERROR, "%s", buf);
808 }
809
810 static void __attribute__((format (printf, 1, 2))) jb_warning_output(const char *fmt, ...)
811 {
812         va_list args;
813         char buf[1024];
814
815         va_start(args, fmt);
816         vsnprintf(buf, sizeof(buf), fmt, args);
817         va_end(args);
818
819         ast_log(LOG_WARNING, "%s", buf);
820 }
821
822 static void __attribute__((format (printf, 1, 2))) jb_debug_output(const char *fmt, ...)
823 {
824         va_list args;
825         char buf[1024];
826
827         va_start(args, fmt);
828         vsnprintf(buf, sizeof(buf), fmt, args);
829         va_end(args);
830
831         ast_verbose("%s", buf);
832 }
833
834 /*!
835  * \brief an array of iax2 pvt structures
836  *
837  * The container for active chan_iax2_pvt structures is implemented as an
838  * array for extremely quick direct access to the correct pvt structure
839  * based on the local call number.  The local call number is used as the
840  * index into the array where the associated pvt structure is stored.
841  */
842 static struct chan_iax2_pvt *iaxs[IAX_MAX_CALLS];
843
844 /*!
845  * \brief Another container of iax2_pvt structures
846  *
847  * Active IAX2 pvt structs are also stored in this container, if they are a part
848  * of an active call where we know the remote side's call number.  The reason
849  * for this is that incoming media frames do not contain our call number.  So,
850  * instead of having to iterate the entire iaxs array, we use this container to
851  * look up calls where the remote side is using a given call number.
852  */
853 static struct ao2_container *iax_peercallno_pvts;
854
855 /*!
856  * \brief chan_iax2_pvt structure locks
857  *
858  * These locks are used when accessing a pvt structure in the iaxs array.
859  * The index used here is the same as used in the iaxs array.  It is the
860  * local call number for the associated pvt struct.
861  */
862 static ast_mutex_t iaxsl[ARRAY_LEN(iaxs)];
863
864 /*!
865  * \brief The last time a call number was used
866  *
867  * It is important to know the last time that a call number was used locally so
868  * that it is not used again too soon.  The reason for this is the same as the
869  * reason that the TCP protocol state machine requires a "TIME WAIT" state.
870  *
871  * For example, say that a call is up.  Then, the remote side sends a HANGUP,
872  * which we respond to with an ACK.  However, there is no way to know whether
873  * the ACK made it there successfully.  If it were to get lost, the remote
874  * side may retransmit the HANGUP.  If in the meantime, this call number has
875  * been reused locally, given the right set of circumstances, this retransmitted
876  * HANGUP could potentially improperly hang up the new session.  So, to avoid
877  * this potential issue, we must wait a specified timeout period before reusing
878  * a local call number.
879  *
880  * The specified time that we must wait before reusing a local call number is
881  * defined as MIN_REUSE_TIME, with a default of 60 seconds.
882  */
883 static struct timeval lastused[ARRAY_LEN(iaxs)];
884
885 /* Flag to use with trunk calls, keeping these calls high up.  It halves our effective use
886    but keeps the division between trunked and non-trunked better. */
887 #define TRUNK_CALL_START        ARRAY_LEN(iaxs) / 2
888
889 static int maxtrunkcall = TRUNK_CALL_START;
890 static int maxnontrunkcall = 1;
891
892 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);
893 static int expire_registry(const void *data);
894 static int iax2_answer(struct ast_channel *c);
895 static int iax2_call(struct ast_channel *c, char *dest, int timeout);
896 static int iax2_devicestate(void *data);
897 static int iax2_digit_begin(struct ast_channel *c, char digit);
898 static int iax2_digit_end(struct ast_channel *c, char digit, unsigned int duration);
899 static int iax2_do_register(struct iax2_registry *reg);
900 static int iax2_fixup(struct ast_channel *oldchannel, struct ast_channel *newchan);
901 static int iax2_hangup(struct ast_channel *c);
902 static int iax2_indicate(struct ast_channel *c, int condition, const void *data, size_t datalen);
903 static int iax2_poke_peer(struct iax2_peer *peer, int heldcall);
904 static int iax2_provision(struct sockaddr_in *end, int sockfd, char *dest, const char *template, int force);
905 static int iax2_send(struct chan_iax2_pvt *pvt, struct ast_frame *f, unsigned int ts, int seqno, int now, int transfer, int final, int media);
906 static int iax2_sendhtml(struct ast_channel *c, int subclass, const char *data, int datalen);
907 static int iax2_sendimage(struct ast_channel *c, struct ast_frame *img);
908 static int iax2_sendtext(struct ast_channel *c, const char *text);
909 static int iax2_setoption(struct ast_channel *c, int option, void *data, int datalen);
910 static int iax2_transfer(struct ast_channel *c, const char *dest);
911 static int iax2_write(struct ast_channel *c, struct ast_frame *f);
912 static int send_trunk(struct iax2_trunk_peer *tpeer, struct timeval *now);
913 static int send_command(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
914 static int send_command_final(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
915 static int send_command_immediate(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
916 static int send_command_locked(unsigned short callno, char, int, unsigned int, const unsigned char *, int, int);
917 static int send_command_transfer(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int);
918 static int send_command_media(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int);
919 static struct ast_channel *iax2_request(const char *type, int format, void *data, int *cause);
920 static struct ast_frame *iax2_read(struct ast_channel *c);
921 static struct iax2_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly);
922 static struct iax2_user *build_user(const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly);
923 static void realtime_update_peer(const char *peername, struct sockaddr_in *sin, time_t regtime);
924 static void prune_peers(void);
925 static void *iax2_dup_variable_datastore(void *);
926 static void iax2_free_variable_datastore(void *);
927
928 static int acf_channel_read(struct ast_channel *chan, const char *funcname, char *preparse, char *buf, size_t buflen);
929 static int acf_channel_write(struct ast_channel *chan, const char *function, char *data, const char *value);
930
931 static const struct ast_channel_tech iax2_tech = {
932         .type = "IAX2",
933         .description = tdesc,
934         .capabilities = IAX_CAPABILITY_FULLBANDWIDTH,
935         .properties = AST_CHAN_TP_WANTSJITTER,
936         .requester = iax2_request,
937         .devicestate = iax2_devicestate,
938         .send_digit_begin = iax2_digit_begin,
939         .send_digit_end = iax2_digit_end,
940         .send_text = iax2_sendtext,
941         .send_image = iax2_sendimage,
942         .send_html = iax2_sendhtml,
943         .call = iax2_call,
944         .hangup = iax2_hangup,
945         .answer = iax2_answer,
946         .read = iax2_read,
947         .write = iax2_write,
948         .write_video = iax2_write,
949         .indicate = iax2_indicate,
950         .setoption = iax2_setoption,
951         .bridge = iax2_bridge,
952         .transfer = iax2_transfer,
953         .fixup = iax2_fixup,
954         .func_channel_read = acf_channel_read,
955         .func_channel_write = acf_channel_write,
956 };
957
958 static void mwi_event_cb(const struct ast_event *event, void *userdata)
959 {
960         /* The MWI subscriptions exist just so the core knows we care about those
961          * mailboxes.  However, we just grab the events out of the cache when it
962          * is time to send MWI, since it is only sent with a REGACK. */
963 }
964
965 /*! \brief Send manager event at call setup to link between Asterisk channel name
966         and IAX2 call identifiers */
967 static void iax2_ami_channelupdate(struct chan_iax2_pvt *pvt) 
968 {
969         manager_event(EVENT_FLAG_SYSTEM, "ChannelUpdate",
970                 "Channel: %s\r\nChanneltype: IAX2\r\nIAX2-callno-local: %d\r\nIAX2-callno-remote: %d\r\nIAX2-peer: %s\r\n",
971                 pvt->owner ? pvt->owner->name : "",
972                 pvt->callno, pvt->peercallno, pvt->peer ? pvt->peer : "");
973 }
974
975
976 static struct ast_datastore_info iax2_variable_datastore_info = {
977         .type = "IAX2_VARIABLE",
978         .duplicate = iax2_dup_variable_datastore,
979         .destroy = iax2_free_variable_datastore,
980 };
981
982 static void *iax2_dup_variable_datastore(void *old)
983 {
984         AST_LIST_HEAD(, ast_var_t) *oldlist = old, *newlist;
985         struct ast_var_t *oldvar, *newvar;
986
987         newlist = ast_calloc(sizeof(*newlist), 1);
988         if (!newlist) {
989                 ast_log(LOG_ERROR, "Unable to duplicate iax2 variables\n");
990                 return NULL;
991         }
992
993         AST_LIST_HEAD_INIT(newlist);
994         AST_LIST_LOCK(oldlist);
995         AST_LIST_TRAVERSE(oldlist, oldvar, entries) {
996                 newvar = ast_var_assign(ast_var_name(oldvar), ast_var_value(oldvar));
997                 if (newvar)
998                         AST_LIST_INSERT_TAIL(newlist, newvar, entries);
999                 else
1000                         ast_log(LOG_ERROR, "Unable to duplicate iax2 variable '%s'\n", ast_var_name(oldvar));
1001         }
1002         AST_LIST_UNLOCK(oldlist);
1003         return newlist;
1004 }
1005
1006 static void iax2_free_variable_datastore(void *old)
1007 {
1008         AST_LIST_HEAD(, ast_var_t) *oldlist = old;
1009         struct ast_var_t *oldvar;
1010
1011         AST_LIST_LOCK(oldlist);
1012         while ((oldvar = AST_LIST_REMOVE_HEAD(oldlist, entries))) {
1013                 ast_free(oldvar);
1014         }
1015         AST_LIST_UNLOCK(oldlist);
1016         AST_LIST_HEAD_DESTROY(oldlist);
1017         ast_free(oldlist);
1018 }
1019
1020
1021 /* WARNING: insert_idle_thread should only ever be called within the
1022  * context of an iax2_process_thread() thread.
1023  */
1024 static void insert_idle_thread(struct iax2_thread *thread)
1025 {
1026         if (thread->type == IAX_THREAD_TYPE_DYNAMIC) {
1027                 AST_LIST_LOCK(&dynamic_list);
1028                 AST_LIST_INSERT_TAIL(&dynamic_list, thread, list);
1029                 AST_LIST_UNLOCK(&dynamic_list);
1030         } else {
1031                 AST_LIST_LOCK(&idle_list);
1032                 AST_LIST_INSERT_TAIL(&idle_list, thread, list);
1033                 AST_LIST_UNLOCK(&idle_list);
1034         }
1035
1036         return;
1037 }
1038
1039 static struct iax2_thread *find_idle_thread(void)
1040 {
1041         struct iax2_thread *thread = NULL;
1042
1043         /* Pop the head of the idle list off */
1044         AST_LIST_LOCK(&idle_list);
1045         thread = AST_LIST_REMOVE_HEAD(&idle_list, list);
1046         AST_LIST_UNLOCK(&idle_list);
1047
1048         /* If we popped a thread off the idle list, just return it */
1049         if (thread) {
1050                 memset(&thread->ffinfo, 0, sizeof(thread->ffinfo));
1051                 return thread;
1052         }
1053
1054         /* Pop the head of the dynamic list off */
1055         AST_LIST_LOCK(&dynamic_list);
1056         thread = AST_LIST_REMOVE_HEAD(&dynamic_list, list);
1057         AST_LIST_UNLOCK(&dynamic_list);
1058
1059         /* If we popped a thread off the dynamic list, just return it */
1060         if (thread) {
1061                 memset(&thread->ffinfo, 0, sizeof(thread->ffinfo));
1062                 return thread;
1063         }
1064
1065         /* If we can't create a new dynamic thread for any reason, return no thread at all */
1066         if (iaxdynamicthreadcount >= iaxmaxthreadcount || !(thread = ast_calloc(1, sizeof(*thread))))
1067                 return NULL;
1068
1069         /* Set default values */
1070         thread->threadnum = ast_atomic_fetchadd_int(&iaxdynamicthreadcount, 1);
1071         thread->type = IAX_THREAD_TYPE_DYNAMIC;
1072
1073         /* Initialize lock and condition */
1074         ast_mutex_init(&thread->lock);
1075         ast_cond_init(&thread->cond, NULL);
1076
1077         /* Create thread and send it on it's way */
1078         if (ast_pthread_create_detached_background(&thread->threadid, NULL, iax2_process_thread, thread)) {
1079                 ast_cond_destroy(&thread->cond);
1080                 ast_mutex_destroy(&thread->lock);
1081                 ast_free(thread);
1082                 return NULL;
1083         }
1084
1085         /* this thread is not processing a full frame (since it is idle),
1086            so ensure that the field for the full frame call number is empty */
1087         memset(&thread->ffinfo, 0, sizeof(thread->ffinfo));
1088
1089         /* Wait for the thread to be ready before returning it to the caller */
1090         while (!thread->ready_for_signal)
1091                 usleep(1);
1092
1093         return thread;
1094 }
1095
1096 #ifdef SCHED_MULTITHREADED
1097 static int __schedule_action(void (*func)(const void *data), const void *data, const char *funcname)
1098 {
1099         struct iax2_thread *thread = NULL;
1100         static time_t lasterror;
1101         static time_t t;
1102
1103         thread = find_idle_thread();
1104
1105         if (thread != NULL) {
1106                 thread->schedfunc = func;
1107                 thread->scheddata = data;
1108                 thread->iostate = IAX_IOSTATE_SCHEDREADY;
1109 #ifdef DEBUG_SCHED_MULTITHREAD
1110                 ast_copy_string(thread->curfunc, funcname, sizeof(thread->curfunc));
1111 #endif
1112                 signal_condition(&thread->lock, &thread->cond);
1113                 return 0;
1114         }
1115         time(&t);
1116         if (t != lasterror) 
1117                 ast_debug(1, "Out of idle IAX2 threads for scheduling!\n");
1118         lasterror = t;
1119
1120         return -1;
1121 }
1122 #define schedule_action(func, data) __schedule_action(func, data, __PRETTY_FUNCTION__)
1123 #endif
1124
1125 static int iax2_sched_replace(int id, struct sched_context *con, int when, ast_sched_cb callback, const void *data)
1126 {
1127         AST_SCHED_REPLACE(id, con, when, callback, data);
1128         signal_condition(&sched_lock, &sched_cond);
1129
1130         return id;
1131 }
1132
1133 static int iax2_sched_add(struct sched_context *con, int when, ast_sched_cb callback, const void *data)
1134 {
1135         int res;
1136
1137         res = ast_sched_add(con, when, callback, data);
1138         signal_condition(&sched_lock, &sched_cond);
1139
1140         return res;
1141 }
1142
1143 static int send_ping(const void *data);
1144
1145 static void __send_ping(const void *data)
1146 {
1147         int callno = (long)data;
1148         ast_mutex_lock(&iaxsl[callno]);
1149         if (iaxs[callno] && iaxs[callno]->pingid != -1) {
1150                 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_PING, 0, NULL, 0, -1);
1151                 iaxs[callno]->pingid = iax2_sched_add(sched, ping_time * 1000, send_ping, data);
1152         }
1153         ast_mutex_unlock(&iaxsl[callno]);
1154 }
1155
1156 static int send_ping(const void *data)
1157 {
1158 #ifdef SCHED_MULTITHREADED
1159         if (schedule_action(__send_ping, data))
1160 #endif          
1161                 __send_ping(data);
1162         return 0;
1163 }
1164
1165 static int get_encrypt_methods(const char *s)
1166 {
1167         int e;
1168         if (!strcasecmp(s, "aes128"))
1169                 e = IAX_ENCRYPT_AES128;
1170         else if (ast_true(s))
1171                 e = IAX_ENCRYPT_AES128;
1172         else
1173                 e = 0;
1174         return e;
1175 }
1176
1177 static int send_lagrq(const void *data);
1178
1179 static void __send_lagrq(const void *data)
1180 {
1181         int callno = (long)data;
1182         /* Ping only if it's real not if it's bridged */
1183         ast_mutex_lock(&iaxsl[callno]);
1184         if (iaxs[callno] && iaxs[callno]->lagid > -1) {
1185                 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_LAGRQ, 0, NULL, 0, -1);
1186                 iaxs[callno]->lagid = iax2_sched_add(sched, lagrq_time * 1000, send_lagrq, data);
1187         }
1188         ast_mutex_unlock(&iaxsl[callno]);
1189 }
1190
1191 static int send_lagrq(const void *data)
1192 {
1193 #ifdef SCHED_MULTITHREADED
1194         if (schedule_action(__send_lagrq, data))
1195 #endif          
1196                 __send_lagrq(data);
1197         return 0;
1198 }
1199
1200 static unsigned char compress_subclass(int subclass)
1201 {
1202         int x;
1203         int power=-1;
1204         /* If it's 128 or smaller, just return it */
1205         if (subclass < IAX_FLAG_SC_LOG)
1206                 return subclass;
1207         /* Otherwise find its power */
1208         for (x = 0; x < IAX_MAX_SHIFT; x++) {
1209                 if (subclass & (1 << x)) {
1210                         if (power > -1) {
1211                                 ast_log(LOG_WARNING, "Can't compress subclass %d\n", subclass);
1212                                 return 0;
1213                         } else
1214                                 power = x;
1215                 }
1216         }
1217         return power | IAX_FLAG_SC_LOG;
1218 }
1219
1220 static int uncompress_subclass(unsigned char csub)
1221 {
1222         /* If the SC_LOG flag is set, return 2^csub otherwise csub */
1223         if (csub & IAX_FLAG_SC_LOG) {
1224                 /* special case for 'compressed' -1 */
1225                 if (csub == 0xff)
1226                         return -1;
1227                 else
1228                         return 1 << (csub & ~IAX_FLAG_SC_LOG & IAX_MAX_SHIFT);
1229         }
1230         else
1231                 return csub;
1232 }
1233
1234 /*!
1235  * \note The only member of the peer passed here guaranteed to be set is the name field
1236  */
1237 static int peer_hash_cb(const void *obj, const int flags)
1238 {
1239         const struct iax2_peer *peer = obj;
1240
1241         return ast_str_hash(peer->name);
1242 }
1243
1244 /*!
1245  * \note The only member of the peer passed here guaranteed to be set is the name field
1246  */
1247 static int peer_cmp_cb(void *obj, void *arg, int flags)
1248 {
1249         struct iax2_peer *peer = obj, *peer2 = arg;
1250
1251         return !strcasecmp(peer->name, peer2->name) ? CMP_MATCH : 0;
1252 }
1253
1254 /*!
1255  * \note The only member of the user passed here guaranteed to be set is the name field
1256  */
1257 static int user_hash_cb(const void *obj, const int flags)
1258 {
1259         const struct iax2_user *user = obj;
1260
1261         return ast_str_hash(user->name);
1262 }
1263
1264 /*!
1265  * \note The only member of the user passed here guaranteed to be set is the name field
1266  */
1267 static int user_cmp_cb(void *obj, void *arg, int flags)
1268 {
1269         struct iax2_user *user = obj, *user2 = arg;
1270
1271         return !strcasecmp(user->name, user2->name) ? CMP_MATCH : 0;
1272 }
1273
1274 /*!
1275  * \note This funtion calls realtime_peer -> reg_source_db -> iax2_poke_peer -> find_callno,
1276  *       so do not call it with a pvt lock held.
1277  */
1278 static struct iax2_peer *find_peer(const char *name, int realtime) 
1279 {
1280         struct iax2_peer *peer = NULL;
1281         struct iax2_peer tmp_peer = {
1282                 .name = name,
1283         };
1284
1285         peer = ao2_find(peers, &tmp_peer, OBJ_POINTER);
1286
1287         /* Now go for realtime if applicable */
1288         if(!peer && realtime)
1289                 peer = realtime_peer(name, NULL);
1290
1291         return peer;
1292 }
1293
1294 static struct iax2_peer *peer_ref(struct iax2_peer *peer)
1295 {
1296         ao2_ref(peer, +1);
1297         return peer;
1298 }
1299
1300 static inline struct iax2_peer *peer_unref(struct iax2_peer *peer)
1301 {
1302         ao2_ref(peer, -1);
1303         return NULL;
1304 }
1305
1306 static inline struct iax2_user *user_ref(struct iax2_user *user)
1307 {
1308         ao2_ref(user, +1);
1309         return user;
1310 }
1311
1312 static inline struct iax2_user *user_unref(struct iax2_user *user)
1313 {
1314         ao2_ref(user, -1);
1315         return NULL;
1316 }
1317
1318 static int iax2_getpeername(struct sockaddr_in sin, char *host, int len)
1319 {
1320         struct iax2_peer *peer = NULL;
1321         int res = 0;
1322         struct ao2_iterator i;
1323
1324         i = ao2_iterator_init(peers, 0);
1325         while ((peer = ao2_iterator_next(&i))) {
1326                 if ((peer->addr.sin_addr.s_addr == sin.sin_addr.s_addr) &&
1327                     (peer->addr.sin_port == sin.sin_port)) {
1328                         ast_copy_string(host, peer->name, len);
1329                         peer_unref(peer);
1330                         res = 1;
1331                         break;
1332                 }
1333                 peer_unref(peer);
1334         }
1335
1336         if (!peer) {
1337                 peer = realtime_peer(NULL, &sin);
1338                 if (peer) {
1339                         ast_copy_string(host, peer->name, len);
1340                         peer_unref(peer);
1341                         res = 1;
1342                 }
1343         }
1344
1345         return res;
1346 }
1347
1348 static void iax2_destroy_helper(struct chan_iax2_pvt *pvt)
1349 {
1350         /* Decrement AUTHREQ count if needed */
1351         if (ast_test_flag(pvt, IAX_MAXAUTHREQ)) {
1352                 struct iax2_user *user;
1353                 struct iax2_user tmp_user = {
1354                         .name = pvt->username,
1355                 };
1356
1357                 user = ao2_find(users, &tmp_user, OBJ_POINTER);
1358                 if (user) {
1359                         ast_atomic_fetchadd_int(&user->curauthreq, -1);
1360                         user_unref(user);       
1361                 }
1362
1363                 ast_clear_flag(pvt, IAX_MAXAUTHREQ);
1364         }
1365         /* No more pings or lagrq's */
1366         AST_SCHED_DEL(sched, pvt->pingid);
1367         AST_SCHED_DEL(sched, pvt->lagid);
1368         AST_SCHED_DEL(sched, pvt->autoid);
1369         AST_SCHED_DEL(sched, pvt->authid);
1370         AST_SCHED_DEL(sched, pvt->initid);
1371         AST_SCHED_DEL(sched, pvt->jbid);
1372 }
1373
1374 static void iax2_frame_free(struct iax_frame *fr)
1375 {
1376         AST_SCHED_DEL(sched, fr->retrans);
1377         iax_frame_free(fr);
1378 }
1379
1380 static void pvt_destructor(void *obj)
1381 {
1382         struct chan_iax2_pvt *pvt = obj;
1383         struct iax_frame *cur = NULL;
1384
1385         iax2_destroy_helper(pvt);
1386
1387         /* Already gone */
1388         ast_set_flag(pvt, IAX_ALREADYGONE);     
1389
1390         AST_LIST_LOCK(&frame_queue);
1391         AST_LIST_TRAVERSE(&frame_queue, cur, list) {
1392                 /* Cancel any pending transmissions */
1393                 if (cur->callno == pvt->callno) { 
1394                         cur->retries = -1;
1395                 }
1396         }
1397         AST_LIST_UNLOCK(&frame_queue);
1398
1399         if (pvt->reg) {
1400                 pvt->reg->callno = 0;
1401         }
1402
1403         if (!pvt->owner) {
1404                 jb_frame frame;
1405                 if (pvt->vars) {
1406                     ast_variables_destroy(pvt->vars);
1407                     pvt->vars = NULL;
1408                 }
1409
1410                 while (jb_getall(pvt->jb, &frame) == JB_OK) {
1411                         iax2_frame_free(frame.data);
1412                 }
1413
1414                 jb_destroy(pvt->jb);
1415                 ast_string_field_free_memory(pvt);
1416         }
1417 }
1418
1419 static struct chan_iax2_pvt *new_iax(struct sockaddr_in *sin, const char *host)
1420 {
1421         struct chan_iax2_pvt *tmp;
1422         jb_conf jbconf;
1423
1424         if (!(tmp = ao2_alloc(sizeof(*tmp), pvt_destructor))) {
1425                 return NULL;
1426         }
1427
1428         if (ast_string_field_init(tmp, 32)) {
1429                 ao2_ref(tmp, -1);
1430                 tmp = NULL;
1431                 return NULL;
1432         }
1433                 
1434         tmp->prefs = prefs;
1435         tmp->pingid = -1;
1436         tmp->lagid = -1;
1437         tmp->autoid = -1;
1438         tmp->authid = -1;
1439         tmp->initid = -1;
1440
1441         ast_string_field_set(tmp,exten, "s");
1442         ast_string_field_set(tmp,host, host);
1443
1444         tmp->jb = jb_new();
1445         tmp->jbid = -1;
1446         jbconf.max_jitterbuf = maxjitterbuffer;
1447         jbconf.resync_threshold = resyncthreshold;
1448         jbconf.max_contig_interp = maxjitterinterps;
1449         jbconf.target_extra = jittertargetextra;
1450         jb_setconf(tmp->jb,&jbconf);
1451
1452         AST_LIST_HEAD_INIT_NOLOCK(&tmp->dpentries);
1453
1454         return tmp;
1455 }
1456
1457 static struct iax_frame *iaxfrdup2(struct iax_frame *fr)
1458 {
1459         struct iax_frame *new = iax_frame_new(DIRECTION_INGRESS, fr->af.datalen, fr->cacheable);
1460         if (new) {
1461                 size_t afdatalen = new->afdatalen;
1462                 memcpy(new, fr, sizeof(*new));
1463                 iax_frame_wrap(new, &fr->af);
1464                 new->afdatalen = afdatalen;
1465                 new->data = NULL;
1466                 new->datalen = 0;
1467                 new->direction = DIRECTION_INGRESS;
1468                 new->retrans = -1;
1469         }
1470         return new;
1471 }
1472
1473 #define NEW_PREVENT     0
1474 #define NEW_ALLOW       1
1475 #define NEW_FORCE       2
1476
1477 static int match(struct sockaddr_in *sin, unsigned short callno, unsigned short dcallno, const struct chan_iax2_pvt *cur, int full_frame)
1478 {
1479         if ((cur->addr.sin_addr.s_addr == sin->sin_addr.s_addr) &&
1480                 (cur->addr.sin_port == sin->sin_port)) {
1481                 /* This is the main host */
1482                 if ( (cur->peercallno == 0 || cur->peercallno == callno) &&
1483                          (full_frame ? dcallno == cur->callno : 1) ) {
1484                         /* That's us.  Be sure we keep track of the peer call number */
1485                         return 1;
1486                 }
1487         }
1488         if ((cur->transfer.sin_addr.s_addr == sin->sin_addr.s_addr) &&
1489             (cur->transfer.sin_port == sin->sin_port) && (cur->transferring)) {
1490                 /* We're transferring */
1491                 if ((dcallno == cur->callno) || (cur->transferring == TRANSFER_NONE && cur->transfercallno == callno))
1492                         return 1;
1493         }
1494         return 0;
1495 }
1496
1497 static void update_max_trunk(void)
1498 {
1499         int max = TRUNK_CALL_START;
1500         int x;
1501
1502         /* XXX Prolly don't need locks here XXX */
1503         for (x = TRUNK_CALL_START; x < ARRAY_LEN(iaxs) - 1; x++) {
1504                 if (iaxs[x]) {
1505                         max = x + 1;
1506                 }
1507         }
1508
1509         maxtrunkcall = max;
1510         if (iaxdebug)
1511                 ast_debug(1, "New max trunk callno is %d\n", max);
1512 }
1513
1514 static void update_max_nontrunk(void)
1515 {
1516         int max = 1;
1517         int x;
1518         /* XXX Prolly don't need locks here XXX */
1519         for (x=1;x<TRUNK_CALL_START - 1; x++) {
1520                 if (iaxs[x])
1521                         max = x + 1;
1522         }
1523         maxnontrunkcall = max;
1524         if (iaxdebug)
1525                 ast_debug(1, "New max nontrunk callno is %d\n", max);
1526 }
1527
1528 static int make_trunk(unsigned short callno, int locked)
1529 {
1530         int x;
1531         int res= 0;
1532         struct timeval now = ast_tvnow();
1533         if (iaxs[callno]->oseqno) {
1534                 ast_log(LOG_WARNING, "Can't make trunk once a call has started!\n");
1535                 return -1;
1536         }
1537         if (callno & TRUNK_CALL_START) {
1538                 ast_log(LOG_WARNING, "Call %d is already a trunk\n", callno);
1539                 return -1;
1540         }
1541         for (x = TRUNK_CALL_START; x < ARRAY_LEN(iaxs) - 1; x++) {
1542                 ast_mutex_lock(&iaxsl[x]);
1543                 if (!iaxs[x] && ((now.tv_sec - lastused[x].tv_sec) > MIN_REUSE_TIME)) {
1544                         iaxs[x] = iaxs[callno];
1545                         iaxs[x]->callno = x;
1546                         iaxs[callno] = NULL;
1547                         /* Update the two timers that should have been started */
1548                         iaxs[x]->pingid = iax2_sched_replace(iaxs[x]->pingid, sched, 
1549                                 ping_time * 1000, send_ping, (void *)(long)x);
1550                         iaxs[x]->lagid = iax2_sched_replace(iaxs[x]->lagid, sched, 
1551                                 lagrq_time * 1000, send_lagrq, (void *)(long)x);
1552                         if (locked)
1553                                 ast_mutex_unlock(&iaxsl[callno]);
1554                         res = x;
1555                         if (!locked)
1556                                 ast_mutex_unlock(&iaxsl[x]);
1557                         break;
1558                 }
1559                 ast_mutex_unlock(&iaxsl[x]);
1560         }
1561         if (x >= ARRAY_LEN(iaxs) - 1) {
1562                 ast_log(LOG_WARNING, "Unable to trunk call: Insufficient space\n");
1563                 return -1;
1564         }
1565         ast_debug(1, "Made call %d into trunk call %d\n", callno, x);
1566         /* We move this call from a non-trunked to a trunked call */
1567         update_max_trunk();
1568         update_max_nontrunk();
1569         return res;
1570 }
1571
1572 static void store_by_peercallno(struct chan_iax2_pvt *pvt)
1573 {
1574         if (!pvt->peercallno) {
1575                 ast_log(LOG_ERROR, "This should not be called without a peer call number.\n");
1576                 return;
1577         }
1578
1579         ao2_link(iax_peercallno_pvts, pvt);
1580 }
1581
1582 static void remove_by_peercallno(struct chan_iax2_pvt *pvt)
1583 {
1584         if (!pvt->peercallno) {
1585                 ast_log(LOG_ERROR, "This should not be called without a peer call number.\n");
1586                 return;
1587         }
1588
1589         ao2_unlink(iax_peercallno_pvts, pvt);
1590 }
1591
1592 /*
1593  * \note Calling this function while holding another pvt lock can cause a deadlock.
1594  */
1595 static int __find_callno(unsigned short callno, unsigned short dcallno, struct sockaddr_in *sin, int new, int sockfd, int return_locked, int full_frame)
1596 {
1597         int res = 0;
1598         int x;
1599         struct timeval now;
1600         char host[80];
1601
1602         if (new <= NEW_ALLOW) {
1603                 if (callno) {
1604                         struct chan_iax2_pvt *pvt;
1605                         struct chan_iax2_pvt tmp_pvt = {
1606                                 .callno = dcallno,
1607                                 .peercallno = callno,
1608                                 /* hack!! */
1609                                 .frames_received = full_frame,
1610                         };
1611
1612                         memcpy(&tmp_pvt.addr, sin, sizeof(tmp_pvt.addr));
1613
1614                         if ((pvt = ao2_find(iax_peercallno_pvts, &tmp_pvt, OBJ_POINTER))) {
1615                                 if (return_locked) {
1616                                         ast_mutex_lock(&iaxsl[pvt->callno]);
1617                                 }
1618                                 res = pvt->callno;
1619                                 ao2_ref(pvt, -1);
1620                                 pvt = NULL;
1621                                 return res;
1622                         }
1623                 }
1624
1625                 for (x = 1; !res && x < maxnontrunkcall; x++) {
1626                         ast_mutex_lock(&iaxsl[x]);
1627                         if (iaxs[x]) {
1628                                 /* Look for an exact match */
1629                                 if (match(sin, callno, dcallno, iaxs[x], full_frame)) {
1630                                         res = x;
1631                                 }
1632                         }
1633                         if (!res || !return_locked)
1634                                 ast_mutex_unlock(&iaxsl[x]);
1635                 }
1636                 for (x = TRUNK_CALL_START; !res && x < maxtrunkcall; x++) {
1637                         ast_mutex_lock(&iaxsl[x]);
1638                         if (iaxs[x]) {
1639                                 /* Look for an exact match */
1640                                 if (match(sin, callno, dcallno, iaxs[x], full_frame)) {
1641                                         res = x;
1642                                 }
1643                         }
1644                         if (!res || !return_locked)
1645                                 ast_mutex_unlock(&iaxsl[x]);
1646                 }
1647         }
1648         if (!res && (new >= NEW_ALLOW)) {
1649                 int start, found = 0;
1650
1651                 /* It may seem odd that we look through the peer list for a name for
1652                  * this *incoming* call.  Well, it is weird.  However, users don't
1653                  * have an IP address/port number that we can match against.  So,
1654                  * this is just checking for a peer that has that IP/port and
1655                  * assuming that we have a user of the same name.  This isn't always
1656                  * correct, but it will be changed if needed after authentication. */
1657                 if (!iax2_getpeername(*sin, host, sizeof(host)))
1658                         snprintf(host, sizeof(host), "%s:%d", ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
1659
1660                 now = ast_tvnow();
1661                 start = 1 + (ast_random() % (TRUNK_CALL_START - 1));
1662                 for (x = start; 1; x++) {
1663                         if (x == TRUNK_CALL_START) {
1664                                 x = 0;
1665                                 continue;
1666                         }
1667
1668                         /* Find first unused call number that hasn't been used in a while */
1669                         ast_mutex_lock(&iaxsl[x]);
1670                         if (!iaxs[x] && ((now.tv_sec - lastused[x].tv_sec) > MIN_REUSE_TIME)) {
1671                                 found = 1;
1672                                 break;
1673                         }
1674                         ast_mutex_unlock(&iaxsl[x]);
1675                         
1676                         if (x == start - 1) {
1677                                 break;
1678                         }
1679                 }
1680                 /* We've still got lock held if we found a spot */
1681                 if (x == start - 1 && !found) {
1682                         ast_log(LOG_WARNING, "No more space\n");
1683                         return 0;
1684                 }
1685                 iaxs[x] = new_iax(sin, host);
1686                 update_max_nontrunk();
1687                 if (iaxs[x]) {
1688                         if (iaxdebug)
1689                                 ast_debug(1, "Creating new call structure %d\n", x);
1690                         iaxs[x]->sockfd = sockfd;
1691                         iaxs[x]->addr.sin_port = sin->sin_port;
1692                         iaxs[x]->addr.sin_family = sin->sin_family;
1693                         iaxs[x]->addr.sin_addr.s_addr = sin->sin_addr.s_addr;
1694                         iaxs[x]->peercallno = callno;
1695                         iaxs[x]->callno = x;
1696                         iaxs[x]->pingtime = DEFAULT_RETRY_TIME;
1697                         iaxs[x]->expiry = min_reg_expire;
1698                         iaxs[x]->pingid = iax2_sched_add(sched, ping_time * 1000, send_ping, (void *)(long)x);
1699                         iaxs[x]->lagid = iax2_sched_add(sched, lagrq_time * 1000, send_lagrq, (void *)(long)x);
1700                         iaxs[x]->amaflags = amaflags;
1701                         ast_copy_flags(iaxs[x], (&globalflags), IAX_NOTRANSFER | IAX_TRANSFERMEDIA | IAX_USEJITTERBUF | IAX_FORCEJITTERBUF);
1702                         
1703                         ast_string_field_set(iaxs[x], accountcode, accountcode);
1704                         ast_string_field_set(iaxs[x], mohinterpret, mohinterpret);
1705                         ast_string_field_set(iaxs[x], mohsuggest, mohsuggest);
1706                         ast_string_field_set(iaxs[x], parkinglot, default_parkinglot);
1707
1708                         if (iaxs[x]->peercallno) {
1709                                 store_by_peercallno(iaxs[x]);
1710                         }
1711                 } else {
1712                         ast_log(LOG_WARNING, "Out of resources\n");
1713                         ast_mutex_unlock(&iaxsl[x]);
1714                         return 0;
1715                 }
1716                 if (!return_locked)
1717                         ast_mutex_unlock(&iaxsl[x]);
1718                 res = x;
1719         }
1720         return res;
1721 }
1722
1723 static int find_callno(unsigned short callno, unsigned short dcallno, struct sockaddr_in *sin, int new, int sockfd, int full_frame) {
1724
1725         return __find_callno(callno, dcallno, sin, new, sockfd, 0, full_frame);
1726 }
1727
1728 static int find_callno_locked(unsigned short callno, unsigned short dcallno, struct sockaddr_in *sin, int new, int sockfd, int full_frame) {
1729
1730         return __find_callno(callno, dcallno, sin, new, sockfd, 1, full_frame);
1731 }
1732
1733 /*!
1734  * \brief Queue a frame to a call's owning asterisk channel
1735  *
1736  * \pre This function assumes that iaxsl[callno] is locked when called.
1737  *
1738  * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
1739  * was valid before calling it, it may no longer be valid after calling it.
1740  * This function may unlock and lock the mutex associated with this callno,
1741  * meaning that another thread may grab it and destroy the call.
1742  */
1743 static int iax2_queue_frame(int callno, struct ast_frame *f)
1744 {
1745         for (;;) {
1746                 if (iaxs[callno] && iaxs[callno]->owner) {
1747                         if (ast_channel_trylock(iaxs[callno]->owner)) {
1748                                 /* Avoid deadlock by pausing and trying again */
1749                                 ast_mutex_unlock(&iaxsl[callno]);
1750                                 usleep(1);
1751                                 ast_mutex_lock(&iaxsl[callno]);
1752                         } else {
1753                                 ast_queue_frame(iaxs[callno]->owner, f);
1754                                 ast_channel_unlock(iaxs[callno]->owner);
1755                                 break;
1756                         }
1757                 } else
1758                         break;
1759         }
1760         return 0;
1761 }
1762
1763 /*!
1764  * \brief Queue a hangup frame on the ast_channel owner
1765  *
1766  * This function queues a hangup frame on the owner of the IAX2 pvt struct that
1767  * is active for the given call number.
1768  *
1769  * \pre Assumes lock for callno is already held.
1770  *
1771  * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
1772  * was valid before calling it, it may no longer be valid after calling it.
1773  * This function may unlock and lock the mutex associated with this callno,
1774  * meaning that another thread may grab it and destroy the call.
1775  */
1776 static int iax2_queue_hangup(int callno)
1777 {
1778         for (;;) {
1779                 if (iaxs[callno] && iaxs[callno]->owner) {
1780                         if (ast_channel_trylock(iaxs[callno]->owner)) {
1781                                 /* Avoid deadlock by pausing and trying again */
1782                                 ast_mutex_unlock(&iaxsl[callno]);
1783                                 usleep(1);
1784                                 ast_mutex_lock(&iaxsl[callno]);
1785                         } else {
1786                                 ast_queue_hangup(iaxs[callno]->owner);
1787                                 ast_channel_unlock(iaxs[callno]->owner);
1788                                 break;
1789                         }
1790                 } else
1791                         break;
1792         }
1793         return 0;
1794 }
1795
1796 /*!
1797  * \brief Queue a control frame on the ast_channel owner
1798  *
1799  * This function queues a control frame on the owner of the IAX2 pvt struct that
1800  * is active for the given call number.
1801  *
1802  * \pre Assumes lock for callno is already held.
1803  *
1804  * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
1805  * was valid before calling it, it may no longer be valid after calling it.
1806  * This function may unlock and lock the mutex associated with this callno,
1807  * meaning that another thread may grab it and destroy the call.
1808  */
1809 static int iax2_queue_control_data(int callno, 
1810         enum ast_control_frame_type control, const void *data, size_t datalen)
1811 {
1812         for (;;) {
1813                 if (iaxs[callno] && iaxs[callno]->owner) {
1814                         if (ast_channel_trylock(iaxs[callno]->owner)) {
1815                                 /* Avoid deadlock by pausing and trying again */
1816                                 ast_mutex_unlock(&iaxsl[callno]);
1817                                 usleep(1);
1818                                 ast_mutex_lock(&iaxsl[callno]);
1819                         } else {
1820                                 ast_queue_control_data(iaxs[callno]->owner, control, data, datalen);
1821                                 ast_channel_unlock(iaxs[callno]->owner);
1822                                 break;
1823                         }
1824                 } else
1825                         break;
1826         }
1827         return 0;
1828 }
1829 static void destroy_firmware(struct iax_firmware *cur)
1830 {
1831         /* Close firmware */
1832         if (cur->fwh) {
1833                 munmap((void*)cur->fwh, ntohl(cur->fwh->datalen) + sizeof(*(cur->fwh)));
1834         }
1835         close(cur->fd);
1836         ast_free(cur);
1837 }
1838
1839 static int try_firmware(char *s)
1840 {
1841         struct stat stbuf;
1842         struct iax_firmware *cur = NULL;
1843         int ifd, fd, res, len, chunk;
1844         struct ast_iax2_firmware_header *fwh, fwh2;
1845         struct MD5Context md5;
1846         unsigned char sum[16], buf[1024];
1847         char *s2, *last;
1848
1849         if (!(s2 = alloca(strlen(s) + 100))) {
1850                 ast_log(LOG_WARNING, "Alloca failed!\n");
1851                 return -1;
1852         }
1853
1854         last = strrchr(s, '/');
1855         if (last)
1856                 last++;
1857         else
1858                 last = s;
1859
1860         snprintf(s2, strlen(s) + 100, "/var/tmp/%s-%ld", last, (unsigned long)ast_random());
1861
1862         if ((res = stat(s, &stbuf) < 0)) {
1863                 ast_log(LOG_WARNING, "Failed to stat '%s': %s\n", s, strerror(errno));
1864                 return -1;
1865         }
1866
1867         /* Make sure it's not a directory */
1868         if (S_ISDIR(stbuf.st_mode))
1869                 return -1;
1870         ifd = open(s, O_RDONLY);
1871         if (ifd < 0) {
1872                 ast_log(LOG_WARNING, "Cannot open '%s': %s\n", s, strerror(errno));
1873                 return -1;
1874         }
1875         fd = open(s2, O_RDWR | O_CREAT | O_EXCL, AST_FILE_MODE);
1876         if (fd < 0) {
1877                 ast_log(LOG_WARNING, "Cannot open '%s' for writing: %s\n", s2, strerror(errno));
1878                 close(ifd);
1879                 return -1;
1880         }
1881         /* Unlink our newly created file */
1882         unlink(s2);
1883         
1884         /* Now copy the firmware into it */
1885         len = stbuf.st_size;
1886         while(len) {
1887                 chunk = len;
1888                 if (chunk > sizeof(buf))
1889                         chunk = sizeof(buf);
1890                 res = read(ifd, buf, chunk);
1891                 if (res != chunk) {
1892                         ast_log(LOG_WARNING, "Only read %d of %d bytes of data :(: %s\n", res, chunk, strerror(errno));
1893                         close(ifd);
1894                         close(fd);
1895                         return -1;
1896                 }
1897                 res = write(fd, buf, chunk);
1898                 if (res != chunk) {
1899                         ast_log(LOG_WARNING, "Only write %d of %d bytes of data :(: %s\n", res, chunk, strerror(errno));
1900                         close(ifd);
1901                         close(fd);
1902                         return -1;
1903                 }
1904                 len -= chunk;
1905         }
1906         close(ifd);
1907         /* Return to the beginning */
1908         lseek(fd, 0, SEEK_SET);
1909         if ((res = read(fd, &fwh2, sizeof(fwh2))) != sizeof(fwh2)) {
1910                 ast_log(LOG_WARNING, "Unable to read firmware header in '%s'\n", s);
1911                 close(fd);
1912                 return -1;
1913         }
1914         if (ntohl(fwh2.magic) != IAX_FIRMWARE_MAGIC) {
1915                 ast_log(LOG_WARNING, "'%s' is not a valid firmware file\n", s);
1916                 close(fd);
1917                 return -1;
1918         }
1919         if (ntohl(fwh2.datalen) != (stbuf.st_size - sizeof(fwh2))) {
1920                 ast_log(LOG_WARNING, "Invalid data length in firmware '%s'\n", s);
1921                 close(fd);
1922                 return -1;
1923         }
1924         if (fwh2.devname[sizeof(fwh2.devname) - 1] || ast_strlen_zero((char *)fwh2.devname)) {
1925                 ast_log(LOG_WARNING, "No or invalid device type specified for '%s'\n", s);
1926                 close(fd);
1927                 return -1;
1928         }
1929         fwh = (struct ast_iax2_firmware_header*)mmap(NULL, stbuf.st_size, PROT_READ, MAP_PRIVATE, fd, 0); 
1930         if (fwh == (void *) -1) {
1931                 ast_log(LOG_WARNING, "mmap failed: %s\n", strerror(errno));
1932                 close(fd);
1933                 return -1;
1934         }
1935         MD5Init(&md5);
1936         MD5Update(&md5, fwh->data, ntohl(fwh->datalen));
1937         MD5Final(sum, &md5);
1938         if (memcmp(sum, fwh->chksum, sizeof(sum))) {
1939                 ast_log(LOG_WARNING, "Firmware file '%s' fails checksum\n", s);
1940                 munmap((void*)fwh, stbuf.st_size);
1941                 close(fd);
1942                 return -1;
1943         }
1944
1945         AST_LIST_TRAVERSE(&firmwares, cur, list) {
1946                 if (!strcmp((char *)cur->fwh->devname, (char *)fwh->devname)) {
1947                         /* Found a candidate */
1948                         if (cur->dead || (ntohs(cur->fwh->version) < ntohs(fwh->version)))
1949                                 /* The version we have on loaded is older, load this one instead */
1950                                 break;
1951                         /* This version is no newer than what we have.  Don't worry about it.
1952                            We'll consider it a proper load anyhow though */
1953                         munmap((void*)fwh, stbuf.st_size);
1954                         close(fd);
1955                         return 0;
1956                 }
1957         }
1958         
1959         if (!cur && ((cur = ast_calloc(1, sizeof(*cur))))) {
1960                 cur->fd = -1;
1961                 AST_LIST_INSERT_TAIL(&firmwares, cur, list);
1962         }
1963         
1964         if (cur) {
1965                 if (cur->fwh)
1966                         munmap((void*)cur->fwh, cur->mmaplen);
1967                 if (cur->fd > -1)
1968                         close(cur->fd);
1969                 cur->fwh = fwh;
1970                 cur->fd = fd;
1971                 cur->mmaplen = stbuf.st_size;
1972                 cur->dead = 0;
1973         }
1974         
1975         return 0;
1976 }
1977
1978 static int iax_check_version(char *dev)
1979 {
1980         int res = 0;
1981         struct iax_firmware *cur = NULL;
1982
1983         if (ast_strlen_zero(dev))
1984                 return 0;
1985
1986         AST_LIST_LOCK(&firmwares);
1987         AST_LIST_TRAVERSE(&firmwares, cur, list) {
1988                 if (!strcmp(dev, (char *)cur->fwh->devname)) {
1989                         res = ntohs(cur->fwh->version);
1990                         break;
1991                 }
1992         }
1993         AST_LIST_UNLOCK(&firmwares);
1994
1995         return res;
1996 }
1997
1998 static int iax_firmware_append(struct iax_ie_data *ied, const unsigned char *dev, unsigned int desc)
1999 {
2000         int res = -1;
2001         unsigned int bs = desc & 0xff;
2002         unsigned int start = (desc >> 8) & 0xffffff;
2003         unsigned int bytes;
2004         struct iax_firmware *cur;
2005
2006         if (ast_strlen_zero((char *)dev) || !bs)
2007                 return -1;
2008
2009         start *= bs;
2010         
2011         AST_LIST_LOCK(&firmwares);
2012         AST_LIST_TRAVERSE(&firmwares, cur, list) {
2013                 if (strcmp((char *)dev, (char *)cur->fwh->devname))
2014                         continue;
2015                 iax_ie_append_int(ied, IAX_IE_FWBLOCKDESC, desc);
2016                 if (start < ntohl(cur->fwh->datalen)) {
2017                         bytes = ntohl(cur->fwh->datalen) - start;
2018                         if (bytes > bs)
2019                                 bytes = bs;
2020                         iax_ie_append_raw(ied, IAX_IE_FWBLOCKDATA, cur->fwh->data + start, bytes);
2021                 } else {
2022                         bytes = 0;
2023                         iax_ie_append(ied, IAX_IE_FWBLOCKDATA);
2024                 }
2025                 if (bytes == bs)
2026                         res = 0;
2027                 else
2028                         res = 1;
2029                 break;
2030         }
2031         AST_LIST_UNLOCK(&firmwares);
2032
2033         return res;
2034 }
2035
2036
2037 static void reload_firmware(int unload)
2038 {
2039         struct iax_firmware *cur = NULL;
2040         DIR *fwd;
2041         struct dirent *de;
2042         char dir[256], fn[256];
2043
2044         AST_LIST_LOCK(&firmwares);
2045
2046         /* Mark all as dead */
2047         AST_LIST_TRAVERSE(&firmwares, cur, list)
2048                 cur->dead = 1;
2049
2050         /* Now that we have marked them dead... load new ones */
2051         if (!unload) {
2052                 snprintf(dir, sizeof(dir), "%s/firmware/iax", ast_config_AST_DATA_DIR);
2053                 fwd = opendir(dir);
2054                 if (fwd) {
2055                         while((de = readdir(fwd))) {
2056                                 if (de->d_name[0] != '.') {
2057                                         snprintf(fn, sizeof(fn), "%s/%s", dir, de->d_name);
2058                                         if (!try_firmware(fn)) {
2059                                                 ast_verb(2, "Loaded firmware '%s'\n", de->d_name);
2060                                         }
2061                                 }
2062                         }
2063                         closedir(fwd);
2064                 } else 
2065                         ast_log(LOG_WARNING, "Error opening firmware directory '%s': %s\n", dir, strerror(errno));
2066         }
2067
2068         /* Clean up leftovers */
2069         AST_LIST_TRAVERSE_SAFE_BEGIN(&firmwares, cur, list) {
2070                 if (!cur->dead)
2071                         continue;
2072                 AST_LIST_REMOVE_CURRENT(list);
2073                 destroy_firmware(cur);
2074         }
2075         AST_LIST_TRAVERSE_SAFE_END;
2076
2077         AST_LIST_UNLOCK(&firmwares);
2078 }
2079
2080 /*!
2081  * \note This function assumes that iaxsl[callno] is locked when called.
2082  *
2083  * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
2084  * was valid before calling it, it may no longer be valid after calling it.
2085  * This function calls iax2_queue_frame(), which may unlock and lock the mutex 
2086  * associated with this callno, meaning that another thread may grab it and destroy the call.
2087  */
2088 static int __do_deliver(void *data)
2089 {
2090         /* Just deliver the packet by using queueing.  This is called by
2091           the IAX thread with the iaxsl lock held. */
2092         struct iax_frame *fr = data;
2093         fr->retrans = -1;
2094         ast_clear_flag(&fr->af, AST_FRFLAG_HAS_TIMING_INFO);
2095         if (iaxs[fr->callno] && !ast_test_flag(iaxs[fr->callno], IAX_ALREADYGONE))
2096                 iax2_queue_frame(fr->callno, &fr->af);
2097         /* Free our iax frame */
2098         iax2_frame_free(fr);
2099         /* And don't run again */
2100         return 0;
2101 }
2102
2103 static int handle_error(void)
2104 {
2105         /* XXX Ideally we should figure out why an error occurred and then abort those
2106            rather than continuing to try.  Unfortunately, the published interface does
2107            not seem to work XXX */
2108 #if 0
2109         struct sockaddr_in *sin;
2110         int res;
2111         struct msghdr m;
2112         struct sock_extended_err e;
2113         m.msg_name = NULL;
2114         m.msg_namelen = 0;
2115         m.msg_iov = NULL;
2116         m.msg_control = &e;
2117         m.msg_controllen = sizeof(e);
2118         m.msg_flags = 0;
2119         res = recvmsg(netsocket, &m, MSG_ERRQUEUE);
2120         if (res < 0)
2121                 ast_log(LOG_WARNING, "Error detected, but unable to read error: %s\n", strerror(errno));
2122         else {
2123                 if (m.msg_controllen) {
2124                         sin = (struct sockaddr_in *)SO_EE_OFFENDER(&e);
2125                         if (sin) 
2126                                 ast_log(LOG_WARNING, "Receive error from %s\n", ast_inet_ntoa(sin->sin_addr));
2127                         else
2128                                 ast_log(LOG_WARNING, "No address detected??\n");
2129                 } else {
2130                         ast_log(LOG_WARNING, "Local error: %s\n", strerror(e.ee_errno));
2131                 }
2132         }
2133 #endif
2134         return 0;
2135 }
2136
2137 static int transmit_trunk(struct iax_frame *f, struct sockaddr_in *sin, int sockfd)
2138 {
2139         int res;
2140         res = sendto(sockfd, f->data, f->datalen, 0,(struct sockaddr *)sin,
2141                                         sizeof(*sin));
2142         if (res < 0) {
2143                 ast_debug(1, "Received error: %s\n", strerror(errno));
2144                 handle_error();
2145         } else
2146                 res = 0;
2147         return res;
2148 }
2149
2150 static int send_packet(struct iax_frame *f)
2151 {
2152         int res;
2153         int callno = f->callno;
2154         struct sockaddr_in *addr;
2155
2156         /* Don't send if there was an error, but return error instead */
2157         if (!callno || !iaxs[callno] || iaxs[callno]->error)
2158             return -1;
2159         
2160         /* Called with iaxsl held */
2161         if (iaxdebug)
2162                 ast_debug(3, "Sending %d on %d/%d to %s:%d\n", f->ts, callno, iaxs[callno]->peercallno, ast_inet_ntoa(iaxs[callno]->addr.sin_addr), ntohs(iaxs[callno]->addr.sin_port));
2163
2164         if (f->media) {
2165                 addr = &iaxs[callno]->media;
2166         } else if (f->transfer) {
2167                 addr = &iaxs[callno]->transfer;
2168         } else {
2169                 addr = &iaxs[callno]->addr;
2170         }
2171         
2172         if (iaxdebug)
2173                 iax_showframe(f, NULL, 0, addr, f->datalen - sizeof(struct ast_iax2_full_hdr));
2174
2175         res = sendto(iaxs[callno]->sockfd, f->data, f->datalen, 0,(struct sockaddr *)addr, 
2176                      sizeof(iaxs[callno]->media));
2177
2178         if (res < 0) {
2179                 if (iaxdebug)
2180                         ast_debug(1, "Received error: %s\n", strerror(errno));
2181                 handle_error();
2182         } else
2183                 res = 0;
2184
2185         return res;
2186 }
2187
2188 /*!
2189  * \note Since this function calls iax2_queue_hangup(), the pvt struct
2190  *       for the given call number may disappear during its execution.
2191  */
2192 static int iax2_predestroy(int callno)
2193 {
2194         struct ast_channel *c = NULL;
2195         struct chan_iax2_pvt *pvt = iaxs[callno];
2196
2197         if (!pvt)
2198                 return -1;
2199
2200         if (!ast_test_flag(pvt, IAX_ALREADYGONE)) {
2201                 iax2_destroy_helper(pvt);
2202                 ast_set_flag(pvt, IAX_ALREADYGONE);     
2203         }
2204
2205         if ((c = pvt->owner)) {
2206                 c->tech_pvt = NULL;
2207                 iax2_queue_hangup(callno);
2208                 pvt->owner = NULL;
2209                 ast_module_unref(ast_module_info->self);
2210         }
2211
2212         return 0;
2213 }
2214
2215 static void iax2_destroy(int callno)
2216 {
2217         struct chan_iax2_pvt *pvt = NULL;
2218         struct ast_channel *owner = NULL;
2219
2220 retry:
2221         pvt = iaxs[callno];
2222         lastused[callno] = ast_tvnow();
2223         
2224         owner = pvt ? pvt->owner : NULL;
2225
2226         if (owner) {
2227                 if (ast_channel_trylock(owner)) {
2228                         ast_log(LOG_NOTICE, "Avoiding IAX destroy deadlock\n");
2229                         ast_mutex_unlock(&iaxsl[callno]);
2230                         usleep(1);
2231                         ast_mutex_lock(&iaxsl[callno]);
2232                         goto retry;
2233                 }
2234         }
2235
2236         if (!owner) {
2237                 iaxs[callno] = NULL;
2238         }
2239
2240         if (pvt) {
2241                 if (!owner) {
2242                         pvt->owner = NULL;
2243                 } else {
2244                         /* If there's an owner, prod it to give up */
2245                         /* It is ok to use ast_queue_hangup() here instead of iax2_queue_hangup()
2246                          * because we already hold the owner channel lock. */
2247                         ast_queue_hangup(owner);
2248                 }
2249
2250                 if (pvt->peercallno) {
2251                         remove_by_peercallno(pvt);
2252                 }
2253
2254                 if (!owner) {
2255                         ao2_ref(pvt, -1);
2256                         pvt = NULL;
2257                 }
2258         }
2259
2260         if (owner) {
2261                 ast_channel_unlock(owner);
2262         }
2263
2264         if (callno & 0x4000) {
2265                 update_max_trunk();
2266         }
2267 }
2268
2269 static int update_packet(struct iax_frame *f)
2270 {
2271         /* Called with iaxsl lock held, and iaxs[callno] non-NULL */
2272         struct ast_iax2_full_hdr *fh = f->data;
2273         /* Mark this as a retransmission */
2274         fh->dcallno = ntohs(IAX_FLAG_RETRANS | f->dcallno);
2275         /* Update iseqno */
2276         f->iseqno = iaxs[f->callno]->iseqno;
2277         fh->iseqno = f->iseqno;
2278         return 0;
2279 }
2280
2281 static int attempt_transmit(const void *data);
2282 static void __attempt_transmit(const void *data)
2283 {
2284         /* Attempt to transmit the frame to the remote peer...
2285            Called without iaxsl held. */
2286         struct iax_frame *f = (struct iax_frame *)data;
2287         int freeme = 0;
2288         int callno = f->callno;
2289         /* Make sure this call is still active */
2290         if (callno) 
2291                 ast_mutex_lock(&iaxsl[callno]);
2292         if (callno && iaxs[callno]) {
2293                 if ((f->retries < 0) /* Already ACK'd */ ||
2294                     (f->retries >= max_retries) /* Too many attempts */) {
2295                                 /* Record an error if we've transmitted too many times */
2296                                 if (f->retries >= max_retries) {
2297                                         if (f->transfer) {
2298                                                 /* Transfer timeout */
2299                                                 struct iax_ie_data ied;
2300                                                 memset(&ied, 0, sizeof(ied));
2301                                                 iax_ie_append_int(&ied, IAX_IE_TRANSFERID, iaxs[callno]->transferid);
2302                                                 if (iaxs[callno]->mediareleased) {
2303                                                         send_command_media(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_TXREJ, 0, ied.buf, ied.pos);
2304                                                 } else {
2305                                                         send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_TXREJ, 0, ied.buf, ied.pos, -1);
2306                                                 }
2307                                         } else if (f->final) {
2308                                                 if (f->final) 
2309                                                         iax2_destroy(callno);
2310                                         } else {
2311                                                 if (iaxs[callno]->owner)
2312                                                         ast_log(LOG_WARNING, "Max retries exceeded to host %s on %s (type = %d, subclass = %d, ts=%d, seqno=%d)\n", ast_inet_ntoa(iaxs[f->callno]->addr.sin_addr),iaxs[f->callno]->owner->name , f->af.frametype, f->af.subclass, f->ts, f->oseqno);
2313                                                 iaxs[callno]->error = ETIMEDOUT;
2314                                                 if (iaxs[callno]->owner) {
2315                                                         struct ast_frame fr = { AST_FRAME_CONTROL, AST_CONTROL_HANGUP, .data.uint32 = AST_CAUSE_DESTINATION_OUT_OF_ORDER };
2316                                                         /* Hangup the fd */
2317                                                         iax2_queue_frame(callno, &fr); /* XXX */
2318                                                         /* Remember, owner could disappear */
2319                                                         if (iaxs[callno] && iaxs[callno]->owner)
2320                                                                 iaxs[callno]->owner->hangupcause = AST_CAUSE_DESTINATION_OUT_OF_ORDER;
2321                                                 } else {
2322                                                         if (iaxs[callno]->reg) {
2323                                                                 memset(&iaxs[callno]->reg->us, 0, sizeof(iaxs[callno]->reg->us));
2324                                                                 iaxs[callno]->reg->regstate = REG_STATE_TIMEOUT;
2325                                                                 iaxs[callno]->reg->refresh = IAX_DEFAULT_REG_EXPIRE;
2326                                                         }
2327                                                         iax2_destroy(callno);
2328                                                 }
2329                                         }
2330
2331                                 }
2332                                 freeme = 1;
2333                 } else {
2334                         /* Update it if it needs it */
2335                         update_packet(f);
2336                         /* Attempt transmission */
2337                         send_packet(f);
2338                         f->retries++;
2339                         /* Try again later after 10 times as long */
2340                         f->retrytime *= 10;
2341                         if (f->retrytime > MAX_RETRY_TIME)
2342                                 f->retrytime = MAX_RETRY_TIME;
2343                         /* Transfer messages max out at one second */
2344                         if (f->transfer && (f->retrytime > 1000))
2345                                 f->retrytime = 1000;
2346                         f->retrans = iax2_sched_add(sched, f->retrytime, attempt_transmit, f);
2347                 }
2348         } else {
2349                 /* Make sure it gets freed */
2350                 f->retries = -1;
2351                 freeme = 1;
2352         }
2353         if (callno)
2354                 ast_mutex_unlock(&iaxsl[callno]);
2355         /* Do not try again */
2356         if (freeme) {
2357                 /* Don't attempt delivery, just remove it from the queue */
2358                 AST_LIST_LOCK(&frame_queue);
2359                 AST_LIST_REMOVE(&frame_queue, f, list);
2360                 AST_LIST_UNLOCK(&frame_queue);
2361                 f->retrans = -1;
2362                 /* Free the IAX frame */
2363                 iax2_frame_free(f);
2364         }
2365 }
2366
2367 static int attempt_transmit(const void *data)
2368 {
2369 #ifdef SCHED_MULTITHREADED
2370         if (schedule_action(__attempt_transmit, data))
2371 #endif          
2372                 __attempt_transmit(data);
2373         return 0;
2374 }
2375
2376 static char *handle_cli_iax2_prune_realtime(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2377 {
2378         struct iax2_peer *peer;
2379
2380         switch (cmd) {
2381         case CLI_INIT:
2382                 e->command = "iax2 prune realtime";
2383                 e->usage =
2384                         "Usage: iax2 prune realtime [<peername>|all]\n"
2385                         "       Prunes object(s) from the cache\n";
2386                 return NULL;
2387         case CLI_GENERATE:
2388                 return complete_iax2_show_peer(a->line, a->word, a->pos, a->n);
2389         }
2390
2391         if (a->argc != 4)
2392         return CLI_SHOWUSAGE;
2393         if (!strcmp(a->argv[3], "all")) {
2394                 reload_config();
2395                 ast_cli(a->fd, "Cache flushed successfully.\n");
2396         } else if ((peer = find_peer(a->argv[3], 0))) {
2397                 if(ast_test_flag(peer, IAX_RTCACHEFRIENDS)) {
2398                         ast_set_flag(peer, IAX_RTAUTOCLEAR);
2399                         expire_registry(peer_ref(peer));
2400                         ast_cli(a->fd, "Peer %s was removed from the cache.\n", a->argv[3]);
2401                 } else {
2402                         ast_cli(a->fd, "Peer %s is not eligible for this operation.\n", a->argv[3]);
2403                 }
2404                 peer_unref(peer);
2405         } else {
2406                 ast_cli(a->fd, "Peer %s was not found in the cache.\n", a->argv[3]);
2407         }
2408         
2409         return CLI_SUCCESS;
2410 }
2411
2412 static char *handle_cli_iax2_test_losspct(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2413 {
2414         switch (cmd) {
2415         case CLI_INIT:
2416                 e->command = "iax2 test losspct";
2417                 e->usage =
2418                         "Usage: iax2 test losspct <percentage>\n"
2419                         "       For testing, throws away <percentage> percent of incoming packets\n";
2420                 return NULL;
2421         case CLI_GENERATE:
2422                 return NULL;
2423         }
2424         if (a->argc != 4)
2425                 return CLI_SHOWUSAGE;
2426
2427         test_losspct = atoi(a->argv[3]);
2428
2429         return CLI_SUCCESS;
2430 }
2431
2432 #ifdef IAXTESTS
2433 static char *handle_cli_iax2_test_late(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2434 {
2435         switch (cmd) {
2436         case CLI_INIT:
2437                 e->command = "iax2 test late";
2438                 e->usage =
2439                         "Usage: iax2 test late <ms>\n"
2440                         "       For testing, count the next frame as <ms> ms late\n";
2441                 return NULL;
2442         case CLI_GENERATE:
2443                 return NULL;
2444         }
2445
2446         if (a->argc != 4)
2447                 return CLI_SHOWUSAGE;
2448
2449         test_late = atoi(a->argv[3]);
2450
2451         return CLI_SUCCESS;
2452 }
2453
2454 static char *handle_cli_iax2_test_resync(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2455 {
2456         switch (cmd) {
2457         case CLI_INIT:
2458                 e->command = "iax2 test resync";
2459                 e->usage =
2460                         "Usage: iax2 test resync <ms>\n"
2461                         "       For testing, adjust all future frames by <ms> ms\n";
2462                 return NULL;
2463         case CLI_GENERATE:
2464                 return NULL;
2465         }
2466
2467         if (a->argc != 4)
2468                 return CLI_SHOWUSAGE;
2469
2470         test_resync = atoi(a->argv[3]);
2471
2472         return CLI_SUCCESS;
2473 }
2474
2475 static char *handle_cli_iax2_test_jitter(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2476 {
2477         switch (cmd) {
2478         case CLI_INIT:
2479                 e->command = "iax2 test jitter";
2480                 e->usage =
2481                         "Usage: iax2 test jitter <ms> <pct>\n"
2482                         "       For testing, simulate maximum jitter of +/- <ms> on <pct>\n"
2483                         "       percentage of packets. If <pct> is not specified, adds\n"
2484                         "       jitter to all packets.\n";
2485                 return NULL;
2486         case CLI_GENERATE:
2487                 return NULL;
2488         }
2489
2490         if (a->argc < 4 || a->argc > 5)
2491                 return CLI_SHOWUSAGE;
2492
2493         test_jit = atoi(a->argv[3]);
2494         if (a->argc == 5)
2495                 test_jitpct = atoi(a->argv[4]);
2496
2497         return CLI_SUCCESS;
2498 }
2499 #endif /* IAXTESTS */
2500
2501 /*! \brief  peer_status: Report Peer status in character string */
2502 /*      returns 1 if peer is online, -1 if unmonitored */
2503 static int peer_status(struct iax2_peer *peer, char *status, int statuslen)
2504 {
2505         int res = 0;
2506         if (peer->maxms) {
2507                 if (peer->lastms < 0) {
2508                         ast_copy_string(status, "UNREACHABLE", statuslen);
2509                 } else if (peer->lastms > peer->maxms) {
2510                         snprintf(status, statuslen, "LAGGED (%d ms)", peer->lastms);
2511                         res = 1;
2512                 } else if (peer->lastms) {
2513                         snprintf(status, statuslen, "OK (%d ms)", peer->lastms);
2514                         res = 1;
2515                 } else {
2516                         ast_copy_string(status, "UNKNOWN", statuslen);
2517                 }
2518         } else { 
2519                 ast_copy_string(status, "Unmonitored", statuslen);
2520                 res = -1;
2521         }
2522         return res;
2523 }
2524
2525 /*! \brief Show one peer in detail */
2526 static char *handle_cli_iax2_show_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2527 {
2528         char status[30];
2529         char cbuf[256];
2530         struct iax2_peer *peer;
2531         char codec_buf[512];
2532         int x = 0, codec = 0, load_realtime = 0;
2533
2534         switch (cmd) {
2535         case CLI_INIT:
2536                 e->command = "iax2 show peer";
2537                 e->usage =
2538                         "Usage: iax2 show peer <name>\n"
2539                         "       Display details on specific IAX peer\n";
2540                 return NULL;
2541         case CLI_GENERATE:
2542                 return complete_iax2_show_peer(a->line, a->word, a->pos, a->n);
2543         }
2544
2545         if (a->argc < 4)
2546                 return CLI_SHOWUSAGE;
2547
2548         load_realtime = (a->argc == 5 && !strcmp(a->argv[4], "load")) ? 1 : 0;
2549
2550         peer = find_peer(a->argv[3], load_realtime);
2551         if (peer) {
2552                 ast_cli(a->fd, "\n\n");
2553                 ast_cli(a->fd, "  * Name       : %s\n", peer->name);
2554                 ast_cli(a->fd, "  Secret       : %s\n", ast_strlen_zero(peer->secret) ? "<Not set>" : "<Set>");
2555                 ast_cli(a->fd, "  Context      : %s\n", peer->context);
2556                 ast_cli(a->fd, "  Parking lot  : %s\n", peer->parkinglot);
2557                 ast_cli(a->fd, "  Mailbox      : %s\n", peer->mailbox);
2558                 ast_cli(a->fd, "  Dynamic      : %s\n", ast_test_flag(peer, IAX_DYNAMIC) ? "Yes" : "No");
2559                 ast_cli(a->fd, "  Callerid     : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, "<unspecified>"));
2560                 ast_cli(a->fd, "  Expire       : %d\n", peer->expire);
2561                 ast_cli(a->fd, "  ACL          : %s\n", (peer->ha ? "Yes" : "No"));
2562                 ast_cli(a->fd, "  Addr->IP     : %s Port %d\n",  peer->addr.sin_addr.s_addr ? ast_inet_ntoa(peer->addr.sin_addr) : "(Unspecified)", ntohs(peer->addr.sin_port));
2563                 ast_cli(a->fd, "  Defaddr->IP  : %s Port %d\n", ast_inet_ntoa(peer->defaddr.sin_addr), ntohs(peer->defaddr.sin_port));
2564                 ast_cli(a->fd, "  Username     : %s\n", peer->username);
2565                 ast_cli(a->fd, "  Codecs       : ");
2566                 ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, peer->capability);
2567                 ast_cli(a->fd, "%s\n", codec_buf);
2568
2569                 ast_cli(a->fd, "  Codec Order  : (");
2570                 for(x = 0; x < 32 ; x++) {
2571                         codec = ast_codec_pref_index(&peer->prefs,x);
2572                         if(!codec)
2573                                 break;
2574                         ast_cli(a->fd, "%s", ast_getformatname(codec));
2575                         if(x < 31 && ast_codec_pref_index(&peer->prefs,x+1))
2576                                 ast_cli(a->fd, "|");
2577                 }
2578
2579                 if (!x)
2580                         ast_cli(a->fd, "none");
2581                 ast_cli(a->fd, ")\n");
2582
2583                 ast_cli(a->fd, "  Status       : ");
2584                 peer_status(peer, status, sizeof(status));      
2585                 ast_cli(a->fd, "%s\n",status);
2586                 ast_cli(a->fd, "  Qualify      : every %dms when OK, every %dms when UNREACHABLE (sample smoothing %s)\n", peer->pokefreqok, peer->pokefreqnotok, peer->smoothing ? "On" : "Off");
2587                 ast_cli(a->fd, "\n");
2588                 peer_unref(peer);
2589         } else {
2590                 ast_cli(a->fd, "Peer %s not found.\n", a->argv[3]);
2591                 ast_cli(a->fd, "\n");
2592         }
2593
2594         return CLI_SUCCESS;
2595 }
2596
2597 static char *complete_iax2_show_peer(const char *line, const char *word, int pos, int state)
2598 {
2599         int which = 0;
2600         struct iax2_peer *peer;
2601         char *res = NULL;
2602         int wordlen = strlen(word);
2603         struct ao2_iterator i;
2604
2605         /* 0 - iax2; 1 - show; 2 - peer; 3 - <peername> */
2606         if (pos != 3)
2607                 return NULL;
2608
2609         i = ao2_iterator_init(peers, 0);
2610         while ((peer = ao2_iterator_next(&i))) {
2611                 if (!strncasecmp(peer->name, word, wordlen) && ++which > state) {
2612                         res = ast_strdup(peer->name);
2613                         peer_unref(peer);
2614                         break;
2615                 }
2616                 peer_unref(peer);
2617         }
2618
2619         return res;
2620 }
2621
2622 static char *handle_cli_iax2_show_stats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2623 {
2624         struct iax_frame *cur;
2625         int cnt = 0, dead = 0, final = 0;
2626
2627         switch (cmd) {
2628         case CLI_INIT:
2629                 e->command = "iax2 show stats";
2630                 e->usage =
2631                         "Usage: iax2 show stats\n"
2632                         "       Display statistics on IAX channel driver.\n";
2633                 return NULL;
2634         case CLI_GENERATE:
2635                 return NULL;
2636         }
2637
2638         if (a->argc != 3)
2639                 return CLI_SHOWUSAGE;
2640
2641         AST_LIST_LOCK(&frame_queue);
2642         AST_LIST_TRAVERSE(&frame_queue, cur, list) {
2643                 if (cur->retries < 0)
2644                         dead++;
2645                 if (cur->final)
2646                         final++;
2647                 cnt++;
2648         }
2649         AST_LIST_UNLOCK(&frame_queue);
2650
2651         ast_cli(a->fd, "    IAX Statistics\n");
2652         ast_cli(a->fd, "---------------------\n");
2653         ast_cli(a->fd, "Outstanding frames: %d (%d ingress, %d egress)\n", iax_get_frames(), iax_get_iframes(), iax_get_oframes());
2654         ast_cli(a->fd, "%d timed and %d untimed transmits; MTU %d/%d/%d\n", trunk_timed, trunk_untimed,
2655                 trunk_maxmtu, trunk_nmaxmtu, global_max_trunk_mtu);
2656         ast_cli(a->fd, "Packets in transmit queue: %d dead, %d final, %d total\n\n", dead, final, cnt);
2657
2658         trunk_timed = trunk_untimed = 0;
2659         if (trunk_maxmtu > trunk_nmaxmtu)
2660                 trunk_nmaxmtu = trunk_maxmtu;
2661
2662         return CLI_SUCCESS;
2663 }
2664
2665 /*! \brief Set trunk MTU from CLI */
2666 static char *handle_cli_iax2_set_mtu(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2667 {
2668         int mtuv;
2669
2670         switch (cmd) {
2671         case CLI_INIT:
2672                 e->command = "iax2 set mtu";
2673                 e->usage =
2674                         "Usage: iax2 set mtu <value>\n"
2675                         "       Set the system-wide IAX IP mtu to <value> bytes net or\n"
2676                         "       zero to disable. Disabling means that the operating system\n"
2677                         "       must handle fragmentation of UDP packets when the IAX2 trunk\n"
2678                         "       packet exceeds the UDP payload size. This is substantially\n"
2679                         "       below the IP mtu. Try 1240 on ethernets. Must be 172 or\n"
2680                         "       greater for G.711 samples.\n";
2681                 return NULL;
2682         case CLI_GENERATE:
2683                 return NULL;
2684         }
2685
2686         if (a->argc != 4)
2687                 return CLI_SHOWUSAGE; 
2688         if (strncasecmp(a->argv[3], "default", strlen(a->argv[3])) == 0)
2689                 mtuv = MAX_TRUNK_MTU;
2690         else
2691                 mtuv = atoi(a->argv[3]);
2692
2693         if (mtuv == 0) {
2694                 ast_cli(a->fd, "Trunk MTU control disabled (mtu was %d)\n", global_max_trunk_mtu); 
2695                 global_max_trunk_mtu = 0; 
2696                 return CLI_SUCCESS; 
2697         }
2698         if (mtuv < 172 || mtuv > 4000) {
2699                 ast_cli(a->fd, "Trunk MTU must be between 172 and 4000\n"); 
2700                 return CLI_SHOWUSAGE; 
2701         }
2702         ast_cli(a->fd, "Trunk MTU changed from %d to %d\n", global_max_trunk_mtu, mtuv); 
2703         global_max_trunk_mtu = mtuv; 
2704         return CLI_SUCCESS;
2705 }
2706
2707 static char *handle_cli_iax2_show_cache(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2708 {
2709         struct iax2_dpcache *dp = NULL;
2710         char tmp[1024], *pc = NULL;
2711         int s, x, y;
2712         struct timeval tv = ast_tvnow();
2713
2714         switch (cmd) {
2715         case CLI_INIT:
2716                 e->command = "iax2 show cache";
2717                 e->usage =
2718                         "Usage: iax2 show cache\n"
2719                         "       Display currently cached IAX Dialplan results.\n";
2720                 return NULL;
2721         case CLI_GENERATE:
2722                 return NULL;
2723         }
2724
2725         AST_LIST_LOCK(&dpcache);
2726
2727         ast_cli(a->fd, "%-20.20s %-12.12s %-9.9s %-8.8s %s\n", "Peer/Context", "Exten", "Exp.", "Wait.", "Flags");
2728
2729         AST_LIST_TRAVERSE(&dpcache, dp, cache_list) {
2730                 s = dp->expiry.tv_sec - tv.tv_sec;
2731                 tmp[0] = '\0';
2732                 if (dp->flags & CACHE_FLAG_EXISTS)
2733                         strncat(tmp, "EXISTS|", sizeof(tmp) - strlen(tmp) - 1);
2734                 if (dp->flags & CACHE_FLAG_NONEXISTENT)
2735                         strncat(tmp, "NONEXISTENT|", sizeof(tmp) - strlen(tmp) - 1);
2736                 if (dp->flags & CACHE_FLAG_CANEXIST)
2737                         strncat(tmp, "CANEXIST|", sizeof(tmp) - strlen(tmp) - 1);
2738                 if (dp->flags & CACHE_FLAG_PENDING)
2739                         strncat(tmp, "PENDING|", sizeof(tmp) - strlen(tmp) - 1);
2740                 if (dp->flags & CACHE_FLAG_TIMEOUT)
2741                         strncat(tmp, "TIMEOUT|", sizeof(tmp) - strlen(tmp) - 1);
2742                 if (dp->flags & CACHE_FLAG_TRANSMITTED)
2743                         strncat(tmp, "TRANSMITTED|", sizeof(tmp) - strlen(tmp) - 1);
2744                 if (dp->flags & CACHE_FLAG_MATCHMORE)
2745                         strncat(tmp, "MATCHMORE|", sizeof(tmp) - strlen(tmp) - 1);
2746                 if (dp->flags & CACHE_FLAG_UNKNOWN)
2747                         strncat(tmp, "UNKNOWN|", sizeof(tmp) - strlen(tmp) - 1);
2748                 /* Trim trailing pipe */
2749                 if (!ast_strlen_zero(tmp))
2750                         tmp[strlen(tmp) - 1] = '\0';
2751                 else
2752                         ast_copy_string(tmp, "(none)", sizeof(tmp));
2753                 y = 0;
2754                 pc = strchr(dp->peercontext, '@');
2755                 if (!pc)
2756                         pc = dp->peercontext;
2757                 else
2758                         pc++;
2759                 for (x = 0; x < sizeof(dp->waiters) / sizeof(dp->waiters[0]); x++)
2760                         if (dp->waiters[x] > -1)
2761                                 y++;
2762                 if (s > 0)
2763                         ast_cli(a->fd, "%-20.20s %-12.12s %-9d %-8d %s\n", pc, dp->exten, s, y, tmp);
2764                 else
2765                         ast_cli(a->fd, "%-20.20s %-12.12s %-9.9s %-8d %s\n", pc, dp->exten, "(expired)", y, tmp);
2766         }
2767
2768         AST_LIST_LOCK(&dpcache);
2769
2770         return CLI_SUCCESS;
2771 }
2772
2773 static unsigned int calc_rxstamp(struct chan_iax2_pvt *p, unsigned int offset);
2774
2775 static void unwrap_timestamp(struct iax_frame *fr)
2776 {
2777         int x;
2778
2779         if ( (fr->ts & 0xFFFF0000) == (iaxs[fr->callno]->last & 0xFFFF0000) ) {
2780                 x = fr->ts - iaxs[fr->callno]->last;
2781                 if (x < -50000) {
2782                         /* Sudden big jump backwards in timestamp:
2783                            What likely happened here is that miniframe timestamp has circled but we haven't
2784                            gotten the update from the main packet.  We'll just pretend that we did, and
2785                            update the timestamp appropriately. */
2786                         fr->ts = ( (iaxs[fr->callno]->last & 0xFFFF0000) + 0x10000) | (fr->ts & 0xFFFF);
2787                         if (iaxdebug)
2788                                 ast_debug(1, "schedule_delivery: pushed forward timestamp\n");
2789                 }
2790                 if (x > 50000) {
2791                         /* Sudden apparent big jump forwards in timestamp:
2792                            What's likely happened is this is an old miniframe belonging to the previous
2793                            top-16-bit timestamp that has turned up out of order.
2794                            Adjust the timestamp appropriately. */
2795                         fr->ts = ( (iaxs[fr->callno]->last & 0xFFFF0000) - 0x10000) | (fr->ts & 0xFFFF);
2796                         if (iaxdebug)
2797                                 ast_debug(1, "schedule_delivery: pushed back timestamp\n");
2798                 }
2799         }
2800 }
2801
2802 static int get_from_jb(const void *p);
2803
2804 static void update_jbsched(struct chan_iax2_pvt *pvt)
2805 {
2806         int when;
2807         
2808         when = ast_tvdiff_ms(ast_tvnow(), pvt->rxcore);
2809         
2810         when = jb_next(pvt->jb) - when;
2811
2812         if (when <= 0) {
2813                 /* XXX should really just empty until when > 0.. */
2814                 when = 1;
2815         }
2816         
2817         pvt->jbid = iax2_sched_replace(pvt->jbid, sched, when, get_from_jb, 
2818                 CALLNO_TO_PTR(pvt->callno));
2819 }
2820
2821 static void __get_from_jb(const void *p) 
2822 {
2823         int callno = PTR_TO_CALLNO(p);
2824         struct chan_iax2_pvt *pvt = NULL;
2825         struct iax_frame *fr;
2826         jb_frame frame;
2827         int ret;
2828         long now;
2829         long next;
2830         struct timeval tv = ast_tvnow();
2831         
2832         /* Make sure we have a valid private structure before going on */
2833         ast_mutex_lock(&iaxsl[callno]);
2834         pvt = iaxs[callno];
2835         if (!pvt) {
2836                 /* No go! */
2837                 ast_mutex_unlock(&iaxsl[callno]);
2838                 return;
2839         }
2840
2841         pvt->jbid = -1;
2842         
2843         /* round up a millisecond since ast_sched_runq does; */
2844         /* prevents us from spinning while waiting for our now */
2845         /* to catch up with runq's now */
2846         tv.tv_usec += 1000;
2847         
2848         now = ast_tvdiff_ms(tv, pvt->rxcore);
2849         
2850         if(now >= (next = jb_next(pvt->jb))) {
2851                 ret = jb_get(pvt->jb,&frame,now,ast_codec_interp_len(pvt->voiceformat));
2852                 switch(ret) {
2853                 case JB_OK:
2854                         fr = frame.data;
2855                         __do_deliver(fr);
2856                         /* __do_deliver() can cause the call to disappear */
2857                         pvt = iaxs[callno];
2858                         break;
2859                 case JB_INTERP:
2860                 {
2861                         struct ast_frame af = { 0, };
2862                         
2863                         /* create an interpolation frame */
2864                         af.frametype = AST_FRAME_VOICE;
2865                         af.subclass = pvt->voiceformat;
2866                         af.samples  = frame.ms * 8;
2867                         af.src  = "IAX2 JB interpolation";
2868                         af.delivery = ast_tvadd(pvt->rxcore, ast_samp2tv(next, 1000));
2869                         af.offset = AST_FRIENDLY_OFFSET;
2870                         
2871                         /* queue the frame:  For consistency, we would call __do_deliver here, but __do_deliver wants an iax_frame,
2872                          * which we'd need to malloc, and then it would free it.  That seems like a drag */
2873                         if (!ast_test_flag(iaxs[callno], IAX_ALREADYGONE)) {
2874                                 iax2_queue_frame(callno, &af);
2875                                 /* iax2_queue_frame() could cause the call to disappear */
2876                                 pvt = iaxs[callno];
2877                         }
2878                 }
2879                         break;
2880                 case JB_DROP:
2881                         iax2_frame_free(frame.data);
2882                         break;
2883                 case JB_NOFRAME:
2884                 case JB_EMPTY:
2885                         /* do nothing */
2886                         break;
2887                 default:
2888                         /* shouldn't happen */
2889                         break;
2890                 }
2891         }
2892         if (pvt)
2893                 update_jbsched(pvt);
2894         ast_mutex_unlock(&iaxsl[callno]);
2895 }
2896
2897 static int get_from_jb(const void *data)
2898 {
2899 #ifdef SCHED_MULTITHREADED
2900         if (schedule_action(__get_from_jb, data))
2901 #endif          
2902                 __get_from_jb(data);
2903         return 0;
2904 }
2905
2906 /*!
2907  * \note This function assumes fr->callno is locked
2908  *
2909  * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
2910  * was valid before calling it, it may no longer be valid after calling it.
2911  */
2912 static int schedule_delivery(struct iax_frame *fr, int updatehistory, int fromtrunk, unsigned int *tsout)
2913 {
2914         int type, len;
2915         int ret;
2916         int needfree = 0;
2917         struct ast_channel *owner = NULL;
2918         struct ast_channel *bridge = NULL;
2919         
2920         /* Attempt to recover wrapped timestamps */
2921         unwrap_timestamp(fr);
2922
2923         /* delivery time is sender's sent timestamp converted back into absolute time according to our clock */
2924         if ( !fromtrunk && !ast_tvzero(iaxs[fr->callno]->rxcore))
2925                 fr->af.delivery = ast_tvadd(iaxs[fr->callno]->rxcore, ast_samp2tv(fr->ts, 1000));
2926         else {
2927 #if 0
2928                 ast_debug(1, "schedule_delivery: set delivery to 0 as we don't have an rxcore yet, or frame is from trunk.\n");
2929 #endif
2930                 fr->af.delivery = ast_tv(0,0);
2931         }
2932
2933         type = JB_TYPE_CONTROL;
2934         len = 0;
2935
2936         if(fr->af.frametype == AST_FRAME_VOICE) {
2937                 type = JB_TYPE_VOICE;
2938                 len = ast_codec_get_samples(&fr->af) / 8;
2939         } else if(fr->af.frametype == AST_FRAME_CNG) {
2940                 type = JB_TYPE_SILENCE;
2941         }
2942
2943         if ( (!ast_test_flag(iaxs[fr->callno], IAX_USEJITTERBUF)) ) {
2944                 if (tsout)
2945                         *tsout = fr->ts;
2946                 __do_deliver(fr);
2947                 return -1;
2948         }
2949
2950         if ((owner = iaxs[fr->callno]->owner))
2951                 bridge = ast_bridged_channel(owner);
2952
2953         /* if the user hasn't requested we force the use of the jitterbuffer, and we're bridged to
2954          * a channel that can accept jitter, then flush and suspend the jb, and send this frame straight through */
2955         if ( (!ast_test_flag(iaxs[fr->callno], IAX_FORCEJITTERBUF)) && owner && bridge && (bridge->tech->properties & AST_CHAN_TP_WANTSJITTER) ) {
2956                 jb_frame frame;
2957
2958                 /* deliver any frames in the jb */
2959                 while (jb_getall(iaxs[fr->callno]->jb, &frame) == JB_OK) {
2960                         __do_deliver(frame.data);
2961                         /* __do_deliver() can make the call disappear */
2962                         if (!iaxs[fr->callno])
2963                                 return -1;
2964                 }
2965
2966                 jb_reset(iaxs[fr->callno]->jb);
2967
2968                 AST_SCHED_DEL(sched, iaxs[fr->callno]->jbid);
2969
2970                 /* deliver this frame now */
2971                 if (tsout)
2972                         *tsout = fr->ts;
2973                 __do_deliver(fr);
2974                 return -1;
2975         }
2976
2977         /* insert into jitterbuffer */
2978         /* TODO: Perhaps we could act immediately if it's not droppable and late */
2979         ret = jb_put(iaxs[fr->callno]->jb, fr, type, len, fr->ts,
2980                         calc_rxstamp(iaxs[fr->callno],fr->ts));
2981         if (ret == JB_DROP) {
2982                 needfree++;
2983         } else if (ret == JB_SCHED) {
2984                 update_jbsched(iaxs[fr->callno]);
2985         }
2986         if (tsout)
2987                 *tsout = fr->ts;
2988         if (needfree) {
2989                 /* Free our iax frame */
2990                 iax2_frame_free(fr);
2991                 return -1;
2992         }
2993         return 0;
2994 }
2995
2996 static int iax2_transmit(struct iax_frame *fr)
2997 {
2998         /* Lock the queue and place this packet at the end */
2999         /* By setting this to 0, the network thread will send it for us, and
3000            queue retransmission if necessary */
3001         fr->sentyet = 0;
3002         AST_LIST_LOCK(&frame_queue);
3003         AST_LIST_INSERT_TAIL(&frame_queue, fr, list);
3004         AST_LIST_UNLOCK(&frame_queue);
3005         /* Wake up the network and scheduler thread */
3006         if (netthreadid != AST_PTHREADT_NULL)
3007                 pthread_kill(netthreadid, SIGURG);
3008         signal_condition(&sched_lock, &sched_cond);
3009         return 0;
3010 }
3011
3012
3013
3014 static int iax2_digit_begin(struct ast_channel *c, char digit)
3015 {
3016         return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_DTMF_BEGIN, digit, 0, NULL, 0, -1);
3017 }
3018
3019 static int iax2_digit_end(struct ast_channel *c, char digit, unsigned int duration)
3020 {
3021         return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_DTMF_END, digit, 0, NULL, 0, -1);
3022 }
3023
3024 static int iax2_sendtext(struct ast_channel *c, const char *text)
3025 {
3026         
3027         return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_TEXT,
3028                 0, 0, (unsigned char *)text, strlen(text) + 1, -1);
3029 }
3030
3031 static int iax2_sendimage(struct ast_channel *c, struct ast_frame *img)
3032 {
3033         return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_IMAGE, img->subclass, 0, img->data.ptr, img->datalen, -1);
3034 }
3035
3036 static int iax2_sendhtml(struct ast_channel *c, int subclass, const char *data, int datalen)
3037 {
3038         return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_HTML, subclass, 0, (unsigned char *)data, datalen, -1);
3039 }
3040
3041 static int iax2_fixup(struct ast_channel *oldchannel, struct ast_channel *newchan)
3042 {
3043         unsigned short callno = PTR_TO_CALLNO(newchan->tech_pvt);
3044         ast_mutex_lock(&iaxsl[callno]);
3045         if (iaxs[callno])
3046                 iaxs[callno]->owner = newchan;
3047         else
3048                 ast_log(LOG_WARNING, "Uh, this isn't a good sign...\n");
3049         ast_mutex_unlock(&iaxsl[callno]);
3050         return 0;
3051 }
3052
3053 /*!
3054  * \note This function calls reg_source_db -> iax2_poke_peer -> find_callno,
3055  *       so do not call this with a pvt lock held.
3056  */
3057 static struct iax2_peer *realtime_peer(const char *peername, struct sockaddr_in *sin)
3058 {
3059         struct ast_variable *var = NULL;
3060         struct ast_variable *tmp;
3061         struct iax2_peer *peer=NULL;
3062         time_t regseconds = 0, nowtime;
3063         int dynamic=0;
3064
3065         if (peername) {
3066                 var = ast_load_realtime("iaxpeers", "name", peername, "host", "dynamic", NULL);
3067                 if (!var && sin)
3068                         var = ast_load_realtime("iaxpeers", "name", peername, "host", ast_inet_ntoa(sin->sin_addr), NULL);
3069         } else if (sin) {
3070                 char porta[25];
3071                 sprintf(porta, "%d", ntohs(sin->sin_port));
3072                 var = ast_load_realtime("iaxpeers", "ipaddr", ast_inet_ntoa(sin->sin_addr), "port", porta, NULL);
3073                 if (var) {
3074                         /* We'll need the peer name in order to build the structure! */
3075                         for (tmp = var; tmp; tmp = tmp->next) {
3076                                 if (!strcasecmp(tmp->name, "name"))
3077                                         peername = tmp->value;
3078                         }
3079                 }
3080         }
3081         if (!var && peername) { /* Last ditch effort */
3082                 var = ast_load_realtime("iaxpeers", "name", peername, NULL);
3083                 /*!\note
3084                  * If this one loaded something, then we need to ensure that the host
3085                  * field matched.  The only reason why we can't have this as a criteria
3086                  * is because we only have the IP address and the host field might be
3087                  * set as a name (and the reverse PTR might not match).
3088                  */
3089                 if (var && sin) {
3090                         for (tmp = var; tmp; tmp = tmp->next) {
3091                                 if (!strcasecmp(tmp->name, "host")) {
3092                                         struct ast_hostent ahp;
3093                                         struct hostent *hp;
3094                                         if (!(hp = ast_gethostbyname(tmp->value, &ahp)) || (memcmp(&hp->h_addr, &sin->sin_addr, sizeof(hp->h_addr)))) {
3095                                                 /* No match */
3096                                                 ast_variables_destroy(var);
3097                                                 var = NULL;
3098                                         }
3099                                         break;
3100                                 }
3101                         }
3102                 }
3103         }
3104         if (!var)
3105                 return NULL;
3106
3107         peer = build_peer(peername, var, NULL, ast_test_flag((&globalflags), IAX_RTCACHEFRIENDS) ? 0 : 1);
3108         
3109         if (!peer) {
3110                 ast_variables_destroy(var);
3111                 return NULL;
3112         }
3113
3114         for (tmp = var; tmp; tmp = tmp->next) {
3115                 /* Make sure it's not a user only... */
3116                 if (!strcasecmp(tmp->name, "type")) {
3117                         if (strcasecmp(tmp->value, "friend") &&
3118                             strcasecmp(tmp->value, "peer")) {
3119                                 /* Whoops, we weren't supposed to exist! */
3120                                 peer = peer_unref(peer);
3121                                 break;
3122                         } 
3123                 } else if (!strcasecmp(tmp->name, "regseconds")) {
3124                         ast_get_time_t(tmp->value, &regseconds, 0, NULL);
3125                 } else if (!strcasecmp(tmp->name, "ipaddr")) {
3126                         inet_aton(tmp->value, &(peer->addr.sin_addr));
3127                 } else if (!strcasecmp(tmp->name, "port")) {
3128                         peer->addr.sin_port = htons(atoi(tmp->value));
3129                 } else if (!strcasecmp(tmp->name, "host")) {
3130                         if (!strcasecmp(tmp->value, "dynamic"))
3131                                 dynamic = 1;
3132                 }
3133         }
3134
3135         ast_variables_destroy(var);
3136
3137         if (!peer)
3138                 return NULL;
3139
3140         if (ast_test_flag((&globalflags), IAX_RTCACHEFRIENDS)) {
3141                 ast_copy_flags(peer, &globalflags, IAX_RTAUTOCLEAR|IAX_RTCACHEFRIENDS);
3142                 if (ast_test_flag(peer, IAX_RTAUTOCLEAR)) {
3143                         if (peer->expire > -1) {
3144                                 if (!ast_sched_del(sched, peer->expire)) {
3145                                         peer->expire = -1;
3146                                         peer_unref(peer);
3147                                 }
3148                         }
3149                         peer->expire = iax2_sched_add(sched, (global_rtautoclear) * 1000, expire_registry, peer_ref(peer));
3150                         if (peer->expire == -1)
3151                                 peer_unref(peer);
3152                 }
3153                 ao2_link(peers, peer);
3154                 if (ast_test_flag(peer, IAX_DYNAMIC))
3155                         reg_source_db(peer);
3156         } else {
3157                 ast_set_flag(peer, IAX_TEMPONLY);       
3158         }
3159
3160         if (!ast_test_flag(&globalflags, IAX_RTIGNOREREGEXPIRE) && dynamic) {
3161                 time(&nowtime);
3162                 if ((nowtime - regseconds) > IAX_DEFAULT_REG_EXPIRE) {
3163                         memset(&peer->addr, 0, sizeof(peer->addr));
3164                         realtime_update_peer(peer->name, &peer->addr, 0);
3165                         ast_debug(1, "realtime_peer: Bah, '%s' is expired (%d/%d/%d)!\n",
3166                                 peername, (int)(nowtime - regseconds), (int)regseconds, (int)nowtime);
3167                 }
3168                 else {
3169                         ast_debug(1, "realtime_peer: Registration for '%s' still active (%d/%d/%d)!\n",
3170                                 peername, (int)(nowtime - regseconds), (int)regseconds, (int)nowtime);
3171                 }
3172         }
3173
3174         return peer;
3175 }
3176
3177 static struct iax2_user *realtime_user(const char *username, struct sockaddr_in *sin)
3178 {
3179         struct ast_variable *var;
3180         struct ast_variable *tmp;
3181         struct iax2_user *user=NULL;
3182
3183         var = ast_load_realtime("iaxusers", "name", username, "host", "dynamic", NULL);
3184         if (!var)
3185                 var = ast_load_realtime("iaxusers", "name", username, "host", ast_inet_ntoa(sin->sin_addr), NULL);
3186         if (!var && sin) {
3187                 char porta[6];
3188                 snprintf(porta, sizeof(porta), "%d", ntohs(sin->sin_port));
3189                 var = ast_load_realtime("iaxusers", "name", username, "ipaddr", ast_inet_ntoa(sin->sin_addr), "port", porta, NULL);
3190                 if (!var)
3191                         var = ast_load_realtime("iaxusers", "ipaddr", ast_inet_ntoa(sin->sin_addr), "port", porta, NULL);
3192         }
3193         if (!var) { /* Last ditch effort */
3194                 var = ast_load_realtime("iaxusers", "name", username, NULL);
3195                 /*!\note
3196                  * If this one loaded something, then we need to ensure that the host
3197                  * field matched.  The only reason why we can't have this as a criteria
3198                  * is because we only have the IP address and the host field might be
3199                  * set as a name (and the reverse PTR might not match).
3200                  */
3201                 if (var) {
3202                         for (tmp = var; tmp; tmp = tmp->next) {
3203                                 if (!strcasecmp(tmp->name, "host")) {
3204                                         struct ast_hostent ahp;
3205                                         struct hostent *hp;
3206                                         if (!(hp = ast_gethostbyname(tmp->value, &ahp)) || (memcmp(&hp->h_addr, &sin->sin_addr, sizeof(hp->h_addr)))) {
3207                                                 /* No match */
3208                                                 ast_variables_destroy(var);
3209                                                 var = NULL;
3210                                         }
3211                                         break;
3212                                 }
3213                         }
3214                 }
3215         }
3216         if (!var)
3217                 return NULL;
3218
3219         tmp = var;
3220         while(tmp) {
3221                 /* Make sure it's not a peer only... */
3222                 if (!strcasecmp(tmp->name, "type")) {
3223                         if (strcasecmp(tmp->value, "friend") &&
3224                             strcasecmp(tmp->value, "user")) {
3225                                 return NULL;
3226                         } 
3227                 }
3228                 tmp = tmp->next;
3229         }
3230
3231         user = build_user(username, var, NULL, !ast_test_flag((&globalflags), IAX_RTCACHEFRIENDS));
3232
3233         ast_variables_destroy(var);
3234
3235         if (!user)
3236                 return NULL;
3237
3238         if (ast_test_flag((&globalflags), IAX_RTCACHEFRIENDS)) {
3239                 ast_set_flag(user, IAX_RTCACHEFRIENDS);
3240                 ao2_link(users, user);
3241         } else {
3242                 ast_set_flag(user, IAX_TEMPONLY);       
3243         }
3244
3245         return user;
3246 }
3247
3248 static void realtime_update_peer(const char *peername, struct sockaddr_in *sin, time_t regtime)
3249 {
3250         char port[10];
3251         char regseconds[20];
3252         
3253         snprintf(regseconds, sizeof(regseconds), "%d", (int)regtime);
3254         snprintf(port, sizeof(port), "%d", ntohs(sin->sin_port));
3255         ast_update_realtime("iaxpeers", "name", peername, 
3256                 "ipaddr", ast_inet_ntoa(sin->sin_addr), "port", port, 
3257                 "regseconds", regseconds, NULL);
3258 }
3259
3260 struct create_addr_info {
3261         int capability;
3262         unsigned int flags;
3263         int maxtime;
3264         int encmethods;
3265         int found;
3266         int sockfd;
3267         int adsi;
3268         char username[80];
3269         char secret[80];
3270         char outkey[80];
3271         char timezone[80];
3272         char prefs[32];
3273         char context[AST_MAX_CONTEXT];
3274         char peercontext[AST_MAX_CONTEXT];
3275         char mohinterpret[MAX_MUSICCLASS];
3276         char mohsuggest[MAX_MUSICCLASS];
3277 };
3278
3279 static int create_addr(const char *peername, struct ast_channel *c, struct sockaddr_in *sin, struct create_addr_info *cai)
3280 {
3281         struct iax2_peer *peer;
3282         int res = -1;
3283         struct ast_codec_pref ourprefs;
3284
3285         ast_clear_flag(cai, IAX_SENDANI | IAX_TRUNK);
3286         cai->sockfd = defaultsockfd;
3287         cai->maxtime = 0;
3288         sin->sin_family = AF_INET;
3289
3290         if (!(peer = find_peer(peername, 1))) {
3291                 cai->found = 0;
3292                 if (ast_get_ip_or_srv(sin, peername, srvlookup ? "_iax._udp" : NULL)) {
3293                         ast_log(LOG_WARNING, "No such host: %s\n", peername);
3294                         return -1;
3295                 }
3296                 sin->sin_port = htons(IAX_DEFAULT_PORTNO);
3297                 /* use global iax prefs for unknown peer/user */
3298                 /* But move the calling channel's native codec to the top of the preference list */
3299                 memcpy(&ourprefs, &prefs, sizeof(ourprefs));
3300                 if (c)
3301                         ast_codec_pref_prepend(&ourprefs, c->nativeformats, 1);
3302                 ast_codec_pref_convert(&ourprefs, cai->prefs, sizeof(cai->prefs), 1);
3303                 return 0;
3304         }
3305
3306         cai->found = 1;
3307         
3308         /* if the peer has no address (current or default), return failure */
3309         if (!(peer->addr.sin_addr.s_addr || peer->defaddr.sin_addr.s_addr))
3310                 goto return_unref;
3311
3312         /* if the peer is being monitored and is currently unreachable, return failure */
3313         if (peer->maxms && ((peer->lastms > peer->maxms) || (peer->lastms < 0)))
3314                 goto return_unref;
3315
3316         ast_copy_flags(cai, peer, IAX_SENDANI | IAX_TRUNK | IAX_NOTRANSFER | IAX_TRANSFERMEDIA | IAX_USEJITTERBUF | IAX_FORCEJITTERBUF);
3317         cai->maxtime = peer->maxms;
3318         cai->capability = peer->capability;
3319         cai->encmethods = peer->encmethods;
3320         cai->sockfd = peer->sockfd;
3321         cai->adsi = peer->adsi;
3322         memcpy(&ourprefs, &peer->prefs, sizeof(ourprefs));
3323         /* Move the calling channel's native codec to the top of the preference list */
3324         if (c) {
3325                 ast_log(LOG_DEBUG, "prepending %x to prefs\n", c->nativeformats);
3326                 ast_codec_pref_prepend(&ourprefs, c->nativeformats, 1);
3327         }
3328         ast_codec_pref_convert(&ourprefs, cai->prefs, sizeof(cai->prefs), 1);
3329         ast_copy_string(cai->context, peer->context, sizeof(cai->context));
3330         ast_copy_string(cai->peercontext, peer->peercontext, sizeof(cai->peercontext));
3331         ast_copy_string(cai->username, peer->username, sizeof(cai->username));
3332         ast_copy_string(cai->timezone, peer->zonetag, sizeof(cai->timezone));
3333         ast_copy_string(cai->outkey, peer->outkey, sizeof(cai->outkey));
3334         ast_copy_string(cai->mohinterpret, peer->mohinterpret, sizeof(cai->mohinterpret));
3335         ast_copy_string(cai->mohsuggest, peer->mohsuggest, sizeof(cai->mohsuggest));
3336         if (ast_strlen_zero(peer->dbsecret)) {
3337                 ast_copy_string(cai->secret, peer->secret, sizeof(cai->secret));
3338         } else {
3339                 char *family;
3340                 char *key = NULL;
3341
3342                 family = ast_strdupa(peer->dbsecret);
3343                 key = strchr(family, '/');
3344                 if (key)
3345                         *key++ = '\0';
3346                 if (!key || ast_db_get(family, key, cai->secret, sizeof(cai->secret))) {
3347                         ast_log(LOG_WARNING, "Unable to retrieve database password for family/key '%s'!\n", peer->dbsecret);
3348                         goto return_unref;
3349                 }
3350         }
3351
3352         if (peer->addr.sin_addr.s_addr) {
3353                 sin->sin_addr = peer->addr.sin_addr;
3354                 sin->sin_port = peer->addr.sin_port;
3355         } else {
3356                 sin->sin_addr = peer->defaddr.sin_addr;
3357                 sin->sin_port = peer->defaddr.sin_port;
3358         }
3359
3360         res = 0;
3361
3362 return_unref:
3363         peer_unref(peer);
3364
3365         return res;
3366 }
3367
3368 static void __auto_congest(const void *nothing)
3369 {
3370         int callno = PTR_TO_CALLNO(nothing);
3371         struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_CONGESTION };
3372         ast_mutex_lock(&iaxsl[callno]);
3373         if (iaxs[callno]) {
3374                 iaxs[callno]->initid = -1;
3375                 iax2_queue_frame(callno, &f);
3376                 ast_log(LOG_NOTICE, "Auto-congesting call due to slow response\n");
3377         }
3378         ast_mutex_unlock(&iaxsl[callno]);
3379 }
3380
3381 static int auto_congest(const void *data)
3382 {
3383 #ifdef SCHED_MULTITHREADED
3384         if (schedule_action(__auto_congest, data))
3385 #endif          
3386                 __auto_congest(data);
3387         return 0;
3388 }
3389
3390 static unsigned int iax2_datetime(const char *tz)
3391 {
3392         struct timeval t = ast_tvnow();
3393         struct ast_tm tm;
3394         unsigned int tmp;
3395         ast_localtime(&t, &tm, ast_strlen_zero(tz) ? NULL : tz);
3396         tmp  = (tm.tm_sec >> 1) & 0x1f;                 /* 5 bits of seconds */
3397         tmp |= (tm.tm_min & 0x3f) << 5;                 /* 6 bits of minutes */
3398         tmp |= (tm.tm_hour & 0x1f) << 11;               /* 5 bits of hours */
3399         tmp |= (tm.tm_mday & 0x1f) << 16;               /* 5 bits of day of month */
3400         tmp |= ((tm.tm_mon + 1) & 0xf) << 21;           /* 4 bits of month */
3401         tmp |= ((tm.tm_year - 100) & 0x7f) << 25;       /* 7 bits of year */
3402         return tmp;
3403 }
3404
3405 struct parsed_dial_string {
3406         char *username;
3407         char *password;
3408         char *key;
3409         char *peer;
3410         char *port;
3411         char *exten;
3412         char *context;
3413         char *options;
3414 };
3415
3416 /*!
3417  * \brief Parses an IAX dial string into its component parts.
3418  * \param data the string to be parsed
3419  * \param pds pointer to a \c struct \c parsed_dial_string to be filled in
3420  * \return nothing
3421  *
3422  * This function parses the string and fills the structure
3423  * with pointers to its component parts. The input string
3424  * will be modified.
3425  *
3426  * \note This function supports both plaintext passwords and RSA
3427  * key names; if the password string is formatted as '[keyname]',
3428  * then the keyname will be placed into the key field, and the
3429  * password field will be set to NULL.
3430  *
3431  * \note The dial string format is:
3432  *       [username[:password]@]peer[:port][/exten[@@context]][/options]
3433  */
3434 static void parse_dial_string(char *data, struct parsed_dial_string *pds)
3435 {
3436         if (ast_strlen_zero(data))
3437                 return;
3438
3439         pds->peer = strsep(&data, "/");
3440         pds->exten = strsep(&data, "/");
3441         pds->options = data;
3442
3443         if (pds->exten) {
3444                 data = pds->exten;
3445                 pds->exten = strsep(&data, "@");
3446                 pds->context = data;
3447         }
3448
3449         if (strchr(pds->peer, '@')) {
3450                 data = pds->peer;
3451                 pds->username = strsep(&data, "@");
3452                 pds->peer = data;
3453         }
3454
3455         if (pds->username) {
3456                 data = pds->username;
3457                 pds->username = strsep(&data, ":");
3458                 pds->password = data;
3459         }
3460
3461         data = pds->peer;
3462         pds->peer = strsep(&data, ":");
3463         pds->port = data;
3464
3465         /* check for a key name wrapped in [] in the secret position, if found,
3466            move it to the key field instead
3467         */
3468         if (pds->password && (pds->password[0] == '[')) {
3469                 pds->key = ast_strip_quoted(pds->password, "[", "]");
3470                 pds->password = NULL;
3471         }
3472 }
3473
3474 static int iax2_call(struct ast_channel *c, char *dest, int timeout)
3475 {
3476         struct sockaddr_in sin;
3477         char *l=NULL, *n=NULL, *tmpstr;
3478         struct iax_ie_data ied;
3479         char *defaultrdest = "s";
3480         unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
3481         struct parsed_dial_string pds;
3482         struct create_addr_info cai;
3483         struct ast_var_t *var;
3484         struct ast_datastore *variablestore = ast_channel_datastore_find(c, &iax2_variable_datastore_info, NULL);
3485         const char* osp_token_ptr;
3486         unsigned int osp_token_length;
3487         unsigned char osp_block_index;
3488         unsigned int osp_block_length;
3489         unsigned char osp_buffer[256];
3490
3491         if ((c->_state != AST_STATE_DOWN) && (c->_state != AST_STATE_RESERVED)) {
3492                 ast_log(LOG_WARNING, "Channel is already in use (%s)?\n", c->name);
3493                 return -1;
3494         }
3495
3496         memset(&cai, 0, sizeof(cai));
3497         cai.encmethods = iax2_encryption;
3498
3499         memset(&pds, 0, sizeof(pds));
3500         tmpstr = ast_strdupa(dest);
3501         parse_dial_string(tmpstr, &pds);
3502
3503         if (ast_strlen_zero(pds.peer)) {
3504                 ast_log(LOG_WARNING, "No peer provided in the IAX2 dial string '%s'\n", dest);
3505                 return -1;
3506         }
3507
3508         if (!pds.exten) {
3509                 if (!ast_strlen_zero(c->exten))
3510                         pds.exten = c->exten;
3511                 else
3512                         pds.exten = defaultrdest;
3513         }
3514
3515         if (create_addr(pds.peer, c, &sin, &cai)) {
3516                 ast_log(LOG_WARNING, "No address associated with '%s'\n", pds.peer);
3517                 return -1;
3518         }
3519
3520         if (!pds.username && !ast_strlen_zero(cai.username))
3521                 pds.username = cai.username;
3522         if (!pds.password && !ast_strlen_zero(cai.secret))
3523                 pds.password = cai.secret;
3524         if (!pds.key && !ast_strlen_zero(cai.outkey))
3525                 pds.key = cai.outkey;
3526         if (!pds.context && !ast_strlen_zero(cai.peercontext))
3527                 pds.context = cai.peercontext;
3528
3529         /* Keep track of the context for outgoing calls too */
3530         ast_copy_string(c->context, cai.context, sizeof(c->context));
3531
3532         if (pds.port)
3533                 sin.sin_port = htons(atoi(pds.port));
3534
3535         l = c->cid.cid_num;
3536         n = c->cid.cid_name;
3537
3538         /* Now build request */ 
3539         memset(&ied, 0, sizeof(ied));
3540
3541         /* On new call, first IE MUST be IAX version of caller */
3542         iax_ie_append_short(&ied, IAX_IE_VERSION, IAX_PROTO_VERSION);
3543         iax_ie_append_str(&ied, IAX_IE_CALLED_NUMBER, pds.exten);
3544         if (pds.options && strchr(pds.options, 'a')) {
3545                 /* Request auto answer */
3546                 iax_ie_append(&ied, IAX_IE_AUTOANSWER);
3547         }
3548
3549         iax_ie_append_str(&ied, IAX_IE_CODEC_PREFS, cai.prefs);
3550
3551         if (l) {
3552                 iax_ie_append_str(&ied, IAX_IE_CALLING_NUMBER, l);
3553                 iax_ie_append_byte(&ied, IAX_IE_CALLINGPRES, c->cid.cid_pres);
3554         } else {
3555                 if (n)
3556                         iax_ie_append_byte(&ied, IAX_IE_CALLINGPRES, c->cid.cid_pres);
3557                 else
3558                         iax_ie_append_byte(&ied, IAX_IE_CALLINGPRES, AST_PRES_NUMBER_NOT_AVAILABLE);
3559         }
3560
3561         iax_ie_append_byte(&ied, IAX_IE_CALLINGTON, c->cid.cid_ton);
3562         iax_ie_append_short(&ied, IAX_IE_CALLINGTNS, c->cid.cid_tns);
3563
3564         if (n)
3565                 iax_ie_append_str(&ied, IAX_IE_CALLING_NAME, n);
3566         if (ast_test_flag(iaxs[callno], IAX_SENDANI) && c->cid.cid_ani)
3567                 iax_ie_append_str(&ied, IAX_IE_CALLING_ANI, c->cid.cid_ani);
3568
3569         if (!ast_strlen_zero(c->language))
3570                 iax_ie_append_str(&ied, IAX_IE_LANGUAGE, c->language);
3571         if (!ast_strlen_zero(c->cid.cid_dnid))
3572                 iax_ie_append_str(&ied, IAX_IE_DNID, c->cid.cid_dnid);
3573         if (!ast_strlen_zero(c->cid.cid_rdnis))
3574                 iax_ie_append_str(&ied, IAX_IE_RDNIS, c->cid.cid_rdnis);
3575
3576         if (pds.context)
3577                 iax_ie_append_str(&ied, IAX_IE_CALLED_CONTEXT, pds.context);
3578
3579         if (pds.username)
3580                 iax_ie_append_str(&ied, IAX_IE_USERNAME, pds.username);
3581
3582         if (cai.encmethods)
3583                 iax_ie_append_short(&ied, IAX_IE_ENCRYPTION, cai.encmethods);
3584
3585         ast_mutex_lock(&iaxsl[callno]);
3586
3587         if (!ast_strlen_zero(c->context))
3588                 ast_string_field_set(iaxs[callno], context, c->context);
3589
3590         if (pds.username)
3591                 ast_string_field_set(iaxs[callno], username, pds.username);
3592
3593         iaxs[callno]->encmethods = cai.encmethods;
3594
3595         iaxs[callno]->adsi = cai.adsi;
3596         
3597         ast_string_field_set(iaxs[callno], mohinterpret, cai.mohinterpret);
3598         ast_string_field_set(iaxs[callno], mohsuggest, cai.mohsuggest);
3599
3600         if (pds.key)
3601                 ast_string_field_set(iaxs[callno], outkey, pds.key);
3602         if (pds.password)
3603                 ast_string_field_set(iaxs[callno], secret, pds.password);
3604
3605         iax_ie_append_int(&ied, IAX_IE_FORMAT, c->nativeformats);
3606         iax_ie_append_int(&ied, IAX_IE_CAPABILITY, iaxs[callno]->capability);
3607         iax_ie_append_short(&ied, IAX_IE_ADSICPE, c->adsicpe);
3608         iax_ie_append_int(&ied, IAX_IE_DATETIME, iax2_datetime(cai.timezone));
3609
3610         if (iaxs[callno]->maxtime) {
3611                 /* Initialize pingtime and auto-congest time */
3612                 iaxs[callno]->pingtime = iaxs[callno]->maxtime / 2;
3613                 iaxs[callno]->initid = iax2_sched_add(sched, iaxs[callno]->maxtime * 2, auto_congest, CALLNO_TO_PTR(callno));
3614         } else if (autokill) {
3615                 iaxs[callno]->pingtime = autokill / 2;
3616                 iaxs[callno]->initid = iax2_sched_add(sched, autokill * 2, auto_congest, CALLNO_TO_PTR(callno));
3617         }
3618
3619         /* Check if there is an OSP token set by IAXCHANINFO function */
3620         osp_token_ptr = iaxs[callno]->osptoken;
3621         if (!ast_strlen_zero(osp_token_ptr)) {
3622                 if ((osp_token_length = strlen(osp_token_ptr)) <= IAX_MAX_OSPTOKEN_SIZE) {
3623                         osp_block_index = 0;
3624                         while (osp_token_length > 0) {
3625                                 osp_block_length = IAX_MAX_OSPBLOCK_SIZE < osp_token_length ? IAX_MAX_OSPBLOCK_SIZE : osp_token_length;
3626                                 osp_buffer[0] = osp_block_index;
3627                                 memcpy(osp_buffer + 1, osp_token_ptr, osp_block_length);
3628                                 iax_ie_append_raw(&ied, IAX_IE_OSPTOKEN, osp_buffer, osp_block_length + 1);
3629                                 osp_block_index++;
3630                                 osp_token_ptr += osp_block_length;
3631                                 osp_token_length -= osp_block_length;
3632                         } 
3633                 } else
3634                         ast_log(LOG_WARNING, "OSP token is too long\n");
3635         } else if (iaxdebug)
3636                 ast_debug(1, "OSP token is undefined\n");
3637
3638         /* send the command using the appropriate socket for this peer */
3639         iaxs[callno]->sockfd = cai.sockfd;
3640
3641         /* Add remote vars */
3642         if (variablestore) {
3643                 AST_LIST_HEAD(, ast_var_t) *variablelist = variablestore->data;
3644                 AST_LIST_LOCK(variablelist);
3645                 AST_LIST_TRAVERSE(variablelist, var, entries) {
3646                         char tmp[256];
3647                         int i;
3648                         /* Automatically divide the value up into sized chunks */
3649                         for (i = 0; i < strlen(ast_var_value(var)); i += 255 - (strlen(ast_var_name(var)) + 1)) {
3650                                 snprintf(tmp, sizeof(tmp), "%s=%s", ast_var_name(var), ast_var_value(var) + i);
3651                                 iax_ie_append_str(&ied, IAX_IE_VARIABLE, tmp);
3652                         }
3653                 }
3654                 AST_LIST_UNLOCK(variablelist);
3655         }
3656
3657         /* Transmit the string in a "NEW" request */
3658         send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_NEW, 0, ied.buf, ied.pos, -1);
3659
3660         ast_mutex_unlock(&iaxsl[callno]);
3661         ast_setstate(c, AST_STATE_RINGING);
3662
3663         return 0;
3664 }
3665
3666 static int iax2_hangup(struct ast_channel *c) 
3667 {
3668         unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
3669         int alreadygone;
3670         struct iax_ie_data ied;
3671         memset(&ied, 0, sizeof(ied));
3672         ast_mutex_lock(&iaxsl[callno]);
3673         if (callno && iaxs[callno]) {
3674                 ast_debug(1, "We're hanging up %s now...\n", c->name);
3675                 alreadygone = ast_test_flag(iaxs[callno], IAX_ALREADYGONE);