db2ec980ff7504ff33ae4d95704b8c593f5bda93
[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 = cd.call_token;
1058         p->cd.call_source_aliases = cd.call_source_aliases;
1059         p->cd.call_dest_alias = cd.call_dest_alias;
1060         p->cd.call_source_name = cd.call_source_name;
1061         p->cd.call_source_e164 = cd.call_source_e164;
1062         p->cd.call_dest_e164 = 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   * Call-back function to cleanup communication
1296   * Returns nothing,
1297   */
1298 void cleanup_connection(call_details_t cd)
1299 {       
1300         struct oh323_pvt *p = NULL;
1301 /*      struct oh323_peer *peer = NULL; */
1302         struct oh323_user *user = NULL;
1303         struct ast_rtp *rtp = NULL;
1304         
1305         p = find_call(cd.call_reference);
1306
1307         if (!p) {
1308                 return;
1309         }
1310         ast_mutex_lock(&p->lock);
1311
1312         /* Decrement usage counter */
1313         if (!p->outgoing) {
1314                 user = find_user(cd);
1315                 
1316                 if(user) {
1317                         user->inUse--;
1318                 }
1319         }
1320
1321 #if 0
1322         if (p->outgoing) {
1323                 peer = find_peer(cd.call_dest_alias);
1324                 peer->inUse--;
1325         } else {
1326                 user = find_user(cd);
1327                 user->inUse--;
1328         }
1329 #endif
1330         
1331         if (p->rtp) {
1332                 rtp = p->rtp;
1333                 p->rtp = NULL;
1334                 /* Immediately stop RTP */
1335                 ast_rtp_destroy(rtp);
1336         }
1337
1338         p->alreadygone = 1;
1339         
1340         /* Send hangup */       
1341         if (p->owner) {
1342                 ast_queue_hangup(p->owner);
1343         } 
1344
1345         ast_mutex_unlock(&p->lock);
1346         return; 
1347 }
1348
1349 static void *do_monitor(void *data)
1350 {
1351         int res;
1352         struct oh323_pvt *oh323 = NULL;
1353         
1354                 for(;;) {
1355                 /* Check for interfaces needing to be killed */
1356                 ast_mutex_lock(&iflock);
1357 restartsearch:          
1358                 oh323 = iflist;
1359                 while(oh323) {
1360                         if (oh323->needdestroy) {
1361                                 __oh323_destroy(oh323);
1362                                 goto restartsearch;
1363                         }
1364                         oh323 = oh323->next;
1365                 }
1366                 ast_mutex_unlock(&iflock);
1367
1368                 /* Wait for sched or io */
1369                 res = ast_sched_wait(sched);
1370                 if ((res < 0) || (res > 1000))
1371                         res = 1000;
1372                 res = ast_io_wait(io, res);
1373
1374                 pthread_testcancel();
1375
1376                 ast_mutex_lock(&monlock);
1377                 if (res >= 0) 
1378                         ast_sched_runq(sched);
1379                 ast_mutex_unlock(&monlock);
1380         }
1381         /* Never reached */
1382         return NULL;
1383         
1384 }
1385
1386 static int restart_monitor(void)
1387 {
1388         /* If we're supposed to be stopped -- stay stopped */
1389         if (monitor_thread == AST_PTHREADT_STOP)
1390                 return 0;
1391         if (ast_mutex_lock(&monlock)) {
1392                 ast_log(LOG_WARNING, "Unable to lock monitor\n");
1393                 return -1;
1394         }
1395         if (monitor_thread == pthread_self()) {
1396                 ast_mutex_unlock(&monlock);
1397                 ast_log(LOG_WARNING, "Cannot kill myself\n");
1398                 return -1;
1399         }
1400         if (monitor_thread && (monitor_thread != AST_PTHREADT_NULL)) {
1401                 /* Wake up the thread */
1402                 pthread_kill(monitor_thread, SIGURG);
1403         } else {
1404                 /* Start a new monitor */
1405                 if (pthread_create(&monitor_thread, NULL, do_monitor, NULL) < 0) {
1406                         ast_mutex_unlock(&monlock);
1407                         ast_log(LOG_ERROR, "Unable to start monitor thread.\n");
1408                         return -1;
1409                 }
1410         }
1411         ast_mutex_unlock(&monlock);
1412         return 0;
1413 }
1414
1415 static int h323_do_trace(int fd, int argc, char *argv[])
1416 {
1417         if (argc != 3) {
1418                 return RESULT_SHOWUSAGE;
1419         }
1420         h323_debug(1, atoi(argv[2]));
1421         ast_cli(fd, "H.323 trace set to level %s\n", argv[2]);
1422         return RESULT_SUCCESS;
1423 }
1424
1425 static int h323_no_trace(int fd, int argc, char *argv[])
1426 {
1427         if (argc != 3) {
1428                 return RESULT_SHOWUSAGE;
1429         }
1430         h323_debug(0,0);
1431         ast_cli(fd, "H.323 trace disabled\n");
1432         return RESULT_SUCCESS;
1433 }
1434
1435 static int h323_do_debug(int fd, int argc, char *argv[])
1436 {
1437         if (argc != 2) {
1438                 return RESULT_SHOWUSAGE;
1439         }
1440         h323debug = 1;
1441         ast_cli(fd, "H323 debug enabled\n");
1442         return RESULT_SUCCESS;
1443 }
1444
1445 static int h323_no_debug(int fd, int argc, char *argv[])
1446 {
1447         if (argc != 3) {
1448                 return RESULT_SHOWUSAGE;
1449         }
1450         h323debug = 0;
1451         ast_cli(fd, "H323 Debug disabled\n");
1452         return RESULT_SUCCESS;
1453 }
1454
1455 static int h323_gk_cycle(int fd, int argc, char *argv[])
1456 {
1457         return RESULT_SUCCESS;
1458 #if 0
1459         if (argc != 3) {
1460                 return RESULT_SHOWUSAGE;
1461         }       
1462         h323_gk_urq();
1463         
1464         /* Possibly register with a GK */
1465         if (!gatekeeper_disable) {
1466                 if (h323_set_gk(gatekeeper_discover, gatekeeper, secret)) {
1467                         ast_log(LOG_ERROR, "Gatekeeper registration failed.\n");
1468                 }
1469         }
1470         return RESULT_SUCCESS;
1471 #endif
1472 }
1473
1474 static int h323_ep_hangup(int fd, int argc, char *argv[])
1475 {
1476
1477         if (argc != 3) {
1478                 return RESULT_SHOWUSAGE;
1479         }
1480
1481         if (h323_soft_hangup(argv[2])) {
1482                 ast_verbose(VERBOSE_PREFIX_3 "Hangup succeeded on %s\n", argv[2]);
1483         } else { 
1484                 ast_verbose(VERBOSE_PREFIX_3 "Hangup failed for %s\n", argv[2]);
1485         }
1486
1487         return RESULT_SUCCESS;
1488 }
1489
1490 static int h323_tokens_show(int fd, int argc, char *argv[])
1491 {
1492
1493         if (argc != 3) {
1494                 return RESULT_SHOWUSAGE;
1495         }
1496         h323_show_tokens();
1497
1498         return RESULT_SUCCESS;
1499 }
1500
1501
1502 static char trace_usage[] = 
1503 "Usage: h.323 trace <level num>\n"
1504 "       Enables H.323 stack tracing for debugging purposes\n";
1505
1506 static char no_trace_usage[] = 
1507 "Usage: h.323 no trace\n"
1508 "       Disables H.323 stack tracing for debugging purposes\n";
1509
1510 static char debug_usage[] = 
1511 "Usage: h.323 debug\n"
1512 "       Enables chan_h323 debug output\n";
1513
1514 static char no_debug_usage[] = 
1515 "Usage: h.323 no debug\n"
1516 "       Disables chan_h323 debug output\n";
1517
1518 static char show_codec_usage[] = 
1519 "Usage: h.323 show codec\n"
1520 "       Shows all enabled codecs\n";
1521
1522 static char show_cycle_usage[] = 
1523 "Usage: h.323 gk cycle\n"
1524 "       Manually re-register with the Gatekeper\n";
1525
1526 static char show_hangup_usage[] = 
1527 "Usage: h.323 hangup <token>\n"
1528 "       Manually try to hang up call identified by <token>\n";
1529
1530 static char show_tokens_usage[] = 
1531 "Usage: h.323 show tokens\n"
1532 "       Print out all active call tokens\n";
1533
1534 static struct ast_cli_entry  cli_trace =
1535         { { "h.323", "trace", NULL }, h323_do_trace, "Enable H.323 Stack Tracing", trace_usage };
1536 static struct ast_cli_entry  cli_no_trace =
1537         { { "h.323", "no", "trace", NULL }, h323_no_trace, "Disable H.323 Stack Tracing", no_trace_usage };
1538 static struct ast_cli_entry  cli_debug =
1539         { { "h.323", "debug", NULL }, h323_do_debug, "Enable chan_h323 debug", debug_usage };
1540 static struct ast_cli_entry  cli_no_debug =
1541         { { "h.323", "no", "debug", NULL }, h323_no_debug, "Disable chan_h323 debug", no_debug_usage };
1542 static struct ast_cli_entry  cli_show_codecs =
1543         { { "h.323", "show", "codecs", NULL }, h323_show_codec, "Show enabled codecs", show_codec_usage };
1544 static struct ast_cli_entry  cli_gk_cycle =
1545         { { "h.323", "gk", "cycle", NULL }, h323_gk_cycle, "Manually re-register with the Gatekeper", show_cycle_usage };
1546 static struct ast_cli_entry  cli_hangup_call =
1547         { { "h.323", "hangup", NULL }, h323_ep_hangup, "Show all active call tokens", show_hangup_usage };
1548 static struct ast_cli_entry  cli_show_tokens =
1549         { { "h.323", "show", "tokens", NULL }, h323_tokens_show, "Manually try to hang up a call", show_tokens_usage };
1550
1551
1552
1553 int reload_config(void)
1554 {
1555         
1556         int format;
1557         struct ast_config *cfg;
1558         struct ast_variable *v;
1559         struct oh323_peer *peer   = NULL;
1560         struct oh323_user *user   = NULL;
1561         struct oh323_alias *alias = NULL;
1562         struct ast_hostent ahp; struct hostent *hp;
1563         char *cat;
1564         char *utype;
1565         
1566         cfg = ast_load(config);
1567
1568         /* We *must* have a config file otherwise stop immediately */
1569         if (!cfg) {
1570                 ast_log(LOG_NOTICE, "Unable to load config %s, H.323 disabled\n", config);
1571                 return 1;
1572         }
1573         
1574        /* fire up the H.323 Endpoint */       
1575         if (!h323_end_point_exist()) {
1576                h323_end_point_create(noFastStart,noH245Tunneling);        
1577         }
1578         h323debug=0;
1579         dtmfmode = H323_DTMF_RFC2833;
1580
1581         memset(&bindaddr, 0, sizeof(bindaddr));
1582
1583         v = ast_variable_browse(cfg, "general");
1584         while(v) {
1585                 /* Create the interface list */
1586                 if (!strcasecmp(v->name, "port")) {
1587                         port = (int)strtol(v->value, NULL, 10);
1588                 } else if (!strcasecmp(v->name, "bindaddr")) {
1589                         if (!(hp = ast_gethostbyname(v->value, &ahp))) {
1590                                 ast_log(LOG_WARNING, "Invalid address: %s\n", v->value);
1591                         } else {
1592                                 memcpy(&bindaddr.sin_addr, hp->h_addr, sizeof(bindaddr.sin_addr));
1593                         }
1594                 } else if (!strcasecmp(v->name, "allow")) {
1595                         format = ast_getformatbyname(v->value);
1596                         if (format < 1) 
1597                                 ast_log(LOG_WARNING, "Cannot allow unknown format '%s'\n", v->value);
1598                         else
1599                                 capability |= format;
1600                 } else if (!strcasecmp(v->name, "disallow")) {
1601                         format = ast_getformatbyname(v->value);
1602                         if (format < 1) 
1603                                 ast_log(LOG_WARNING, "Cannot disallow unknown format '%s'\n", v->value);
1604                         else
1605                                 capability &= ~format;
1606                 } else if (!strcasecmp(v->name, "tos")) {
1607                         if (sscanf(v->value, "%i", &format) == 1)
1608                                 tos = format & 0xff;
1609                         else if (!strcasecmp(v->value, "lowdelay"))
1610                                 tos = IPTOS_LOWDELAY;
1611                         else if (!strcasecmp(v->value, "throughput"))
1612                                 tos = IPTOS_THROUGHPUT;
1613                         else if (!strcasecmp(v->value, "reliability"))
1614                                 tos = IPTOS_RELIABILITY;
1615                         else if (!strcasecmp(v->value, "mincost"))
1616                                 tos = IPTOS_MINCOST;
1617                         else if (!strcasecmp(v->value, "none"))
1618                                 tos = 0;
1619                         else
1620                                 ast_log(LOG_WARNING, "Invalid tos value at line %d, should be 'lowdelay', 'throughput', 'reliability', 'mincost', or 'none'\n", v->lineno);
1621                 } else if (!strcasecmp(v->name, "gatekeeper")) {
1622                         if (!strcasecmp(v->value, "DISABLE")) {
1623                                 gatekeeper_disable = 1;
1624                                 usingGk = 0;
1625                         } else if (!strcasecmp(v->value, "DISCOVER")) {
1626                                 gatekeeper_disable = 0;
1627                                 gatekeeper_discover = 1;
1628                                 usingGk = 1;
1629                         } else {
1630                                 gatekeeper_disable = 0;
1631                                 usingGk = 1;
1632                                 strncpy(gatekeeper, v->value, sizeof(gatekeeper)-1);
1633                         }
1634                 } else if (!strcasecmp(v->name, "secret")) {
1635                                 strncpy(secret, v->value, sizeof(secret)-1);
1636                 } else if (!strcasecmp(v->name, "AllowGKRouted")) {
1637                                 gkroute = ast_true(v->value);
1638                 } else if (!strcasecmp(v->name, "context")) {
1639                         strncpy(default_context, v->value, sizeof(default_context)-1);
1640                         ast_verbose(VERBOSE_PREFIX_3 "  == Setting default context to %s\n", default_context);  
1641                 } else if (!strcasecmp(v->name, "dtmfmode")) {
1642                         if (!strcasecmp(v->value, "inband"))
1643                                 dtmfmode=H323_DTMF_INBAND;
1644                         else if (!strcasecmp(v->value, "rfc2833"))
1645                                 dtmfmode = H323_DTMF_RFC2833;
1646                         else {
1647                                 ast_log(LOG_WARNING, "Unknown dtmf mode '%s', using rfc2833\n", v->value);
1648                                 dtmfmode = H323_DTMF_RFC2833;
1649                         }
1650                 } else if (!strcasecmp(v->name, "UserByAlias")) {
1651                         userbyalias = ast_true(v->value);
1652                 } else if (!strcasecmp(v->name, "bridge")) {
1653                         bridge_default = ast_true(v->value);
1654                 } else if (!strcasecmp(v->name, "noFastStart")) {
1655                                 noFastStart = ast_true(v->value);
1656                 } else if (!strcasecmp(v->name, "noH245Tunneling")) {
1657                                 noH245Tunneling = ast_true(v->value);
1658                 }
1659                 v = v->next;    
1660         }
1661         
1662         cat = ast_category_browse(cfg, NULL);
1663         while(cat) {
1664                 if (strcasecmp(cat, "general")) {
1665                         utype = ast_variable_retrieve(cfg, cat, "type");
1666                         if (utype) {
1667                                 if (!strcasecmp(utype, "user") || !strcasecmp(utype, "friend")) {
1668                                         user = build_user(cat, ast_variable_browse(cfg, cat));
1669                                         if (user) {
1670                                                 ast_mutex_lock(&userl.lock);
1671                                                 user->next = userl.users;
1672                                                 userl.users = user;
1673                                                 ast_mutex_unlock(&userl.lock);
1674                                         }
1675                                 }  else if (!strcasecmp(utype, "peer") || !strcasecmp(utype, "friend")) {
1676                                         peer = build_peer(cat, ast_variable_browse(cfg, cat));
1677                                         if (peer) {
1678                                                 ast_mutex_lock(&peerl.lock);
1679                                                 peer->next = peerl.peers;
1680                                                 peerl.peers = peer;
1681                                                 ast_mutex_unlock(&peerl.lock);
1682                                         }
1683                                 }  else if (!strcasecmp(utype, "h323")) {                       
1684                                         alias = build_alias(cat, ast_variable_browse(cfg, cat));
1685                                         if (alias) {
1686                                                 ast_mutex_lock(&aliasl.lock);
1687                                                 alias->next = aliasl.aliases;
1688                                                 aliasl.aliases = alias;
1689                                                 ast_mutex_unlock(&aliasl.lock);
1690                                         }
1691                                 } else {
1692                                         ast_log(LOG_WARNING, "Unknown type '%s' for '%s' in %s\n", utype, cat, config);
1693                                 }
1694                         } else
1695                                 ast_log(LOG_WARNING, "Section '%s' lacks type\n", cat);
1696                 }
1697                 cat = ast_category_browse(cfg, cat);
1698         }
1699
1700         /* Register our H.323 aliases if any*/
1701         while (alias) {         
1702                 if (h323_set_alias(alias)) {
1703                         ast_log(LOG_ERROR, "Alias %s rejected by endpoint\n", alias->name);
1704                         return -1;
1705                 }       
1706                 alias = alias->next;
1707         }
1708
1709         /* Add some capabilities */
1710         if(h323_set_capability(capability, dtmfmode)) {
1711                 ast_log(LOG_ERROR, "Capabilities failure, this is bad.\n");
1712                 return -1;
1713         }       
1714         ast_destroy(cfg);
1715
1716         return 0;
1717 }
1718
1719 void delete_users(void)
1720 {
1721         struct oh323_user *user, *userlast;
1722         struct oh323_peer *peer;
1723         
1724         /* Delete all users */
1725         ast_mutex_lock(&userl.lock);
1726         for (user=userl.users;user;) {
1727                 userlast = user;
1728                 user=user->next;
1729                 free(userlast);
1730         }
1731         userl.users=NULL;
1732         ast_mutex_unlock(&userl.lock);
1733         ast_mutex_lock(&peerl.lock);
1734         for (peer=peerl.peers;peer;) {
1735                 /* Assume all will be deleted, and we'll find out for sure later */
1736                 peer->delme = 1;
1737                 peer = peer->next;
1738         }
1739         ast_mutex_unlock(&peerl.lock);
1740 }
1741
1742 void delete_aliases(void)
1743 {
1744         struct oh323_alias *alias, *aliaslast;
1745                 
1746         /* Delete all users */
1747         ast_mutex_lock(&aliasl.lock);
1748         for (alias=aliasl.aliases;alias;) {
1749                 aliaslast = alias;
1750                 alias=alias->next;
1751                 free(aliaslast);
1752         }
1753         aliasl.aliases=NULL;
1754         ast_mutex_unlock(&aliasl.lock);
1755 }
1756
1757 void prune_peers(void)
1758 {
1759         /* Prune peers who still are supposed to be deleted */
1760         struct oh323_peer *peer, *peerlast, *peernext;
1761         ast_mutex_lock(&peerl.lock);
1762         peerlast = NULL;
1763         for (peer=peerl.peers;peer;) {
1764                 peernext = peer->next;
1765                 if (peer->delme) {
1766                         free(peer);
1767                         if (peerlast)
1768                                 peerlast->next = peernext;
1769                         else
1770                                 peerl.peers = peernext;
1771                 } else
1772                         peerlast = peer;
1773                 peer=peernext;
1774         }
1775         ast_mutex_unlock(&peerl.lock);
1776 }
1777
1778 int reload(void)
1779 {
1780         delete_users();
1781         delete_aliases();
1782         prune_peers();
1783
1784 #if 0
1785         if (!ast_strlen_zero(gatekeeper)) {
1786                 h323_gk_urq();
1787         }
1788 #endif
1789
1790         reload_config();
1791
1792 #if 0
1793         /* Possibly register with a GK */
1794         if (gatekeeper_disable == 0) {
1795                 if (h323_set_gk(gatekeeper_discover, gatekeeper, secret)) {
1796                         ast_log(LOG_ERROR, "Gatekeeper registration failed.\n");
1797                         h323_end_process();
1798                         return -1;
1799                 }
1800         }
1801 #endif
1802         restart_monitor();
1803         return 0;
1804 }
1805
1806
1807 static struct ast_rtp *oh323_get_rtp_peer(struct ast_channel *chan)
1808 {
1809         struct oh323_pvt *p;
1810         p = (struct oh323_pvt *) chan->pvt->pvt;
1811         if (p && p->rtp && p->bridge) {
1812                 return p->rtp;
1813         }
1814         return NULL;
1815 }
1816
1817 static struct ast_rtp *oh323_get_vrtp_peer(struct ast_channel *chan)
1818 {
1819         return NULL;
1820 }
1821
1822 static char *convertcap(int cap)
1823 {
1824         switch (cap) {
1825         case AST_FORMAT_G723_1:
1826                 return "G.723";
1827         case AST_FORMAT_GSM:
1828                 return "GSM";
1829         case AST_FORMAT_ULAW:
1830                 return "ULAW";
1831         case AST_FORMAT_ALAW:
1832                 return "ALAW";
1833         case AST_FORMAT_ADPCM:
1834                 return "G.728";
1835         case AST_FORMAT_G729A:
1836                 return "G.729";
1837         case AST_FORMAT_SPEEX:
1838                 return "SPEEX";
1839         case AST_FORMAT_ILBC:
1840                 return "ILBC";
1841         default:
1842                 ast_log(LOG_NOTICE, "Don't know how to deal with mode %d\n", cap);
1843                 return NULL;
1844         }
1845
1846 }
1847
1848 static int oh323_set_rtp_peer(struct ast_channel *chan, struct ast_rtp *rtp, struct ast_rtp *vrtp, int codecs)
1849 {
1850         /* XXX Deal with Video */
1851         struct oh323_pvt *p;
1852         struct sockaddr_in them;
1853         struct sockaddr_in us;
1854         char *mode;
1855         char iabuf[INET_ADDRSTRLEN];
1856
1857         mode = convertcap(chan->writeformat); 
1858
1859         if (!rtp) {
1860                 return 0;
1861         }
1862
1863         p = (struct oh323_pvt *) chan->pvt->pvt;
1864         if (!p) {
1865                 ast_log(LOG_ERROR, "No Private Structure, this is bad\n");
1866                 return -1;
1867         }
1868
1869         ast_rtp_get_peer(rtp, &them);   
1870         ast_rtp_get_us(rtp, &us);
1871
1872         h323_native_bridge(p->cd.call_token, ast_inet_ntoa(iabuf, sizeof(iabuf), them.sin_addr), mode);
1873         
1874         return 0;
1875         
1876 }
1877
1878 static struct ast_rtp_protocol oh323_rtp = {
1879         get_rtp_info: oh323_get_rtp_peer,
1880         get_vrtp_info: oh323_get_vrtp_peer,
1881         set_rtp_peer: oh323_set_rtp_peer,
1882 };
1883
1884 int load_module()
1885 {
1886         int res;
1887
1888         ast_mutex_init(&userl.lock);
1889         ast_mutex_init(&peerl.lock);
1890         ast_mutex_init(&aliasl.lock);
1891
1892         res = reload_config();
1893
1894         if (res) {
1895                 return 0;
1896         } else {
1897                 /* Make sure we can register our channel type */
1898                 if (ast_channel_register(type, tdesc, capability, oh323_request)) {
1899                         ast_log(LOG_ERROR, "Unable to register channel class %s\n", type);
1900                         h323_end_process();
1901                         return -1;
1902                 }
1903                 ast_cli_register(&cli_debug);
1904                 ast_cli_register(&cli_no_debug);
1905                 ast_cli_register(&cli_trace);
1906                 ast_cli_register(&cli_no_trace);
1907                 ast_cli_register(&cli_show_codecs);
1908                 ast_cli_register(&cli_gk_cycle);
1909                 ast_cli_register(&cli_hangup_call);
1910                 ast_cli_register(&cli_show_tokens);
1911
1912                 oh323_rtp.type = type;
1913                 ast_rtp_proto_register(&oh323_rtp);
1914
1915                 sched = sched_context_create();
1916                 if (!sched) {
1917                         ast_log(LOG_WARNING, "Unable to create schedule context\n");
1918                 }
1919                 io = io_context_create();
1920                 if (!io) {
1921                         ast_log(LOG_WARNING, "Unable to create I/O context\n");
1922                 }
1923                 
1924                 /* Register our callback functions */
1925                 h323_callback_register(setup_incoming_call, 
1926                                        setup_outgoing_call,                                                      
1927                                        create_connection, 
1928                                        setup_rtp_connection, 
1929                                        cleanup_connection, 
1930                                        chan_ringing,
1931                                        connection_made, 
1932                                        send_digit,
1933                                        answer_call);
1934         
1935
1936                 /* start the h.323 listener */
1937                 if (h323_start_listener(port, bindaddr)) {
1938                         ast_log(LOG_ERROR, "Unable to create H323 listener.\n");
1939                         return -1;
1940                 }
1941
1942                 /* Possibly register with a GK */
1943                 if (gatekeeper_disable == 0) {
1944                         if (h323_set_gk(gatekeeper_discover, gatekeeper, secret)) {
1945                                 ast_log(LOG_ERROR, "Gatekeeper registration failed.\n");
1946                                 return 0;
1947                         }
1948                 }
1949                 /* And start the monitor for the first time */
1950                 restart_monitor();
1951         }
1952         return res;
1953 }
1954
1955
1956 int unload_module() 
1957 {
1958         struct oh323_pvt *p, *pl;
1959                 
1960         if (!ast_mutex_lock(&iflock)) {
1961         /* hangup all interfaces if they have an owner */
1962         p = iflist;
1963         while(p) {
1964                 if (p->owner)
1965                         ast_softhangup(p->owner, AST_SOFTHANGUP_APPUNLOAD);
1966                 p = p->next;
1967         }
1968         iflist = NULL;
1969         ast_mutex_unlock(&iflock);
1970         } else {
1971                 ast_log(LOG_WARNING, "Unable to lock the interface list\n");
1972                 return -1;
1973         }
1974
1975         if (!ast_mutex_lock(&monlock)) {
1976                 if (monitor_thread && (monitor_thread != AST_PTHREADT_STOP)) {
1977                         pthread_cancel(monitor_thread);
1978                         pthread_kill(monitor_thread, SIGURG);
1979                         pthread_join(monitor_thread, NULL);
1980                  }
1981                 monitor_thread = AST_PTHREADT_STOP;
1982                 ast_mutex_unlock(&monlock);
1983         } else {
1984                 ast_log(LOG_WARNING, "Unable to lock the monitor\n");
1985                 return -1;
1986         }
1987                 
1988         if (!ast_mutex_lock(&iflock)) {
1989                 /* destroy all the interfaces and free their memory */
1990                 p = iflist;
1991                 while(p) {
1992                         pl = p;
1993                         p = p->next;
1994                         /* free associated memory */
1995                         ast_mutex_destroy(&pl->lock);
1996                         free(pl);
1997                 }
1998                 iflist = NULL;
1999                 ast_mutex_unlock(&iflock);
2000         } else {
2001                 ast_log(LOG_WARNING, "Unable to lock the interface list\n");
2002                 return -1;
2003         }
2004         h323_gk_urq();
2005         h323_end_process();
2006
2007         /* unregister rtp */
2008         ast_rtp_proto_unregister(&oh323_rtp);
2009         
2010         /* unregister commands */
2011         ast_cli_unregister(&cli_debug);
2012         ast_cli_unregister(&cli_no_debug);
2013         ast_cli_unregister(&cli_trace);
2014         ast_cli_unregister(&cli_no_trace);   
2015         ast_cli_unregister(&cli_show_codecs);
2016         ast_cli_unregister(&cli_gk_cycle);
2017         ast_cli_unregister(&cli_hangup_call);
2018         ast_cli_unregister(&cli_show_tokens);
2019                         
2020         /* unregister channel type */
2021         ast_channel_unregister(type);
2022
2023         return 0; 
2024
2025
2026 int usecount()
2027 {
2028         int res;
2029         ast_mutex_lock(&usecnt_lock);
2030         res = usecnt;
2031         ast_mutex_unlock(&usecnt_lock);
2032         return res;
2033 }
2034
2035 char *description()
2036 {
2037         return desc;
2038 }
2039
2040 char *key()
2041 {
2042         return ASTERISK_GPL_KEY;
2043 }
2044
2045
2046
2047