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