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