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