Sun Mar 16 07:00:01 CET 2003
[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, Digium
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 <arpa/inet.h>
35 #include <sys/socket.h>
36 #include <netinet/in.h>
37 #include <netinet/ip.h>
38 #include <sys/time.h>
39 #include <sys/signal.h>
40 #include <stdlib.h>
41 #include <stdio.h>
42 #include <string.h>
43 #include <errno.h>
44 #include <unistd.h>
45 #include <netdb.h>
46 #include <fcntl.h>
47 #ifdef IAX_TRUNKING
48 #include <sys/ioctl.h>
49 #include <linux/zaptel.h>
50 #endif
51
52 #include "iax2.h"
53
54 /*
55  * Uncomment to try experimental IAX bridge optimization,
56  * designed to reduce latency when IAX calls cannot
57  * be trasnferred
58  */
59
60 #define BRIDGE_OPTIMIZATION 
61
62
63 #define DEFAULT_RETRY_TIME 1000
64 #define MEMORY_SIZE 100
65 #define DEFAULT_DROP 3
66 /* Flag to use with trunk calls, keeping these calls high up.  It halves our effective use
67    but keeps the division between trunked and non-trunked better. */
68 #define TRUNK_CALL_START        0x4000
69
70 #define DEBUG_SUPPORT
71
72 #define MIN_REUSE_TIME          60      /* Don't reuse a call number within 60 seconds */
73
74 /* Sample over last 100 units to determine historic jitter */
75 #define GAMMA (0.01)
76
77 static char *desc = "Inter Asterisk eXchange (Ver 2)";
78 static char *tdesc = "Inter Asterisk eXchange Driver (Ver 2)";
79 static char *type = "IAX2";
80
81 static char context[80] = "default";
82
83 static int max_retries = 4;
84 static int ping_time = 20;
85 static int lagrq_time = 10;
86 static int maxtrunkcall = TRUNK_CALL_START;
87 static int maxnontrunkcall = 1;
88 static int maxjitterbuffer=3000;
89 static int trunkfreq = 20;
90
91 static int iaxdefaultdpcache=10 * 60;   /* Cache dialplan entries for 10 minutes by default */
92
93 static int iaxdefaulttimeout = 5;               /* Default to wait no more than 5 seconds for a reply to come back */
94
95 static int netsocket = -1;
96
97 static int tos = 0;
98
99 static int expirey = AST_DEFAULT_REG_EXPIRE;
100
101 static int timingfd = -1;                               /* Timing file descriptor */
102
103 static int usecnt;
104 static pthread_mutex_t usecnt_lock = AST_MUTEX_INITIALIZER;
105
106 int (*regfunk)(char *username, int onoff) = NULL;
107
108 /* Ethernet, etc */
109 #define IAX_CAPABILITY_FULLBANDWIDTH    0xFFFF
110 /* T1, maybe ISDN */
111 #define IAX_CAPABILITY_MEDBANDWIDTH     (IAX_CAPABILITY_FULLBANDWIDTH & \
112                                                                         ~AST_FORMAT_SLINEAR & \
113                                                                         ~AST_FORMAT_ULAW & \
114                                                                         ~AST_FORMAT_ALAW) 
115 /* A modem */
116 #define IAX_CAPABILITY_LOWBANDWIDTH             (IAX_CAPABILITY_MEDBANDWIDTH & \
117                                                                         ~AST_FORMAT_MP3 & \
118                                                                         ~AST_FORMAT_ADPCM)
119
120 #define IAX_CAPABILITY_LOWFREE          (IAX_CAPABILITY_LOWBANDWIDTH & \
121                                                                          ~AST_FORMAT_G723_1)
122
123
124 #define DEFAULT_MAXMS           2000            /* Must be faster than 2 seconds by default */
125 #define DEFAULT_FREQ_OK         60 * 1000               /* How often to check for the host to be up */
126 #define DEFAULT_FREQ_NOTOK      10 * 1000               /* How often to check, if the host is down... */
127
128 static  struct io_context *io;
129 static  struct sched_context *sched;
130
131 static int iax2_capability = IAX_CAPABILITY_FULLBANDWIDTH;
132
133 static int iax2_dropcount = DEFAULT_DROP;
134
135 static int use_jitterbuffer = 1;
136
137 static int iaxdebug = 0;
138
139 static char accountcode[20];
140 static int amaflags = 0;
141
142 static pthread_t netthreadid;
143
144 #define IAX_STATE_STARTED               (1 << 0)
145 #define IAX_STATE_AUTHENTICATED (1 << 1)
146 #define IAX_STATE_TBD                   (1 << 2)
147
148 struct iax2_context {
149         char context[AST_MAX_EXTENSION];
150         struct iax2_context *next;
151 };
152
153 struct iax2_user {
154         char name[80];
155         char secret[80];
156         int authmethods;
157         char accountcode[20];
158         char inkeys[80];                                /* Key(s) this user can use to authenticate to us */
159         int amaflags;
160         int hascallerid;
161         int trunk;
162         char callerid[AST_MAX_EXTENSION];
163         struct ast_ha *ha;
164         struct iax2_context *contexts;
165         struct iax2_user *next;
166 };
167
168 struct iax2_peer {
169         char name[80];
170         char username[80];              
171         char secret[80];
172         char outkey[80];                /* What key we use to talk to this peer */
173         char context[AST_MAX_EXTENSION];        /* Default context (for transfer really) */
174         char mailbox[AST_MAX_EXTENSION];        /* Mailbox */
175         struct sockaddr_in addr;
176         int formats;
177         struct in_addr mask;
178
179         /* Dynamic Registration fields */
180         int dynamic;                                    /* If this is a dynamic peer */
181         struct sockaddr_in defaddr;             /* Default address if there is one */
182         char challenge[80];                             /* Challenge used to authenticate the secret */
183         int authmethods;                                /* Authentication methods (IAX_AUTH_*) */
184         char inkeys[80];                                /* Key(s) this peer can use to authenticate to us */
185
186         int hascallerid;
187         /* Suggested caller id if registering */
188         char callerid[AST_MAX_EXTENSION];
189         /* Whether or not to send ANI */
190         int sendani;
191         int expire;                                             /* Schedule entry for expirey */
192         int expirey;                                    /* How soon to expire */
193         int capability;                                 /* Capability */
194         int delme;                                              /* I need to be deleted */
195         int trunk;                                              /* Treat as an IAX trunking */
196         struct timeval txtrunktime;             /* Transmit trunktime */
197         struct timeval rxtrunktime;             /* Receive trunktime */
198         struct timeval lasttxtime;              /* Last transmitted trunktime */
199         unsigned int lastsent;                  /* Last sent time */
200
201         /* Qualification */
202         int callno;                                     /* Call number of POKE request */
203         int pokeexpire;                                 /* When to expire poke */
204         int lastms;                                     /* How long last response took (in ms), or -1 for no response */
205         int maxms;                                      /* Max ms we will accept for the host to be up, 0 to not monitor */
206         
207         struct ast_ha *ha;
208         struct iax2_peer *next;
209 };
210
211 #define REG_STATE_UNREGISTERED 0
212 #define REG_STATE_REGSENT          1
213 #define REG_STATE_AUTHSENT         2
214 #define REG_STATE_REGISTERED   3
215 #define REG_STATE_REJECTED         4
216 #define REG_STATE_TIMEOUT          5
217 #define REG_STATE_NOAUTH           6
218
219 #define TRANSFER_NONE                   0
220 #define TRANSFER_BEGIN                  1
221 #define TRANSFER_READY                  2
222 #define TRANSFER_RELEASED               3
223 #define TRANSFER_PASSTHROUGH    4
224
225 struct iax2_registry {
226         struct sockaddr_in addr;                /* Who we connect to for registration purposes */
227         char username[80];
228         char secret[80];                        /* Password or key name in []'s */
229         char random[80];
230         int expire;                                             /* Sched ID of expiration */
231         int refresh;                                    /* How often to refresh */
232         int regstate;
233         int messages;                                   /* Message count */
234         int callno;                                             /* Associated call number if applicable */
235         struct sockaddr_in us;                  /* Who the server thinks we are */
236         struct iax2_registry *next;
237 };
238
239 struct iax2_registry *registrations;
240
241 /* Don't retry more frequently than every 10 ms, or less frequently than every 5 seconds */
242 #define MIN_RETRY_TIME  10
243 #define MAX_RETRY_TIME  10000
244 #define MAX_JITTER_BUFFER 50
245
246 #define MAX_TRUNKDATA   640             /* 40ms, uncompressed linear */
247
248 /* If we have more than this much excess real jitter buffer, srhink it. */
249 static int max_jitter_buffer = MAX_JITTER_BUFFER;
250
251 struct chan_iax2_pvt {
252         /* Pipes for communication.  pipe[1] belongs to the
253            network thread (write), and pipe[0] belongs to the individual 
254            channel (read) */
255         /* Whether or not we Quelch audio */
256         int quelch;
257         /* Last received voice format */
258         int voiceformat;
259         /* Last sent voice format */
260         int svoiceformat;
261         /* What we are capable of sending */
262         int capability;
263         /* Last received timestamp */
264         unsigned int last;
265         /* Last sent timestamp - never send the same timestamp twice in a single call */
266         unsigned int lastsent;
267         /* Ping time */
268         unsigned int pingtime;
269         /* Max time for initial response */
270         int maxtime;
271         /* Peer Address */
272         struct sockaddr_in addr;
273         /* Our call number */
274         unsigned short callno;
275         /* Peer callno */
276         unsigned short peercallno;
277         /* Peer selected format */
278         int peerformat;
279         /* Peer capability */
280         int peercapability;
281         /* timeval that we base our transmission on */
282         struct timeval offset;
283         /* timeval that we base our delivery on */
284         struct timeval rxcore;
285         /* Historical delivery time */
286         int history[MEMORY_SIZE];
287         /* Current base jitterbuffer */
288         int jitterbuffer;
289         /* Current jitter measure */
290         int jitter;
291         /* Historic jitter value */
292         int historicjitter;
293         /* LAG */
294         int lag;
295         /* Error, as discovered by the manager */
296         int error;
297         /* Owner if we have one */
298         struct ast_channel *owner;
299         /* What's our state? */
300         int state;
301         /* Expirey (optional) */
302         int expirey;
303         /* Next outgoing sequence number */
304         unsigned char oseqno;
305         /* Next sequence number they have not yet acknowledged */
306         unsigned char rseqno;
307         /* Next incoming sequence number */
308         unsigned char iseqno;
309         /* Last incoming sequence number we have acknowledged */
310         unsigned char aseqno;
311         /* Peer name */
312         char peer[80];
313         /* Default Context */
314         char context[80];
315         /* Caller ID if available */
316         char callerid[80];
317         /* Hidden Caller ID (i.e. ANI) if appropriate */
318         char ani[80];
319         /* Whether or not ani should be transmitted in addition to Caller*ID */
320         int sendani;
321         /* DNID */
322         char dnid[80];
323         /* Requested Extension */
324         char exten[AST_MAX_EXTENSION];
325         /* Expected Username */
326         char username[80];
327         /* Expected Secret */
328         char secret[80];
329         /* permitted authentication methods */
330         int authmethods;
331         /* MD5 challenge */
332         char challenge[10];
333         /* Public keys permitted keys for incoming authentication */
334         char inkeys[80];
335         /* Private key for outgoing authentication */
336         char outkey[80];
337         /* Preferred language */
338         char language[80];
339         /* Associated registry */
340         struct iax2_registry *reg;
341         /* Associated peer for poking */
342         struct iax2_peer *peerpoke;
343
344         /* Transferring status */
345         int transferring;
346         /* Already disconnected */
347         int alreadygone;
348         /* Who we are IAX transfering to */
349         struct sockaddr_in transfer;
350         /* What's the new call number for the transfer */
351         unsigned short transfercallno;
352
353         /* Status of knowledge of peer ADSI capability */
354         int peeradsicpe;
355         
356         /* Who we are bridged to */
357         unsigned short bridgecallno;
358         int pingid;                     /* Transmit PING request */
359         int lagid;                      /* Retransmit lag request */
360         int autoid;                     /* Auto hangup for Dialplan requestor */
361         int initid;                     /* Initial peer auto-congest ID (based on qualified peers) */
362         char dproot[AST_MAX_EXTENSION];
363         char accountcode[20];
364         int amaflags;
365         /* This is part of a trunk interface */
366         int trunk;
367         /* Trunk data and length */
368         unsigned char trunkdata[MAX_TRUNKDATA];
369         unsigned int trunkdatalen;
370         int trunkerror;
371         struct iax2_dpcache *dpentries;
372 };
373
374 #define DIRECTION_INGRESS 1
375 #define DIRECTION_OUTGRESS 2
376
377 struct ast_iax2_frame {
378         /* /Our/ call number */
379         unsigned short callno;
380         /* /Their/ call number */
381         unsigned short dcallno;
382         /* Start of raw frame (outgoing only) */
383         void *data;
384         /* Length of frame (outgoing only) */
385         int datalen;
386         /* How many retries so far? */
387         int retries;
388         /* Outgoing relative timestamp (ms) */
389         unsigned int ts;
390         /* How long to wait before retrying */
391         int retrytime;
392         /* Are we received out of order?  */
393         int outoforder;
394         /* Have we been sent at all yet? */
395         int sentyet;
396         /* Outgoing Packet sequence number */
397         int oseqno;
398         /* Next expected incoming packet sequence number */
399         int iseqno;
400         /* Non-zero if should be sent to transfer peer */
401         int transfer;
402         /* Non-zero if this is the final message */
403         int final;
404         /* Ingress or outgres */
405         int direction;
406         /* Retransmission ID */
407         int retrans;
408         /* Easy linking */
409         struct ast_iax2_frame *next;
410         struct ast_iax2_frame *prev;
411         /* Actual, isolated frame header */
412         struct ast_frame af;
413         unsigned char unused[AST_FRIENDLY_OFFSET];
414         unsigned char afdata[0];        /* Data for frame */
415 };
416
417 struct iax_ies {
418         char *called_number;
419         char *calling_number;
420         char *calling_ani;
421         char *calling_name;
422         char *called_context;
423         char *username;
424         char *password;
425         unsigned int capability;
426         unsigned int format;
427         char *language;
428         int version;
429         unsigned short adsicpe;
430         char *dnid;
431         unsigned int authmethods;
432         char *challenge;
433         char *md5_result;
434         char *rsa_result;
435         struct sockaddr_in *apparent_addr;
436         unsigned short refresh;
437         unsigned short dpstatus;
438         unsigned short callno;
439         char *cause;
440         unsigned char iax_unknown;
441         int msgcount;
442 };
443
444 struct iax_ie_data {
445         unsigned char buf[1024];
446         int pos;
447 };
448
449 static struct ast_iax2_queue {
450         struct ast_iax2_frame *head;
451         struct ast_iax2_frame *tail;
452         int count;
453         pthread_mutex_t lock;
454 } iaxq;
455
456 static struct ast_user_list {
457         struct iax2_user *users;
458         pthread_mutex_t lock;
459 } userl;
460
461 static struct ast_peer_list {
462         struct iax2_peer *peers;
463         pthread_mutex_t lock;
464 } peerl;
465
466 /* Extension exists */
467 #define CACHE_FLAG_EXISTS               (1 << 0)
468 /* Extension is non-existant */
469 #define CACHE_FLAG_NONEXISTANT  (1 << 1)
470 /* Extension can exist */
471 #define CACHE_FLAG_CANEXIST             (1 << 2)
472 /* Waiting to hear back response */
473 #define CACHE_FLAG_PENDING              (1 << 3)
474 /* Timed out */
475 #define CACHE_FLAG_TIMEOUT              (1 << 4)
476 /* Request transmitted */
477 #define CACHE_FLAG_TRANSMITTED  (1 << 5)
478 /* Timeout */
479 #define CACHE_FLAG_UNKNOWN              (1 << 6)
480 /* Matchmore */
481 #define CACHE_FLAG_MATCHMORE    (1 << 7)
482
483 static struct iax2_dpcache {
484         char peercontext[AST_MAX_EXTENSION];
485         char exten[AST_MAX_EXTENSION];
486         struct timeval orig;
487         struct timeval expirey;
488         int flags;
489         unsigned short callno;
490         int waiters[256];
491         struct iax2_dpcache *next;
492         struct iax2_dpcache *peer;      /* For linking in peers */
493 } *dpcache;
494
495 pthread_mutex_t dpcache_lock;
496
497 static void dump_addr(char *output, int maxlen, void *value, int len)
498 {
499         struct sockaddr_in sin;
500         if (len == sizeof(sin)) {
501                 memcpy(&sin, value, len);
502                 snprintf(output, maxlen, "IPV4 %s:%d", inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
503         } else {
504                 snprintf(output, maxlen, "Invalid Address");
505         }
506 }
507
508 static void dump_string(char *output, int maxlen, void *value, int len)
509 {
510         maxlen--;
511         if (maxlen > len)
512                 maxlen = len;
513         strncpy(output,value, maxlen);
514         output[maxlen] = '\0';
515 }
516
517 static void dump_int(char *output, int maxlen, void *value, int len)
518 {
519         if (len == sizeof(unsigned int))
520                 snprintf(output, maxlen, "%d", ntohl(*((unsigned int *)value)));
521         else
522                 snprintf(output, maxlen, "Invalid INT");
523 }
524
525 static void dump_short(char *output, int maxlen, void *value, int len)
526 {
527         if (len == sizeof(unsigned short))
528                 snprintf(output, maxlen, "%d", ntohs(*((unsigned short *)value)));
529         else
530                 snprintf(output, maxlen, "Invalid SHORT");
531 }
532
533 static void dump_byte(char *output, int maxlen, void *value, int len)
534 {
535         if (len == sizeof(unsigned char))
536                 snprintf(output, maxlen, "%d", ntohs(*((unsigned char *)value)));
537         else
538                 snprintf(output, maxlen, "Invalid BYTE");
539 }
540
541 static struct iax2_ie {
542         int ie;
543         char *name;
544         void (*dump)(char *output, int maxlen, void *value, int len);
545 } ies[] = {
546         { IAX_IE_CALLED_NUMBER, "CALLED NUMBER", dump_string },
547         { IAX_IE_CALLING_NUMBER, "CALLING NUMBER", dump_string },
548         { IAX_IE_CALLING_NUMBER, "ANI", dump_string },
549         { IAX_IE_CALLING_NAME, "CALLING NAME", dump_string },
550         { IAX_IE_CALLED_CONTEXT, "CALLED CONTEXT", dump_string },
551         { IAX_IE_USERNAME, "USERNAME", dump_string },
552         { IAX_IE_PASSWORD, "PASSWORD", dump_string },
553         { IAX_IE_CAPABILITY, "CAPABILITY", dump_int },
554         { IAX_IE_FORMAT, "FORMAT", dump_int },
555         { IAX_IE_LANGUAGE, "LANGUAGE", dump_string },
556         { IAX_IE_VERSION, "VERSION", dump_short },
557         { IAX_IE_ADSICPE, "ADSICPE", dump_short },
558         { IAX_IE_DNID, "DNID", dump_string },
559         { IAX_IE_AUTHMETHODS, "AUTHMETHODS", dump_short },
560         { IAX_IE_CHALLENGE, "CHALLENGE", dump_string },
561         { IAX_IE_MD5_RESULT, "MD5 RESULT", dump_string },
562         { IAX_IE_RSA_RESULT, "RSA RESULT", dump_string },
563         { IAX_IE_APPARENT_ADDR, "APPARENT ADDRESS", dump_addr },
564         { IAX_IE_REFRESH, "REFRESH", dump_short },
565         { IAX_IE_DPSTATUS, "DIALPLAN STATUS", dump_short },
566         { IAX_IE_CALLNO, "CALL NUMBER", dump_short },
567         { IAX_IE_CAUSE, "CAUSE", dump_string },
568         { IAX_IE_IAX_UNKNOWN, "UNKNOWN IAX CMD", dump_byte },
569         { IAX_IE_MSGCOUNT, "MESSAGE COUNT", dump_short },
570 };
571
572 static char *ie2str(int ie)
573 {
574         int x;
575         for (x=0;x<sizeof(ies) / sizeof(ies[0]); x++) {
576                 if (ies[x].ie == ie)
577                         return ies[x].name;
578         }
579         return "Unknown IE";
580 }
581
582 static void dump_ies(unsigned char *iedata, int len)
583 {
584         int ielen;
585         int ie;
586         int x;
587         int found;
588         char interp[80];
589         if (len < 2)
590                 return;
591         while(len > 2) {
592                 ie = iedata[0];
593                 ielen = iedata[1];
594                 if (ielen + 2> len) {
595                         ast_verbose("Total IE length of %d bytes exceeds remaining frame length of %d bytes\n", ielen + 2, len);
596                         return;
597                 }
598                 found = 0;
599                 for (x=0;x<sizeof(ies) / sizeof(ies[0]); x++) {
600                         if (ies[x].ie == ie) {
601                                 if (ies[x].dump) {
602                                         ies[x].dump(interp, sizeof(interp), iedata + 2, ielen);
603                                         ast_verbose("   %-15.15s : %s\n", ies[x].name, interp);
604                                 } else {
605                                         ast_verbose("   %-15.15s : Present\n", ies[x].name);
606                                 }
607                                 found++;
608                         }
609                 }
610                 if (!found)
611                         ast_verbose("   Unknown IE %d : Present\n", ie);
612                 iedata += (2 + ielen);
613                 len -= (2 + ielen);
614         }
615         ast_verbose("\n");
616 }
617
618 #ifdef DEBUG_SUPPORT
619 void showframe(struct ast_iax2_frame *f, struct ast_iax2_full_hdr *fhi, int rx, struct sockaddr_in *sin, int datalen)
620 {
621         char *frames[] = {
622                 "(0?)",
623                 "DTMF   ",
624                 "VOICE  ",
625                 "VIDEO  ",
626                 "CONTROL",
627                 "NULL   ",
628                 "IAX    ",
629                 "TEXT   ",
630                 "IMAGE  " };
631         char *iaxs[] = {
632                 "(0?)",
633                 "NEW    ",
634                 "PING   ",
635                 "PONG   ",
636                 "ACK    ",
637                 "HANGUP ",
638                 "REJECT ",
639                 "ACCEPT ",
640                 "AUTHREQ",
641                 "AUTHREP",
642                 "INVAL  ",
643                 "LAGRQ  ",
644                 "LAGRP  ",
645                 "REGREQ ",
646                 "REGAUTH",
647                 "REGACK ",
648                 "REGREJ ",
649                 "REGREL ",
650                 "VNAK   ",
651                 "DPREQ  ",
652                 "DPREP  ",
653                 "DIAL   ",
654                 "TXREQ  ",
655                 "TXCNT  ",
656                 "TXACC  ",
657                 "TXREADY",
658                 "TXREL  ",
659                 "TXREJ  ",
660                 "QUELCH ",
661                 "UNQULCH",
662                 "POKE",
663                 "PAGE",
664                 "MWI",
665                 "UNSUPPORTED",
666         };
667         char *cmds[] = {
668                 "(0?)",
669                 "HANGUP ",
670                 "RING   ",
671                 "RINGING",
672                 "ANSWER ",
673                 "BUSY   ",
674                 "TKOFFHK ",
675                 "OFFHOOK" };
676         struct ast_iax2_full_hdr *fh;
677         char retries[20];
678         char class2[20];
679         char subclass2[20];
680         char *class;
681         char *subclass;
682         if (f) {
683                 fh = f->data;
684                 snprintf(retries, sizeof(retries), "%03d", f->retries);
685         } else {
686                 fh = fhi;
687                 if (ntohs(fh->dcallno) & AST_FLAG_RETRANS)
688                         strcpy(retries, "Yes");
689                 else
690                         strcpy(retries, "No");
691         }
692         if (!(ntohs(fh->scallno) & AST_FLAG_FULL)) {
693                 /* Don't mess with mini-frames */
694                 return;
695         }
696         if (fh->type > sizeof(frames)/sizeof(char *)) {
697                 snprintf(class2, sizeof(class2), "(%d?)", fh->type);
698                 class = class2;
699         } else {
700                 class = frames[(int)fh->type];
701         }
702         if (fh->type == AST_FRAME_DTMF) {
703                 sprintf(subclass2, "%c", fh->csub);
704                 subclass = subclass2;
705         } else if (fh->type == AST_FRAME_IAX) {
706                 if (fh->csub >= sizeof(iaxs)/sizeof(iaxs[0])) {
707                         snprintf(subclass2, sizeof(subclass2), "(%d?)", fh->csub);
708                         subclass = subclass2;
709                 } else {
710                         subclass = iaxs[(int)fh->csub];
711                 }
712         } else if (fh->type == AST_FRAME_CONTROL) {
713                 if (fh->csub > sizeof(cmds)/sizeof(char *)) {
714                         snprintf(subclass2, sizeof(subclass2), "(%d?)", fh->csub);
715                         subclass = subclass2;
716                 } else {
717                         subclass = cmds[(int)fh->csub];
718                 }
719         } else {
720                 snprintf(subclass2, sizeof(subclass2), "%d", fh->csub);
721                 subclass = subclass2;
722         }
723         ast_verbose(
724 "%s-Frame Retry[%s] -- OSeqno: %3.3d ISeqno: %3.3d Type: %s Subclass: %s\n",
725         (rx ? "Rx" : "Tx"),
726         retries, fh->oseqno, fh->iseqno, class, subclass);
727                 fprintf(stderr,
728 "   Timestamp: %05dms  SCall: %5.5d  DCall: %5.5d [%s:%d]\n",
729         ntohl(fh->ts),
730         ntohs(fh->scallno) & ~AST_FLAG_FULL, ntohs(fh->dcallno) & ~AST_FLAG_RETRANS,
731                 inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
732         if (fh->type == AST_FRAME_IAX)
733                 dump_ies(fh->iedata, datalen);
734 }
735 #endif
736
737 /* XXX We probably should use a mutex when working with this XXX */
738 static struct chan_iax2_pvt *iaxs[AST_IAX2_MAX_CALLS];
739 static pthread_mutex_t iaxsl[AST_IAX2_MAX_CALLS];
740 static struct timeval lastused[AST_IAX2_MAX_CALLS];
741
742
743 static int send_command(struct chan_iax2_pvt *, char, int, unsigned int, char *, int, int);
744 static int send_command_immediate(struct chan_iax2_pvt *, char, int, unsigned int, char *, int, int);
745 static int send_command_final(struct chan_iax2_pvt *, char, int, unsigned int, char *, int, int);
746 static int send_command_transfer(struct chan_iax2_pvt *, char, int, unsigned int, char *, int);
747
748 static unsigned int calc_timestamp(struct chan_iax2_pvt *p, unsigned int ts);
749
750 static int send_ping(void *data)
751 {
752         int callno = (long)data;
753         /* Ping only if it's real, not if it's bridged */
754         if (iaxs[callno]) {
755 #ifdef BRIDGE_OPTIMIZATION
756                 if (!iaxs[callno]->bridgecallno)
757 #endif
758                         send_command(iaxs[callno], AST_FRAME_IAX, AST_IAX2_COMMAND_PING, 0, NULL, 0, -1);
759                 return 1;
760         } else
761                 return 0;
762 }
763
764 static int send_lagrq(void *data)
765 {
766         int callno = (long)data;
767         /* Ping only if it's real not if it's bridged */
768         if (iaxs[callno]) {
769 #ifdef BRIDGE_OPTIMIZATION
770                 if (!iaxs[callno]->bridgecallno)
771 #endif          
772                         send_command(iaxs[callno], AST_FRAME_IAX, AST_IAX2_COMMAND_LAGRQ, 0, NULL, 0, -1);
773                 return 1;
774         } else
775                 return 0;
776 }
777
778 static unsigned char compress_subclass(int subclass)
779 {
780         int x;
781         int power=-1;
782         /* If it's 128 or smaller, just return it */
783         if (subclass < AST_FLAG_SC_LOG)
784                 return subclass;
785         /* Otherwise find its power */
786         for (x = 0; x < AST_MAX_SHIFT; x++) {
787                 if (subclass & (1 << x)) {
788                         if (power > -1) {
789                                 ast_log(LOG_WARNING, "Can't compress subclass %d\n", subclass);
790                                 return 0;
791                         } else
792                                 power = x;
793                 }
794         }
795         return power | AST_FLAG_SC_LOG;
796 }
797
798 static int uncompress_subclass(unsigned char csub)
799 {
800         /* If the SC_LOG flag is set, return 2^csub otherwise csub */
801         if (csub & AST_FLAG_SC_LOG) {
802                 /* special case for 'compressed' -1 */
803                 if (csub == 0xff)
804                         return -1;
805                 else
806                         return 1 << (csub & ~AST_FLAG_SC_LOG & AST_MAX_SHIFT);
807         }
808         else
809                 return csub;
810 }
811
812 static struct chan_iax2_pvt *new_iax(void)
813 {
814         struct chan_iax2_pvt *tmp;
815         tmp = malloc(sizeof(struct chan_iax2_pvt));
816         if (tmp) {
817                 memset(tmp, 0, sizeof(struct chan_iax2_pvt));
818                 tmp->callno = 0;
819                 tmp->peercallno = 0;
820                 tmp->transfercallno = 0;
821                 tmp->bridgecallno = 0;
822                 tmp->pingid = -1;
823                 tmp->lagid = -1;
824                 tmp->autoid = -1;
825                 tmp->initid = -1;
826                 /* strncpy(tmp->context, context, sizeof(tmp->context)-1); */
827                 strncpy(tmp->exten, "s", sizeof(tmp->exten)-1);
828         }
829         return tmp;
830 }
831
832 static int get_samples(struct ast_frame *f)
833 {
834         int samples=0;
835         switch(f->subclass) {
836         case AST_FORMAT_G723_1:
837                 samples = 240 /* XXX Not necessarily true XXX */;
838                 break;
839         case AST_FORMAT_GSM:
840                 samples = 160 * (f->datalen / 33);
841                 break;
842         case AST_FORMAT_SLINEAR:
843                 samples = f->datalen / 2;
844                 break;
845         case AST_FORMAT_LPC10:
846                 samples = 22 * 8;
847                 samples += (((char *)(f->data))[7] & 0x1) * 8;
848                 break;
849         case AST_FORMAT_ULAW:
850                 samples = f->datalen;
851                 break;
852         case AST_FORMAT_ALAW:
853                 samples = f->datalen;
854                 break;
855         case AST_FORMAT_ADPCM:
856                 samples = f->datalen *2;
857                 break;
858         default:
859                 ast_log(LOG_WARNING, "Don't know how to calculate samples on %d packets\n", f->subclass);
860         }
861         return samples;
862 }
863
864 static int frames = 0;
865 static int iframes = 0;
866 static int oframes = 0;
867
868 static void ast_iax2_frame_wrap(struct ast_iax2_frame *fr, struct ast_frame *f)
869 {
870         fr->af.frametype = f->frametype;
871         fr->af.subclass = f->subclass;
872         fr->af.mallocd = 0;                             /* Our frame is static relative to the container */
873         fr->af.datalen = f->datalen;
874         fr->af.samples = f->samples;
875         fr->af.offset = AST_FRIENDLY_OFFSET;
876         fr->af.src = f->src;
877         fr->af.data = fr->afdata;
878         if (fr->af.datalen) 
879                 memcpy(fr->af.data, f->data, fr->af.datalen);
880 }
881
882 static struct ast_iax2_frame *ast_iax2_frame_new(int direction, int datalen)
883 {
884         struct ast_iax2_frame *fr;
885         fr = malloc(sizeof(struct ast_iax2_frame) + datalen);
886         if (fr) {
887                 fr->direction = direction;
888                 fr->retrans = -1;
889                 frames++;
890                 if (fr->direction == DIRECTION_INGRESS)
891                         iframes++;
892                 else
893                         oframes++;
894         }
895         return fr;
896 }
897
898 static void ast_iax2_frame_free(struct ast_iax2_frame *fr)
899 {
900         if (fr->retrans > -1)
901                 ast_sched_del(sched, fr->retrans);
902         if (fr->direction == DIRECTION_INGRESS)
903                 iframes--;
904         else if (fr->direction == DIRECTION_OUTGRESS)
905                 oframes--;
906         else {
907                 ast_log(LOG_WARNING, "Attempt to double free frame detected\n");
908                 CRASH;
909                 return;
910         }
911         fr->direction = 0;
912         free(fr);
913         frames--;
914 }
915
916 static struct ast_iax2_frame *iaxfrdup2(struct ast_iax2_frame *fr)
917 {
918         /* Malloc() a copy of a frame */
919         struct ast_iax2_frame *new = ast_iax2_frame_new(DIRECTION_INGRESS, fr->af.datalen);
920         if (new) {
921                 memcpy(new, fr, sizeof(struct ast_iax2_frame)); 
922                 ast_iax2_frame_wrap(new, &fr->af);
923                 new->data = NULL;
924                 new->datalen = 0;
925                 new->direction = DIRECTION_INGRESS;
926                 new->retrans = -1;
927         }
928         return new;
929 }
930
931 #define NEW_PREVENT 0
932 #define NEW_ALLOW       1
933 #define NEW_FORCE       2
934
935 static int match(struct sockaddr_in *sin, unsigned short callno, unsigned short dcallno, struct chan_iax2_pvt *cur)
936 {
937         if ((cur->addr.sin_addr.s_addr == sin->sin_addr.s_addr) &&
938                 (cur->addr.sin_port == sin->sin_port)) {
939                 /* This is the main host */
940                 if ((cur->peercallno == callno) ||
941                         ((dcallno == cur->callno) && !cur->peercallno)) {
942                         /* That's us.  Be sure we keep track of the peer call number */
943                         return 1;
944                 }
945         }
946         if ((cur->transfer.sin_addr.s_addr == sin->sin_addr.s_addr) &&
947             (cur->transfer.sin_port == sin->sin_port) && (cur->transferring)) {
948                 /* We're transferring */
949                 if (dcallno == cur->callno)
950                         return 1;
951         }
952         return 0;
953 }
954
955 static void update_max_trunk(void)
956 {
957         int max = TRUNK_CALL_START;
958         int x;
959         /* XXX Prolly don't need locks here XXX */
960         for (x=TRUNK_CALL_START;x<AST_IAX2_MAX_CALLS - 1; x++) {
961                 if (iaxs[x])
962                         max = x + 1;
963         }
964         maxtrunkcall = max;
965         if (option_debug)
966                 ast_log(LOG_DEBUG, "New max trunk callno is %d\n", max);
967 }
968
969 static void update_max_nontrunk(void)
970 {
971         int max = 1;
972         int x;
973         /* XXX Prolly don't need locks here XXX */
974         for (x=1;x<TRUNK_CALL_START - 1; x++) {
975                 if (iaxs[x])
976                         max = x + 1;
977         }
978         maxnontrunkcall = max;
979         if (option_debug)
980                 ast_log(LOG_DEBUG, "New max nontrunk callno is %d\n", max);
981 }
982
983 static int make_trunk(unsigned short callno, int locked)
984 {
985         int x;
986         int res= 0;
987         struct timeval now;
988         if (iaxs[callno]->oseqno) {
989                 ast_log(LOG_WARNING, "Can't make trunk once a call has started!\n");
990                 return -1;
991         }
992         if (callno & TRUNK_CALL_START) {
993                 ast_log(LOG_WARNING, "Call %d is already a trunk\n", callno);
994                 return -1;
995         }
996         gettimeofday(&now, NULL);
997         for (x=TRUNK_CALL_START;x<AST_IAX2_MAX_CALLS - 1; x++) {
998                 ast_pthread_mutex_lock(&iaxsl[x]);
999                 if (!iaxs[x] && ((now.tv_sec - lastused[x].tv_sec) > MIN_REUSE_TIME)) {
1000                         iaxs[x] = iaxs[callno];
1001                         iaxs[x]->callno = x;
1002                         iaxs[callno] = NULL;
1003                         /* Update the two timers that should have been started */
1004                         if (iaxs[x]->pingid > -1)
1005                                 ast_sched_del(sched, iaxs[x]->pingid);
1006                         if (iaxs[x]->lagid > -1)
1007                                 ast_sched_del(sched, iaxs[x]->lagid);
1008                         iaxs[x]->pingid = ast_sched_add(sched, ping_time * 1000, send_ping, (void *)x);
1009                         iaxs[x]->lagid = ast_sched_add(sched, lagrq_time * 1000, send_lagrq, (void *)x);
1010                         if (locked)
1011                                 ast_pthread_mutex_unlock(&iaxsl[callno]);
1012                         res = x;
1013                         if (!locked)
1014                                 ast_pthread_mutex_unlock(&iaxsl[x]);
1015                         break;
1016                 }
1017                 ast_pthread_mutex_unlock(&iaxsl[x]);
1018         }
1019         if (x >= AST_IAX2_MAX_CALLS - 1) {
1020                 ast_log(LOG_WARNING, "Unable to trunk call: Insufficient space\n");
1021                 return -1;
1022         }
1023         ast_log(LOG_DEBUG, "Made call %d into trunk call %d\n", callno, x);
1024         /* We move this call from a non-trunked to a trunked call */
1025         update_max_trunk();
1026         update_max_nontrunk();
1027         return res;
1028 }
1029
1030 static int find_callno(unsigned short callno, unsigned short dcallno, struct sockaddr_in *sin, int new)
1031 {
1032         int res = 0;
1033         int x;
1034         struct timeval now;
1035         if (new <= NEW_ALLOW) {
1036                 /* Look for an existing connection first */
1037                 for (x=1;(res < 1) && (x<maxnontrunkcall);x++) {
1038                         ast_pthread_mutex_lock(&iaxsl[x]);
1039                         if (iaxs[x]) {
1040                                 /* Look for an exact match */
1041                                 if (match(sin, callno, dcallno, iaxs[x])) {
1042                                         res = x;
1043                                 }
1044                         }
1045                         ast_pthread_mutex_unlock(&iaxsl[x]);
1046                 }
1047                 for (x=TRUNK_CALL_START;(res < 1) && (x<maxtrunkcall);x++) {
1048                         ast_pthread_mutex_lock(&iaxsl[x]);
1049                         if (iaxs[x]) {
1050                                 /* Look for an exact match */
1051                                 if (match(sin, callno, dcallno, iaxs[x])) {
1052                                         res = x;
1053                                 }
1054                         }
1055                         ast_pthread_mutex_unlock(&iaxsl[x]);
1056                 }
1057         }
1058         if ((res < 1) && (new >= NEW_ALLOW)) {
1059                 gettimeofday(&now, NULL);
1060                 for (x=1;x<TRUNK_CALL_START;x++) {
1061                         /* Find first unused call number that hasn't been used in a while */
1062                         ast_pthread_mutex_lock(&iaxsl[x]);
1063                         if (!iaxs[x] && ((now.tv_sec - lastused[x].tv_sec) > MIN_REUSE_TIME)) break;
1064                         ast_pthread_mutex_unlock(&iaxsl[x]);
1065                 }
1066                 /* We've still got lock held if we found a spot */
1067                 if (x >= TRUNK_CALL_START) {
1068                         ast_log(LOG_WARNING, "No more space\n");
1069                         return -1;
1070                 }
1071                 iaxs[x] = new_iax();
1072                 ast_pthread_mutex_unlock(&iaxsl[x]);
1073                 update_max_nontrunk();
1074                 if (iaxs[x]) {
1075                         if (option_debug)
1076                                 ast_log(LOG_DEBUG, "Creating new call structure %d\n", x);
1077                         iaxs[x]->addr.sin_port = sin->sin_port;
1078                         iaxs[x]->addr.sin_family = sin->sin_family;
1079                         iaxs[x]->addr.sin_addr.s_addr = sin->sin_addr.s_addr;
1080                         iaxs[x]->peercallno = callno;
1081                         iaxs[x]->callno = x;
1082                         iaxs[x]->pingtime = DEFAULT_RETRY_TIME;
1083                         iaxs[x]->expirey = expirey;
1084                         iaxs[x]->pingid = ast_sched_add(sched, ping_time * 1000, send_ping, (void *)x);
1085                         iaxs[x]->lagid = ast_sched_add(sched, lagrq_time * 1000, send_lagrq, (void *)x);
1086                         iaxs[x]->amaflags = amaflags;
1087                         strncpy(iaxs[x]->accountcode, accountcode, sizeof(iaxs[x]->accountcode)-1);
1088                 } else {
1089                         ast_log(LOG_WARNING, "Out of resources\n");
1090                         return 0;
1091                 }
1092                 res = x;
1093         }
1094         return res;
1095 }
1096
1097 static int iax2_queue_frame(int callno, struct ast_frame *f)
1098 {
1099         int pass =0;
1100         /* Assumes lock for callno is already held... */
1101         for (;;) {
1102                 pass++;
1103                 if (!pthread_mutex_trylock(&iaxsl[callno])) {
1104                         ast_log(LOG_WARNING, "Lock is not held on pass %d of iax2_queue_frame\n", pass);
1105                         CRASH;
1106                 }
1107                 if (iaxs[callno] && iaxs[callno]->owner) {
1108                         if (pthread_mutex_trylock(&iaxs[callno]->owner->lock)) {
1109                                 /* Avoid deadlock by pausing and trying again */
1110                                 ast_pthread_mutex_unlock(&iaxsl[callno]);
1111                                 usleep(1);
1112                                 ast_pthread_mutex_lock(&iaxsl[callno]);
1113                         } else {
1114                                 ast_queue_frame(iaxs[callno]->owner, f, 0);
1115                                 ast_pthread_mutex_unlock(&iaxs[callno]->owner->lock);
1116                                 break;
1117                         }
1118                 } else
1119                         break;
1120         }
1121         return 0;
1122 }
1123
1124 static int iax2_send(struct chan_iax2_pvt *pvt, struct ast_frame *f, unsigned int ts, int seqno, int now, int transfer, int final);
1125
1126 static int __do_deliver(void *data)
1127 {
1128         /* Just deliver the packet by using queueing.  This is called by
1129           the IAX thread with the iaxsl lock held. */
1130         struct ast_iax2_frame *fr = data;
1131         unsigned int ts;
1132         fr->retrans = -1;
1133         if (iaxs[fr->callno] && !iaxs[fr->callno]->alreadygone) {
1134                 if (fr->af.frametype == AST_FRAME_IAX) {
1135                         /* We have to treat some of these packets specially because
1136                            they're LAG measurement packets */
1137                         if (fr->af.subclass == AST_IAX2_COMMAND_LAGRQ) {
1138                                 /* If we got a queued request, build a reply and send it */
1139                                 fr->af.subclass = AST_IAX2_COMMAND_LAGRP;
1140                                 iax2_send(iaxs[fr->callno], &fr->af, fr->ts, -1, 0, 0, 0);
1141                         } else if (fr->af.subclass == AST_IAX2_COMMAND_LAGRP) {
1142                                 /* This is a reply we've been given, actually measure the difference */
1143                                 ts = calc_timestamp(iaxs[fr->callno], 0);
1144                                 iaxs[fr->callno]->lag = ts - fr->ts;
1145                         }
1146                 } else {
1147                         iax2_queue_frame(fr->callno, &fr->af);
1148                 }
1149         }
1150         /* Free our iax frame */
1151         ast_iax2_frame_free(fr);
1152         /* And don't run again */
1153         return 0;
1154 }
1155
1156 static int do_deliver(void *data)
1157 {
1158         /* Locking version of __do_deliver */
1159         struct ast_iax2_frame *fr = data;
1160         int callno = fr->callno;
1161         int res;
1162         ast_pthread_mutex_lock(&iaxsl[callno]);
1163         res = __do_deliver(data);
1164         ast_pthread_mutex_unlock(&iaxsl[callno]);
1165         return res;
1166 }
1167
1168 static int handle_error(void)
1169 {
1170         /* XXX Ideally we should figure out why an error occured and then abort those
1171            rather than continuing to try.  Unfortunately, the published interface does
1172            not seem to work XXX */
1173 #if 0
1174         struct sockaddr_in *sin;
1175         int res;
1176         struct msghdr m;
1177         struct sock_extended_err e;
1178         m.msg_name = NULL;
1179         m.msg_namelen = 0;
1180         m.msg_iov = NULL;
1181         m.msg_control = &e;
1182         m.msg_controllen = sizeof(e);
1183         m.msg_flags = 0;
1184         res = recvmsg(netsocket, &m, MSG_ERRQUEUE);
1185         if (res < 0)
1186                 ast_log(LOG_WARNING, "Error detected, but unable to read error: %s\n", strerror(errno));
1187         else {
1188                 if (m.msg_controllen) {
1189                         sin = (struct sockaddr_in *)SO_EE_OFFENDER(&e);
1190                         if (sin) 
1191                                 ast_log(LOG_WARNING, "Receive error from %s\n", inet_ntoa(sin->sin_addr));
1192                         else
1193                                 ast_log(LOG_WARNING, "No address detected??\n");
1194                 } else {
1195                         ast_log(LOG_WARNING, "Local error: %s\n", strerror(e.ee_errno));
1196                 }
1197         }
1198 #endif
1199         return 0;
1200 }
1201
1202 static int send_packet(struct ast_iax2_frame *f)
1203 {
1204         int res;
1205         /* Called with iaxsl held */
1206         if (option_debug)
1207                 ast_log(LOG_DEBUG, "Sending %d on %d/%d to %s:%d\n", f->ts, f->callno, iaxs[f->callno]->peercallno, inet_ntoa(iaxs[f->callno]->addr.sin_addr), ntohs(iaxs[f->callno]->addr.sin_port));
1208         /* Don't send if there was an error, but return error instead */
1209         if (!f->callno) {
1210                 ast_log(LOG_WARNING, "Call number = %d\n", f->callno);
1211                 return -1;
1212         }
1213         if (!iaxs[f->callno])
1214                 return -1;
1215         if (iaxs[f->callno]->error)
1216                 return -1;
1217         if (f->transfer) {
1218 #ifdef DEBUG_SUPPORT
1219                 if (iaxdebug)
1220                         showframe(f, NULL, 0, &iaxs[f->callno]->transfer, f->datalen - sizeof(struct ast_iax2_full_hdr));
1221 #endif
1222                 res = sendto(netsocket, f->data, f->datalen, 0,(struct sockaddr *)&iaxs[f->callno]->transfer,
1223                                         sizeof(iaxs[f->callno]->transfer));
1224         } else {
1225 #ifdef DEBUG_SUPPORT
1226                 if (iaxdebug)
1227                         showframe(f, NULL, 0, &iaxs[f->callno]->addr, f->datalen - sizeof(struct ast_iax2_full_hdr));
1228 #endif
1229                 res = sendto(netsocket, f->data, f->datalen, 0,(struct sockaddr *)&iaxs[f->callno]->addr,
1230                                         sizeof(iaxs[f->callno]->addr));
1231         }
1232         if (res < 0) {
1233                 if (option_debug)
1234                         ast_log(LOG_DEBUG, "Received error: %s\n", strerror(errno));
1235                 handle_error();
1236         } else
1237                 res = 0;
1238         return res;
1239 }
1240
1241
1242 static int iax2_predestroy(int callno)
1243 {
1244         struct ast_channel *c;
1245         struct chan_iax2_pvt *pvt;
1246         ast_pthread_mutex_lock(&iaxsl[callno]);
1247         pvt = iaxs[callno];
1248         if (!pvt) {
1249                 ast_pthread_mutex_unlock(&iaxsl[callno]);
1250                 return -1;
1251         }
1252         if (!pvt->alreadygone) {
1253                 /* No more pings or lagrq's */
1254                 if (pvt->pingid > -1)
1255                         ast_sched_del(sched, pvt->pingid);
1256                 if (pvt->lagid > -1)
1257                         ast_sched_del(sched, pvt->lagid);
1258                 if (pvt->autoid > -1)
1259                         ast_sched_del(sched, pvt->autoid);
1260                 if (pvt->initid > -1)
1261                         ast_sched_del(sched, pvt->initid);
1262                 pvt->pingid = -1;
1263                 pvt->lagid = -1;
1264                 pvt->autoid = -1;
1265                 pvt->initid = -1;
1266                 pvt->alreadygone = 1;
1267         }
1268         c = pvt->owner;
1269         if (c) {
1270                 c->_softhangup |= AST_SOFTHANGUP_DEV;
1271                 c->pvt->pvt = NULL;
1272                 ast_queue_hangup(c, 0);
1273                 pvt->owner = NULL;
1274                 ast_pthread_mutex_lock(&usecnt_lock);
1275                 usecnt--;
1276                 if (usecnt < 0) 
1277                         ast_log(LOG_WARNING, "Usecnt < 0???\n");
1278                 ast_pthread_mutex_unlock(&usecnt_lock);
1279                 ast_update_use_count();
1280         }
1281         ast_pthread_mutex_unlock(&iaxsl[callno]);
1282         return 0;
1283 }
1284
1285 static int iax2_predestroy_nolock(int callno)
1286 {
1287         int res;
1288         ast_pthread_mutex_unlock(&iaxsl[callno]);
1289         res = iax2_predestroy(callno);
1290         ast_pthread_mutex_lock(&iaxsl[callno]);
1291         return res;
1292 }
1293
1294 static void iax2_destroy(int callno)
1295 {
1296         struct chan_iax2_pvt *pvt;
1297         struct ast_iax2_frame *cur;
1298         struct ast_channel *owner;
1299
1300 retry:
1301         ast_pthread_mutex_lock(&iaxsl[callno]);
1302         pvt = iaxs[callno];
1303         iaxs[callno] = NULL;
1304         gettimeofday(&lastused[callno], NULL);
1305
1306         if (pvt)
1307                 owner = pvt->owner;
1308         else
1309                 owner = NULL;
1310         if (owner) {
1311                 if (pthread_mutex_trylock(&owner->lock)) {
1312                         ast_log(LOG_NOTICE, "Avoiding IAX destroy deadlock\n");
1313                         ast_pthread_mutex_unlock(&iaxsl[callno]);
1314                         usleep(1);
1315                         goto retry;
1316                 }
1317         }
1318         if (pvt) {
1319                 pvt->owner = NULL;
1320                 /* No more pings or lagrq's */
1321                 if (pvt->pingid > -1)
1322                         ast_sched_del(sched, pvt->pingid);
1323                 if (pvt->lagid > -1)
1324                         ast_sched_del(sched, pvt->lagid);
1325                 if (pvt->autoid > -1)
1326                         ast_sched_del(sched, pvt->autoid);
1327                 if (pvt->initid > -1)
1328                         ast_sched_del(sched, pvt->initid);
1329                 pvt->pingid = -1;
1330                 pvt->lagid = -1;
1331                 pvt->autoid = -1;
1332                 pvt->initid = -1;
1333
1334                 /* Already gone */
1335                 pvt->alreadygone = 1;
1336
1337                 if (owner) {
1338                         /* If there's an owner, prod it to give up */
1339                         owner->pvt->pvt = NULL;
1340                         owner->_softhangup |= AST_SOFTHANGUP_DEV;
1341                         ast_queue_hangup(owner, 0);
1342                 }
1343
1344                 for (cur = iaxq.head; cur ; cur = cur->next) {
1345                         /* Cancel any pending transmissions */
1346                         if (cur->callno == pvt->callno) 
1347                                 cur->retries = -1;
1348                 }
1349                 if (pvt->reg) {
1350                         pvt->reg->callno = 0;
1351                 }
1352                 free(pvt);
1353         }
1354         if (owner) {
1355                 ast_pthread_mutex_unlock(&owner->lock);
1356         }
1357         ast_pthread_mutex_unlock(&iaxsl[callno]);
1358         if (callno & 0x4000)
1359                 update_max_trunk();
1360 }
1361 static void iax2_destroy_nolock(int callno)
1362 {       
1363         /* Actually it's easier to unlock, kill it, and relock */
1364         ast_pthread_mutex_unlock(&iaxsl[callno]);
1365         iax2_destroy(callno);
1366         ast_pthread_mutex_lock(&iaxsl[callno]);
1367 }
1368
1369 static int update_packet(struct ast_iax2_frame *f)
1370 {
1371         /* Called with iaxsl lock held, and iaxs[callno] non-NULL */
1372         struct ast_iax2_full_hdr *fh = f->data;
1373         /* Mark this as a retransmission */
1374         fh->dcallno = ntohs(AST_FLAG_RETRANS | f->dcallno);
1375         /* Update iseqno */
1376         f->iseqno = iaxs[f->callno]->iseqno;
1377         fh->iseqno = f->iseqno;
1378         return 0;
1379 }
1380
1381 static int attempt_transmit(void *data)
1382 {
1383         /* Attempt to transmit the frame to the remote peer...
1384            Called without iaxsl held. */
1385         struct ast_iax2_frame *f = data;
1386         int freeme=0;
1387         int callno = f->callno;
1388         /* Make sure this call is still active */
1389         if (callno) 
1390                 ast_pthread_mutex_lock(&iaxsl[callno]);
1391         if ((f->callno) && iaxs[f->callno]) {
1392                 if ((f->retries < 0) /* Already ACK'd */ ||
1393                     (f->retries >= max_retries) /* Too many attempts */) {
1394                                 /* Record an error if we've transmitted too many times */
1395                                 if (f->retries >= max_retries) {
1396                                         if (f->transfer) {
1397                                                 /* Transfer timeout */
1398                                                 send_command(iaxs[f->callno], AST_FRAME_IAX, AST_IAX2_COMMAND_TXREJ, 0, NULL, 0, -1);
1399                                         } else if (f->final) {
1400                                                 if (f->final) 
1401                                                         iax2_destroy_nolock(f->callno);
1402                                         } else {
1403                                                 if (iaxs[f->callno]->owner)
1404                                                         ast_log(LOG_WARNING, "Max retries exceeded to host %s on %s (type = %d, subclass = %d, ts=%d, seqno=%d)\n", inet_ntoa(iaxs[f->callno]->addr.sin_addr),iaxs[f->callno]->owner->name , f->af.frametype, f->af.subclass, f->ts, f->oseqno);
1405                                                 iaxs[f->callno]->error = ETIMEDOUT;
1406                                                 if (iaxs[f->callno]->owner) {
1407                                                         struct ast_frame fr = { 0, };
1408                                                         /* Hangup the fd */
1409                                                         fr.frametype = AST_FRAME_CONTROL;
1410                                                         fr.subclass = AST_CONTROL_HANGUP;
1411                                                         iax2_queue_frame(f->callno, &fr);
1412                                                 } else {
1413                                                         if (iaxs[f->callno]->reg) {
1414                                                                 memset(&iaxs[f->callno]->reg->us, 0, sizeof(iaxs[f->callno]->reg->us));
1415                                                                 iaxs[f->callno]->reg->regstate = REG_STATE_TIMEOUT;
1416                                                                 iaxs[f->callno]->reg->refresh = AST_DEFAULT_REG_EXPIRE;
1417                                                         }
1418                                                         iax2_destroy_nolock(f->callno);
1419                                                 }
1420                                         }
1421
1422                                 }
1423                                 freeme++;
1424                 } else {
1425                         /* Update it if it needs it */
1426                         update_packet(f);
1427                         /* Attempt transmission */
1428                         send_packet(f);
1429                         f->retries++;
1430                         /* Try again later after 10 times as long */
1431                         f->retrytime *= 10;
1432                         if (f->retrytime > MAX_RETRY_TIME)
1433                                 f->retrytime = MAX_RETRY_TIME;
1434                         /* Transfer messages max out at one second */
1435                         if (f->transfer && (f->retrytime > 1000))
1436                                 f->retrytime = 1000;
1437                         f->retrans = ast_sched_add(sched, f->retrytime, attempt_transmit, f);
1438                 }
1439         } else {
1440                 /* Make sure it gets freed */
1441                 f->retries = -1;
1442                 freeme++;
1443         }
1444         if (callno)
1445                 ast_pthread_mutex_unlock(&iaxsl[callno]);
1446         /* Do not try again */
1447         if (freeme) {
1448                 /* Don't attempt delivery, just remove it from the queue */
1449                 ast_pthread_mutex_lock(&iaxq.lock);
1450                 if (f->prev) 
1451                         f->prev->next = f->next;
1452                 else
1453                         iaxq.head = f->next;
1454                 if (f->next)
1455                         f->next->prev = f->prev;
1456                 else
1457                         iaxq.tail = f->prev;
1458                 iaxq.count--;
1459                 ast_pthread_mutex_unlock(&iaxq.lock);
1460                 f->retrans = -1;
1461                 /* Free the IAX2 frame */
1462                 ast_iax2_frame_free(f);
1463         }
1464         return 0;
1465 }
1466
1467 static int iax2_set_jitter(int fd, int argc, char *argv[])
1468 {
1469         if ((argc != 4) && (argc != 5))
1470                 return RESULT_SHOWUSAGE;
1471         if (argc == 4) {
1472                 max_jitter_buffer = atoi(argv[3]);
1473                 if (max_jitter_buffer < 0)
1474                         max_jitter_buffer = 0;
1475         } else {
1476                 if (argc == 5) {
1477                         if ((atoi(argv[3]) >= 0) && (atoi(argv[3]) < AST_IAX2_MAX_CALLS)) {
1478                                 if (iaxs[atoi(argv[3])]) {
1479                                         iaxs[atoi(argv[3])]->jitterbuffer = atoi(argv[4]);
1480                                         if (iaxs[atoi(argv[3])]->jitterbuffer < 0)
1481                                                 iaxs[atoi(argv[3])]->jitterbuffer = 0;
1482                                 } else
1483                                         ast_cli(fd, "No such call '%d'\n", atoi(argv[3]));
1484                         } else
1485                                 ast_cli(fd, "%d is not a valid call number\n", atoi(argv[3]));
1486                 }
1487         }
1488         return RESULT_SUCCESS;
1489 }
1490
1491 static char jitter_usage[] = 
1492 "Usage: iax set jitter [callid] <value>\n"
1493 "       If used with a callid, it sets the jitter buffer to the given static\n"
1494 "value (until its next calculation).  If used without a callid, the value is used\n"
1495 "to establish the maximum excess jitter buffer that is permitted before the jitter\n"
1496 "buffer size is reduced.";
1497
1498 static int iax2_show_stats(int fd, int argc, char *argv[])
1499 {
1500         struct ast_iax2_frame *cur;
1501         int cnt = 0, dead=0, final=0;
1502         if (argc != 3)
1503                 return RESULT_SHOWUSAGE;
1504         for (cur = iaxq.head; cur ; cur = cur->next) {
1505                 if (cur->retries < 0)
1506                         dead++;
1507                 if (cur->final)
1508                         final++;
1509                 cnt++;
1510         }
1511         ast_cli(fd, "    IAX Statistics\n");
1512         ast_cli(fd, "---------------------\n");
1513         ast_cli(fd, "Outstanding frames: %d (%d ingress, %d outgress)\n", frames, iframes, oframes);
1514         ast_cli(fd, "Packets in transmit queue: %d dead, %d final, %d total\n", dead, final, cnt);
1515         return RESULT_SUCCESS;
1516 }
1517
1518 static int iax2_show_cache(int fd, int argc, char *argv[])
1519 {
1520         struct iax2_dpcache *dp;
1521         char tmp[1024], *pc;
1522         int s;
1523         int x,y;
1524         struct timeval tv;
1525         gettimeofday(&tv, NULL);
1526         ast_pthread_mutex_lock(&dpcache_lock);
1527         dp = dpcache;
1528         ast_cli(fd, "%-20.20s %-12.12s %-9.9s %-8.8s %s\n", "Peer/Context", "Exten", "Exp.", "Wait.", "Flags");
1529         while(dp) {
1530                 s = dp->expirey.tv_sec - tv.tv_sec;
1531                 strcpy(tmp, "");
1532                 if (dp->flags & CACHE_FLAG_EXISTS)
1533                         strcat(tmp, "EXISTS|");
1534                 if (dp->flags & CACHE_FLAG_NONEXISTANT)
1535                         strcat(tmp, "NONEXISTANT|");
1536                 if (dp->flags & CACHE_FLAG_CANEXIST)
1537                         strcat(tmp, "CANEXIST|");
1538                 if (dp->flags & CACHE_FLAG_PENDING)
1539                         strcat(tmp, "PENDING|");
1540                 if (dp->flags & CACHE_FLAG_TIMEOUT)
1541                         strcat(tmp, "TIMEOUT|");
1542                 if (dp->flags & CACHE_FLAG_TRANSMITTED)
1543                         strcat(tmp, "TRANSMITTED|");
1544                 if (dp->flags & CACHE_FLAG_MATCHMORE)
1545                         strcat(tmp, "MATCHMORE|");
1546                 if (dp->flags & CACHE_FLAG_UNKNOWN)
1547                         strcat(tmp, "UNKNOWN|");
1548                 /* Trim trailing pipe */
1549                 if (strlen(tmp))
1550                         tmp[strlen(tmp) - 1] = '\0';
1551                 else
1552                         strcpy(tmp, "(none)");
1553                 y=0;
1554                 pc = strchr(dp->peercontext, '@');
1555                 if (!pc)
1556                         pc = dp->peercontext;
1557                 else
1558                         pc++;
1559                 for (x=0;x<sizeof(dp->waiters) / sizeof(dp->waiters[0]); x++)
1560                         if (dp->waiters[x] > -1)
1561                                 y++;
1562                 if (s > 0)
1563                         ast_cli(fd, "%-20.20s %-12.12s %-9d %-8d %s\n", pc, dp->exten, s, y, tmp);
1564                 else
1565                         ast_cli(fd, "%-20.20s %-12.12s %-9.9s %-8d %s\n", pc, dp->exten, "(expired)", y, tmp);
1566                 dp = dp->next;
1567         }
1568         ast_pthread_mutex_unlock(&dpcache_lock);
1569         return RESULT_SUCCESS;
1570 }
1571
1572 static char show_stats_usage[] =
1573 "Usage: iax show stats\n"
1574 "       Display statistics on IAX channel driver.\n";
1575
1576
1577 static char show_cache_usage[] =
1578 "Usage: iax show cache\n"
1579 "       Display currently cached IAX Dialplan results.\n";
1580
1581 static struct ast_cli_entry cli_set_jitter = 
1582 { { "iax2", "set", "jitter", NULL }, iax2_set_jitter, "Sets IAX jitter buffer", jitter_usage };
1583
1584 static struct ast_cli_entry cli_show_stats =
1585 { { "iax2", "show", "stats", NULL }, iax2_show_stats, "Display IAX statistics", show_stats_usage };
1586
1587 static struct ast_cli_entry cli_show_cache =
1588 { { "iax2", "show", "cache", NULL }, iax2_show_cache, "Display IAX cached dialplan", show_cache_usage };
1589
1590 static unsigned int calc_rxstamp(struct chan_iax2_pvt *p);
1591
1592 #ifdef BRIDGE_OPTIMIZATION
1593 static unsigned int calc_fakestamp(struct chan_iax2_pvt *from, struct chan_iax2_pvt *to, unsigned int ts);
1594
1595 static int forward_delivery(struct ast_iax2_frame *fr)
1596 {
1597         struct chan_iax2_pvt *p1, *p2;
1598         p1 = iaxs[fr->callno];
1599         p2 = iaxs[p1->bridgecallno];
1600         if (!p1)
1601                 return -1;
1602         if (!p2)
1603                 return -1;
1604         /* Fix relative timestamp */
1605         fr->ts = calc_fakestamp(p1, p2, fr->ts);
1606         /* Now just send it send on the 2nd one 
1607            with adjusted timestamp */
1608         return iax2_send(p2, &fr->af, fr->ts, -1, 0, 0, 0);
1609 }
1610 #endif
1611
1612 static int schedule_delivery(struct ast_iax2_frame *fr, int reallydeliver, int updatehistory)
1613 {
1614         int ms,x;
1615         int drops[MEMORY_SIZE];
1616         int min, max=0, maxone=0,y,z, match;
1617         /* ms is a measure of the "lateness" of the packet relative to the first
1618            packet we received, which always has a lateness of 1.  Called by
1619            IAX thread, with iaxsl lock held. */
1620         ms = calc_rxstamp(iaxs[fr->callno]) - fr->ts;
1621
1622         if (ms > 32767) {
1623                 /* What likely happened here is that our counter has circled but we haven't
1624                    gotten the update from the main packet.  We'll just pretend that we did, and
1625                    update the timestamp appropriately. */
1626                 ms -= 65536;
1627         }
1628
1629         if (ms < -32768) {
1630                 /* We got this packet out of order.  Lets add 65536 to it to bring it into our new
1631                    time frame */
1632                 ms += 65536;
1633         }
1634         
1635         /* Rotate our history queue of "lateness".  Don't worry about those initial
1636            zeros because the first entry will always be zero */
1637         if (updatehistory) {
1638                 for (x=0;x<MEMORY_SIZE - 1;x++) 
1639                         iaxs[fr->callno]->history[x] = iaxs[fr->callno]->history[x+1];
1640                 /* Add a history entry for this one */
1641                 iaxs[fr->callno]->history[x] = ms;
1642         }
1643
1644         /* Initialize the minimum to reasonable values.  It's too much
1645            work to do the same for the maximum, repeatedly */
1646         min=iaxs[fr->callno]->history[0];
1647         for (z=0;z < iax2_dropcount + 1;z++) {
1648                 /* Start very optimistic ;-) */
1649                 max=-999999999;
1650                 for (x=0;x<MEMORY_SIZE;x++) {
1651                         if (max < iaxs[fr->callno]->history[x]) {
1652                                 /* We have a candidate new maximum value.  Make
1653                                    sure it's not in our drop list */
1654                                 match = 0;
1655                                 for (y=0;!match && (y<z);y++)
1656                                         match |= (drops[y] == x);
1657                                 if (!match) {
1658                                         /* It's not in our list, use it as the new maximum */
1659                                         max = iaxs[fr->callno]->history[x];
1660                                         maxone = x;
1661                                 }
1662                                 
1663                         }
1664                         if (!z) {
1665                                 /* On our first pass, find the minimum too */
1666                                 if (min > iaxs[fr->callno]->history[x])
1667                                         min = iaxs[fr->callno]->history[x];
1668                         }
1669                 }
1670 #if 1
1671                 drops[z] = maxone;
1672 #endif
1673         }
1674         /* Just for reference, keep the "jitter" value, the difference between the
1675            earliest and the latest. */
1676         iaxs[fr->callno]->jitter = max - min;   
1677         
1678         /* IIR filter for keeping track of historic jitter, but always increase
1679            historic jitter immediately for increase */
1680         
1681         if (iaxs[fr->callno]->jitter > iaxs[fr->callno]->historicjitter )
1682                 iaxs[fr->callno]->historicjitter = iaxs[fr->callno]->jitter;
1683         else
1684                 iaxs[fr->callno]->historicjitter = GAMMA * (double)iaxs[fr->callno]->jitter + (1-GAMMA) * 
1685                         iaxs[fr->callno]->historicjitter;
1686
1687         /* If our jitter buffer is too big (by a significant margin), then we slowly
1688            shrink it by about 1 ms each time to avoid letting the change be perceived */
1689         if (max < iaxs[fr->callno]->jitterbuffer - max_jitter_buffer)
1690                 iaxs[fr->callno]->jitterbuffer -= 2;
1691
1692
1693 #if 1
1694         /* Constrain our maximum jitter buffer appropriately */
1695         if (max > min + maxjitterbuffer) {
1696                 if (option_debug)
1697                         ast_log(LOG_DEBUG, "Constraining buffer from %d to %d + %d\n", max, min , maxjitterbuffer);
1698                 max = min + maxjitterbuffer;
1699         }
1700 #endif
1701
1702         /* If our jitter buffer is smaller than our maximum delay, grow the jitter
1703            buffer immediately to accomodate it (and a little more).  */
1704         if (max > iaxs[fr->callno]->jitterbuffer)
1705                 iaxs[fr->callno]->jitterbuffer = max 
1706                         /* + ((float)iaxs[fr->callno]->jitter) * 0.1 */;
1707                 
1708
1709         if (option_debug)
1710                 ast_log(LOG_DEBUG, "min = %d, max = %d, jb = %d, lateness = %d\n", min, max, iaxs[fr->callno]->jitterbuffer, ms);
1711         
1712         /* Subtract the lateness from our jitter buffer to know how long to wait
1713            before sending our packet.  */
1714         ms = iaxs[fr->callno]->jitterbuffer - ms;
1715         
1716         if (!use_jitterbuffer)
1717                 ms = 0;
1718
1719         /* If the caller just wanted us to update, return now */
1720         if (!reallydeliver)
1721                 return 0;
1722                 
1723         if (ms < 1) {
1724                 if (option_debug)
1725                         ast_log(LOG_DEBUG, "Calculated ms is %d\n", ms);
1726                 /* Don't deliver it more than 4 ms late */
1727                 if ((ms > -4) || (fr->af.frametype != AST_FRAME_VOICE)) {
1728                         __do_deliver(fr);
1729                 } else {
1730                         if (option_debug)
1731                                 ast_log(LOG_DEBUG, "Dropping voice packet since %d ms is, too old\n", ms);
1732                         /* Free our iax frame */
1733                         ast_iax2_frame_free(fr);
1734                 }
1735         } else {
1736                 if (option_debug)
1737                         ast_log(LOG_DEBUG, "Scheduling delivery in %d ms\n", ms);
1738                 fr->retrans = ast_sched_add(sched, ms, do_deliver, fr);
1739         }
1740         return 0;
1741 }
1742
1743 static int iax2_transmit(struct ast_iax2_frame *fr)
1744 {
1745         /* Lock the queue and place this packet at the end */
1746         fr->next = NULL;
1747         fr->prev = NULL;
1748         /* By setting this to 0, the network thread will send it for us, and
1749            queue retransmission if necessary */
1750         fr->sentyet = 0;
1751         ast_pthread_mutex_lock(&iaxq.lock);
1752         if (!iaxq.head) {
1753                 /* Empty queue */
1754                 iaxq.head = fr;
1755                 iaxq.tail = fr;
1756         } else {
1757                 /* Double link */
1758                 iaxq.tail->next = fr;
1759                 fr->prev = iaxq.tail;
1760                 iaxq.tail = fr;
1761         }
1762         iaxq.count++;
1763         ast_pthread_mutex_unlock(&iaxq.lock);
1764         /* Wake up the network thread */
1765         pthread_kill(netthreadid, SIGURG);
1766         return 0;
1767 }
1768
1769
1770
1771 static int iax2_digit(struct ast_channel *c, char digit)
1772 {
1773         return send_command(c->pvt->pvt, AST_FRAME_DTMF, digit, 0, NULL, 0, -1);
1774 }
1775
1776 static int iax2_sendtext(struct ast_channel *c, char *text)
1777 {
1778         
1779         return send_command(c->pvt->pvt, AST_FRAME_TEXT,
1780                 0, 0, text, strlen(text) + 1, -1);
1781 }
1782
1783 static int iax2_sendimage(struct ast_channel *c, struct ast_frame *img)
1784 {
1785         return send_command(c->pvt->pvt, AST_FRAME_IMAGE, img->subclass, 0, img->data, img->datalen, -1);
1786 }
1787
1788 static int iax2_sendhtml(struct ast_channel *c, int subclass, char *data, int datalen)
1789 {
1790         return send_command(c->pvt->pvt, AST_FRAME_HTML, subclass, 0, data, datalen, -1);
1791 }
1792
1793 static int iax2_fixup(struct ast_channel *oldchannel, struct ast_channel *newchan)
1794 {
1795         struct chan_iax2_pvt *pvt = newchan->pvt->pvt;
1796         pvt->owner = newchan;
1797         return 0;
1798 }
1799
1800 static int create_addr(struct sockaddr_in *sin, int *capability, int *sendani, int *maxtime, char *peer, char *context, int *trunk)
1801 {
1802         struct hostent *hp;
1803         struct iax2_peer *p;
1804         int found=0;
1805         if (sendani)
1806                 *sendani = 0;
1807         if (maxtime)
1808                 *maxtime = 0;
1809         if (trunk)
1810                 *trunk = 0;
1811         sin->sin_family = AF_INET;
1812         ast_pthread_mutex_lock(&peerl.lock);
1813         p = peerl.peers;
1814         while(p) {
1815                 if (!strcasecmp(p->name, peer)) {
1816                         found++;
1817                         if ((p->addr.sin_addr.s_addr || p->defaddr.sin_addr.s_addr) &&
1818                                 (!p->maxms || ((p->lastms > 0)  && (p->lastms <= p->maxms)))) {
1819                                 if (sendani)
1820                                         *sendani = p->sendani;          /* Whether we transmit ANI */
1821                                 if (maxtime)
1822                                         *maxtime = p->maxms;            /* Max time they should take */
1823                                 if (context)
1824                                         strncpy(context, p->context, AST_MAX_EXTENSION - 1);
1825                                 if (trunk)
1826                                         *trunk = p->trunk;
1827                                 if (capability)
1828                                         *capability = p->capability;
1829                                 if (p->addr.sin_addr.s_addr) {
1830                                         sin->sin_addr = p->addr.sin_addr;
1831                                         sin->sin_port = p->addr.sin_port;
1832                                 } else {
1833                                         sin->sin_addr = p->defaddr.sin_addr;
1834                                         sin->sin_port = p->defaddr.sin_port;
1835                                 }
1836                                 break;
1837                         }
1838                 }
1839                 p = p->next;
1840         }
1841         ast_pthread_mutex_unlock(&peerl.lock);
1842         if (!p && !found) {
1843                 hp = gethostbyname(peer);
1844                 if (hp) {
1845                         memcpy(&sin->sin_addr, hp->h_addr, sizeof(sin->sin_addr));
1846                         sin->sin_port = htons(AST_DEFAULT_IAX_PORTNO);
1847                         return 0;
1848                 } else {
1849                         ast_log(LOG_WARNING, "No such host: %s\n", peer);
1850                         return -1;
1851                 }
1852         } else if (!p)
1853                 return -1;
1854         else
1855                 return 0;
1856 }
1857
1858 static int auto_congest(void *nothing)
1859 {
1860         int callno = (int)(long)(nothing);
1861         struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_CONGESTION };
1862         ast_pthread_mutex_lock(&iaxsl[callno]);
1863         if (iaxs[callno]) {
1864                 iaxs[callno]->initid = -1;
1865                 iax2_queue_frame(callno, &f);
1866                 ast_log(LOG_NOTICE, "Auto-congesting call due to slow response\n");
1867         }
1868         ast_pthread_mutex_unlock(&iaxsl[callno]);
1869         return 0;
1870 }
1871
1872 static int iax_ie_append_raw(struct iax_ie_data *ied, unsigned char ie, void *data, int datalen)
1873 {
1874         if (datalen > (sizeof(ied->buf) - ied->pos)) {
1875                 ast_log(LOG_WARNING, "Out of space for ie '%s' (%d), need %d have %d\n", ie2str(ie), ie, datalen, sizeof(ied->buf) - ied->pos);
1876                 return -1;
1877         }
1878         ied->buf[ied->pos++] = ie;
1879         ied->buf[ied->pos++] = datalen;
1880         memcpy(ied->buf + ied->pos, data, datalen);
1881         ied->pos += datalen;
1882         return 0;
1883 }
1884
1885 static int iax_ie_append_addr(struct iax_ie_data *ied, unsigned char ie, struct sockaddr_in *sin)
1886 {
1887         return iax_ie_append_raw(ied, ie, sin, sizeof(struct sockaddr_in));
1888 }
1889
1890 static int iax_ie_append_int(struct iax_ie_data *ied, unsigned char ie, unsigned int value) 
1891 {
1892         unsigned int newval;
1893         newval = htonl(value);
1894         return iax_ie_append_raw(ied, ie, &newval, sizeof(newval));
1895 }
1896
1897 static int iax_ie_append_short(struct iax_ie_data *ied, unsigned char ie, unsigned short value) 
1898 {
1899         unsigned short newval;
1900         newval = htons(value);
1901         return iax_ie_append_raw(ied, ie, &newval, sizeof(newval));
1902 }
1903
1904 static int iax_ie_append_str(struct iax_ie_data *ied, unsigned char ie, unsigned char *str)
1905 {
1906         return iax_ie_append_raw(ied, ie, str, strlen(str));
1907 }
1908
1909 static int iax_ie_append_byte(struct iax_ie_data *ied, unsigned char ie, unsigned char dat)
1910 {
1911         return iax_ie_append_raw(ied, ie, &dat, 1);
1912 }
1913
1914 static int iax2_call(struct ast_channel *c, char *dest, int timeout)
1915 {
1916         struct sockaddr_in sin;
1917         char host[256];
1918         char *rdest;
1919         char *rcontext;
1920         char *username;
1921         char *secret = NULL;
1922         char *hname;
1923         char cid[256] = "";
1924         char *l=NULL, *n=NULL;
1925         struct iax_ie_data ied;
1926         char myrdest [5] = "s";
1927         char context[AST_MAX_EXTENSION] ="";
1928         char *portno = NULL;
1929         struct chan_iax2_pvt *p = c->pvt->pvt;
1930         char *stringp=NULL;
1931         if ((c->_state != AST_STATE_DOWN) && (c->_state != AST_STATE_RESERVED)) {
1932                 ast_log(LOG_WARNING, "Line is already in use (%s)?\n", c->name);
1933                 return -1;
1934         }
1935         strncpy(host, dest, sizeof(host)-1);
1936         stringp=host;
1937         strsep(&stringp, "/");
1938         /* If no destination extension specified, use 's' */
1939         rdest = strsep(&stringp, "/");
1940         if (!rdest) 
1941                 rdest = myrdest;
1942         stringp=rdest;
1943         strsep(&stringp, "@");
1944         rcontext = strsep(&stringp, "@");
1945         stringp=host;
1946         strsep(&stringp, "@");
1947         username = strsep(&stringp, "@");
1948         if (username) {
1949                 /* Really the second argument is the host, not the username */
1950                 hname = username;
1951                 username = host;
1952         } else {
1953                 hname = host;
1954         }
1955         if (username) {
1956                 stringp=username;
1957                 username = strsep(&stringp, ":");
1958                 secret = strsep(&stringp, ":");
1959         }
1960         stringp=hname;
1961         if (strsep(&stringp, ":")) {
1962                 stringp=hname;
1963                 strsep(&stringp, ":");
1964                 portno = strsep(&stringp, ":");
1965         }
1966         if (create_addr(&sin, NULL, NULL, NULL, hname, context, NULL)) {
1967                 ast_log(LOG_WARNING, "No address associated with '%s'\n", hname);
1968                 return -1;
1969         }
1970         /* Keep track of the context for outgoing calls too */
1971         strncpy(c->context, context, sizeof(c->context) - 1);
1972         if (portno) {
1973                 sin.sin_port = htons(atoi(portno));
1974         }
1975         if (c->callerid) {
1976                 strncpy(cid, c->callerid, sizeof(cid) - 1);
1977                 ast_callerid_parse(cid, &n, &l);
1978                 if (l)
1979                         ast_shrink_phone_number(l);
1980         }
1981         /* Now build request */ 
1982         memset(&ied, 0, sizeof(ied));
1983         /* On new call, first IE MUST be IAX version of caller */
1984         iax_ie_append_short(&ied, IAX_IE_VERSION, AST_IAX2_PROTO_VERSION);
1985         iax_ie_append_str(&ied, IAX_IE_CALLED_NUMBER, rdest);
1986         if (l)
1987                 iax_ie_append_str(&ied, IAX_IE_CALLING_NUMBER, l);
1988         if (n)
1989                 iax_ie_append_str(&ied, IAX_IE_CALLING_NAME, n);
1990         if (p->sendani && c->ani) {
1991                 l = n = NULL;
1992                 strncpy(cid, c->ani, sizeof(cid) - 1);
1993                 ast_callerid_parse(cid, &n, &l);
1994                 if (l) {
1995                         ast_shrink_phone_number(l);
1996                         iax_ie_append_str(&ied, IAX_IE_CALLING_ANI, l);
1997                 }
1998         }
1999         if (c->language && strlen(c->language))
2000                 iax_ie_append_str(&ied, IAX_IE_LANGUAGE, c->language);
2001         if (c->dnid && strlen(c->dnid))
2002                 iax_ie_append_str(&ied, IAX_IE_DNID, c->dnid);
2003         if (rcontext)
2004                 iax_ie_append_str(&ied, IAX_IE_CALLED_CONTEXT, rcontext);
2005         if (username)
2006                 iax_ie_append_str(&ied, IAX_IE_USERNAME, username);
2007         if (secret) {
2008                 if (secret[0] == '[') {
2009                         /* This is an RSA key, not a normal secret */
2010                         strncpy(p->outkey, secret + 1, sizeof(p->secret)-1);
2011                         if (strlen(p->outkey)) {
2012                                 p->outkey[strlen(p->outkey) - 1] = '\0';
2013                         }
2014                 } else
2015                         strncpy(p->secret, secret, sizeof(p->secret)-1);
2016         }
2017         iax_ie_append_int(&ied, IAX_IE_FORMAT, c->nativeformats);
2018         iax_ie_append_int(&ied, IAX_IE_CAPABILITY, p->capability);
2019         iax_ie_append_short(&ied, IAX_IE_ADSICPE, c->adsicpe);
2020         /* Transmit the string in a "NEW" request */
2021 #if 0
2022         /* XXX We have no equivalent XXX */
2023         if (option_verbose > 2)
2024                 ast_verbose(VERBOSE_PREFIX_3 "Calling using options '%s'\n", requeststr);
2025 #endif          
2026         if (p->maxtime) {
2027                 /* Initialize pingtime and auto-congest time */
2028                 p->pingtime = p->maxtime / 2;
2029                 p->initid = ast_sched_add(sched, p->maxtime * 2, auto_congest, (void *)(long)p->callno);
2030         }
2031         send_command(p, AST_FRAME_IAX,
2032                 AST_IAX2_COMMAND_NEW, 0, ied.buf, ied.pos, -1);
2033         ast_setstate(c, AST_STATE_RINGING);
2034         return 0;
2035 }
2036
2037 static int iax2_hangup(struct ast_channel *c) 
2038 {
2039         struct chan_iax2_pvt *pvt = c->pvt->pvt;
2040         int alreadygone;
2041         int callno;
2042         if (pvt) {
2043                 callno = pvt->callno;
2044                 ast_pthread_mutex_lock(&iaxsl[callno]);
2045                 ast_log(LOG_DEBUG, "We're hanging up %s now...\n", c->name);
2046                 alreadygone = pvt->alreadygone;
2047                 /* Send the hangup unless we have had a transmission error or are already gone */
2048                 if (!pvt->error && !alreadygone) 
2049                         send_command_final(pvt, AST_FRAME_IAX, AST_IAX2_COMMAND_HANGUP, 0, NULL, 0, -1);
2050                 /* Explicitly predestroy it */
2051                 iax2_predestroy_nolock(callno);
2052                 /* If we were already gone to begin with, destroy us now */
2053                 if (alreadygone) {
2054                         ast_log(LOG_DEBUG, "Really destroying %s now...\n", c->name);
2055                         iax2_destroy_nolock(callno);
2056                 }
2057                 ast_pthread_mutex_unlock(&iaxsl[callno]);
2058         }
2059         if (option_verbose > 2) 
2060                 ast_verbose(VERBOSE_PREFIX_3 "Hungup '%s'\n", c->name);
2061         return 0;
2062 }
2063
2064 static int iax2_setoption(struct ast_channel *c, int option, void *data, int datalen)
2065 {
2066         struct ast_option_header *h;
2067         int res;
2068         h = malloc(datalen + sizeof(struct ast_option_header));
2069         if (h) {
2070                 h->flag = AST_OPTION_FLAG_REQUEST;
2071                 h->option = htons(option);
2072                 memcpy(h->data, data, datalen);
2073                 res = send_command((struct chan_iax2_pvt *)c->pvt->pvt, AST_FRAME_CONTROL,
2074                         AST_CONTROL_OPTION, 0, (char *)h, datalen + sizeof(struct ast_option_header), -1);
2075                 free(h);
2076                 return res;
2077         } else 
2078                 ast_log(LOG_WARNING, "Out of memory\n");
2079         return -1;
2080 }
2081 static struct ast_frame *iax2_read(struct ast_channel *c) 
2082 {
2083         static struct ast_frame f = { AST_FRAME_NULL, };
2084         ast_log(LOG_NOTICE, "I should never be called!\n");
2085         return &f;
2086 }
2087
2088 static int iax2_start_transfer(struct ast_channel *c0, struct ast_channel *c1)
2089 {
2090         int res;
2091         struct iax_ie_data ied0;
2092         struct iax_ie_data ied1;
2093         struct chan_iax2_pvt *p0 = c0->pvt->pvt;
2094         struct chan_iax2_pvt *p1 = c1->pvt->pvt;
2095         memset(&ied0, 0, sizeof(ied0));
2096         iax_ie_append_addr(&ied0, IAX_IE_APPARENT_ADDR, &p1->addr);
2097         iax_ie_append_short(&ied0, IAX_IE_CALLNO, p1->peercallno);
2098
2099         memset(&ied1, 0, sizeof(ied1));
2100         iax_ie_append_addr(&ied1, IAX_IE_APPARENT_ADDR, &p0->addr);
2101         iax_ie_append_short(&ied1, IAX_IE_CALLNO, p0->peercallno);
2102         
2103         res = send_command(p0, AST_FRAME_IAX, AST_IAX2_COMMAND_TXREQ, 0, ied0.buf, ied0.pos, -1);
2104         if (res)
2105                 return -1;
2106         res = send_command(p1, AST_FRAME_IAX, AST_IAX2_COMMAND_TXREQ, 0, ied1.buf, ied1.pos, -1);
2107         if (res)
2108                 return -1;
2109         p0->transferring = TRANSFER_BEGIN;
2110         p1->transferring = TRANSFER_BEGIN;
2111         return 0;
2112 }
2113
2114 static int iax2_bridge(struct ast_channel *c0, struct ast_channel *c1, int flags, struct ast_frame **fo, struct ast_channel **rc)
2115 {
2116         struct ast_channel *cs[3];
2117         struct ast_channel *who;
2118         int to = -1;
2119         int res;
2120         int transferstarted=0;
2121         struct ast_frame *f;
2122         struct chan_iax2_pvt *p0 = c0->pvt->pvt;
2123         struct chan_iax2_pvt *p1 = c1->pvt->pvt;
2124
2125         /* Put them in native bridge mode */
2126         p0->bridgecallno = p1->callno;
2127         p1->bridgecallno = p0->callno;
2128
2129         /* If not, try to bridge until we can execute a transfer, if we can */
2130         cs[0] = c0;
2131         cs[1] = c1;
2132         for (/* ever */;;) {
2133                 /* Check in case we got masqueraded into */
2134                 if ((c0->type != type) || (c1->type != type)) {
2135                         if (option_verbose > 2)
2136                                 ast_verbose(VERBOSE_PREFIX_3 "Can't masquerade, we're different...\n");
2137                         return -2;
2138                 }
2139                 if (c0->nativeformats != c1->nativeformats) {
2140                         ast_verbose(VERBOSE_PREFIX_3 "Operating with different codecs, can't native bridge...\n");
2141                         return -2;
2142                 }
2143                 if (!transferstarted) {
2144                         /* Try the transfer */
2145                         if (iax2_start_transfer(c0, c1))
2146                                 ast_log(LOG_WARNING, "Unable to start the transfer\n");
2147                         transferstarted = 1;
2148                 }
2149                 
2150                 if ((p0->transferring == TRANSFER_RELEASED) && (p1->transferring == TRANSFER_RELEASED)) {
2151                         /* Call has been transferred.  We're no longer involved */
2152                         sleep(1);
2153                         c0->_softhangup |= AST_SOFTHANGUP_DEV;
2154                         c1->_softhangup |= AST_SOFTHANGUP_DEV;
2155                         *fo = NULL;
2156                         *rc = c0;
2157                         res = 0;
2158                         break;
2159                 }
2160                 to = 1000;
2161                 who = ast_waitfor_n(cs, 2, &to);
2162                 if (!who) {
2163                         continue;
2164                 }
2165                 f = ast_read(who);
2166                 if (!f) {
2167                         *fo = NULL;
2168                         *rc = who;
2169                         res = 0;
2170                         break;
2171                 }
2172                 if ((f->frametype == AST_FRAME_CONTROL) && !(flags & AST_BRIDGE_IGNORE_SIGS)) {
2173                         *fo = f;
2174                         *rc = who;
2175                         res =  0;
2176                         break;
2177                 }
2178                 if ((f->frametype == AST_FRAME_VOICE) ||
2179                         (f->frametype == AST_FRAME_TEXT) ||
2180                         (f->frametype == AST_FRAME_VIDEO) || 
2181                         (f->frametype == AST_FRAME_IMAGE) ||
2182                         (f->frametype == AST_FRAME_DTMF)) {
2183                         if ((f->frametype == AST_FRAME_DTMF) && 
2184                                 (flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1))) {
2185                                 if ((who == c0)) {
2186                                         if  ((flags & AST_BRIDGE_DTMF_CHANNEL_0)) {
2187                                                 *rc = c0;
2188                                                 *fo = f;
2189                                                 /* Take out of conference mode */
2190                                                 res = 0;
2191                                                 break;
2192                                         } else 
2193                                                 goto tackygoto;
2194                                 } else
2195                                 if ((who == c1)) {
2196                                         if (flags & AST_BRIDGE_DTMF_CHANNEL_1) {
2197                                                 *rc = c1;
2198                                                 *fo = f;
2199                                                 res =  0;
2200                                                 break;
2201                                         } else
2202                                                 goto tackygoto;
2203                                 }
2204                         } else {
2205 #if 0
2206                                 ast_log(LOG_DEBUG, "Read from %s\n", who->name);
2207                                 if (who == last) 
2208                                         ast_log(LOG_DEBUG, "Servicing channel %s twice in a row?\n", last->name);
2209                                 last = who;
2210 #endif
2211 tackygoto:
2212                                 if (who == c0) 
2213                                         ast_write(c1, f);
2214                                 else 
2215                                         ast_write(c0, f);
2216                         }
2217                         ast_frfree(f);
2218                 } else
2219                         ast_frfree(f);
2220                 /* Swap who gets priority */
2221                 cs[2] = cs[0];
2222                 cs[0] = cs[1];
2223                 cs[1] = cs[2];
2224         }
2225         p0->bridgecallno = 0;
2226         p1->bridgecallno = 0;
2227         return res;
2228 }
2229
2230 static int iax2_answer(struct ast_channel *c)
2231 {
2232         struct chan_iax2_pvt *pvt = c->pvt->pvt;
2233         if (option_debug)
2234                 ast_log(LOG_DEBUG, "Answering\n");
2235         return send_command(pvt, AST_FRAME_CONTROL, AST_CONTROL_ANSWER, 0, NULL, 0, -1);
2236 }
2237
2238 static int iax2_indicate(struct ast_channel *c, int condition)
2239 {
2240         struct chan_iax2_pvt *pvt = c->pvt->pvt;
2241         if (option_debug)
2242                 ast_log(LOG_DEBUG, "Indicating condition %d\n", condition);
2243         return send_command(pvt, AST_FRAME_CONTROL, condition, 0, NULL, 0, -1);
2244 }
2245         
2246
2247 static int iax2_write(struct ast_channel *c, struct ast_frame *f);
2248
2249 static int iax2_getpeername(struct sockaddr_in sin, char *host, int len)
2250 {
2251         struct iax2_peer *peer;
2252         int res = 0;
2253         ast_pthread_mutex_lock(&peerl.lock);
2254         peer = peerl.peers;
2255         while(peer) {
2256                 if ((peer->addr.sin_addr.s_addr == sin.sin_addr.s_addr) &&
2257                                 (peer->addr.sin_port == sin.sin_port)) {
2258                                         strncpy(host, peer->name, len-1);
2259                                         res = 1;
2260                                         break;
2261                 }
2262                 peer = peer->next;
2263         }
2264         ast_pthread_mutex_unlock(&peerl.lock);
2265         return res;
2266 }
2267
2268 static struct ast_channel *ast_iax2_new(struct chan_iax2_pvt *i, int state, int capability)
2269 {
2270         char host[256];
2271         struct ast_channel *tmp;
2272         tmp = ast_channel_alloc(1);
2273         if (tmp) {
2274                 if (!iax2_getpeername(i->addr, host, sizeof(host)))
2275                         snprintf(host, sizeof(host), "%s:%d", inet_ntoa(i->addr.sin_addr), ntohs(i->addr.sin_port));
2276                 if (strlen(i->username))
2277                         snprintf(tmp->name, sizeof(tmp->name), "IAX2[%s@%s]/%d", i->username, host, i->callno);
2278                 else
2279                         snprintf(tmp->name, sizeof(tmp->name), "IAX2[%s]/%d", host, i->callno);
2280                 tmp->type = type;
2281                 /* We can support any format by default, until we get restricted */
2282                 tmp->nativeformats = capability;
2283                 tmp->readformat = 0;
2284                 tmp->writeformat = 0;
2285                 tmp->pvt->pvt = i;
2286                 tmp->pvt->send_digit = iax2_digit;
2287                 tmp->pvt->send_text = iax2_sendtext;
2288                 tmp->pvt->send_image = iax2_sendimage;
2289                 tmp->pvt->send_html = iax2_sendhtml;
2290                 tmp->pvt->call = iax2_call;
2291                 tmp->pvt->hangup = iax2_hangup;
2292                 tmp->pvt->answer = iax2_answer;
2293                 tmp->pvt->read = iax2_read;
2294                 tmp->pvt->write = iax2_write;
2295                 tmp->pvt->indicate = iax2_indicate;
2296                 tmp->pvt->setoption = iax2_setoption;
2297                 tmp->pvt->bridge = iax2_bridge;
2298                 if (strlen(i->callerid))
2299                         tmp->callerid = strdup(i->callerid);
2300                 if (strlen(i->ani))
2301                         tmp->ani = strdup(i->ani);
2302                 if (strlen(i->language))
2303                         strncpy(tmp->language, i->language, sizeof(tmp->language)-1);
2304                 if (strlen(i->dnid))
2305                         tmp->dnid = strdup(i->dnid);
2306                 if (strlen(i->accountcode))
2307                         strncpy(tmp->accountcode, i->accountcode, sizeof(tmp->accountcode)-1);
2308                 if (i->amaflags)
2309                         tmp->amaflags = i->amaflags;
2310                 strncpy(tmp->context, i->context, sizeof(tmp->context)-1);
2311                 strncpy(tmp->exten, i->exten, sizeof(tmp->exten)-1);
2312                 tmp->adsicpe = i->peeradsicpe;
2313                 tmp->pvt->fixup = iax2_fixup;
2314                 i->owner = tmp;
2315                 i->capability = capability;
2316                 ast_setstate(tmp, state);
2317                 ast_pthread_mutex_lock(&usecnt_lock);
2318                 usecnt++;
2319                 ast_pthread_mutex_unlock(&usecnt_lock);
2320                 ast_update_use_count();
2321                 if (state != AST_STATE_DOWN) {
2322                         if (ast_pbx_start(tmp)) {
2323                                 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
2324                                 ast_hangup(tmp);
2325                                 tmp = NULL;
2326                         }
2327                 }
2328         }
2329         return tmp;
2330 }
2331
2332 static unsigned int calc_txpeerstamp(struct iax2_peer *peer)
2333 {
2334         struct timeval tv;
2335         unsigned int mssincetx;
2336         unsigned int ms;
2337         gettimeofday(&tv, NULL);
2338         mssincetx = (tv.tv_sec - peer->lasttxtime.tv_sec) * 1000 + (tv.tv_usec - peer->lasttxtime.tv_usec) / 1000;
2339         if (mssincetx > 5000) {
2340                 /* If it's been at least 5 seconds since the last time we transmitted on this trunk, reset our timers */
2341                 peer->txtrunktime.tv_sec = tv.tv_sec;
2342                 peer->txtrunktime.tv_usec = tv.tv_usec;
2343         }
2344         /* Update last transmit time now */
2345         peer->lasttxtime.tv_sec = tv.tv_sec;
2346         peer->lasttxtime.tv_usec = tv.tv_usec;
2347         
2348         /* Calculate ms offset */
2349         ms = (tv.tv_sec - peer->txtrunktime.tv_sec) * 1000 + (tv.tv_usec - peer->txtrunktime.tv_usec) / 1000;
2350         
2351         /* We never send the same timestamp twice, so fudge a little if we must */
2352         if (ms == peer->lastsent)
2353                 ms = peer->lastsent + 1;
2354         peer->lastsent = ms;
2355         return ms;
2356 }
2357
2358 static unsigned int fix_peerts(struct iax2_peer *peer, int callno, unsigned int ts)
2359 {
2360         long ms;        /* NOT unsigned */
2361         if (!iaxs[callno]->rxcore.tv_sec && !iaxs[callno]->rxcore.tv_usec) {
2362                 /* Initialize rxcore time if appropriate */
2363                 gettimeofday(&iaxs[callno]->rxcore, NULL);
2364         }
2365         /* Calculate difference between trunk and channel */
2366         ms = (peer->rxtrunktime.tv_sec - iaxs[callno]->rxcore.tv_sec) * 1000 + 
2367                 (peer->rxtrunktime.tv_usec - iaxs[callno]->rxcore.tv_usec) / 1000;
2368         /* Return as the sum of trunk time and the difference between trunk and real time */
2369         return ms + ts;
2370 }
2371
2372 static unsigned int calc_timestamp(struct chan_iax2_pvt *p, unsigned int ts)
2373 {
2374         struct timeval tv;
2375         unsigned int ms;
2376         if (!p->offset.tv_sec && !p->offset.tv_usec)
2377                 gettimeofday(&p->offset, NULL);
2378         /* If the timestamp is specified, just send it as is */
2379         if (ts)
2380                 return ts;
2381         gettimeofday(&tv, NULL);
2382         ms = (tv.tv_sec - p->offset.tv_sec) * 1000 + (tv.tv_usec - p->offset.tv_usec) / 1000;
2383         /* We never send the same timestamp twice, so fudge a little if we must */
2384         if (ms <= p->lastsent)
2385                 ms = p->lastsent + 1;
2386         p->lastsent = ms;
2387         return ms;
2388 }
2389
2390 #ifdef BRIDGE_OPTIMIZATION
2391 static unsigned int calc_fakestamp(struct chan_iax2_pvt *p1, struct chan_iax2_pvt *p2, unsigned int fakets)
2392 {
2393         int ms;
2394         /* Receive from p1, send to p2 */
2395         
2396         /* Setup rxcore if necessary on outgoing channel */
2397         if (!p1->rxcore.tv_sec && !p1->rxcore.tv_usec)
2398                 gettimeofday(&p1->rxcore, NULL);
2399
2400         /* Setup txcore if necessary on outgoing channel */
2401         if (!p2->offset.tv_sec && !p2->offset.tv_usec)
2402                 gettimeofday(&p2->offset, NULL);
2403         
2404         /* Now, ts is the timestamp of the original packet in the orignal context.
2405            Adding rxcore to it gives us when we would want the packet to be delivered normally.
2406            Subtracting txcore of the outgoing channel gives us what we'd expect */
2407         
2408         ms = (p1->rxcore.tv_sec - p2->offset.tv_sec) * 1000 + (p1->rxcore.tv_usec - p2->offset.tv_usec) / 1000;
2409         fakets += ms;
2410         if (fakets <= p2->lastsent)
2411                 fakets = p2->lastsent + 1;
2412         p2->lastsent = fakets;
2413         return fakets;
2414 }
2415 #endif
2416
2417 static unsigned int calc_rxstamp(struct chan_iax2_pvt *p)
2418 {
2419         /* Returns where in "receive time" we are */
2420         struct timeval tv;
2421         unsigned int ms;
2422         /* Setup rxcore if necessary */
2423         if (!p->rxcore.tv_sec && !p->rxcore.tv_usec)
2424                 gettimeofday(&p->rxcore, NULL);
2425
2426         gettimeofday(&tv, NULL);
2427         ms = (tv.tv_sec - p->rxcore.tv_sec) * 1000 + (tv.tv_usec - p->rxcore.tv_usec) / 1000;
2428         return ms;
2429 }
2430
2431 static int iax2_send(struct chan_iax2_pvt *pvt, struct ast_frame *f, unsigned int ts, int seqno, int now, int transfer, int final)
2432 {
2433         /* Queue a packet for delivery on a given private structure.  Use "ts" for
2434            timestamp, or calculate if ts is 0.  Send immediately without retransmission
2435            or delayed, with retransmission */
2436         struct ast_iax2_full_hdr *fh;
2437         struct ast_iax2_mini_hdr *mh;
2438         struct ast_iax2_frame *fr, fr2;
2439         int res;
2440         unsigned int lastsent;
2441         /* Allocate an ast_iax2_frame */
2442         if (now) {
2443                 fr = &fr2;
2444         } else
2445                 fr = ast_iax2_frame_new(DIRECTION_OUTGRESS, f->datalen);
2446         if (!fr) {
2447                 ast_log(LOG_WARNING, "Out of memory\n");
2448                 return -1;
2449         }
2450         if (!pvt) {
2451                 ast_log(LOG_WARNING, "No private structure for packet (%d)?\n", fr->callno);
2452                 if (!now)
2453                         ast_iax2_frame_free(fr);
2454                 return -1;
2455         }
2456         /* Copy our prospective frame into our immediate or retransmitted wrapper */
2457         ast_iax2_frame_wrap(fr, f);
2458
2459         lastsent = pvt->lastsent;
2460         fr->ts = calc_timestamp(pvt, ts);
2461         if (!fr->ts) {
2462                 ast_log(LOG_WARNING, "timestamp is 0?\n");
2463                 if (!now)
2464                         ast_iax2_frame_free(fr);
2465                 return -1;
2466         }
2467         fr->callno = pvt->callno;
2468         fr->transfer = transfer;
2469         fr->final = final;
2470         if (((fr->ts & 0xFFFF0000L) != (lastsent & 0xFFFF0000L))
2471                 /* High two bits of timestamp differ */ ||
2472             (fr->af.frametype != AST_FRAME_VOICE) 
2473                 /* or not a voice frame */ || 
2474                 (fr->af.subclass != pvt->svoiceformat) 
2475                 /* or new voice format */ ) {
2476                 /* We need a full frame */
2477                 if (seqno > -1)
2478                         fr->oseqno = seqno;
2479                 else
2480                         fr->oseqno = pvt->oseqno++;
2481                 fr->iseqno = pvt->iseqno;
2482                 fh = (struct ast_iax2_full_hdr *)(fr->af.data - sizeof(struct ast_iax2_full_hdr));
2483                 fh->scallno = htons(fr->callno | AST_FLAG_FULL);
2484                 fh->ts = htonl(fr->ts);
2485                 fh->oseqno = fr->oseqno;
2486                 fh->iseqno = fr->iseqno;
2487                 /* Keep track of the last thing we've acknowledged */
2488                 pvt->aseqno = fr->iseqno;
2489                 fh->type = fr->af.frametype & 0xFF;
2490                 fh->csub = compress_subclass(fr->af.subclass);
2491                 if (transfer) {
2492                         fr->dcallno = pvt->transfercallno;
2493                 } else
2494                         fr->dcallno = pvt->peercallno;
2495                 fh->dcallno = htons(fr->dcallno);
2496                 fr->datalen = fr->af.datalen + sizeof(struct ast_iax2_full_hdr);
2497                 fr->data = fh;
2498                 fr->retries = 0;
2499                 /* Retry after 2x the ping time has passed */
2500                 fr->retrytime = pvt->pingtime * 2;
2501                 if (fr->retrytime < MIN_RETRY_TIME)
2502                         fr->retrytime = MIN_RETRY_TIME;
2503                 if (fr->retrytime > MAX_RETRY_TIME)
2504                         fr->retrytime = MAX_RETRY_TIME;
2505                 /* Acks' don't get retried */
2506                 if ((f->frametype == AST_FRAME_IAX) && (f->subclass == AST_IAX2_COMMAND_ACK))
2507                         fr->retries = -1;
2508                 if (f->frametype == AST_FRAME_VOICE) {
2509                         pvt->svoiceformat = f->subclass;
2510                 }
2511                 if (now) {
2512                         res = send_packet(fr);
2513                 } else
2514                         res = iax2_transmit(fr);
2515         } else {
2516                 if (pvt->trunk) {
2517                         /* Queue for transmission in a meta frame */
2518                         if ((sizeof(pvt->trunkdata) - pvt->trunkdatalen) >= fr->af.datalen) {
2519                                 memcpy(pvt->trunkdata + pvt->trunkdatalen, fr->af.data, fr->af.datalen);
2520                                 pvt->trunkdatalen += fr->af.datalen;
2521                                 res = 0;
2522                                 pvt->trunkerror = 0;
2523                         } else {
2524                                 if (!pvt->trunkerror)
2525                                         ast_log(LOG_WARNING, "Out of trunk data space on call number %d, dropping\n", pvt->callno);
2526                                 pvt->trunkerror = 1;
2527                         }
2528                 } else {
2529                         /* Mini-frames have no sequence number */
2530                         fr->oseqno = -1;
2531                         fr->iseqno = -1;
2532                         /* Mini frame will do */
2533                         mh = (struct ast_iax2_mini_hdr *)(fr->af.data - sizeof(struct ast_iax2_mini_hdr));
2534                         mh->callno = htons(fr->callno);
2535                         mh->ts = htons(fr->ts & 0xFFFF);
2536                         fr->datalen = fr->af.datalen + sizeof(struct ast_iax2_mini_hdr);
2537                         fr->data = mh;
2538                         fr->retries = -1;
2539                         if (now) {
2540                                 res = send_packet(fr);
2541                         } else
2542                                 res = iax2_transmit(fr);
2543                 }
2544         }
2545         return res;
2546 }
2547
2548
2549
2550 static int iax2_show_users(int fd, int argc, char *argv[])
2551 {
2552 #define FORMAT "%-15.15s  %-15.15s  %-15.15s  %-15.15s  %-5.5s\n"
2553 #define FORMAT2 "%-15.15s  %-15.15s  %-15.15d  %-15.15s  %-5.5s\n"
2554         struct iax2_user *user;
2555         if (argc != 3) 
2556                 return RESULT_SHOWUSAGE;
2557         ast_pthread_mutex_lock(&userl.lock);
2558         ast_cli(fd, FORMAT, "Username", "Secret", "Authen", "Def.Context", "A/C");
2559         for(user=userl.users;user;user=user->next) {
2560                 ast_cli(fd, FORMAT2, user->name, user->secret, user->authmethods, 
2561                                 user->contexts ? user->contexts->context : context,
2562                                 user->ha ? "Yes" : "No");
2563         }
2564         ast_pthread_mutex_unlock(&userl.lock);
2565         return RESULT_SUCCESS;
2566 #undef FORMAT
2567 #undef FORMAT2
2568 }
2569
2570 static int iax2_show_peers(int fd, int argc, char *argv[])
2571 {
2572 #define FORMAT2 "%-15.15s  %-15.15s %s  %-15.15s  %-8s  %-10s\n"
2573 #define FORMAT "%-15.15s  %-15.15s %s  %-15.15s  %-5d%s  %-10s\n"
2574         struct iax2_peer *peer;
2575         char name[256] = "";
2576         if (argc != 3)
2577                 return RESULT_SHOWUSAGE;
2578         ast_pthread_mutex_lock(&peerl.lock);
2579         ast_cli(fd, FORMAT2, "Name/Username", "Host", "   ", "Mask", "Port", "Status");
2580         for (peer = peerl.peers;peer;peer = peer->next) {
2581                 char nm[20];
2582                 char status[20];
2583                 if (strlen(peer->username))
2584                         snprintf(name, sizeof(name), "%s/%s", peer->name, peer->username);
2585                 else
2586                         strncpy(name, peer->name, sizeof(name) - 1);
2587                 if (peer->maxms) {
2588                         if (peer->lastms < 0)
2589                                 strcpy(status, "UNREACHABLE");
2590                         else if (peer->lastms > peer->maxms) 
2591                                 snprintf(status, sizeof(status), "LAGGED (%d ms)", peer->lastms);
2592                         else if (peer->lastms) 
2593                                 snprintf(status, sizeof(status), "OK (%d ms)", peer->lastms);
2594                         else 
2595                                 strcpy(status, "UNKNOWN");
2596                 } else 
2597                         strcpy(status, "Unmonitored");
2598                 strncpy(nm, inet_ntoa(peer->mask), sizeof(nm)-1);
2599                 ast_cli(fd, FORMAT, name, 
2600                                         peer->addr.sin_addr.s_addr ? inet_ntoa(peer->addr.sin_addr) : "(Unspecified)",
2601                                         peer->dynamic ? "(D)" : "(S)",
2602                                         nm,
2603                                         ntohs(peer->addr.sin_port), peer->trunk ? "(T)" : "   ", status);
2604         }
2605         ast_pthread_mutex_unlock(&peerl.lock);
2606         return RESULT_SUCCESS;
2607 #undef FORMAT
2608 #undef FORMAT2
2609 }
2610
2611 /* JDG: callback to display iax peers in manager */
2612 static int manager_iax2_show_peers( struct mansession *s, struct message *m )
2613 {
2614         char *a[] = { "iax2", "show", "users" };
2615         int ret;
2616         ret = iax2_show_peers( s->fd, 3, a );
2617         ast_cli( s->fd, "\r\n" );
2618         return ret;
2619 } /* /JDG */
2620
2621 static char *regstate2str(int regstate)
2622 {
2623         switch(regstate) {
2624         case REG_STATE_UNREGISTERED:
2625                 return "Unregistered";
2626         case REG_STATE_REGSENT:
2627                 return "Request Sent";
2628         case REG_STATE_AUTHSENT:
2629                 return "Auth. Sent";
2630         case REG_STATE_REGISTERED:
2631                 return "Registered";
2632         case REG_STATE_REJECTED:
2633                 return "Rejected";
2634         case REG_STATE_TIMEOUT:
2635                 return "Timeout";
2636         case REG_STATE_NOAUTH:
2637                 return "No Authentication";
2638         default:
2639                 return "Unknown";
2640         }
2641 }
2642
2643 static int iax2_show_registry(int fd, int argc, char *argv[])
2644 {
2645 #define FORMAT2 "%-20.20s  %-10.10s  %-20.20s %8.8s  %s\n"
2646 #define FORMAT "%-20.20s  %-10.10s  %-20.20s %8d  %s\n"
2647         struct iax2_registry *reg;
2648         char host[80];
2649         char perceived[80];
2650         if (argc != 3)
2651                 return RESULT_SHOWUSAGE;
2652         ast_pthread_mutex_lock(&peerl.lock);
2653         ast_cli(fd, FORMAT2, "Host", "Username", "Perceived", "Refresh", "State");
2654         for (reg = registrations;reg;reg = reg->next) {
2655                 snprintf(host, sizeof(host), "%s:%d", inet_ntoa(reg->addr.sin_addr), ntohs(reg->addr.sin_port));
2656                 if (reg->us.sin_addr.s_addr) 
2657                         snprintf(perceived, sizeof(perceived), "%s:%d", inet_ntoa(reg->us.sin_addr), ntohs(reg->us.sin_port));
2658                 else
2659                         strcpy(perceived, "<Unregistered>");
2660                 ast_cli(fd, FORMAT, host, 
2661                                         reg->username, perceived, reg->refresh, regstate2str(reg->regstate));
2662         }
2663         ast_pthread_mutex_unlock(&peerl.lock);
2664         return RESULT_SUCCESS;
2665 #undef FORMAT
2666 #undef FORMAT2
2667 }
2668
2669 static int iax2_show_channels(int fd, int argc, char *argv[])
2670 {
2671 #define FORMAT2 "%-15.15s  %-10.10s  %-11.11s  %-11.11s  %-7.7s  %-6.6s  %s\n"
2672 #define FORMAT  "%-15.15s  %-10.10s  %5.5d/%5.5d  %5.5d/%5.5d  %-5.5dms  %-4.4dms  %d\n"
2673         int x;
2674         int numchans = 0;
2675         if (argc != 3)
2676                 return RESULT_SHOWUSAGE;
2677         ast_cli(fd, FORMAT2, "Peer", "Username", "ID (Lo/Rem)", "Seq (Tx/Rx)", "Lag", "Jitter", "Format");
2678         for (x=0;x<AST_IAX2_MAX_CALLS;x++) {
2679                 ast_pthread_mutex_lock(&iaxsl[x]);
2680                 if (iaxs[x]) {
2681                         ast_cli(fd, FORMAT, inet_ntoa(iaxs[x]->addr.sin_addr), 
2682                                                 strlen(iaxs[x]->username) ? iaxs[x]->username : "(None)", 
2683                                                 iaxs[x]->callno, iaxs[x]->peercallno, 
2684                                                 iaxs[x]->oseqno, iaxs[x]->iseqno, 
2685                                                 iaxs[x]->lag,
2686                                                 iaxs[x]->jitter,
2687                                                 iaxs[x]->voiceformat);
2688                         numchans++;
2689                 }
2690                 ast_pthread_mutex_unlock(&iaxsl[x]);
2691         }
2692         ast_cli(fd, "%d active IAX channel(s)\n", numchans);
2693         return RESULT_SUCCESS;
2694 #undef FORMAT
2695 #undef FORMAT2
2696 }
2697
2698 static int iax2_do_debug(int fd, int argc, char *argv[])
2699 {
2700         if (argc != 2)
2701                 return RESULT_SHOWUSAGE;
2702         iaxdebug = 1;
2703         ast_cli(fd, "IAX2 Debugging Enabled\n");
2704         return RESULT_SUCCESS;
2705 }
2706
2707 static int iax2_no_debug(int fd, int argc, char *argv[])
2708 {
2709         if (argc != 3)
2710                 return RESULT_SHOWUSAGE;
2711         iaxdebug = 0;
2712         ast_cli(fd, "IAX2 Debugging Disabled\n");
2713         return RESULT_SUCCESS;
2714 }
2715
2716
2717
2718 static char show_users_usage[] = 
2719 "Usage: iax2 show users\n"
2720 "       Lists all users known to the IAX2 (Inter-Asterisk eXchange rev 2) subsystem.\n";
2721
2722 static char show_channels_usage[] = 
2723 "Usage: iax2 show channels\n"
2724 "       Lists all currently active IAX2 channels.\n";
2725
2726 static char show_peers_usage[] = 
2727 "Usage: iax2 show peers\n"
2728 "       Lists all known IAX peers.\n";
2729
2730 static char show_reg_usage[] =
2731 "Usage: iax2 show registry\n"
2732 "       Lists all registration requests and status.\n";
2733
2734 #ifdef DEBUG_SUPPORT
2735
2736 static char debug_usage[] = 
2737 "Usage: iax2 debug\n"
2738 "       Enables dumping of IAX2 packets for debugging purposes\n";
2739
2740 static char no_debug_usage[] = 
2741 "Usage: iax2 no debug\n"
2742 "       Disables dumping of IAX2 packets for debugging purposes\n";
2743
2744 #endif
2745
2746 static struct ast_cli_entry  cli_show_users = 
2747         { { "iax2", "show", "users", NULL }, iax2_show_users, "Show defined IAX2 users", show_users_usage };
2748 static struct ast_cli_entry  cli_show_channels =
2749         { { "iax2", "show", "channels", NULL }, iax2_show_channels, "Show active IAX2 channels", show_channels_usage };
2750 static struct ast_cli_entry  cli_show_peers =
2751         { { "iax2", "show", "peers", NULL }, iax2_show_peers, "Show defined IAX2 peers", show_peers_usage };
2752 static struct ast_cli_entry  cli_show_registry =
2753         { { "iax2", "show", "registry", NULL }, iax2_show_registry, "Show IAX2 registration status", show_reg_usage };
2754 static struct ast_cli_entry  cli_debug =
2755         { { "iax2", "debug", NULL }, iax2_do_debug, "Enable IAX2 debugging", debug_usage };
2756 static struct ast_cli_entry  cli_no_debug =
2757         { { "iax2", "no", "debug", NULL }, iax2_no_debug, "Disable IAX2 debugging", no_debug_usage };
2758
2759 static int iax2_write(struct ast_channel *c, struct ast_frame *f)
2760 {
2761         struct chan_iax2_pvt *i = c->pvt->pvt;
2762         if (!i)
2763                 return -1;
2764         /* If there's an outstanding error, return failure now */
2765         if (i->error) {
2766                 ast_log(LOG_DEBUG, "Write error: %s\n", strerror(errno));
2767                 return -1;
2768         }
2769         /* If it's already gone, just return */
2770         if (i->alreadygone)
2771                 return 0;
2772         /* Don't waste bandwidth sending null frames */
2773         if (f->frametype == AST_FRAME_NULL)
2774                 return 0;
2775         /* If we're quelching voice, don't bother sending it */
2776         if ((f->frametype == AST_FRAME_VOICE) && i->quelch)
2777                 return 0;
2778         /* Simple, just queue for transmission */
2779         return iax2_send(i, f, 0, -1, 0, 0, 0);
2780 }
2781
2782 static int __send_command(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, char *data, int datalen, int seqno, 
2783                 int now, int transfer, int final)
2784 {
2785         struct ast_frame f;
2786         f.frametype = type;
2787         f.subclass = command;
2788         f.datalen = datalen;
2789         f.samples = 0;
2790         f.mallocd = 0;
2791         f.offset = 0;
2792         f.src = __FUNCTION__;
2793         f.data = data;
2794         return iax2_send(i, &f, ts, seqno, now, transfer, final);
2795 }
2796
2797 static int send_command(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, char *data, int datalen, int seqno)
2798 {
2799         return __send_command(i, type, command, ts, data, datalen, seqno, 0, 0, 0);
2800 }
2801
2802 #ifdef BRIDGE_OPTIMIZATION
2803 static int forward_command(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, char *data, int datalen, int seqno)
2804 {
2805         return __send_command(iaxs[i->bridgecallno], type, command, ts, data, datalen, seqno, 0, 0, 0);
2806 }
2807 #endif
2808
2809 static int send_command_final(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, char *data, int datalen, int seqno)
2810 {
2811         /* It is assumed that the callno has already been locked */
2812         iax2_predestroy_nolock(i->callno);
2813         return __send_command(i, type, command, ts, data, datalen, seqno, 0, 0, 1);
2814 }
2815
2816 static int send_command_immediate(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, char *data, int datalen, int seqno)
2817 {
2818         return __send_command(i, type, command, ts, data, datalen, seqno, 1, 0, 0);
2819 }
2820
2821 static int send_command_transfer(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, char *data, int datalen)
2822 {
2823         return __send_command(i, type, command, ts, data, datalen, 0, 0, 1, 0);
2824 }
2825
2826 static int apply_context(struct iax2_context *con, char *context)
2827 {
2828         while(con) {
2829                 if (!strcmp(con->context, context))
2830                         return -1;
2831                 con = con->next;
2832         }
2833         return 0;
2834 }
2835
2836
2837 static int check_access(int callno, struct sockaddr_in *sin, struct iax_ies *ies)
2838 {
2839         /* Start pessimistic */
2840         int res = -1;
2841         int version = 2;
2842         struct iax2_user *user;
2843         int gotcapability=0;
2844         if (!iaxs[callno])
2845                 return res;
2846         if (ies->called_number)
2847                 strncpy(iaxs[callno]->exten, ies->called_number, sizeof(iaxs[callno]->exten) - 1);
2848         if (ies->calling_number) {
2849                 if (ies->calling_name)
2850                         snprintf(iaxs[callno]->callerid, sizeof(iaxs[callno]->callerid), "\"%s\" <%s>", ies->calling_name, ies->calling_number);
2851                 else
2852                         strncpy(iaxs[callno]->callerid, ies->calling_number, sizeof(iaxs[callno]->callerid) - 1);
2853         } else if (ies->calling_name)
2854                 strncpy(iaxs[callno]->callerid, ies->calling_name, sizeof(iaxs[callno]->callerid) - 1);
2855         if (ies->calling_ani)
2856                 strncpy(iaxs[callno]->ani, ies->calling_ani, sizeof(iaxs[callno]->ani) - 1);
2857         if (ies->dnid)
2858                 strncpy(iaxs[callno]->dnid, ies->dnid, sizeof(iaxs[callno]->dnid)-1);
2859         if (ies->called_context)
2860                 strncpy(iaxs[callno]->context, ies->called_context, sizeof(iaxs[callno]->context)-1);
2861         if (ies->language)
2862                 strncpy(iaxs[callno]->language, ies->language, sizeof(iaxs[callno]->language)-1);
2863         if (ies->username)
2864                 strncpy(iaxs[callno]->username, ies->username, sizeof(iaxs[callno]->username)-1);
2865         if (ies->format)
2866                 iaxs[callno]->peerformat = ies->format;
2867         if (ies->adsicpe)
2868                 iaxs[callno]->peeradsicpe = ies->adsicpe;
2869         if (ies->capability) {
2870                 gotcapability = 1;
2871                 iaxs[callno]->peercapability = ies->capability;
2872         } 
2873         if (ies->version)
2874                 version = ies->version;
2875         if (!gotcapability) 
2876                 iaxs[callno]->peercapability = iaxs[callno]->peerformat;
2877         if (version > AST_IAX2_PROTO_VERSION) {
2878                 ast_log(LOG_WARNING, "Peer '%s' has too new a protocol version (%d) for me\n", 
2879                         inet_ntoa(sin->sin_addr), version);
2880                 return res;
2881         }
2882         ast_pthread_mutex_lock(&userl.lock);
2883         /* Search the userlist for a compatible entry, and fill in the rest */
2884         user = userl.users;
2885         while(user) {
2886                 if ((!strlen(iaxs[callno]->username) ||                         /* No username specified */
2887                         !strcmp(iaxs[callno]->username, user->name))    /* Or this username specified */
2888                         && ast_apply_ha(user->ha, sin)  /* Access is permitted from this IP */
2889                         && (!strlen(iaxs[callno]->context) ||                   /* No context specified */
2890                              apply_context(user->contexts, iaxs[callno]->context))) {                   /* Context is permitted */
2891                         /* We found our match (use the first) */
2892                         
2893                         /* Store the requested username if not specified */
2894                         if (!strlen(iaxs[callno]->username))
2895                                 strncpy(iaxs[callno]->username, user->name, sizeof(iaxs[callno]->username)-1);
2896                         /* Store whether this is a trunked call, too, of course, and move if appropriate */
2897                         iaxs[callno]->trunk = user->trunk;
2898                         /* And use the default context */
2899                         if (!strlen(iaxs[callno]->context)) {
2900                                 if (user->contexts)
2901                                         strncpy(iaxs[callno]->context, user->contexts->context, sizeof(iaxs[callno]->context)-1);
2902                                 else
2903                                         strncpy(iaxs[callno]->context, context, sizeof(iaxs[callno]->context)-1);
2904                         }
2905                         /* Copy the secret */
2906                         strncpy(iaxs[callno]->secret, user->secret, sizeof(iaxs[callno]->secret)-1);
2907                         /* And any input keys */
2908                         strncpy(iaxs[callno]->inkeys, user->inkeys, sizeof(iaxs[callno]->inkeys));
2909                         /* And the permitted authentication methods */
2910                         iaxs[callno]->authmethods = user->authmethods;
2911                         /* If they have callerid, override the given caller id.  Always store the ANI */
2912                         if (strlen(iaxs[callno]->callerid)) {
2913                                 if (user->hascallerid)
2914                                         strncpy(iaxs[callno]->callerid, user->callerid, sizeof(iaxs[callno]->callerid)-1);
2915                                 strncpy(iaxs[callno]->ani, user->callerid, sizeof(iaxs[callno]->ani)-1);
2916                         }
2917                         if (strlen(user->accountcode))
2918                                 strncpy(iaxs[callno]->accountcode, user->accountcode, sizeof(iaxs[callno]->accountcode)-1);
2919                         if (user->amaflags)
2920                                 iaxs[callno]->amaflags = user->amaflags;
2921                         res = 0;
2922                         break;
2923                 }
2924                 user = user->next;      
2925         }
2926         ast_pthread_mutex_unlock(&userl.lock);
2927         return res;
2928 }
2929
2930 static int raw_hangup(struct sockaddr_in *sin, unsigned short src, unsigned short dst)
2931 {
2932         struct ast_iax2_full_hdr fh;
2933         fh.scallno = htons(src | AST_FLAG_FULL);
2934         fh.dcallno = htons(dst);
2935         fh.ts = 0;
2936         fh.oseqno = 0;
2937         fh.iseqno = 0;
2938         fh.type = AST_FRAME_IAX;
2939         fh.csub = compress_subclass(AST_IAX2_COMMAND_INVAL);
2940 #if 0
2941         if (option_debug)
2942 #endif  
2943                 ast_log(LOG_DEBUG, "Raw Hangup %s:%d, src=%d, dst=%d\n",
2944                         inet_ntoa(sin->sin_addr), ntohs(sin->sin_port), src, dst);
2945         return sendto(netsocket, &fh, sizeof(fh), 0, (struct sockaddr *)sin, sizeof(*sin));
2946 }
2947
2948 static int authenticate_request(struct chan_iax2_pvt *p)
2949 {
2950         struct iax_ie_data ied;
2951         memset(&ied, 0, sizeof(ied));
2952         iax_ie_append_short(&ied, IAX_IE_AUTHMETHODS, p->authmethods);
2953         if (p->authmethods & (IAX_AUTH_MD5 | IAX_AUTH_RSA)) {
2954                 snprintf(p->challenge, sizeof(p->challenge), "%d", rand());
2955                 iax_ie_append_str(&ied, IAX_IE_CHALLENGE, p->challenge);
2956         }
2957         iax_ie_append_str(&ied,IAX_IE_USERNAME, p->username);
2958         return send_command(p, AST_FRAME_IAX, AST_IAX2_COMMAND_AUTHREQ, 0, ied.buf, ied.pos, -1);
2959 }
2960
2961 static int authenticate_verify(struct chan_iax2_pvt *p, struct iax_ies *ies)
2962 {
2963         char requeststr[256] = "";
2964         char md5secret[256] = "";
2965         char secret[256] = "";
2966         char rsasecret[256] = "";
2967         int res = -1; 
2968         int x;
2969         
2970         if (!(p->state & IAX_STATE_AUTHENTICATED))
2971                 return res;
2972         if (ies->password)
2973                 strncpy(secret, ies->password, sizeof(secret) - 1);
2974         if (ies->md5_result)
2975                 strncpy(md5secret, ies->md5_result, sizeof(md5secret)-1);
2976         if (ies->rsa_result)
2977                 strncpy(rsasecret, ies->rsa_result, sizeof(rsasecret)-1);
2978         printf("Auth methods: %d, rsasecret: %s, inkeys: %s\n", p->authmethods, rsasecret, p->inkeys);
2979         if ((p->authmethods & IAX_AUTH_RSA) && strlen(rsasecret) && strlen(p->inkeys)) {
2980                 struct ast_key *key;
2981                 char *keyn;
2982                 char tmpkey[256];
2983                 char *stringp=NULL;
2984                 printf("Checking RSA methods\n");
2985                 strncpy(tmpkey, p->inkeys, sizeof(tmpkey));
2986                 stringp=tmpkey;
2987                 keyn = strsep(&stringp, ":");
2988                 while(keyn) {
2989                         key = ast_key_get(keyn, AST_KEY_PUBLIC);
2990                         if (key && !ast_check_signature(key, p->challenge, rsasecret)) {
2991                                 res = 0;
2992                                 break;
2993                         } else if (!key)
2994                                 ast_log(LOG_WARNING, "requested inkey '%s' for RSA authentication does not exist\n", keyn);
2995                         keyn = strsep(&stringp, ":");
2996                 }
2997         } else if (p->authmethods & IAX_AUTH_MD5) {
2998                 struct MD5Context md5;
2999                 unsigned char digest[16];
3000                 MD5Init(&md5);
3001                 MD5Update(&md5, p->challenge, strlen(p->challenge));
3002                 MD5Update(&md5, p->secret, strlen(p->secret));
3003                 MD5Final(digest, &md5);
3004                 /* If they support md5, authenticate with it.  */
3005                 for (x=0;x<16;x++)
3006                         sprintf(requeststr + (x << 1), "%2.2x", digest[x]);
3007                 if (!strcasecmp(requeststr, md5secret))
3008                         res = 0;
3009         } else if (p->authmethods & IAX_AUTH_PLAINTEXT) {
3010                 if (!strcmp(secret, p->secret))
3011                         res = 0;
3012         }
3013         return res;
3014 }
3015
3016 static int register_verify(int callno, struct sockaddr_in *sin, struct iax_ies *ies)
3017 {
3018         char requeststr[256] = "";
3019         char peer[256] = "";
3020         char md5secret[256] = "";
3021         char rsasecret[256] = "";
3022         char secret[256] = "";
3023         struct iax2_peer *p;
3024         struct ast_key *key;
3025         char *keyn;
3026         int x;
3027         int expire = 0;
3028
3029         iaxs[callno]->state &= ~IAX_STATE_AUTHENTICATED;
3030         strcpy(iaxs[callno]->peer, "");
3031         if (ies->username)
3032                 strncpy(peer, ies->username, sizeof(peer) - 1);
3033         if (ies->password)
3034                 strncpy(secret, ies->password, sizeof(secret) - 1);
3035         if (ies->md5_result)
3036                 strncpy(md5secret, ies->md5_result, sizeof(md5secret)-1);
3037         if (ies->rsa_result)
3038                 strncpy(rsasecret, ies->rsa_result, sizeof(rsasecret)-1);
3039         if (ies->refresh)
3040                 expire = ies->refresh;
3041
3042         if (!strlen(peer)) {
3043                 ast_log(LOG_NOTICE, "Empty registration from %s\n", inet_ntoa(sin->sin_addr));
3044                 return -1;
3045         }
3046
3047         for (p = peerl.peers; p ; p = p->next) 
3048                 if (!strcasecmp(p->name, peer))
3049                         break;
3050
3051         if (!p) {
3052                 ast_log(LOG_NOTICE, "No registration for peer '%s' (from %s)\n", peer, inet_ntoa(sin->sin_addr));
3053                 return -1;
3054         }
3055
3056         if (!p->dynamic) {
3057                 ast_log(LOG_NOTICE, "Peer '%s' is not dynamic (from %s)\n", peer, inet_ntoa(sin->sin_addr));
3058                 return -1;
3059         }
3060
3061         if (!ast_apply_ha(p->ha, sin)) {
3062                 ast_log(LOG_NOTICE, "Host %s denied access to register peer '%s'\n", inet_ntoa(sin->sin_addr), p->name);
3063                 return -1;
3064         }
3065         strncpy(iaxs[callno]->secret, p->secret, sizeof(iaxs[callno]->secret)-1);
3066         strncpy(iaxs[callno]->inkeys, p->inkeys, sizeof(iaxs[callno]->inkeys)-1);
3067         /* Check secret against what we have on file */
3068         if (strlen(rsasecret) && (p->authmethods & IAX_AUTH_RSA) && strlen(p->challenge)) {
3069                 if (strlen(p->inkeys)) {
3070                         char tmpkeys[256];
3071                         char *stringp=NULL;
3072                         strncpy(tmpkeys, p->inkeys, sizeof(tmpkeys));
3073                         stringp=tmpkeys;
3074                         keyn = strsep(&stringp, ":");
3075                         while(keyn) {
3076                                 key = ast_key_get(keyn, AST_KEY_PUBLIC);
3077                                 if (key && !ast_check_signature(key, p->challenge, rsasecret)) {
3078                                         iaxs[callno]->state |= IAX_STATE_AUTHENTICATED;
3079                                         break;
3080                                 } else if (!key) 
3081                                         ast_log(LOG_WARNING, "requested inkey '%s' does not exist\n", keyn);
3082                                 keyn = strsep(&stringp, ":");
3083                         }