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