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