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