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