another round of version tag updates, along with 'show version files' pattern filtering
[asterisk/asterisk.git] / channels / chan_iax2.c
1 /*
2  * Asterisk -- A telephony toolkit for Linux.
3  *
4  * Implementation of Inter-Asterisk eXchange Version 2
5  *
6  * Copyright (C) 2003 - 2005, Digium, Inc.
7  *
8  * Mark Spencer <markster@digium.com>
9  *
10  * This program is free software, distributed under the terms of
11  * the GNU General Public License
12  */
13
14 #include "asterisk.h"
15
16 ASTERISK_FILE_VERSION("$Revision$")
17
18 #include "asterisk/lock.h"
19 #include "asterisk/frame.h" 
20 #include "asterisk/channel.h"
21 #include "asterisk/logger.h"
22 #include "asterisk/module.h"
23 #include "asterisk/pbx.h"
24 #include "asterisk/sched.h"
25 #include "asterisk/io.h"
26 #include "asterisk/config.h"
27 #include "asterisk/options.h"
28 #include "asterisk/cli.h"
29 #include "asterisk/translate.h"
30 #include "asterisk/md5.h"
31 #include "asterisk/cdr.h"
32 #include "asterisk/crypto.h"
33 #include "asterisk/acl.h"
34 #include "asterisk/manager.h"
35 #include "asterisk/callerid.h"
36 #include "asterisk/app.h"
37 #include "asterisk/astdb.h"
38 #include "asterisk/musiconhold.h"
39 #include "asterisk/features.h"
40 #include "asterisk/utils.h"
41 #include "asterisk/causes.h"
42 #include "asterisk/localtime.h"
43 #include "asterisk/aes.h"
44 #include "asterisk/dnsmgr.h"
45 #include <sys/mman.h>
46 #include <arpa/inet.h>
47 #include <dirent.h>
48 #include <sys/socket.h>
49 #include <netinet/in.h>
50 #include <netinet/in_systm.h>
51 #include <netinet/ip.h>
52 #include <sys/time.h>
53 #include <sys/signal.h>
54 #include <signal.h>
55 #include <stdlib.h>
56 #include <stdio.h>
57 #include <string.h>
58 #include <errno.h>
59 #include <unistd.h>
60 #include <netdb.h>
61 #include <fcntl.h>
62 #include <sys/types.h>
63 #include <sys/stat.h>
64 #include <regex.h>
65 #ifdef IAX_TRUNKING
66 #include <sys/ioctl.h>
67 #ifdef __linux__
68 #include <linux/zaptel.h>
69 #else
70 #include <zaptel.h>
71 #endif /* __linux__ */
72 #endif
73 #include "iax2.h"
74 #include "iax2-parser.h"
75 #include "iax2-provision.h"
76 #include "asterisk.h"
77
78 /* Define NEWJB to use the new channel independent jitterbuffer,
79  * otherwise, use the old jitterbuffer */
80 #define NEWJB
81
82 #ifdef NEWJB
83 #include "../jitterbuf.h"
84 #endif
85
86 #ifndef IPTOS_MINCOST
87 #define IPTOS_MINCOST 0x02
88 #endif
89
90 #ifdef SO_NO_CHECK
91 static int nochecksums = 0;
92 #endif
93
94 /*
95  * Uncomment to try experimental IAX bridge optimization,
96  * designed to reduce latency when IAX calls cannot
97  * be trasnferred
98  */
99
100 #define BRIDGE_OPTIMIZATION 
101
102 #define PTR_TO_CALLNO(a) ((unsigned short)(unsigned long)(a))
103 #define CALLNO_TO_PTR(a) ((void *)(unsigned long)(a))
104
105 #define DEFAULT_RETRY_TIME 1000
106 #define MEMORY_SIZE 100
107 #define DEFAULT_DROP 3
108 /* Flag to use with trunk calls, keeping these calls high up.  It halves our effective use
109    but keeps the division between trunked and non-trunked better. */
110 #define TRUNK_CALL_START        0x4000
111
112 #define DEBUG_SUPPORT
113
114 #define MIN_REUSE_TIME          60      /* Don't reuse a call number within 60 seconds */
115
116 /* Sample over last 100 units to determine historic jitter */
117 #define GAMMA (0.01)
118
119 static struct ast_codec_pref prefs;
120
121 static const char desc[] = "Inter Asterisk eXchange (Ver 2)";
122 static const char tdesc[] = "Inter Asterisk eXchange Driver (Ver 2)";
123 static const char channeltype[] = "IAX2";
124
125 static char context[80] = "default";
126
127 static char language[MAX_LANGUAGE] = "";
128 static char regcontext[AST_MAX_EXTENSION] = "";
129
130 static int max_retries = 4;
131 static int ping_time = 20;
132 static int lagrq_time = 10;
133 static int maxtrunkcall = TRUNK_CALL_START;
134 static int maxnontrunkcall = 1;
135 static int maxjitterbuffer=1000;
136 #ifdef NEWJB
137 static int resyncthreshold=1000;
138 #endif
139 static int jittershrinkrate=2;
140 static int trunkfreq = 20;
141 static int send_trunktimestamps = 1;
142 static int authdebug = 1;
143 static int autokill = 0;
144 static int iaxcompat = 0;
145
146 static int iaxdefaultdpcache=10 * 60;   /* Cache dialplan entries for 10 minutes by default */
147
148 static int iaxdefaulttimeout = 5;               /* Default to wait no more than 5 seconds for a reply to come back */
149
150 static int tos = 0;
151
152 static int expirey = IAX_DEFAULT_REG_EXPIRE;
153
154 static int timingfd = -1;                               /* Timing file descriptor */
155
156 static struct ast_netsock_list netsock;
157 static int defaultsockfd = -1;
158
159 static int usecnt;
160 AST_MUTEX_DEFINE_STATIC(usecnt_lock);
161
162 int (*iax2_regfunk)(char *username, int onoff) = NULL;
163
164 /* Ethernet, etc */
165 #define IAX_CAPABILITY_FULLBANDWIDTH    0xFFFF
166 /* T1, maybe ISDN */
167 #define IAX_CAPABILITY_MEDBANDWIDTH     (IAX_CAPABILITY_FULLBANDWIDTH & \
168                                                                         ~AST_FORMAT_SLINEAR & \
169                                                                         ~AST_FORMAT_ULAW & \
170                                                                         ~AST_FORMAT_ALAW) 
171 /* A modem */
172 #define IAX_CAPABILITY_LOWBANDWIDTH             (IAX_CAPABILITY_MEDBANDWIDTH & \
173                                                                         ~AST_FORMAT_G726 & \
174                                                                         ~AST_FORMAT_ADPCM)
175
176 #define IAX_CAPABILITY_LOWFREE          (IAX_CAPABILITY_LOWBANDWIDTH & \
177                                                                          ~AST_FORMAT_G723_1)
178
179
180 #define DEFAULT_MAXMS           2000            /* Must be faster than 2 seconds by default */
181 #define DEFAULT_FREQ_OK         60 * 1000               /* How often to check for the host to be up */
182 #define DEFAULT_FREQ_NOTOK      10 * 1000               /* How often to check, if the host is down... */
183
184 static  struct io_context *io;
185 static  struct sched_context *sched;
186
187 static int iax2_capability = IAX_CAPABILITY_FULLBANDWIDTH;
188
189 static int iax2_dropcount = DEFAULT_DROP;
190
191 static int iaxdebug = 0;
192
193 static int iaxtrunkdebug = 0;
194
195 static int test_losspct = 0;
196 #ifdef IAXTESTS
197 static int test_late = 0;
198 static int test_resync = 0;
199 static int test_jit = 0;
200 static int test_jitpct = 0;
201 #endif /* IAXTESTS */
202
203 static char accountcode[AST_MAX_ACCOUNT_CODE];
204 static int amaflags = 0;
205 static int delayreject = 0;
206 static int iax2_encryption = 0;
207
208 static struct ast_flags globalflags = {0};
209
210 static pthread_t netthreadid = AST_PTHREADT_NULL;
211
212 #define IAX_STATE_STARTED               (1 << 0)
213 #define IAX_STATE_AUTHENTICATED         (1 << 1)
214 #define IAX_STATE_TBD                   (1 << 2)
215
216 struct iax2_context {
217         char context[AST_MAX_EXTENSION];
218         struct iax2_context *next;
219 };
220
221 #define IAX_HASCALLERID         (1 << 0)        /* CallerID has been specified */
222 #define IAX_DELME               (1 << 1)        /* Needs to be deleted */
223 #define IAX_TEMPONLY            (1 << 2)        /* Temporary (realtime) */
224 #define IAX_TRUNK               (1 << 3)        /* Treat as a trunk */
225 #define IAX_NOTRANSFER          (1 << 4)        /* Don't native bridge */
226 #define IAX_USEJITTERBUF        (1 << 5)        /* Use jitter buffer */
227 #define IAX_DYNAMIC             (1 << 6)        /* dynamic peer */
228 #define IAX_SENDANI             (1 << 7)        /* Send ANI along with CallerID */
229 #define IAX_MESSAGEDETAIL       (1 << 8)        /* Show exact numbers */
230 #define IAX_ALREADYGONE         (1 << 9)        /* Already disconnected */
231 #define IAX_PROVISION           (1 << 10)       /* This is a provisioning request */
232 #define IAX_QUELCH              (1 << 11)       /* Whether or not we quelch audio */
233 #define IAX_ENCRYPTED           (1 << 12)       /* Whether we should assume encrypted tx/rx */
234 #define IAX_KEYPOPULATED        (1 << 13)       /* Whether we have a key populated */
235 #define IAX_CODEC_USER_FIRST    (1 << 14)       /* are we willing to let the other guy choose the codec? */
236 #define IAX_CODEC_NOPREFS       (1 << 15)       /* Force old behaviour by turning off prefs */
237 #define IAX_CODEC_NOCAP         (1 << 16)       /* only consider requested format and ignore capabilities*/
238 #define IAX_RTCACHEFRIENDS      (1 << 17)       /* let realtime stay till your reload */
239 #define IAX_RTNOUPDATE          (1 << 18)       /* Don't send a realtime update */
240 #define IAX_RTAUTOCLEAR         (1 << 19)       /* erase me on expire */ 
241 #define IAX_FORCEJITTERBUF      (1 << 20)       /* Force jitterbuffer, even when bridged to a channel that can take jitter */ 
242
243 static int global_rtautoclear = 120;
244
245 static int reload_config(void);
246 static int iax2_reload(int fd, int argc, char *argv[]);
247
248
249 struct iax2_user {
250         char name[80];
251         char secret[80];
252         char dbsecret[80];
253         int authmethods;
254         int encmethods;
255         char accountcode[AST_MAX_ACCOUNT_CODE];
256         char inkeys[80];                                /* Key(s) this user can use to authenticate to us */
257         char language[MAX_LANGUAGE];
258         int amaflags;
259         unsigned int flags;
260         int capability;
261         char cid_num[AST_MAX_EXTENSION];
262         char cid_name[AST_MAX_EXTENSION];
263         struct ast_codec_pref prefs;
264         struct ast_ha *ha;
265         struct iax2_context *contexts;
266         struct iax2_user *next;
267         struct ast_variable *vars;
268 };
269
270 struct iax2_peer {
271         char name[80];
272         char username[80];              
273         char secret[80];
274         char dbsecret[80];
275         char outkey[80];                                /* What key we use to talk to this peer */
276         char context[AST_MAX_EXTENSION];                /* For transfers only */
277         char regexten[AST_MAX_EXTENSION];               /* Extension to register (if regcontext is used) */
278         char peercontext[AST_MAX_EXTENSION];            /* Context to pass to peer */
279         char mailbox[AST_MAX_EXTENSION];                /* Mailbox */
280         struct ast_codec_pref prefs;
281         struct ast_dnsmgr_entry *dnsmgr;                /* DNS refresh manager */
282         struct sockaddr_in addr;
283         int formats;
284         int sockfd;                                     /* Socket to use for transmission */
285         struct in_addr mask;
286         unsigned int flags;
287
288         /* Dynamic Registration fields */
289         struct sockaddr_in defaddr;                     /* Default address if there is one */
290         int authmethods;                                /* Authentication methods (IAX_AUTH_*) */
291         int encmethods;                                 /* Encryption methods (IAX_ENCRYPT_*) */
292         char inkeys[80];                                /* Key(s) this peer can use to authenticate to us */
293
294         /* Suggested caller id if registering */
295         char cid_num[AST_MAX_EXTENSION];                /* Default context (for transfer really) */
296         char cid_name[AST_MAX_EXTENSION];               /* Default context (for transfer really) */
297         
298         int expire;                                     /* Schedule entry for expirey */
299         int expirey;                                    /* How soon to expire */
300         int capability;                                 /* Capability */
301         char zonetag[80];                               /* Time Zone */
302
303         /* Qualification */
304         int callno;                                     /* Call number of POKE request */
305         int pokeexpire;                                 /* When to expire poke */
306         int lastms;                                     /* How long last response took (in ms), or -1 for no response */
307         int maxms;                                      /* Max ms we will accept for the host to be up, 0 to not monitor */
308         
309         struct ast_ha *ha;
310         struct iax2_peer *next;
311 };
312
313 #define IAX2_TRUNK_PREFACE (sizeof(struct iax_frame) + sizeof(struct ast_iax2_meta_hdr) + sizeof(struct ast_iax2_meta_trunk_hdr))
314
315 static struct iax2_trunk_peer {
316         ast_mutex_t lock;
317         int sockfd;
318         struct sockaddr_in addr;
319         struct timeval txtrunktime;             /* Transmit trunktime */
320         struct timeval rxtrunktime;             /* Receive trunktime */
321         struct timeval lasttxtime;              /* Last transmitted trunktime */
322         struct timeval trunkact;                /* Last trunk activity */
323         unsigned int lastsent;                  /* Last sent time */
324         /* Trunk data and length */
325         unsigned char *trunkdata;
326         unsigned int trunkdatalen;
327         unsigned int trunkdataalloc;
328         struct iax2_trunk_peer *next;
329         int trunkerror;
330         int calls;
331 } *tpeers = NULL;
332
333 AST_MUTEX_DEFINE_STATIC(tpeerlock);
334
335 struct iax_firmware {
336         struct iax_firmware *next;
337         int fd;
338         int mmaplen;
339         int dead;
340         struct ast_iax2_firmware_header *fwh;
341         unsigned char *buf;
342 };
343
344 #define REG_STATE_UNREGISTERED  0
345 #define REG_STATE_REGSENT       1
346 #define REG_STATE_AUTHSENT      2
347 #define REG_STATE_REGISTERED    3
348 #define REG_STATE_REJECTED      4
349 #define REG_STATE_TIMEOUT       5
350 #define REG_STATE_NOAUTH        6
351
352 #define TRANSFER_NONE           0
353 #define TRANSFER_BEGIN          1
354 #define TRANSFER_READY          2
355 #define TRANSFER_RELEASED       3
356 #define TRANSFER_PASSTHROUGH    4
357
358 struct iax2_registry {
359         struct sockaddr_in addr;                /* Who we connect to for registration purposes */
360         char username[80];
361         char secret[80];                        /* Password or key name in []'s */
362         char random[80];
363         int expire;                             /* Sched ID of expiration */
364         int refresh;                            /* How often to refresh */
365         int regstate;
366         int messages;                           /* Message count */
367         int callno;                             /* Associated call number if applicable */
368         struct sockaddr_in us;                  /* Who the server thinks we are */
369         struct iax2_registry *next;
370 };
371
372 static struct iax2_registry *registrations;
373
374 /* Don't retry more frequently than every 10 ms, or less frequently than every 5 seconds */
375 #define MIN_RETRY_TIME  100
376 #define MAX_RETRY_TIME  10000
377
378 #define MAX_JITTER_BUFFER 50
379 #define MIN_JITTER_BUFFER 10
380
381 #define DEFAULT_TRUNKDATA       640 * 10                /* 40ms, uncompressed linear * 10 channels */
382 #define MAX_TRUNKDATA           640 * 200               /* 40ms, uncompressed linear * 200 channels */
383
384 #define MAX_TIMESTAMP_SKEW      160                     /* maximum difference between actual and predicted ts for sending */
385
386 /* If consecutive voice frame timestamps jump by more than this many milliseconds, then jitter buffer will resync */
387 #define TS_GAP_FOR_JB_RESYNC    5000
388
389 /* If we have more than this much excess real jitter buffer, shrink it. */
390 static int max_jitter_buffer = MAX_JITTER_BUFFER;
391 /* If we have less than this much excess real jitter buffer, enlarge it. */
392 static int min_jitter_buffer = MIN_JITTER_BUFFER;
393
394 struct iax_rr {
395         int jitter;
396         int losspct;
397         int losscnt;
398         int packets;
399         int delay;
400         int dropped;
401         int ooo;
402 };
403
404 struct chan_iax2_pvt {
405         /* Socket to send/receive on for this call */
406         int sockfd;
407         /* Last received voice format */
408         int voiceformat;
409         /* Last received voice format */
410         int videoformat;
411         /* Last sent voice format */
412         int svoiceformat;
413         /* Last sent video format */
414         int svideoformat;
415         /* What we are capable of sending */
416         int capability;
417         /* Last received timestamp */
418         unsigned int last;
419         /* Last sent timestamp - never send the same timestamp twice in a single call */
420         unsigned int lastsent;
421         /* Next outgoing timestamp if everything is good */
422         unsigned int nextpred;
423         /* True if the last voice we transmitted was not silence/CNG */
424         int notsilenttx;
425         /* Ping time */
426         unsigned int pingtime;
427         /* Max time for initial response */
428         int maxtime;
429         /* Peer Address */
430         struct sockaddr_in addr;
431         struct ast_codec_pref prefs;
432         /* Our call number */
433         unsigned short callno;
434         /* Peer callno */
435         unsigned short peercallno;
436         /* Peer selected format */
437         int peerformat;
438         /* Peer capability */
439         int peercapability;
440         /* timeval that we base our transmission on */
441         struct timeval offset;
442         /* timeval that we base our delivery on */
443         struct timeval rxcore;
444 #ifdef NEWJB
445         /* The jitterbuffer */
446         jitterbuf *jb;
447         /* active jb read scheduler id */
448         int jbid;                       
449 #else
450         /* Historical delivery time */
451         int history[MEMORY_SIZE];
452         /* Current base jitterbuffer */
453         int jitterbuffer;
454         /* Current jitter measure */
455         int jitter;
456         /* Historic jitter value */
457         int historicjitter;
458 #endif
459         /* LAG */
460         int lag;
461         /* Error, as discovered by the manager */
462         int error;
463         /* Owner if we have one */
464         struct ast_channel *owner;
465         /* What's our state? */
466         int state;
467         /* Expirey (optional) */
468         int expirey;
469         /* Next outgoing sequence number */
470         unsigned char oseqno;
471         /* Next sequence number they have not yet acknowledged */
472         unsigned char rseqno;
473         /* Next incoming sequence number */
474         unsigned char iseqno;
475         /* Last incoming sequence number we have acknowledged */
476         unsigned char aseqno;
477         /* Peer name */
478         char peer[80];
479         /* Default Context */
480         char context[80];
481         /* Caller ID if available */
482         char cid_num[80];
483         char cid_name[80];
484         /* Hidden Caller ID (i.e. ANI) if appropriate */
485         char ani[80];
486         /* DNID */
487         char dnid[80];
488         /* Requested Extension */
489         char exten[AST_MAX_EXTENSION];
490         /* Expected Username */
491         char username[80];
492         /* Expected Secret */
493         char secret[80];
494         /* permitted authentication methods */
495         int authmethods;
496         /* permitted encryption methods */
497         int encmethods;
498         /* MD5 challenge */
499         char challenge[10];
500         /* Public keys permitted keys for incoming authentication */
501         char inkeys[80];
502         /* Private key for outgoing authentication */
503         char outkey[80];
504         /* Encryption AES-128 Key */
505         aes_encrypt_ctx ecx;
506         /* Decryption AES-128 Key */
507         aes_decrypt_ctx dcx;
508         /* 32 bytes of semi-random data */
509         char semirand[32];
510         /* Preferred language */
511         char language[MAX_LANGUAGE];
512         /* Hostname/peername for naming purposes */
513         char host[80];
514         /* Associated registry */
515         struct iax2_registry *reg;
516         /* Associated peer for poking */
517         struct iax2_peer *peerpoke;
518         /* IAX_ flags */
519         unsigned int flags;
520
521         /* Transferring status */
522         int transferring;
523         /* Transfer identifier */
524         int transferid;
525         /* Who we are IAX transfering to */
526         struct sockaddr_in transfer;
527         /* What's the new call number for the transfer */
528         unsigned short transfercallno;
529         /* Transfer decrypt AES-128 Key */
530         aes_encrypt_ctx tdcx;
531
532         /* Status of knowledge of peer ADSI capability */
533         int peeradsicpe;
534         
535         /* Who we are bridged to */
536         unsigned short bridgecallno;
537         unsigned int bridgesfmt;
538         struct ast_trans_pvt *bridgetrans;
539         
540         int pingid;                     /* Transmit PING request */
541         int lagid;                      /* Retransmit lag request */
542         int autoid;                     /* Auto hangup for Dialplan requestor */
543         int authid;                     /* Authentication rejection ID */
544         int authfail;           /* Reason to report failure */
545         int initid;                     /* Initial peer auto-congest ID (based on qualified peers) */
546         int calling_ton;
547         int calling_tns;
548         int calling_pres;
549         char dproot[AST_MAX_EXTENSION];
550         char accountcode[AST_MAX_ACCOUNT_CODE];
551         int amaflags;
552         struct iax2_dpcache *dpentries;
553         struct ast_variable *vars;
554         /* last received remote rr */
555         struct iax_rr remote_rr;
556         /* Current base time: (just for stats) */
557         int min;
558         /* Dropped frame count: (just for stats) */
559         int frames_dropped;
560         /* received frame count: (just for stats) */
561         int frames_received;
562 };
563
564 static struct ast_iax2_queue {
565         struct iax_frame *head;
566         struct iax_frame *tail;
567         int count;
568         ast_mutex_t lock;
569 } iaxq;
570
571 static struct ast_user_list {
572         struct iax2_user *users;
573         ast_mutex_t lock;
574 } userl;
575
576 static struct ast_peer_list {
577         struct iax2_peer *peers;
578         ast_mutex_t lock;
579 } peerl;
580
581 static struct ast_firmware_list {
582         struct iax_firmware *wares;
583         ast_mutex_t lock;
584 } waresl;
585
586 /* Extension exists */
587 #define CACHE_FLAG_EXISTS               (1 << 0)
588 /* Extension is nonexistent */
589 #define CACHE_FLAG_NONEXISTENT  (1 << 1)
590 /* Extension can exist */
591 #define CACHE_FLAG_CANEXIST             (1 << 2)
592 /* Waiting to hear back response */
593 #define CACHE_FLAG_PENDING              (1 << 3)
594 /* Timed out */
595 #define CACHE_FLAG_TIMEOUT              (1 << 4)
596 /* Request transmitted */
597 #define CACHE_FLAG_TRANSMITTED  (1 << 5)
598 /* Timeout */
599 #define CACHE_FLAG_UNKNOWN              (1 << 6)
600 /* Matchmore */
601 #define CACHE_FLAG_MATCHMORE    (1 << 7)
602
603 static struct iax2_dpcache {
604         char peercontext[AST_MAX_EXTENSION];
605         char exten[AST_MAX_EXTENSION];
606         struct timeval orig;
607         struct timeval expirey;
608         int flags;
609         unsigned short callno;
610         int waiters[256];
611         struct iax2_dpcache *next;
612         struct iax2_dpcache *peer;      /* For linking in peers */
613 } *dpcache;
614
615 AST_MUTEX_DEFINE_STATIC(dpcache_lock);
616
617 static void reg_source_db(struct iax2_peer *p);
618 static struct iax2_peer *realtime_peer(const char *peername);
619
620 static void destroy_peer(struct iax2_peer *peer);
621 static int ast_cli_netstats(int fd, int limit_fmt);
622
623 static void iax_debug_output(const char *data)
624 {
625         if (iaxdebug)
626                 ast_verbose("%s", data);
627 }
628
629 static void iax_error_output(const char *data)
630 {
631         ast_log(LOG_WARNING, "%s", data);
632 }
633
634 #ifdef NEWJB
635 static void jb_error_output(const char *fmt, ...)
636 {
637         va_list args;
638         char buf[1024];
639
640         va_start(args, fmt);
641         vsnprintf(buf, 1024, fmt, args);
642         va_end(args);
643
644         ast_log(LOG_ERROR, buf);
645 }
646
647 static void jb_warning_output(const char *fmt, ...)
648 {
649         va_list args;
650         char buf[1024];
651
652         va_start(args, fmt);
653         vsnprintf(buf, 1024, fmt, args);
654         va_end(args);
655
656         ast_log(LOG_WARNING, buf);
657 }
658
659 static void jb_debug_output(const char *fmt, ...)
660 {
661         va_list args;
662         char buf[1024];
663         if(!iaxdebug) return;
664
665         va_start(args, fmt);
666         vsnprintf(buf, 1024, fmt, args);
667         va_end(args);
668
669         ast_verbose(buf);
670 }
671 #endif
672
673
674 /* XXX We probably should use a mutex when working with this XXX */
675 static struct chan_iax2_pvt *iaxs[IAX_MAX_CALLS];
676 static ast_mutex_t iaxsl[IAX_MAX_CALLS];
677 static struct timeval lastused[IAX_MAX_CALLS];
678
679
680 static int send_command(struct chan_iax2_pvt *, char, int, unsigned int, const char *, int, int);
681 static int send_command_locked(unsigned short callno, char, int, unsigned int, const char *, int, int);
682 static int send_command_immediate(struct chan_iax2_pvt *, char, int, unsigned int, const char *, int, int);
683 static int send_command_final(struct chan_iax2_pvt *, char, int, unsigned int, const char *, int, int);
684 static int send_command_transfer(struct chan_iax2_pvt *, char, int, unsigned int, const char *, int);
685 static struct iax2_user *build_user(const char *name, struct ast_variable *v, int temponly);
686 static void destroy_user(struct iax2_user *user);
687 static int expire_registry(void *data);
688 static int iax2_write(struct ast_channel *c, struct ast_frame *f);
689 static int iax2_do_register(struct iax2_registry *reg);
690 static void prune_peers(void);
691 static int iax2_poke_peer(struct iax2_peer *peer, int heldcall);
692 static int iax2_provision(struct sockaddr_in *end, char *dest, const char *template, int force);
693
694 static struct ast_channel *iax2_request(const char *type, int format, void *data, int *cause);
695 static int iax2_devicestate(void *data);
696 static int iax2_digit(struct ast_channel *c, char digit);
697 static int iax2_sendtext(struct ast_channel *c, const char *text);
698 static int iax2_sendimage(struct ast_channel *c, struct ast_frame *img);
699 static int iax2_sendhtml(struct ast_channel *c, int subclass, const char *data, int datalen);
700 static int iax2_call(struct ast_channel *c, char *dest, int timeout);
701 static int iax2_hangup(struct ast_channel *c);
702 static int iax2_answer(struct ast_channel *c);
703 static struct ast_frame *iax2_read(struct ast_channel *c);
704 static int iax2_write(struct ast_channel *c, struct ast_frame *f);
705 static int iax2_indicate(struct ast_channel *c, int condition);
706 static int iax2_setoption(struct ast_channel *c, int option, void *data, int datalen);
707 static int iax2_bridge(struct ast_channel *c0, struct ast_channel *c1, int flags, struct ast_frame **fo, struct ast_channel **rc);
708 static int iax2_transfer(struct ast_channel *c, const char *dest);
709 static int iax2_fixup(struct ast_channel *oldchannel, struct ast_channel *newchan);
710
711 static const struct ast_channel_tech iax2_tech = {
712         .type = channeltype,
713         .description = tdesc,
714         .capabilities = IAX_CAPABILITY_FULLBANDWIDTH,
715         .properties = AST_CHAN_TP_WANTSJITTER,
716         .requester = iax2_request,
717         .devicestate = iax2_devicestate,
718         .send_digit = iax2_digit,
719         .send_text = iax2_sendtext,
720         .send_image = iax2_sendimage,
721         .send_html = iax2_sendhtml,
722         .call = iax2_call,
723         .hangup = iax2_hangup,
724         .answer = iax2_answer,
725         .read = iax2_read,
726         .write = iax2_write,
727         .write_video = iax2_write,
728         .indicate = iax2_indicate,
729         .setoption = iax2_setoption,
730         .bridge = iax2_bridge,
731         .transfer = iax2_transfer,
732         .fixup = iax2_fixup,
733 };
734
735 static int send_ping(void *data)
736 {
737         int callno = (long)data;
738         /* Ping only if it's real, not if it's bridged */
739         if (iaxs[callno]) {
740 #ifdef BRIDGE_OPTIMIZATION
741                 if (!iaxs[callno]->bridgecallno)
742 #endif
743                         send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_PING, 0, NULL, 0, -1);
744                 return 1;
745         } else
746                 return 0;
747 }
748
749 static int get_encrypt_methods(const char *s)
750 {
751         int e;
752         if (!strcasecmp(s, "aes128"))
753                 e = IAX_ENCRYPT_AES128;
754         else if (ast_true(s))
755                 e = IAX_ENCRYPT_AES128;
756         else
757                 e = 0;
758         return e;
759 }
760
761 static int send_lagrq(void *data)
762 {
763         int callno = (long)data;
764         /* Ping only if it's real not if it's bridged */
765         if (iaxs[callno]) {
766 #ifdef BRIDGE_OPTIMIZATION
767                 if (!iaxs[callno]->bridgecallno)
768 #endif          
769                         send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_LAGRQ, 0, NULL, 0, -1);
770                 return 1;
771         } else
772                 return 0;
773 }
774
775 static unsigned char compress_subclass(int subclass)
776 {
777         int x;
778         int power=-1;
779         /* If it's 128 or smaller, just return it */
780         if (subclass < IAX_FLAG_SC_LOG)
781                 return subclass;
782         /* Otherwise find its power */
783         for (x = 0; x < IAX_MAX_SHIFT; x++) {
784                 if (subclass & (1 << x)) {
785                         if (power > -1) {
786                                 ast_log(LOG_WARNING, "Can't compress subclass %d\n", subclass);
787                                 return 0;
788                         } else
789                                 power = x;
790                 }
791         }
792         return power | IAX_FLAG_SC_LOG;
793 }
794
795 static int uncompress_subclass(unsigned char csub)
796 {
797         /* If the SC_LOG flag is set, return 2^csub otherwise csub */
798         if (csub & IAX_FLAG_SC_LOG) {
799                 /* special case for 'compressed' -1 */
800                 if (csub == 0xff)
801                         return -1;
802                 else
803                         return 1 << (csub & ~IAX_FLAG_SC_LOG & IAX_MAX_SHIFT);
804         }
805         else
806                 return csub;
807 }
808
809 static struct iax2_peer *find_peer(const char *name, int realtime) 
810 {
811         struct iax2_peer *peer;
812         ast_mutex_lock(&peerl.lock);
813         for(peer = peerl.peers; peer; peer = peer->next) {
814                 if (!strcasecmp(peer->name, name)) {
815                         break;
816                 }
817         }
818         ast_mutex_unlock(&peerl.lock);
819         if(!peer && realtime)
820                 peer = realtime_peer(name);
821         return peer;
822 }
823
824 static int iax2_getpeername(struct sockaddr_in sin, char *host, int len, int lockpeer)
825 {
826         struct iax2_peer *peer;
827         int res = 0;
828         if (lockpeer)
829                 ast_mutex_lock(&peerl.lock);
830         peer = peerl.peers;
831         while(peer) {
832                 if ((peer->addr.sin_addr.s_addr == sin.sin_addr.s_addr) &&
833                                 (peer->addr.sin_port == sin.sin_port)) {
834                                         ast_copy_string(host, peer->name, len);
835                                         res = 1;
836                                         break;
837                 }
838                 peer = peer->next;
839         }
840         if (lockpeer)
841                 ast_mutex_unlock(&peerl.lock);
842         return res;
843 }
844
845 static struct chan_iax2_pvt *new_iax(struct sockaddr_in *sin, int lockpeer, const char *host)
846 {
847         struct chan_iax2_pvt *tmp;
848         tmp = malloc(sizeof(struct chan_iax2_pvt));
849         if (tmp) {
850                 memset(tmp, 0, sizeof(struct chan_iax2_pvt));
851                 tmp->prefs = prefs;
852                 tmp->callno = 0;
853                 tmp->peercallno = 0;
854                 tmp->transfercallno = 0;
855                 tmp->bridgecallno = 0;
856                 tmp->pingid = -1;
857                 tmp->lagid = -1;
858                 tmp->autoid = -1;
859                 tmp->authid = -1;
860                 tmp->initid = -1;
861                 /* ast_copy_string(tmp->context, context, sizeof(tmp->context)); */
862                 ast_copy_string(tmp->exten, "s", sizeof(tmp->exten));
863                 ast_copy_string(tmp->host, host, sizeof(tmp->host));
864 #ifdef NEWJB
865                 {
866                         jb_conf jbconf;
867
868                         tmp->jb = jb_new();
869                         tmp->jbid = -1;
870                         jbconf.max_jitterbuf = maxjitterbuffer;
871                         jbconf.resync_threshold = resyncthreshold;
872                         jb_setconf(tmp->jb,&jbconf);
873                 }
874 #endif
875         }
876         return tmp;
877 }
878
879 static struct iax_frame *iaxfrdup2(struct iax_frame *fr)
880 {
881         /* Malloc() a copy of a frame */
882         struct iax_frame *new = iax_frame_new(DIRECTION_INGRESS, fr->af.datalen);
883         if (new) {
884                 memcpy(new, fr, sizeof(struct iax_frame));      
885                 iax_frame_wrap(new, &fr->af);
886                 new->data = NULL;
887                 new->datalen = 0;
888                 new->direction = DIRECTION_INGRESS;
889                 new->retrans = -1;
890         }
891         return new;
892 }
893
894 #define NEW_PREVENT 0
895 #define NEW_ALLOW       1
896 #define NEW_FORCE       2
897
898 static int match(struct sockaddr_in *sin, unsigned short callno, unsigned short dcallno, struct chan_iax2_pvt *cur)
899 {
900         if ((cur->addr.sin_addr.s_addr == sin->sin_addr.s_addr) &&
901                 (cur->addr.sin_port == sin->sin_port)) {
902                 /* This is the main host */
903                 if ((cur->peercallno == callno) ||
904                         ((dcallno == cur->callno) && !cur->peercallno)) {
905                         /* That's us.  Be sure we keep track of the peer call number */
906                         return 1;
907                 }
908         }
909         if ((cur->transfer.sin_addr.s_addr == sin->sin_addr.s_addr) &&
910             (cur->transfer.sin_port == sin->sin_port) && (cur->transferring)) {
911                 /* We're transferring */
912                 if (dcallno == cur->callno)
913                         return 1;
914         }
915         return 0;
916 }
917
918 static void update_max_trunk(void)
919 {
920         int max = TRUNK_CALL_START;
921         int x;
922         /* XXX Prolly don't need locks here XXX */
923         for (x=TRUNK_CALL_START;x<IAX_MAX_CALLS - 1; x++) {
924                 if (iaxs[x])
925                         max = x + 1;
926         }
927         maxtrunkcall = max;
928         if (option_debug)
929                 ast_log(LOG_DEBUG, "New max trunk callno is %d\n", max);
930 }
931
932 static void update_max_nontrunk(void)
933 {
934         int max = 1;
935         int x;
936         /* XXX Prolly don't need locks here XXX */
937         for (x=1;x<TRUNK_CALL_START - 1; x++) {
938                 if (iaxs[x])
939                         max = x + 1;
940         }
941         maxnontrunkcall = max;
942         if (option_debug)
943                 ast_log(LOG_DEBUG, "New max nontrunk callno is %d\n", max);
944 }
945
946 static int make_trunk(unsigned short callno, int locked)
947 {
948         int x;
949         int res= 0;
950         struct timeval now;
951         if (iaxs[callno]->oseqno) {
952                 ast_log(LOG_WARNING, "Can't make trunk once a call has started!\n");
953                 return -1;
954         }
955         if (callno & TRUNK_CALL_START) {
956                 ast_log(LOG_WARNING, "Call %d is already a trunk\n", callno);
957                 return -1;
958         }
959         gettimeofday(&now, NULL);
960         for (x=TRUNK_CALL_START;x<IAX_MAX_CALLS - 1; x++) {
961                 ast_mutex_lock(&iaxsl[x]);
962                 if (!iaxs[x] && ((now.tv_sec - lastused[x].tv_sec) > MIN_REUSE_TIME)) {
963                         iaxs[x] = iaxs[callno];
964                         iaxs[x]->callno = x;
965                         iaxs[callno] = NULL;
966                         /* Update the two timers that should have been started */
967                         if (iaxs[x]->pingid > -1)
968                                 ast_sched_del(sched, iaxs[x]->pingid);
969                         if (iaxs[x]->lagid > -1)
970                                 ast_sched_del(sched, iaxs[x]->lagid);
971                         iaxs[x]->pingid = ast_sched_add(sched, ping_time * 1000, send_ping, (void *)(long)x);
972                         iaxs[x]->lagid = ast_sched_add(sched, lagrq_time * 1000, send_lagrq, (void *)(long)x);
973                         if (locked)
974                                 ast_mutex_unlock(&iaxsl[callno]);
975                         res = x;
976                         if (!locked)
977                                 ast_mutex_unlock(&iaxsl[x]);
978                         break;
979                 }
980                 ast_mutex_unlock(&iaxsl[x]);
981         }
982         if (x >= IAX_MAX_CALLS - 1) {
983                 ast_log(LOG_WARNING, "Unable to trunk call: Insufficient space\n");
984                 return -1;
985         }
986         ast_log(LOG_DEBUG, "Made call %d into trunk call %d\n", callno, x);
987         /* We move this call from a non-trunked to a trunked call */
988         update_max_trunk();
989         update_max_nontrunk();
990         return res;
991 }
992
993 static int find_callno(unsigned short callno, unsigned short dcallno, struct sockaddr_in *sin, int new, int lockpeer, int sockfd)
994 {
995         int res = 0;
996         int x;
997         struct timeval now;
998         char iabuf[INET_ADDRSTRLEN];
999         char host[80];
1000         if (new <= NEW_ALLOW) {
1001                 /* Look for an existing connection first */
1002                 for (x=1;(res < 1) && (x<maxnontrunkcall);x++) {
1003                         ast_mutex_lock(&iaxsl[x]);
1004                         if (iaxs[x]) {
1005                                 /* Look for an exact match */
1006                                 if (match(sin, callno, dcallno, iaxs[x])) {
1007                                         res = x;
1008                                 }
1009                         }
1010                         ast_mutex_unlock(&iaxsl[x]);
1011                 }
1012                 for (x=TRUNK_CALL_START;(res < 1) && (x<maxtrunkcall);x++) {
1013                         ast_mutex_lock(&iaxsl[x]);
1014                         if (iaxs[x]) {
1015                                 /* Look for an exact match */
1016                                 if (match(sin, callno, dcallno, iaxs[x])) {
1017                                         res = x;
1018                                 }
1019                         }
1020                         ast_mutex_unlock(&iaxsl[x]);
1021                 }
1022         }
1023         if ((res < 1) && (new >= NEW_ALLOW)) {
1024                 if (!iax2_getpeername(*sin, host, sizeof(host), lockpeer))
1025                         snprintf(host, sizeof(host), "%s:%d", ast_inet_ntoa(iabuf, sizeof(iabuf), sin->sin_addr), ntohs(sin->sin_port));
1026                 gettimeofday(&now, NULL);
1027                 for (x=1;x<TRUNK_CALL_START;x++) {
1028                         /* Find first unused call number that hasn't been used in a while */
1029                         ast_mutex_lock(&iaxsl[x]);
1030                         if (!iaxs[x] && ((now.tv_sec - lastused[x].tv_sec) > MIN_REUSE_TIME)) break;
1031                         ast_mutex_unlock(&iaxsl[x]);
1032                 }
1033                 /* We've still got lock held if we found a spot */
1034                 if (x >= TRUNK_CALL_START) {
1035                         ast_log(LOG_WARNING, "No more space\n");
1036                         return 0;
1037                 }
1038                 iaxs[x] = new_iax(sin, lockpeer, host);
1039                 update_max_nontrunk();
1040                 if (iaxs[x]) {
1041                         if (option_debug)
1042                                 ast_log(LOG_DEBUG, "Creating new call structure %d\n", x);
1043                         iaxs[x]->sockfd = sockfd;
1044                         iaxs[x]->addr.sin_port = sin->sin_port;
1045                         iaxs[x]->addr.sin_family = sin->sin_family;
1046                         iaxs[x]->addr.sin_addr.s_addr = sin->sin_addr.s_addr;
1047                         iaxs[x]->peercallno = callno;
1048                         iaxs[x]->callno = x;
1049                         iaxs[x]->pingtime = DEFAULT_RETRY_TIME;
1050                         iaxs[x]->expirey = expirey;
1051                         iaxs[x]->pingid = ast_sched_add(sched, ping_time * 1000, send_ping, (void *)(long)x);
1052                         iaxs[x]->lagid = ast_sched_add(sched, lagrq_time * 1000, send_lagrq, (void *)(long)x);
1053                         iaxs[x]->amaflags = amaflags;
1054                         ast_copy_flags(iaxs[x], (&globalflags), IAX_NOTRANSFER | IAX_USEJITTERBUF | IAX_FORCEJITTERBUF);        
1055                         ast_copy_string(iaxs[x]->accountcode, accountcode, sizeof(iaxs[x]->accountcode));
1056                 } else {
1057                         ast_log(LOG_WARNING, "Out of resources\n");
1058                         ast_mutex_unlock(&iaxsl[x]);
1059                         return 0;
1060                 }
1061                 ast_mutex_unlock(&iaxsl[x]);
1062                 res = x;
1063         }
1064         return res;
1065 }
1066
1067 static void iax2_frame_free(struct iax_frame *fr)
1068 {
1069         if (fr->retrans > -1)
1070                 ast_sched_del(sched, fr->retrans);
1071         iax_frame_free(fr);
1072 }
1073
1074 static int iax2_queue_frame(int callno, struct ast_frame *f)
1075 {
1076         /* Assumes lock for callno is already held... */
1077         for (;;) {
1078                 if (iaxs[callno] && iaxs[callno]->owner) {
1079                         if (ast_mutex_trylock(&iaxs[callno]->owner->lock)) {
1080                                 /* Avoid deadlock by pausing and trying again */
1081                                 ast_mutex_unlock(&iaxsl[callno]);
1082                                 usleep(1);
1083                                 ast_mutex_lock(&iaxsl[callno]);
1084                         } else {
1085                                 ast_queue_frame(iaxs[callno]->owner, f);
1086                                 ast_mutex_unlock(&iaxs[callno]->owner->lock);
1087                                 break;
1088                         }
1089                 } else
1090                         break;
1091         }
1092         return 0;
1093 }
1094
1095 static void destroy_firmware(struct iax_firmware *cur)
1096 {
1097         /* Close firmware */
1098         if (cur->fwh) {
1099                 munmap(cur->fwh, ntohl(cur->fwh->datalen) + sizeof(*(cur->fwh)));
1100         }
1101         close(cur->fd);
1102         free(cur);
1103 }
1104
1105 static int try_firmware(char *s)
1106 {
1107         struct stat stbuf;
1108         struct iax_firmware *cur;
1109         int ifd;
1110         int fd;
1111         int res;
1112         
1113         struct ast_iax2_firmware_header *fwh, fwh2;
1114         struct MD5Context md5;
1115         unsigned char sum[16];
1116         unsigned char buf[1024];
1117         int len, chunk;
1118         char *s2;
1119         char *last;
1120         s2 = alloca(strlen(s) + 100);
1121         if (!s2) {
1122                 ast_log(LOG_WARNING, "Alloca failed!\n");
1123                 return -1;
1124         }
1125         last = strrchr(s, '/');
1126         if (last)
1127                 last++;
1128         else
1129                 last = s;
1130         snprintf(s2, strlen(s) + 100, "/var/tmp/%s-%ld", last, (unsigned long)rand());
1131         res = stat(s, &stbuf);
1132         if (res < 0) {
1133                 ast_log(LOG_WARNING, "Failed to stat '%s': %s\n", s, strerror(errno));
1134                 return -1;
1135         }
1136         /* Make sure it's not a directory */
1137         if (S_ISDIR(stbuf.st_mode))
1138                 return -1;
1139         ifd = open(s, O_RDONLY);
1140         if (ifd < 0) {
1141                 ast_log(LOG_WARNING, "Cannot open '%s': %s\n", s, strerror(errno));
1142                 return -1;
1143         }
1144         fd = open(s2, O_RDWR | O_CREAT | O_EXCL);
1145         if (fd < 0) {
1146                 ast_log(LOG_WARNING, "Cannot open '%s' for writing: %s\n", s2, strerror(errno));
1147                 close(ifd);
1148                 return -1;
1149         }
1150         /* Unlink our newly created file */
1151         unlink(s2);
1152         
1153         /* Now copy the firmware into it */
1154         len = stbuf.st_size;
1155         while(len) {
1156                 chunk = len;
1157                 if (chunk > sizeof(buf))
1158                         chunk = sizeof(buf);
1159                 res = read(ifd, buf, chunk);
1160                 if (res != chunk) {
1161                         ast_log(LOG_WARNING, "Only read %d of %d bytes of data :(: %s\n", res, chunk, strerror(errno));
1162                         close(ifd);
1163                         close(fd);
1164                         return -1;
1165                 }
1166                 res = write(fd, buf, chunk);
1167                 if (res != chunk) {
1168                         ast_log(LOG_WARNING, "Only write %d of %d bytes of data :(: %s\n", res, chunk, strerror(errno));
1169                         close(ifd);
1170                         close(fd);
1171                         return -1;
1172                 }
1173                 len -= chunk;
1174         }
1175         close(ifd);
1176         /* Return to the beginning */
1177         lseek(fd, 0, SEEK_SET);
1178         if ((res = read(fd, &fwh2, sizeof(fwh2))) != sizeof(fwh2)) {
1179                 ast_log(LOG_WARNING, "Unable to read firmware header in '%s'\n", s);
1180                 close(fd);
1181                 return -1;
1182         }
1183         if (ntohl(fwh2.magic) != IAX_FIRMWARE_MAGIC) {
1184                 ast_log(LOG_WARNING, "'%s' is not a valid firmware file\n", s);
1185                 close(fd);
1186                 return -1;
1187         }
1188         if (ntohl(fwh2.datalen) != (stbuf.st_size - sizeof(fwh2))) {
1189                 ast_log(LOG_WARNING, "Invalid data length in firmware '%s'\n", s);
1190                 close(fd);
1191                 return -1;
1192         }
1193         if (fwh2.devname[sizeof(fwh2.devname) - 1] || ast_strlen_zero(fwh2.devname)) {
1194                 ast_log(LOG_WARNING, "No or invalid device type specified for '%s'\n", s);
1195                 close(fd);
1196                 return -1;
1197         }
1198         fwh = mmap(NULL, stbuf.st_size, PROT_READ, MAP_PRIVATE, fd, 0); 
1199         if (!fwh) {
1200                 ast_log(LOG_WARNING, "mmap failed: %s\n", strerror(errno));
1201                 close(fd);
1202                 return -1;
1203         }
1204         MD5Init(&md5);
1205         MD5Update(&md5, fwh->data, ntohl(fwh->datalen));
1206         MD5Final(sum, &md5);
1207         if (memcmp(sum, fwh->chksum, sizeof(sum))) {
1208                 ast_log(LOG_WARNING, "Firmware file '%s' fails checksum\n", s);
1209                 munmap(fwh, stbuf.st_size);
1210                 close(fd);
1211                 return -1;
1212         }
1213         cur = waresl.wares;
1214         while(cur) {
1215                 if (!strcmp(cur->fwh->devname, fwh->devname)) {
1216                         /* Found a candidate */
1217                         if (cur->dead || (ntohs(cur->fwh->version) < ntohs(fwh->version)))
1218                                 /* The version we have on loaded is older, load this one instead */
1219                                 break;
1220                         /* This version is no newer than what we have.  Don't worry about it.
1221                            We'll consider it a proper load anyhow though */
1222                         munmap(fwh, stbuf.st_size);
1223                         close(fd);
1224                         return 0;
1225                 }
1226                 cur = cur->next;
1227         }
1228         if (!cur) {
1229                 /* Allocate a new one and link it */
1230                 cur = malloc(sizeof(struct iax_firmware));
1231                 if (cur) {
1232                         memset(cur, 0, sizeof(struct iax_firmware));
1233                         cur->fd = -1;
1234                         cur->next = waresl.wares;
1235                         waresl.wares = cur;
1236                 }
1237         }
1238         if (cur) {
1239                 if (cur->fwh) {
1240                         munmap(cur->fwh, cur->mmaplen);
1241                 }
1242                 if (cur->fd > -1)
1243                         close(cur->fd);
1244                 cur->fwh = fwh;
1245                 cur->fd = fd;
1246                 cur->mmaplen = stbuf.st_size;
1247                 cur->dead = 0;
1248         }
1249         return 0;
1250 }
1251
1252 static int iax_check_version(char *dev)
1253 {
1254         int res = 0;
1255         struct iax_firmware *cur;
1256         if (dev && !ast_strlen_zero(dev)) {
1257                 ast_mutex_lock(&waresl.lock);
1258                 cur = waresl.wares;
1259                 while(cur) {
1260                         if (!strcmp(dev, cur->fwh->devname)) {
1261                                 res = ntohs(cur->fwh->version);
1262                                 break;
1263                         }
1264                         cur = cur->next;
1265                 }
1266                 ast_mutex_unlock(&waresl.lock);
1267         }
1268         return res;
1269 }
1270
1271 static int iax_firmware_append(struct iax_ie_data *ied, const unsigned char *dev, unsigned int desc)
1272 {
1273         int res = -1;
1274         unsigned int bs = desc & 0xff;
1275         unsigned int start = (desc >> 8) & 0xffffff;
1276         unsigned int bytes;
1277         struct iax_firmware *cur;
1278         if (dev && !ast_strlen_zero(dev) && bs) {
1279                 start *= bs;
1280                 ast_mutex_lock(&waresl.lock);
1281                 cur = waresl.wares;
1282                 while(cur) {
1283                         if (!strcmp(dev, cur->fwh->devname)) {
1284                                 iax_ie_append_int(ied, IAX_IE_FWBLOCKDESC, desc);
1285                                 if (start < ntohl(cur->fwh->datalen)) {
1286                                         bytes = ntohl(cur->fwh->datalen) - start;
1287                                         if (bytes > bs)
1288                                                 bytes = bs;
1289                                         iax_ie_append_raw(ied, IAX_IE_FWBLOCKDATA, cur->fwh->data + start, bytes);
1290                                 } else {
1291                                         bytes = 0;
1292                                         iax_ie_append(ied, IAX_IE_FWBLOCKDATA);
1293                                 }
1294                                 if (bytes == bs)
1295                                         res = 0;
1296                                 else
1297                                         res = 1;
1298                                 break;
1299                         }
1300                         cur = cur->next;
1301                 }
1302                 ast_mutex_unlock(&waresl.lock);
1303         }
1304         return res;
1305 }
1306
1307
1308 static void reload_firmware(void)
1309 {
1310         struct iax_firmware *cur, *curl, *curp;
1311         DIR *fwd;
1312         struct dirent *de;
1313         char dir[256];
1314         char fn[256];
1315         /* Mark all as dead */
1316         ast_mutex_lock(&waresl.lock);
1317         cur = waresl.wares;
1318         while(cur) {
1319                 cur->dead = 1;
1320                 cur = cur->next;
1321         }
1322         /* Now that we've freed them, load the new ones */
1323         snprintf(dir, sizeof(dir), "%s/firmware/iax", (char *)ast_config_AST_VAR_DIR);
1324         fwd = opendir(dir);
1325         if (fwd) {
1326                 while((de = readdir(fwd))) {
1327                         if (de->d_name[0] != '.') {
1328                                 snprintf(fn, sizeof(fn), "%s/%s", dir, de->d_name);
1329                                 if (!try_firmware(fn)) {
1330                                         if (option_verbose > 1)
1331                                                 ast_verbose(VERBOSE_PREFIX_2 "Loaded firmware '%s'\n", de->d_name);
1332                                 }
1333                         }
1334                 }
1335                 closedir(fwd);
1336         } else 
1337                 ast_log(LOG_WARNING, "Error opening firmware directory '%s': %s\n", dir, strerror(errno));
1338
1339         /* Clean up leftovers */
1340         cur = waresl.wares;
1341         curp = NULL;
1342         while(cur) {
1343                 curl = cur;
1344                 cur = cur->next;
1345                 if (curl->dead) {
1346                         if (curp) {
1347                                 curp->next = cur;
1348                         } else {
1349                                 waresl.wares = cur;
1350                         }
1351                         destroy_firmware(curl);
1352                 } else {
1353                         curp = cur;
1354                 }
1355         }
1356         ast_mutex_unlock(&waresl.lock);
1357 }
1358
1359 static int iax2_send(struct chan_iax2_pvt *pvt, struct ast_frame *f, unsigned int ts, int seqno, int now, int transfer, int final);
1360
1361 static int __do_deliver(void *data)
1362 {
1363         /* Just deliver the packet by using queueing.  This is called by
1364           the IAX thread with the iaxsl lock held. */
1365         struct iax_frame *fr = data;
1366         fr->retrans = -1;
1367         if (iaxs[fr->callno] && !ast_test_flag(iaxs[fr->callno], IAX_ALREADYGONE))
1368                 iax2_queue_frame(fr->callno, &fr->af);
1369         /* Free our iax frame */
1370         iax2_frame_free(fr);
1371         /* And don't run again */
1372         return 0;
1373 }
1374
1375 #ifndef NEWJB
1376 static int do_deliver(void *data)
1377 {
1378         /* Locking version of __do_deliver */
1379         struct iax_frame *fr = data;
1380         int callno = fr->callno;
1381         int res;
1382         ast_mutex_lock(&iaxsl[callno]);
1383         res = __do_deliver(data);
1384         ast_mutex_unlock(&iaxsl[callno]);
1385         return res;
1386 }
1387 #endif /* NEWJB */
1388
1389 static int handle_error(void)
1390 {
1391         /* XXX Ideally we should figure out why an error occured and then abort those
1392            rather than continuing to try.  Unfortunately, the published interface does
1393            not seem to work XXX */
1394 #if 0
1395         struct sockaddr_in *sin;
1396         int res;
1397         struct msghdr m;
1398         struct sock_extended_err e;
1399         m.msg_name = NULL;
1400         m.msg_namelen = 0;
1401         m.msg_iov = NULL;
1402         m.msg_control = &e;
1403         m.msg_controllen = sizeof(e);
1404         m.msg_flags = 0;
1405         res = recvmsg(netsocket, &m, MSG_ERRQUEUE);
1406         if (res < 0)
1407                 ast_log(LOG_WARNING, "Error detected, but unable to read error: %s\n", strerror(errno));
1408         else {
1409                 if (m.msg_controllen) {
1410                         sin = (struct sockaddr_in *)SO_EE_OFFENDER(&e);
1411                         if (sin) 
1412                                 ast_log(LOG_WARNING, "Receive error from %s\n", ast_inet_ntoa(iabuf, sizeof(iabuf), sin->sin_addr));
1413                         else
1414                                 ast_log(LOG_WARNING, "No address detected??\n");
1415                 } else {
1416                         ast_log(LOG_WARNING, "Local error: %s\n", strerror(e.ee_errno));
1417                 }
1418         }
1419 #endif
1420         return 0;
1421 }
1422
1423 static int transmit_trunk(struct iax_frame *f, struct sockaddr_in *sin, int sockfd)
1424 {
1425         int res;
1426         res = sendto(sockfd, f->data, f->datalen, 0,(struct sockaddr *)sin,
1427                                         sizeof(*sin));
1428         if (res < 0) {
1429                 if (option_debug)
1430                         ast_log(LOG_DEBUG, "Received error: %s\n", strerror(errno));
1431                 handle_error();
1432         } else
1433                 res = 0;
1434         return res;
1435 }
1436
1437 static int send_packet(struct iax_frame *f)
1438 {
1439         int res;
1440         char iabuf[INET_ADDRSTRLEN];
1441         /* Called with iaxsl held */
1442         if (option_debug > 2)
1443                 ast_log(LOG_DEBUG, "Sending %d on %d/%d to %s:%d\n", f->ts, f->callno, iaxs[f->callno]->peercallno, ast_inet_ntoa(iabuf, sizeof(iabuf), iaxs[f->callno]->addr.sin_addr), ntohs(iaxs[f->callno]->addr.sin_port));
1444         /* Don't send if there was an error, but return error instead */
1445         if (!f->callno) {
1446                 ast_log(LOG_WARNING, "Call number = %d\n", f->callno);
1447                 return -1;
1448         }
1449         if (!iaxs[f->callno])
1450                 return -1;
1451         if (iaxs[f->callno]->error)
1452                 return -1;
1453         if (f->transfer) {
1454                 if (iaxdebug)
1455                         iax_showframe(f, NULL, 0, &iaxs[f->callno]->transfer, f->datalen - sizeof(struct ast_iax2_full_hdr));
1456                 res = sendto(iaxs[f->callno]->sockfd, f->data, f->datalen, 0,(struct sockaddr *)&iaxs[f->callno]->transfer,
1457                                         sizeof(iaxs[f->callno]->transfer));
1458         } else {
1459                 if (iaxdebug)
1460                         iax_showframe(f, NULL, 0, &iaxs[f->callno]->addr, f->datalen - sizeof(struct ast_iax2_full_hdr));
1461                 res = sendto(iaxs[f->callno]->sockfd, f->data, f->datalen, 0,(struct sockaddr *)&iaxs[f->callno]->addr,
1462                                         sizeof(iaxs[f->callno]->addr));
1463         }
1464         if (res < 0) {
1465                 if (option_debug)
1466                         ast_log(LOG_DEBUG, "Received error: %s\n", strerror(errno));
1467                 handle_error();
1468         } else
1469                 res = 0;
1470         return res;
1471 }
1472
1473
1474 static int iax2_predestroy(int callno)
1475 {
1476         struct ast_channel *c;
1477         struct chan_iax2_pvt *pvt;
1478         ast_mutex_lock(&iaxsl[callno]);
1479         pvt = iaxs[callno];
1480         if (!pvt) {
1481                 ast_mutex_unlock(&iaxsl[callno]);
1482                 return -1;
1483         }
1484         if (!ast_test_flag(pvt, IAX_ALREADYGONE)) {
1485                 /* No more pings or lagrq's */
1486                 if (pvt->pingid > -1)
1487                         ast_sched_del(sched, pvt->pingid);
1488                 if (pvt->lagid > -1)
1489                         ast_sched_del(sched, pvt->lagid);
1490                 if (pvt->autoid > -1)
1491                         ast_sched_del(sched, pvt->autoid);
1492                 if (pvt->authid > -1)
1493                         ast_sched_del(sched, pvt->authid);
1494                 if (pvt->initid > -1)
1495                         ast_sched_del(sched, pvt->initid);
1496 #ifdef NEWJB
1497                 if (pvt->jbid > -1)
1498                         ast_sched_del(sched, pvt->jbid);
1499                 pvt->jbid = -1;
1500 #endif
1501                 pvt->pingid = -1;
1502                 pvt->lagid = -1;
1503                 pvt->autoid = -1;
1504                 pvt->initid = -1;
1505                 pvt->authid = -1;
1506                 ast_set_flag(pvt, IAX_ALREADYGONE);     
1507         }
1508         c = pvt->owner;
1509         if (c) {
1510                 c->_softhangup |= AST_SOFTHANGUP_DEV;
1511                 c->tech_pvt = NULL;
1512                 ast_queue_hangup(c);
1513                 pvt->owner = NULL;
1514                 ast_mutex_lock(&usecnt_lock);
1515                 usecnt--;
1516                 if (usecnt < 0) 
1517                         ast_log(LOG_WARNING, "Usecnt < 0???\n");
1518                 ast_mutex_unlock(&usecnt_lock);
1519         }
1520         ast_mutex_unlock(&iaxsl[callno]);
1521         ast_update_use_count();
1522         return 0;
1523 }
1524
1525 static int iax2_predestroy_nolock(int callno)
1526 {
1527         int res;
1528         ast_mutex_unlock(&iaxsl[callno]);
1529         res = iax2_predestroy(callno);
1530         ast_mutex_lock(&iaxsl[callno]);
1531         return res;
1532 }
1533
1534 static void iax2_destroy(int callno)
1535 {
1536         struct chan_iax2_pvt *pvt;
1537         struct iax_frame *cur;
1538         struct ast_channel *owner;
1539
1540 retry:
1541         ast_mutex_lock(&iaxsl[callno]);
1542         pvt = iaxs[callno];
1543         gettimeofday(&lastused[callno], NULL);
1544
1545         if (pvt)
1546                 owner = pvt->owner;
1547         else
1548                 owner = NULL;
1549         if (owner) {
1550                 if (ast_mutex_trylock(&owner->lock)) {
1551                         ast_log(LOG_NOTICE, "Avoiding IAX destroy deadlock\n");
1552                         ast_mutex_unlock(&iaxsl[callno]);
1553                         usleep(1);
1554                         goto retry;
1555                 }
1556         }
1557         if (!owner)
1558                 iaxs[callno] = NULL;
1559         if (pvt) {
1560                 if (!owner)
1561                         pvt->owner = NULL;
1562                 /* No more pings or lagrq's */
1563                 if (pvt->pingid > -1)
1564                         ast_sched_del(sched, pvt->pingid);
1565                 if (pvt->lagid > -1)
1566                         ast_sched_del(sched, pvt->lagid);
1567                 if (pvt->autoid > -1)
1568                         ast_sched_del(sched, pvt->autoid);
1569                 if (pvt->authid > -1)
1570                         ast_sched_del(sched, pvt->authid);
1571                 if (pvt->initid > -1)
1572                         ast_sched_del(sched, pvt->initid);
1573 #ifdef NEWJB
1574                 if (pvt->jbid > -1)
1575                         ast_sched_del(sched, pvt->jbid);
1576                 pvt->jbid = -1;
1577 #endif
1578                 pvt->pingid = -1;
1579                 pvt->lagid = -1;
1580                 pvt->autoid = -1;
1581                 pvt->authid = -1;
1582                 pvt->initid = -1;
1583                 if (pvt->bridgetrans)
1584                         ast_translator_free_path(pvt->bridgetrans);
1585                 pvt->bridgetrans = NULL;
1586
1587                 /* Already gone */
1588                 ast_set_flag(pvt, IAX_ALREADYGONE);     
1589
1590                 if (owner) {
1591                         /* If there's an owner, prod it to give up */
1592                         owner->_softhangup |= AST_SOFTHANGUP_DEV;
1593                         ast_queue_hangup(owner);
1594                 }
1595
1596                 for (cur = iaxq.head; cur ; cur = cur->next) {
1597                         /* Cancel any pending transmissions */
1598                         if (cur->callno == pvt->callno) 
1599                                 cur->retries = -1;
1600                 }
1601                 if (pvt->reg) {
1602                         pvt->reg->callno = 0;
1603                 }
1604                 if (!owner) {
1605                         if (pvt->vars) {
1606                                 ast_variables_destroy(pvt->vars);
1607                                 pvt->vars = NULL;
1608                         }
1609 #ifdef NEWJB
1610                         {
1611                             jb_frame frame;
1612                             while(jb_getall(pvt->jb,&frame) == JB_OK)
1613                                 iax2_frame_free(frame.data);
1614                             jb_destroy(pvt->jb);
1615                         }
1616 #endif
1617                         free(pvt);
1618                 }
1619         }
1620         if (owner) {
1621                 ast_mutex_unlock(&owner->lock);
1622         }
1623         ast_mutex_unlock(&iaxsl[callno]);
1624         if (callno & 0x4000)
1625                 update_max_trunk();
1626 }
1627 static void iax2_destroy_nolock(int callno)
1628 {       
1629         /* Actually it's easier to unlock, kill it, and relock */
1630         ast_mutex_unlock(&iaxsl[callno]);
1631         iax2_destroy(callno);
1632         ast_mutex_lock(&iaxsl[callno]);
1633 }
1634
1635 static int update_packet(struct iax_frame *f)
1636 {
1637         /* Called with iaxsl lock held, and iaxs[callno] non-NULL */
1638         struct ast_iax2_full_hdr *fh = f->data;
1639         /* Mark this as a retransmission */
1640         fh->dcallno = ntohs(IAX_FLAG_RETRANS | f->dcallno);
1641         /* Update iseqno */
1642         f->iseqno = iaxs[f->callno]->iseqno;
1643         fh->iseqno = f->iseqno;
1644         return 0;
1645 }
1646
1647 static int attempt_transmit(void *data)
1648 {
1649         /* Attempt to transmit the frame to the remote peer...
1650            Called without iaxsl held. */
1651         struct iax_frame *f = data;
1652         int freeme=0;
1653         int callno = f->callno;
1654         char iabuf[INET_ADDRSTRLEN];
1655         /* Make sure this call is still active */
1656         if (callno) 
1657                 ast_mutex_lock(&iaxsl[callno]);
1658         if ((f->callno) && iaxs[f->callno]) {
1659                 if ((f->retries < 0) /* Already ACK'd */ ||
1660                     (f->retries >= max_retries) /* Too many attempts */) {
1661                                 /* Record an error if we've transmitted too many times */
1662                                 if (f->retries >= max_retries) {
1663                                         if (f->transfer) {
1664                                                 /* Transfer timeout */
1665                                                 send_command(iaxs[f->callno], AST_FRAME_IAX, IAX_COMMAND_TXREJ, 0, NULL, 0, -1);
1666                                         } else if (f->final) {
1667                                                 if (f->final) 
1668                                                         iax2_destroy_nolock(f->callno);
1669                                         } else {
1670                                                 if (iaxs[f->callno]->owner)
1671                                                         ast_log(LOG_WARNING, "Max retries exceeded to host %s on %s (type = %d, subclass = %d, ts=%d, seqno=%d)\n", ast_inet_ntoa(iabuf, sizeof(iabuf), iaxs[f->callno]->addr.sin_addr),iaxs[f->callno]->owner->name , f->af.frametype, f->af.subclass, f->ts, f->oseqno);
1672                                                 iaxs[f->callno]->error = ETIMEDOUT;
1673                                                 if (iaxs[f->callno]->owner) {
1674                                                         struct ast_frame fr = { 0, };
1675                                                         /* Hangup the fd */
1676                                                         fr.frametype = AST_FRAME_CONTROL;
1677                                                         fr.subclass = AST_CONTROL_HANGUP;
1678                                                         iax2_queue_frame(f->callno, &fr);
1679                                                         /* Remember, owner could disappear */
1680                                                         if (iaxs[f->callno]->owner)
1681                                                                 iaxs[f->callno]->owner->hangupcause = AST_CAUSE_DESTINATION_OUT_OF_ORDER;
1682                                                 } else {
1683                                                         if (iaxs[f->callno]->reg) {
1684                                                                 memset(&iaxs[f->callno]->reg->us, 0, sizeof(iaxs[f->callno]->reg->us));
1685                                                                 iaxs[f->callno]->reg->regstate = REG_STATE_TIMEOUT;
1686                                                                 iaxs[f->callno]->reg->refresh = IAX_DEFAULT_REG_EXPIRE;
1687                                                         }
1688                                                         iax2_destroy_nolock(f->callno);
1689                                                 }
1690                                         }
1691
1692                                 }
1693                                 freeme++;
1694                 } else {
1695                         /* Update it if it needs it */
1696                         update_packet(f);
1697                         /* Attempt transmission */
1698                         send_packet(f);
1699                         f->retries++;
1700                         /* Try again later after 10 times as long */
1701                         f->retrytime *= 10;
1702                         if (f->retrytime > MAX_RETRY_TIME)
1703                                 f->retrytime = MAX_RETRY_TIME;
1704                         /* Transfer messages max out at one second */
1705                         if (f->transfer && (f->retrytime > 1000))
1706                                 f->retrytime = 1000;
1707                         f->retrans = ast_sched_add(sched, f->retrytime, attempt_transmit, f);
1708                 }
1709         } else {
1710                 /* Make sure it gets freed */
1711                 f->retries = -1;
1712                 freeme++;
1713         }
1714         if (callno)
1715                 ast_mutex_unlock(&iaxsl[callno]);
1716         /* Do not try again */
1717         if (freeme) {
1718                 /* Don't attempt delivery, just remove it from the queue */
1719                 ast_mutex_lock(&iaxq.lock);
1720                 if (f->prev) 
1721                         f->prev->next = f->next;
1722                 else
1723                         iaxq.head = f->next;
1724                 if (f->next)
1725                         f->next->prev = f->prev;
1726                 else
1727                         iaxq.tail = f->prev;
1728                 iaxq.count--;
1729                 ast_mutex_unlock(&iaxq.lock);
1730                 f->retrans = -1;
1731                 /* Free the IAX frame */
1732                 iax2_frame_free(f);
1733         }
1734         return 0;
1735 }
1736
1737 static int iax2_set_jitter(int fd, int argc, char *argv[])
1738 {
1739 #ifdef NEWJB
1740         ast_cli(fd, "sorry, this command is deprecated\n");
1741         return RESULT_SUCCESS;
1742 #else
1743         if ((argc != 4) && (argc != 5))
1744                 return RESULT_SHOWUSAGE;
1745         if (argc == 4) {
1746                 max_jitter_buffer = atoi(argv[3]);
1747                 if (max_jitter_buffer < 0)
1748                         max_jitter_buffer = 0;
1749         } else {
1750                 if (argc == 5) {
1751                         if ((atoi(argv[3]) >= 0) && (atoi(argv[3]) < IAX_MAX_CALLS)) {
1752                                 if (iaxs[atoi(argv[3])]) {
1753                                         iaxs[atoi(argv[3])]->jitterbuffer = atoi(argv[4]);
1754                                         if (iaxs[atoi(argv[3])]->jitterbuffer < 0)
1755                                                 iaxs[atoi(argv[3])]->jitterbuffer = 0;
1756                                 } else
1757                                         ast_cli(fd, "No such call '%d'\n", atoi(argv[3]));
1758                         } else
1759                                 ast_cli(fd, "%d is not a valid call number\n", atoi(argv[3]));
1760                 }
1761         }
1762         return RESULT_SUCCESS;
1763 #endif
1764 }
1765
1766 static char jitter_usage[] = 
1767 "Usage: iax set jitter [callid] <value>\n"
1768 "       If used with a callid, it sets the jitter buffer to the given static\n"
1769 "value (until its next calculation).  If used without a callid, the value is used\n"
1770 "to establish the maximum excess jitter buffer that is permitted before the jitter\n"
1771 "buffer size is reduced.";
1772
1773 static int iax2_prune_realtime(int fd, int argc, char *argv[])
1774 {
1775         struct iax2_peer *peer;
1776
1777         if (argc != 4)
1778         return RESULT_SHOWUSAGE;
1779         if (!strcmp(argv[3],"all")) {
1780                 reload_config();
1781                 ast_cli(fd, "OK cache is flushed.\n");
1782         } else if ((peer = find_peer(argv[3], 0))) {
1783                 if(ast_test_flag(peer, IAX_RTCACHEFRIENDS)) {
1784                         ast_set_flag(peer, IAX_RTAUTOCLEAR);
1785                         expire_registry(peer);
1786                         ast_cli(fd, "OK peer %s was removed from the cache.\n", argv[3]);
1787                 } else {
1788                         ast_cli(fd, "SORRY peer %s is not eligible for this operation.\n", argv[3]);
1789                 }
1790         } else {
1791                 ast_cli(fd, "SORRY peer %s was not found in the cache.\n", argv[3]);
1792         }
1793         
1794         return RESULT_SUCCESS;
1795 }
1796
1797 static int iax2_test_losspct(int fd, int argc, char *argv[])
1798 {
1799        if (argc != 4)
1800                return RESULT_SHOWUSAGE;
1801
1802        test_losspct = atoi(argv[3]);
1803
1804        return RESULT_SUCCESS;
1805 }
1806
1807 #ifdef IAXTESTS
1808 static int iax2_test_late(int fd, int argc, char *argv[])
1809 {
1810         if (argc != 4)
1811                 return RESULT_SHOWUSAGE;
1812
1813         test_late = atoi(argv[3]);
1814
1815         return RESULT_SUCCESS;
1816 }
1817
1818 static int iax2_test_resync(int fd, int argc, char *argv[])
1819 {
1820         if (argc != 4)
1821                 return RESULT_SHOWUSAGE;
1822
1823         test_resync = atoi(argv[3]);
1824
1825         return RESULT_SUCCESS;
1826 }
1827
1828 static int iax2_test_jitter(int fd, int argc, char *argv[])
1829 {
1830         if (argc < 4 || argc > 5)
1831                 return RESULT_SHOWUSAGE;
1832
1833         test_jit = atoi(argv[3]);
1834         if (argc == 5) 
1835                 test_jitpct = atoi(argv[4]);
1836
1837         return RESULT_SUCCESS;
1838 }
1839 #endif /* IAXTESTS */
1840
1841 /*--- iax2_show_peer: Show one peer in detail ---*/
1842 static int iax2_show_peer(int fd, int argc, char *argv[])
1843 {
1844         char status[30] = "";
1845         char cbuf[256];
1846         char iabuf[INET_ADDRSTRLEN];
1847         struct iax2_peer *peer;
1848         char codec_buf[512];
1849         int x = 0, codec = 0, load_realtime = 0;
1850
1851         if (argc < 4)
1852                 return RESULT_SHOWUSAGE;
1853
1854         load_realtime = (argc == 5 && !strcmp(argv[4], "load")) ? 1 : 0;
1855
1856         peer = find_peer(argv[3], load_realtime);
1857         if (peer) {
1858                 ast_cli(fd,"\n\n");
1859                 ast_cli(fd, "  * Name       : %s\n", peer->name);
1860                 ast_cli(fd, "  Secret       : %s\n", ast_strlen_zero(peer->secret)?"<Not set>":"<Set>");
1861                 ast_cli(fd, "  Context      : %s\n", peer->context);
1862                 ast_cli(fd, "  Mailbox      : %s\n", peer->mailbox);
1863                 ast_cli(fd, "  Dynamic      : %s\n", ast_test_flag(peer, IAX_DYNAMIC) ? "Yes":"No");
1864                 ast_cli(fd, "  Callerid     : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, "<unspecified>"));
1865                 ast_cli(fd, "  Expire       : %d\n", peer->expire);
1866                 ast_cli(fd, "  ACL          : %s\n", (peer->ha?"Yes":"No"));
1867                 ast_cli(fd, "  Addr->IP     : %s Port %d\n",  peer->addr.sin_addr.s_addr ? ast_inet_ntoa(iabuf, sizeof(iabuf), peer->addr.sin_addr) : "(Unspecified)", ntohs(peer->addr.sin_port));
1868                 ast_cli(fd, "  Defaddr->IP  : %s Port %d\n", ast_inet_ntoa(iabuf, sizeof(iabuf), peer->defaddr.sin_addr), ntohs(peer->defaddr.sin_port));
1869                 ast_cli(fd, "  Username     : %s\n", peer->username);
1870                 ast_cli(fd, "  Codecs       : ");
1871                 ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, peer->capability);
1872                 ast_cli(fd, "%s\n", codec_buf);
1873
1874                 ast_cli(fd, "  Codec Order  : (");
1875                 for(x = 0; x < 32 ; x++) {
1876                         codec = ast_codec_pref_index(&peer->prefs,x);
1877                         if(!codec)
1878                                 break;
1879                         ast_cli(fd, "%s", ast_getformatname(codec));
1880                         if(x < 31 && ast_codec_pref_index(&peer->prefs,x+1))
1881                                 ast_cli(fd, "|");
1882                 }
1883
1884                 if (!x)
1885                         ast_cli(fd, "none");
1886                 ast_cli(fd, ")\n");
1887
1888                 ast_cli(fd, "  Status       : ");
1889                 if (peer->lastms < 0)
1890                         ast_copy_string(status, "UNREACHABLE", sizeof(status));
1891                 else if (peer->lastms > peer->maxms)
1892                         snprintf(status, sizeof(status), "LAGGED (%d ms)", peer->lastms);
1893                 else if (peer->lastms)
1894                         snprintf(status, sizeof(status), "OK (%d ms)", peer->lastms);
1895                 else
1896                         ast_copy_string(status, "UNKNOWN", sizeof(status));
1897                 ast_cli(fd, "%s\n",status);
1898                 ast_cli(fd,"\n");
1899                 if (ast_test_flag(peer, IAX_TEMPONLY))
1900                         destroy_peer(peer);
1901         } else {
1902                 ast_cli(fd,"Peer %s not found.\n", argv[3]);
1903                 ast_cli(fd,"\n");
1904         }
1905
1906         return RESULT_SUCCESS;
1907 }
1908
1909 static char *complete_iax2_show_peer(char *line, char *word, int pos, int state)
1910 {
1911         int which = 0;
1912         struct iax2_peer *p;
1913
1914         /* 0 - iax2; 1 - show; 2 - peer; 3 - <peername> */
1915         if(pos == 3) {
1916                 ast_mutex_lock(&peerl.lock);
1917                 for(p = peerl.peers ; p ; p = p->next) {
1918                         if(!strncasecmp(p->name, word, strlen(word))) {
1919                                 if(++which > state) {
1920                                         return strdup(p->name);
1921                                 }
1922                         }
1923                 }
1924                 ast_mutex_unlock(&peerl.lock);
1925         }
1926
1927         return NULL;
1928 }
1929
1930 static int iax2_show_stats(int fd, int argc, char *argv[])
1931 {
1932         struct iax_frame *cur;
1933         int cnt = 0, dead=0, final=0;
1934         if (argc != 3)
1935                 return RESULT_SHOWUSAGE;
1936         for (cur = iaxq.head; cur ; cur = cur->next) {
1937                 if (cur->retries < 0)
1938                         dead++;
1939                 if (cur->final)
1940                         final++;
1941                 cnt++;
1942         }
1943         ast_cli(fd, "    IAX Statistics\n");
1944         ast_cli(fd, "---------------------\n");
1945         ast_cli(fd, "Outstanding frames: %d (%d ingress, %d outgress)\n", iax_get_frames(), iax_get_iframes(), iax_get_oframes());
1946         ast_cli(fd, "Packets in transmit queue: %d dead, %d final, %d total\n", dead, final, cnt);
1947         return RESULT_SUCCESS;
1948 }
1949
1950 static int iax2_show_cache(int fd, int argc, char *argv[])
1951 {
1952         struct iax2_dpcache *dp;
1953         char tmp[1024] = "", *pc;
1954         int s;
1955         int x,y;
1956         struct timeval tv;
1957         gettimeofday(&tv, NULL);
1958         ast_mutex_lock(&dpcache_lock);
1959         dp = dpcache;
1960         ast_cli(fd, "%-20.20s %-12.12s %-9.9s %-8.8s %s\n", "Peer/Context", "Exten", "Exp.", "Wait.", "Flags");
1961         while(dp) {
1962                 s = dp->expirey.tv_sec - tv.tv_sec;
1963                 tmp[0] = '\0';
1964                 if (dp->flags & CACHE_FLAG_EXISTS)
1965                         strncat(tmp, "EXISTS|", sizeof(tmp) - strlen(tmp) - 1);
1966                 if (dp->flags & CACHE_FLAG_NONEXISTENT)
1967                         strncat(tmp, "NONEXISTENT|", sizeof(tmp) - strlen(tmp) - 1);
1968                 if (dp->flags & CACHE_FLAG_CANEXIST)
1969                         strncat(tmp, "CANEXIST|", sizeof(tmp) - strlen(tmp) - 1);
1970                 if (dp->flags & CACHE_FLAG_PENDING)
1971                         strncat(tmp, "PENDING|", sizeof(tmp) - strlen(tmp) - 1);
1972                 if (dp->flags & CACHE_FLAG_TIMEOUT)
1973                         strncat(tmp, "TIMEOUT|", sizeof(tmp) - strlen(tmp) - 1);
1974                 if (dp->flags & CACHE_FLAG_TRANSMITTED)
1975                         strncat(tmp, "TRANSMITTED|", sizeof(tmp) - strlen(tmp) - 1);
1976                 if (dp->flags & CACHE_FLAG_MATCHMORE)
1977                         strncat(tmp, "MATCHMORE|", sizeof(tmp) - strlen(tmp) - 1);
1978                 if (dp->flags & CACHE_FLAG_UNKNOWN)
1979                         strncat(tmp, "UNKNOWN|", sizeof(tmp) - strlen(tmp) - 1);
1980                 /* Trim trailing pipe */
1981                 if (!ast_strlen_zero(tmp))
1982                         tmp[strlen(tmp) - 1] = '\0';
1983                 else
1984                         ast_copy_string(tmp, "(none)", sizeof(tmp));
1985                 y=0;
1986                 pc = strchr(dp->peercontext, '@');
1987                 if (!pc)
1988                         pc = dp->peercontext;
1989                 else
1990                         pc++;
1991                 for (x=0;x<sizeof(dp->waiters) / sizeof(dp->waiters[0]); x++)
1992                         if (dp->waiters[x] > -1)
1993                                 y++;
1994                 if (s > 0)
1995                         ast_cli(fd, "%-20.20s %-12.12s %-9d %-8d %s\n", pc, dp->exten, s, y, tmp);
1996                 else
1997                         ast_cli(fd, "%-20.20s %-12.12s %-9.9s %-8d %s\n", pc, dp->exten, "(expired)", y, tmp);
1998                 dp = dp->next;
1999         }
2000         ast_mutex_unlock(&dpcache_lock);
2001         return RESULT_SUCCESS;
2002 }
2003
2004 static unsigned int calc_rxstamp(struct chan_iax2_pvt *p, unsigned int offset);
2005
2006 #ifdef BRIDGE_OPTIMIZATION
2007 static unsigned int calc_fakestamp(struct chan_iax2_pvt *from, struct chan_iax2_pvt *to, unsigned int ts);
2008
2009 static int forward_delivery(struct iax_frame *fr)
2010 {
2011         struct chan_iax2_pvt *p1, *p2;
2012         char iabuf[INET_ADDRSTRLEN];
2013         int res, orig_ts;
2014
2015         p1 = iaxs[fr->callno];
2016         p2 = iaxs[p1->bridgecallno];
2017         if (!p1)
2018                 return -1;
2019         if (!p2)
2020                 return -1;
2021
2022         if (option_debug)
2023                 ast_log(LOG_DEBUG, "forward_delivery: Forwarding ts=%d on %d/%d to %d/%d on %s:%d\n",
2024                                 fr->ts,
2025                                 p1->callno, p1->peercallno,
2026                                 p2->callno, p2->peercallno,
2027                                 ast_inet_ntoa(iabuf, sizeof(iabuf), p2->addr.sin_addr),
2028                                 ntohs(p2->addr.sin_port));
2029
2030         /* Undo wraparound - which can happen when full VOICE frame wasn't sent by our peer.
2031            This is necessary for when our peer is chan_iax2.c v1.1nn or earlier which didn't
2032            send full frame on timestamp wrap when doing optimized bridging
2033            (actually current code STILL doesn't)
2034         */
2035         if (fr->ts + 50000 <= p1->last) {
2036                 fr->ts = ( (p1->last & 0xFFFF0000) + 0x10000) | (fr->ts & 0xFFFF);
2037                 if (option_debug)
2038                         ast_log(LOG_DEBUG, "forward_delivery: pushed forward timestamp to %u\n", fr->ts);
2039         }
2040
2041         /* Send with timestamp adjusted to the origin of the outbound leg */
2042         /* But don't destroy inbound timestamp still needed later to set "last" */
2043         orig_ts = fr->ts;
2044         fr->ts = calc_fakestamp(p1, p2, fr->ts);
2045         res = iax2_send(p2, &fr->af, fr->ts, -1, 0, 0, 0);
2046         fr->ts = orig_ts;
2047         return res;
2048 }
2049 #endif
2050
2051 static void unwrap_timestamp(struct iax_frame *fr)
2052 {
2053         int x;
2054
2055         if ( (fr->ts & 0xFFFF0000) == (iaxs[fr->callno]->last & 0xFFFF0000) ) {
2056                 x = fr->ts - iaxs[fr->callno]->last;
2057                 if (x < -50000) {
2058                         /* Sudden big jump backwards in timestamp:
2059                            What likely happened here is that miniframe timestamp has circled but we haven't
2060                            gotten the update from the main packet.  We'll just pretend that we did, and
2061                            update the timestamp appropriately. */
2062                         fr->ts = ( (iaxs[fr->callno]->last & 0xFFFF0000) + 0x10000) | (fr->ts & 0xFFFF);
2063                         if (option_debug)
2064                                 ast_log(LOG_DEBUG, "schedule_delivery: pushed forward timestamp\n");
2065                 }
2066                 if (x > 50000) {
2067                         /* Sudden apparent big jump forwards in timestamp:
2068                            What's likely happened is this is an old miniframe belonging to the previous
2069                            top-16-bit timestamp that has turned up out of order.
2070                            Adjust the timestamp appropriately. */
2071                         fr->ts = ( (iaxs[fr->callno]->last & 0xFFFF0000) - 0x10000) | (fr->ts & 0xFFFF);
2072                         if (option_debug)
2073                                 ast_log(LOG_DEBUG, "schedule_delivery: pushed back timestamp\n");
2074                 }
2075         }
2076 }
2077
2078 #ifdef NEWJB
2079 static int get_from_jb(void *p);
2080
2081 static void update_jbsched(struct chan_iax2_pvt *pvt) {
2082     int when;
2083     struct timeval tv;
2084
2085     gettimeofday(&tv,NULL);
2086
2087     when = (tv.tv_sec - pvt->rxcore.tv_sec) * 1000 +
2088           (tv.tv_usec - pvt->rxcore.tv_usec) / 1000;
2089
2090     /*    fprintf(stderr, "now = %d, next=%d\n", when, jb_next(pvt->jb)); */
2091
2092     when = jb_next(pvt->jb) - when;
2093     /*   fprintf(stderr, "when = %d\n", when); */
2094
2095     if(pvt->jbid > -1) ast_sched_del(sched, pvt->jbid);
2096
2097     if(when <= 0) {
2098       /* XXX should really just empty until when > 0.. */
2099       when = 1;
2100     }
2101
2102     pvt->jbid = ast_sched_add(sched, when, get_from_jb, (void *)pvt);
2103 }
2104
2105 static int get_from_jb(void *p) {
2106         /* make sure pvt is valid! */   
2107     struct chan_iax2_pvt *pvt = p;
2108     struct iax_frame *fr;
2109     jb_frame frame;
2110     int ret;
2111     long now;
2112     long next;
2113     struct timeval tv;
2114
2115     ast_mutex_lock(&iaxsl[pvt->callno]);
2116     /*  fprintf(stderr, "get_from_jb called\n"); */
2117     pvt->jbid = -1;
2118
2119     gettimeofday(&tv,NULL);
2120     /* round up a millisecond since ast_sched_runq does; */
2121     /* prevents us from spinning while waiting for our now */
2122     /* to catch up with runq's now */
2123     tv.tv_usec += 1000;
2124
2125     now = (tv.tv_sec - pvt->rxcore.tv_sec) * 1000 +
2126           (tv.tv_usec - pvt->rxcore.tv_usec) / 1000;
2127
2128     if(now >= (next = jb_next(pvt->jb))) {
2129         ret = jb_get(pvt->jb,&frame,now,ast_codec_interp_len(pvt->voiceformat));
2130         switch(ret) {
2131             case JB_OK:
2132                 /*if(frame.type == JB_TYPE_VOICE && next + 20 != jb_next(pvt->jb)) fprintf(stderr, "NEXT %ld is not %ld+20!\n", jb_next(pvt->jb), next); */
2133                 fr = frame.data;
2134                 __do_deliver(fr);
2135             break;
2136             case JB_INTERP:
2137             {
2138                 struct ast_frame af;
2139
2140                 /*if(next + 20 != jb_next(pvt->jb)) fprintf(stderr, "NEXT %ld is not %ld+20!\n", jb_next(pvt->jb), next); */
2141
2142                 /* create an interpolation frame */
2143                 /*fprintf(stderr, "Making Interpolation frame\n"); */
2144                 af.frametype = AST_FRAME_VOICE;
2145                 af.subclass = pvt->voiceformat;
2146                 af.datalen  = 0;
2147                 af.samples  = frame.ms * 8;
2148                 af.mallocd  = 0;
2149                 af.src  = "IAX2 JB interpolation";
2150                 af.data  = NULL;
2151                 af.delivery.tv_sec = pvt->rxcore.tv_sec;
2152                 af.delivery.tv_usec = pvt->rxcore.tv_usec;
2153                 af.delivery.tv_sec += next / 1000;
2154                 af.delivery.tv_usec += (next % 1000) * 1000;
2155                 af.offset=AST_FRIENDLY_OFFSET;
2156                 if (af.delivery.tv_usec >= 1000000) {
2157                         af.delivery.tv_usec -= 1000000;
2158                         af.delivery.tv_sec += 1;
2159                 }
2160
2161                 /* queue the frame:  For consistency, we would call __do_deliver here, but __do_deliver wants an iax_frame,
2162                  * which we'd need to malloc, and then it would free it.  That seems like a drag */
2163                 if (iaxs[pvt->callno] && !ast_test_flag(iaxs[pvt->callno], IAX_ALREADYGONE))
2164                         iax2_queue_frame(pvt->callno, &af);
2165             }
2166             break;
2167             case JB_DROP:
2168                 /*if(next != jb_next(pvt->jb)) fprintf(stderr, "NEXT %ld is not next %ld!\n", jb_next(pvt->jb), next); */
2169                 iax2_frame_free(frame.data);
2170             break;
2171             case JB_NOFRAME:
2172             case JB_EMPTY:
2173                 /* do nothing */
2174             break;
2175             default:
2176                 /* shouldn't happen */
2177             break;
2178         }
2179     }
2180     update_jbsched(pvt);
2181     ast_mutex_unlock(&iaxsl[pvt->callno]);
2182     return 0;
2183 }
2184 #endif
2185
2186 /* while we transition from the old JB to the new one, we can either make two schedule_delivery functions, or 
2187  * make preprocessor swiss-cheese out of this one.  I'm not sure which is less revolting.. */
2188 static int schedule_delivery(struct iax_frame *fr, int reallydeliver, int updatehistory, int fromtrunk)
2189 {
2190 #ifdef NEWJB
2191         int type, len;
2192         int ret;
2193 #else
2194         int x;
2195         int ms;
2196         int delay;
2197         unsigned int orig_ts;
2198         int drops[MEMORY_SIZE];
2199         int min, max=0, prevjitterbuffer, maxone=0,y,z, match;
2200
2201         /* Remember current jitterbuffer so we can log any change */
2202         prevjitterbuffer = iaxs[fr->callno]->jitterbuffer;
2203         /* Similarly for the frame timestamp */
2204         orig_ts = fr->ts;
2205 #endif
2206
2207 #if 0
2208         if (option_debug)
2209                 ast_log(LOG_DEBUG, "schedule_delivery: ts=%d, last=%d, really=%d, update=%d\n",
2210                                 fr->ts, iaxs[fr->callno]->last, reallydeliver, updatehistory);
2211 #endif
2212
2213         /* Attempt to recover wrapped timestamps */
2214         unwrap_timestamp(fr);
2215
2216         if (updatehistory) {
2217 #ifndef NEWJB
2218
2219                 /* Attempt to spot a change of timebase on timestamps coming from the other side
2220                    We detect by noticing a jump in consecutive timestamps that can't reasonably be explained
2221                    by network jitter or reordering.  Sometimes, also, the peer stops sending us frames
2222                    for a while - in this case this code might also resync us.  But that's not a bad thing.
2223                    Be careful of non-voice frames which are timestamped differently (especially ACKS!)
2224                    [that's why we only do this when updatehistory is true]
2225                 */
2226                 x = fr->ts - iaxs[fr->callno]->last;
2227                 if (x > TS_GAP_FOR_JB_RESYNC || x < -TS_GAP_FOR_JB_RESYNC) {
2228                         if (option_debug)
2229                                 ast_log(LOG_DEBUG, "schedule_delivery: call=%d: TS jumped.  resyncing rxcore (ts=%d, last=%d)\n",
2230                                                         fr->callno, fr->ts, iaxs[fr->callno]->last);
2231                         /* zap rxcore - calc_rxstamp will make a new one based on this frame */
2232                         iaxs[fr->callno]->rxcore.tv_sec = 0;
2233                         iaxs[fr->callno]->rxcore.tv_usec = 0;
2234                         /* wipe "last" if stamps have jumped backwards */
2235                         if (x<0)
2236                                 iaxs[fr->callno]->last = 0;
2237                         /* should we also empty history? */
2238                 }
2239                 /* ms is a measure of the "lateness" of the frame relative to the "reference"
2240                    frame we received.  (initially the very first, but also see code just above here).
2241                    Understand that "ms" can easily be -ve if lag improves since the reference frame.
2242                    Called by IAX thread, with iaxsl lock held. */
2243                 ms = calc_rxstamp(iaxs[fr->callno], fr->ts) - fr->ts;
2244         
2245                 /* Rotate our history queue of "lateness".  Don't worry about those initial
2246                    zeros because the first entry will always be zero */
2247                 for (x=0;x<MEMORY_SIZE - 1;x++) 
2248                         iaxs[fr->callno]->history[x] = iaxs[fr->callno]->history[x+1];
2249                 /* Add a history entry for this one */
2250                 iaxs[fr->callno]->history[x] = ms;
2251 #endif
2252         }
2253 #ifndef NEWJB
2254         else
2255                 ms = 0;
2256 #endif
2257
2258
2259         /* delivery time is sender's sent timestamp converted back into absolute time according to our clock */
2260         if ( (!fromtrunk) && (iaxs[fr->callno]->rxcore.tv_sec || iaxs[fr->callno]->rxcore.tv_usec) ) {
2261                 fr->af.delivery.tv_sec = iaxs[fr->callno]->rxcore.tv_sec;
2262                 fr->af.delivery.tv_usec = iaxs[fr->callno]->rxcore.tv_usec;
2263                 fr->af.delivery.tv_sec += fr->ts / 1000;
2264                 fr->af.delivery.tv_usec += (fr->ts % 1000) * 1000;
2265                 if (fr->af.delivery.tv_usec >= 1000000) {
2266                         fr->af.delivery.tv_usec -= 1000000;
2267                         fr->af.delivery.tv_sec += 1;
2268                 }
2269         }
2270         else {
2271 #if 0
2272                 if (reallydeliver)
2273                         ast_log(LOG_DEBUG, "schedule_delivery: set delivery to 0 as we don't have an rxcore yet, or frame is from trunk.\n");
2274 #endif
2275                 fr->af.delivery.tv_sec = 0;
2276                 fr->af.delivery.tv_usec = 0;
2277         }
2278
2279 #ifndef NEWJB
2280         /* Initialize the minimum to reasonable values.  It's too much
2281            work to do the same for the maximum, repeatedly */
2282         min=iaxs[fr->callno]->history[0];
2283         for (z=0;z < iax2_dropcount + 1;z++) {
2284                 /* Start very optimistic ;-) */
2285                 max=-999999999;
2286                 for (x=0;x<MEMORY_SIZE;x++) {
2287                         if (max < iaxs[fr->callno]->history[x]) {
2288                                 /* We have a candidate new maximum value.  Make
2289                                    sure it's not in our drop list */
2290                                 match = 0;
2291                                 for (y=0;!match && (y<z);y++)
2292                                         match |= (drops[y] == x);
2293                                 if (!match) {
2294                                         /* It's not in our list, use it as the new maximum */
2295                                         max = iaxs[fr->callno]->history[x];
2296                                         maxone = x;
2297                                 }
2298                                 
2299                         }
2300                         if (!z) {
2301                                 /* On our first pass, find the minimum too */
2302                                 if (min > iaxs[fr->callno]->history[x])
2303                                         min = iaxs[fr->callno]->history[x];
2304                         }
2305                 }
2306 #if 1
2307                 drops[z] = maxone;
2308 #endif
2309         }
2310 #endif
2311
2312 #ifdef NEWJB
2313         if(!reallydeliver)
2314                 return 0;
2315
2316         type = JB_TYPE_CONTROL;
2317         len = 0;
2318
2319         if(fr->af.frametype == AST_FRAME_VOICE) {
2320                 type = JB_TYPE_VOICE;
2321                 len = ast_codec_get_samples(&fr->af) / 8;
2322         } else if(fr->af.frametype == AST_FRAME_CNG) {
2323                 type = JB_TYPE_SILENCE;
2324         }
2325
2326         if ( (!ast_test_flag(iaxs[fr->callno], IAX_USEJITTERBUF)) ) {
2327                 __do_deliver(fr);
2328                 return 0;
2329         }
2330
2331         /* if the user hasn't requested we force the use of the jitterbuffer, and we're bridged to
2332          * a channel that can accept jitter, then flush and suspend the jb, and send this frame straight through */
2333         if( (!ast_test_flag(iaxs[fr->callno], IAX_FORCEJITTERBUF)) &&
2334             iaxs[fr->callno]->owner && ast_bridged_channel(iaxs[fr->callno]->owner) &&
2335             (ast_bridged_channel(iaxs[fr->callno]->owner)->tech->properties & AST_CHAN_TP_WANTSJITTER)) {
2336                 jb_frame frame;
2337
2338                 /* deliver any frames in the jb */
2339                 while(jb_getall(iaxs[fr->callno]->jb,&frame) == JB_OK)
2340                         __do_deliver(frame.data);
2341
2342                 jb_reset(iaxs[fr->callno]->jb);
2343
2344                 if (iaxs[fr->callno]->jbid > -1)
2345                         ast_sched_del(sched, iaxs[fr->callno]->jbid);
2346
2347                 iaxs[fr->callno]->jbid = -1;
2348
2349                 /* deliver this frame now */
2350                 __do_deliver(fr);
2351                 return 0;
2352
2353         }
2354
2355
2356         /* insert into jitterbuffer */
2357         /* TODO: Perhaps we could act immediately if it's not droppable and late */
2358         ret = jb_put(iaxs[fr->callno]->jb, fr, type, len, fr->ts,
2359                         calc_rxstamp(iaxs[fr->callno],fr->ts));
2360         if (ret == JB_DROP) {
2361                 iax2_frame_free(fr);
2362         } else if (ret == JB_SCHED) {
2363                 update_jbsched(iaxs[fr->callno]);
2364         }
2365 #else
2366         /* Just for reference, keep the "jitter" value, the difference between the
2367            earliest and the latest. */
2368         if (max >= min)
2369                 iaxs[fr->callno]->jitter = max - min;   
2370         
2371         /* IIR filter for keeping track of historic jitter, but always increase
2372            historic jitter immediately for increase */
2373         
2374         if (iaxs[fr->callno]->jitter > iaxs[fr->callno]->historicjitter )
2375                 iaxs[fr->callno]->historicjitter = iaxs[fr->callno]->jitter;
2376         else
2377                 iaxs[fr->callno]->historicjitter = GAMMA * (double)iaxs[fr->callno]->jitter + (1-GAMMA) * 
2378                         iaxs[fr->callno]->historicjitter;
2379
2380         /* If our jitter buffer is too big (by a significant margin), then we slowly
2381            shrink it to avoid letting the change be perceived */
2382         if (max < iaxs[fr->callno]->jitterbuffer - max_jitter_buffer)
2383                 iaxs[fr->callno]->jitterbuffer -= jittershrinkrate;
2384
2385         /* If our jitter buffer headroom is too small (by a significant margin), then we slowly enlarge it */
2386         /* min_jitter_buffer should be SMALLER than max_jitter_buffer - leaving a "no mans land"
2387            in between - otherwise the jitterbuffer size will hunt up and down causing unnecessary
2388            disruption.  Set maxexcessbuffer to say 150msec, minexcessbuffer to say 50 */
2389         if (max > iaxs[fr->callno]->jitterbuffer - min_jitter_buffer)
2390                 iaxs[fr->callno]->jitterbuffer += jittershrinkrate;
2391
2392         /* If our jitter buffer is smaller than our maximum delay, grow the jitter
2393            buffer immediately to accomodate it (and a little more).  */
2394         if (max > iaxs[fr->callno]->jitterbuffer)
2395                 iaxs[fr->callno]->jitterbuffer = max 
2396                         /* + ((float)iaxs[fr->callno]->jitter) * 0.1 */;
2397
2398         /* update "min", just for RRs and stats */
2399         iaxs[fr->callno]->min = min; 
2400
2401         /* If the caller just wanted us to update, return now */
2402         if (!reallydeliver)
2403                 return 0;
2404
2405         /* Subtract the lateness from our jitter buffer to know how long to wait
2406            before sending our packet.  */
2407         delay = iaxs[fr->callno]->jitterbuffer - ms;
2408
2409         /* Whatever happens, no frame waits longer than maxjitterbuffer */
2410         if (delay > maxjitterbuffer)
2411                 delay = maxjitterbuffer;
2412         
2413         /* If jitter buffer is disabled then just pretend the frame is "right on time" */
2414         /* If frame came from trunk, also don't do any delay */
2415         if ( (!ast_test_flag(iaxs[fr->callno], IAX_USEJITTERBUF)) || fromtrunk )
2416                 delay = 0;
2417
2418         if (option_debug) {
2419                 /* Log jitter stats for possible offline analysis */
2420                 ast_log(LOG_DEBUG, "Jitter: call=%d ts=%d orig=%d last=%d %s: min=%d max=%d jb=%d %+d lateness=%d jbdelay=%d jitter=%d historic=%d\n",
2421                                         fr->callno, fr->ts, orig_ts, iaxs[fr->callno]->last,
2422                                         (fr->af.frametype == AST_FRAME_VOICE) ? "VOICE" : "CONTROL",
2423                                         min, max, iaxs[fr->callno]->jitterbuffer,
2424                                         iaxs[fr->callno]->jitterbuffer - prevjitterbuffer,
2425                                         ms, delay,
2426                                         iaxs[fr->callno]->jitter, iaxs[fr->callno]->historicjitter);
2427         }
2428
2429         if (delay < 1) {
2430                 /* Don't deliver it more than 4 ms late */
2431                 if ((delay > -4) || (fr->af.frametype != AST_FRAME_VOICE)) {
2432                         if (option_debug)
2433                                 ast_log(LOG_DEBUG, "schedule_delivery: Delivering immediately (Calculated delay is %d)\n", delay);
2434                         __do_deliver(fr);
2435                 } else {
2436                         if (option_debug)
2437                                 ast_log(LOG_DEBUG, "schedule_delivery: Dropping voice packet since %dms delay is too old\n", delay);
2438                         iaxs[fr->callno]->frames_dropped++;
2439                         /* Free our iax frame */
2440                         iax2_frame_free(fr);
2441                 }
2442         } else {
2443                 if (option_debug)
2444                         ast_log(LOG_DEBUG, "schedule_delivery: Scheduling delivery in %d ms\n", delay);
2445                 fr->retrans = ast_sched_add(sched, delay, do_deliver, fr);
2446         }
2447 #endif
2448         return 0;
2449 }
2450
2451 static int iax2_transmit(struct iax_frame *fr)
2452 {
2453         /* Lock the queue and place this packet at the end */
2454         fr->next = NULL;
2455         fr->prev = NULL;
2456         /* By setting this to 0, the network thread will send it for us, and
2457            queue retransmission if necessary */
2458         fr->sentyet = 0;
2459         ast_mutex_lock(&iaxq.lock);
2460         if (!iaxq.head) {
2461                 /* Empty queue */
2462                 iaxq.head = fr;
2463                 iaxq.tail = fr;
2464         } else {
2465                 /* Double link */
2466                 iaxq.tail->next = fr;
2467                 fr->prev = iaxq.tail;
2468                 iaxq.tail = fr;
2469         }
2470         iaxq.count++;
2471         ast_mutex_unlock(&iaxq.lock);
2472         /* Wake up the network thread */
2473         pthread_kill(netthreadid, SIGURG);
2474         return 0;
2475 }
2476
2477
2478
2479 static int iax2_digit(struct ast_channel *c, char digit)
2480 {
2481         return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_DTMF, digit, 0, NULL, 0, -1);
2482 }
2483
2484 static int iax2_sendtext(struct ast_channel *c, const char *text)
2485 {
2486         
2487         return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_TEXT,
2488                 0, 0, text, strlen(text) + 1, -1);
2489 }
2490
2491 static int iax2_sendimage(struct ast_channel *c, struct ast_frame *img)
2492 {
2493         return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_IMAGE, img->subclass, 0, img->data, img->datalen, -1);
2494 }
2495
2496 static int iax2_sendhtml(struct ast_channel *c, int subclass, const char *data, int datalen)
2497 {
2498         return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_HTML, subclass, 0, data, datalen, -1);
2499 }
2500
2501 static int iax2_fixup(struct ast_channel *oldchannel, struct ast_channel *newchan)
2502 {
2503         unsigned short callno = PTR_TO_CALLNO(newchan->tech_pvt);
2504         ast_mutex_lock(&iaxsl[callno]);
2505         if (iaxs[callno])
2506                 iaxs[callno]->owner = newchan;
2507         else
2508                 ast_log(LOG_WARNING, "Uh, this isn't a good sign...\n");
2509         ast_mutex_unlock(&iaxsl[callno]);
2510         return 0;
2511 }
2512
2513 static struct iax2_peer *build_peer(const char *name, struct ast_variable *v, int temponly);
2514 static struct iax2_user *build_user(const char *name, struct ast_variable *v, int temponly);
2515
2516 static void destroy_user(struct iax2_user *user);
2517 static int expire_registry(void *data);
2518
2519 static struct iax2_peer *realtime_peer(const char *peername)
2520 {
2521         struct ast_variable *var;
2522         struct ast_variable *tmp;
2523         struct iax2_peer *peer=NULL;
2524         time_t regseconds, nowtime;
2525         int dynamic=0;
2526
2527         var = ast_load_realtime("iaxpeers", "name", peername, NULL);
2528         if (!var)
2529                 return NULL;
2530
2531         peer = build_peer(peername, var, ast_test_flag((&globalflags), IAX_RTCACHEFRIENDS) ? 0 : 1);
2532         
2533         if (!peer)
2534                 return NULL;
2535
2536         tmp = var;
2537         while(tmp) {
2538                 /* Make sure it's not a user only... */
2539                 if (!strcasecmp(tmp->name, "type")) {
2540                         if (strcasecmp(tmp->value, "friend") &&
2541                             strcasecmp(tmp->value, "peer")) {
2542                                 /* Whoops, we weren't supposed to exist! */
2543                                 destroy_peer(peer);
2544                                 peer = NULL;
2545                                 break;
2546                         } 
2547                 } else if (!strcasecmp(tmp->name, "regseconds")) {
2548                         if (sscanf(tmp->value, "%li", &regseconds) != 1)
2549                                 regseconds = 0;
2550                 } else if (!strcasecmp(tmp->name, "ipaddr")) {
2551                         inet_aton(tmp->value, &(peer->addr.sin_addr));
2552                 } else if (!strcasecmp(tmp->name, "port")) {
2553                         peer->addr.sin_port = htons(atoi(tmp->value));
2554                 } else if (!strcasecmp(tmp->name, "host")) {
2555                         if (!strcasecmp(tmp->value, "dynamic"))
2556                                 dynamic = 1;
2557                 }
2558                 tmp = tmp->next;
2559         }
2560         if (!peer)
2561                 return NULL;
2562
2563         ast_variables_destroy(var);
2564
2565         if (ast_test_flag((&globalflags), IAX_RTCACHEFRIENDS)) {
2566                 ast_copy_flags(peer, &globalflags, IAX_RTAUTOCLEAR|IAX_RTCACHEFRIENDS);
2567                 if (ast_test_flag(peer, IAX_RTAUTOCLEAR)) {
2568                         if (peer->expire > -1)
2569                                 ast_sched_del(sched, peer->expire);
2570                         peer->expire = ast_sched_add(sched, (global_rtautoclear) * 1000, expire_registry, peer);
2571                 }
2572                 ast_mutex_lock(&peerl.lock);
2573                 peer->next = peerl.peers;
2574                 peerl.peers = peer;
2575                 ast_mutex_unlock(&peerl.lock);
2576                 if (ast_test_flag(peer, IAX_DYNAMIC))
2577                         reg_source_db(peer);
2578         } else {
2579                 ast_set_flag(peer, IAX_TEMPONLY);       
2580         }
2581
2582         if (dynamic) {
2583                 time(&nowtime);
2584                 if ((nowtime - regseconds) > IAX_DEFAULT_REG_EXPIRE) {
2585                         memset(&peer->addr, 0, sizeof(peer->addr));
2586                         if (option_debug)
2587                                 ast_log(LOG_DEBUG, "Bah, we're expired (%ld/%ld/%ld)!\n", nowtime - regseconds, regseconds, nowtime);
2588                 }
2589         }
2590
2591         return peer;
2592 }
2593
2594 static struct iax2_user *realtime_user(const char *username)
2595 {
2596         struct ast_variable *var;
2597         struct ast_variable *tmp;
2598         struct iax2_user *user=NULL;
2599
2600         var = ast_load_realtime("iaxusers", "name", username, NULL);
2601         if (!var)
2602                 return NULL;
2603
2604         tmp = var;
2605         while(tmp) {
2606                 /* Make sure it's not a peer only... */
2607                 if (!strcasecmp(tmp->name, "type")) {
2608                         if (strcasecmp(tmp->value, "friend") &&
2609                             strcasecmp(tmp->value, "user")) {
2610                                 return NULL;
2611                         } 
2612                 }
2613                 tmp = tmp->next;
2614         }
2615
2616         user = build_user(username, var, !ast_test_flag((&globalflags), IAX_RTCACHEFRIENDS));
2617         if (!user)
2618                 return NULL;
2619
2620         ast_variables_destroy(var);
2621
2622         if (ast_test_flag((&globalflags), IAX_RTCACHEFRIENDS)) {
2623                 ast_set_flag(user, IAX_RTCACHEFRIENDS);
2624                 ast_mutex_lock(&userl.lock);
2625                 user->next = userl.users;
2626                 userl.users = user;
2627                 ast_mutex_unlock(&userl.lock);
2628         } else {
2629                 ast_set_flag(user, IAX_TEMPONLY);       
2630         }
2631
2632         return user;
2633 }
2634
2635 static void realtime_update_peer(const char *peername, struct sockaddr_in *sin)
2636 {
2637         char port[10];
2638         char ipaddr[20];
2639         char regseconds[20];
2640         time_t nowtime;
2641         
2642         time(&nowtime);
2643         snprintf(regseconds, sizeof(regseconds), "%ld", nowtime);
2644         ast_inet_ntoa(ipaddr, sizeof(ipaddr), sin->sin_addr);
2645         snprintf(port, sizeof(port), "%d", ntohs(sin->sin_port));
2646         ast_update_realtime("iaxpeers", "name", peername, "ipaddr", ipaddr, "port", port, "regseconds", regseconds, NULL);
2647 }
2648
2649 struct create_addr_info {
2650         int capability;
2651         unsigned int flags;
2652         int maxtime;
2653         int encmethods;
2654         int found;
2655         int sockfd;
2656         char username[80];
2657         char secret[80];
2658         char outkey[80];
2659         char timezone[80];
2660         char prefs[32];
2661         char context[AST_MAX_EXTENSION];
2662         char peercontext[AST_MAX_EXTENSION];
2663 };
2664
2665 static int create_addr(const char *peername, struct sockaddr_in *sin, struct create_addr_info *cai)
2666 {
2667         struct ast_hostent ahp;
2668         struct hostent *hp;
2669         struct iax2_peer *peer;
2670
2671         ast_clear_flag(cai, IAX_SENDANI | IAX_TRUNK);
2672         cai->sockfd = defaultsockfd;
2673         cai->maxtime = 0;
2674         sin->sin_family = AF_INET;
2675
2676         if (!(peer = find_peer(peername, 1))) {
2677                 cai->found = 0;
2678
2679                 hp = ast_gethostbyname(peername, &ahp);
2680                 if (hp) {
2681                         memcpy(&sin->sin_addr, hp->h_addr, sizeof(sin->sin_addr));
2682                         sin->sin_port = htons(IAX_DEFAULT_PORTNO);
2683                         /* use global iax prefs for unknown peer/user */
2684                         ast_codec_pref_convert(&prefs, cai->prefs, sizeof(cai->prefs), 1);
2685                         return 0;
2686                 } else {
2687                         ast_log(LOG_WARNING, "No such host: %s\n", peername);
2688                         return -1;
2689                 }
2690         }
2691
2692         cai->found = 1;
2693         
2694         /* if the peer has no address (current or default), return failure */
2695         if (!(peer->addr.sin_addr.s_addr || peer->defaddr.sin_addr.s_addr)) {
2696                 if (ast_test_flag(peer, IAX_TEMPONLY))
2697                         destroy_peer(peer);
2698                 return -1;
2699         }
2700
2701         /* if the peer is being monitored and is currently unreachable, return failure */
2702         if (peer->maxms && (peer->lastms > peer->maxms)) {
2703                 if (ast_test_flag(peer, IAX_TEMPONLY))
2704                         destroy_peer(peer);
2705                 return -1;
2706         }
2707
2708         ast_copy_flags(cai, peer, IAX_SENDANI | IAX_TRUNK | IAX_NOTRANSFER | IAX_USEJITTERBUF | IAX_FORCEJITTERBUF);
2709         cai->maxtime = peer->maxms;
2710         cai->capability = peer->capability;
2711         cai->encmethods = peer->encmethods;
2712         cai->sockfd = peer->sockfd;
2713         ast_codec_pref_convert(&peer->prefs, cai->prefs, sizeof(cai->prefs), 1);
2714         ast_copy_string(cai->context, peer->context, sizeof(cai->context));
2715         ast_copy_string(cai->peercontext, peer->peercontext, sizeof(cai->peercontext));
2716         ast_copy_string(cai->username, peer->username, sizeof(cai->username));
2717         ast_copy_string(cai->timezone, peer->zonetag, sizeof(cai->timezone));
2718         ast_copy_string(cai->outkey, peer->outkey, sizeof(cai->outkey));
2719         if (ast_strlen_zero(peer->dbsecret)) {
2720                 ast_copy_string(cai->secret, peer->secret, sizeof(cai->secret));
2721         } else {
2722                 char *family;
2723                 char *key = NULL;
2724
2725                 family = ast_strdupa(peer->dbsecret);
2726                 if (family) {
2727                         key = strchr(family, '/');
2728                         if (key)
2729                                 *key++ = '\0';
2730                 }
2731                 if (!family || !key || ast_db_get(family, key, cai->secret, sizeof(cai->secret))) {
2732                         ast_log(LOG_WARNING, "Unable to retrieve database password for family/key '%s'!\n", peer->dbsecret);
2733                         if (ast_test_flag(peer, IAX_TEMPONLY))
2734                                 destroy_peer(peer);
2735                         return -1;
2736                 }
2737         }
2738
2739         if (peer->addr.sin_addr.s_addr) {
2740                 sin->sin_addr = peer->addr.sin_addr;
2741                 sin->sin_port = peer->addr.sin_port;
2742         } else {
2743                 sin->sin_addr = peer->defaddr.sin_addr;
2744                 sin->sin_port = peer->defaddr.sin_port;
2745         }
2746
2747         if (ast_test_flag(peer, IAX_TEMPONLY))
2748                 destroy_peer(peer);
2749
2750         return 0;
2751 }
2752
2753 static int auto_congest(void *nothing)
2754 {
2755         int callno = PTR_TO_CALLNO(nothing);
2756         struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_CONGESTION };
2757         ast_mutex_lock(&iaxsl[callno]);
2758         if (iaxs[callno]) {
2759                 iaxs[callno]->initid = -1;
2760                 iax2_queue_frame(callno, &f);
2761                 ast_log(LOG_NOTICE, "Auto-congesting call due to slow response\n");
2762         }
2763         ast_mutex_unlock(&iaxsl[callno]);
2764         return 0;
2765 }
2766
2767 static unsigned int iax2_datetime(char *tz)
2768 {
2769         time_t t;
2770         struct tm tm;
2771         unsigned int tmp;
2772         time(&t);
2773         localtime_r(&t, &tm);
2774         if (!ast_strlen_zero(tz))
2775                 ast_localtime(&t, &tm, tz);
2776         tmp  = (tm.tm_sec >> 1) & 0x1f;                 /* 5 bits of seconds */
2777         tmp |= (tm.tm_min & 0x3f) << 5;                 /* 6 bits of minutes */
2778         tmp |= (tm.tm_hour & 0x1f) << 11;               /* 5 bits of hours */
2779         tmp |= (tm.tm_mday & 0x1f) << 16;               /* 5 bits of day of month */
2780         tmp |= ((tm.tm_mon + 1) & 0xf) << 21;           /* 4 bits of month */
2781         tmp |= ((tm.tm_year - 100) & 0x7f) << 25;       /* 7 bits of year */
2782         return tmp;
2783 }
2784
2785 struct parsed_dial_string {
2786         char *username;
2787         char *password;
2788         char *key;
2789         char *peer;
2790         char *port;
2791         char *exten;
2792         char *context;
2793         char *options;
2794 };
2795
2796 /*!
2797  * \brief Parses an IAX dial string into its component parts.
2798  * \param data the string to be parsed
2799  * \param pds pointer to a \c struct \c parsed_dial_string to be filled in
2800  * \return nothing
2801  *
2802  * This function parses the string and fills the structure
2803  * with pointers to its component parts. The input string
2804  * will be modified.
2805  *
2806  * \note This function supports both plaintext passwords and RSA
2807  * key names; if the password string is formatted as '[keyname]',
2808  * then the keyname will be placed into the key field, and the
2809  * password field will be set to NULL.
2810  *
2811  * \note The dial string format is:
2812  *       [username[:password]@]peer[:port][/exten[@@context]][/options]
2813  */
2814 static void parse_dial_string(char *data, struct parsed_dial_string *pds)
2815 {
2816         if (!data || ast_strlen_zero(data))
2817                 return;
2818
2819         pds->peer = strsep(&data, "/");
2820         pds->exten = strsep(&data, "/");
2821         pds->options = data;
2822
2823         if (pds->exten) {
2824                 data = pds->exten;
2825                 pds->exten = strsep(&data, "@");
2826                 pds->context = data;
2827         }
2828
2829         if (strchr(pds->peer, '@')) {
2830                 data = pds->peer;
2831                 pds->username = strsep(&data, "@");
2832                 pds->peer = data;
2833         }
2834
2835         if (pds->username) {
2836                 data = pds->username;
2837                 pds->username = strsep(&data, ":");
2838                 pds->password = data;
2839         }
2840
2841         data = pds->peer;
2842         pds->peer = strsep(&data, ":");
2843         pds->port = data;
2844
2845         /* check for a key name wrapped in [] in the secret position, if found,
2846            move it to the key field instead
2847         */
2848         if (pds->password && (pds->password[0] == '[')) {
2849                 pds->key = ast_strip_quoted(pds->password, "[", "]");
2850                 pds->password = NULL;
2851         }
2852 }
2853
2854 static int iax2_call(struct ast_channel *c, char *dest, int timeout)
2855 {
2856         struct sockaddr_in sin;
2857         char *l=NULL, *n=NULL;
2858         struct iax_ie_data ied;
2859         char *defaultrdest = "s";
2860         unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
2861         struct parsed_dial_string pds;
2862         struct create_addr_info cai;
2863
2864         if ((c->_state != AST_STATE_DOWN) && (c->_state != AST_STATE_RESERVED)) {
2865                 ast_log(LOG_WARNING, "Channel is already in use (%s)?\n", c->name);
2866                 return -1;
2867         }
2868
2869         memset(&cai, 0, sizeof(cai));
2870         cai.encmethods = iax2_encryption;
2871
2872         memset(&pds, 0, sizeof(pds));
2873         parse_dial_string(ast_strdupa(dest), &pds);
2874
2875         if (!pds.exten)
2876                 pds.exten = defaultrdest;
2877
2878         if (create_addr(pds.peer, &sin, &cai)) {
2879                 ast_log(LOG_WARNING, "No address associated with '%s'\n", pds.peer);
2880                 return -1;
2881         }
2882
2883         if (!pds.username && !ast_strlen_zero(cai.username))
2884                 pds.username = cai.username;
2885         if (!pds.password && !ast_strlen_zero(cai.secret))
2886                 pds.password = cai.secret;
2887         if (!pds.key && !ast_strlen_zero(cai.outkey))
2888                 pds.key = cai.outkey;
2889         if (!pds.context && !ast_strlen_zero(cai.peercontext))
2890                 pds.context = cai.peercontext;
2891
2892         /* Keep track of the context for outgoing calls too */
2893         ast_copy_string(c->context, cai.context, sizeof(c->context));
2894
2895         if (pds.port)
2896                 sin.sin_port = htons(atoi(pds.port));
2897
2898         l = c->cid.cid_num;
2899         n = c->cid.cid_name;
2900
2901         /* Now build request */ 
2902         memset(&ied, 0, sizeof(ied));
2903
2904         /* On new call, first IE MUST be IAX version of caller */
2905         iax_ie_append_short(&ied, IAX_IE_VERSION, IAX_PROTO_VERSION);
2906         iax_ie_append_str(&ied, IAX_IE_CALLED_NUMBER, pds.exten);
2907         if (pds.options && strchr(pds.options, 'a')) {
2908                 /* Request auto answer */
2909                 iax_ie_append(&ied, IAX_IE_AUTOANSWER);
2910         }
2911
2912         iax_ie_append_str(&ied, IAX_IE_CODEC_PREFS, cai.prefs);
2913
2914         if (l) {
2915                 iax_ie_append_str(&ied, IAX_IE_CALLING_NUMBER, l);
2916                 iax_ie_append_byte(&ied, IAX_IE_CALLINGPRES, c->cid.cid_pres);
2917         } else {
2918                 iax_ie_append_byte(&ied, IAX_IE_CALLINGPRES, AST_PRES_NUMBER_NOT_AVAILABLE);
2919         }
2920
2921         iax_ie_append_byte(&ied, IAX_IE_CALLINGTON, c->cid.cid_ton);
2922         iax_ie_append_short(&ied, IAX_IE_CALLINGTNS, c->cid.cid_tns);
2923
2924         if (n)
2925                 iax_ie_append_str(&ied, IAX_IE_CALLING_NAME, n);
2926         if (ast_test_flag(iaxs[callno], IAX_SENDANI) && c->cid.cid_ani)
2927                 iax_ie_append_str(&ied, IAX_IE_CALLING_ANI, c->cid.cid_ani);
2928
2929         if (c->language && !ast_strlen_zero(c->language))
2930                 iax_ie_append_str(&ied, IAX_IE_LANGUAGE, c->language);
2931         if (c->cid.cid_dnid && !ast_strlen_zero(c->cid.cid_dnid))
2932                 iax_ie_append_str(&ied, IAX_IE_DNID, c->cid.cid_dnid);
2933
2934         if (pds.context)
2935                 iax_ie_append_str(&ied, IAX_IE_CALLED_CONTEXT, pds.context);
2936
2937         if (pds.username)
2938                 iax_ie_append_str(&ied, IAX_IE_USERNAME, pds.username);
2939
2940         if (cai.encmethods)
2941                 iax_ie_append_short(&ied, IAX_IE_ENCRYPTION, cai.encmethods);
2942
2943         ast_mutex_lock(&iaxsl[callno]);
2944
2945         if (!ast_strlen_zero(c->context))
2946                 ast_copy_string(iaxs[callno]->context, c->context, sizeof(iaxs[callno]->context));
2947
2948         if (pds.username)
2949                 ast_copy_string(iaxs[callno]->username, pds.username, sizeof(iaxs[callno]->username));
2950
2951         iaxs[callno]->encmethods = cai.encmethods;
2952
2953         if (pds.key)
2954                 ast_copy_string(iaxs[callno]->outkey, pds.key, sizeof(iaxs[callno]->outkey));
2955         if (pds.password)
2956                 ast_copy_string(iaxs[callno]->secret, pds.password, sizeof(iaxs[callno]->secret));
2957
2958         iax_ie_append_int(&ied, IAX_IE_FORMAT, c->nativeformats);
2959         iax_ie_append_int(&ied, IAX_IE_CAPABILITY, iaxs[callno]->capability);
2960         iax_ie_append_short(&ied, IAX_IE_ADSICPE, c->adsicpe);
2961         iax_ie_append_int(&ied, IAX_IE_DATETIME, iax2_datetime(cai.timezone));
2962
2963         if (iaxs[callno]->maxtime) {
2964                 /* Initialize pingtime and auto-congest time */
2965                 iaxs[callno]->pingtime = iaxs[callno]->maxtime / 2;
2966                 iaxs[callno]->initid = ast_sched_add(sched, iaxs[callno]->maxtime * 2, auto_congest, CALLNO_TO_PTR(callno));
2967         } else if (autokill) {
2968                 iaxs[callno]->pingtime = autokill / 2;
2969                 iaxs[callno]->initid = ast_sched_add(sched, autokill * 2, auto_congest, CALLNO_TO_PTR(callno));
2970         }
2971
2972         /* Transmit the string in a "NEW" request */
2973         send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_NEW, 0, ied.buf, ied.pos, -1);
2974
2975         ast_mutex_unlock(&iaxsl[callno]);
2976         ast_setstate(c, AST_STATE_RINGING);
2977         
2978         return 0;
2979 }
2980
2981 static int iax2_hangup(struct ast_channel *c) 
2982 {
2983         unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
2984         int alreadygone;
2985         struct iax_ie_data ied;
2986         memset(&ied, 0, sizeof(ied));
2987         ast_mutex_lock(&iaxsl[callno]);
2988         if (callno && iaxs[callno]) {
2989                 ast_log(LOG_DEBUG, "We're hanging up %s now...\n", c->name);
2990                 alreadygone = ast_test_flag(iaxs[callno], IAX_ALREADYGONE);
2991                 /* Send the hangup unless we have had a transmission error or are already gone */
2992                 iax_ie_append_byte(&ied, IAX_IE_CAUSECODE, (unsigned char)c->hangupcause);
2993                 if (!iaxs[callno]->error && !alreadygone) 
2994                         send_command_final(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_HANGUP, 0, ied.buf, ied.pos, -1);
2995                 /* Explicitly predestroy it */
2996                 iax2_predestroy_nolock(callno);
2997                 /* If we were already gone to begin with, destroy us now */
2998                 if (alreadygone) {
2999                         ast_log(LOG_DEBUG, "Really destroying %s now...\n", c->name);
3000                         iax2_destroy_nolock(callno);
3001                 }
3002         }
3003         ast_mutex_unlock(&iaxsl[callno]);
3004         if (option_verbose > 2) 
3005                 ast_verbose(VERBOSE_PREFIX_3 "Hungup '%s'\n", c->name);
3006         return 0;
3007 }
3008
3009 static int iax2_setoption(struct ast_channel *c, int option, void *data, int datalen)
3010 {
3011         struct ast_option_header *h;
3012         int res;
3013         h = malloc(datalen + sizeof(struct ast_option_header));
3014         if (h) {
3015                 h->flag = AST_OPTION_FLAG_REQUEST;
3016                 h->option = htons(option);
3017                 memcpy(h->data, data, datalen);
3018                 res = send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_CONTROL,
3019                         AST_CONTROL_OPTION, 0, (char *)h, datalen + sizeof(struct ast_option_header), -1);
3020                 free(h);
3021                 return res;
3022         } else 
3023                 ast_log(LOG_WARNING, "Out of memory\n");
3024         return -1;
3025 }
3026
3027 static struct ast_frame *iax2_read(struct ast_channel *c) 
3028 {
3029         static struct ast_frame f = { AST_FRAME_NULL, };
3030         ast_log(LOG_NOTICE, "I should never be called!\n");
3031         return &f;
3032 }
3033
3034 static int iax2_start_transfer(unsigned short callno0, unsigned short callno1)
3035 {
3036         int res;
3037         struct iax_ie_data ied0;
3038         struct iax_ie_data ied1;
3039         unsigned int transferid = rand();
3040         memset(&ied0, 0, sizeof(ied0));
3041         iax_ie_append_addr(&ied0, IAX_IE_APPARENT_ADDR, &iaxs[callno1]->addr);
3042         iax_ie_append_short(&ied0, IAX_IE_CALLNO, iaxs[callno1]->peercallno);
3043         iax_ie_append_int(&ied0, IAX_IE_TRANSFERID, transferid);
3044
3045         memset(&ied1, 0, sizeof(ied1));
3046         iax_ie_append_addr(&ied1, IAX_IE_APPARENT_ADDR, &iaxs[callno0]->addr);
3047         iax_ie_append_short(&ied1, IAX_IE_CALLNO, iaxs[callno0]->peercallno);
3048         iax_ie_append_int(&ied1, IAX_IE_TRANSFERID, transferid);
3049         
3050         res = send_command(iaxs[callno0], AST_FRAME_IAX, IAX_COMMAND_TXREQ, 0, ied0.buf, ied0.pos, -1);
3051         if (res)
3052                 return -1;
3053         res = send_command(iaxs[callno1], AST_FRAME_IAX, IAX_COMMAND_TXREQ, 0, ied1.buf, ied1.pos, -1);
3054         if (res)
3055                 return -1;
3056         iaxs[callno0]->transferring = TRANSFER_BEGIN;
3057         iaxs[callno1]->transferring = TRANSFER_BEGIN;
3058         return 0;
3059 }
3060
3061 static void lock_both(unsigned short callno0, unsigned short callno1)
3062 {
3063         ast_mutex_lock(&iaxsl[callno0]);
3064         while (ast_mutex_trylock(&iaxsl[callno1])) {
3065                 ast_mutex_unlock(&iaxsl[callno0]);
3066                 usleep(10);
3067                 ast_mutex_lock(&iaxsl[callno0]);
3068         }
3069 }
3070
3071 static void unlock_both(unsigned short callno0, unsigned short callno1)
3072 {
3073         ast_mutex_unlock(&iaxsl[callno1]);
3074         ast_mutex_unlock(&iaxsl[callno0]);
3075 }
3076
3077 static int iax2_bridge(struct ast_channel *c0, struct ast_channel *c1, int flags, struct ast_frame **fo, struct ast_channel **rc)
3078 {
3079         struct ast_channel *cs[3];
3080         struct ast_channel *who;
3081         int to = -1;
3082         int res = -1;
3083         int transferstarted=0;
3084         struct ast_frame *f;
3085         unsigned short callno0 = PTR_TO_CALLNO(c0->tech_pvt);
3086         unsigned short callno1 = PTR_TO_CALLNO(c1->tech_pvt);
3087         struct timeval waittimer = {0, 0}, tv;
3088
3089         lock_both(callno0, callno1);
3090         /* Put them in native bridge mode */
3091         if (!flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1)) {
3092                 iaxs[callno0]->bridgecallno = callno1;
3093                 iaxs[callno1]->bridgecallno = callno0;
3094         }
3095         unlock_both(callno0, callno1);
3096
3097         /* If not, try to bridge until we can execute a transfer, if we can */
3098         cs[0] = c0;
3099         cs[1] = c1;
3100         for (/* ever */;;) {
3101                 /* Check in case we got masqueraded into */
3102                 if ((c0->type != channeltype) || (c1->type != channeltype)) {
3103                         if (option_verbose > 2)
3104                                 ast_verbose(VERBOSE_PREFIX_3 "Can't masquerade, we're different...\n");
3105                         /* Remove from native mode */
3106                         if (c0->type == channeltype) {
3107                                 ast_mutex_lock(&iaxsl[callno0]);
3108                                 iaxs[callno0]->bridgecallno = 0;
3109                                 ast_mutex_unlock(&iaxsl[callno0]);
3110                         }
3111                         if (c1->type == channeltype) {
3112                                 ast_mutex_lock(&iaxsl[callno1]);
3113                                 iaxs[callno1]->bridgecallno = 0;
3114                                 ast_mutex_unlock(&iaxsl[callno1]);
3115                         }
3116                         return -2;
3117                 }
3118                 if (c0->nativeformats != c1->nativeformats) {
3119                         if (option_verbose > 2) {
3120                                 char buf0[255];
3121                                 char buf1[255];
3122                                 ast_getformatname_multiple(buf0, sizeof(buf0) -1, c0->nativeformats);
3123                                 ast_getformatname_multiple(buf1, sizeof(buf1) -1, c1->nativeformats);
3124                                 ast_verbose(VERBOSE_PREFIX_3 "Operating with different codecs %d[%s] %d[%s] , can't native bridge...\n", c0->nativeformats, buf0, c1->nativeformats, buf1);
3125                         }
3126                         /* Remove from native mode */
3127                         lock_both(callno0, callno1);
3128                         iaxs[callno0]->bridgecallno = 0;
3129                         iaxs[callno1]->bridgecallno = 0;
3130                         unlock_both(callno0, callno1);
3131                         return -2;
3132                 }
3133                 /* check if transfered and if we really want native bridging */
3134                 if (!transferstarted && !ast_test_flag(iaxs[callno0], IAX_NOTRANSFER) && !ast_test_flag(iaxs[callno1], IAX_NOTRANSFER) && 
3135                 !(flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1))) {
3136                         /* Try the transfer */
3137                         if (iax2_start_transfer(callno0, callno1))
3138                                 ast_log(LOG_WARNING, "Unable to start the transfer\n");
3139                         transferstarted = 1;
3140                 }
3141                 if ((iaxs[callno0]->transferring == TRANSFER_RELEASED) && (iaxs[callno1]->transferring == TRANSFER_RELEASED)) {