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