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