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