Use INET_ADDRLEN (bug #1956) (from airport!)
[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) {
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         /* pass on our preferred codec to the H.323 stack */
886         h323_set_capability(format, dtmfmode);
887
888         if (ext) {
889                 strncpy(p->username, ext, sizeof(p->username) - 1);
890         }
891         ast_log(LOG_DEBUG, "Host: %s\tUsername: %s\n", host, p->username);
892
893         tmpc = oh323_new(p, AST_STATE_DOWN, host);
894         if (!tmpc)
895                 oh323_destroy(p);
896         
897         restart_monitor();
898         
899         return tmpc;
900 }
901
902 struct oh323_alias *find_alias(const char *source_aliases)
903 {
904         struct oh323_alias *a;
905
906         a = aliasl.aliases;
907
908         while(a) {
909
910                 if (!strcasecmp(a->name, source_aliases)) {
911                         break;
912                 }
913                 a = a->next;
914         }
915         return a;
916 }
917
918 struct oh323_user *find_user(const call_details_t cd)
919 {
920         struct oh323_user *u;
921         char iabuf[INET_ADDRSTRLEN];
922         u = userl.users;
923         if(userbyalias == 1){
924                 while(u) {
925                         if (!strcasecmp(u->name, cd.call_source_aliases)) {
926                                 break;
927                         }
928                         u = u->next;
929                 }
930
931         } else {
932                 while(u) {
933                         if (!strcasecmp(cd.sourceIp, ast_inet_ntoa(iabuf, sizeof(iabuf), u->addr.sin_addr))) {
934                                 break;
935                         }
936                         u = u->next;
937                 }
938
939         
940         }
941         return u;
942
943 }
944
945 struct oh323_peer *find_peer(char *dest_peer)
946 {
947         struct oh323_peer *p;
948
949         p = peerl.peers;
950
951         while(p) {
952                 if (!strcasecmp(p->name, dest_peer)) {
953                         break;
954                 }
955                 p = p->next;
956         }
957         return p;
958
959 }
960
961 /**
962   * Callback for sending digits from H.323 up to asterisk
963   *
964   */
965 int send_digit(unsigned call_reference, char digit)
966 {
967         struct oh323_pvt *p;
968         struct ast_frame f;
969
970         ast_log(LOG_DEBUG, "Recieved Digit: %c\n", digit);
971         p = find_call(call_reference);
972         
973         if (!p) {
974                 ast_log(LOG_ERROR, "Private structure not found in send_digit.\n");
975                 return -1;
976         }
977         memset(&f, 0, sizeof(f));
978         f.frametype = AST_FRAME_DTMF;
979     f.subclass = digit;
980     f.datalen = 0;
981     f.samples = 800;
982     f.offset = 0;
983     f.data = NULL;
984     f.mallocd = 0;
985     f.src = "SEND_DIGIT";
986         
987         return ast_queue_frame(p->owner, &f);   
988 }
989
990 /**
991   * Call-back function that gets called when any H.323 connection is made
992   *
993   * Returns the local RTP information
994   */
995 struct rtp_info *create_connection(unsigned call_reference)
996 {       
997         struct oh323_pvt *p;
998         struct sockaddr_in us;
999         struct sockaddr_in them;
1000         struct rtp_info *info;
1001         /* XXX This is sooooo bugus.  inet_ntoa is not reentrant
1002            but this function wants to return a static variable so
1003            the only way to do this will be to declare iabuf within
1004            the oh323_pvt structure XXX */
1005         static char iabuf[INET_ADDRSTRLEN];
1006
1007         info = (struct rtp_info *) malloc(sizeof(struct rtp_info));
1008
1009         p = find_call(call_reference);
1010
1011         if (!p) {
1012                 ast_log(LOG_ERROR, "Unable to allocate private structure, this is very bad.\n");
1013                 return NULL;
1014         }
1015
1016         /* figure out our local RTP port and tell the H.323 stack about it*/
1017         ast_rtp_get_us(p->rtp, &us);
1018         ast_rtp_get_peer(p->rtp, &them);
1019
1020         info->addr = ast_inet_ntoa(iabuf, sizeof(iabuf), us.sin_addr);
1021         info->port = ntohs(us.sin_port);
1022
1023         return info;
1024 }
1025
1026 /**
1027  *  Call-back function for incoming calls
1028  *
1029  *  Returns 1 on success
1030  */
1031
1032 int setup_incoming_call(call_details_t cd)
1033 {
1034         
1035         struct oh323_pvt *p = NULL;
1036 /*      struct ast_channel *c = NULL; */
1037         struct oh323_user *user = NULL;
1038         struct oh323_alias *alias = NULL;
1039         char iabuf[INET_ADDRSTRLEN];
1040
1041         /* allocate the call*/
1042         p = oh323_alloc(cd.call_reference);
1043
1044         if (!p) {
1045                 ast_log(LOG_ERROR, "Unable to allocate private structure, this is bad.\n");
1046                 return 0;
1047         }
1048
1049         /* Populate the call details in the private structure */
1050         p->cd.call_token = cd.call_token;
1051         p->cd.call_source_aliases = cd.call_source_aliases;
1052         p->cd.call_dest_alias = cd.call_dest_alias;
1053         p->cd.call_source_name = cd.call_source_name;
1054         p->cd.call_source_e164 = cd.call_source_e164;
1055         p->cd.call_dest_e164 = cd.call_dest_e164;
1056
1057         if (h323debug) {
1058                 ast_verbose(VERBOSE_PREFIX_3 "Setting up Call\n");
1059                 ast_verbose(VERBOSE_PREFIX_3 "     Call token:  [%s]\n", p->cd.call_token);
1060                 ast_verbose(VERBOSE_PREFIX_3 "     Calling party name:  [%s]\n", p->cd.call_source_name);
1061                 ast_verbose(VERBOSE_PREFIX_3 "     Calling party number:  [%s]\n", p->cd.call_source_e164);
1062                 ast_verbose(VERBOSE_PREFIX_3 "     Called  party name:  [%s]\n", p->cd.call_dest_alias);
1063                 ast_verbose(VERBOSE_PREFIX_3 "     Called  party number:  [%s]\n", p->cd.call_dest_e164);
1064         }
1065
1066         /* Decide if we are allowing Gatekeeper routed calls*/
1067         if ((!strcasecmp(cd.sourceIp, gatekeeper)) && (gkroute == -1) && (usingGk == 1)) {
1068                 
1069                 if (!ast_strlen_zero(cd.call_dest_e164)) {
1070                         strncpy(p->exten, cd.call_dest_e164, sizeof(p->exten)-1);
1071                         strncpy(p->context, default_context, sizeof(p->context)-1); 
1072                 } else {
1073                         alias = find_alias(cd.call_dest_alias);
1074                 
1075                         if (!alias) {
1076                                 ast_log(LOG_ERROR, "Call for %s rejected, alias not found\n", cd.call_dest_alias);
1077                                 return 0;
1078                         }
1079                         strncpy(p->exten, alias->name, sizeof(p->exten)-1);
1080                         strncpy(p->context, alias->context, sizeof(p->context)-1);
1081                 }
1082                 sprintf(p->callerid, "%s <%s>", p->cd.call_source_name, p->cd.call_source_e164);
1083         } else { 
1084                 /* Either this call is not from the Gatekeeper 
1085                    or we are not allowing gk routed calls */
1086                 user  = find_user(cd);
1087
1088                 if (!user) {
1089                         sprintf(p->callerid, "%s <%s>", p->cd.call_source_name, p->cd.call_source_e164);
1090                         if (!ast_strlen_zero(p->cd.call_dest_e164)) {
1091                                 strncpy(p->exten, cd.call_dest_e164, sizeof(p->exten)-1);
1092                         } else {
1093                                 strncpy(p->exten, cd.call_dest_alias, sizeof(p->exten)-1);              
1094                         }
1095                         if (ast_strlen_zero(default_context)) {
1096                                 ast_log(LOG_ERROR, "Call from '%s' rejected due to no default context\n", p->cd.call_source_aliases);
1097                                 return 0;
1098                         }
1099                         strncpy(p->context, default_context, sizeof(p->context)-1);
1100                         ast_log(LOG_DEBUG, "Sending %s to context [%s]\n", cd.call_source_aliases, p->context);
1101                 } else {                                        
1102                         if (user->host) {
1103                                 if (strcasecmp(cd.sourceIp, ast_inet_ntoa(iabuf, sizeof(iabuf), user->addr.sin_addr))){                                 
1104                                         if (ast_strlen_zero(user->context)) {
1105                                                 if (ast_strlen_zero(default_context)) {                                 
1106                                                         ast_log(LOG_ERROR, "Call from '%s' rejected due to non-matching IP address (%s) and no default context\n", user->name, cd.sourceIp);
1107                                                         return 0;
1108                                                 }
1109                                                 strncpy(p->context, default_context, sizeof(p->context)-1);
1110                                         } else {
1111                                                 strncpy(p->context, user->context, sizeof(p->context)-1);
1112                                         }
1113                                         sprintf(p->exten, "i");
1114                                         ast_log(LOG_ERROR, "Call from '%s' rejected due to non-matching IP address (%s)s\n", user->name, cd.sourceIp);
1115                                         goto exit;                                      
1116                                 }
1117                         }
1118                         if (user->incominglimit > 0) {
1119                                 if (user->inUse >= user->incominglimit) {
1120                                         ast_log(LOG_ERROR, "Call from user '%s' rejected due to usage limit of %d\n", user->name, user->incominglimit);
1121                                         return 0;
1122                                 }
1123                         }
1124                         strncpy(p->context, user->context, sizeof(p->context)-1);
1125                         p->bridge = user->bridge;
1126                         p->nat = user->nat;
1127
1128                         if (!ast_strlen_zero(user->callerid)) {
1129                                 strncpy(p->callerid, user->callerid, sizeof(p->callerid) - 1);
1130                         } else {
1131                                  sprintf(p->callerid, "%s <%s>", p->cd.call_source_name, p->cd.call_source_e164); 
1132                         }
1133                         if (!ast_strlen_zero(p->cd.call_dest_e164)) {
1134                                 strncpy(p->exten, cd.call_dest_e164, sizeof(p->exten)-1);
1135                         } else {
1136                                 strncpy(p->exten, cd.call_dest_alias, sizeof(p->exten)-1);              
1137                         }
1138                         if (!ast_strlen_zero(user->accountcode)) {
1139                                 strncpy(p->accountcode, user->accountcode, sizeof(p->accountcode)-1);
1140                         } 
1141
1142                         /* Increment the usage counter */
1143                         user->inUse++;
1144                 } 
1145         }
1146
1147 exit:
1148 #if 0
1149         /* allocate a channel and tell asterisk about it */
1150         c = oh323_new(p, AST_STATE_RINGING, cd.call_token);
1151         if (!c) {
1152                 ast_log(LOG_ERROR, "Couldn't create channel. This is bad\n");
1153                 return 0;
1154         }
1155 #endif
1156         return 1;
1157 }
1158
1159 /**
1160  * Call-back function to start PBX when OpenH323 ready to serve incoming call
1161  *
1162  * Returns 1 on success
1163  */
1164 static int answer_call(unsigned call_reference)
1165 {
1166         struct oh323_pvt *p = NULL;
1167         struct ast_channel *c = NULL;
1168         
1169         /* Find the call or allocate a private structure if call not found */
1170         p = find_call(call_reference);
1171         
1172         if (!p) {
1173                 ast_log(LOG_ERROR, "Something is wrong: answer_call\n");
1174                 return 0;
1175         }
1176         
1177         /* allocate a channel and tell asterisk about it */
1178         c = oh323_new(p, AST_STATE_RINGING, p->cd.call_token);
1179         if (!c) {
1180                 ast_log(LOG_ERROR, "Couldn't create channel. This is bad\n");
1181                 return 0;
1182         }
1183         return 1;
1184 }
1185
1186 /**
1187  * Call-back function to establish an outgoing H.323 call
1188  * 
1189  * Returns 1 on success 
1190  */
1191 int setup_outgoing_call(call_details_t cd)
1192 {       
1193         return 1;
1194 }
1195
1196 #if 0
1197 if (p->inUse >= p->outgoinglimit) {
1198         ast_log(LOG_ERROR, "Call to %s rejected due to usage limit of %d outgoing channels\n", p->name, p->inUse);
1199         return 0;
1200 }
1201
1202 if (!p) {
1203         ast_log(LOG_ERROR, "Rejecting call: peer %s not found\n", dest_peer);
1204         return 0;
1205 }
1206 #endif
1207
1208 /**
1209   * Call-back function that gets called for each rtp channel opened 
1210   *
1211   * Returns nothing 
1212   */
1213 void setup_rtp_connection(unsigned call_reference, const char *remoteIp, int remotePort)
1214 {
1215         struct oh323_pvt *p = NULL;
1216         struct sockaddr_in them;
1217
1218         /* Find the call or allocate a private structure if call not found */
1219         p = find_call(call_reference);
1220
1221         if (!p) {
1222                 ast_log(LOG_ERROR, "Something is wrong: rtp\n");
1223                 return;
1224         }
1225
1226         them.sin_family = AF_INET;
1227         them.sin_addr.s_addr = inet_addr(remoteIp); // only works for IPv4
1228         them.sin_port = htons(remotePort);
1229         ast_rtp_set_peer(p->rtp, &them);
1230
1231         return;
1232 }
1233
1234 /**  
1235   *     Call-back function to signal asterisk that the channel has been answered 
1236   * Returns nothing
1237   */
1238 void connection_made(unsigned call_reference)
1239 {
1240         struct ast_channel *c = NULL;
1241         struct oh323_pvt *p = NULL;
1242         
1243         p = find_call(call_reference);
1244         
1245         if (!p)
1246                 ast_log(LOG_ERROR, "Something is wrong: connection\n");
1247
1248
1249         if (!p->owner) {
1250                 ast_log(LOG_ERROR, "Channel has no owner\n");
1251                 return;
1252         }
1253         c = p->owner;   
1254
1255         ast_setstate(c, AST_STATE_UP);
1256         ast_queue_control(c, AST_CONTROL_ANSWER);
1257         return;
1258 }
1259
1260 /**
1261   *  Call-back function to signal asterisk that the channel is ringing
1262   *  Returns nothing
1263   */
1264 void chan_ringing(unsigned call_reference)
1265 {
1266         struct ast_channel *c = NULL;
1267         struct oh323_pvt *p = NULL;
1268
1269         p = find_call(call_reference);
1270
1271         if (!p) {
1272                 ast_log(LOG_ERROR, "Something is wrong: ringing\n");
1273         }
1274
1275         if (!p->owner) {
1276                 ast_log(LOG_ERROR, "Channel has no owner\n");
1277                 return;
1278         }
1279         c = p->owner;
1280         ast_setstate(c, AST_STATE_RINGING);
1281         ast_queue_control(c, AST_CONTROL_RINGING);
1282         return;
1283 }
1284
1285 /**
1286   * Call-back function to cleanup communication
1287   * Returns nothing,
1288   */
1289 void cleanup_connection(call_details_t cd)
1290 {       
1291         struct oh323_pvt *p = NULL;
1292 /*      struct oh323_peer *peer = NULL; */
1293         struct oh323_user *user = NULL;
1294         struct ast_rtp *rtp = NULL;
1295         
1296         p = find_call(cd.call_reference);
1297
1298         if (!p) {
1299                 return;
1300         }
1301         ast_mutex_lock(&p->lock);
1302
1303         /* Decrement usage counter */
1304         if (!p->outgoing) {
1305                 user = find_user(cd);
1306                 
1307                 if(user) {
1308                         user->inUse--;
1309                 }
1310         }
1311
1312 #if 0
1313         if (p->outgoing) {
1314                 peer = find_peer(cd.call_dest_alias);
1315                 peer->inUse--;
1316         } else {
1317                 user = find_user(cd);
1318                 user->inUse--;
1319         }
1320 #endif
1321         
1322         if (p->rtp) {
1323                 rtp = p->rtp;
1324                 p->rtp = NULL;
1325                 /* Immediately stop RTP */
1326                 ast_rtp_destroy(rtp);
1327         }
1328
1329         p->alreadygone = 1;
1330         
1331         /* Send hangup */       
1332         if (p->owner) {
1333                 ast_queue_hangup(p->owner);
1334         } 
1335
1336         ast_mutex_unlock(&p->lock);
1337         return; 
1338 }
1339
1340 static void *do_monitor(void *data)
1341 {
1342         int res;
1343         struct oh323_pvt *oh323 = NULL;
1344         
1345                 for(;;) {
1346                 /* Check for interfaces needing to be killed */
1347                 ast_mutex_lock(&iflock);
1348 restartsearch:          
1349                 oh323 = iflist;
1350                 while(oh323) {
1351                         if (oh323->needdestroy) {
1352                                 __oh323_destroy(oh323);
1353                                 goto restartsearch;
1354                         }
1355                         oh323 = oh323->next;
1356                 }
1357                 ast_mutex_unlock(&iflock);
1358
1359                 /* Wait for sched or io */
1360                 res = ast_sched_wait(sched);
1361                 if ((res < 0) || (res > 1000))
1362                         res = 1000;
1363                 res = ast_io_wait(io, res);
1364
1365                 pthread_testcancel();
1366
1367                 ast_mutex_lock(&monlock);
1368                 if (res >= 0) 
1369                         ast_sched_runq(sched);
1370                 ast_mutex_unlock(&monlock);
1371         }
1372         /* Never reached */
1373         return NULL;
1374         
1375 }
1376
1377 static int restart_monitor(void)
1378 {
1379         /* If we're supposed to be stopped -- stay stopped */
1380         if (monitor_thread == AST_PTHREADT_STOP)
1381                 return 0;
1382         if (ast_mutex_lock(&monlock)) {
1383                 ast_log(LOG_WARNING, "Unable to lock monitor\n");
1384                 return -1;
1385         }
1386         if (monitor_thread == pthread_self()) {
1387                 ast_mutex_unlock(&monlock);
1388                 ast_log(LOG_WARNING, "Cannot kill myself\n");
1389                 return -1;
1390         }
1391         if (monitor_thread && (monitor_thread != AST_PTHREADT_NULL)) {
1392                 /* Wake up the thread */
1393                 pthread_kill(monitor_thread, SIGURG);
1394         } else {
1395                 /* Start a new monitor */
1396                 if (pthread_create(&monitor_thread, NULL, do_monitor, NULL) < 0) {
1397                         ast_mutex_unlock(&monlock);
1398                         ast_log(LOG_ERROR, "Unable to start monitor thread.\n");
1399                         return -1;
1400                 }
1401         }
1402         ast_mutex_unlock(&monlock);
1403         return 0;
1404 }
1405
1406 static int h323_do_trace(int fd, int argc, char *argv[])
1407 {
1408         if (argc != 3) {
1409                 return RESULT_SHOWUSAGE;
1410         }
1411         h323_debug(1, atoi(argv[2]));
1412         ast_cli(fd, "H.323 trace set to level %s\n", argv[2]);
1413         return RESULT_SUCCESS;
1414 }
1415
1416 static int h323_no_trace(int fd, int argc, char *argv[])
1417 {
1418         if (argc != 3) {
1419                 return RESULT_SHOWUSAGE;
1420         }
1421         h323_debug(0,0);
1422         ast_cli(fd, "H.323 trace disabled\n");
1423         return RESULT_SUCCESS;
1424 }
1425
1426 static int h323_do_debug(int fd, int argc, char *argv[])
1427 {
1428         if (argc != 2) {
1429                 return RESULT_SHOWUSAGE;
1430         }
1431         h323debug = 1;
1432         ast_cli(fd, "H323 debug enabled\n");
1433         return RESULT_SUCCESS;
1434 }
1435
1436 static int h323_no_debug(int fd, int argc, char *argv[])
1437 {
1438         if (argc != 3) {
1439                 return RESULT_SHOWUSAGE;
1440         }
1441         h323debug = 0;
1442         ast_cli(fd, "H323 Debug disabled\n");
1443         return RESULT_SUCCESS;
1444 }
1445
1446 static int h323_gk_cycle(int fd, int argc, char *argv[])
1447 {
1448         return RESULT_SUCCESS;
1449 #if 0
1450         if (argc != 3) {
1451                 return RESULT_SHOWUSAGE;
1452         }       
1453         h323_gk_urq();
1454         
1455         /* Possibly register with a GK */
1456         if (!gatekeeper_disable) {
1457                 if (h323_set_gk(gatekeeper_discover, gatekeeper, secret)) {
1458                         ast_log(LOG_ERROR, "Gatekeeper registration failed.\n");
1459                 }
1460         }
1461         return RESULT_SUCCESS;
1462 #endif
1463 }
1464
1465 static int h323_ep_hangup(int fd, int argc, char *argv[])
1466 {
1467
1468         if (argc != 3) {
1469                 return RESULT_SHOWUSAGE;
1470         }
1471
1472         if (h323_soft_hangup(argv[2])) {
1473                 ast_verbose(VERBOSE_PREFIX_3 "Hangup succeeded on %s\n", argv[2]);
1474         } else { 
1475                 ast_verbose(VERBOSE_PREFIX_3 "Hangup failed for %s\n", argv[2]);
1476         }
1477
1478         return RESULT_SUCCESS;
1479 }
1480
1481 static int h323_tokens_show(int fd, int argc, char *argv[])
1482 {
1483
1484         if (argc != 3) {
1485                 return RESULT_SHOWUSAGE;
1486         }
1487         h323_show_tokens();
1488
1489         return RESULT_SUCCESS;
1490 }
1491
1492
1493 static char trace_usage[] = 
1494 "Usage: h.323 trace <level num>\n"
1495 "       Enables H.323 stack tracing for debugging purposes\n";
1496
1497 static char no_trace_usage[] = 
1498 "Usage: h.323 no trace\n"
1499 "       Disables H.323 stack tracing for debugging purposes\n";
1500
1501 static char debug_usage[] = 
1502 "Usage: h.323 debug\n"
1503 "       Enables chan_h323 debug output\n";
1504
1505 static char no_debug_usage[] = 
1506 "Usage: h.323 no debug\n"
1507 "       Disables chan_h323 debug output\n";
1508
1509 static char show_codec_usage[] = 
1510 "Usage: h.323 show codec\n"
1511 "       Shows all enabled codecs\n";
1512
1513 static char show_cycle_usage[] = 
1514 "Usage: h.323 gk cycle\n"
1515 "       Manually re-register with the Gatekeper\n";
1516
1517 static char show_hangup_usage[] = 
1518 "Usage: h.323 hangup <token>\n"
1519 "       Manually try to hang up call identified by <token>\n";
1520
1521 static char show_tokens_usage[] = 
1522 "Usage: h.323 show tokens\n"
1523 "       Print out all active call tokens\n";
1524
1525 static struct ast_cli_entry  cli_trace =
1526         { { "h.323", "trace", NULL }, h323_do_trace, "Enable H.323 Stack Tracing", trace_usage };
1527 static struct ast_cli_entry  cli_no_trace =
1528         { { "h.323", "no", "trace", NULL }, h323_no_trace, "Disable H.323 Stack Tracing", no_trace_usage };
1529 static struct ast_cli_entry  cli_debug =
1530         { { "h.323", "debug", NULL }, h323_do_debug, "Enable chan_h323 debug", debug_usage };
1531 static struct ast_cli_entry  cli_no_debug =
1532         { { "h.323", "no", "debug", NULL }, h323_no_debug, "Disable chan_h323 debug", no_debug_usage };
1533 static struct ast_cli_entry  cli_show_codecs =
1534         { { "h.323", "show", "codecs", NULL }, h323_show_codec, "Show enabled codecs", show_codec_usage };
1535 static struct ast_cli_entry  cli_gk_cycle =
1536         { { "h.323", "gk", "cycle", NULL }, h323_gk_cycle, "Manually re-register with the Gatekeper", show_cycle_usage };
1537 static struct ast_cli_entry  cli_hangup_call =
1538         { { "h.323", "hangup", NULL }, h323_ep_hangup, "Show all active call tokens", show_hangup_usage };
1539 static struct ast_cli_entry  cli_show_tokens =
1540         { { "h.323", "show", "tokens", NULL }, h323_tokens_show, "Manually try to hang up a call", show_tokens_usage };
1541
1542
1543
1544 int reload_config(void)
1545 {
1546         
1547         int format;
1548         struct ast_config *cfg;
1549         struct ast_variable *v;
1550         struct oh323_peer *peer   = NULL;
1551         struct oh323_user *user   = NULL;
1552         struct oh323_alias *alias = NULL;
1553         struct ast_hostent ahp; struct hostent *hp;
1554         char *cat;
1555         char *utype;
1556         
1557         cfg = ast_load(config);
1558
1559         /* We *must* have a config file otherwise stop immediately */
1560         if (!cfg) {
1561                 ast_log(LOG_NOTICE, "Unable to load config %s, H.323 disabled\n", config);
1562                 return 1;
1563         }
1564         
1565        /* fire up the H.323 Endpoint */       
1566         if (!h323_end_point_exist()) {
1567                h323_end_point_create();        
1568         }
1569         h323debug=0;
1570         dtmfmode = H323_DTMF_RFC2833;
1571
1572         memset(&bindaddr, 0, sizeof(bindaddr));
1573
1574         v = ast_variable_browse(cfg, "general");
1575         while(v) {
1576                 /* Create the interface list */
1577                 if (!strcasecmp(v->name, "port")) {
1578                         port = (int)strtol(v->value, NULL, 10);
1579                 } else if (!strcasecmp(v->name, "bindaddr")) {
1580                         if (!(hp = ast_gethostbyname(v->value, &ahp))) {
1581                                 ast_log(LOG_WARNING, "Invalid address: %s\n", v->value);
1582                         } else {
1583                                 memcpy(&bindaddr.sin_addr, hp->h_addr, sizeof(bindaddr.sin_addr));
1584                         }
1585                 } else if (!strcasecmp(v->name, "allow")) {
1586                         format = ast_getformatbyname(v->value);
1587                         if (format < 1) 
1588                                 ast_log(LOG_WARNING, "Cannot allow unknown format '%s'\n", v->value);
1589                         else
1590                                 capability |= format;
1591                 } else if (!strcasecmp(v->name, "disallow")) {
1592                         format = ast_getformatbyname(v->value);
1593                         if (format < 1) 
1594                                 ast_log(LOG_WARNING, "Cannot disallow unknown format '%s'\n", v->value);
1595                         else
1596                                 capability &= ~format;
1597                 } else if (!strcasecmp(v->name, "tos")) {
1598                         if (sscanf(v->value, "%i", &format) == 1)
1599                                 tos = format & 0xff;
1600                         else if (!strcasecmp(v->value, "lowdelay"))
1601                                 tos = IPTOS_LOWDELAY;
1602                         else if (!strcasecmp(v->value, "throughput"))
1603                                 tos = IPTOS_THROUGHPUT;
1604                         else if (!strcasecmp(v->value, "reliability"))
1605                                 tos = IPTOS_RELIABILITY;
1606                         else if (!strcasecmp(v->value, "mincost"))
1607                                 tos = IPTOS_MINCOST;
1608                         else if (!strcasecmp(v->value, "none"))
1609                                 tos = 0;
1610                         else
1611                                 ast_log(LOG_WARNING, "Invalid tos value at line %d, should be 'lowdelay', 'throughput', 'reliability', 'mincost', or 'none'\n", v->lineno);
1612                 } else if (!strcasecmp(v->name, "gatekeeper")) {
1613                         if (!strcasecmp(v->value, "DISABLE")) {
1614                                 gatekeeper_disable = 1;
1615                                 usingGk = 0;
1616                         } else if (!strcasecmp(v->value, "DISCOVER")) {
1617                                 gatekeeper_disable = 0;
1618                                 gatekeeper_discover = 1;
1619                                 usingGk = 1;
1620                         } else {
1621                                 gatekeeper_disable = 0;
1622                                 usingGk = 1;
1623                                 strncpy(gatekeeper, v->value, sizeof(gatekeeper)-1);
1624                         }
1625                 } else if (!strcasecmp(v->name, "secret")) {
1626                                 strncpy(secret, v->value, sizeof(secret)-1);
1627                 } else if (!strcasecmp(v->name, "AllowGKRouted")) {
1628                                 gkroute = ast_true(v->value);
1629                 } else if (!strcasecmp(v->name, "context")) {
1630                         strncpy(default_context, v->value, sizeof(default_context)-1);
1631                         ast_verbose(VERBOSE_PREFIX_3 "  == Setting default context to %s\n", default_context);  
1632                 } else if (!strcasecmp(v->name, "dtmfmode")) {
1633                         if (!strcasecmp(v->value, "inband"))
1634                                 dtmfmode=H323_DTMF_INBAND;
1635                         else if (!strcasecmp(v->value, "rfc2833"))
1636                                 dtmfmode = H323_DTMF_RFC2833;
1637                         else {
1638                                 ast_log(LOG_WARNING, "Unknown dtmf mode '%s', using rfc2833\n", v->value);
1639                                 dtmfmode = H323_DTMF_RFC2833;
1640                         }
1641                 } else if (!strcasecmp(v->name, "UserByAlias")) {
1642                         userbyalias = ast_true(v->value);
1643                 } else if (!strcasecmp(v->name, "bridge")) {
1644                         bridge_default = ast_true(v->value);
1645                 }
1646                 v = v->next;    
1647         }
1648         
1649         cat = ast_category_browse(cfg, NULL);
1650         while(cat) {
1651                 if (strcasecmp(cat, "general")) {
1652                         utype = ast_variable_retrieve(cfg, cat, "type");
1653                         if (utype) {
1654                                 if (!strcasecmp(utype, "user") || !strcasecmp(utype, "friend")) {
1655                                         user = build_user(cat, ast_variable_browse(cfg, cat));
1656                                         if (user) {
1657                                                 ast_mutex_lock(&userl.lock);
1658                                                 user->next = userl.users;
1659                                                 userl.users = user;
1660                                                 ast_mutex_unlock(&userl.lock);
1661                                         }
1662                                 }  else if (!strcasecmp(utype, "peer") || !strcasecmp(utype, "friend")) {
1663                                         peer = build_peer(cat, ast_variable_browse(cfg, cat));
1664                                         if (peer) {
1665                                                 ast_mutex_lock(&peerl.lock);
1666                                                 peer->next = peerl.peers;
1667                                                 peerl.peers = peer;
1668                                                 ast_mutex_unlock(&peerl.lock);
1669                                         }
1670                                 }  else if (!strcasecmp(utype, "h323")) {                       
1671                                         alias = build_alias(cat, ast_variable_browse(cfg, cat));
1672                                         if (alias) {
1673                                                 ast_mutex_lock(&aliasl.lock);
1674                                                 alias->next = aliasl.aliases;
1675                                                 aliasl.aliases = alias;
1676                                                 ast_mutex_unlock(&aliasl.lock);
1677                                         }
1678                                 } else {
1679                                         ast_log(LOG_WARNING, "Unknown type '%s' for '%s' in %s\n", utype, cat, config);
1680                                 }
1681                         } else
1682                                 ast_log(LOG_WARNING, "Section '%s' lacks type\n", cat);
1683                 }
1684                 cat = ast_category_browse(cfg, cat);
1685         }
1686
1687         /* Register our H.323 aliases if any*/
1688         while (alias) {         
1689                 if (h323_set_alias(alias)) {
1690                         ast_log(LOG_ERROR, "Alias %s rejected by endpoint\n", alias->name);
1691                         return -1;
1692                 }       
1693                 alias = alias->next;
1694         }
1695
1696         /* Add some capabilities */
1697         if(h323_set_capability(capability, dtmfmode)) {
1698                 ast_log(LOG_ERROR, "Capabilities failure, this is bad.\n");
1699                 return -1;
1700         }       
1701         ast_destroy(cfg);
1702
1703         return 0;
1704 }
1705
1706 void delete_users(void)
1707 {
1708         struct oh323_user *user, *userlast;
1709         struct oh323_peer *peer;
1710         
1711         /* Delete all users */
1712         ast_mutex_lock(&userl.lock);
1713         for (user=userl.users;user;) {
1714                 userlast = user;
1715                 user=user->next;
1716                 free(userlast);
1717         }
1718         userl.users=NULL;
1719         ast_mutex_unlock(&userl.lock);
1720         ast_mutex_lock(&peerl.lock);
1721         for (peer=peerl.peers;peer;) {
1722                 /* Assume all will be deleted, and we'll find out for sure later */
1723                 peer->delme = 1;
1724                 peer = peer->next;
1725         }
1726         ast_mutex_unlock(&peerl.lock);
1727 }
1728
1729 void delete_aliases(void)
1730 {
1731         struct oh323_alias *alias, *aliaslast;
1732                 
1733         /* Delete all users */
1734         ast_mutex_lock(&aliasl.lock);
1735         for (alias=aliasl.aliases;alias;) {
1736                 aliaslast = alias;
1737                 alias=alias->next;
1738                 free(aliaslast);
1739         }
1740         aliasl.aliases=NULL;
1741         ast_mutex_unlock(&aliasl.lock);
1742 }
1743
1744 void prune_peers(void)
1745 {
1746         /* Prune peers who still are supposed to be deleted */
1747         struct oh323_peer *peer, *peerlast, *peernext;
1748         ast_mutex_lock(&peerl.lock);
1749         peerlast = NULL;
1750         for (peer=peerl.peers;peer;) {
1751                 peernext = peer->next;
1752                 if (peer->delme) {
1753                         free(peer);
1754                         if (peerlast)
1755                                 peerlast->next = peernext;
1756                         else
1757                                 peerl.peers = peernext;
1758                 } else
1759                         peerlast = peer;
1760                 peer=peernext;
1761         }
1762         ast_mutex_unlock(&peerl.lock);
1763 }
1764
1765 int reload(void)
1766 {
1767         delete_users();
1768         delete_aliases();
1769         prune_peers();
1770
1771 #if 0
1772         if (!ast_strlen_zero(gatekeeper)) {
1773                 h323_gk_urq();
1774         }
1775 #endif
1776
1777         reload_config();
1778
1779 #if 0
1780         /* Possibly register with a GK */
1781         if (gatekeeper_disable == 0) {
1782                 if (h323_set_gk(gatekeeper_discover, gatekeeper, secret)) {
1783                         ast_log(LOG_ERROR, "Gatekeeper registration failed.\n");
1784                         h323_end_process();
1785                         return -1;
1786                 }
1787         }
1788 #endif
1789         restart_monitor();
1790         return 0;
1791 }
1792
1793
1794 static struct ast_rtp *oh323_get_rtp_peer(struct ast_channel *chan)
1795 {
1796         struct oh323_pvt *p;
1797         p = (struct oh323_pvt *) chan->pvt->pvt;
1798         if (p && p->rtp && p->bridge) {
1799                 return p->rtp;
1800         }
1801         return NULL;
1802 }
1803
1804 static struct ast_rtp *oh323_get_vrtp_peer(struct ast_channel *chan)
1805 {
1806         return NULL;
1807 }
1808
1809 static char *convertcap(int cap)
1810 {
1811         switch (cap) {
1812         case AST_FORMAT_G723_1:
1813                 return "G.723";
1814         case AST_FORMAT_GSM:
1815                 return "GSM";
1816         case AST_FORMAT_ULAW:
1817                 return "ULAW";
1818         case AST_FORMAT_ALAW:
1819                 return "ALAW";
1820         case AST_FORMAT_ADPCM:
1821                 return "G.728";
1822         case AST_FORMAT_G729A:
1823                 return "G.729";
1824         case AST_FORMAT_SPEEX:
1825                 return "SPEEX";
1826         case AST_FORMAT_ILBC:
1827                 return "ILBC";
1828         default:
1829                 ast_log(LOG_NOTICE, "Don't know how to deal with mode %d\n", cap);
1830                 return NULL;
1831         }
1832
1833 }
1834
1835 static int oh323_set_rtp_peer(struct ast_channel *chan, struct ast_rtp *rtp, struct ast_rtp *vrtp, int codecs)
1836 {
1837         /* XXX Deal with Video */
1838         struct oh323_pvt *p;
1839         struct sockaddr_in them;
1840         struct sockaddr_in us;
1841         char *mode;
1842         char iabuf[INET_ADDRSTRLEN];
1843
1844         mode = convertcap(chan->writeformat); 
1845
1846         if (!rtp) {
1847                 return 0;
1848         }
1849
1850         p = (struct oh323_pvt *) chan->pvt->pvt;
1851         if (!p) {
1852                 ast_log(LOG_ERROR, "No Private Structure, this is bad\n");
1853                 return -1;
1854         }
1855
1856         ast_rtp_get_peer(rtp, &them);   
1857         ast_rtp_get_us(rtp, &us);
1858
1859         h323_native_bridge(p->cd.call_token, ast_inet_ntoa(iabuf, sizeof(iabuf), them.sin_addr), mode);
1860         
1861         return 0;
1862         
1863 }
1864
1865 static struct ast_rtp_protocol oh323_rtp = {
1866         get_rtp_info: oh323_get_rtp_peer,
1867         get_vrtp_info: oh323_get_vrtp_peer,
1868         set_rtp_peer: oh323_set_rtp_peer,
1869 };
1870
1871 int load_module()
1872 {
1873         int res;
1874
1875         ast_mutex_init(&userl.lock);
1876         ast_mutex_init(&peerl.lock);
1877         ast_mutex_init(&aliasl.lock);
1878
1879         res = reload_config();
1880
1881         if (res) {
1882                 return 0;
1883         } else {
1884                 /* Make sure we can register our channel type */
1885                 if (ast_channel_register(type, tdesc, capability, oh323_request)) {
1886                         ast_log(LOG_ERROR, "Unable to register channel class %s\n", type);
1887                         h323_end_process();
1888                         return -1;
1889                 }
1890                 ast_cli_register(&cli_debug);
1891                 ast_cli_register(&cli_no_debug);
1892                 ast_cli_register(&cli_trace);
1893                 ast_cli_register(&cli_no_trace);
1894                 ast_cli_register(&cli_show_codecs);
1895                 ast_cli_register(&cli_gk_cycle);
1896                 ast_cli_register(&cli_hangup_call);
1897                 ast_cli_register(&cli_show_tokens);
1898
1899                 oh323_rtp.type = type;
1900                 ast_rtp_proto_register(&oh323_rtp);
1901
1902                 sched = sched_context_create();
1903                 if (!sched) {
1904                         ast_log(LOG_WARNING, "Unable to create schedule context\n");
1905                 }
1906                 io = io_context_create();
1907                 if (!io) {
1908                         ast_log(LOG_WARNING, "Unable to create I/O context\n");
1909                 }
1910                 
1911                 /* Register our callback functions */
1912                 h323_callback_register(setup_incoming_call, 
1913                                        setup_outgoing_call,                                                      
1914                                        create_connection, 
1915                                        setup_rtp_connection, 
1916                                        cleanup_connection, 
1917                                        chan_ringing,
1918                                        connection_made, 
1919                                        send_digit,
1920                                        answer_call);
1921         
1922
1923                 /* start the h.323 listener */
1924                 if (h323_start_listener(port, bindaddr)) {
1925                         ast_log(LOG_ERROR, "Unable to create H323 listener.\n");
1926                         return -1;
1927                 }
1928
1929                 /* Possibly register with a GK */
1930                 if (gatekeeper_disable == 0) {
1931                         if (h323_set_gk(gatekeeper_discover, gatekeeper, secret)) {
1932                                 ast_log(LOG_ERROR, "Gatekeeper registration failed.\n");
1933                                 return 0;
1934                         }
1935                 }
1936                 /* And start the monitor for the first time */
1937                 restart_monitor();
1938         }
1939         return res;
1940 }
1941
1942
1943 int unload_module() 
1944 {
1945         struct oh323_pvt *p, *pl;
1946                 
1947         if (!ast_mutex_lock(&iflock)) {
1948         /* hangup all interfaces if they have an owner */
1949         p = iflist;
1950         while(p) {
1951                 if (p->owner)
1952                         ast_softhangup(p->owner, AST_SOFTHANGUP_APPUNLOAD);
1953                 p = p->next;
1954         }
1955         iflist = NULL;
1956         ast_mutex_unlock(&iflock);
1957         } else {
1958                 ast_log(LOG_WARNING, "Unable to lock the interface list\n");
1959                 return -1;
1960         }
1961
1962         if (!ast_mutex_lock(&monlock)) {
1963                 if (monitor_thread && (monitor_thread != AST_PTHREADT_STOP)) {
1964                         pthread_cancel(monitor_thread);
1965                         pthread_kill(monitor_thread, SIGURG);
1966                         pthread_join(monitor_thread, NULL);
1967                  }
1968                 monitor_thread = AST_PTHREADT_STOP;
1969                 ast_mutex_unlock(&monlock);
1970         } else {
1971                 ast_log(LOG_WARNING, "Unable to lock the monitor\n");
1972                 return -1;
1973         }
1974                 
1975         if (!ast_mutex_lock(&iflock)) {
1976                 /* destroy all the interfaces and free their memory */
1977                 p = iflist;
1978                 while(p) {
1979                         pl = p;
1980                         p = p->next;
1981                         /* free associated memory */
1982                         ast_mutex_destroy(&pl->lock);
1983                         free(pl);
1984                 }
1985                 iflist = NULL;
1986                 ast_mutex_unlock(&iflock);
1987         } else {
1988                 ast_log(LOG_WARNING, "Unable to lock the interface list\n");
1989                 return -1;
1990         }
1991         h323_gk_urq();
1992         h323_end_process();
1993
1994         /* unregister rtp */
1995         ast_rtp_proto_unregister(&oh323_rtp);
1996         
1997         /* unregister commands */
1998         ast_cli_unregister(&cli_debug);
1999         ast_cli_unregister(&cli_no_debug);
2000         ast_cli_unregister(&cli_trace);
2001         ast_cli_unregister(&cli_no_trace);   
2002         ast_cli_unregister(&cli_show_codecs);
2003         ast_cli_unregister(&cli_gk_cycle);
2004         ast_cli_unregister(&cli_hangup_call);
2005         ast_cli_unregister(&cli_show_tokens);
2006                         
2007         /* unregister channel type */
2008         ast_channel_unregister(type);
2009
2010         return 0; 
2011
2012
2013 int usecount()
2014 {
2015         int res;
2016         ast_mutex_lock(&usecnt_lock);
2017         res = usecnt;
2018         ast_mutex_unlock(&usecnt_lock);
2019         return res;
2020 }
2021
2022 char *description()
2023 {
2024         return desc;
2025 }
2026
2027 char *key()
2028 {
2029         return ASTERISK_GPL_KEY;
2030 }
2031
2032
2033
2034