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