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