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