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