OpenBSD portability enhancements (bug 1002)
[asterisk/asterisk.git] / channels / chan_h323.c
1 /*
2  * chan_h323.c
3  *
4  * OpenH323 Channel Driver for ASTERISK PBX.
5  *                      By Jeremy McNamara
6  *                      For The NuFone Network 
7  *
8  * This code has been derived from code created by
9  *              Michael Manousos and Mark Spencer
10  *
11  * This file is part of the chan_h323 driver for Asterisk
12  *
13  * chan_h323 is free software; you can redistribute it and/or modify
14  * it under the terms of the GNU General Public License as published by
15  * the Free Software Foundation; either version 2 of the License, or
16  * (at your option) any later version. 
17  *
18  * chan_h323 is distributed WITHOUT ANY WARRANTY; without even 
19  * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR 
20  * PURPOSE. See the GNU General Public License for more details. 
21  *
22  * You should have received a copy of the GNU General Public License
23  * along with this program; if not, write to the Free Software
24  * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. 
25  *
26  * Version Info: $Id$
27  */
28
29
30 #include <stdio.h>
31 #include <pthread.h>
32 #include <string.h>
33 #include <asterisk/lock.h>
34 #include <asterisk/logger.h>
35 #include <asterisk/channel.h>
36 #include <asterisk/channel_pvt.h>
37 #include <asterisk/config.h>
38 #include <asterisk/module.h>
39 #include <asterisk/pbx.h>
40 #include <asterisk/options.h>
41 #include <asterisk/lock.h>
42 #include <asterisk/sched.h>
43 #include <asterisk/io.h>
44 #include <asterisk/rtp.h>
45 #include <asterisk/acl.h>
46 #include <asterisk/callerid.h>
47 #include <asterisk/cli.h>
48 #include <asterisk/dsp.h>
49 #include <sys/socket.h>
50 #include <net/if.h>
51 #include <errno.h>
52 #include <unistd.h>
53 #include <stdlib.h>
54 #include <fcntl.h>
55 #include <netdb.h>
56 #include <sys/signal.h>
57 #include <netinet/ip.h>
58 #ifdef __OpenBSD__
59 #include <netinet/in_systm.h>
60 #ifndef IPTOS_MINCOST
61 #define IPTOS_MINCOST 0x02
62 #endif
63 #endif
64
65 #include "h323/chan_h323.h"
66
67 /** String variables required by ASTERISK */
68 static char *type       = "H323";
69 static char *desc       = "The NuFone Network's Open H.323 Channel Driver";
70 static char *tdesc      = "The NuFone Network's Open H.323 Channel Driver";
71 static char *config = "h323.conf";
72
73 static char default_context[AST_MAX_EXTENSION];
74
75 /** H.323 configuration values */
76 static char gatekeeper[100];
77 static int  gatekeeper_disable = 1;
78 static int  gatekeeper_discover = 0;
79 static int  usingGk;
80 static int  port = 1720;
81 static int  gkroute = 0;
82
83 /* to find user by alias is default, alternative is the incomming call's source IP address*/
84 static int  userbyalias = 1;
85
86 static int  bridge_default = 1;
87
88 /* Just about everybody seems to support ulaw, so make it a nice default */
89 static int capability = AST_FORMAT_ULAW;
90
91 /* TOS flag */
92 static int tos = 0;
93
94 static int dtmfmode = H323_DTMF_RFC2833;
95
96 static char secret[50];
97
98 /** Private structure of a OpenH323 channel */
99 struct oh323_pvt {
100         ast_mutex_t lock;                                       /* Channel private lock */
101         call_options_t calloptions;                             /* Options to be used during call setup */
102         int alreadygone;                                        /* Whether or not we've already been destroyed by or peer */
103         int needdestroy;                                        /* if we need to be destroyed */
104         call_details_t cd;                                      /* Call details */
105         struct ast_channel *owner;                              /* Who owns us */
106         int capability;                                         /* audio capability */
107         int nonCodecCapability;                                 /* non-audio capability */
108         int outgoing;                                           /* Outgoing or incoming call? */
109         int nat;                                                /* Are we talking to a NAT EP?*/
110         int bridge;                                             /* Determine of we should native bridge or not*/
111         char exten[AST_MAX_EXTENSION];                          /* Requested extension */
112         char context[AST_MAX_EXTENSION];                        /* Context where to start */
113         char username[81];                                      /* H.323 alias using this channel */
114         char accountcode[256];                                  /* Account code */
115         int amaflags;                                           /* AMA Flags */
116         char callerid[80];                                      /* Caller*ID if available */
117         struct ast_rtp *rtp;                                    /* RTP Session */
118         int dtmfmode;                                           /* What DTMF Mode is being used */
119         struct ast_dsp *vad;                                    /* Used for in-band DTMF detection */
120         struct oh323_pvt *next;                                 /* Next channel in list */
121 } *iflist = NULL;
122
123 static struct ast_user_list {
124         struct oh323_user *users;
125         ast_mutex_t lock;
126 } userl = { NULL, AST_MUTEX_INITIALIZER };
127
128 static struct ast_peer_list {
129         struct oh323_peer *peers;
130         ast_mutex_t lock;
131 } peerl = { NULL, AST_MUTEX_INITIALIZER };
132
133 static struct ast_alias_list {
134         struct oh323_alias *aliases;
135         ast_mutex_t lock;
136 } aliasl = { NULL, AST_MUTEX_INITIALIZER };
137
138 /** Asterisk RTP stuff*/
139 static struct sched_context *sched;
140 static struct io_context *io;
141
142 /** Protect the interface list (of oh323_pvt's) */
143 static ast_mutex_t iflock = AST_MUTEX_INITIALIZER;
144
145 /** Usage counter and associated lock */
146 static int usecnt =0;
147 static ast_mutex_t usecnt_lock = AST_MUTEX_INITIALIZER;
148
149 /* Protect the monitoring thread, so only one process can kill or start it, and not
150    when it's doing something critical. */
151 static ast_mutex_t monlock = AST_MUTEX_INITIALIZER;
152
153 /* This is the thread for the monitor which checks for input on the channels
154    which are not currently in use.  */
155 static pthread_t monitor_thread = AST_PTHREADT_NULL;
156
157 static int restart_monitor(void);
158
159 static void __oh323_destroy(struct oh323_pvt *p)
160 {
161         struct oh323_pvt *cur, *prev = NULL;
162         
163         if (p->rtp) {
164                 ast_rtp_destroy(p->rtp);
165         }
166         
167         /* Unlink us from the owner if we have one */
168         if (p->owner) {
169                 ast_mutex_lock(&p->owner->lock);
170                 ast_log(LOG_DEBUG, "Detaching from %s\n", p->owner->name);
171                 p->owner->pvt->pvt = NULL;
172                 ast_mutex_unlock(&p->owner->lock);
173         }
174         cur = iflist;
175         while(cur) {
176                 if (cur == p) {
177                         if (prev)
178                                 prev->next = cur->next;
179                         else
180                                 iflist = cur->next;
181                         break;
182                 }
183                 prev = cur;
184                 cur = cur->next;
185         }
186         if (!cur) {
187                 ast_log(LOG_WARNING, "%p is not in list?!?! \n", cur);
188         } else
189                 free(p);
190 }
191
192 static void oh323_destroy(struct oh323_pvt *p)
193 {
194         ast_mutex_lock(&iflock);
195         __oh323_destroy(p);
196         ast_mutex_unlock(&iflock);
197 }
198
199 static struct oh323_alias *build_alias(char *name, struct ast_variable *v)
200 {
201         struct oh323_alias *alias;
202
203         alias = (struct oh323_alias *)malloc(sizeof(struct oh323_alias));
204
205         if (alias) {
206                 memset(alias, 0, sizeof(struct oh323_alias));
207                 strncpy(alias->name, name, sizeof(alias->name)-1);
208
209                 while (v) {
210                         if (!strcasecmp(v->name, "e164")) {
211                                 strncpy(alias->e164,  v->value, sizeof(alias->e164)-1);
212                         } else if (!strcasecmp(v->name, "prefix")) {
213                                 strncpy(alias->prefix,  v->value, sizeof(alias->prefix)-1);
214                         } else if (!strcasecmp(v->name, "context")) {
215                                 strncpy(alias->context,  v->value, sizeof(alias->context)-1);
216                         } else if (!strcasecmp(v->name, "secret")) {
217                                 strncpy(alias->secret,  v->value, sizeof(alias->secret)-1);
218                         } else {
219                                 if (strcasecmp(v->value, "h323")) {     
220                                         ast_log(LOG_WARNING, "Keyword %s does not make sense in type=h323\n", v->value);
221                                 }
222                         }
223                         v = v->next;
224                 }
225         }
226         return alias;
227 }
228
229 static struct oh323_user *build_user(char *name, struct ast_variable *v)
230 {
231         struct oh323_user *user;
232         int format;
233         
234         user = (struct oh323_user *)malloc(sizeof(struct oh323_user));
235         if (user) {
236                 memset(user, 0, sizeof(struct oh323_user));
237                 strncpy(user->name, name, sizeof(user->name)-1);
238                 
239                 /* set the usage flag to a sane starting value*/
240                 user->inUse = 0;
241                 /* Assume we can native bridge */
242                 user->bridge = bridge_default; 
243
244                 while(v) {
245                         if (!strcasecmp(v->name, "context")) {
246                                 strncpy(user->context, v->value, sizeof(user->context)-1);
247                         } else if (!strcasecmp(v->name, "bridge")) {
248                                 user->bridge = ast_true(v->value);
249                       } else if (!strcasecmp(v->name, "nat")) {
250                               user->nat = ast_true(v->value);
251                         } else if (!strcasecmp(v->name, "noFastStart")) {
252                                 user->noFastStart = ast_true(v->value);
253                         } else if (!strcasecmp(v->name, "noH245Tunneling")) {
254                                 user->noH245Tunneling = ast_true(v->value);
255                         } else if (!strcasecmp(v->name, "noSilenceSuppression")) {
256                                 user->noSilenceSuppression = ast_true(v->value);
257                         } else if (!strcasecmp(v->name, "secret")) {
258                                 strncpy(user->secret, v->value, sizeof(user->secret)-1);
259                         } else if (!strcasecmp(v->name, "callerid")) {
260                                 strncpy(user->callerid, v->value, sizeof(user->callerid)-1);
261                         } else if (!strcasecmp(v->name, "accountcode")) {
262                                 strncpy(user->accountcode, v->value, sizeof(user->accountcode)-1);
263                         } else if (!strcasecmp(v->name, "incominglimit")) {
264                                 user->incominglimit = atoi(v->value);
265                                 if (user->incominglimit < 0)
266                                         user->incominglimit = 0;
267                         } else if (!strcasecmp(v->name, "host")) {
268                                 if (!strcasecmp(v->value, "dynamic")) {
269                                         ast_log(LOG_ERROR, "Dynamic host configuration not implemented, yet!\n");
270                                         free(user);
271                                         return NULL;
272                                 } else if (ast_get_ip(&user->addr, v->value)) {
273                                         free(user);
274                                         return NULL;
275                                 } 
276                                 /* Let us know we need to use ip authentication */
277                                 user->host = 1;
278                         } else if (!strcasecmp(v->name, "amaflags")) {
279                                 format = ast_cdr_amaflags2int(v->value);
280                                 if (format < 0) {
281                                         ast_log(LOG_WARNING, "Invalid AMA Flags: %s at line %d\n", v->value, v->lineno);
282                                 } else {
283                                         user->amaflags = format;
284                                 }
285                         }
286                         v = v->next;
287                 }
288         }
289         return user;
290 }
291
292
293 static struct oh323_peer *build_peer(char *name, struct ast_variable *v)
294 {
295         struct oh323_peer *peer;
296         struct oh323_peer *prev;
297         int found=0;
298         
299         prev = NULL;
300         ast_mutex_lock(&peerl.lock);
301         peer = peerl.peers;
302
303         while(peer) {
304                 if (!strcasecmp(peer->name, name)) {    
305                         break;
306                 }
307                 prev = peer;
308                 peer = peer->next;
309         }
310
311         if (peer) {
312                 found++;
313                 /* Already in the list, remove it and it will be added back (or FREE'd) */
314                 if (prev) {
315                         prev->next = peer->next;
316                 } else {
317                         peerl.peers = peer->next;
318                 }
319                 ast_mutex_unlock(&peerl.lock);
320         } else {
321                 ast_mutex_unlock(&peerl.lock);
322                 peer = malloc(sizeof(struct oh323_peer));
323                 memset(peer, 0, sizeof(struct oh323_peer));
324         }
325         if (peer) {
326                 if (!found) {
327                         strncpy(peer->name, name, sizeof(peer->name)-1);
328                 }
329                 
330                 /* set the usage flag to a sane starting value*/
331                 peer->inUse = 0;
332
333                 while(v) {
334                         if (!strcasecmp(v->name, "context")) {
335                                 strncpy(peer->context, v->value, sizeof(peer->context)-1);
336                         }  else if (!strcasecmp(v->name, "bridge")) {
337                                 peer->bridge = ast_true(v->value);
338                         } else if (!strcasecmp(v->name, "noFastStart")) {
339                                 peer->noFastStart = ast_true(v->value);
340                         } else if (!strcasecmp(v->name, "noH245Tunneling")) {
341                                 peer->noH245Tunneling = ast_true(v->value);
342                         } else if (!strcasecmp(v->name, "noSilenceSuppression")) {
343                                 peer->noSilenceSuppression = ast_true(v->value);
344                         } else if (!strcasecmp(v->name, "outgoinglimit")) {
345                                 peer->outgoinglimit = atoi(v->value);
346                                 if (peer->outgoinglimit > 0)
347                                         peer->outgoinglimit = 0;
348                         } else if (!strcasecmp(v->name, "host")) {
349                                 if (!strcasecmp(v->value, "dynamic")) {
350                                         ast_log(LOG_ERROR, "Dynamic host configuration not implemented, yet!\n");
351                                         free(peer);
352                                         return NULL;
353                                 }
354                                 if (ast_get_ip(&peer->addr, v->value)) {
355                                                 free(peer);
356                                                 return NULL;
357                                 }
358                         } 
359                         v=v->next;
360                 }
361         }
362         return peer;
363 }
364
365
366
367 /**
368  * Send (play) the specified digit to the channel.
369  * 
370  */
371 static int oh323_digit(struct ast_channel *c, char digit)
372 {
373         struct oh323_pvt *p = c->pvt->pvt;
374         if (p && p->rtp && (p->dtmfmode & H323_DTMF_RFC2833)) {
375                 ast_rtp_senddigit(p->rtp, digit);
376         }
377         /* If in-band DTMF is desired, send that */
378         if (p->dtmfmode & H323_DTMF_INBAND)
379                 h323_send_tone(p->cd.call_token, digit);
380         return 0;
381 }
382
383
384 /**
385  * Make a call over the specified channel to the specified 
386  * destination. This function will parse the destination string
387  * and determine the address-number to call.
388  * Return -1 on error, 0 on success.
389  */
390 static int oh323_call(struct ast_channel *c, char *dest, int timeout)
391 {
392         int res;
393         struct oh323_pvt *p = c->pvt->pvt;
394         char called_addr[256];
395         char *tmp;
396
397         strtok_r(dest, "/", &(tmp));
398
399         ast_log(LOG_DEBUG, "dest=%s, timeout=%d.\n", dest, timeout);
400
401         if ((c->_state != AST_STATE_DOWN) && (c->_state != AST_STATE_RESERVED)) {
402                 ast_log(LOG_WARNING, "Line is already in use (%s)\n", c->name);
403                 return -1;
404         }
405         
406         /* outgoing call */
407         p->outgoing = 1;
408
409         /* Clear the call token */
410         if ((p->cd).call_token == NULL)
411                 (p->cd).call_token = (char *)malloc(128);
412
413         memset((char *)(p->cd).call_token, 0, 128);
414         
415         if (p->cd.call_token == NULL) {
416                 ast_log(LOG_ERROR, "Not enough memory.\n");
417                 return -1;
418         }
419
420         /* Build the address to call */
421         memset(called_addr, 0, sizeof(dest));
422         memcpy(called_addr, dest, sizeof(called_addr));
423
424         /* Copy callerid, if there is any */
425         if (c->callerid) {
426                 char *tmp = strchr(c->callerid, '"');
427                 if (!tmp) {
428                         p->calloptions.callerid = malloc(80); // evil
429                         // sprintf(p->calloptions.callerid, "\"%s\"", c->callerid);
430                         sprintf(p->calloptions.callerid, "\"\" <%s>", c->callerid);
431                 } else {
432                         p->calloptions.callerid = strdup(c->callerid);
433                 }       
434          }
435
436         res = h323_make_call(called_addr, &(p->cd), p->calloptions);
437
438         if (res) {
439                 ast_log(LOG_NOTICE, "h323_make_call failed(%s)\n", c->name);
440                 return -1;
441         }
442
443         ast_setstate(c, AST_STATE_RINGING);
444         return 0;
445 }
446
447
448 static int oh323_answer(struct ast_channel *c)
449 {
450         int res;
451
452         struct oh323_pvt *p = c->pvt->pvt;
453
454         res = h323_answering_call(p->cd.call_token, 0);
455         
456         if (c->_state != AST_STATE_UP)
457                 ast_setstate(c, AST_STATE_UP);
458
459         return res;
460 }
461
462 static int oh323_hangup(struct ast_channel *c)
463 {
464         struct oh323_pvt *p = c->pvt->pvt;
465         int needcancel = 0;
466         if (h323debug)
467                 ast_log(LOG_DEBUG, "oh323_hangup(%s)\n", c->name);
468         if (!c->pvt->pvt) {
469                 ast_log(LOG_DEBUG, "Asked to hangup channel not connected\n");
470                 return 0;
471         }
472         ast_mutex_lock(&p->lock);
473         /* Determine how to disconnect */
474         if (p->owner != c) {
475                 ast_log(LOG_WARNING, "Huh?  We aren't the owner?\n");
476                 ast_mutex_unlock(&p->lock);
477                 return 0;
478         }
479         if (!c || (c->_state != AST_STATE_UP))
480                 needcancel = 1;
481         /* Disconnect */
482         p = c->pvt->pvt;
483         
484         /* Free dsp used for in-band DTMF detection */
485         if (p->vad) {
486                 ast_dsp_free(p->vad);
487         }
488
489         p->owner = NULL;
490         c->pvt->pvt = NULL;
491
492         /* Start the process if it's not already started */
493         if (!p->alreadygone) {
494                 p->needdestroy = 1;
495                 if (h323_clear_call((p->cd).call_token)) { 
496                         ast_log(LOG_DEBUG, "ClearCall failed.\n");
497                 }
498         }
499
500         /* Update usage counter */
501         ast_mutex_lock(&usecnt_lock);
502         usecnt--;
503         if (usecnt < 0)
504                 ast_log(LOG_WARNING, "Usecnt < 0\n");
505         ast_mutex_unlock(&usecnt_lock);
506         ast_update_use_count();
507
508         ast_mutex_unlock(&p->lock);
509         return 0;
510 }
511
512 static struct ast_frame *oh323_rtp_read(struct oh323_pvt *p)
513 {
514         /* Retrieve audio/etc from channel.  Assumes p->lock is already held. */
515         struct ast_frame *f;
516         static struct ast_frame null_frame = { AST_FRAME_NULL, };
517
518       /* Only apply it for the first packet, we just need the correct ip/port */
519       if(p->nat)
520       {
521               ast_rtp_setnat(p->rtp,p->nat);
522               p->nat = 0;
523       }
524
525         f = ast_rtp_read(p->rtp);
526         /* Don't send RFC2833 if we're not supposed to */
527         if (f && (f->frametype == AST_FRAME_DTMF) && !(p->dtmfmode & H323_DTMF_RFC2833))
528                 return &null_frame;
529         if (p->owner) {
530                 /* We already hold the channel lock */
531                 if (f->frametype == AST_FRAME_VOICE) {
532                         if (f->subclass != p->owner->nativeformats) {
533                                 ast_log(LOG_DEBUG, "Oooh, format changed to %d\n", f->subclass);
534                                 p->owner->nativeformats = f->subclass;
535                                 ast_set_read_format(p->owner, p->owner->readformat);
536                                 ast_set_write_format(p->owner, p->owner->writeformat);
537                         }
538                 
539                         /* Do in-band DTMF detection */
540                         if (p->dtmfmode & H323_DTMF_INBAND) {
541                    f = ast_dsp_process(p->owner,p->vad,f);
542                                    if (f->frametype == AST_FRAME_DTMF)
543                                         ast_log(LOG_DEBUG, "Got in-band digit %c.\n", f->subclass);
544             }
545                         
546                         
547                 }
548         }
549         return f;
550 }
551
552
553 static struct ast_frame  *oh323_read(struct ast_channel *c)
554 {
555         struct ast_frame *fr;
556         struct oh323_pvt *p = c->pvt->pvt;
557         ast_mutex_lock(&p->lock);
558         fr = oh323_rtp_read(p);
559         ast_mutex_unlock(&p->lock);
560         return fr;
561 }
562
563 static int oh323_write(struct ast_channel *c, struct ast_frame *frame)
564 {
565         struct oh323_pvt *p = c->pvt->pvt;
566         int res = 0;
567         if (frame->frametype != AST_FRAME_VOICE) {
568                 if (frame->frametype == AST_FRAME_IMAGE)
569                         return 0;
570                 else {
571                         ast_log(LOG_WARNING, "Can't send %d type frames with H323 write\n", frame->frametype);
572                         return 0;
573                 }
574         } else {
575                 if (!(frame->subclass & c->nativeformats)) {
576                         ast_log(LOG_WARNING, "Asked to transmit frame type %d, while native formats is %d (read/write = %d/%d)\n",
577                                 frame->subclass, c->nativeformats, c->readformat, c->writeformat);
578                         return -1;
579                 }
580         }
581         if (p) {
582                 ast_mutex_lock(&p->lock);
583                 if (p->rtp) {
584                         res =  ast_rtp_write(p->rtp, frame);
585                 }
586                 ast_mutex_unlock(&p->lock);
587         }
588         return res;
589 }
590
591 /** FIXME: Can I acutally use this or does Open H.323 take care of everything? */
592 static int oh323_indicate(struct ast_channel *c, int condition)
593 {
594
595         struct oh323_pvt *p = c->pvt->pvt;
596         
597         switch(condition) {
598         case AST_CONTROL_RINGING:
599                 if (c->_state == AST_STATE_RING) {
600                 //      transmit_response(p, "180 Ringing", &p->initreq);
601                         break;
602                 }
603                 return 0;
604         case AST_CONTROL_BUSY:
605                 if (c->_state != AST_STATE_UP) {
606                 //      transmit_response(p, "600 Busy everywhere", &p->initreq);
607                         p->alreadygone = 1;
608                         ast_softhangup(c, AST_SOFTHANGUP_DEV);
609                         break;
610                 }
611                 return 0;
612         case AST_CONTROL_CONGESTION:
613                 if (c->_state != AST_STATE_UP) {
614                 //      transmit_response(p, "486 Busy here", &p->initreq);
615                         p->alreadygone = 1;
616                         ast_softhangup(c, AST_SOFTHANGUP_DEV);
617                         break;
618                 }
619                 return 0;
620         case -1:
621                 return -1;
622         default:
623                 ast_log(LOG_WARNING, "Don't know how to indicate condition %d\n", condition);
624                 return -1;
625         }
626         return 0;
627 }
628
629 // FIXME: WTF is this? Do I need this???
630 static int oh323_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
631 {
632         struct oh323_pvt *p = newchan->pvt->pvt;
633
634         ast_mutex_lock(&p->lock);
635         if (p->owner != oldchan) {
636                 ast_log(LOG_WARNING, "old channel wasn't %p but was %p\n", oldchan, p->owner);
637                 return -1;
638         }
639         p->owner = newchan;
640         ast_mutex_unlock(&p->lock);
641         return 0;
642 }
643
644 static struct ast_channel *oh323_new(struct oh323_pvt *i, int state, const char *host)
645 {
646         struct ast_channel *ch;
647         int fmt;
648         ch = ast_channel_alloc(1);
649         
650         if (ch) {
651                 
652                 snprintf(ch->name, sizeof(ch->name)-1, "H323/%s", host);
653                 ch->nativeformats = i->capability;
654                 if (!ch->nativeformats)
655                         ch->nativeformats = capability;
656                 fmt = ast_best_codec(ch->nativeformats);
657                 ch->type = type;
658                 ch->fds[0] = ast_rtp_fd(i->rtp);
659                 ast_setstate(ch, state);
660                 
661                 if (state == AST_STATE_RING)
662                         ch->rings = 1;
663                 
664                 ch->writeformat = fmt;
665                 ch->pvt->rawwriteformat = fmt;
666                 ch->readformat = fmt;
667                 ch->pvt->rawreadformat = fmt;
668                 
669                 /* Allocate dsp for in-band DTMF support */
670                 if (i->dtmfmode & H323_DTMF_INBAND) {
671                         i->vad = ast_dsp_new();
672                         ast_dsp_set_features(i->vad, DSP_FEATURE_DTMF_DETECT);
673                 }
674
675                 /* Register the OpenH323 channel's functions. */
676                 ch->pvt->pvt = i;
677                 ch->pvt->send_digit = oh323_digit;
678                 ch->pvt->call = oh323_call;
679                 ch->pvt->hangup = oh323_hangup;
680                 ch->pvt->answer = oh323_answer;
681                 ch->pvt->read = oh323_read;
682                 ch->pvt->write = oh323_write;
683                 ch->pvt->indicate = oh323_indicate;
684                 ch->pvt->fixup = oh323_fixup;
685 //              ch->pvt->bridge = ast_rtp_bridge;
686
687                 /*  Set the owner of this channel */
688                 i->owner = ch;
689                 
690                 ast_mutex_lock(&usecnt_lock);
691                 usecnt++;
692                 ast_mutex_unlock(&usecnt_lock);
693                 ast_update_use_count();
694                 strncpy(ch->context, i->context, sizeof(ch->context)-1);
695                 strncpy(ch->exten, i->exten, sizeof(ch->exten)-1);              
696                 ch->priority = 1;
697                 if (strlen(i->callerid))
698                         ch->callerid = strdup(i->callerid);
699                 if (strlen(i->accountcode))
700                         strncpy(ch->accountcode, i->accountcode, sizeof(ch->accountcode)-1);
701                 if (i->amaflags)
702                         ch->amaflags = i->amaflags;
703                 if (state != AST_STATE_DOWN) {
704                         if (ast_pbx_start(ch)) {
705                                 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", ch->name);
706                                 ast_hangup(ch);
707                                 ch = NULL;
708                         }
709                 }
710         } else
711                 ast_log(LOG_WARNING, "Unable to allocate channel structure\n");
712         return ch;
713 }
714
715 static struct oh323_pvt *oh323_alloc(int callid)
716 {
717         struct oh323_pvt *p;
718
719         p = malloc(sizeof(struct oh323_pvt));
720         if (!p) {
721                 ast_log(LOG_ERROR, "Couldn't allocate private structure. This is bad\n");
722                 return NULL;
723         }
724
725         /* Keep track of stuff */
726         memset(p, 0, sizeof(struct oh323_pvt));
727         p->rtp = ast_rtp_new(sched, io, 1, 0);
728
729         if (!p->rtp) {
730                 ast_log(LOG_WARNING, "Unable to create RTP session: %s\n", strerror(errno));
731                 free(p);
732                 return NULL;
733         }
734         ast_rtp_settos(p->rtp, tos);
735         ast_mutex_init(&p->lock);
736         
737         p->cd.call_reference = callid;
738         p->bridge = bridge_default;
739         
740         p->dtmfmode = dtmfmode;
741         if (p->dtmfmode & H323_DTMF_RFC2833)
742                 p->nonCodecCapability |= AST_RTP_DTMF;
743
744         /* Add to interface list */
745         ast_mutex_lock(&iflock);
746         p->next = iflist;
747         iflist = p;
748         ast_mutex_unlock(&iflock);
749         return p;
750 }
751
752 static struct oh323_pvt *find_call(int call_reference)
753 {  
754         struct oh323_pvt *p;
755
756                 ast_mutex_lock(&iflock);
757         p = iflist; 
758
759         while(p) {
760                 if (p->cd.call_reference == call_reference) {
761                         /* Found the call */                                            
762                                                 ast_mutex_unlock(&iflock);
763                                                 return p;
764                 }
765                 p = p->next; 
766         }
767         ast_mutex_unlock(&iflock);
768                 return NULL;
769         
770 }
771
772 static struct ast_channel *oh323_request(char *type, int format, void *data)
773 {
774
775         int oldformat;
776         struct oh323_pvt *p;
777         struct ast_channel *tmpc = NULL;
778         char *dest = data;
779         char *ext, *host;
780         char *h323id = NULL;
781         char tmp[256];
782
783         
784         ast_log(LOG_DEBUG, "type=%s, format=%d, data=%s.\n", type, format, (char *)data);
785
786         oldformat = format;
787         format &= capability;
788         if (!format) {
789                 ast_log(LOG_NOTICE, "Asked to get a channel of unsupported format '%d'\n", format);
790                 return NULL;
791         }
792         
793         strncpy(tmp, dest, sizeof(tmp) - 1);
794                 
795         host = strchr(tmp, '@');
796         if (host) {
797                 *host = '\0';
798                 host++;
799                 ext = tmp;
800         } else {
801                 host = tmp;
802                 ext = NULL;
803         }
804
805         strtok_r(host, "/", &(h323id));
806                 
807         if (*h323id) {
808                 h323_set_id(h323id);
809         }
810                 
811         p = oh323_alloc(0);
812
813         if (!p) {
814                 ast_log(LOG_WARNING, "Unable to build pvt data for '%s'\n", (char *)data);
815                 return NULL;
816         }
817
818         /* Assign a default capability */
819         p->capability = capability;
820         
821         if (p->dtmfmode) {
822                 if (p->dtmfmode & H323_DTMF_RFC2833)
823                         p->nonCodecCapability |= AST_RTP_DTMF;
824                 else
825                         p->nonCodecCapability &= ~AST_RTP_DTMF;
826         }
827         /* pass on our preferred codec to the H.323 stack */
828         h323_set_capability(format, dtmfmode);
829
830         if (ext) {
831                 strncpy(p->username, ext, sizeof(p->username) - 1);
832         }
833         ast_log(LOG_DEBUG, "Host: %s\tUsername: %s\n", host, p->username);
834
835         tmpc = oh323_new(p, AST_STATE_DOWN, host);
836         if (!tmpc)
837                 oh323_destroy(p);
838         
839         restart_monitor();
840         
841         return tmpc;
842 }
843
844 struct oh323_alias *find_alias(const char *source_aliases)
845 {
846         struct oh323_alias *a;
847
848         a = aliasl.aliases;
849
850         while(a) {
851
852                 if (!strcasecmp(a->name, source_aliases)) {
853                         break;
854                 }
855                 a = a->next;
856         }
857         return a;
858 }
859
860 struct oh323_user *find_user(const call_details_t cd)
861 {
862         struct oh323_user *u;
863
864         u = userl.users;
865         if(userbyalias == 1){
866                 while(u) {
867                         if (!strcasecmp(u->name, cd.call_source_aliases)) {
868                                 break;
869                         }
870                         u = u->next;
871                 }
872
873         } else {
874                 while(u) {
875                         if (!strcasecmp(cd.sourceIp, inet_ntoa(u->addr.sin_addr))) {
876                                 break;
877                         }
878                         u = u->next;
879                 }
880
881         
882         }
883         return u;
884
885 }
886
887 struct oh323_peer *find_peer(char *dest_peer)
888 {
889         struct oh323_peer *p;
890
891         p = peerl.peers;
892
893         while(p) {
894                 if (!strcasecmp(p->name, dest_peer)) {
895                         break;
896                 }
897                 p = p->next;
898         }
899         return p;
900
901 }
902
903 /**
904   * Callback for sending digits from H.323 up to asterisk
905   *
906   */
907 int send_digit(unsigned call_reference, char digit)
908 {
909         struct oh323_pvt *p;
910         struct ast_frame f;
911
912         ast_log(LOG_DEBUG, "Recieved Digit: %c\n", digit);
913         p = find_call(call_reference);
914         
915         if (!p) {
916                 ast_log(LOG_ERROR, "Private structure not found in send_digit.\n");
917                 return -1;
918         }
919         memset(&f, 0, sizeof(f));
920         f.frametype = AST_FRAME_DTMF;
921     f.subclass = digit;
922     f.datalen = 0;
923     f.samples = 300;
924         f.offset = 0;
925         f.data = NULL;
926     f.mallocd = 0;
927     f.src = "SEND_DIGIT";
928         
929         return ast_queue_frame(p->owner, &f);   
930 }
931
932 /**
933   * Call-back function that gets called when any H.323 connection is made
934   *
935   * Returns the local RTP information
936   */
937 struct rtp_info *create_connection(unsigned call_reference)
938 {       
939         struct oh323_pvt *p;
940         struct sockaddr_in us;
941         struct sockaddr_in them;
942         struct rtp_info *info;
943
944         info = malloc(sizeof(struct rtp_info));
945
946         p = find_call(call_reference);
947
948         if (!p) {
949                 ast_log(LOG_ERROR, "Unable to allocate private structure, this is very bad.\n");
950                 return NULL;
951         }
952
953         /* figure out our local RTP port and tell the H.323 stack about it*/
954         ast_rtp_get_us(p->rtp, &us);
955         ast_rtp_get_peer(p->rtp, &them);
956
957
958         info->addr = inet_ntoa(us.sin_addr);
959         info->port = ntohs(us.sin_port);
960
961
962         return info;
963 }
964
965 /**
966  *  Call-back function for incoming calls
967  *
968  *  Returns 1 on success
969  */
970
971 int setup_incoming_call(call_details_t cd)
972 {
973         
974         struct oh323_pvt *p = NULL;
975         struct ast_channel *c = NULL;
976         struct oh323_user *user = NULL;
977         struct oh323_alias *alias = NULL;
978
979         /* allocate the call*/
980         p = oh323_alloc(cd.call_reference);
981
982         if (!p) {
983                 ast_log(LOG_ERROR, "Unable to allocate private structure, this is bad.\n");
984                 return 0;
985         }
986
987         /* Populate the call details in the private structure */
988         p->cd.call_token = cd.call_token;
989         p->cd.call_source_aliases = cd.call_source_aliases;
990         p->cd.call_dest_alias = cd.call_dest_alias;
991         p->cd.call_source_e164 = cd.call_source_e164;
992         p->cd.call_dest_e164 = cd.call_dest_e164;
993
994         if (h323debug) {
995                 ast_verbose(VERBOSE_PREFIX_3 "Setting up Call\n");
996                 ast_verbose(VERBOSE_PREFIX_3 "     Call token:  [%s]\n", p->cd.call_token);
997                 ast_verbose(VERBOSE_PREFIX_3 "     Calling party name:  [%s]\n", p->cd.call_source_aliases);
998                 ast_verbose(VERBOSE_PREFIX_3 "     Calling party number:  [%s]\n", p->cd.call_source_e164);
999                 ast_verbose(VERBOSE_PREFIX_3 "     Called  party name:  [%s]\n", p->cd.call_dest_alias);
1000                 ast_verbose(VERBOSE_PREFIX_3 "     Called  party number:  [%s]\n", p->cd.call_dest_e164);
1001         }
1002
1003         /* Decide if we are allowing Gatekeeper routed calls*/
1004         if ((!strcasecmp(cd.sourceIp, gatekeeper)) && (gkroute == -1) && (usingGk == 1)) {
1005                 
1006                 if (strlen(cd.call_dest_e164)) {
1007                         strncpy(p->exten, cd.call_dest_e164, sizeof(p->exten)-1);
1008                         strncpy(p->context, default_context, sizeof(p->context)-1); 
1009                 } else {
1010                         alias = find_alias(cd.call_dest_alias);
1011                 
1012                         if (!alias) {
1013                                 ast_log(LOG_ERROR, "Call for %s rejected, alias not found\n", cd.call_dest_alias);
1014                                 return 0;
1015                         }
1016                         strncpy(p->exten, alias->name, sizeof(p->exten)-1);
1017                         strncpy(p->context, alias->context, sizeof(p->context)-1);
1018                 }
1019
1020
1021                 sprintf(p->callerid, "%s <%s>", p->cd.call_source_aliases, p->cd.call_source_e164);
1022
1023         } else { 
1024                 /* Either this call is not from the Gatekeeper 
1025                    or we are not allowing gk routed calls */
1026                 
1027
1028                 user  = find_user(cd);
1029
1030
1031                 if (!user) {
1032                         sprintf(p->callerid, "%s <%s>", p->cd.call_source_aliases, p->cd.call_source_e164); 
1033                         if (strlen(p->cd.call_dest_e164)) {
1034                                 strncpy(p->exten, cd.call_dest_e164, sizeof(p->exten)-1);
1035                         } else {
1036                                 strncpy(p->exten, cd.call_dest_alias, sizeof(p->exten)-1);              
1037                         }
1038                         if (!strlen(default_context)) {
1039                                 ast_log(LOG_ERROR, "Call from user '%s' rejected due to no default context\n", p->cd.call_source_aliases);
1040                                 return 0;
1041                         }
1042                         strncpy(p->context, default_context, sizeof(p->context)-1);
1043                         ast_log(LOG_DEBUG, "Sending %s to context [%s]\n", cd.call_source_aliases, p->context);
1044                 } else {                                        
1045                         if (user->host) {
1046                                 if (strcasecmp(cd.sourceIp, inet_ntoa(user->addr.sin_addr))){
1047                                         
1048                                         if(!strlen(default_context)) {
1049                                                 ast_log(LOG_ERROR, "Call from user '%s' rejected due to non-matching IP address of '%s'\n", user->name, cd.sourceIp);
1050                                                 return 0;
1051                                         }
1052                                         
1053                                         strncpy(p->context, default_context, sizeof(p->context)-1);
1054                                         sprintf(p->exten,"i");
1055
1056                                         goto exit;                                      
1057                                 }
1058                         }
1059                         if (user->incominglimit > 0) {
1060                                 if (user->inUse >= user->incominglimit) {
1061                                         ast_log(LOG_ERROR, "Call from user '%s' rejected due to usage limit of %d\n", user->name, user->incominglimit);
1062                                         return 0;
1063                                 }
1064                         }
1065                         strncpy(p->context, user->context, sizeof(p->context)-1);
1066                         p->bridge = user->bridge;
1067                       p->nat = user->nat;
1068
1069                         if (strlen(user->callerid)) 
1070                                 strncpy(p->callerid, user->callerid, sizeof(p->callerid) - 1);
1071                         else
1072                                 sprintf(p->callerid, "%s <%s>", p->cd.call_source_aliases, p->cd.call_source_e164); 
1073
1074                         if (strlen(p->cd.call_dest_e164)) {
1075                                 strncpy(p->exten, cd.call_dest_e164, sizeof(p->exten)-1);
1076                         } else {
1077                                 strncpy(p->exten, cd.call_dest_alias, sizeof(p->exten)-1);              
1078                         }
1079                         if (strlen(user->accountcode)) {
1080                                 strncpy(p->accountcode, user->accountcode, sizeof(p->accountcode)-1);
1081                         } 
1082
1083                         /* Increment the usage counter */
1084                         user->inUse++;
1085                 } 
1086         }
1087
1088 /* I know this is horrid, don't kill me saddam */
1089 exit:
1090         /* allocate a channel and tell asterisk about it */
1091         c = oh323_new(p, AST_STATE_RINGING, cd.call_token);
1092         if (!c) {
1093                 ast_log(LOG_ERROR, "Couldn't create channel. This is bad\n");
1094                 return 0;
1095         }
1096
1097         return 1;
1098 }
1099
1100 /**
1101  * Call-back function to establish an outgoing H.323 call
1102  * 
1103  * Returns 1 on success 
1104  */
1105 int setup_outgoing_call(call_details_t cd)
1106 {       
1107         return 1;
1108 }
1109
1110 #if 0
1111 if (p->inUse >= p->outgoinglimit) {
1112         ast_log(LOG_ERROR, "Call to %s rejected due to usage limit of %d outgoing channels\n", p->name, p->inUse);
1113         return 0;
1114 }
1115
1116 if (!p) {
1117         ast_log(LOG_ERROR, "Rejecting call: peer %s not found\n", dest_peer);
1118         return 0;
1119 }
1120 #endif
1121
1122 /**
1123   * Call-back function that gets called for each rtp channel opened 
1124   *
1125   * Returns nothing 
1126   */
1127 void setup_rtp_connection(unsigned call_reference, const char *remoteIp, int remotePort)
1128 {
1129         struct oh323_pvt *p = NULL;
1130         struct sockaddr_in them;
1131
1132         /* Find the call or allocate a private structure if call not found */
1133         p = find_call(call_reference);
1134
1135         if (!p) {
1136                 ast_log(LOG_ERROR, "Something is wrong: rtp\n");
1137                 return;
1138         }
1139
1140         them.sin_family = AF_INET;
1141         them.sin_addr.s_addr = inet_addr(remoteIp); // only works for IPv4
1142         them.sin_port = htons(remotePort);
1143         ast_rtp_set_peer(p->rtp, &them);
1144
1145         return;
1146 }
1147
1148 /**  
1149   *     Call-back function to signal asterisk that the channel has been answered 
1150   * Returns nothing
1151   */
1152 void connection_made(unsigned call_reference)
1153 {
1154         struct ast_channel *c = NULL;
1155         struct oh323_pvt *p = NULL;
1156         
1157         p = find_call(call_reference);
1158         
1159         if (!p)
1160                 ast_log(LOG_ERROR, "Something is wrong: connection\n");
1161
1162
1163         if (!p->owner) {
1164                 ast_log(LOG_ERROR, "Channel has no owner\n");
1165                 return;
1166         }
1167         c = p->owner;   
1168
1169         ast_setstate(c, AST_STATE_UP);
1170         return;
1171 }
1172
1173 /**
1174   * Call-back function to cleanup communication
1175   * Returns nothing,
1176   */
1177 void cleanup_connection(call_details_t cd)
1178 {       
1179         struct oh323_pvt *p = NULL;
1180 //      struct oh323_peer *peer = NULL;
1181         struct oh323_user *user = NULL;
1182         struct ast_rtp *rtp = NULL;
1183
1184         ast_log(LOG_DEBUG, "Cleaning up our mess\n");
1185         
1186         p = find_call(cd.call_reference);
1187
1188         if (!p) {
1189                 return;
1190         }
1191
1192         /* Decrement usage counter */
1193         if (!p->outgoing) {
1194                 user = find_user(cd);
1195                 
1196                 if(user)
1197                         user->inUse--;
1198         }
1199
1200 #if 0
1201                 if (p->outgoing) {
1202                 peer = find_peer(cd.call_dest_alias);
1203                 peer->inUse--;
1204         } else {
1205                 user = find_user(cd);
1206                 user->inUse--;
1207         }
1208 #endif
1209         
1210         if (p->rtp) {
1211                 rtp = p->rtp;
1212                 p->rtp = NULL;
1213                 /* Immediately stop RTP */
1214                 ast_rtp_destroy(rtp);
1215         }
1216         
1217         p->alreadygone = 1;
1218
1219         /* Send hangup */       
1220         if (p->owner)
1221                 ast_queue_hangup(p->owner);
1222
1223         p = NULL;
1224         return; 
1225 }
1226
1227 static void *do_monitor(void *data)
1228 {
1229         int res;
1230         struct oh323_pvt *oh323 = NULL;
1231         
1232                 for(;;) {
1233                 /* Check for interfaces needing to be killed */
1234                 ast_mutex_lock(&iflock);
1235 restartsearch:          
1236                 oh323 = iflist;
1237                 while(oh323) {
1238                         if (oh323->needdestroy) {
1239                                 __oh323_destroy(oh323);
1240                                 goto restartsearch;
1241                         }
1242                         oh323 = oh323->next;
1243                 }
1244                 ast_mutex_unlock(&iflock);
1245
1246                 /* Wait for sched or io */
1247                 res = ast_sched_wait(sched);
1248                 if ((res < 0) || (res > 1000))
1249                         res = 1000;
1250                 res = ast_io_wait(io, res);
1251
1252                 pthread_testcancel();
1253
1254                 ast_mutex_lock(&monlock);
1255                 if (res >= 0) 
1256                         ast_sched_runq(sched);
1257                 ast_mutex_unlock(&monlock);
1258         }
1259         /* Never reached */
1260         return NULL;
1261         
1262 }
1263
1264 static int restart_monitor(void)
1265 {
1266         /* If we're supposed to be stopped -- stay stopped */
1267         if (monitor_thread == AST_PTHREADT_STOP)
1268                 return 0;
1269         if (ast_mutex_lock(&monlock)) {
1270                 ast_log(LOG_WARNING, "Unable to lock monitor\n");
1271                 return -1;
1272         }
1273         if (monitor_thread == pthread_self()) {
1274                 ast_mutex_unlock(&monlock);
1275                 ast_log(LOG_WARNING, "Cannot kill myself\n");
1276                 return -1;
1277         }
1278         if (monitor_thread && (monitor_thread != AST_PTHREADT_NULL)) {
1279                 /* Wake up the thread */
1280                 pthread_kill(monitor_thread, SIGURG);
1281         } else {
1282                 /* Start a new monitor */
1283                 if (pthread_create(&monitor_thread, NULL, do_monitor, NULL) < 0) {
1284                         ast_mutex_unlock(&monlock);
1285                         ast_log(LOG_ERROR, "Unable to start monitor thread.\n");
1286                         return -1;
1287                 }
1288         }
1289         ast_mutex_unlock(&monlock);
1290         return 0;
1291 }
1292
1293 static int h323_do_trace(int fd, int argc, char *argv[])
1294 {
1295         if (argc != 3) {
1296                 return RESULT_SHOWUSAGE;
1297         }
1298         h323_debug(1, atoi(argv[2]));
1299         ast_cli(fd, "H.323 trace set to level %s\n", argv[2]);
1300         return RESULT_SUCCESS;
1301 }
1302
1303 static int h323_no_trace(int fd, int argc, char *argv[])
1304 {
1305         if (argc != 3) {
1306                 return RESULT_SHOWUSAGE;
1307         }
1308         h323_debug(0,0);
1309         ast_cli(fd, "H.323 trace disabled\n");
1310         return RESULT_SUCCESS;
1311 }
1312
1313 static int h323_do_debug(int fd, int argc, char *argv[])
1314 {
1315         if (argc != 2) {
1316                 return RESULT_SHOWUSAGE;
1317         }
1318         h323debug = 1;
1319         ast_cli(fd, "H323 debug enabled\n");
1320         return RESULT_SUCCESS;
1321 }
1322
1323 static int h323_no_debug(int fd, int argc, char *argv[])
1324 {
1325         if (argc != 3) {
1326                 return RESULT_SHOWUSAGE;
1327         }
1328         h323debug = 0;
1329         ast_cli(fd, "H323 Debug disabled\n");
1330         return RESULT_SUCCESS;
1331 }
1332
1333 static int h323_gk_cycle(int fd, int argc, char *argv[])
1334 {
1335         return RESULT_SUCCESS;
1336 #if 0
1337         if (argc != 3) {
1338                 return RESULT_SHOWUSAGE;
1339         }       
1340         h323_gk_urq();
1341         
1342         /* Possibly register with a GK */
1343         if (!gatekeeper_disable) {
1344                 if (h323_set_gk(gatekeeper_discover, gatekeeper, secret)) {
1345                         ast_log(LOG_ERROR, "Gatekeeper registration failed.\n");
1346                 }
1347         }
1348         return RESULT_SUCCESS;
1349 #endif
1350 }
1351
1352 static int h323_ep_hangup(int fd, int argc, char *argv[])
1353 {
1354
1355         if (argc != 3) {
1356                 return RESULT_SHOWUSAGE;
1357         }
1358
1359         if (h323_soft_hangup(argv[2])) {
1360                 ast_verbose(VERBOSE_PREFIX_3 "Hangup succeeded on %s\n", argv[2]);
1361         } else { 
1362                 ast_verbose(VERBOSE_PREFIX_3 "Hangup failed for %s\n", argv[2]);
1363         }
1364
1365         return RESULT_SUCCESS;
1366 }
1367
1368 static int h323_tokens_show(int fd, int argc, char *argv[])
1369 {
1370
1371         if (argc != 3) {
1372                 return RESULT_SHOWUSAGE;
1373         }
1374         h323_show_tokens();
1375
1376         return RESULT_SUCCESS;
1377 }
1378
1379
1380 static char trace_usage[] = 
1381 "Usage: h.323 trace <level num>\n"
1382 "       Enables H.323 stack tracing for debugging purposes\n";
1383
1384 static char no_trace_usage[] = 
1385 "Usage: h.323 no trace\n"
1386 "       Disables H.323 stack tracing for debugging purposes\n";
1387
1388 static char debug_usage[] = 
1389 "Usage: h.323 debug\n"
1390 "       Enables chan_h323 debug output\n";
1391
1392 static char no_debug_usage[] = 
1393 "Usage: h.323 no debug\n"
1394 "       Disables chan_h323 debug output\n";
1395
1396 static char show_codec_usage[] = 
1397 "Usage: h.323 show codec\n"
1398 "       Shows all enabled codecs\n";
1399
1400 static char show_cycle_usage[] = 
1401 "Usage: h.323 gk cycle\n"
1402 "       Manually re-register with the Gatekeper\n";
1403
1404 static char show_hangup_usage[] = 
1405 "Usage: h.323 hangup <token>\n"
1406 "       Manually try to hang up call identified by <token>\n";
1407
1408 static char show_tokens_usage[] = 
1409 "Usage: h.323 show tokens\n"
1410 "       Print out all active call tokens\n";
1411
1412 static struct ast_cli_entry  cli_trace =
1413         { { "h.323", "trace", NULL }, h323_do_trace, "Enable H.323 Stack Tracing", trace_usage };
1414 static struct ast_cli_entry  cli_no_trace =
1415         { { "h.323", "no", "trace", NULL }, h323_no_trace, "Disable H.323 Stack Tracing", no_trace_usage };
1416 static struct ast_cli_entry  cli_debug =
1417         { { "h.323", "debug", NULL }, h323_do_debug, "Enable chan_h323 debug", debug_usage };
1418 static struct ast_cli_entry  cli_no_debug =
1419         { { "h.323", "no", "debug", NULL }, h323_no_debug, "Disable chan_h323 debug", no_debug_usage };
1420 static struct ast_cli_entry  cli_show_codecs =
1421         { { "h.323", "show", "codecs", NULL }, h323_show_codec, "Show enabled codecs", show_codec_usage };
1422 static struct ast_cli_entry  cli_gk_cycle =
1423         { { "h.323", "gk", "cycle", NULL }, h323_gk_cycle, "Manually re-register with the Gatekeper", show_cycle_usage };
1424 static struct ast_cli_entry  cli_hangup_call =
1425         { { "h.323", "hangup", NULL }, h323_ep_hangup, "Manually try to hang up a call", show_hangup_usage };
1426 static struct ast_cli_entry  cli_show_tokens =
1427         { { "h.323", "show", "tokens", NULL }, h323_tokens_show, "Manually try to hang up a call", show_tokens_usage };
1428
1429
1430
1431 int reload_config(void)
1432 {
1433         
1434         int format;
1435         struct ast_config *cfg;
1436         struct ast_variable *v;
1437         struct oh323_peer *peer   = NULL;
1438         struct oh323_user *user   = NULL;
1439         struct oh323_alias *alias = NULL;
1440         struct hostent *hp;
1441         char *cat;
1442         char *utype;
1443         
1444         cfg = ast_load(config);
1445
1446         /* We *must* have a config file otherwise stop immediately */
1447         if (!cfg) {
1448                 ast_log(LOG_NOTICE, "Unable to load config %s, H.323 disabled\n", config);
1449                 return 1;
1450         }
1451         
1452        /* fire up the H.323 Endpoint */       
1453         if (!h323_end_point_exist()) {
1454                h323_end_point_create();        
1455         }
1456         h323debug=0;
1457         dtmfmode = H323_DTMF_RFC2833;
1458
1459         memset(&bindaddr, 0, sizeof(bindaddr));
1460
1461         v = ast_variable_browse(cfg, "general");
1462         while(v) {
1463                 /* Create the interface list */
1464                 if (!strcasecmp(v->name, "port")) {
1465                         port = (int)strtol(v->value, NULL, 10);
1466                 } else if (!strcasecmp(v->name, "bindaddr")) {
1467                         if (!(hp = gethostbyname(v->value))) {
1468                                 ast_log(LOG_WARNING, "Invalid address: %s\n", v->value);
1469                         } else {
1470                                 memcpy(&bindaddr.sin_addr, hp->h_addr, sizeof(bindaddr.sin_addr));
1471                         }
1472                 } else if (!strcasecmp(v->name, "allow")) {
1473                         format = ast_getformatbyname(v->value);
1474                         if (format < 1) 
1475                                 ast_log(LOG_WARNING, "Cannot allow unknown format '%s'\n", v->value);
1476                         else
1477                                 capability |= format;
1478                 } else if (!strcasecmp(v->name, "disallow")) {
1479                         format = ast_getformatbyname(v->value);
1480                         if (format < 1) 
1481                                 ast_log(LOG_WARNING, "Cannot disallow unknown format '%s'\n", v->value);
1482                         else
1483                                 capability &= ~format;
1484                 } else if (!strcasecmp(v->name, "tos")) {
1485                         if (sscanf(v->value, "%i", &format) == 1)
1486                                 tos = format & 0xff;
1487                         else if (!strcasecmp(v->value, "lowdelay"))
1488                                 tos = IPTOS_LOWDELAY;
1489                         else if (!strcasecmp(v->value, "throughput"))
1490                                 tos = IPTOS_THROUGHPUT;
1491                         else if (!strcasecmp(v->value, "reliability"))
1492                                 tos = IPTOS_RELIABILITY;
1493                         else if (!strcasecmp(v->value, "mincost"))
1494                                 tos = IPTOS_MINCOST;
1495                         else if (!strcasecmp(v->value, "none"))
1496                                 tos = 0;
1497                         else
1498                                 ast_log(LOG_WARNING, "Invalid tos value at line %d, should be 'lowdelay', 'throughput', 'reliability', 'mincost', or 'none'\n", v->lineno);
1499                 } else if (!strcasecmp(v->name, "gatekeeper")) {
1500                         if (!strcasecmp(v->value, "DISABLE")) {
1501                                 gatekeeper_disable = 1;
1502                                 usingGk = 0;
1503                         } else if (!strcasecmp(v->value, "DISCOVER")) {
1504                                 gatekeeper_disable = 0;
1505                                 gatekeeper_discover = 1;
1506                                 usingGk = 1;
1507                         } else {
1508                                 gatekeeper_disable = 0;
1509                                 usingGk = 1;
1510                                 strncpy(gatekeeper, v->value, sizeof(gatekeeper)-1);
1511                         }
1512                 } else if (!strcasecmp(v->name, "secret")) {
1513                                 strncpy(secret, v->value, sizeof(secret)-1);
1514                 } else if (!strcasecmp(v->name, "AllowGKRouted")) {
1515                                 gkroute = ast_true(v->value);
1516                 } else if (!strcasecmp(v->name, "context")) {
1517                         strncpy(default_context, v->value, sizeof(default_context)-1);
1518                         ast_verbose(VERBOSE_PREFIX_3 "  == Setting default context to %s\n", default_context);  
1519                 } else if (!strcasecmp(v->name, "dtmfmode")) {
1520                         if (!strcasecmp(v->value, "inband"))
1521                                 dtmfmode=H323_DTMF_INBAND;
1522                         else if (!strcasecmp(v->value, "rfc2833"))
1523                                 dtmfmode = H323_DTMF_RFC2833;
1524                         else {
1525                                 ast_log(LOG_WARNING, "Unknown dtmf mode '%s', using rfc2833\n", v->value);
1526                                 dtmfmode = H323_DTMF_RFC2833;
1527                         }
1528                 } else if (!strcasecmp(v->name, "UserByAlias")) {
1529                         userbyalias = ast_true(v->value);
1530                 } else if (!strcasecmp(v->name, "bridge")) {
1531                         bridge_default = ast_true(v->value);
1532                 }
1533                 v = v->next;    
1534         }
1535         
1536         cat = ast_category_browse(cfg, NULL);
1537         while(cat) {
1538                 if (strcasecmp(cat, "general")) {
1539                         utype = ast_variable_retrieve(cfg, cat, "type");
1540                         if (utype) {
1541                                 if (!strcasecmp(utype, "user") || !strcasecmp(utype, "friend")) {
1542                                         user = build_user(cat, ast_variable_browse(cfg, cat));
1543                                         if (user) {
1544                                                 ast_mutex_lock(&userl.lock);
1545                                                 user->next = userl.users;
1546                                                 userl.users = user;
1547                                                 ast_mutex_unlock(&userl.lock);
1548                                         }
1549                                 }  else if (!strcasecmp(utype, "peer") || !strcasecmp(utype, "friend")) {
1550                                         peer = build_peer(cat, ast_variable_browse(cfg, cat));
1551                                         if (peer) {
1552                                                 ast_mutex_lock(&peerl.lock);
1553                                                 peer->next = peerl.peers;
1554                                                 peerl.peers = peer;
1555                                                 ast_mutex_unlock(&peerl.lock);
1556                                         }
1557                                 }  else if (!strcasecmp(utype, "h323")) {                       
1558                                         alias = build_alias(cat, ast_variable_browse(cfg, cat));
1559                                         if (alias) {
1560                                                 ast_mutex_lock(&aliasl.lock);
1561                                                 alias->next = aliasl.aliases;
1562                                                 aliasl.aliases = alias;
1563                                                 ast_mutex_unlock(&aliasl.lock);
1564                                         }
1565                                 } else {
1566                                         ast_log(LOG_WARNING, "Unknown type '%s' for '%s' in %s\n", utype, cat, config);
1567                                 }
1568                         } else
1569                                 ast_log(LOG_WARNING, "Section '%s' lacks type\n", cat);
1570                 }
1571                 cat = ast_category_browse(cfg, cat);
1572         }
1573
1574         /* Register our H.323 aliases if any*/
1575         while (alias) {         
1576                 if (h323_set_alias(alias)) {
1577                         ast_log(LOG_ERROR, "Alias %s rejected by endpoint\n", alias->name);
1578                         return -1;
1579                 }       
1580                 alias = alias->next;
1581         }
1582
1583         /* Add some capabilities */
1584         if(h323_set_capability(capability, dtmfmode)) {
1585                 ast_log(LOG_ERROR, "Capabilities failure, this is bad.\n");
1586                 return -1;
1587         }       
1588         ast_destroy(cfg);
1589
1590         return 0;
1591 }
1592
1593 void delete_users(void)
1594 {
1595         struct oh323_user *user, *userlast;
1596         struct oh323_peer *peer;
1597         
1598         /* Delete all users */
1599         ast_mutex_lock(&userl.lock);
1600         for (user=userl.users;user;) {
1601                 userlast = user;
1602                 user=user->next;
1603                 free(userlast);
1604         }
1605         userl.users=NULL;
1606         ast_mutex_unlock(&userl.lock);
1607         ast_mutex_lock(&peerl.lock);
1608         for (peer=peerl.peers;peer;) {
1609                 /* Assume all will be deleted, and we'll find out for sure later */
1610                 peer->delme = 1;
1611                 peer = peer->next;
1612         }
1613         ast_mutex_unlock(&peerl.lock);
1614 }
1615
1616 void delete_aliases(void)
1617 {
1618         struct oh323_alias *alias, *aliaslast;
1619                 
1620         /* Delete all users */
1621         ast_mutex_lock(&aliasl.lock);
1622         for (alias=aliasl.aliases;alias;) {
1623                 aliaslast = alias;
1624                 alias=alias->next;
1625                 free(aliaslast);
1626         }
1627         aliasl.aliases=NULL;
1628         ast_mutex_unlock(&aliasl.lock);
1629 }
1630
1631 void prune_peers(void)
1632 {
1633         /* Prune peers who still are supposed to be deleted */
1634         struct oh323_peer *peer, *peerlast, *peernext;
1635         ast_mutex_lock(&peerl.lock);
1636         peerlast = NULL;
1637         for (peer=peerl.peers;peer;) {
1638                 peernext = peer->next;
1639                 if (peer->delme) {
1640                         free(peer);
1641                         if (peerlast)
1642                                 peerlast->next = peernext;
1643                         else
1644                                 peerl.peers = peernext;
1645                 } else
1646                         peerlast = peer;
1647                 peer=peernext;
1648         }
1649         ast_mutex_unlock(&peerl.lock);
1650 }
1651
1652 int reload(void)
1653 {
1654         delete_users();
1655         delete_aliases();
1656         prune_peers();
1657
1658 #if 0
1659         if (strlen(gatekeeper)) {
1660                 h323_gk_urq();
1661         }
1662 #endif
1663
1664         reload_config();
1665
1666 #if 0
1667         /* Possibly register with a GK */
1668         if (gatekeeper_disable == 0) {
1669                 if (h323_set_gk(gatekeeper_discover, gatekeeper, secret)) {
1670                         ast_log(LOG_ERROR, "Gatekeeper registration failed.\n");
1671                         h323_end_process();
1672                         return -1;
1673                 }
1674         }
1675 #endif
1676         restart_monitor();
1677         return 0;
1678 }
1679
1680
1681 static struct ast_rtp *oh323_get_rtp_peer(struct ast_channel *chan)
1682 {
1683         struct oh323_pvt *p;
1684         p = chan->pvt->pvt;
1685         if (p && p->rtp && p->bridge) {
1686                 return p->rtp;
1687         }
1688         return NULL;
1689 }
1690
1691 static struct ast_rtp *oh323_get_vrtp_peer(struct ast_channel *chan)
1692 {
1693         return NULL;
1694 }
1695
1696 static char *convertcap(int cap)
1697 {
1698         switch (cap) {
1699         case AST_FORMAT_G723_1:
1700                 return "G.723";
1701         case AST_FORMAT_GSM:
1702                 return "GSM";
1703         case AST_FORMAT_ULAW:
1704                 return "ULAW";
1705         case AST_FORMAT_ALAW:
1706                 return "ALAW";
1707         case AST_FORMAT_ADPCM:
1708                 return "G.728";
1709         case AST_FORMAT_G729A:
1710                 return "G.729";
1711         case AST_FORMAT_SPEEX:
1712                 return "SPEEX";
1713         case AST_FORMAT_ILBC:
1714                 return "ILBC";
1715         default:
1716                 ast_log(LOG_NOTICE, "Don't know how to deal with mode %d\n", cap);
1717                 return NULL;
1718         }
1719
1720 }
1721
1722 static int oh323_set_rtp_peer(struct ast_channel *chan, struct ast_rtp *rtp, struct ast_rtp *vrtp)
1723 {
1724         /* XXX Deal with Video */
1725         struct oh323_pvt *p;
1726         struct sockaddr_in them;
1727         struct sockaddr_in us;
1728         char *mode;
1729
1730         mode = convertcap(chan->writeformat); 
1731
1732         if (!rtp) {
1733                 return 0;
1734         }
1735
1736         p = chan->pvt->pvt;
1737         if (!p) {
1738                 ast_log(LOG_ERROR, "No Private Structure, this is bad\n");
1739                 return -1;
1740         }
1741
1742         ast_rtp_get_peer(rtp, &them);   
1743         ast_rtp_get_us(rtp, &us);
1744
1745
1746         h323_native_bridge(p->cd.call_token, inet_ntoa(them.sin_addr), mode);
1747         
1748         return 0;
1749         
1750 }
1751
1752 static struct ast_rtp_protocol oh323_rtp = {
1753         get_rtp_info: oh323_get_rtp_peer,
1754         get_vrtp_info: oh323_get_vrtp_peer,
1755         set_rtp_peer: oh323_set_rtp_peer,
1756 };
1757
1758
1759 int load_module()
1760 {
1761         int res;
1762
1763         res = reload_config();
1764
1765         if (res) {
1766                 return 0;
1767         } else {
1768                 /* Make sure we can register our channel type */
1769                 if (ast_channel_register(type, tdesc, capability, oh323_request)) {
1770                         ast_log(LOG_ERROR, "Unable to register channel class %s\n", type);
1771                         h323_end_process();
1772                         return -1;
1773                 }
1774                 ast_cli_register(&cli_debug);
1775                 ast_cli_register(&cli_no_debug);
1776                 ast_cli_register(&cli_trace);
1777                 ast_cli_register(&cli_no_trace);
1778                 ast_cli_register(&cli_show_codecs);
1779                 ast_cli_register(&cli_gk_cycle);
1780                 ast_cli_register(&cli_hangup_call);
1781                 ast_cli_register(&cli_show_tokens);
1782
1783                 oh323_rtp.type = type;
1784                 ast_rtp_proto_register(&oh323_rtp);
1785
1786                 sched = sched_context_create();
1787                 if (!sched) {
1788                         ast_log(LOG_WARNING, "Unable to create schedule context\n");
1789                 }
1790                 io = io_context_create();
1791                 if (!io) {
1792                         ast_log(LOG_WARNING, "Unable to create I/O context\n");
1793                 }
1794                 
1795                 /* Register our callback functions */
1796                 h323_callback_register(setup_incoming_call, 
1797                                        setup_outgoing_call,                                                      
1798                                        create_connection, 
1799                                        setup_rtp_connection, 
1800                                        cleanup_connection, 
1801                                        connection_made, 
1802                                        send_digit);     
1803         
1804
1805                 /* start the h.323 listener */
1806                 if (h323_start_listener(port, bindaddr)) {
1807                         ast_log(LOG_ERROR, "Unable to create H323 listener.\n");
1808 //                      h323_end_process();
1809                         return -1;
1810                 }
1811
1812                 /* Possibly register with a GK */
1813                 if (gatekeeper_disable == 0) {
1814                         if (h323_set_gk(gatekeeper_discover, gatekeeper, secret)) {
1815                                 ast_log(LOG_ERROR, "Gatekeeper registration failed.\n");
1816 //                              h323_end_process();
1817                                 return 0;
1818                         }
1819                 }
1820                 /* And start the monitor for the first time */
1821                 restart_monitor();
1822         }
1823         return res;
1824 }
1825
1826
1827 int unload_module() 
1828 {
1829         struct oh323_pvt *p, *pl;
1830                 
1831         if (!ast_mutex_lock(&iflock)) {
1832         /* hangup all interfaces if they have an owner */
1833         p = iflist;
1834         while(p) {
1835                 if (p->owner)
1836                         ast_softhangup(p->owner, AST_SOFTHANGUP_APPUNLOAD);
1837                 p = p->next;
1838         }
1839         iflist = NULL;
1840         ast_mutex_unlock(&iflock);
1841         } else {
1842                 ast_log(LOG_WARNING, "Unable to lock the interface list\n");
1843                 return -1;
1844         }
1845
1846         if (!ast_mutex_lock(&monlock)) {
1847                 if (monitor_thread && (monitor_thread != AST_PTHREADT_STOP)) {
1848                         pthread_cancel(monitor_thread);
1849                         pthread_kill(monitor_thread, SIGURG);
1850                         pthread_join(monitor_thread, NULL);
1851                  }
1852                 monitor_thread = AST_PTHREADT_STOP;
1853                 ast_mutex_unlock(&monlock);
1854         } else {
1855                 ast_log(LOG_WARNING, "Unable to lock the monitor\n");
1856                 return -1;
1857         }
1858                 
1859         if (!ast_mutex_lock(&iflock)) {
1860                 /* destroy all the interfaces and free their memory */
1861                 p = iflist;
1862                 while(p) {
1863                         pl = p;
1864                         p = p->next;
1865                         /* free associated memory */
1866                         free(pl);
1867                 }
1868                 iflist = NULL;
1869                 ast_mutex_unlock(&iflock);
1870         } else {
1871                 ast_log(LOG_WARNING, "Unable to lock the interface list\n");
1872                 return -1;
1873         }
1874         h323_gk_urq();
1875         h323_end_process();
1876
1877         /* unregister rtp */
1878         ast_rtp_proto_unregister(&oh323_rtp);
1879         
1880         /* unregister commands */
1881         ast_cli_unregister(&cli_debug);
1882         ast_cli_unregister(&cli_no_debug);
1883         ast_cli_unregister(&cli_trace);
1884         ast_cli_unregister(&cli_no_trace);   
1885         ast_cli_unregister(&cli_show_codecs);
1886         ast_cli_unregister(&cli_gk_cycle);
1887         ast_cli_unregister(&cli_hangup_call);
1888         ast_cli_unregister(&cli_show_tokens);
1889                         
1890         /* unregister channel type */
1891         ast_channel_unregister(type);
1892
1893         return 0; 
1894
1895
1896 int usecount()
1897 {
1898         int res;
1899         ast_mutex_lock(&usecnt_lock);
1900         res = usecnt;
1901         ast_mutex_unlock(&usecnt_lock);
1902         return res;
1903 }
1904
1905 char *description()
1906 {
1907         return desc;
1908 }
1909
1910 char *key()
1911 {
1912         return ASTERISK_GPL_KEY;
1913 }
1914
1915
1916
1917