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