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