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