Fix segfault when building peer based on IP
[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 {
2134         /* make sure pvt is valid! */   
2135     struct chan_iax2_pvt *pvt = p;
2136     struct iax_frame *fr;
2137     jb_frame frame;
2138     int ret;
2139     long now;
2140     long next;
2141     struct timeval tv;
2142
2143     ast_mutex_lock(&iaxsl[pvt->callno]);
2144     /*  fprintf(stderr, "get_from_jb called\n"); */
2145     pvt->jbid = -1;
2146
2147     gettimeofday(&tv,NULL);
2148     /* round up a millisecond since ast_sched_runq does; */
2149     /* prevents us from spinning while waiting for our now */
2150     /* to catch up with runq's now */
2151     tv.tv_usec += 1000;
2152
2153     now = ast_tvdiff_ms(tv, pvt->rxcore);
2154
2155     if(now >= (next = jb_next(pvt->jb))) {
2156                 ret = jb_get(pvt->jb,&frame,now,ast_codec_interp_len(pvt->voiceformat));
2157                 switch(ret) {
2158                 case JB_OK:
2159                         /*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); */
2160                         fr = frame.data;
2161                         __do_deliver(fr);
2162                     break;
2163                 case JB_INTERP:
2164                     {
2165                         struct ast_frame af;
2166         
2167                         /*if(next + 20 != jb_next(pvt->jb)) fprintf(stderr, "NEXT %ld is not %ld+20!\n", jb_next(pvt->jb), next); */
2168         
2169                         /* create an interpolation frame */
2170                         /*fprintf(stderr, "Making Interpolation frame\n"); */
2171                         af.frametype = AST_FRAME_VOICE;
2172                         af.subclass = pvt->voiceformat;
2173                         af.datalen  = 0;
2174                         af.samples  = frame.ms * 8;
2175                         af.mallocd  = 0;
2176                         af.src  = "IAX2 JB interpolation";
2177                         af.data  = NULL;
2178                         af.delivery = ast_tvadd(pvt->rxcore, ast_samp2tv(next, 1000));
2179                         af.offset=AST_FRIENDLY_OFFSET;
2180         
2181                         /* queue the frame:  For consistency, we would call __do_deliver here, but __do_deliver wants an iax_frame,
2182                          * which we'd need to malloc, and then it would free it.  That seems like a drag */
2183                         if (iaxs[pvt->callno] && !ast_test_flag(iaxs[pvt->callno], IAX_ALREADYGONE))
2184                                 iax2_queue_frame(pvt->callno, &af);
2185                     }
2186                     break;
2187                 case JB_DROP:
2188                         /*if(next != jb_next(pvt->jb)) fprintf(stderr, "NEXT %ld is not next %ld!\n", jb_next(pvt->jb), next); */
2189                         iax2_frame_free(frame.data);
2190                     break;
2191                 case JB_NOFRAME:
2192                 case JB_EMPTY:
2193                         /* do nothing */
2194                     break;
2195                 default:
2196                         /* shouldn't happen */
2197                     break;
2198                 }
2199     }
2200     update_jbsched(pvt);
2201     ast_mutex_unlock(&iaxsl[pvt->callno]);
2202     return 0;
2203 }
2204 #endif
2205
2206 /* while we transition from the old JB to the new one, we can either make two schedule_delivery functions, or 
2207  * make preprocessor swiss-cheese out of this one.  I'm not sure which is less revolting.. */
2208 static int schedule_delivery(struct iax_frame *fr, int updatehistory, int fromtrunk)
2209 {
2210 #ifdef NEWJB
2211         int type, len;
2212         int ret;
2213 #else
2214         int x;
2215         int ms;
2216         int delay;
2217         unsigned int orig_ts;
2218         int drops[MEMORY_SIZE];
2219         int min, max=0, prevjitterbuffer, maxone=0,y,z, match;
2220
2221         /* Remember current jitterbuffer so we can log any change */
2222         prevjitterbuffer = iaxs[fr->callno]->jitterbuffer;
2223         /* Similarly for the frame timestamp */
2224         orig_ts = fr->ts;
2225 #endif
2226
2227 #if 0
2228         if (option_debug && iaxdebug)
2229                 ast_log(LOG_DEBUG, "schedule_delivery: ts=%d, last=%d, update=%d\n",
2230                                 fr->ts, iaxs[fr->callno]->last, updatehistory);
2231 #endif
2232
2233         /* Attempt to recover wrapped timestamps */
2234         unwrap_timestamp(fr);
2235
2236         if (updatehistory) {
2237 #ifndef NEWJB
2238
2239                 /* Attempt to spot a change of timebase on timestamps coming from the other side
2240                    We detect by noticing a jump in consecutive timestamps that can't reasonably be explained
2241                    by network jitter or reordering.  Sometimes, also, the peer stops sending us frames
2242                    for a while - in this case this code might also resync us.  But that's not a bad thing.
2243                    Be careful of non-voice frames which are timestamped differently (especially ACKS!)
2244                    [that's why we only do this when updatehistory is true]
2245                 */
2246                 x = fr->ts - iaxs[fr->callno]->last;
2247                 if (x > TS_GAP_FOR_JB_RESYNC || x < -TS_GAP_FOR_JB_RESYNC) {
2248                         if (option_debug && iaxdebug)
2249                                 ast_log(LOG_DEBUG, "schedule_delivery: call=%d: TS jumped.  resyncing rxcore (ts=%d, last=%d)\n",
2250                                                         fr->callno, fr->ts, iaxs[fr->callno]->last);
2251                         /* zap rxcore - calc_rxstamp will make a new one based on this frame */
2252                         iaxs[fr->callno]->rxcore = ast_tv(0, 0);
2253                         /* wipe "last" if stamps have jumped backwards */
2254                         if (x<0)
2255                                 iaxs[fr->callno]->last = 0;
2256                         /* should we also empty history? */
2257                 }
2258                 /* ms is a measure of the "lateness" of the frame relative to the "reference"
2259                    frame we received.  (initially the very first, but also see code just above here).
2260                    Understand that "ms" can easily be -ve if lag improves since the reference frame.
2261                    Called by IAX thread, with iaxsl lock held. */
2262                 ms = calc_rxstamp(iaxs[fr->callno], fr->ts) - fr->ts;
2263         
2264                 /* Rotate our history queue of "lateness".  Don't worry about those initial
2265                    zeros because the first entry will always be zero */
2266                 for (x=0;x<MEMORY_SIZE - 1;x++) 
2267                         iaxs[fr->callno]->history[x] = iaxs[fr->callno]->history[x+1];
2268                 /* Add a history entry for this one */
2269                 iaxs[fr->callno]->history[x] = ms;
2270 #endif
2271         }
2272 #ifndef NEWJB
2273         else
2274                 ms = 0;
2275 #endif
2276
2277
2278         /* delivery time is sender's sent timestamp converted back into absolute time according to our clock */
2279         if ( !fromtrunk && !ast_tvzero(iaxs[fr->callno]->rxcore))
2280                 fr->af.delivery = ast_tvadd(iaxs[fr->callno]->rxcore, ast_samp2tv(fr->ts, 1000));
2281         else {
2282 #if 0
2283                 ast_log(LOG_DEBUG, "schedule_delivery: set delivery to 0 as we don't have an rxcore yet, or frame is from trunk.\n");
2284 #endif
2285                 fr->af.delivery = ast_tv(0,0);
2286         }
2287
2288 #ifndef NEWJB
2289         /* Initialize the minimum to reasonable values.  It's too much
2290            work to do the same for the maximum, repeatedly */
2291         min=iaxs[fr->callno]->history[0];
2292         for (z=0;z < iax2_dropcount + 1;z++) {
2293                 /* Start very optimistic ;-) */
2294                 max=-999999999;
2295                 for (x=0;x<MEMORY_SIZE;x++) {
2296                         if (max < iaxs[fr->callno]->history[x]) {
2297                                 /* We have a candidate new maximum value.  Make
2298                                    sure it's not in our drop list */
2299                                 match = 0;
2300                                 for (y=0;!match && (y<z);y++)
2301                                         match |= (drops[y] == x);
2302                                 if (!match) {
2303                                         /* It's not in our list, use it as the new maximum */
2304                                         max = iaxs[fr->callno]->history[x];
2305                                         maxone = x;
2306                                 }
2307                                 
2308                         }
2309                         if (!z) {
2310                                 /* On our first pass, find the minimum too */
2311                                 if (min > iaxs[fr->callno]->history[x])
2312                                         min = iaxs[fr->callno]->history[x];
2313                         }
2314                 }
2315 #if 1
2316                 drops[z] = maxone;
2317 #endif
2318         }
2319 #endif
2320
2321 #ifdef NEWJB
2322         type = JB_TYPE_CONTROL;
2323         len = 0;
2324
2325         if(fr->af.frametype == AST_FRAME_VOICE) {
2326                 type = JB_TYPE_VOICE;
2327                 len = ast_codec_get_samples(&fr->af) / 8;
2328         } else if(fr->af.frametype == AST_FRAME_CNG) {
2329                 type = JB_TYPE_SILENCE;
2330         }
2331
2332         if ( (!ast_test_flag(iaxs[fr->callno], IAX_USEJITTERBUF)) ) {
2333                 __do_deliver(fr);
2334                 return 0;
2335         }
2336
2337         /* if the user hasn't requested we force the use of the jitterbuffer, and we're bridged to
2338          * a channel that can accept jitter, then flush and suspend the jb, and send this frame straight through */
2339         if( (!ast_test_flag(iaxs[fr->callno], IAX_FORCEJITTERBUF)) &&
2340             iaxs[fr->callno]->owner && ast_bridged_channel(iaxs[fr->callno]->owner) &&
2341             (ast_bridged_channel(iaxs[fr->callno]->owner)->tech->properties & AST_CHAN_TP_WANTSJITTER)) {
2342                 jb_frame frame;
2343
2344                 /* deliver any frames in the jb */
2345                 while(jb_getall(iaxs[fr->callno]->jb,&frame) == JB_OK)
2346                         __do_deliver(frame.data);
2347
2348                 jb_reset(iaxs[fr->callno]->jb);
2349
2350                 if (iaxs[fr->callno]->jbid > -1)
2351                         ast_sched_del(sched, iaxs[fr->callno]->jbid);
2352
2353                 iaxs[fr->callno]->jbid = -1;
2354
2355                 /* deliver this frame now */
2356                 __do_deliver(fr);
2357                 return 0;
2358
2359         }
2360
2361
2362         /* insert into jitterbuffer */
2363         /* TODO: Perhaps we could act immediately if it's not droppable and late */
2364         ret = jb_put(iaxs[fr->callno]->jb, fr, type, len, fr->ts,
2365                         calc_rxstamp(iaxs[fr->callno],fr->ts));
2366         if (ret == JB_DROP) {
2367                 iax2_frame_free(fr);
2368         } else if (ret == JB_SCHED) {
2369                 update_jbsched(iaxs[fr->callno]);
2370         }
2371 #else
2372         /* Just for reference, keep the "jitter" value, the difference between the
2373            earliest and the latest. */
2374         if (max >= min)
2375                 iaxs[fr->callno]->jitter = max - min;   
2376         
2377         /* IIR filter for keeping track of historic jitter, but always increase
2378            historic jitter immediately for increase */
2379         
2380         if (iaxs[fr->callno]->jitter > iaxs[fr->callno]->historicjitter )
2381                 iaxs[fr->callno]->historicjitter = iaxs[fr->callno]->jitter;
2382         else
2383                 iaxs[fr->callno]->historicjitter = GAMMA * (double)iaxs[fr->callno]->jitter + (1-GAMMA) * 
2384                         iaxs[fr->callno]->historicjitter;
2385
2386         /* If our jitter buffer is too big (by a significant margin), then we slowly
2387            shrink it to avoid letting the change be perceived */
2388         if (max < iaxs[fr->callno]->jitterbuffer - max_jitter_buffer)
2389                 iaxs[fr->callno]->jitterbuffer -= jittershrinkrate;
2390
2391         /* If our jitter buffer headroom is too small (by a significant margin), then we slowly enlarge it */
2392         /* min_jitter_buffer should be SMALLER than max_jitter_buffer - leaving a "no mans land"
2393            in between - otherwise the jitterbuffer size will hunt up and down causing unnecessary
2394            disruption.  Set maxexcessbuffer to say 150msec, minexcessbuffer to say 50 */
2395         if (max > iaxs[fr->callno]->jitterbuffer - min_jitter_buffer)
2396                 iaxs[fr->callno]->jitterbuffer += jittershrinkrate;
2397
2398         /* If our jitter buffer is smaller than our maximum delay, grow the jitter
2399            buffer immediately to accomodate it (and a little more).  */
2400         if (max > iaxs[fr->callno]->jitterbuffer)
2401                 iaxs[fr->callno]->jitterbuffer = max 
2402                         /* + ((float)iaxs[fr->callno]->jitter) * 0.1 */;
2403
2404         /* update "min", just for RRs and stats */
2405         iaxs[fr->callno]->min = min; 
2406
2407         /* Subtract the lateness from our jitter buffer to know how long to wait
2408            before sending our packet.  */
2409         delay = iaxs[fr->callno]->jitterbuffer - ms;
2410
2411         /* Whatever happens, no frame waits longer than maxjitterbuffer */
2412         if (delay > maxjitterbuffer)
2413                 delay = maxjitterbuffer;
2414         
2415         /* If jitter buffer is disabled then just pretend the frame is "right on time" */
2416         /* If frame came from trunk, also don't do any delay */
2417         if ( (!ast_test_flag(iaxs[fr->callno], IAX_USEJITTERBUF)) || fromtrunk )
2418                 delay = 0;
2419
2420         if (option_debug && iaxdebug) {
2421                 /* Log jitter stats for possible offline analysis */
2422                 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",
2423                                         fr->callno, fr->ts, orig_ts, iaxs[fr->callno]->last,
2424                                         (fr->af.frametype == AST_FRAME_VOICE) ? "VOICE" : "CONTROL",
2425                                         min, max, iaxs[fr->callno]->jitterbuffer,
2426                                         iaxs[fr->callno]->jitterbuffer - prevjitterbuffer,
2427                                         ms, delay,
2428                                         iaxs[fr->callno]->jitter, iaxs[fr->callno]->historicjitter);
2429         }
2430
2431         if (delay < 1) {
2432                 /* Don't deliver it more than 4 ms late */
2433                 if ((delay > -4) || (fr->af.frametype != AST_FRAME_VOICE)) {
2434                         if (option_debug && iaxdebug)
2435                                 ast_log(LOG_DEBUG, "schedule_delivery: Delivering immediately (Calculated delay is %d)\n", delay);
2436                         __do_deliver(fr);
2437                 } else {
2438                         if (option_debug && iaxdebug)
2439                                 ast_log(LOG_DEBUG, "schedule_delivery: Dropping voice packet since %dms delay is too old\n", delay);
2440                         iaxs[fr->callno]->frames_dropped++;
2441                         /* Free our iax frame */
2442                         iax2_frame_free(fr);
2443                 }
2444         } else {
2445                 if (option_debug && iaxdebug)
2446                         ast_log(LOG_DEBUG, "schedule_delivery: Scheduling delivery in %d ms\n", delay);
2447                 fr->retrans = ast_sched_add(sched, delay, do_deliver, fr);
2448         }
2449 #endif
2450         return 0;
2451 }
2452
2453 static int iax2_transmit(struct iax_frame *fr)
2454 {
2455         /* Lock the queue and place this packet at the end */
2456         fr->next = NULL;
2457         fr->prev = NULL;
2458         /* By setting this to 0, the network thread will send it for us, and
2459            queue retransmission if necessary */
2460         fr->sentyet = 0;
2461         ast_mutex_lock(&iaxq.lock);
2462         if (!iaxq.head) {
2463                 /* Empty queue */
2464                 iaxq.head = fr;
2465                 iaxq.tail = fr;
2466         } else {
2467                 /* Double link */
2468                 iaxq.tail->next = fr;
2469                 fr->prev = iaxq.tail;
2470                 iaxq.tail = fr;
2471         }
2472         iaxq.count++;
2473         ast_mutex_unlock(&iaxq.lock);
2474         /* Wake up the network thread */
2475         pthread_kill(netthreadid, SIGURG);
2476         return 0;
2477 }
2478
2479
2480
2481 static int iax2_digit(struct ast_channel *c, char digit)
2482 {
2483         return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_DTMF, digit, 0, NULL, 0, -1);
2484 }
2485
2486 static int iax2_sendtext(struct ast_channel *c, const char *text)
2487 {
2488         
2489         return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_TEXT,
2490                 0, 0, (unsigned char *)text, strlen(text) + 1, -1);
2491 }
2492
2493 static int iax2_sendimage(struct ast_channel *c, struct ast_frame *img)
2494 {
2495         return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_IMAGE, img->subclass, 0, img->data, img->datalen, -1);
2496 }
2497
2498 static int iax2_sendhtml(struct ast_channel *c, int subclass, const char *data, int datalen)
2499 {
2500         return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_HTML, subclass, 0, (unsigned char *)data, datalen, -1);
2501 }
2502
2503 static int iax2_fixup(struct ast_channel *oldchannel, struct ast_channel *newchan)
2504 {
2505         unsigned short callno = PTR_TO_CALLNO(newchan->tech_pvt);
2506         ast_mutex_lock(&iaxsl[callno]);
2507         if (iaxs[callno])
2508                 iaxs[callno]->owner = newchan;
2509         else
2510                 ast_log(LOG_WARNING, "Uh, this isn't a good sign...\n");
2511         ast_mutex_unlock(&iaxsl[callno]);
2512         return 0;
2513 }
2514
2515 static struct iax2_peer *build_peer(const char *name, struct ast_variable *v, int temponly);
2516 static struct iax2_user *build_user(const char *name, struct ast_variable *v, int temponly);
2517
2518 static void destroy_user(struct iax2_user *user);
2519 static int expire_registry(void *data);
2520
2521 static struct iax2_peer *realtime_peer(const char *peername, struct sockaddr_in *sin)
2522 {
2523         struct ast_variable *var;
2524         struct ast_variable *tmp;
2525         struct iax2_peer *peer=NULL;
2526         time_t regseconds, nowtime;
2527         int dynamic=0;
2528
2529         if (peername)
2530                 var = ast_load_realtime("iaxpeers", "name", peername, NULL);
2531         else {
2532                 char iabuf[INET_ADDRSTRLEN];
2533                 char porta[25];
2534                 ast_inet_ntoa(iabuf, sizeof(iabuf), sin->sin_addr);
2535                 sprintf(porta, "%d", ntohs(sin->sin_port));
2536                 var = ast_load_realtime("iaxpeers", "ipaddr", iabuf, "port", porta, NULL);
2537                 if (var) {
2538                         /* We'll need the peer name in order to build the structure! */
2539                         tmp = var;
2540                         while(tmp) {
2541                                 if (!strcasecmp(tmp->name, "name"))
2542                                         peername = tmp->value;
2543                                 tmp = tmp->next;
2544                         }
2545                 }
2546         }
2547         if (!var)
2548                 return NULL;
2549
2550         peer = build_peer(peername, var, ast_test_flag((&globalflags), IAX_RTCACHEFRIENDS) ? 0 : 1);
2551         
2552         if (!peer)
2553                 return NULL;
2554
2555         tmp = var;
2556         while(tmp) {
2557                 /* Make sure it's not a user only... */
2558                 if (!strcasecmp(tmp->name, "type")) {
2559                         if (strcasecmp(tmp->value, "friend") &&
2560                             strcasecmp(tmp->value, "peer")) {
2561                                 /* Whoops, we weren't supposed to exist! */
2562                                 destroy_peer(peer);
2563                                 peer = NULL;
2564                                 break;
2565                         } 
2566                 } else if (!strcasecmp(tmp->name, "regseconds")) {
2567                         if (sscanf(tmp->value, "%li", &regseconds) != 1)
2568                                 regseconds = 0;
2569                 } else if (!strcasecmp(tmp->name, "ipaddr")) {
2570                         inet_aton(tmp->value, &(peer->addr.sin_addr));
2571                 } else if (!strcasecmp(tmp->name, "port")) {
2572                         peer->addr.sin_port = htons(atoi(tmp->value));
2573                 } else if (!strcasecmp(tmp->name, "host")) {
2574                         if (!strcasecmp(tmp->value, "dynamic"))
2575                                 dynamic = 1;
2576                 }
2577                 tmp = tmp->next;
2578         }
2579         if (!peer)
2580                 return NULL;
2581
2582         ast_variables_destroy(var);
2583
2584         if (ast_test_flag((&globalflags), IAX_RTCACHEFRIENDS)) {
2585                 ast_copy_flags(peer, &globalflags, IAX_RTAUTOCLEAR|IAX_RTCACHEFRIENDS);
2586                 if (ast_test_flag(peer, IAX_RTAUTOCLEAR)) {
2587                         if (peer->expire > -1)
2588                                 ast_sched_del(sched, peer->expire);
2589                         peer->expire = ast_sched_add(sched, (global_rtautoclear) * 1000, expire_registry, peer);
2590                 }
2591                 ast_mutex_lock(&peerl.lock);
2592                 peer->next = peerl.peers;
2593                 peerl.peers = peer;
2594                 ast_mutex_unlock(&peerl.lock);
2595                 if (ast_test_flag(peer, IAX_DYNAMIC))
2596                         reg_source_db(peer);
2597         } else {
2598                 ast_set_flag(peer, IAX_TEMPONLY);       
2599         }
2600
2601         if (!ast_test_flag(&globalflags, IAX_RTIGNOREREGEXPIRE) && dynamic) {
2602                 time(&nowtime);
2603                 if ((nowtime - regseconds) > IAX_DEFAULT_REG_EXPIRE) {
2604                         memset(&peer->addr, 0, sizeof(peer->addr));
2605                         if (option_debug)
2606                                 ast_log(LOG_DEBUG, "Bah, we're expired (%ld/%ld/%ld)!\n", nowtime - regseconds, regseconds, nowtime);
2607                 }
2608         }
2609
2610         return peer;
2611 }
2612
2613 static struct iax2_user *realtime_user(const char *username)
2614 {
2615         struct ast_variable *var;
2616         struct ast_variable *tmp;
2617         struct iax2_user *user=NULL;
2618
2619         var = ast_load_realtime("iaxusers", "name", username, NULL);
2620         if (!var)
2621                 return NULL;
2622
2623         tmp = var;
2624         while(tmp) {
2625                 /* Make sure it's not a peer only... */
2626                 if (!strcasecmp(tmp->name, "type")) {
2627                         if (strcasecmp(tmp->value, "friend") &&
2628                             strcasecmp(tmp->value, "user")) {
2629                                 return NULL;
2630                         } 
2631                 }
2632                 tmp = tmp->next;
2633         }
2634
2635         user = build_user(username, var, !ast_test_flag((&globalflags), IAX_RTCACHEFRIENDS));
2636         if (!user)
2637                 return NULL;
2638
2639         ast_variables_destroy(var);
2640
2641         if (ast_test_flag((&globalflags), IAX_RTCACHEFRIENDS)) {
2642                 ast_set_flag(user, IAX_RTCACHEFRIENDS);
2643                 ast_mutex_lock(&userl.lock);
2644                 user->next = userl.users;
2645                 userl.users = user;
2646                 ast_mutex_unlock(&userl.lock);
2647         } else {
2648                 ast_set_flag(user, IAX_TEMPONLY);       
2649         }
2650
2651         return user;
2652 }
2653
2654 static void realtime_update_peer(const char *peername, struct sockaddr_in *sin)
2655 {
2656         char port[10];
2657         char ipaddr[20];
2658         char regseconds[20];
2659         time_t nowtime;
2660         
2661         time(&nowtime);
2662         snprintf(regseconds, sizeof(regseconds), "%ld", nowtime);
2663         ast_inet_ntoa(ipaddr, sizeof(ipaddr), sin->sin_addr);
2664         snprintf(port, sizeof(port), "%d", ntohs(sin->sin_port));
2665         ast_update_realtime("iaxpeers", "name", peername, "ipaddr", ipaddr, "port", port, "regseconds", regseconds, NULL);
2666 }
2667
2668 struct create_addr_info {
2669         int capability;
2670         unsigned int flags;
2671         int maxtime;
2672         int encmethods;
2673         int found;
2674         int sockfd;
2675         char username[80];
2676         char secret[80];
2677         char outkey[80];
2678         char timezone[80];
2679         char prefs[32];
2680         char context[AST_MAX_CONTEXT];
2681         char peercontext[AST_MAX_CONTEXT];
2682 };
2683
2684 static int create_addr(const char *peername, struct sockaddr_in *sin, struct create_addr_info *cai)
2685 {
2686         struct ast_hostent ahp;
2687         struct hostent *hp;
2688         struct iax2_peer *peer;
2689
2690         ast_clear_flag(cai, IAX_SENDANI | IAX_TRUNK);
2691         cai->sockfd = defaultsockfd;
2692         cai->maxtime = 0;
2693         sin->sin_family = AF_INET;
2694
2695         if (!(peer = find_peer(peername, 1))) {
2696                 cai->found = 0;
2697
2698                 hp = ast_gethostbyname(peername, &ahp);
2699                 if (hp) {
2700                         memcpy(&sin->sin_addr, hp->h_addr, sizeof(sin->sin_addr));
2701                         sin->sin_port = htons(IAX_DEFAULT_PORTNO);
2702                         /* use global iax prefs for unknown peer/user */
2703                         ast_codec_pref_convert(&prefs, cai->prefs, sizeof(cai->prefs), 1);
2704                         return 0;
2705                 } else {
2706                         ast_log(LOG_WARNING, "No such host: %s\n", peername);
2707                         return -1;
2708                 }
2709         }
2710
2711         cai->found = 1;
2712         
2713         /* if the peer has no address (current or default), return failure */
2714         if (!(peer->addr.sin_addr.s_addr || peer->defaddr.sin_addr.s_addr)) {
2715                 if (ast_test_flag(peer, IAX_TEMPONLY))
2716                         destroy_peer(peer);
2717                 return -1;
2718         }
2719
2720         /* if the peer is being monitored and is currently unreachable, return failure */
2721         if (peer->maxms && (peer->lastms > peer->maxms)) {
2722                 if (ast_test_flag(peer, IAX_TEMPONLY))
2723                         destroy_peer(peer);
2724                 return -1;
2725         }
2726
2727         ast_copy_flags(cai, peer, IAX_SENDANI | IAX_TRUNK | IAX_NOTRANSFER | IAX_USEJITTERBUF | IAX_FORCEJITTERBUF);
2728         cai->maxtime = peer->maxms;
2729         cai->capability = peer->capability;
2730         cai->encmethods = peer->encmethods;
2731         cai->sockfd = peer->sockfd;
2732         ast_codec_pref_convert(&peer->prefs, cai->prefs, sizeof(cai->prefs), 1);
2733         ast_copy_string(cai->context, peer->context, sizeof(cai->context));
2734         ast_copy_string(cai->peercontext, peer->peercontext, sizeof(cai->peercontext));
2735         ast_copy_string(cai->username, peer->username, sizeof(cai->username));
2736         ast_copy_string(cai->timezone, peer->zonetag, sizeof(cai->timezone));
2737         ast_copy_string(cai->outkey, peer->outkey, sizeof(cai->outkey));
2738         if (ast_strlen_zero(peer->dbsecret)) {
2739                 ast_copy_string(cai->secret, peer->secret, sizeof(cai->secret));
2740         } else {
2741                 char *family;
2742                 char *key = NULL;
2743
2744                 family = ast_strdupa(peer->dbsecret);
2745                 if (family) {
2746                         key = strchr(family, '/');
2747                         if (key)
2748                                 *key++ = '\0';
2749                 }
2750                 if (!family || !key || ast_db_get(family, key, cai->secret, sizeof(cai->secret))) {
2751                         ast_log(LOG_WARNING, "Unable to retrieve database password for family/key '%s'!\n", peer->dbsecret);
2752                         if (ast_test_flag(peer, IAX_TEMPONLY))
2753                                 destroy_peer(peer);
2754                         return -1;
2755                 }
2756         }
2757
2758         if (peer->addr.sin_addr.s_addr) {
2759                 sin->sin_addr = peer->addr.sin_addr;
2760                 sin->sin_port = peer->addr.sin_port;
2761         } else {
2762                 sin->sin_addr = peer->defaddr.sin_addr;
2763                 sin->sin_port = peer->defaddr.sin_port;
2764         }
2765
2766         if (ast_test_flag(peer, IAX_TEMPONLY))
2767                 destroy_peer(peer);
2768
2769         return 0;
2770 }
2771
2772 static int auto_congest(void *nothing)
2773 {
2774         int callno = PTR_TO_CALLNO(nothing);
2775         struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_CONGESTION };
2776         ast_mutex_lock(&iaxsl[callno]);
2777         if (iaxs[callno]) {
2778                 iaxs[callno]->initid = -1;
2779                 iax2_queue_frame(callno, &f);
2780                 ast_log(LOG_NOTICE, "Auto-congesting call due to slow response\n");
2781         }
2782         ast_mutex_unlock(&iaxsl[callno]);
2783         return 0;
2784 }
2785
2786 static unsigned int iax2_datetime(char *tz)
2787 {
2788         time_t t;
2789         struct tm tm;
2790         unsigned int tmp;
2791         time(&t);
2792         localtime_r(&t, &tm);
2793         if (!ast_strlen_zero(tz))
2794                 ast_localtime(&t, &tm, tz);
2795         tmp  = (tm.tm_sec >> 1) & 0x1f;                 /* 5 bits of seconds */
2796         tmp |= (tm.tm_min & 0x3f) << 5;                 /* 6 bits of minutes */
2797         tmp |= (tm.tm_hour & 0x1f) << 11;               /* 5 bits of hours */
2798         tmp |= (tm.tm_mday & 0x1f) << 16;               /* 5 bits of day of month */
2799         tmp |= ((tm.tm_mon + 1) & 0xf) << 21;           /* 4 bits of month */
2800         tmp |= ((tm.tm_year - 100) & 0x7f) << 25;       /* 7 bits of year */
2801         return tmp;
2802 }
2803
2804 struct parsed_dial_string {
2805         char *username;
2806         char *password;
2807         char *key;
2808         char *peer;
2809         char *port;
2810         char *exten;
2811         char *context;
2812         char *options;
2813 };
2814
2815 /*!
2816  * \brief Parses an IAX dial string into its component parts.
2817  * \param data the string to be parsed
2818  * \param pds pointer to a \c struct \c parsed_dial_string to be filled in
2819  * \return nothing
2820  *
2821  * This function parses the string and fills the structure
2822  * with pointers to its component parts. The input string
2823  * will be modified.
2824  *
2825  * \note This function supports both plaintext passwords and RSA
2826  * key names; if the password string is formatted as '[keyname]',
2827  * then the keyname will be placed into the key field, and the
2828  * password field will be set to NULL.
2829  *
2830  * \note The dial string format is:
2831  *       [username[:password]@]peer[:port][/exten[@@context]][/options]
2832  */
2833 static void parse_dial_string(char *data, struct parsed_dial_string *pds)
2834 {
2835         if (!data || ast_strlen_zero(data))
2836                 return;
2837
2838         pds->peer = strsep(&data, "/");
2839         pds->exten = strsep(&data, "/");
2840         pds->options = data;
2841
2842         if (pds->exten) {
2843                 data = pds->exten;
2844                 pds->exten = strsep(&data, "@");
2845                 pds->context = data;
2846         }
2847
2848         if (strchr(pds->peer, '@')) {
2849                 data = pds->peer;
2850                 pds->username = strsep(&data, "@");
2851                 pds->peer = data;
2852         }
2853
2854         if (pds->username) {
2855                 data = pds->username;
2856                 pds->username = strsep(&data, ":");
2857                 pds->password = data;
2858         }
2859
2860         data = pds->peer;
2861         pds->peer = strsep(&data, ":");
2862         pds->port = data;
2863
2864         /* check for a key name wrapped in [] in the secret position, if found,
2865            move it to the key field instead
2866         */
2867         if (pds->password && (pds->password[0] == '[')) {
2868                 pds->key = ast_strip_quoted(pds->password, "[", "]");
2869                 pds->password = NULL;
2870         }
2871 }
2872
2873 static int iax2_call(struct ast_channel *c, char *dest, int timeout)
2874 {
2875         struct sockaddr_in sin;
2876         char *l=NULL, *n=NULL, *tmpstr;
2877         struct iax_ie_data ied;
2878         char *defaultrdest = "s";
2879         unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
2880         struct parsed_dial_string pds;
2881         struct create_addr_info cai;
2882
2883         if ((c->_state != AST_STATE_DOWN) && (c->_state != AST_STATE_RESERVED)) {
2884                 ast_log(LOG_WARNING, "Channel is already in use (%s)?\n", c->name);
2885                 return -1;
2886         }
2887
2888         memset(&cai, 0, sizeof(cai));
2889         cai.encmethods = iax2_encryption;
2890
2891         memset(&pds, 0, sizeof(pds));
2892         tmpstr = ast_strdupa(dest);
2893         parse_dial_string(tmpstr, &pds);
2894
2895         if (!pds.exten)
2896                 pds.exten = defaultrdest;
2897
2898         if (create_addr(pds.peer, &sin, &cai)) {
2899                 ast_log(LOG_WARNING, "No address associated with '%s'\n", pds.peer);
2900                 return -1;
2901         }
2902
2903         if (!pds.username && !ast_strlen_zero(cai.username))
2904                 pds.username = cai.username;
2905         if (!pds.password && !ast_strlen_zero(cai.secret))
2906                 pds.password = cai.secret;
2907         if (!pds.key && !ast_strlen_zero(cai.outkey))
2908                 pds.key = cai.outkey;
2909         if (!pds.context && !ast_strlen_zero(cai.peercontext))
2910                 pds.context = cai.peercontext;
2911
2912         /* Keep track of the context for outgoing calls too */
2913         ast_copy_string(c->context, cai.context, sizeof(c->context));
2914
2915         if (pds.port)
2916                 sin.sin_port = htons(atoi(pds.port));
2917
2918         l = c->cid.cid_num;
2919         n = c->cid.cid_name;
2920
2921         /* Now build request */ 
2922         memset(&ied, 0, sizeof(ied));
2923
2924         /* On new call, first IE MUST be IAX version of caller */
2925         iax_ie_append_short(&ied, IAX_IE_VERSION, IAX_PROTO_VERSION);
2926         iax_ie_append_str(&ied, IAX_IE_CALLED_NUMBER, pds.exten);
2927         if (pds.options && strchr(pds.options, 'a')) {
2928                 /* Request auto answer */
2929                 iax_ie_append(&ied, IAX_IE_AUTOANSWER);
2930         }
2931
2932         iax_ie_append_str(&ied, IAX_IE_CODEC_PREFS, cai.prefs);
2933
2934         if (l) {
2935                 iax_ie_append_str(&ied, IAX_IE_CALLING_NUMBER, l);
2936                 iax_ie_append_byte(&ied, IAX_IE_CALLINGPRES, c->cid.cid_pres);
2937         } else {
2938                 if (n)
2939                         iax_ie_append_byte(&ied, IAX_IE_CALLINGPRES, c->cid.cid_pres);
2940                 else
2941                         iax_ie_append_byte(&ied, IAX_IE_CALLINGPRES, AST_PRES_NUMBER_NOT_AVAILABLE);
2942         }
2943
2944         iax_ie_append_byte(&ied, IAX_IE_CALLINGTON, c->cid.cid_ton);
2945         iax_ie_append_short(&ied, IAX_IE_CALLINGTNS, c->cid.cid_tns);
2946
2947         if (n)
2948                 iax_ie_append_str(&ied, IAX_IE_CALLING_NAME, n);
2949         if (ast_test_flag(iaxs[callno], IAX_SENDANI) && c->cid.cid_ani)
2950                 iax_ie_append_str(&ied, IAX_IE_CALLING_ANI, c->cid.cid_ani);
2951
2952         if (c->language && !ast_strlen_zero(c->language))
2953                 iax_ie_append_str(&ied, IAX_IE_LANGUAGE, c->language);
2954         if (c->cid.cid_dnid && !ast_strlen_zero(c->cid.cid_dnid))
2955                 iax_ie_append_str(&ied, IAX_IE_DNID, c->cid.cid_dnid);
2956
2957         if (pds.context)
2958                 iax_ie_append_str(&ied, IAX_IE_CALLED_CONTEXT, pds.context);
2959
2960         if (pds.username)
2961                 iax_ie_append_str(&ied, IAX_IE_USERNAME, pds.username);
2962
2963         if (cai.encmethods)
2964                 iax_ie_append_short(&ied, IAX_IE_ENCRYPTION, cai.encmethods);
2965
2966         ast_mutex_lock(&iaxsl[callno]);
2967
2968         if (!ast_strlen_zero(c->context))
2969                 ast_copy_string(iaxs[callno]->context, c->context, sizeof(iaxs[callno]->context));
2970
2971         if (pds.username)
2972                 ast_copy_string(iaxs[callno]->username, pds.username, sizeof(iaxs[callno]->username));
2973
2974         iaxs[callno]->encmethods = cai.encmethods;
2975
2976         if (pds.key)
2977                 ast_copy_string(iaxs[callno]->outkey, pds.key, sizeof(iaxs[callno]->outkey));
2978         if (pds.password)
2979                 ast_copy_string(iaxs[callno]->secret, pds.password, sizeof(iaxs[callno]->secret));
2980
2981         iax_ie_append_int(&ied, IAX_IE_FORMAT, c->nativeformats);
2982         iax_ie_append_int(&ied, IAX_IE_CAPABILITY, iaxs[callno]->capability);
2983         iax_ie_append_short(&ied, IAX_IE_ADSICPE, c->adsicpe);
2984         iax_ie_append_int(&ied, IAX_IE_DATETIME, iax2_datetime(cai.timezone));
2985
2986         if (iaxs[callno]->maxtime) {
2987                 /* Initialize pingtime and auto-congest time */
2988                 iaxs[callno]->pingtime = iaxs[callno]->maxtime / 2;
2989                 iaxs[callno]->initid = ast_sched_add(sched, iaxs[callno]->maxtime * 2, auto_congest, CALLNO_TO_PTR(callno));
2990         } else if (autokill) {
2991                 iaxs[callno]->pingtime = autokill / 2;
2992                 iaxs[callno]->initid = ast_sched_add(sched, autokill * 2, auto_congest, CALLNO_TO_PTR(callno));
2993         }
2994
2995         /* Transmit the string in a "NEW" request */
2996         send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_NEW, 0, ied.buf, ied.pos, -1);
2997
2998         ast_mutex_unlock(&iaxsl[callno]);
2999         ast_setstate(c, AST_STATE_RINGING);
3000         
3001         return 0;
3002 }
3003
3004 static int iax2_hangup(struct ast_channel *c) 
3005 {
3006         unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
3007         int alreadygone;
3008         struct iax_ie_data ied;
3009         memset(&ied, 0, sizeof(ied));
3010         ast_mutex_lock(&iaxsl[callno]);
3011         if (callno && iaxs[callno]) {
3012                 ast_log(LOG_DEBUG, "We're hanging up %s now...\n", c->name);
3013                 alreadygone = ast_test_flag(iaxs[callno], IAX_ALREADYGONE);
3014                 /* Send the hangup unless we have had a transmission error or are already gone */
3015                 iax_ie_append_byte(&ied, IAX_IE_CAUSECODE, (unsigned char)c->hangupcause);
3016                 if (!iaxs[callno]->error && !alreadygone) 
3017                         send_command_final(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_HANGUP, 0, ied.buf, ied.pos, -1);
3018                 /* Explicitly predestroy it */
3019                 iax2_predestroy_nolock(callno);
3020                 /* If we were already gone to begin with, destroy us now */
3021                 if (alreadygone) {
3022                         ast_log(LOG_DEBUG, "Really destroying %s now...\n", c->name);
3023                         iax2_destroy_nolock(callno);
3024                 }
3025         }
3026         ast_mutex_unlock(&iaxsl[callno]);
3027         if (option_verbose > 2) 
3028                 ast_verbose(VERBOSE_PREFIX_3 "Hungup '%s'\n", c->name);
3029         return 0;
3030 }
3031
3032 static int iax2_setoption(struct ast_channel *c, int option, void *data, int datalen)
3033 {
3034         struct ast_option_header *h;
3035         int res;
3036
3037         switch (option) {
3038         case AST_OPTION_TXGAIN:
3039         case AST_OPTION_RXGAIN:
3040                 /* these two cannot be sent, because they require a result */
3041                 errno = ENOSYS;
3042                 return -1;
3043         default:
3044                 h = malloc(datalen + sizeof(*h));
3045                 if (h) {
3046                         h->flag = AST_OPTION_FLAG_REQUEST;
3047                         h->option = htons(option);
3048                         memcpy(h->data, data, datalen);
3049                         res = send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_CONTROL,
3050                                                   AST_CONTROL_OPTION, 0, (unsigned char *) h,
3051                                                   datalen + sizeof(*h), -1);
3052                         free(h);
3053                         return res;
3054                 } else {
3055                         ast_log(LOG_WARNING, "Out of memory\n");
3056                         return -1;
3057                 }
3058         }
3059 }
3060
3061 static struct ast_frame *iax2_read(struct ast_channel *c) 
3062 {
3063         static struct ast_frame f = { AST_FRAME_NULL, };
3064         ast_log(LOG_NOTICE, "I should never be called!\n");
3065         return &f;
3066 }
3067
3068 static int iax2_start_transfer(unsigned short callno0, unsigned short callno1)
3069 {
3070         int res;
3071         struct iax_ie_data ied0;
3072         struct iax_ie_data ied1;
3073         unsigned int transferid = rand();
3074         memset(&ied0, 0, sizeof(ied0));
3075         iax_ie_append_addr(&ied0, IAX_IE_APPARENT_ADDR, &iaxs[callno1]->addr);
3076         iax_ie_append_short(&ied0, IAX_IE_CALLNO, iaxs[callno1]->peercallno);
3077         iax_ie_append_int(&ied0, IAX_IE_TRANSFERID, transferid);
3078
3079         memset(&ied1, 0, sizeof(ied1));
3080         iax_ie_append_addr(&ied1, IAX_IE_APPARENT_ADDR, &iaxs[callno0]->addr);
3081         iax_ie_append_short(&ied1, IAX_IE_CALLNO, iaxs[callno0]->peercallno);
3082         iax_ie_append_int(&ied1, IAX_IE_TRANSFERID, transferid);
3083         
3084         res = send_command(iaxs[callno0], AST_FRAME_IAX, IAX_COMMAND_TXREQ, 0, ied0.buf, ied0.pos, -1);
3085         if (res)
3086                 return -1;
3087         res = send_command(iaxs[callno1], AST_FRAME_IAX, IAX_COMMAND_TXREQ, 0, ied1.buf, ied1.pos, -1);
3088         if (res)
3089                 return -1;
3090         iaxs[callno0]->transferring = TRANSFER_BEGIN;
3091         iaxs[callno1]->transferring = TRANSFER_BEGIN;
3092         return 0;
3093 }
3094
3095 static void lock_both(unsigned short callno0, unsigned short callno1)
3096 {
3097         ast_mutex_lock(&iaxsl[callno0]);
3098         while (ast_mutex_trylock(&iaxsl[callno1])) {
3099                 ast_mutex_unlock(&iaxsl[callno0]);
3100                 usleep(10);
3101                 ast_mutex_lock(&iaxsl[callno0]);
3102         }
3103 }
3104
3105 static void unlock_both(unsigned short callno0, unsigned short callno1)
3106 {
3107         ast_mutex_unlock(&iaxsl[callno1]);
3108         ast_mutex_unlock(&iaxsl[callno0]);
3109 }
3110
3111 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)
3112 {
3113         struct ast_channel *cs[3];
3114         struct ast_channel *who;
3115         int to = -1;
3116         int res = -1;
3117         int transferstarted=0;
3118         struct ast_frame *f;
3119         unsigned short callno0 = PTR_TO_CALLNO(c0->tech_pvt);
3120         unsigned short callno1 = PTR_TO_CALLNO(c1->tech_pvt);
3121         struct timeval waittimer = {0, 0}, tv;
3122
3123         lock_both(callno0, callno1);
3124         /* Put them in native bridge mode */
3125         if (!flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1)) {
3126                 iaxs[callno0]->bridgecallno = callno1;
3127                 iaxs[callno1]->bridgecallno = callno0;
3128         }
3129         unlock_both(callno0, callno1);
3130
3131         /* If not, try to bridge until we can execute a transfer, if we can */
3132         cs[0] = c0;
3133         cs[1] = c1;
3134         for (/* ever */;;) {
3135                 /* Check in case we got masqueraded into */
3136                 if ((c0->type != channeltype) || (c1->type != channeltype)) {
3137                         if (option_verbose > 2)
3138                                 ast_verbose(VERBOSE_PREFIX_3 "Can't masquerade, we're different...\n");
3139      &nbs