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