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