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