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