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