Constify a bunch of the usage strings for CLI commands.
[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 transimission 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         int notsilenttx;
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 transfering 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, 1024, 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, 1024, 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, 1024, fmt, args);
768         va_end(args);
769
770         ast_verbose(buf);
771 }
772
773 /* XXX We probably should use a mutex when working with this XXX */
774 static struct chan_iax2_pvt *iaxs[IAX_MAX_CALLS];
775 static ast_mutex_t iaxsl[IAX_MAX_CALLS];
776 static struct timeval lastused[IAX_MAX_CALLS];
777
778 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);
779 static int expire_registry(void *data);
780 static int iax2_answer(struct ast_channel *c);
781 static int iax2_call(struct ast_channel *c, char *dest, int timeout);
782 static int iax2_devicestate(void *data);
783 static int iax2_digit_begin(struct ast_channel *c, char digit);
784 static int iax2_digit_end(struct ast_channel *c, char digit);
785 static int iax2_do_register(struct iax2_registry *reg);
786 static int iax2_fixup(struct ast_channel *oldchannel, struct ast_channel *newchan);
787 static int iax2_hangup(struct ast_channel *c);
788 static int iax2_indicate(struct ast_channel *c, int condition, const void *data, size_t datalen);
789 static int iax2_poke_peer(struct iax2_peer *peer, int heldcall);
790 static int iax2_provision(struct sockaddr_in *end, int sockfd, char *dest, const char *template, int force);
791 static int iax2_send(struct chan_iax2_pvt *pvt, struct ast_frame *f, unsigned int ts, int seqno, int now, int transfer, int final);
792 static int iax2_sendhtml(struct ast_channel *c, int subclass, const char *data, int datalen);
793 static int iax2_sendimage(struct ast_channel *c, struct ast_frame *img);
794 static int iax2_sendtext(struct ast_channel *c, const char *text);
795 static int iax2_setoption(struct ast_channel *c, int option, void *data, int datalen);
796 static int iax2_transfer(struct ast_channel *c, const char *dest);
797 static int iax2_write(struct ast_channel *c, struct ast_frame *f);
798 static int send_trunk(struct iax2_trunk_peer *tpeer, struct timeval *now);
799 static int send_command(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
800 static int send_command_final(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
801 static int send_command_immediate(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
802 static int send_command_locked(unsigned short callno, char, int, unsigned int, const unsigned char *, int, int);
803 static int send_command_transfer(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int);
804 static struct ast_channel *iax2_request(const char *type, int format, void *data, int *cause);
805 static struct ast_frame *iax2_read(struct ast_channel *c);
806 static struct iax2_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly);
807 static struct iax2_user *build_user(const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly);
808 static void realtime_update_peer(const char *peername, struct sockaddr_in *sin, time_t regtime);
809 static void destroy_user(struct iax2_user *user);
810 static void prune_peers(void);
811
812 static const struct ast_channel_tech iax2_tech = {
813         .type = "IAX2",
814         .description = tdesc,
815         .capabilities = IAX_CAPABILITY_FULLBANDWIDTH,
816         .properties = AST_CHAN_TP_WANTSJITTER,
817         .requester = iax2_request,
818         .devicestate = iax2_devicestate,
819         .send_digit_begin = iax2_digit_begin,
820         .send_digit_end = iax2_digit_end,
821         .send_text = iax2_sendtext,
822         .send_image = iax2_sendimage,
823         .send_html = iax2_sendhtml,
824         .call = iax2_call,
825         .hangup = iax2_hangup,
826         .answer = iax2_answer,
827         .read = iax2_read,
828         .write = iax2_write,
829         .write_video = iax2_write,
830         .indicate = iax2_indicate,
831         .setoption = iax2_setoption,
832         .bridge = iax2_bridge,
833         .transfer = iax2_transfer,
834         .fixup = iax2_fixup,
835 };
836
837 static struct iax2_thread *find_idle_thread(void)
838 {
839         struct iax2_thread *thread = NULL;
840
841         /* Pop the head of the list off */
842         AST_LIST_LOCK(&idle_list);
843         thread = AST_LIST_REMOVE_HEAD(&idle_list, list);
844         AST_LIST_UNLOCK(&idle_list);
845
846         /* If no idle thread is available from the regular list, try dynamic */
847         if (thread == NULL) {
848                 AST_LIST_LOCK(&dynamic_list);
849                 thread = AST_LIST_FIRST(&dynamic_list);
850                 if (thread != NULL) {
851                         AST_LIST_REMOVE(&dynamic_list, thread, list);
852                 }
853                 /* Make sure we absolutely have a thread... if not, try to make one if allowed */
854                 if (thread == NULL && iaxmaxthreadcount > iaxdynamicthreadcount) {
855                         /* We need to MAKE a thread! */
856                         thread = ast_calloc(1, sizeof(*thread));
857                         if (thread != NULL) {
858                                 thread->threadnum = iaxdynamicthreadcount;
859                                 thread->type = IAX_TYPE_DYNAMIC;
860                                 ast_mutex_init(&thread->lock);
861                                 ast_cond_init(&thread->cond, NULL);
862                                 if (ast_pthread_create(&thread->threadid, NULL, iax2_process_thread, thread)) {
863                                         free(thread);
864                                         thread = NULL;
865                                 } else {
866                                         /* All went well and the thread is up, so increment our count */
867                                         iaxdynamicthreadcount++;
868                                 }
869                         }
870                 }
871                 AST_LIST_UNLOCK(&dynamic_list);
872         }
873
874         return thread;
875 }
876
877 #ifdef SCHED_MULTITHREADED
878 static int __schedule_action(void (*func)(void *data), void *data, const char *funcname)
879 {
880         struct iax2_thread *thread = NULL;
881         static time_t lasterror;
882         static time_t t;
883
884         thread = find_idle_thread();
885
886         if (thread != NULL) {
887                 thread->schedfunc = func;
888                 thread->scheddata = data;
889                 thread->iostate = IAX_IOSTATE_SCHEDREADY;
890 #ifdef DEBUG_SCHED_MULTITHREAD
891                 ast_copy_string(thread->curfunc, funcname, sizeof(thread->curfunc));
892 #endif
893                 signal_condition(&thread->lock, &thread->cond);
894                 return 0;
895         }
896         time(&t);
897         if (t != lasterror) 
898                 ast_log(LOG_NOTICE, "Out of idle IAX2 threads for scheduling!\n");
899         lasterror = t;
900
901         return -1;
902 }
903 #define schedule_action(func, data) __schedule_action(func, data, __PRETTY_FUNCTION__)
904 #endif
905
906 static void __send_ping(void *data)
907 {
908         int callno = (long)data;
909         send_command_locked(callno, AST_FRAME_IAX, IAX_COMMAND_PING, 0, NULL, 0, -1);
910 }
911
912 static int send_ping(void *data)
913 {
914         int callno = (long)data;
915         if (iaxs[callno]) {
916 #ifdef SCHED_MULTITHREADED
917                 if (schedule_action(__send_ping, data))
918 #endif          
919                         __send_ping(data);
920                 return 1;
921         } else
922                 return 0;
923         return 0;
924 }
925
926 static int get_encrypt_methods(const char *s)
927 {
928         int e;
929         if (!strcasecmp(s, "aes128"))
930                 e = IAX_ENCRYPT_AES128;
931         else if (ast_true(s))
932                 e = IAX_ENCRYPT_AES128;
933         else
934                 e = 0;
935         return e;
936 }
937
938 static void __send_lagrq(void *data)
939 {
940         int callno = (long)data;
941         /* Ping only if it's real not if it's bridged */
942         send_command_locked(callno, AST_FRAME_IAX, IAX_COMMAND_LAGRQ, 0, NULL, 0, -1);
943 }
944
945 static int send_lagrq(void *data)
946 {
947         int callno = (long)data;
948         if (iaxs[callno]) {
949 #ifdef SCHED_MULTITHREADED
950                 if (schedule_action(__send_lagrq, data))
951 #endif          
952                         __send_lagrq(data);
953                 return 1;
954         } else
955                 return 0;
956         return 0;
957 }
958
959 static unsigned char compress_subclass(int subclass)
960 {
961         int x;
962         int power=-1;
963         /* If it's 128 or smaller, just return it */
964         if (subclass < IAX_FLAG_SC_LOG)
965                 return subclass;
966         /* Otherwise find its power */
967         for (x = 0; x < IAX_MAX_SHIFT; x++) {
968                 if (subclass & (1 << x)) {
969                         if (power > -1) {
970                                 ast_log(LOG_WARNING, "Can't compress subclass %d\n", subclass);
971                                 return 0;
972                         } else
973                                 power = x;
974                 }
975         }
976         return power | IAX_FLAG_SC_LOG;
977 }
978
979 static int uncompress_subclass(unsigned char csub)
980 {
981         /* If the SC_LOG flag is set, return 2^csub otherwise csub */
982         if (csub & IAX_FLAG_SC_LOG) {
983                 /* special case for 'compressed' -1 */
984                 if (csub == 0xff)
985                         return -1;
986                 else
987                         return 1 << (csub & ~IAX_FLAG_SC_LOG & IAX_MAX_SHIFT);
988         }
989         else
990                 return csub;
991 }
992
993 static struct iax2_peer *find_peer(const char *name, int realtime) 
994 {
995         struct iax2_peer *peer = NULL;
996
997         /* Grab peer from linked list */
998         AST_LIST_LOCK(&peers);
999         AST_LIST_TRAVERSE(&peers, peer, entry) {
1000                 if (!strcasecmp(peer->name, name)) {
1001                         break;
1002                 }
1003         }
1004         AST_LIST_UNLOCK(&peers);
1005
1006         /* Now go for realtime if applicable */
1007         if(!peer && realtime)
1008                 peer = realtime_peer(name, NULL);
1009         return peer;
1010 }
1011
1012 static int iax2_getpeername(struct sockaddr_in sin, char *host, int len, int lockpeer)
1013 {
1014         struct iax2_peer *peer = NULL;
1015         int res = 0;
1016
1017         if (lockpeer)
1018                 AST_LIST_LOCK(&peers);
1019         AST_LIST_TRAVERSE(&peers, peer, entry) {
1020                 if ((peer->addr.sin_addr.s_addr == sin.sin_addr.s_addr) &&
1021                     (peer->addr.sin_port == sin.sin_port)) {
1022                         ast_copy_string(host, peer->name, len);
1023                         res = 1;
1024                         break;
1025                 }
1026         }
1027         if (lockpeer)
1028                 AST_LIST_UNLOCK(&peers);
1029         if (!peer) {
1030                 peer = realtime_peer(NULL, &sin);
1031                 if (peer) {
1032                         ast_copy_string(host, peer->name, len);
1033                         if (ast_test_flag(peer, IAX_TEMPONLY))
1034                                 destroy_peer(peer);
1035                         res = 1;
1036                 }
1037         }
1038
1039         return res;
1040 }
1041
1042 static struct chan_iax2_pvt *new_iax(struct sockaddr_in *sin, int lockpeer, const char *host)
1043 {
1044         struct chan_iax2_pvt *tmp;
1045         jb_conf jbconf;
1046
1047         if (!(tmp = ast_calloc(1, sizeof(*tmp))))
1048                 return NULL;
1049
1050         if (ast_string_field_init(tmp, 32)) {
1051                 free(tmp);
1052                 tmp = NULL;
1053                 return NULL;
1054         }
1055                 
1056         tmp->prefs = prefs;
1057         tmp->callno = 0;
1058         tmp->peercallno = 0;
1059         tmp->transfercallno = 0;
1060         tmp->bridgecallno = 0;
1061         tmp->pingid = -1;
1062         tmp->lagid = -1;
1063         tmp->autoid = -1;
1064         tmp->authid = -1;
1065         tmp->initid = -1;
1066
1067         ast_string_field_set(tmp,exten, "s");
1068         ast_string_field_set(tmp,host, host);
1069
1070         tmp->jb = jb_new();
1071         tmp->jbid = -1;
1072         jbconf.max_jitterbuf = maxjitterbuffer;
1073         jbconf.resync_threshold = resyncthreshold;
1074         jbconf.max_contig_interp = maxjitterinterps;
1075         jb_setconf(tmp->jb,&jbconf);
1076
1077         AST_LIST_HEAD_INIT_NOLOCK(&tmp->dpentries);
1078
1079         return tmp;
1080 }
1081
1082 static struct iax_frame *iaxfrdup2(struct iax_frame *fr)
1083 {
1084         struct iax_frame *new = iax_frame_new(DIRECTION_INGRESS, fr->af.datalen);
1085         if (new) {
1086                 size_t mallocd_datalen = new->mallocd_datalen;
1087                 memcpy(new, fr, sizeof(*new));
1088                 iax_frame_wrap(new, &fr->af);
1089                 new->mallocd_datalen = mallocd_datalen;
1090                 new->data = NULL;
1091                 new->datalen = 0;
1092                 new->direction = DIRECTION_INGRESS;
1093                 new->retrans = -1;
1094         }
1095         return new;
1096 }
1097
1098 #define NEW_PREVENT     0
1099 #define NEW_ALLOW       1
1100 #define NEW_FORCE       2
1101
1102 static int match(struct sockaddr_in *sin, unsigned short callno, unsigned short dcallno, struct chan_iax2_pvt *cur)
1103 {
1104         if ((cur->addr.sin_addr.s_addr == sin->sin_addr.s_addr) &&
1105                 (cur->addr.sin_port == sin->sin_port)) {
1106                 /* This is the main host */
1107                 if ((cur->peercallno == callno) ||
1108                         ((dcallno == cur->callno) && !cur->peercallno)) {
1109                         /* That's us.  Be sure we keep track of the peer call number */
1110                         return 1;
1111                 }
1112         }
1113         if ((cur->transfer.sin_addr.s_addr == sin->sin_addr.s_addr) &&
1114             (cur->transfer.sin_port == sin->sin_port) && (cur->transferring)) {
1115                 /* We're transferring */
1116                 if (dcallno == cur->callno)
1117                         return 1;
1118         }
1119         return 0;
1120 }
1121
1122 static void update_max_trunk(void)
1123 {
1124         int max = TRUNK_CALL_START;
1125         int x;
1126         /* XXX Prolly don't need locks here XXX */
1127         for (x=TRUNK_CALL_START;x<IAX_MAX_CALLS - 1; x++) {
1128                 if (iaxs[x])
1129                         max = x + 1;
1130         }
1131         maxtrunkcall = max;
1132         if (option_debug && iaxdebug)
1133                 ast_log(LOG_DEBUG, "New max trunk callno is %d\n", max);
1134 }
1135
1136 static void update_max_nontrunk(void)
1137 {
1138         int max = 1;
1139         int x;
1140         /* XXX Prolly don't need locks here XXX */
1141         for (x=1;x<TRUNK_CALL_START - 1; x++) {
1142                 if (iaxs[x])
1143                         max = x + 1;
1144         }
1145         maxnontrunkcall = max;
1146         if (option_debug && iaxdebug)
1147                 ast_log(LOG_DEBUG, "New max nontrunk callno is %d\n", max);
1148 }
1149
1150 static int make_trunk(unsigned short callno, int locked)
1151 {
1152         int x;
1153         int res= 0;
1154         struct timeval now;
1155         if (iaxs[callno]->oseqno) {
1156                 ast_log(LOG_WARNING, "Can't make trunk once a call has started!\n");
1157                 return -1;
1158         }
1159         if (callno & TRUNK_CALL_START) {
1160                 ast_log(LOG_WARNING, "Call %d is already a trunk\n", callno);
1161                 return -1;
1162         }
1163         gettimeofday(&now, NULL);
1164         for (x=TRUNK_CALL_START;x<IAX_MAX_CALLS - 1; x++) {
1165                 ast_mutex_lock(&iaxsl[x]);
1166                 if (!iaxs[x] && ((now.tv_sec - lastused[x].tv_sec) > MIN_REUSE_TIME)) {
1167                         iaxs[x] = iaxs[callno];
1168                         iaxs[x]->callno = x;
1169                         iaxs[callno] = NULL;
1170                         /* Update the two timers that should have been started */
1171                         if (iaxs[x]->pingid > -1)
1172                                 ast_sched_del(sched, iaxs[x]->pingid);
1173                         if (iaxs[x]->lagid > -1)
1174                                 ast_sched_del(sched, iaxs[x]->lagid);
1175                         iaxs[x]->pingid = ast_sched_add(sched, ping_time * 1000, send_ping, (void *)(long)x);
1176                         iaxs[x]->lagid = ast_sched_add(sched, lagrq_time * 1000, send_lagrq, (void *)(long)x);
1177                         if (locked)
1178                                 ast_mutex_unlock(&iaxsl[callno]);
1179                         res = x;
1180                         if (!locked)
1181                                 ast_mutex_unlock(&iaxsl[x]);
1182                         break;
1183                 }
1184                 ast_mutex_unlock(&iaxsl[x]);
1185         }
1186         if (x >= IAX_MAX_CALLS - 1) {
1187                 ast_log(LOG_WARNING, "Unable to trunk call: Insufficient space\n");
1188                 return -1;
1189         }
1190         if (option_debug)
1191                 ast_log(LOG_DEBUG, "Made call %d into trunk call %d\n", callno, x);
1192         /* We move this call from a non-trunked to a trunked call */
1193         update_max_trunk();
1194         update_max_nontrunk();
1195         return res;
1196 }
1197
1198 /*!
1199  * \todo XXX Note that this function contains a very expensive operation that
1200  * happens for *every* incoming media frame.  It iterates through every
1201  * possible call number, locking and unlocking each one, to try to match the
1202  * incoming frame to an active call.  Call numbers can be up to 2^15, 32768.
1203  * So, for an call with a local call number of 20000, every incoming audio
1204  * frame would require 20000 mutex lock and unlock operations.  Ouch.
1205  *
1206  * It's a shame that IAX2 media frames carry the source call number instead of
1207  * the destination call number.  If they did, this lookup wouldn't be needed.
1208  * However, it's too late to change that now.  Instead, we need to come up with
1209  * a better way of indexing active calls so that these frequent lookups are not
1210  * so expensive.
1211  */
1212 static int find_callno(unsigned short callno, unsigned short dcallno, struct sockaddr_in *sin, int new, int lockpeer, int sockfd)
1213 {
1214         int res = 0;
1215         int x;
1216         struct timeval now;
1217         char host[80];
1218         if (new <= NEW_ALLOW) {
1219                 /* Look for an existing connection first */
1220                 for (x=1;(res < 1) && (x<maxnontrunkcall);x++) {
1221                         ast_mutex_lock(&iaxsl[x]);
1222                         if (iaxs[x]) {
1223                                 /* Look for an exact match */
1224                                 if (match(sin, callno, dcallno, iaxs[x])) {
1225                                         res = x;
1226                                 }
1227                         }
1228                         ast_mutex_unlock(&iaxsl[x]);
1229                 }
1230                 for (x=TRUNK_CALL_START;(res < 1) && (x<maxtrunkcall);x++) {
1231                         ast_mutex_lock(&iaxsl[x]);
1232                         if (iaxs[x]) {
1233                                 /* Look for an exact match */
1234                                 if (match(sin, callno, dcallno, iaxs[x])) {
1235                                         res = x;
1236                                 }
1237                         }
1238                         ast_mutex_unlock(&iaxsl[x]);
1239                 }
1240         }
1241         if ((res < 1) && (new >= NEW_ALLOW)) {
1242                 if (!iax2_getpeername(*sin, host, sizeof(host), lockpeer))
1243                         snprintf(host, sizeof(host), "%s:%d", ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
1244                 gettimeofday(&now, NULL);
1245                 for (x=1;x<TRUNK_CALL_START;x++) {
1246                         /* Find first unused call number that hasn't been used in a while */
1247                         ast_mutex_lock(&iaxsl[x]);
1248                         if (!iaxs[x] && ((now.tv_sec - lastused[x].tv_sec) > MIN_REUSE_TIME)) break;
1249                         ast_mutex_unlock(&iaxsl[x]);
1250                 }
1251                 /* We've still got lock held if we found a spot */
1252                 if (x >= TRUNK_CALL_START) {
1253                         ast_log(LOG_WARNING, "No more space\n");
1254                         return 0;
1255                 }
1256                 iaxs[x] = new_iax(sin, lockpeer, host);
1257                 update_max_nontrunk();
1258                 if (iaxs[x]) {
1259                         if (option_debug && iaxdebug)
1260                                 ast_log(LOG_DEBUG, "Creating new call structure %d\n", x);
1261                         iaxs[x]->sockfd = sockfd;
1262                         iaxs[x]->addr.sin_port = sin->sin_port;
1263                         iaxs[x]->addr.sin_family = sin->sin_family;
1264                         iaxs[x]->addr.sin_addr.s_addr = sin->sin_addr.s_addr;
1265                         iaxs[x]->peercallno = callno;
1266                         iaxs[x]->callno = x;
1267                         iaxs[x]->pingtime = DEFAULT_RETRY_TIME;
1268                         iaxs[x]->expiry = min_reg_expire;
1269                         iaxs[x]->pingid = ast_sched_add(sched, ping_time * 1000, send_ping, (void *)(long)x);
1270                         iaxs[x]->lagid = ast_sched_add(sched, lagrq_time * 1000, send_lagrq, (void *)(long)x);
1271                         iaxs[x]->amaflags = amaflags;
1272                         ast_copy_flags(iaxs[x], (&globalflags), IAX_NOTRANSFER | IAX_TRANSFERMEDIA | IAX_USEJITTERBUF | IAX_FORCEJITTERBUF);
1273                         
1274                         ast_string_field_set(iaxs[x], accountcode, accountcode);
1275                         ast_string_field_set(iaxs[x], mohinterpret, mohinterpret);
1276                         ast_string_field_set(iaxs[x], mohsuggest, mohsuggest);
1277                 } else {
1278                         ast_log(LOG_WARNING, "Out of resources\n");
1279                         ast_mutex_unlock(&iaxsl[x]);
1280                         return 0;
1281                 }
1282                 ast_mutex_unlock(&iaxsl[x]);
1283                 res = x;
1284         }
1285         return res;
1286 }
1287
1288 static void iax2_frame_free(struct iax_frame *fr)
1289 {
1290         if (fr->retrans > -1)
1291                 ast_sched_del(sched, fr->retrans);
1292         iax_frame_free(fr);
1293 }
1294
1295 static int iax2_queue_frame(int callno, struct ast_frame *f)
1296 {
1297         /* Assumes lock for callno is already held... */
1298         for (;;) {
1299                 if (iaxs[callno] && iaxs[callno]->owner) {
1300                         if (ast_mutex_trylock(&iaxs[callno]->owner->lock)) {
1301                                 /* Avoid deadlock by pausing and trying again */
1302                                 ast_mutex_unlock(&iaxsl[callno]);
1303                                 usleep(1);
1304                                 ast_mutex_lock(&iaxsl[callno]);
1305                         } else {
1306                                 ast_queue_frame(iaxs[callno]->owner, f);
1307                                 ast_mutex_unlock(&iaxs[callno]->owner->lock);
1308                                 break;
1309                         }
1310                 } else
1311                         break;
1312         }
1313         return 0;
1314 }
1315
1316 static void destroy_firmware(struct iax_firmware *cur)
1317 {
1318         /* Close firmware */
1319         if (cur->fwh) {
1320                 munmap(cur->fwh, ntohl(cur->fwh->datalen) + sizeof(*(cur->fwh)));
1321         }
1322         close(cur->fd);
1323         free(cur);
1324 }
1325
1326 static int try_firmware(char *s)
1327 {
1328         struct stat stbuf;
1329         struct iax_firmware *cur = NULL;
1330         int ifd, fd, res, len, chunk;
1331         struct ast_iax2_firmware_header *fwh, fwh2;
1332         struct MD5Context md5;
1333         unsigned char sum[16], buf[1024];
1334         char *s2, *last;
1335
1336         if (!(s2 = alloca(strlen(s) + 100))) {
1337                 ast_log(LOG_WARNING, "Alloca failed!\n");
1338                 return -1;
1339         }
1340
1341         last = strrchr(s, '/');
1342         if (last)
1343                 last++;
1344         else
1345                 last = s;
1346
1347         snprintf(s2, strlen(s) + 100, "/var/tmp/%s-%ld", last, (unsigned long)ast_random());
1348
1349         if ((res = stat(s, &stbuf) < 0)) {
1350                 ast_log(LOG_WARNING, "Failed to stat '%s': %s\n", s, strerror(errno));
1351                 return -1;
1352         }
1353
1354         /* Make sure it's not a directory */
1355         if (S_ISDIR(stbuf.st_mode))
1356                 return -1;
1357         ifd = open(s, O_RDONLY);
1358         if (ifd < 0) {
1359                 ast_log(LOG_WARNING, "Cannot open '%s': %s\n", s, strerror(errno));
1360                 return -1;
1361         }
1362         fd = open(s2, O_RDWR | O_CREAT | O_EXCL);
1363         if (fd < 0) {
1364                 ast_log(LOG_WARNING, "Cannot open '%s' for writing: %s\n", s2, strerror(errno));
1365                 close(ifd);
1366                 return -1;
1367         }
1368         /* Unlink our newly created file */
1369         unlink(s2);
1370         
1371         /* Now copy the firmware into it */
1372         len = stbuf.st_size;
1373         while(len) {
1374                 chunk = len;
1375                 if (chunk > sizeof(buf))
1376                         chunk = sizeof(buf);
1377                 res = read(ifd, buf, chunk);
1378                 if (res != chunk) {
1379                         ast_log(LOG_WARNING, "Only read %d of %d bytes of data :(: %s\n", res, chunk, strerror(errno));
1380                         close(ifd);
1381                         close(fd);
1382                         return -1;
1383                 }
1384                 res = write(fd, buf, chunk);
1385                 if (res != chunk) {
1386                         ast_log(LOG_WARNING, "Only write %d of %d bytes of data :(: %s\n", res, chunk, strerror(errno));
1387                         close(ifd);
1388                         close(fd);
1389                         return -1;
1390                 }
1391                 len -= chunk;
1392         }
1393         close(ifd);
1394         /* Return to the beginning */
1395         lseek(fd, 0, SEEK_SET);
1396         if ((res = read(fd, &fwh2, sizeof(fwh2))) != sizeof(fwh2)) {
1397                 ast_log(LOG_WARNING, "Unable to read firmware header in '%s'\n", s);
1398                 close(fd);
1399                 return -1;
1400         }
1401         if (ntohl(fwh2.magic) != IAX_FIRMWARE_MAGIC) {
1402                 ast_log(LOG_WARNING, "'%s' is not a valid firmware file\n", s);
1403                 close(fd);
1404                 return -1;
1405         }
1406         if (ntohl(fwh2.datalen) != (stbuf.st_size - sizeof(fwh2))) {
1407                 ast_log(LOG_WARNING, "Invalid data length in firmware '%s'\n", s);
1408                 close(fd);
1409                 return -1;
1410         }
1411         if (fwh2.devname[sizeof(fwh2.devname) - 1] || ast_strlen_zero((char *)fwh2.devname)) {
1412                 ast_log(LOG_WARNING, "No or invalid device type specified for '%s'\n", s);
1413                 close(fd);
1414                 return -1;
1415         }
1416         fwh = mmap(NULL, stbuf.st_size, PROT_READ, MAP_PRIVATE, fd, 0); 
1417         if (!fwh) {
1418                 ast_log(LOG_WARNING, "mmap failed: %s\n", strerror(errno));
1419                 close(fd);
1420                 return -1;
1421         }
1422         MD5Init(&md5);
1423         MD5Update(&md5, fwh->data, ntohl(fwh->datalen));
1424         MD5Final(sum, &md5);
1425         if (memcmp(sum, fwh->chksum, sizeof(sum))) {
1426                 ast_log(LOG_WARNING, "Firmware file '%s' fails checksum\n", s);
1427                 munmap(fwh, stbuf.st_size);
1428                 close(fd);
1429                 return -1;
1430         }
1431
1432         AST_LIST_TRAVERSE(&firmwares, cur, list) {
1433                 if (!strcmp((char *)cur->fwh->devname, (char *)fwh->devname)) {
1434                         /* Found a candidate */
1435                         if (cur->dead || (ntohs(cur->fwh->version) < ntohs(fwh->version)))
1436                                 /* The version we have on loaded is older, load this one instead */
1437                                 break;
1438                         /* This version is no newer than what we have.  Don't worry about it.
1439                            We'll consider it a proper load anyhow though */
1440                         munmap(fwh, stbuf.st_size);
1441                         close(fd);
1442                         return 0;
1443                 }
1444         }
1445         
1446         if (!cur && ((cur = ast_calloc(1, sizeof(*cur))))) {
1447                 cur->fd = -1;
1448                 AST_LIST_INSERT_TAIL(&firmwares, cur, list);
1449         }
1450         
1451         if (cur) {
1452                 if (cur->fwh)
1453                         munmap(cur->fwh, cur->mmaplen);
1454                 if (cur->fd > -1)
1455                         close(cur->fd);
1456                 cur->fwh = fwh;
1457                 cur->fd = fd;
1458                 cur->mmaplen = stbuf.st_size;
1459                 cur->dead = 0;
1460         }
1461         
1462         return 0;
1463 }
1464
1465 static int iax_check_version(char *dev)
1466 {
1467         int res = 0;
1468         struct iax_firmware *cur = NULL;
1469
1470         if (ast_strlen_zero(dev))
1471                 return 0;
1472
1473         AST_LIST_LOCK(&firmwares);
1474         AST_LIST_TRAVERSE(&firmwares, cur, list) {
1475                 if (!strcmp(dev, (char *)cur->fwh->devname)) {
1476                         res = ntohs(cur->fwh->version);
1477                         break;
1478                 }
1479         }
1480         AST_LIST_UNLOCK(&firmwares);
1481
1482         return res;
1483 }
1484
1485 static int iax_firmware_append(struct iax_ie_data *ied, const unsigned char *dev, unsigned int desc)
1486 {
1487         int res = -1;
1488         unsigned int bs = desc & 0xff;
1489         unsigned int start = (desc >> 8) & 0xffffff;
1490         unsigned int bytes;
1491         struct iax_firmware *cur;
1492
1493         if (ast_strlen_zero((char *)dev) || !bs)
1494                 return -1;
1495
1496         start *= bs;
1497         
1498         AST_LIST_LOCK(&firmwares);
1499         AST_LIST_TRAVERSE(&firmwares, cur, list) {
1500                 if (strcmp((char *)dev, (char *)cur->fwh->devname))
1501                         continue;
1502                 iax_ie_append_int(ied, IAX_IE_FWBLOCKDESC, desc);
1503                 if (start < ntohl(cur->fwh->datalen)) {
1504                         bytes = ntohl(cur->fwh->datalen) - start;
1505                         if (bytes > bs)
1506                                 bytes = bs;
1507                         iax_ie_append_raw(ied, IAX_IE_FWBLOCKDATA, cur->fwh->data + start, bytes);
1508                 } else {
1509                         bytes = 0;
1510                         iax_ie_append(ied, IAX_IE_FWBLOCKDATA);
1511                 }
1512                 if (bytes == bs)
1513                         res = 0;
1514                 else
1515                         res = 1;
1516                 break;
1517         }
1518         AST_LIST_UNLOCK(&firmwares);
1519
1520         return res;
1521 }
1522
1523
1524 static void reload_firmware(void)
1525 {
1526         struct iax_firmware *cur = NULL;
1527         DIR *fwd;
1528         struct dirent *de;
1529         char dir[256], fn[256];
1530
1531         AST_LIST_LOCK(&firmwares);
1532
1533         /* Mark all as dead */
1534         AST_LIST_TRAVERSE(&firmwares, cur, list)
1535                 cur->dead = 1;
1536
1537         /* Now that we have marked them dead... load new ones */
1538         snprintf(dir, sizeof(dir), "%s/firmware/iax", (char *)ast_config_AST_DATA_DIR);
1539         fwd = opendir(dir);
1540         if (fwd) {
1541                 while((de = readdir(fwd))) {
1542                         if (de->d_name[0] != '.') {
1543                                 snprintf(fn, sizeof(fn), "%s/%s", dir, de->d_name);
1544                                 if (!try_firmware(fn)) {
1545                                         if (option_verbose > 1)
1546                                                 ast_verbose(VERBOSE_PREFIX_2 "Loaded firmware '%s'\n", de->d_name);
1547                                 }
1548                         }
1549                 }
1550                 closedir(fwd);
1551         } else 
1552                 ast_log(LOG_WARNING, "Error opening firmware directory '%s': %s\n", dir, strerror(errno));
1553
1554         /* Clean up leftovers */
1555         AST_LIST_TRAVERSE_SAFE_BEGIN(&firmwares, cur, list) {
1556                 if (!cur->dead)
1557                         continue;
1558                 AST_LIST_REMOVE_CURRENT(&firmwares, list);
1559                 destroy_firmware(cur);
1560         }
1561         AST_LIST_TRAVERSE_SAFE_END
1562
1563         AST_LIST_UNLOCK(&firmwares);
1564 }
1565
1566 static int __do_deliver(void *data)
1567 {
1568         /* Just deliver the packet by using queueing.  This is called by
1569           the IAX thread with the iaxsl lock held. */
1570         struct iax_frame *fr = data;
1571         fr->retrans = -1;
1572         fr->af.has_timing_info = 0;
1573         if (iaxs[fr->callno] && !ast_test_flag(iaxs[fr->callno], IAX_ALREADYGONE))
1574                 iax2_queue_frame(fr->callno, &fr->af);
1575         /* Free our iax frame */
1576         iax2_frame_free(fr);
1577         /* And don't run again */
1578         return 0;
1579 }
1580
1581 static int handle_error(void)
1582 {
1583         /* XXX Ideally we should figure out why an error occured and then abort those
1584            rather than continuing to try.  Unfortunately, the published interface does
1585            not seem to work XXX */
1586 #if 0
1587         struct sockaddr_in *sin;
1588         int res;
1589         struct msghdr m;
1590         struct sock_extended_err e;
1591         m.msg_name = NULL;
1592         m.msg_namelen = 0;
1593         m.msg_iov = NULL;
1594         m.msg_control = &e;
1595         m.msg_controllen = sizeof(e);
1596         m.msg_flags = 0;
1597         res = recvmsg(netsocket, &m, MSG_ERRQUEUE);
1598         if (res < 0)
1599                 ast_log(LOG_WARNING, "Error detected, but unable to read error: %s\n", strerror(errno));
1600         else {
1601                 if (m.msg_controllen) {
1602                         sin = (struct sockaddr_in *)SO_EE_OFFENDER(&e);
1603                         if (sin) 
1604                                 ast_log(LOG_WARNING, "Receive error from %s\n", ast_inet_ntoa(sin->sin_addr));
1605                         else
1606                                 ast_log(LOG_WARNING, "No address detected??\n");
1607                 } else {
1608                         ast_log(LOG_WARNING, "Local error: %s\n", strerror(e.ee_errno));
1609                 }
1610         }
1611 #endif
1612         return 0;
1613 }
1614
1615 static int transmit_trunk(struct iax_frame *f, struct sockaddr_in *sin, int sockfd)
1616 {
1617         int res;
1618         res = sendto(sockfd, f->data, f->datalen, 0,(struct sockaddr *)sin,
1619                                         sizeof(*sin));
1620         if (res < 0) {
1621                 if (option_debug)
1622                         ast_log(LOG_DEBUG, "Received error: %s\n", strerror(errno));
1623                 handle_error();
1624         } else
1625                 res = 0;
1626         return res;
1627 }
1628
1629 static int send_packet(struct iax_frame *f)
1630 {
1631         int res;
1632         int callno = f->callno;
1633
1634         /* Don't send if there was an error, but return error instead */
1635         if (!callno || !iaxs[callno] || iaxs[callno]->error)
1636             return -1;
1637         
1638         /* Called with iaxsl held */
1639         if (option_debug > 2 && iaxdebug)
1640                 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));
1641         if (f->transfer) {
1642                 if (iaxdebug)
1643                         iax_showframe(f, NULL, 0, &iaxs[callno]->transfer, f->datalen - sizeof(struct ast_iax2_full_hdr));
1644                 res = sendto(iaxs[callno]->sockfd, f->data, f->datalen, 0,(struct sockaddr *)&iaxs[callno]->transfer,
1645                                         sizeof(iaxs[callno]->transfer));
1646         } else {
1647                 if (iaxdebug)
1648                         iax_showframe(f, NULL, 0, &iaxs[callno]->addr, f->datalen - sizeof(struct ast_iax2_full_hdr));
1649                 res = sendto(iaxs[callno]->sockfd, f->data, f->datalen, 0,(struct sockaddr *)&iaxs[callno]->addr,
1650                                         sizeof(iaxs[callno]->addr));
1651         }
1652         if (res < 0) {
1653                 if (option_debug && iaxdebug)
1654                         ast_log(LOG_DEBUG, "Received error: %s\n", strerror(errno));
1655                 handle_error();
1656         } else
1657                 res = 0;
1658         return res;
1659 }
1660
1661 static void iax2_destroy_helper(struct chan_iax2_pvt *pvt)
1662 {
1663         struct iax2_user *user = NULL;
1664
1665         /* Decrement AUTHREQ count if needed */
1666         if (ast_test_flag(pvt, IAX_MAXAUTHREQ)) {
1667                 AST_LIST_LOCK(&users);
1668                 AST_LIST_TRAVERSE(&users, user, entry) {
1669                         if (!strcmp(user->name, pvt->username)) {
1670                                 user->curauthreq--;
1671                                 break;
1672                         }
1673                 }
1674                 AST_LIST_UNLOCK(&users);
1675                 ast_clear_flag(pvt, IAX_MAXAUTHREQ);
1676         }
1677         /* No more pings or lagrq's */
1678         if (pvt->pingid > -1)
1679                 ast_sched_del(sched, pvt->pingid);
1680         pvt->pingid = -1;
1681         if (pvt->lagid > -1)
1682                 ast_sched_del(sched, pvt->lagid);
1683         pvt->lagid = -1;
1684         if (pvt->autoid > -1)
1685                 ast_sched_del(sched, pvt->autoid);
1686         pvt->autoid = -1;
1687         if (pvt->authid > -1)
1688                 ast_sched_del(sched, pvt->authid);
1689         pvt->authid = -1;
1690         if (pvt->initid > -1)
1691                 ast_sched_del(sched, pvt->initid);
1692         pvt->initid = -1;
1693         if (pvt->jbid > -1)
1694                 ast_sched_del(sched, pvt->jbid);
1695         pvt->jbid = -1;
1696 }
1697
1698 static int iax2_predestroy(int callno)
1699 {
1700         struct ast_channel *c = NULL;
1701         struct chan_iax2_pvt *pvt = iaxs[callno];
1702
1703         if (!pvt)
1704                 return -1;
1705
1706         if (!ast_test_flag(pvt, IAX_ALREADYGONE)) {
1707                 iax2_destroy_helper(pvt);
1708                 ast_set_flag(pvt, IAX_ALREADYGONE);     
1709         }
1710
1711         if ((c = pvt->owner)) {
1712                 c->_softhangup |= AST_SOFTHANGUP_DEV;
1713                 c->tech_pvt = NULL;
1714                 ast_queue_hangup(c);
1715                 pvt->owner = NULL;
1716         }
1717
1718         return 0;
1719 }
1720
1721 static void iax2_destroy(int callno)
1722 {
1723         struct chan_iax2_pvt *pvt = NULL;
1724         struct iax_frame *cur = NULL;
1725         struct ast_channel *owner = NULL;
1726
1727 retry:
1728         pvt = iaxs[callno];
1729         gettimeofday(&lastused[callno], NULL);
1730         
1731         owner = pvt ? pvt->owner : NULL;
1732
1733         if (owner) {
1734                 if (ast_mutex_trylock(&owner->lock)) {
1735                         ast_log(LOG_NOTICE, "Avoiding IAX destroy deadlock\n");
1736                         ast_mutex_unlock(&iaxsl[callno]);
1737                         usleep(1);
1738                         ast_mutex_lock(&iaxsl[callno]);
1739                         goto retry;
1740                 }
1741         }
1742         if (!owner)
1743                 iaxs[callno] = NULL;
1744         if (pvt) {
1745                 if (!owner)
1746                         pvt->owner = NULL;
1747                 iax2_destroy_helper(pvt);
1748
1749                 /* Already gone */
1750                 ast_set_flag(pvt, IAX_ALREADYGONE);     
1751
1752                 if (owner) {
1753                         /* If there's an owner, prod it to give up */
1754                         owner->_softhangup |= AST_SOFTHANGUP_DEV;
1755                         ast_queue_hangup(owner);
1756                 }
1757
1758                 AST_LIST_TRAVERSE(&iaxq.queue, cur, list) {
1759                         /* Cancel any pending transmissions */
1760                         if (cur->callno == pvt->callno) 
1761                                 cur->retries = -1;
1762                 }
1763                 if (pvt->reg)
1764                         pvt->reg->callno = 0;
1765                 if (!owner) {
1766                         jb_frame frame;
1767                         if (pvt->vars) {
1768                             ast_variables_destroy(pvt->vars);
1769                             pvt->vars = NULL;
1770                         }
1771
1772                         while (jb_getall(pvt->jb, &frame) == JB_OK)
1773                                 iax2_frame_free(frame.data);
1774                         jb_destroy(pvt->jb);
1775                         /* gotta free up the stringfields */
1776                         ast_string_field_free_pools(pvt);
1777                         free(pvt);
1778                 }
1779         }
1780         if (owner) {
1781                 ast_mutex_unlock(&owner->lock);
1782         }
1783         if (callno & 0x4000)
1784                 update_max_trunk();
1785 }
1786
1787 static int update_packet(struct iax_frame *f)
1788 {
1789         /* Called with iaxsl lock held, and iaxs[callno] non-NULL */
1790         struct ast_iax2_full_hdr *fh = f->data;
1791         /* Mark this as a retransmission */
1792         fh->dcallno = ntohs(IAX_FLAG_RETRANS | f->dcallno);
1793         /* Update iseqno */
1794         f->iseqno = iaxs[f->callno]->iseqno;
1795         fh->iseqno = f->iseqno;
1796         return 0;
1797 }
1798
1799 static int attempt_transmit(void *data);
1800 static void __attempt_transmit(void *data)
1801 {
1802         /* Attempt to transmit the frame to the remote peer...
1803            Called without iaxsl held. */
1804         struct iax_frame *f = data;
1805         int freeme=0;
1806         int callno = f->callno;
1807         /* Make sure this call is still active */
1808         if (callno) 
1809                 ast_mutex_lock(&iaxsl[callno]);
1810         if (callno && iaxs[callno]) {
1811                 if ((f->retries < 0) /* Already ACK'd */ ||
1812                     (f->retries >= max_retries) /* Too many attempts */) {
1813                                 /* Record an error if we've transmitted too many times */
1814                                 if (f->retries >= max_retries) {
1815                                         if (f->transfer) {
1816                                                 /* Transfer timeout */
1817                                                 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_TXREJ, 0, NULL, 0, -1);
1818                                         } else if (f->final) {
1819                                                 if (f->final) 
1820                                                         iax2_destroy(callno);
1821                                         } else {
1822                                                 if (iaxs[callno]->owner)
1823                                                         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);
1824                                                 iaxs[callno]->error = ETIMEDOUT;
1825                                                 if (iaxs[callno]->owner) {
1826                                                         struct ast_frame fr = { 0, };
1827                                                         /* Hangup the fd */
1828                                                         fr.frametype = AST_FRAME_CONTROL;
1829                                                         fr.subclass = AST_CONTROL_HANGUP;
1830                                                         iax2_queue_frame(callno, &fr);
1831                                                         /* Remember, owner could disappear */
1832                                                         if (iaxs[callno]->owner)
1833                                                                 iaxs[callno]->owner->hangupcause = AST_CAUSE_DESTINATION_OUT_OF_ORDER;
1834                                                 } else {
1835                                                         if (iaxs[callno]->reg) {
1836                                                                 memset(&iaxs[callno]->reg->us, 0, sizeof(iaxs[callno]->reg->us));
1837                                                                 iaxs[callno]->reg->regstate = REG_STATE_TIMEOUT;
1838                                                                 iaxs[callno]->reg->refresh = IAX_DEFAULT_REG_EXPIRE;
1839                                                         }
1840                                                         iax2_destroy(callno);
1841                                                 }
1842                                         }
1843
1844                                 }
1845                                 freeme++;
1846                 } else {
1847                         /* Update it if it needs it */
1848                         update_packet(f);
1849                         /* Attempt transmission */
1850                         send_packet(f);
1851                         f->retries++;
1852                         /* Try again later after 10 times as long */
1853                         f->retrytime *= 10;
1854                         if (f->retrytime > MAX_RETRY_TIME)
1855                                 f->retrytime = MAX_RETRY_TIME;
1856                         /* Transfer messages max out at one second */
1857                         if (f->transfer && (f->retrytime > 1000))
1858                                 f->retrytime = 1000;
1859                         f->retrans = ast_sched_add(sched, f->retrytime, attempt_transmit, f);
1860                 }
1861         } else {
1862                 /* Make sure it gets freed */
1863                 f->retries = -1;
1864                 freeme++;
1865         }
1866         if (callno)
1867                 ast_mutex_unlock(&iaxsl[callno]);
1868         /* Do not try again */
1869         if (freeme) {
1870                 /* Don't attempt delivery, just remove it from the queue */
1871                 AST_LIST_LOCK(&iaxq.queue);
1872                 AST_LIST_REMOVE(&iaxq.queue, f, list);
1873                 iaxq.count--;
1874                 AST_LIST_UNLOCK(&iaxq.queue);
1875                 f->retrans = -1;
1876                 /* Free the IAX frame */
1877                 iax2_frame_free(f);
1878         }
1879 }
1880
1881 static int attempt_transmit(void *data)
1882 {
1883 #ifdef SCHED_MULTITHREADED
1884         if (schedule_action(__attempt_transmit, data))
1885 #endif          
1886                 __attempt_transmit(data);
1887         return 0;
1888 }
1889
1890 static int iax2_prune_realtime(int fd, int argc, char *argv[])
1891 {
1892         struct iax2_peer *peer;
1893
1894         if (argc != 4)
1895         return RESULT_SHOWUSAGE;
1896         if (!strcmp(argv[3],"all")) {
1897                 reload_config();
1898                 ast_cli(fd, "OK cache is flushed.\n");
1899         } else if ((peer = find_peer(argv[3], 0))) {
1900                 if(ast_test_flag(peer, IAX_RTCACHEFRIENDS)) {
1901                         ast_set_flag(peer, IAX_RTAUTOCLEAR);
1902                         expire_registry((void*)peer->name);
1903                         ast_cli(fd, "OK peer %s was removed from the cache.\n", argv[3]);
1904                 } else {
1905                         ast_cli(fd, "SORRY peer %s is not eligible for this operation.\n", argv[3]);
1906                 }
1907         } else {
1908                 ast_cli(fd, "SORRY peer %s was not found in the cache.\n", argv[3]);
1909         }
1910         
1911         return RESULT_SUCCESS;
1912 }
1913
1914 static int iax2_test_losspct(int fd, int argc, char *argv[])
1915 {
1916        if (argc != 4)
1917                return RESULT_SHOWUSAGE;
1918
1919        test_losspct = atoi(argv[3]);
1920
1921        return RESULT_SUCCESS;
1922 }
1923
1924 #ifdef IAXTESTS
1925 static int iax2_test_late(int fd, int argc, char *argv[])
1926 {
1927         if (argc != 4)
1928                 return RESULT_SHOWUSAGE;
1929
1930         test_late = atoi(argv[3]);
1931
1932         return RESULT_SUCCESS;
1933 }
1934
1935 static int iax2_test_resync(int fd, int argc, char *argv[])
1936 {
1937         if (argc != 4)
1938                 return RESULT_SHOWUSAGE;
1939
1940         test_resync = atoi(argv[3]);
1941
1942         return RESULT_SUCCESS;
1943 }
1944
1945 static int iax2_test_jitter(int fd, int argc, char *argv[])
1946 {
1947         if (argc < 4 || argc > 5)
1948                 return RESULT_SHOWUSAGE;
1949
1950         test_jit = atoi(argv[3]);
1951         if (argc == 5) 
1952                 test_jitpct = atoi(argv[4]);
1953
1954         return RESULT_SUCCESS;
1955 }
1956 #endif /* IAXTESTS */
1957
1958 /*! \brief  peer_status: Report Peer status in character string */
1959 /*      returns 1 if peer is online, -1 if unmonitored */
1960 static int peer_status(struct iax2_peer *peer, char *status, int statuslen)
1961 {
1962         int res = 0;
1963         if (peer->maxms) {
1964                 if (peer->lastms < 0) {
1965                         ast_copy_string(status, "UNREACHABLE", statuslen);
1966                 } else if (peer->lastms > peer->maxms) {
1967                         snprintf(status, statuslen, "LAGGED (%d ms)", peer->lastms);
1968                         res = 1;
1969                 } else if (peer->lastms) {
1970                         snprintf(status, statuslen, "OK (%d ms)", peer->lastms);
1971                         res = 1;
1972                 } else {
1973                         ast_copy_string(status, "UNKNOWN", statuslen);
1974                 }
1975         } else { 
1976                 ast_copy_string(status, "Unmonitored", statuslen);
1977                 res = -1;
1978         }
1979         return res;
1980 }
1981
1982 /*! \brief Show one peer in detail */
1983 static int iax2_show_peer(int fd, int argc, char *argv[])
1984 {
1985         char status[30];
1986         char cbuf[256];
1987         struct iax2_peer *peer;
1988         char codec_buf[512];
1989         int x = 0, codec = 0, load_realtime = 0;
1990
1991         if (argc < 4)
1992                 return RESULT_SHOWUSAGE;
1993
1994         load_realtime = (argc == 5 && !strcmp(argv[4], "load")) ? 1 : 0;
1995
1996         peer = find_peer(argv[3], load_realtime);
1997         if (peer) {
1998                 ast_cli(fd,"\n\n");
1999                 ast_cli(fd, "  * Name       : %s\n", peer->name);
2000                 ast_cli(fd, "  Secret       : %s\n", ast_strlen_zero(peer->secret)?"<Not set>":"<Set>");
2001                 ast_cli(fd, "  Context      : %s\n", peer->context);
2002                 ast_cli(fd, "  Mailbox      : %s\n", peer->mailbox);
2003                 ast_cli(fd, "  Dynamic      : %s\n", ast_test_flag(peer, IAX_DYNAMIC) ? "Yes":"No");
2004                 ast_cli(fd, "  Callerid     : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, "<unspecified>"));
2005                 ast_cli(fd, "  Expire       : %d\n", peer->expire);
2006                 ast_cli(fd, "  ACL          : %s\n", (peer->ha?"Yes":"No"));
2007                 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));
2008                 ast_cli(fd, "  Defaddr->IP  : %s Port %d\n", ast_inet_ntoa(peer->defaddr.sin_addr), ntohs(peer->defaddr.sin_port));
2009                 ast_cli(fd, "  Username     : %s\n", peer->username);
2010                 ast_cli(fd, "  Codecs       : ");
2011                 ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, peer->capability);
2012                 ast_cli(fd, "%s\n", codec_buf);
2013
2014                 ast_cli(fd, "  Codec Order  : (");
2015                 for(x = 0; x < 32 ; x++) {
2016                         codec = ast_codec_pref_index(&peer->prefs,x);
2017                         if(!codec)
2018                                 break;
2019                         ast_cli(fd, "%s", ast_getformatname(codec));
2020                         if(x < 31 && ast_codec_pref_index(&peer->prefs,x+1))
2021                                 ast_cli(fd, "|");
2022                 }
2023
2024                 if (!x)
2025                         ast_cli(fd, "none");
2026                 ast_cli(fd, ")\n");
2027
2028                 ast_cli(fd, "  Status       : ");
2029                 peer_status(peer, status, sizeof(status));      
2030                 ast_cli(fd, "%s\n",status);
2031                 ast_cli(fd, "  Qualify      : every %dms when OK, every %dms when UNREACHABLE (sample smoothing %s)\n", peer->pokefreqok, peer->pokefreqnotok, peer->smoothing ? "On" : "Off");
2032                 ast_cli(fd,"\n");
2033                 if (ast_test_flag(peer, IAX_TEMPONLY))
2034                         destroy_peer(peer);
2035         } else {
2036                 ast_cli(fd,"Peer %s not found.\n", argv[3]);
2037                 ast_cli(fd,"\n");
2038         }
2039
2040         return RESULT_SUCCESS;
2041 }
2042
2043 static char *complete_iax2_show_peer(const char *line, const char *word, int pos, int state)
2044 {
2045         int which = 0;
2046         struct iax2_peer *p = NULL;
2047         char *res = NULL;
2048         int wordlen = strlen(word);
2049
2050         /* 0 - iax2; 1 - show; 2 - peer; 3 - <peername> */
2051         if (pos == 3) {
2052                 AST_LIST_LOCK(&peers);
2053                 AST_LIST_TRAVERSE(&peers, p, entry) {
2054                         if (!strncasecmp(p->name, word, wordlen) && ++which > state) {
2055                                 res = ast_strdup(p->name);
2056                                 break;
2057                         }
2058                 }
2059                 AST_LIST_UNLOCK(&peers);
2060         }
2061
2062         return res;
2063 }
2064
2065 static int iax2_show_stats(int fd, int argc, char *argv[])
2066 {
2067         struct iax_frame *cur;
2068         int cnt = 0, dead=0, final=0;
2069         if (argc != 3)
2070                 return RESULT_SHOWUSAGE;
2071         AST_LIST_TRAVERSE(&iaxq.queue, cur, list) {
2072                 if (cur->retries < 0)
2073                         dead++;
2074                 if (cur->final)
2075                         final++;
2076                 cnt++;
2077         }
2078         ast_cli(fd, "    IAX Statistics\n");
2079         ast_cli(fd, "---------------------\n");
2080         ast_cli(fd, "Outstanding frames: %d (%d ingress, %d egress)\n", iax_get_frames(), iax_get_iframes(), iax_get_oframes());
2081         ast_cli(fd, "%d timed and %d untimed transmits; MTU %d/%d/%d\n", trunk_timed, trunk_untimed,
2082                 trunk_maxmtu, trunk_nmaxmtu, global_max_trunk_mtu);
2083
2084         ast_cli(fd, "Packets in transmit queue: %d dead, %d final, %d total\n\n", dead, final, cnt);
2085
2086         trunk_timed = trunk_untimed = 0;
2087         if (trunk_maxmtu > trunk_nmaxmtu)
2088                 trunk_nmaxmtu = trunk_maxmtu;
2089         
2090         return RESULT_SUCCESS;
2091 }
2092
2093 /*! \brief Set trunk MTU from CLI */
2094 static int iax2_set_mtu(int fd, int argc, char *argv[])
2095 {
2096         int mtuv;
2097
2098         if (argc != 4)
2099                 return RESULT_SHOWUSAGE; 
2100         if (strncasecmp(argv[3], "default", strlen(argv[3])) == 0) 
2101                 mtuv = MAX_TRUNK_MTU; 
2102         else                                         
2103                 mtuv = atoi(argv[3]); 
2104
2105         if (mtuv == 0) {
2106                 ast_cli(fd, "Trunk MTU control disabled (mtu was %d)\n", global_max_trunk_mtu); 
2107                 global_max_trunk_mtu = 0; 
2108                 return RESULT_SUCCESS; 
2109         }
2110         if (mtuv < 172 || mtuv > 4000) {
2111                 ast_cli(fd, "Trunk MTU must be between 172 and 4000\n"); 
2112                 return RESULT_SHOWUSAGE; 
2113         }
2114         ast_cli(fd, "Trunk MTU changed from %d to %d\n", global_max_trunk_mtu, mtuv); 
2115         global_max_trunk_mtu = mtuv; 
2116         return RESULT_SUCCESS;
2117 }
2118
2119 static int iax2_show_cache(int fd, int argc, char *argv[])
2120 {
2121         struct iax2_dpcache *dp = NULL;
2122         char tmp[1024], *pc = NULL;
2123         int s, x, y;
2124         struct timeval tv;
2125
2126         gettimeofday(&tv, NULL);
2127
2128         AST_LIST_LOCK(&dpcache);
2129
2130         ast_cli(fd, "%-20.20s %-12.12s %-9.9s %-8.8s %s\n", "Peer/Context", "Exten", "Exp.", "Wait.", "Flags");
2131
2132         AST_LIST_TRAVERSE(&dpcache, dp, cache_list) {
2133                 s = dp->expiry.tv_sec - tv.tv_sec;
2134                 tmp[0] = '\0';
2135                 if (dp->flags & CACHE_FLAG_EXISTS)
2136                         strncat(tmp, "EXISTS|", sizeof(tmp) - strlen(tmp) - 1);
2137                 if (dp->flags & CACHE_FLAG_NONEXISTENT)
2138                         strncat(tmp, "NONEXISTENT|", sizeof(tmp) - strlen(tmp) - 1);
2139                 if (dp->flags & CACHE_FLAG_CANEXIST)
2140                         strncat(tmp, "CANEXIST|", sizeof(tmp) - strlen(tmp) - 1);
2141                 if (dp->flags & CACHE_FLAG_PENDING)
2142                         strncat(tmp, "PENDING|", sizeof(tmp) - strlen(tmp) - 1);
2143                 if (dp->flags & CACHE_FLAG_TIMEOUT)
2144                         strncat(tmp, "TIMEOUT|", sizeof(tmp) - strlen(tmp) - 1);
2145                 if (dp->flags & CACHE_FLAG_TRANSMITTED)
2146                         strncat(tmp, "TRANSMITTED|", sizeof(tmp) - strlen(tmp) - 1);
2147                 if (dp->flags & CACHE_FLAG_MATCHMORE)
2148                         strncat(tmp, "MATCHMORE|", sizeof(tmp) - strlen(tmp) - 1);
2149                 if (dp->flags & CACHE_FLAG_UNKNOWN)
2150                         strncat(tmp, "UNKNOWN|", sizeof(tmp) - strlen(tmp) - 1);
2151                 /* Trim trailing pipe */
2152                 if (!ast_strlen_zero(tmp))
2153                         tmp[strlen(tmp) - 1] = '\0';
2154                 else
2155                         ast_copy_string(tmp, "(none)", sizeof(tmp));
2156                 y=0;
2157                 pc = strchr(dp->peercontext, '@');
2158                 if (!pc)
2159                         pc = dp->peercontext;
2160                 else
2161                         pc++;
2162                 for (x=0;x<sizeof(dp->waiters) / sizeof(dp->waiters[0]); x++)
2163                         if (dp->waiters[x] > -1)
2164                                 y++;
2165                 if (s > 0)
2166                         ast_cli(fd, "%-20.20s %-12.12s %-9d %-8d %s\n", pc, dp->exten, s, y, tmp);
2167                 else
2168                         ast_cli(fd, "%-20.20s %-12.12s %-9.9s %-8d %s\n", pc, dp->exten, "(expired)", y, tmp);
2169         }
2170
2171         AST_LIST_LOCK(&dpcache);
2172
2173         return RESULT_SUCCESS;
2174 }
2175
2176 static unsigned int calc_rxstamp(struct chan_iax2_pvt *p, unsigned int offset);
2177
2178 static void unwrap_timestamp(struct iax_frame *fr)
2179 {
2180         int x;
2181
2182         if ( (fr->ts & 0xFFFF0000) == (iaxs[fr->callno]->last & 0xFFFF0000) ) {
2183                 x = fr->ts - iaxs[fr->callno]->last;
2184                 if (x < -50000) {
2185                         /* Sudden big jump backwards in timestamp:
2186                            What likely happened here is that miniframe timestamp has circled but we haven't
2187                            gotten the update from the main packet.  We'll just pretend that we did, and
2188                            update the timestamp appropriately. */
2189                         fr->ts = ( (iaxs[fr->callno]->last & 0xFFFF0000) + 0x10000) | (fr->ts & 0xFFFF);
2190                         if (option_debug && iaxdebug)
2191                                 ast_log(LOG_DEBUG, "schedule_delivery: pushed forward timestamp\n");
2192                 }
2193                 if (x > 50000) {
2194                         /* Sudden apparent big jump forwards in timestamp:
2195                            What's likely happened is this is an old miniframe belonging to the previous
2196                            top-16-bit timestamp that has turned up out of order.
2197                            Adjust the timestamp appropriately. */
2198                         fr->ts = ( (iaxs[fr->callno]->last & 0xFFFF0000) - 0x10000) | (fr->ts & 0xFFFF);
2199                         if (option_debug && iaxdebug)
2200                                 ast_log(LOG_DEBUG, "schedule_delivery: pushed back timestamp\n");
2201                 }
2202         }
2203 }
2204
2205 static int get_from_jb(void *p);
2206
2207 static void update_jbsched(struct chan_iax2_pvt *pvt)
2208 {
2209         int when;
2210         
2211         when = ast_tvdiff_ms(ast_tvnow(), pvt->rxcore);
2212         
2213         when = jb_next(pvt->jb) - when;
2214         
2215         if(pvt->jbid > -1) ast_sched_del(sched, pvt->jbid);
2216         
2217         if(when <= 0) {
2218                 /* XXX should really just empty until when > 0.. */
2219                 when = 1;
2220         }
2221         
2222         pvt->jbid = ast_sched_add(sched, when, get_from_jb, CALLNO_TO_PTR(pvt->callno));
2223         
2224         /* Signal scheduler thread */
2225         signal_condition(&sched_lock, &sched_cond);
2226 }
2227
2228 static void __get_from_jb(void *p) 
2229 {
2230         int callno = PTR_TO_CALLNO(p);
2231         struct chan_iax2_pvt *pvt = NULL;
2232         struct iax_frame *fr;
2233         jb_frame frame;
2234         int ret;
2235         long now;
2236         long next;
2237         struct timeval tv;
2238         
2239         /* Make sure we have a valid private structure before going on */
2240         ast_mutex_lock(&iaxsl[callno]);
2241         pvt = iaxs[callno];
2242         if (!pvt) {
2243                 /* No go! */
2244                 ast_mutex_unlock(&iaxsl[callno]);
2245                 return;
2246         }
2247
2248         pvt->jbid = -1;
2249         
2250         gettimeofday(&tv,NULL);
2251         /* round up a millisecond since ast_sched_runq does; */
2252         /* prevents us from spinning while waiting for our now */
2253         /* to catch up with runq's now */
2254         tv.tv_usec += 1000;
2255         
2256         now = ast_tvdiff_ms(tv, pvt->rxcore);
2257         
2258         if(now >= (next = jb_next(pvt->jb))) {
2259                 ret = jb_get(pvt->jb,&frame,now,ast_codec_interp_len(pvt->voiceformat));
2260                 switch(ret) {
2261                 case JB_OK:
2262                         fr = frame.data;
2263                         __do_deliver(fr);
2264                         break;
2265                 case JB_INTERP:
2266                 {
2267                         struct ast_frame af;
2268                         
2269                         /* create an interpolation frame */
2270                         af.frametype = AST_FRAME_VOICE;
2271                         af.subclass = pvt->voiceformat;
2272                         af.datalen  = 0;
2273                         af.samples  = frame.ms * 8;
2274                         af.mallocd  = 0;
2275                         af.src  = "IAX2 JB interpolation";
2276                         af.data  = NULL;
2277                         af.delivery = ast_tvadd(pvt->rxcore, ast_samp2tv(next, 1000));
2278                         af.offset=AST_FRIENDLY_OFFSET;
2279                         
2280                         /* queue the frame:  For consistency, we would call __do_deliver here, but __do_deliver wants an iax_frame,
2281                          * which we'd need to malloc, and then it would free it.  That seems like a drag */
2282                         if (!ast_test_flag(iaxs[callno], IAX_ALREADYGONE))
2283                                 iax2_queue_frame(callno, &af);
2284                 }
2285                 break;
2286                 case JB_DROP:
2287                         iax2_frame_free(frame.data);
2288                         break;
2289                 case JB_NOFRAME:
2290                 case JB_EMPTY:
2291                         /* do nothing */
2292                         break;
2293                 default:
2294                         /* shouldn't happen */
2295                         break;
2296                 }
2297         }
2298         update_jbsched(pvt);
2299         ast_mutex_unlock(&iaxsl[callno]);
2300 }
2301
2302 static int get_from_jb(void *data)
2303 {
2304 #ifdef SCHED_MULTITHREADED
2305         if (schedule_action(__get_from_jb, data))
2306 #endif          
2307                 __get_from_jb(data);
2308         return 0;
2309 }
2310
2311 static int schedule_delivery(struct iax_frame *fr, int updatehistory, int fromtrunk, unsigned int *tsout)
2312 {
2313         int type, len;
2314         int ret;
2315         int needfree = 0;
2316
2317         /* Attempt to recover wrapped timestamps */
2318         unwrap_timestamp(fr);
2319         
2320
2321         /* delivery time is sender's sent timestamp converted back into absolute time according to our clock */
2322         if ( !fromtrunk && !ast_tvzero(iaxs[fr->callno]->rxcore))
2323                 fr->af.delivery = ast_tvadd(iaxs[fr->callno]->rxcore, ast_samp2tv(fr->ts, 1000));
2324         else {
2325 #if 0
2326                 if (option_debug)
2327                         ast_log(LOG_DEBUG, "schedule_delivery: set delivery to 0 as we don't have an rxcore yet, or frame is from trunk.\n");
2328 #endif
2329                 fr->af.delivery = ast_tv(0,0);
2330         }
2331
2332         type = JB_TYPE_CONTROL;
2333         len = 0;
2334
2335         if(fr->af.frametype == AST_FRAME_VOICE) {
2336                 type = JB_TYPE_VOICE;
2337                 len = ast_codec_get_samples(&fr->af) / 8;
2338         } else if(fr->af.frametype == AST_FRAME_CNG) {
2339                 type = JB_TYPE_SILENCE;
2340         }
2341
2342         if ( (!ast_test_flag(iaxs[fr->callno], IAX_USEJITTERBUF)) ) {
2343                 if (tsout)
2344                         *tsout = fr->ts;
2345                 __do_deliver(fr);
2346                 return -1;
2347         }
2348
2349         /* if the user hasn't requested we force the use of the jitterbuffer, and we're bridged to
2350          * a channel that can accept jitter, then flush and suspend the jb, and send this frame straight through */
2351         if( (!ast_test_flag(iaxs[fr->callno], IAX_FORCEJITTERBUF)) &&
2352             iaxs[fr->callno]->owner && ast_bridged_channel(iaxs[fr->callno]->owner) &&
2353             (ast_bridged_channel(iaxs[fr->callno]->owner)->tech->properties & AST_CHAN_TP_WANTSJITTER)) {
2354                 jb_frame frame;
2355
2356                 /* deliver any frames in the jb */
2357                 while(jb_getall(iaxs[fr->callno]->jb,&frame) == JB_OK)
2358                         __do_deliver(frame.data);
2359
2360                 jb_reset(iaxs[fr->callno]->jb);
2361
2362                 if (iaxs[fr->callno]->jbid > -1)
2363                         ast_sched_del(sched, iaxs[fr->callno]->jbid);
2364
2365                 iaxs[fr->callno]->jbid = -1;
2366
2367                 /* deliver this frame now */
2368                 if (tsout)
2369                         *tsout = fr->ts;
2370                 __do_deliver(fr);
2371                 return -1;
2372         }
2373
2374         /* insert into jitterbuffer */
2375         /* TODO: Perhaps we could act immediately if it's not droppable and late */
2376         ret = jb_put(iaxs[fr->callno]->jb, fr, type, len, fr->ts,
2377                         calc_rxstamp(iaxs[fr->callno],fr->ts));
2378         if (ret == JB_DROP) {
2379                 needfree++;
2380         } else if (ret == JB_SCHED) {
2381                 update_jbsched(iaxs[fr->callno]);
2382         }
2383         if (tsout)
2384                 *tsout = fr->ts;
2385         if (needfree) {
2386                 /* Free our iax frame */
2387                 iax2_frame_free(fr);
2388                 return -1;
2389         }
2390         return 0;
2391 }
2392
2393 static int iax2_transmit(struct iax_frame *fr)
2394 {
2395         /* Lock the queue and place this packet at the end */
2396         /* By setting this to 0, the network thread will send it for us, and
2397            queue retransmission if necessary */
2398         fr->sentyet = 0;
2399         AST_LIST_LOCK(&iaxq.queue);
2400         AST_LIST_INSERT_TAIL(&iaxq.queue, fr, list);
2401         iaxq.count++;
2402         AST_LIST_UNLOCK(&iaxq.queue);
2403         /* Wake up the network and scheduler thread */
2404         pthread_kill(netthreadid, SIGURG);
2405         signal_condition(&sched_lock, &sched_cond);
2406         return 0;
2407 }
2408
2409
2410
2411 static int iax2_digit_begin(struct ast_channel *c, char digit)
2412 {
2413         return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_DTMF_BEGIN, digit, 0, NULL, 0, -1);
2414 }
2415
2416 static int iax2_digit_end(struct ast_channel *c, char digit)
2417 {
2418         return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_DTMF_END, digit, 0, NULL, 0, -1);
2419 }
2420
2421 static int iax2_sendtext(struct ast_channel *c, const char *text)
2422 {
2423         
2424         return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_TEXT,
2425                 0, 0, (unsigned char *)text, strlen(text) + 1, -1);
2426 }
2427
2428 static int iax2_sendimage(struct ast_channel *c, struct ast_frame *img)
2429 {
2430         return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_IMAGE, img->subclass, 0, img->data, img->datalen, -1);
2431 }
2432
2433 static int iax2_sendhtml(struct ast_channel *c, int subclass, const char *data, int datalen)
2434 {
2435         return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_HTML, subclass, 0, (unsigned char *)data, datalen, -1);
2436 }
2437
2438 static int iax2_fixup(struct ast_channel *oldchannel, struct ast_channel *newchan)
2439 {
2440         unsigned short callno = PTR_TO_CALLNO(newchan->tech_pvt);
2441         ast_mutex_lock(&iaxsl[callno]);
2442         if (iaxs[callno])
2443                 iaxs[callno]->owner = newchan;
2444         else
2445                 ast_log(LOG_WARNING, "Uh, this isn't a good sign...\n");
2446         ast_mutex_unlock(&iaxsl[callno]);
2447         return 0;
2448 }
2449
2450 static struct iax2_peer *realtime_peer(const char *peername, struct sockaddr_in *sin)
2451 {
2452         struct ast_variable *var;
2453         struct ast_variable *tmp;
2454         struct iax2_peer *peer=NULL;
2455         time_t regseconds = 0, nowtime;
2456         int dynamic=0;
2457
2458         if (peername)
2459                 var = ast_load_realtime("iaxpeers", "name", peername, NULL);
2460         else {
2461                 char porta[25];
2462                 sprintf(porta, "%d", ntohs(sin->sin_port));
2463                 var = ast_load_realtime("iaxpeers", "ipaddr", ast_inet_ntoa(sin->sin_addr), "port", porta, NULL);
2464                 if (var) {
2465                         /* We'll need the peer name in order to build the structure! */
2466                         for (tmp = var; tmp; tmp = tmp->next) {
2467                                 if (!strcasecmp(tmp->name, "name"))
2468                                         peername = tmp->value;
2469                         }
2470                 }
2471         }
2472         if (!var)
2473                 return NULL;
2474
2475         peer = build_peer(peername, var, NULL, ast_test_flag((&globalflags), IAX_RTCACHEFRIENDS) ? 0 : 1);
2476         
2477         if (!peer)
2478                 return NULL;
2479
2480         for (tmp = var; tmp; tmp = tmp->next) {
2481                 /* Make sure it's not a user only... */
2482                 if (!strcasecmp(tmp->name, "type")) {
2483                         if (strcasecmp(tmp->value, "friend") &&
2484                             strcasecmp(tmp->value, "peer")) {
2485                                 /* Whoops, we weren't supposed to exist! */
2486                                 destroy_peer(peer);
2487                                 peer = NULL;
2488                                 break;
2489                         } 
2490                 } else if (!strcasecmp(tmp->name, "regseconds")) {
2491                         ast_get_time_t(tmp->value, &regseconds, 0, NULL);
2492                 } else if (!strcasecmp(tmp->name, "ipaddr")) {
2493                         inet_aton(tmp->value, &(peer->addr.sin_addr));
2494                 } else if (!strcasecmp(tmp->name, "port")) {
2495                         peer->addr.sin_port = htons(atoi(tmp->value));
2496                 } else if (!strcasecmp(tmp->name, "host")) {
2497                         if (!strcasecmp(tmp->value, "dynamic"))
2498                                 dynamic = 1;
2499                 }
2500         }
2501         if (!peer)
2502                 return NULL;
2503
2504         ast_variables_destroy(var);
2505
2506         if (ast_test_flag((&globalflags), IAX_RTCACHEFRIENDS)) {
2507                 ast_copy_flags(peer, &globalflags, IAX_RTAUTOCLEAR|IAX_RTCACHEFRIENDS);
2508                 if (ast_test_flag(peer, IAX_RTAUTOCLEAR)) {
2509                         if (peer->expire > -1)
2510                                 ast_sched_del(sched, peer->expire);
2511                         peer->expire = ast_sched_add(sched, (global_rtautoclear) * 1000, expire_registry, (void*)peer->name);
2512                 }
2513                 AST_LIST_LOCK(&peers);
2514                 AST_LIST_INSERT_HEAD(&peers, peer, entry);
2515                 AST_LIST_UNLOCK(&peers);
2516                 if (ast_test_flag(peer, IAX_DYNAMIC))
2517                         reg_source_db(peer);
2518         } else {
2519                 ast_set_flag(peer, IAX_TEMPONLY);       
2520         }
2521
2522         if (!ast_test_flag(&globalflags, IAX_RTIGNOREREGEXPIRE) && dynamic) {
2523                 time(&nowtime);
2524                 if ((nowtime - regseconds) > IAX_DEFAULT_REG_EXPIRE) {
2525                         memset(&peer->addr, 0, sizeof(peer->addr));
2526                         realtime_update_peer(peer->name, &peer->addr, 0);
2527                         if (option_debug)
2528                                 ast_log(LOG_DEBUG, "realtime_peer: Bah, '%s' is expired (%d/%d/%d)!\n",
2529                                                 peername, (int)(nowtime - regseconds), (int)regseconds, (int)nowtime);
2530                 }
2531                 else {
2532                         if (option_debug)
2533                                 ast_log(LOG_DEBUG, "realtime_peer: Registration for '%s' still active (%d/%d/%d)!\n",
2534                                                 peername, (int)(nowtime - regseconds), (int)regseconds, (int)nowtime);
2535                 }
2536         }
2537
2538         return peer;
2539 }
2540
2541 static struct iax2_user *realtime_user(const char *username)
2542 {
2543         struct ast_variable *var;
2544         struct ast_variable *tmp;
2545         struct iax2_user *user=NULL;
2546
2547         var = ast_load_realtime("iaxusers", "name", username, NULL);
2548         if (!var)
2549                 return NULL;
2550
2551         tmp = var;
2552         while(tmp) {
2553                 /* Make sure it's not a peer only... */
2554                 if (!strcasecmp(tmp->name, "type")) {
2555                         if (strcasecmp(tmp->value, "friend") &&
2556                             strcasecmp(tmp->value, "user")) {
2557                                 return NULL;
2558                         } 
2559                 }
2560                 tmp = tmp->next;
2561         }
2562
2563         user = build_user(username, var, NULL, !ast_test_flag((&globalflags), IAX_RTCACHEFRIENDS));
2564         if (!user)
2565                 return NULL;
2566
2567         ast_variables_destroy(var);
2568
2569         if (ast_test_flag((&globalflags), IAX_RTCACHEFRIENDS)) {
2570                 ast_set_flag(user, IAX_RTCACHEFRIENDS);
2571                 AST_LIST_LOCK(&users);
2572                 AST_LIST_INSERT_HEAD(&users, user, entry);
2573                 AST_LIST_UNLOCK(&users);
2574         } else {
2575                 ast_set_flag(user, IAX_TEMPONLY);       
2576         }
2577
2578         return user;
2579 }
2580
2581 static void realtime_update_peer(const char *peername, struct sockaddr_in *sin, time_t regtime)
2582 {
2583         char port[10];
2584         char regseconds[20];
2585         
2586         snprintf(regseconds, sizeof(regseconds), "%d", (int)regtime);
2587         snprintf(port, sizeof(port), "%d", ntohs(sin->sin_port));
2588         ast_update_realtime("iaxpeers", "name", peername, 
2589                 "ipaddr", ast_inet_ntoa(sin->sin_addr), "port", port, 
2590                 "regseconds", regseconds, NULL);
2591 }
2592
2593 struct create_addr_info {
2594         int capability;
2595         unsigned int flags;
2596         int maxtime;
2597         int encmethods;
2598         int found;
2599         int sockfd;
2600         int adsi;
2601         char username[80];
2602         char secret[80];
2603         char outkey[80];
2604         char timezone[80];
2605         char prefs[32];
2606         char context[AST_MAX_CONTEXT];
2607         char peercontext[AST_MAX_CONTEXT];
2608         char mohinterpret[MAX_MUSICCLASS];
2609         char mohsuggest[MAX_MUSICCLASS];
2610 };
2611
2612 static int create_addr(const char *peername, struct sockaddr_in *sin, struct create_addr_info *cai)
2613 {
2614         struct ast_hostent ahp;
2615         struct hostent *hp;
2616         struct iax2_peer *peer;
2617
2618         ast_clear_flag(cai, IAX_SENDANI | IAX_TRUNK);
2619         cai->sockfd = defaultsockfd;
2620         cai->maxtime = 0;
2621         sin->sin_family = AF_INET;
2622
2623         if (!(peer = find_peer(peername, 1))) {
2624                 cai->found = 0;
2625
2626                 hp = ast_gethostbyname(peername, &ahp);
2627                 if (hp) {
2628                         memcpy(&sin->sin_addr, hp->h_addr, sizeof(sin->sin_addr));
2629                         sin->sin_port = htons(IAX_DEFAULT_PORTNO);
2630                         /* use global iax prefs for unknown peer/user */
2631                         ast_codec_pref_convert(&prefs, cai->prefs, sizeof(cai->prefs), 1);
2632                         return 0;
2633                 } else {
2634                         ast_log(LOG_WARNING, "No such host: %s\n", peername);
2635                         return -1;
2636                 }
2637         }
2638
2639         cai->found = 1;
2640         
2641         /* if the peer has no address (current or default), return failure */
2642         if (!(peer->addr.sin_addr.s_addr || peer->defaddr.sin_addr.s_addr)) {
2643                 if (ast_test_flag(peer, IAX_TEMPONLY))
2644                         destroy_peer(peer);
2645                 return -1;
2646         }
2647
2648         /* if the peer is being monitored and is currently unreachable, return failure */
2649         if (peer->maxms && ((peer->lastms > peer->maxms) || (peer->lastms < 0))) {
2650                 if (ast_test_flag(peer, IAX_TEMPONLY))
2651                         destroy_peer(peer);
2652                 return -1;
2653         }
2654
2655         ast_copy_flags(cai, peer, IAX_SENDANI | IAX_TRUNK | IAX_NOTRANSFER | IAX_TRANSFERMEDIA | IAX_USEJITTERBUF | IAX_FORCEJITTERBUF);
2656         cai->maxtime = peer->maxms;
2657         cai->capability = peer->capability;
2658         cai->encmethods = peer->encmethods;
2659         cai->sockfd = peer->sockfd;
2660         cai->adsi = peer->adsi;
2661         ast_codec_pref_convert(&peer->prefs, cai->prefs, sizeof(cai->prefs), 1);
2662         ast_copy_string(cai->context, peer->context, sizeof(cai->context));
2663         ast_copy_string(cai->peercontext, peer->peercontext, sizeof(cai->peercontext));
2664         ast_copy_string(cai->username, peer->username, sizeof(cai->username));
2665         ast_copy_string(cai->timezone, peer->zonetag, sizeof(cai->timezone));
2666         ast_copy_string(cai->outkey, peer->outkey, sizeof(cai->outkey));
2667         ast_copy_string(cai->mohinterpret, peer->mohinterpret, sizeof(cai->mohinterpret));
2668         ast_copy_string(cai->mohsuggest, peer->mohsuggest, sizeof(cai->mohsuggest));
2669         if (ast_strlen_zero(peer->dbsecret)) {
2670                 ast_copy_string(cai->secret, peer->secret, sizeof(cai->secret));
2671         } else {
2672                 char *family;
2673                 char *key = NULL;
2674
2675                 family = ast_strdupa(peer->dbsecret);
2676                 key = strchr(family, '/');
2677                 if (key)
2678                         *key++ = '\0';
2679                 if (!key || ast_db_get(family, key, cai->secret, sizeof(cai->secret))) {
2680                         ast_log(LOG_WARNING, "Unable to retrieve database password for family/key '%s'!\n", peer->dbsecret);
2681                         if (ast_test_flag(peer, IAX_TEMPONLY))
2682                                 destroy_peer(peer);
2683                         return -1;
2684                 }
2685         }
2686
2687         if (peer->addr.sin_addr.s_addr) {
2688                 sin->sin_addr = peer->addr.sin_addr;
2689                 sin->sin_port = peer->addr.sin_port;
2690         } else {
2691                 sin->sin_addr = peer->defaddr.sin_addr;
2692                 sin->sin_port = peer->defaddr.sin_port;
2693         }
2694
2695         if (ast_test_flag(peer, IAX_TEMPONLY))
2696                 destroy_peer(peer);
2697
2698         return 0;
2699 }
2700
2701 static void __auto_congest(void *nothing)
2702 {
2703         int callno = PTR_TO_CALLNO(nothing);
2704         struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_CONGESTION };
2705         ast_mutex_lock(&iaxsl[callno]);
2706         if (iaxs[callno]) {
2707                 iaxs[callno]->initid = -1;
2708                 iax2_queue_frame(callno, &f);
2709                 ast_log(LOG_NOTICE, "Auto-congesting call due to slow response\n");
2710         }
2711         ast_mutex_unlock(&iaxsl[callno]);
2712 }
2713
2714 static int auto_congest(void *data)
2715 {
2716 #ifdef SCHED_MULTITHREADED
2717         if (schedule_action(__auto_congest, data))
2718 #endif          
2719                 __auto_congest(data);
2720         return 0;
2721 }
2722
2723 static unsigned int iax2_datetime(const char *tz)
2724 {
2725         time_t t;
2726         struct tm tm;
2727         unsigned int tmp;
2728         time(&t);
2729         localtime_r(&t, &tm);
2730         if (!ast_strlen_zero(tz))
2731                 ast_localtime(&t, &tm, tz);
2732         tmp  = (tm.tm_sec >> 1) & 0x1f;                 /* 5 bits of seconds */
2733         tmp |= (tm.tm_min & 0x3f) << 5;                 /* 6 bits of minutes */
2734         tmp |= (tm.tm_hour & 0x1f) << 11;               /* 5 bits of hours */
2735         tmp |= (tm.tm_mday & 0x1f) << 16;               /* 5 bits of day of month */
2736         tmp |= ((tm.tm_mon + 1) & 0xf) << 21;           /* 4 bits of month */
2737         tmp |= ((tm.tm_year - 100) & 0x7f) << 25;       /* 7 bits of year */
2738         return tmp;
2739 }
2740
2741 struct parsed_dial_string {
2742         char *username;
2743         char *password;
2744         char *key;
2745         char *peer;
2746         char *port;
2747         char *exten;
2748         char *context;
2749         char *options;
2750 };
2751
2752 /*!
2753  * \brief Parses an IAX dial string into its component parts.
2754  * \param data the string to be parsed
2755  * \param pds pointer to a \c struct \c parsed_dial_string to be filled in
2756  * \return nothing
2757  *
2758  * This function parses the string and fills the structure
2759  * with pointers to its component parts. The input string
2760  * will be modified.
2761  *
2762  * \note This function supports both plaintext passwords and RSA
2763  * key names; if the password string is formatted as '[keyname]',
2764  * then the keyname will be placed into the key field, and the
2765  * password field will be set to NULL.
2766  *
2767  * \note The dial string format is:
2768  *       [username[:password]@]peer[:port][/exten[@@context]][/options]
2769  */
2770 static void parse_dial_string(char *data, struct parsed_dial_string *pds)
2771 {
2772         if (ast_strlen_zero(data))
2773                 return;
2774
2775         pds->peer = strsep(&data, "/");
2776         pds->exten = strsep(&data, "/");
2777         pds->options = data;
2778
2779         if (pds->exten) {
2780                 data = pds->exten;
2781                 pds->exten = strsep(&data, "@");
2782                 pds->context = data;
2783         }
2784
2785         if (strchr(pds->peer, '@')) {
2786                 data = pds->peer;
2787                 pds->username = strsep(&data, "@");
2788                 pds->peer = data;
2789         }
2790
2791         if (pds->username) {
2792                 data = pds->username;
2793                 pds->username = strsep(&data, ":");
2794                 pds->password = data;
2795         }
2796
2797         data = pds->peer;
2798         pds->peer = strsep(&data, ":");
2799         pds->port = data;
2800
2801         /* check for a key name wrapped in [] in the secret position, if found,
2802            move it to the key field instead
2803         */
2804         if (pds->password && (pds->password[0] == '[')) {
2805                 pds->key = ast_strip_quoted(pds->password, "[", "]");
2806                 pds->password = NULL;
2807         }
2808 }
2809
2810 static int iax2_call(struct ast_channel *c, char *dest, int timeout)
2811 {
2812         struct sockaddr_in sin;
2813         char *l=NULL, *n=NULL, *tmpstr;
2814         struct iax_ie_data ied;
2815         char *defaultrdest = "s";
2816         unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
2817         struct parsed_dial_string pds;
2818         struct create_addr_info cai;
2819
2820         if ((c->_state != AST_STATE_DOWN) && (c->_state != AST_STATE_RESERVED)) {
2821                 ast_log(LOG_WARNING, "Channel is already in use (%s)?\n", c->name);
2822                 return -1;
2823         }
2824
2825         memset(&cai, 0, sizeof(cai));
2826         cai.encmethods = iax2_encryption;
2827
2828         memset(&pds, 0, sizeof(pds));
2829         tmpstr = ast_strdupa(dest);
2830         parse_dial_string(tmpstr, &pds);
2831
2832         if (!pds.exten)
2833                 pds.exten = defaultrdest;
2834
2835         if (create_addr(pds.peer, &sin, &cai)) {
2836                 ast_log(LOG_WARNING, "No address associated with '%s'\n", pds.peer);
2837                 return -1;
2838         }
2839
2840         if (!pds.username && !ast_strlen_zero(cai.username))
2841                 pds.username = cai.username;
2842         if (!pds.password && !ast_strlen_zero(cai.secret))
2843                 pds.password = cai.secret;
2844         if (!pds.key && !ast_strlen_zero(cai.outkey))
2845                 pds.key = cai.outkey;
2846         if (!pds.context && !ast_strlen_zero(cai.peercontext))
2847                 pds.context = cai.peercontext;
2848
2849         /* Keep track of the context for outgoing calls too */
2850         ast_copy_string(c->context, cai.context, sizeof(c->context));
2851
2852         if (pds.port)
2853                 sin.sin_port = htons(atoi(pds.port));
2854
2855         l = c->cid.cid_num;
2856         n = c->cid.cid_name;
2857
2858         /* Now build request */ 
2859         memset(&ied, 0, sizeof(ied));
2860
2861         /* On new call, first IE MUST be IAX version of caller */
2862         iax_ie_append_short(&ied, IAX_IE_VERSION, IAX_PROTO_VERSION);
2863         iax_ie_append_str(&ied, IAX_IE_CALLED_NUMBER, pds.exten);
2864         if (pds.options && strchr(pds.options, 'a')) {
2865                 /* Request auto answer */
2866                 iax_ie_append(&ied, IAX_IE_AUTOANSWER);
2867         }
2868
2869         iax_ie_append_str(&ied, IAX_IE_CODEC_PREFS, cai.prefs);
2870
2871         if (l) {
2872                 iax_ie_append_str(&ied, IAX_IE_CALLING_NUMBER, l);
2873                 iax_ie_append_byte(&ied, IAX_IE_CALLINGPRES, c->cid.cid_pres);
2874         } else {
2875                 if (n)
2876                         iax_ie_append_byte(&ied, IAX_IE_CALLINGPRES, c->cid.cid_pres);
2877                 else
2878                         iax_ie_append_byte(&ied, IAX_IE_CALLINGPRES, AST_PRES_NUMBER_NOT_AVAILABLE);
2879         }
2880
2881         iax_ie_append_byte(&ied, IAX_IE_CALLINGTON, c->cid.cid_ton);
2882         iax_ie_append_short(&ied, IAX_IE_CALLINGTNS, c->cid.cid_tns);
2883
2884         if (n)
2885                 iax_ie_append_str(&ied, IAX_IE_CALLING_NAME, n);
2886         if (ast_test_flag(iaxs[callno], IAX_SENDANI) && c->cid.cid_ani)
2887                 iax_ie_append_str(&ied, IAX_IE_CALLING_ANI, c->cid.cid_ani);
2888
2889         if (!ast_strlen_zero(c->language))
2890                 iax_ie_append_str(&ied, IAX_IE_LANGUAGE, c->language);
2891         if (!ast_strlen_zero(c->cid.cid_dnid))
2892                 iax_ie_append_str(&ied, IAX_IE_DNID, c->cid.cid_dnid);
2893         if (!ast_strlen_zero(c->cid.cid_rdnis))
2894                 iax_ie_append_str(&ied, IAX_IE_RDNIS, c->cid.cid_rdnis);
2895
2896         if (pds.context)
2897                 iax_ie_append_str(&ied, IAX_IE_CALLED_CONTEXT, pds.context);
2898
2899         if (pds.username)
2900                 iax_ie_append_str(&ied, IAX_IE_USERNAME, pds.username);
2901
2902         if (cai.encmethods)
2903                 iax_ie_append_short(&ied, IAX_IE_ENCRYPTION, cai.encmethods);
2904
2905         ast_mutex_lock(&iaxsl[callno]);
2906
2907         if (!ast_strlen_zero(c->context))
2908                 ast_string_field_set(iaxs[callno], context, c->context);
2909
2910         if (pds.username)
2911                 ast_string_field_set(iaxs[callno], username, pds.username);
2912
2913         iaxs[callno]->encmethods = cai.encmethods;
2914
2915         iaxs[callno]->adsi = cai.adsi;
2916         
2917         ast_string_field_set(iaxs[callno], mohinterpret, cai.mohinterpret);
2918         ast_string_field_set(iaxs[callno], mohsuggest, cai.mohsuggest);
2919
2920         if (pds.key)
2921                 ast_string_field_set(iaxs[callno], outkey, pds.key);
2922         if (pds.password)
2923                 ast_string_field_set(iaxs[callno], secret, pds.password);
2924
2925         iax_ie_append_int(&ied, IAX_IE_FORMAT, c->nativeformats);
2926         iax_ie_append_int(&ied, IAX_IE_CAPABILITY, iaxs[callno]->capability);
2927         iax_ie_append_short(&ied, IAX_IE_ADSICPE, c->adsicpe);
2928         iax_ie_append_int(&ied, IAX_IE_DATETIME, iax2_datetime(cai.timezone));
2929
2930         if (iaxs[callno]->maxtime) {
2931                 /* Initialize pingtime and auto-congest time */
2932                 iaxs[callno]->pingtime = iaxs[callno]->maxtime / 2;
2933                 iaxs[callno]->initid = ast_sched_add(sched, iaxs[callno]->maxtime * 2, auto_congest, CALLNO_TO_PTR(callno));
2934         } else if (autokill) {
2935                 iaxs[callno]->pingtime = autokill / 2;
2936                 iaxs[callno]->initid = ast_sched_add(sched, autokill * 2, auto_congest, CALLNO_TO_PTR(callno));
2937         }
2938
2939         /* send the command using the appropriate socket for this peer */
2940         iaxs[callno]->sockfd = cai.sockfd;
2941
2942         /* Transmit the string in a "NEW" request */
2943         send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_NEW, 0, ied.buf, ied.pos, -1);
2944
2945         ast_mutex_unlock(&iaxsl[callno]);
2946         ast_setstate(c, AST_STATE_RINGING);
2947         
2948         return 0;
2949 }
2950
2951 static int iax2_hangup(struct ast_channel *c) 
2952 {
2953         unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
2954         int alreadygone;
2955         struct iax_ie_data ied;
2956         memset(&ied, 0, sizeof(ied));
2957         ast_mutex_lock(&iaxsl[callno]);
2958         if (callno && iaxs[callno]) {
2959                 if (option_debug)
2960                         ast_log(LOG_DEBUG, "We're hanging up %s now...\n", c->name);
2961                 alreadygone = ast_test_flag(iaxs[callno], IAX_ALREADYGONE);
2962                 /* Send the hangup unless we have had a transmission error or are already gone */
2963                 iax_ie_append_byte(&ied, IAX_IE_CAUSECODE, (unsigned char)c->hangupcause);
2964                 if (!iaxs[callno]->error && !alreadygone) 
2965                         send_command_final(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_HANGUP, 0, ied.buf, ied.pos, -1);
2966                 /* Explicitly predestroy it */
2967                 iax2_predestroy(callno);
2968                 /* If we were already gone to begin with, destroy us now */
2969                 if (alreadygone) {
2970                         if (option_debug)
2971                                 ast_log(LOG_DEBUG, "Really destroying %s now...\n", c->name);
2972                         iax2_destroy(callno);
2973                 }
2974         }
2975         ast_mutex_unlock(&iaxsl[callno]);
2976         if (option_verbose > 2) 
2977                 ast_verbose(VERBOSE_PREFIX_3 "Hungup '%s'\n", c->name);
2978         return 0;
2979 }
2980
2981 static int iax2_setoption(struct ast_channel *c, int option, void *data, int datalen)
2982 {
2983         struct ast_option_header *h;
2984         int res;
2985
2986         switch (option) {
2987         case AST_OPTION_TXGAIN:
2988         case AST_OPTION_RXGAIN:
2989                 /* these two cannot be sent, because they require a result */
2990                 errno = ENOSYS;
2991                 return -1;
2992         default:
2993                 if (!(h = ast_malloc(datalen + sizeof(*h))))
2994                         return -1;
2995
2996                 h->flag = AST_OPTION_FLAG_REQUEST;
2997                 h->option = htons(option);
2998                 memcpy(h->data, data, datalen);
2999                 res = send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_CONTROL,
3000                                           AST_CONTROL_OPTION, 0, (unsigned char *) h,
3001                                           datalen + sizeof(*h), -1);
3002                 free(h);
3003                 return res;
3004         }
3005 }
3006
3007 static struct ast_frame *iax2_read(struct ast_channel *c) 
3008 {
3009         ast_log(LOG_NOTICE, "I should never be called!\n");
3010         return &ast_null_frame;
3011 }
3012
3013 static int iax2_start_transfer(unsigned short callno0, unsigned short callno1, int mediaonly)
3014 {
3015         int res;
3016         struct iax_ie_data ied0;
3017         struct iax_ie_data ied1;
3018         unsigned int transferid = (unsigned int)ast_random();
3019         memset(&ied0, 0, sizeof(ied0));
3020         iax_ie_append_addr(&ied0, IAX_IE_APPARENT_ADDR, &iaxs[callno1]->addr);
3021         iax_ie_append_short(&ied0, IAX_IE_CALLNO, iaxs[callno1]->peercallno);
3022         iax_ie_append_int(&ied0, IAX_IE_TRANSFERID, transferid);
3023
3024         memset(&ied1, 0, sizeof(ied1));
3025         iax_ie_append_addr(&ied1, IAX_IE_APPARENT_ADDR, &iaxs[callno0]->addr);
3026         iax_ie_append_short(&ied1, IAX_IE_CALLNO, iaxs[callno0]->peercallno);
3027         iax_ie_append_int(&ied1, IAX_IE_TRANSFERID, transferid);
3028         
3029         res = send_command(iaxs[callno0], AST_FRAME_IAX, IAX_COMMAND_TXREQ, 0, ied0.buf, ied0.pos, -1);
3030         if (res)
3031                 return -1;
3032         res = send_command(iaxs[callno1], AST_FRAME_IAX, IAX_COMMAND_TXREQ, 0, ied1.buf, ied1.pos, -1);
3033         if (res)
3034                 return -1;
3035         iaxs[callno0]->transferring = mediaonly ? TRANSFER_MBEGIN : TRANSFER_BEGIN;
3036         iaxs[callno1]->transferring = mediaonly ? TRANSFER_MBEGIN : TRANSFER_BEGIN;
3037         return 0;
3038 }
3039
3040 static void lock_both(unsigned short callno0, unsigned short callno1)
3041 {
3042         ast_mutex_lock(&iaxsl[callno0]);
3043         while (ast_mutex_trylock(&iaxsl[callno1])) {
3044                 ast_mutex_unlock(&iaxsl[callno0]);
3045                 usleep(10);
3046                 ast_mutex_lock(&iaxsl[callno0]);
3047         }
3048 }
3049
3050 static void unlock_both(unsigned short callno0, unsigned short callno1)
3051 {
3052         ast_mutex_unlock(&iaxsl[callno1]);
3053         ast_mutex_unlock(&iaxsl[callno0]);
3054 }
3055
3056 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)
3057 {
3058         struct ast_channel *cs[3];
3059         struct ast_channel *who, *other;
3060         int to = -1;
3061         int res = -1;
3062         int transferstarted=0;
3063         struct ast_frame *f;
3064         unsigned short callno0 = PTR_TO_CALLNO(c0->tech_pvt);
3065         unsigned short callno1 = PTR_TO_CALLNO(c1->tech_pvt);
3066         struct timeval waittimer = {0, 0}, tv;
3067
3068         lock_both(callno0, callno1);
3069         /* Put them in native bridge mode */
3070         if (!flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1)) {
3071                 iaxs[callno0]->bridgecallno = callno1;
3072                 iaxs[callno1]->bridgecallno = callno0;
3073         }
3074         unlock_both(callno0, callno1);
3075
3076         /* If not, try to bridge until we can execute a transfer, if we can */
3077         cs[0] = c0;
3078         cs[1] = c1;
3079         for (/* ever */;;) {
3080                 /* Check in case we got masqueraded into */
3081                 if ((c0->tech != &iax2_tech) || (c1->tech != &iax2_tech)) {
3082                         if (option_verbose > 2)
3083                                 ast_verbose(VERBOSE_PREFIX_3 "Can't masquerade, we're different...\n");
3084                         /* Remove from native mode */
3085                         if (c0->tech == &iax2_tech) {
3086                                 ast_mutex_lock(&iaxsl[callno0]);
3087                                 iaxs[callno0]->bridgecallno = 0;
3088                                 ast_mutex_unlock(&iaxsl[callno0]);
3089                         }
3090                         if (c1->tech == &iax2_tech) {
3091                                 ast_mutex_lock(&iaxsl[callno1]);
3092                                 iaxs[callno1]->bridgecallno = 0;
3093                                 ast_mutex_unlock(&iaxsl[callno1]);
3094                         }
3095                         return AST_BRIDGE_FAILED_NOWARN;
3096                 }
3097                 if (c0->nativeformats != c1->nativeformats) {
3098                         if (option_verbose > 2) {
3099                                 char buf0[255];
3100                                 char buf1[255];
3101                                 ast_getformatname_multiple(buf0, sizeof(buf0) -1, c0->nativeformats);
3102                                 ast_getformatname_multiple(buf1, sizeof(buf1) -1, c1->nativeformats);
3103                                 ast_verbose(VERBOSE_PREFIX_3 "Operating with different codecs %d[%s] %d[%s] , can't native bridge...\n", c0->nativeformats, buf0, c1->nativeformats, buf1);
3104                         }
3105                         /* Remove from native mode */
3106                         lock_both(callno0, callno1);
3107                         iaxs[callno0]->bridgecallno = 0;
3108                         iaxs[callno1]->bridgecallno = 0;
3109                         unlock_both(callno0, callno1);
3110                         return AST_BRIDGE_FAILED_NOWARN;
3111                 }
3112                 /* check if transfered and if we really want native bridging */
3113                 if (!transferstarted && !ast_test_flag(iaxs[callno0], IAX_NOTRANSFER) && !ast_test_flag(iaxs[callno1], IAX_NOTRANSFER)) {
3114                         /* Try the transfer */
3115                         if (iax2_start_transfer(callno0, callno1, (flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1)) ||
3116                                                         ast_test_flag(iaxs[callno0], IAX_TRANSFERMEDIA) | ast_test_flag(iaxs[callno1], IAX_TRANSFERMEDIA)))
3117                                 ast_log(LOG_WARNING, "Unable to start the transfer\n");
3118                         transferstarted = 1;
3119                 }
3120                 if ((iaxs[callno0]->transferring == TRANSFER_RELEASED) && (iaxs[callno1]->transferring == TRANSFER_RELEASED)) {
3121                         /* Call has been transferred.  We're no longer involved */
3122                         gettimeofday(&tv, NULL);
3123                         if (ast_tvzero(waittimer)) {
3124                                 waittimer = tv;
3125                         } else if (tv.tv_sec - waittimer.tv_sec > IAX_LINGER_TIMEOUT) {
3126                                 c0->_softhangup |= AST_SOFTHANGUP_DEV;
3127                                 c1->_softhangup |= AST_SOFTHANGUP_DEV;
3128                                 *fo = NULL;
3129                                 *rc = c0;
3130                                 res = AST_BRIDGE_COMPLETE;
3131                                 break;
3132                         }
3133                 }
3134                 to = 1000;
3135                 who = ast_waitfor_n(cs, 2, &to);
3136                 if (timeoutms > -1) {
3137                         timeoutms -= (1000 - to);
3138                         if (timeoutms < 0)
3139                                 timeoutms = 0;
3140                 }
3141                 if (!who) {
3142                         if (!timeoutms) {
3143                                 res = AST_BRIDGE_RETRY;
3144                                 break;
3145                         }
3146                         if (ast_check_hangup(c0) || ast_check_hangup(c1)) {
3147                                 res = AST_BRIDGE_FAILED;
3148                                 break;
3149                         }
3150                         continue;
3151                 }
3152                 f = ast_read(who);
3153                 if (!f) {
3154                         *fo = NULL;
3155                         *rc = who;
3156                         res = AST_BRIDGE_COMPLETE;
3157                         break;
3158                 }
3159                 if ((f->frametype == AST_FRAME_CONTROL) && !(flags & AST_BRIDGE_IGNORE_SIGS)) {
3160                         *fo = f;
3161                         *rc = who;
3162                         res =  AST_BRIDGE_COMPLETE;
3163                         break;
3164                 }
3165                 other = (who == c0) ? c1 : c0;  /* the 'other' channel */
3166                 if ((f->frametype == AST_FRAME_VOICE) ||