since the module API is changing, it's a good time to const-ify the description(...
[asterisk/asterisk.git] / channels / chan_h323.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 1999 - 2005
5  *
6  * OpenH323 Channel Driver for ASTERISK PBX.
7  *                      By Jeremy McNamara
8  *                      For The NuFone Network 
9  *
10  * chan_h323 has been derived from code created by
11  *               Michael Manousos and Mark Spencer
12  *
13  * See http://www.asterisk.org for more information about
14  * the Asterisk project. Please do not directly contact
15  * any of the maintainers of this project for assistance;
16  * the project provides a web site, mailing lists and IRC
17  * channels for your use.
18  *
19  * This program is free software, distributed under the terms of
20  * the GNU General Public License Version 2. See the LICENSE file
21  * at the top of the source tree.
22  */
23
24 /*! \file
25  *
26  * \brief This file is part of the chan_h323 driver for Asterisk
27  *
28  * \author Jeremy McNamara
29  *
30  * \par See also
31  * \arg Config_h323
32  *
33  * \ingroup channel_drivers
34  */
35
36 #include <sys/socket.h>
37 #include <sys/signal.h>
38 #include <sys/param.h>
39 #if defined(BSD)
40 #ifndef IPTOS_MINCOST
41 #define IPTOS_MINCOST 0x02
42 #endif
43 #endif
44 #include <arpa/inet.h>
45 #include <net/if.h>
46 #include <netinet/in.h>
47 #include <netinet/in_systm.h>
48 #include <netinet/ip.h>
49 #include <unistd.h>
50 #include <stdlib.h>
51 #include <netdb.h>
52 #include <stdio.h>
53 #include <string.h>
54 #include <errno.h>
55 #include <fcntl.h>
56 #ifdef __cplusplus
57 extern "C" {
58 #endif   
59
60 #include "asterisk.h"
61
62 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
63
64 #include "asterisk/lock.h"
65 #include "asterisk/logger.h"
66 #include "asterisk/channel.h"
67 #include "asterisk/config.h"
68 #include "asterisk/module.h"
69 #include "asterisk/pbx.h"
70 #include "asterisk/options.h"
71 #include "asterisk/utils.h"
72 #include "asterisk/lock.h"
73 #include "asterisk/sched.h"
74 #include "asterisk/io.h"
75 #include "asterisk/rtp.h"
76 #include "asterisk/acl.h"
77 #include "asterisk/callerid.h"
78 #include "asterisk/cli.h"
79 #include "asterisk/dsp.h"
80 #include "asterisk/causes.h"
81 #include "asterisk/stringfields.h"
82 #ifdef __cplusplus
83 }
84 #endif
85 #include "h323/chan_h323.h"
86
87 send_digit_cb on_send_digit; 
88 on_rtp_cb on_external_rtp_create; 
89 start_rtp_cb on_start_rtp_channel; 
90 setup_incoming_cb on_incoming_call;
91 setup_outbound_cb on_outgoing_call; 
92 chan_ringing_cb on_chan_ringing;
93 con_established_cb on_connection_established;
94 clear_con_cb on_connection_cleared;
95 answer_call_cb on_answer_call;
96 progress_cb on_progress;
97 rfc2833_cb on_set_rfc2833_payload;
98 hangup_cb on_hangup;
99 setcapabilities_cb on_setcapabilities;
100
101 /* global debug flag */
102 int h323debug;
103
104 /** Variables required by Asterisk */
105 static const char desc[] = "The NuFone Network's Open H.323 Channel Driver";
106 static const char tdesc[] = "The NuFone Network's Open H.323 Channel Driver";
107 static const char config[] = "h323.conf";
108 static char default_context[AST_MAX_CONTEXT] = "default";
109 static struct sockaddr_in bindaddr;
110
111 #define GLOBAL_CAPABILITY (AST_FORMAT_G723_1 | AST_FORMAT_GSM | AST_FORMAT_ULAW | AST_FORMAT_ALAW | AST_FORMAT_G729A | AST_FORMAT_H261)
112
113 /** H.323 configuration values */
114 static int h323_signalling_port = 1720;
115 static char gatekeeper[100];
116 static int gatekeeper_disable = 1;
117 static int gatekeeper_discover = 0;
118 static int usingGk = 0;
119 static int gkroute = 0;
120 /* Find user by alias (h.323 id) is default, alternative is the incomming call's source IP address*/
121 static int userbyalias = 1;
122 static int tos = 0;
123 static char secret[50];
124 static unsigned int unique = 0;
125
126 static call_options_t global_options;
127
128 /** Private structure of a OpenH323 channel */
129 struct oh323_pvt {
130         ast_mutex_t lock;                                       /* Channel private lock */
131         call_options_t options;                                 /* Options to be used during call setup */
132         int alreadygone;                                        /* Whether or not we've already been destroyed by our peer */
133         int needdestroy;                                        /* if we need to be destroyed */
134         call_details_t cd;                                      /* Call details */
135         struct ast_channel *owner;                              /* Who owns us */
136         struct sockaddr_in sa;                                  /* Our peer */
137         struct sockaddr_in redirip;                             /* Where our RTP should be going if not to us */
138         int nonCodecCapability;                                 /* non-audio capability */
139         int outgoing;                                           /* Outgoing or incoming call? */
140         char exten[AST_MAX_EXTENSION];                          /* Requested extension */
141         char context[AST_MAX_CONTEXT];                          /* Context where to start */
142         char accountcode[256];                                  /* Account code */
143         char cid_num[80];                                       /* Caller*id number, if available */
144         char cid_name[80];                                      /* Caller*id name, if available */
145         char rdnis[80];                                         /* Referring DNIS, if available */
146         int amaflags;                                           /* AMA Flags */
147         struct ast_rtp *rtp;                                    /* RTP Session */
148         struct ast_dsp *vad;                                    /* Used for in-band DTMF detection */
149         int nativeformats;                                      /* Codec formats supported by a channel */
150         int needhangup;                                         /* Send hangup when Asterisk is ready */
151         int hangupcause;                                        /* Hangup cause from OpenH323 layer */
152         int newstate;                                           /* Pending state change */
153         int newcontrol;                                         /* Pending control to send */
154         struct oh323_pvt *next;                         /* Next channel in list */
155 } *iflist = NULL;
156
157 static struct ast_user_list {
158         struct oh323_user *users;
159         ast_mutex_t lock;
160 } userl;
161
162 static struct ast_peer_list {
163         struct oh323_peer *peers;
164         ast_mutex_t lock;
165 } peerl;
166
167 static struct ast_alias_list {
168         struct oh323_alias *aliases;
169         ast_mutex_t lock;
170 } aliasl;
171
172 /** Asterisk RTP stuff */
173 static struct sched_context *sched;
174 static struct io_context *io;
175
176 /** Protect the interface list (oh323_pvt) */
177 AST_MUTEX_DEFINE_STATIC(iflock);
178
179 /** Usage counter and associated lock */
180 static int usecnt = 0;
181 AST_MUTEX_DEFINE_STATIC(usecnt_lock);
182
183 /* Protect the monitoring thread, so only one process can kill or start it, and not
184    when it's doing something critical. */
185 AST_MUTEX_DEFINE_STATIC(monlock);
186
187 /* Protect the H.323 capabilities list, to avoid more than one channel to set the capabilities simultaneaously in the h323 stack. */
188 AST_MUTEX_DEFINE_STATIC(caplock);
189
190 /* Protect the reload process */
191 AST_MUTEX_DEFINE_STATIC(h323_reload_lock);
192 static int h323_reloading = 0;
193
194 /* This is the thread for the monitor which checks for input on the channels
195    which are not currently in use.  */
196 static pthread_t monitor_thread = AST_PTHREADT_NULL;
197 static int restart_monitor(void);
198 static int h323_do_reload(void);
199
200 static struct ast_channel *oh323_request(const char *type, int format, void *data, int *cause);
201 static int oh323_digit(struct ast_channel *c, char digit);
202 static int oh323_call(struct ast_channel *c, char *dest, int timeout);
203 static int oh323_hangup(struct ast_channel *c);
204 static int oh323_answer(struct ast_channel *c);
205 static struct ast_frame *oh323_read(struct ast_channel *c);
206 static int oh323_write(struct ast_channel *c, struct ast_frame *frame);
207 static int oh323_indicate(struct ast_channel *c, int condition);
208 static int oh323_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
209
210 static const struct ast_channel_tech oh323_tech = {
211         .type = "H323",
212         .description = tdesc,
213         .capabilities = ((AST_FORMAT_MAX_AUDIO << 1) - 1),
214         .properties = AST_CHAN_TP_WANTSJITTER,
215         .requester = oh323_request,
216         .send_digit = oh323_digit,
217         .call = oh323_call,
218         .hangup = oh323_hangup,
219         .answer = oh323_answer,
220         .read = oh323_read,
221         .write = oh323_write,
222         .indicate = oh323_indicate,
223         .fixup = oh323_fixup,
224         /* disable, for now */
225 #if 0
226         .bridge = ast_rtp_bridge,
227 #endif
228 };
229
230 /* Channel and private structures should be already locked */
231 static void __oh323_update_info(struct ast_channel *c, struct oh323_pvt *pvt)
232 {
233         if (c->nativeformats != pvt->nativeformats) {
234                 if (h323debug)
235                         ast_log(LOG_DEBUG, "Preparing %s for new native format\n", c->name);
236                 c->nativeformats = pvt->nativeformats;
237                 ast_set_read_format(c, c->readformat);
238                 ast_set_write_format(c, c->writeformat);
239         }
240         if (pvt->needhangup) {
241                 if (h323debug)
242                         ast_log(LOG_DEBUG, "Process pending hangup for %s\n", c->name);
243                 c->_softhangup |= AST_SOFTHANGUP_DEV;
244                 c->hangupcause = pvt->hangupcause;
245                 ast_queue_hangup(c);
246                 pvt->needhangup = 0;
247                 pvt->newstate = pvt->newcontrol = -1;
248         }
249         if (pvt->newstate >= 0) {
250                 ast_setstate(c, pvt->newstate);
251                 pvt->newstate = -1;
252         }
253         if (pvt->newcontrol >= 0) {
254                 ast_queue_control(c, pvt->newcontrol);
255                 pvt->newcontrol = -1;
256         }
257 }
258
259 /* Only channel structure should be locked */
260 static void oh323_update_info(struct ast_channel *c)
261 {
262         struct oh323_pvt *pvt = c->tech_pvt;
263
264         if (pvt) {
265                 ast_mutex_lock(&pvt->lock);
266                 __oh323_update_info(c, pvt);
267                 ast_mutex_unlock(&pvt->lock);
268         }
269 }
270
271 static void cleanup_call_details(call_details_t *cd) 
272 {
273         if (cd->call_token) {
274                 free(cd->call_token);
275                 cd->call_token = NULL;
276         }
277         if (cd->call_source_aliases) {
278                 free(cd->call_source_aliases);
279                 cd->call_source_aliases = NULL;
280         }
281         if (cd->call_dest_alias) {
282                 free(cd->call_dest_alias);
283                 cd->call_dest_alias = NULL;
284         }
285         if (cd->call_source_name) { 
286                 free(cd->call_source_name);
287                 cd->call_source_name = NULL;
288         }
289         if (cd->call_source_e164) {
290                 free(cd->call_source_e164);
291                 cd->call_source_e164 = NULL;
292         }
293         if (cd->call_dest_e164) {
294                 free(cd->call_dest_e164);
295                 cd->call_dest_e164 = NULL;
296         }
297         if (cd->sourceIp) {
298                 free(cd->sourceIp);
299                 cd->sourceIp = NULL;
300         }
301 }
302
303 static void __oh323_destroy(struct oh323_pvt *pvt)
304 {
305         struct oh323_pvt *cur, *prev = NULL;
306         
307         if (pvt->rtp) {
308                 ast_rtp_destroy(pvt->rtp);
309         }
310         
311         /* Free dsp used for in-band DTMF detection */
312         if (pvt->vad) {
313                 ast_dsp_free(pvt->vad);
314         }
315         cleanup_call_details(&pvt->cd);
316
317         /* Unlink us from the owner if we have one */
318         if (pvt->owner) {
319                 ast_mutex_lock(&pvt->owner->lock);
320                 ast_log(LOG_DEBUG, "Detaching from %s\n", pvt->owner->name);
321                 pvt->owner->tech_pvt = NULL;
322                 ast_mutex_unlock(&pvt->owner->lock);
323         }
324         cur = iflist;
325         while(cur) {
326                 if (cur == pvt) {
327                         if (prev)
328                                 prev->next = cur->next;
329                         else
330                                 iflist = cur->next;
331                         break;
332                 }
333                 prev = cur;
334                 cur = cur->next;
335         }
336         if (!cur) {
337                 ast_log(LOG_WARNING, "%p is not in list?!?! \n", cur);
338         } else {
339                 ast_mutex_destroy(&pvt->lock);
340                 free(pvt);
341         }
342 }
343
344 static void oh323_destroy(struct oh323_pvt *pvt)
345 {
346         ast_mutex_lock(&iflock);
347         __oh323_destroy(pvt);
348         ast_mutex_unlock(&iflock);
349 }
350
351 /**
352  * Send (play) the specified digit to the channel.
353  * 
354  */
355 static int oh323_digit(struct ast_channel *c, char digit)
356 {
357         struct oh323_pvt *pvt = (struct oh323_pvt *) c->tech_pvt;
358         char *token;
359
360         if (!pvt) {
361                 ast_log(LOG_ERROR, "No private structure?! This is bad\n");
362                 return -1;
363         }
364         ast_mutex_lock(&pvt->lock);
365         if (pvt->rtp && (pvt->options.dtmfmode & H323_DTMF_RFC2833)) {
366                 /* out-of-band DTMF */
367                 if (h323debug) {
368                         ast_log(LOG_DEBUG, "Sending out-of-band digit %c on %s\n", digit, c->name);
369                 }
370                 ast_rtp_senddigit(pvt->rtp, digit);
371         } else {
372                 /* in-band DTMF */
373                 if (h323debug) {
374                         ast_log(LOG_DEBUG, "Sending inband digit %c on %s\n", digit, c->name);
375                 }
376                 token = pvt->cd.call_token ? strdup(pvt->cd.call_token) : NULL;
377                 h323_send_tone(token, digit);
378                 if (token) {
379                         free(token);
380                 }
381         }
382         ast_mutex_unlock(&pvt->lock);
383         oh323_update_info(c);
384         return 0;
385 }
386
387 /**
388  * Make a call over the specified channel to the specified 
389  * destination.
390  * Returns -1 on error, 0 on success.
391  */
392 static int oh323_call(struct ast_channel *c, char *dest, int timeout)
393 {  
394         int res = 0;
395         struct oh323_pvt *pvt = (struct oh323_pvt *)c->tech_pvt;
396         char addr[INET_ADDRSTRLEN];
397         char called_addr[1024];
398
399         if (h323debug) {
400                 ast_log(LOG_DEBUG, "Calling to %s on %s\n", dest, c->name);
401         }
402         if ((c->_state != AST_STATE_DOWN) && (c->_state != AST_STATE_RESERVED)) {
403                 ast_log(LOG_WARNING, "Line is already in use (%s)\n", c->name);
404                 return -1;
405         }
406         ast_mutex_lock(&pvt->lock);
407         if (usingGk) {
408                 if (ast_strlen_zero(pvt->exten)) {
409                         strncpy(called_addr, dest, sizeof(called_addr));
410                 } else {
411                         snprintf(called_addr, sizeof(called_addr), "%s@%s", pvt->exten, dest);
412                 }
413         } else {
414                 ast_inet_ntoa(addr, sizeof(addr), pvt->sa.sin_addr);
415                 res = htons(pvt->sa.sin_port);
416                 if (ast_strlen_zero(pvt->exten)) {
417                         snprintf(called_addr, sizeof(called_addr), "%s:%d", addr, res);
418                 } else {
419                         snprintf(called_addr, sizeof(called_addr), "%s@%s:%d", pvt->exten, addr, res);
420                 }
421         }
422         /* make sure null terminated */
423         called_addr[sizeof(called_addr) - 1] = '\0'; 
424
425         if (c->cid.cid_num) {
426                 strncpy(pvt->options.cid_num, c->cid.cid_num, sizeof(pvt->options.cid_num));
427         }
428         if (c->cid.cid_name) {
429                 strncpy(pvt->options.cid_name, c->cid.cid_name, sizeof(pvt->options.cid_name));
430         }
431
432         /* indicate that this is an outgoing call */
433         pvt->outgoing = 1;
434
435         ast_log(LOG_DEBUG, "Placing outgoing call to %s, %d\n", called_addr, pvt->options.dtmfcodec);
436         ast_mutex_unlock(&pvt->lock);
437         res = h323_make_call(called_addr, &(pvt->cd), &pvt->options);
438         if (res) {
439                 ast_log(LOG_NOTICE, "h323_make_call failed(%s)\n", c->name);
440                 return -1;
441         }
442         oh323_update_info(c);
443         return 0;
444 }
445
446 static int oh323_answer(struct ast_channel *c)
447 {
448         int res;
449         struct oh323_pvt *pvt = (struct oh323_pvt *) c->tech_pvt;
450         char *token;
451
452         if (h323debug)
453                 ast_log(LOG_DEBUG, "Answering on %s\n", c->name);
454
455         ast_mutex_lock(&pvt->lock);
456         token = pvt->cd.call_token ? strdup(pvt->cd.call_token) : NULL;
457         ast_mutex_unlock(&pvt->lock);
458         res = h323_answering_call(token, 0);
459         if (token)
460                 free(token);
461
462         oh323_update_info(c);
463         if (c->_state != AST_STATE_UP) {
464                 ast_setstate(c, AST_STATE_UP);
465         }
466         return res;
467 }
468
469 static int oh323_hangup(struct ast_channel *c)
470 {
471         struct oh323_pvt *pvt = (struct oh323_pvt *) c->tech_pvt;
472         int needcancel = 0;
473         int q931cause = AST_CAUSE_NORMAL_CLEARING;
474         char *call_token;
475
476
477         if (h323debug)
478                 ast_log(LOG_DEBUG, "Hanging up call %s\n", c->name);
479
480         if (!c->tech_pvt) {
481                 ast_log(LOG_DEBUG, "Asked to hangup channel not connected\n");
482                 return 0;
483         }
484         ast_mutex_lock(&pvt->lock);
485         /* Determine how to disconnect */
486         if (pvt->owner != c) {
487                 ast_log(LOG_WARNING, "Huh?  We aren't the owner?\n");
488                 ast_mutex_unlock(&pvt->lock);
489                 return 0;
490         }
491         if (!c || (c->_state != AST_STATE_UP)) {
492                 needcancel = 1;
493         }
494         
495         pvt->owner = NULL;
496         c->tech_pvt = NULL;
497
498         if (c->hangupcause) {
499                 q931cause = c->hangupcause;
500         } else {
501                 const char *cause = pbx_builtin_getvar_helper(c, "DIALSTATUS");
502                 if (cause) {
503                         if (!strcmp(cause, "CONGESTION")) {
504                                 q931cause = AST_CAUSE_NORMAL_CIRCUIT_CONGESTION;
505                         } else if (!strcmp(cause, "BUSY")) {
506                                 q931cause = AST_CAUSE_USER_BUSY;
507                         } else if (!strcmp(cause, "CHANISUNVAIL")) {
508                                 q931cause = AST_CAUSE_REQUESTED_CHAN_UNAVAIL;
509                         } else if (!strcmp(cause, "NOANSWER")) {
510                                 q931cause = AST_CAUSE_NO_ANSWER;
511                         } else if (!strcmp(cause, "CANCEL")) {
512                                 q931cause = AST_CAUSE_CALL_REJECTED;
513                         }
514                 }
515         }
516
517         /* Start the process if it's not already started */
518         if (!pvt->alreadygone && !pvt->hangupcause) {
519                 call_token = pvt->cd.call_token ? strdup(pvt->cd.call_token) : NULL;
520                 if (call_token) {
521                         /* Release lock to eliminate deadlock */
522                         ast_mutex_unlock(&pvt->lock);
523                         if (h323_clear_call(call_token, q931cause)) { 
524                                 ast_log(LOG_DEBUG, "ClearCall failed.\n");
525                         }
526                         free(call_token);
527                         ast_mutex_lock(&pvt->lock);
528                 }
529         } 
530         pvt->needdestroy = 1;
531
532         /* Update usage counter */
533         ast_mutex_lock(&usecnt_lock);
534         usecnt--;
535         if (usecnt < 0) {
536                 ast_log(LOG_WARNING, "Usecnt < 0\n");
537         }
538         ast_mutex_unlock(&usecnt_lock);
539         ast_mutex_unlock(&pvt->lock);
540         ast_update_use_count();
541         return 0;
542 }
543
544 static struct ast_frame *oh323_rtp_read(struct oh323_pvt *pvt)
545 {
546         /* Retrieve audio/etc from channel.  Assumes pvt->lock is already held. */
547         struct ast_frame *f;
548
549         /* Only apply it for the first packet, we just need the correct ip/port */
550         if (pvt->options.nat) {
551                 ast_rtp_setnat(pvt->rtp, pvt->options.nat);
552                 pvt->options.nat = 0;
553         }
554
555         f = ast_rtp_read(pvt->rtp);
556         /* Don't send RFC2833 if we're not supposed to */
557         if (f && (f->frametype == AST_FRAME_DTMF) && !(pvt->options.dtmfmode & H323_DTMF_RFC2833)) {
558                 return &ast_null_frame;
559         }
560         if (pvt->owner) {
561                 /* We already hold the channel lock */
562                 if (f->frametype == AST_FRAME_VOICE) {
563                         if (f->subclass != pvt->owner->nativeformats) {
564                                 /* Try to avoid deadlock */
565                                 if (ast_mutex_trylock(&pvt->owner->lock)) {
566                                         ast_log(LOG_NOTICE, "Format changed but channel is locked. Ignoring frame...\n");
567                                         return &ast_null_frame;
568                                 }
569                                 ast_log(LOG_DEBUG, "Oooh, format changed to %d\n", f->subclass);
570                                 pvt->owner->nativeformats = f->subclass;
571                                 pvt->nativeformats = f->subclass;
572                                 ast_set_read_format(pvt->owner, pvt->owner->readformat);
573                                 ast_set_write_format(pvt->owner, pvt->owner->writeformat);
574                                 ast_mutex_unlock(&pvt->owner->lock);
575                         }       
576                         /* Do in-band DTMF detection */
577                         if ((pvt->options.dtmfmode & H323_DTMF_INBAND) && pvt->vad) {
578                                 if (!ast_mutex_trylock(&pvt->owner->lock)) {
579                                         f = ast_dsp_process(pvt->owner,pvt->vad,f);
580                                         ast_mutex_unlock(&pvt->owner->lock);
581                                 }
582                                 else
583                                         ast_log(LOG_NOTICE, "Unable to process inband DTMF while channel is locked\n");
584                                 if (f &&(f->frametype == AST_FRAME_DTMF)) {
585                                         ast_log(LOG_DEBUG, "Received in-band digit %c.\n", f->subclass);
586                                 }
587                         }
588                 }
589         }
590         return f;
591 }
592
593 static struct ast_frame *oh323_read(struct ast_channel *c)
594 {
595         struct ast_frame *fr;
596         struct oh323_pvt *pvt = (struct oh323_pvt *)c->tech_pvt;
597         ast_mutex_lock(&pvt->lock);
598         __oh323_update_info(c, pvt);
599         fr = oh323_rtp_read(pvt);
600         ast_mutex_unlock(&pvt->lock);
601         return fr;
602 }
603
604 static int oh323_write(struct ast_channel *c, struct ast_frame *frame)
605 {
606         struct oh323_pvt *pvt = (struct oh323_pvt *) c->tech_pvt;
607         int res = 0;
608         if (frame->frametype != AST_FRAME_VOICE) {
609                 if (frame->frametype == AST_FRAME_IMAGE) {
610                         return 0;
611                 } else {
612                         ast_log(LOG_WARNING, "Can't send %d type frames with H323 write\n", frame->frametype);
613                         return 0;
614                 }
615         } else {
616                 if (!(frame->subclass & c->nativeformats)) {
617                         ast_log(LOG_WARNING, "Asked to transmit frame type %d, while native formats is %d (read/write = %d/%d)\n",
618                                 frame->subclass, c->nativeformats, c->readformat, c->writeformat);
619                         return 0;
620                 }
621         }
622         if (pvt) {
623                 ast_mutex_lock(&pvt->lock);
624                 if (pvt->rtp) {
625                         res =  ast_rtp_write(pvt->rtp, frame);
626                 }
627                 __oh323_update_info(c, pvt);
628                 ast_mutex_unlock(&pvt->lock);
629         }
630         return res;
631 }
632
633 static int oh323_indicate(struct ast_channel *c, int condition)
634 {
635
636         struct oh323_pvt *pvt = (struct oh323_pvt *) c->tech_pvt;
637         char *token = (char *)NULL;
638
639         ast_mutex_lock(&pvt->lock);
640         token = (pvt->cd.call_token ? strdup(pvt->cd.call_token) : NULL);
641         ast_mutex_unlock(&pvt->lock);
642
643         if (h323debug)
644                 ast_log(LOG_DEBUG, "OH323: Indicating %d on %s\n", condition, token);
645
646         switch(condition) {
647         case AST_CONTROL_RINGING:
648                 if (c->_state == AST_STATE_RING || c->_state == AST_STATE_RINGING) {
649                         h323_send_alerting(token);
650                         break;
651                 }
652                 if (token)
653                         free(token);
654                 return -1;
655         case AST_CONTROL_PROGRESS:
656                 if (c->_state != AST_STATE_UP) {
657                         h323_send_progress(token);
658                         break;
659                 }
660                 if (token)
661                         free(token);
662                 return -1;
663
664         case AST_CONTROL_BUSY:
665                 if (c->_state != AST_STATE_UP) {
666                         h323_answering_call(token, 1);
667                         ast_mutex_lock(&pvt->lock);
668                         pvt->alreadygone = 1;
669                         ast_mutex_unlock(&pvt->lock);
670                         ast_softhangup_nolock(c, AST_SOFTHANGUP_DEV);                   
671                         break;
672                 }
673                 if (token)
674                         free(token);
675                 return -1;
676         case AST_CONTROL_CONGESTION:
677                 if (c->_state != AST_STATE_UP) {
678                         h323_answering_call(token, 1);
679                         ast_mutex_lock(&pvt->lock);
680                         pvt->alreadygone = 1;
681                         ast_mutex_unlock(&pvt->lock);
682                         ast_softhangup_nolock(c, AST_SOFTHANGUP_DEV);
683                         break;
684                 }
685                 if (token)
686                         free(token);
687                 return -1;
688         case AST_CONTROL_PROCEEDING:
689         case -1:
690                 if (token)
691                         free(token);
692                 return -1;
693         default:
694                 ast_log(LOG_WARNING, "Don't know how to indicate condition %d on %s\n", condition, token);
695                 if (token)
696                         free(token);
697                 return -1;
698         }
699
700         if (h323debug)
701                 ast_log(LOG_DEBUG, "OH323: Indicated %d on %s\n", condition, token);
702         if (token)
703                 free(token);
704         oh323_update_info(c);
705
706         return -1;
707 }
708
709 static int oh323_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
710 {
711         struct oh323_pvt *pvt = (struct oh323_pvt *) newchan->tech_pvt;
712
713         ast_mutex_lock(&pvt->lock);
714         if (pvt->owner != oldchan) {
715                 ast_log(LOG_WARNING, "old channel wasn't %p but was %p\n", oldchan, pvt->owner);
716                 return -1;
717         }
718         pvt->owner = newchan;
719         ast_mutex_unlock(&pvt->lock);
720         return 0;
721 }
722
723 /* Private structure should be locked on a call */
724 static struct ast_channel *__oh323_new(struct oh323_pvt *pvt, int state, const char *host)
725 {
726         struct ast_channel *ch;
727         int fmt;
728         
729         /* Don't hold a oh323_pvt lock while we allocate a chanel */
730         ast_mutex_unlock(&pvt->lock);
731         ch = ast_channel_alloc(1);
732         /* Update usage counter */
733         ast_mutex_lock(&usecnt_lock);
734         usecnt++;
735         ast_mutex_unlock(&usecnt_lock);
736         ast_update_use_count();
737         ast_mutex_lock(&pvt->lock);
738         if (ch) {
739                 ch->tech = &oh323_tech;
740                 ast_string_field_build(ch, name, "H323/%s", host);
741                 ch->nativeformats = pvt->options.capability;
742                 if (!ch->nativeformats) {
743                         ch->nativeformats = global_options.capability;
744                 }
745                 pvt->nativeformats = ch->nativeformats;
746                 fmt = ast_best_codec(ch->nativeformats);
747                 ch->fds[0] = ast_rtp_fd(pvt->rtp);
748                 if (state == AST_STATE_RING) {
749                         ch->rings = 1;
750                 }
751                 ch->writeformat = fmt;
752                 ch->rawwriteformat = fmt;
753                 ch->readformat = fmt;
754                 ch->rawreadformat = fmt;
755                 /* Allocate dsp for in-band DTMF support */
756                 if (pvt->options.dtmfmode & H323_DTMF_INBAND) {
757                         pvt->vad = ast_dsp_new();
758                         ast_dsp_set_features(pvt->vad, DSP_FEATURE_DTMF_DETECT);
759                 }
760                 /* Register channel functions. */
761                 ch->tech_pvt = pvt;
762                 /*  Set the owner of this channel */
763                 pvt->owner = ch;
764                 
765                 strncpy(ch->context, pvt->context, sizeof(ch->context) - 1);
766                 strncpy(ch->exten, pvt->exten, sizeof(ch->exten) - 1);          
767                 ch->priority = 1;
768                 if (!ast_strlen_zero(pvt->accountcode)) {
769                         ast_string_field_set(ch, accountcode, pvt->accountcode);
770                 }
771                 if (pvt->amaflags) {
772                         ch->amaflags = pvt->amaflags;
773                 }
774                 if (!ast_strlen_zero(pvt->cid_num)) {
775                         ch->cid.cid_num = strdup(pvt->cid_num);
776                 } else if (!ast_strlen_zero(pvt->cd.call_source_e164)) {
777                         ch->cid.cid_num = strdup(pvt->cd.call_source_e164);
778                 }
779                 if (!ast_strlen_zero(pvt->cid_name)) {
780                         ch->cid.cid_name = strdup(pvt->cid_name);
781                 } else if (!ast_strlen_zero(pvt->cd.call_source_name)) {
782                         ch->cid.cid_name = strdup(pvt->cd.call_source_name);
783                 }
784                 if (!ast_strlen_zero(pvt->rdnis)) {
785                         ch->cid.cid_rdnis = strdup(pvt->rdnis);
786                 }
787                 if (!ast_strlen_zero(pvt->exten) && strcmp(pvt->exten, "s")) {
788                         ch->cid.cid_dnid = strdup(pvt->exten);
789                 }
790                 ast_setstate(ch, state);
791                 if (state != AST_STATE_DOWN) {
792                         if (ast_pbx_start(ch)) {
793                                 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", ch->name);
794                                 ast_hangup(ch);
795                                 ch = NULL;
796                         }
797                 }
798         } else  {
799                 ast_log(LOG_WARNING, "Unable to allocate channel structure\n");
800         }
801         return ch;
802 }
803
804 static struct oh323_pvt *oh323_alloc(int callid)
805 {
806         struct oh323_pvt *pvt;
807
808         pvt = (struct oh323_pvt *) malloc(sizeof(struct oh323_pvt));
809         if (!pvt) {
810                 ast_log(LOG_ERROR, "Couldn't allocate private structure. This is bad\n");
811                 return NULL;
812         }
813         memset(pvt, 0, sizeof(struct oh323_pvt));
814         pvt->rtp = ast_rtp_new_with_bindaddr(sched, io, 1, 0,bindaddr.sin_addr);
815         if (!pvt->rtp) {
816                 ast_log(LOG_WARNING, "Unable to create RTP session: %s\n", strerror(errno));
817                 free(pvt);
818                 return NULL;
819         }
820         ast_rtp_settos(pvt->rtp, tos);
821         ast_mutex_init(&pvt->lock);
822         /* Ensure the call token is allocated */
823         if ((pvt->cd).call_token == NULL) {
824                 (pvt->cd).call_token = (char *)malloc(128);
825         }
826         if (!pvt->cd.call_token) {
827                 ast_log(LOG_ERROR, "Not enough memory to alocate call token\n");
828                 return NULL;
829         }
830         memset((char *)(pvt->cd).call_token, 0, 128);
831         pvt->cd.call_reference = callid;
832         memcpy(&pvt->options, &global_options, sizeof(pvt->options));
833         if (pvt->options.dtmfmode & H323_DTMF_RFC2833) {
834                 pvt->nonCodecCapability |= AST_RTP_DTMF;
835         } else {
836                 pvt->nonCodecCapability &= ~AST_RTP_DTMF;
837         }
838         strncpy(pvt->context, default_context, sizeof(pvt->context) - 1);
839         pvt->newstate = pvt->newcontrol = -1;
840         /* Add to interface list */
841         ast_mutex_lock(&iflock);
842         pvt->next = iflist;
843         iflist = pvt;
844         ast_mutex_unlock(&iflock);
845         return pvt;
846 }
847
848 static struct oh323_pvt *find_call_locked(int call_reference, const char *token)
849 {  
850         struct oh323_pvt *pvt;
851
852         ast_mutex_lock(&iflock);
853         pvt = iflist; 
854         while(pvt) {
855                 if (!pvt->needdestroy && ((signed int)pvt->cd.call_reference == call_reference)) {
856                         /* Found the call */             
857                         if ((token != NULL) && (!strcmp(pvt->cd.call_token, token))) {
858                                 ast_mutex_lock(&pvt->lock);
859                                 ast_mutex_unlock(&iflock);
860                                 return pvt;
861                         } else if (token == NULL) {
862                                 ast_log(LOG_WARNING, "Call Token is NULL\n");
863                                 ast_mutex_lock(&pvt->lock);
864                                 ast_mutex_unlock(&iflock);
865                                 return pvt;
866                         }
867                 }
868                 pvt = pvt->next; 
869         }
870         ast_mutex_unlock(&iflock);
871         return NULL;
872 }
873
874 static int update_state(struct oh323_pvt *pvt, int state, int signal)
875 {
876         if (!pvt)
877                 return 0;
878         if (pvt->owner && !ast_mutex_trylock(&pvt->owner->lock)) {
879                 if (state >= 0)
880                         ast_setstate(pvt->owner, state);
881                 if (signal >= 0)
882                         ast_queue_control(pvt->owner, signal);
883                 return 1;
884         }
885         else {
886                 if (state >= 0)
887                         pvt->newstate = state;
888                 if (signal >= 0)
889                         pvt->newcontrol = signal;
890                 return 0;
891         }
892 }
893
894 struct oh323_user *find_user(const call_details_t *cd)
895 {
896         struct oh323_user *u;
897         char iabuf[INET_ADDRSTRLEN];
898         u = userl.users;
899         if (userbyalias) {
900                 while(u) {
901                         if (!strcasecmp(u->name, cd->call_source_aliases)) {
902                                 break;
903                         }
904                         u = u->next;
905                 }
906         } else {
907                 while(u) {
908                         if (!strcasecmp(cd->sourceIp, ast_inet_ntoa(iabuf, sizeof(iabuf), u->addr.sin_addr))) {
909                                 break;
910                         }
911                         u = u->next;
912                 }
913         }
914         return u;
915 }
916
917 struct oh323_peer *find_peer(const char *peer, struct sockaddr_in *sin)
918 {
919         struct oh323_peer *p = NULL;
920         static char iabuf[INET_ADDRSTRLEN];
921
922         p = peerl.peers;
923         if (peer) {
924                 while(p) {
925                         if (!strcasecmp(p->name, peer)) {
926                                 ast_log(LOG_DEBUG, "Found peer %s by name\n", peer);
927                                 break;
928                         }
929                         p = p->next;
930                 }
931         } else {
932                 /* find by sin */
933                 if (sin) {
934                         while (p) {
935                                 if ((!inaddrcmp(&p->addr, sin)) || 
936                                         (p->addr.sin_addr.s_addr == sin->sin_addr.s_addr)) {
937                                         ast_log(LOG_DEBUG, "Found peer %s/%s by addr\n", peer, ast_inet_ntoa(iabuf, sizeof(iabuf), p->addr.sin_addr));
938                                         break;
939                                 }
940                                 p = p->next;
941                         }
942                 }       
943         }
944         if (!p) {
945                 ast_log(LOG_DEBUG, "Could not find peer %s by name or address\n", peer);
946         }
947         return p;
948 }
949
950 static int create_addr(struct oh323_pvt *pvt, char *opeer)
951 {
952         struct hostent *hp;
953         struct ast_hostent ahp;
954         struct oh323_peer *p;
955         int portno;
956         int found = 0;
957         char *port;
958         char *hostn;
959         char peer[256] = "";
960
961         strncpy(peer, opeer, sizeof(peer) - 1);
962         port = strchr(peer, ':');
963         if (port) {
964                 *port = '\0';
965                 port++;
966         }
967         pvt->sa.sin_family = AF_INET;
968         ast_mutex_lock(&peerl.lock);
969         p = find_peer(peer, NULL);
970         if (p) {
971                 found++;
972                 memcpy(&pvt->options, &p->options, sizeof(pvt->options));
973                 if (pvt->rtp) {
974                         ast_log(LOG_DEBUG, "Setting NAT on RTP to %d\n", pvt->options.nat);
975                         ast_rtp_setnat(pvt->rtp, pvt->options.nat);
976                 }
977                 if (pvt->options.dtmfmode) {
978                         if (pvt->options.dtmfmode & H323_DTMF_RFC2833) {
979                                 pvt->nonCodecCapability |= AST_RTP_DTMF;
980                         } else {
981                                 pvt->nonCodecCapability &= ~AST_RTP_DTMF;
982                         }
983                 }
984                 if (p->addr.sin_addr.s_addr) {
985                         pvt->sa.sin_addr = p->addr.sin_addr;    
986                         pvt->sa.sin_port = p->addr.sin_port;    
987                 } 
988         }
989         ast_mutex_unlock(&peerl.lock);
990         if (!p && !found) {
991                 hostn = peer;
992                 if (port) {
993                         portno = atoi(port);
994                 } else {
995                         portno = h323_signalling_port;
996                 }               
997                 hp = ast_gethostbyname(hostn, &ahp);
998                 if (hp) {
999                         memcpy(&pvt->options, &global_options, sizeof(pvt->options));
1000                         memcpy(&pvt->sa.sin_addr, hp->h_addr, sizeof(pvt->sa.sin_addr));
1001                         pvt->sa.sin_port = htons(portno);
1002                         return 0;       
1003                 } else {
1004                         ast_log(LOG_WARNING, "No such host: %s\n", peer);
1005                         return -1;
1006                 }
1007         } else if (!p) {
1008                 return -1;
1009         } else {        
1010                 return 0;
1011         }
1012 }
1013 static struct ast_channel *oh323_request(const char *type, int format, void *data, int *cause)
1014 {
1015         int oldformat;
1016         struct oh323_pvt *pvt;
1017         struct ast_channel *tmpc = NULL;
1018         char *dest = (char *)data;
1019         char *ext, *host;
1020         char *h323id = NULL;
1021         char tmp[256], tmp1[256];
1022         
1023         ast_log(LOG_DEBUG, "type=%s, format=%d, data=%s.\n", type, format, (char *)data);
1024         pvt = oh323_alloc(0);
1025         if (!pvt) {
1026                 ast_log(LOG_WARNING, "Unable to build pvt data for '%s'\n", (char *)data);
1027                 return NULL;
1028         }       
1029         oldformat = format;
1030         format &= ((AST_FORMAT_MAX_AUDIO << 1) - 1);
1031         if (!format) {
1032                 ast_log(LOG_NOTICE, "Asked to get a channel of unsupported format '%d'\n", format);
1033                 return NULL;
1034         }
1035         strncpy(tmp, dest, sizeof(tmp) - 1);    
1036         host = strchr(tmp, '@');
1037         if (host) {
1038                 *host = '\0';
1039                 host++;
1040                 ext = tmp;
1041         } else {
1042                 host = tmp;
1043                 ext = NULL;
1044         }
1045         strtok_r(host, "/", &(h323id));         
1046         if (!ast_strlen_zero(h323id)) {
1047                 h323_set_id(h323id);
1048         }
1049         if (ext) {
1050                 strncpy(pvt->exten, ext, sizeof(pvt->exten) - 1);
1051         }
1052         ast_log(LOG_DEBUG, "Extension: %s Host: %s\n",  pvt->exten, host);
1053         if (!usingGk) {
1054                 if (create_addr(pvt, host)) {
1055                         oh323_destroy(pvt);
1056                         return NULL;
1057                 }
1058         }
1059         else {
1060                 memcpy(&pvt->options, &global_options, sizeof(pvt->options));
1061                 if (pvt->rtp) {
1062                         ast_log(LOG_DEBUG, "Setting NAT on RTP to %d\n", pvt->options.nat);
1063                         ast_rtp_setnat(pvt->rtp, pvt->options.nat);
1064                 }
1065                 if (pvt->options.dtmfmode) {
1066                         if (pvt->options.dtmfmode & H323_DTMF_RFC2833) {
1067                                 pvt->nonCodecCapability |= AST_RTP_DTMF;
1068                         } else {
1069                                 pvt->nonCodecCapability &= ~AST_RTP_DTMF;
1070                         }
1071                 }
1072         }
1073
1074         ast_mutex_lock(&caplock);
1075         /* Generate unique channel identifier */
1076         snprintf(tmp1, sizeof(tmp1)-1, "%s-%u", host, ++unique);
1077         tmp1[sizeof(tmp1)-1] = '\0';
1078         ast_mutex_unlock(&caplock);
1079
1080         ast_mutex_lock(&pvt->lock);
1081         tmpc = __oh323_new(pvt, AST_STATE_DOWN, tmp1);
1082         ast_mutex_unlock(&pvt->lock);
1083         if (!tmpc) {
1084                 oh323_destroy(pvt);
1085         }
1086         ast_update_use_count();
1087         restart_monitor();
1088         return tmpc;
1089 }
1090
1091 /** Find a call by alias */
1092 struct oh323_alias *find_alias(const char *source_aliases)
1093 {
1094         struct oh323_alias *a;
1095
1096         a = aliasl.aliases;
1097         while(a) {
1098                 if (!strcasecmp(a->name, source_aliases)) {
1099                         break;
1100                 }
1101                 a = a->next;
1102         }
1103         return a;
1104 }
1105
1106 /**
1107   * Callback for sending digits from H.323 up to asterisk
1108   *
1109   */
1110 int send_digit(unsigned call_reference, char digit, const char *token)
1111 {
1112         struct oh323_pvt *pvt;
1113         struct ast_frame f;
1114         int res;
1115
1116         ast_log(LOG_DEBUG, "Received Digit: %c\n", digit);
1117         pvt = find_call_locked(call_reference, token); 
1118         if (!pvt) {
1119                 ast_log(LOG_ERROR, "Private structure not found in send_digit.\n");
1120                 return -1;
1121         }
1122         memset(&f, 0, sizeof(f));
1123         f.frametype = AST_FRAME_DTMF;
1124         f.subclass = digit;
1125         f.datalen = 0;
1126         f.samples = 800;
1127         f.offset = 0;
1128         f.data = NULL;
1129         f.mallocd = 0;
1130         f.src = "SEND_DIGIT";   
1131         res = ast_queue_frame(pvt->owner, &f);
1132         ast_mutex_unlock(&pvt->lock);
1133         return res;
1134 }
1135
1136 /**
1137   * Callback function used to inform the H.323 stack of the local rtp ip/port details
1138   *
1139   * Returns the local RTP information
1140   */
1141 struct rtp_info *external_rtp_create(unsigned call_reference, const char * token)
1142 {       
1143         struct oh323_pvt *pvt;
1144         struct sockaddr_in us;
1145         struct rtp_info *info;
1146
1147         info = (struct rtp_info *)malloc(sizeof(struct rtp_info));
1148         if (!info) {
1149                 ast_log(LOG_ERROR, "Unable to allocated info structure, this is very bad\n");
1150                 return NULL;
1151         }
1152         pvt = find_call_locked(call_reference, token); 
1153         if (!pvt) {
1154                 free(info);
1155                 ast_log(LOG_ERROR, "Unable to find call %s(%d)\n", token, call_reference);
1156                 return NULL;
1157         }
1158         /* figure out our local RTP port and tell the H.323 stack about it */
1159         ast_rtp_get_us(pvt->rtp, &us);
1160         ast_mutex_unlock(&pvt->lock);
1161
1162         ast_inet_ntoa(info->addr, sizeof(info->addr), us.sin_addr);
1163         info->port = ntohs(us.sin_port);
1164         if (h323debug)
1165                 ast_log(LOG_DEBUG, "Sending RTP 'US' %s:%d\n", info->addr, info->port);
1166         return info;
1167 }
1168
1169 /**
1170  * Definition taken from rtp.c for rtpPayloadType because we need it here.
1171  */
1172 struct rtpPayloadType {
1173         int isAstFormat;        /* whether the following code is an AST_FORMAT */
1174         int code;
1175 };
1176
1177 /**
1178   * Call-back function passing remote ip/port information from H.323 to asterisk 
1179   *
1180   * Returns nothing 
1181   */
1182 void setup_rtp_connection(unsigned call_reference, const char *remoteIp, int remotePort, const char *token, int pt)
1183 {
1184         struct oh323_pvt *pvt;
1185         struct sockaddr_in them;
1186         struct rtpPayloadType rtptype;
1187
1188         if (h323debug)
1189                 ast_log(LOG_DEBUG, "Setting up RTP connection for %s\n", token);
1190
1191         /* Find the call or allocate a private structure if call not found */
1192         pvt = find_call_locked(call_reference, token); 
1193         if (!pvt) {
1194                 ast_log(LOG_ERROR, "Something is wrong: rtp\n");
1195                 return;
1196         }
1197         if (pvt->alreadygone) {
1198                 ast_mutex_unlock(&pvt->lock);
1199                 return;
1200         }
1201         rtptype = ast_rtp_lookup_pt(pvt->rtp, pt);
1202         pvt->nativeformats = rtptype.code;
1203         if (pvt->owner && !ast_mutex_trylock(&pvt->owner->lock)) {
1204                 pvt->owner->nativeformats = pvt->nativeformats;
1205                 ast_set_read_format(pvt->owner, pvt->owner->readformat);
1206                 ast_set_write_format(pvt->owner, pvt->owner->writeformat);
1207                 if (pvt->options.progress_audio)
1208                         ast_queue_control(pvt->owner, AST_CONTROL_PROGRESS);
1209                 ast_mutex_unlock(&pvt->owner->lock);
1210         }
1211         else {
1212                 if (pvt->options.progress_audio)
1213                         pvt->newcontrol = AST_CONTROL_PROGRESS;
1214                 if (h323debug)
1215                         ast_log(LOG_DEBUG, "RTP connection preparation for %s is pending...\n", token);
1216         }
1217
1218         them.sin_family = AF_INET;
1219         /* only works for IPv4 */
1220         them.sin_addr.s_addr = inet_addr(remoteIp); 
1221         them.sin_port = htons(remotePort);
1222         ast_rtp_set_peer(pvt->rtp, &them);
1223
1224         ast_mutex_unlock(&pvt->lock);
1225
1226         if (h323debug)
1227                 ast_log(LOG_DEBUG, "RTP connection prepared for %s\n", token);
1228
1229         return;
1230 }
1231
1232 /**  
1233   *     Call-back function to signal asterisk that the channel has been answered 
1234   * Returns nothing
1235   */
1236 void connection_made(unsigned call_reference, const char *token)
1237 {
1238         struct oh323_pvt *pvt;
1239
1240         if (h323debug)
1241                 ast_log(LOG_DEBUG, "Call %s answered\n", token);
1242
1243         pvt = find_call_locked(call_reference, token); 
1244         if (!pvt) {
1245                 ast_log(LOG_ERROR, "Something is wrong: connection\n");
1246                 return;
1247         }
1248
1249         /* Inform asterisk about remote party connected only on outgoing calls */
1250         if (!pvt->outgoing) {
1251                 ast_mutex_unlock(&pvt->lock);
1252                 return;
1253         }
1254         if (update_state(pvt, AST_STATE_UP, AST_CONTROL_ANSWER))
1255                 ast_mutex_unlock(&pvt->owner->lock);
1256         ast_mutex_unlock(&pvt->lock);
1257         return;
1258 }
1259
1260 int progress(unsigned call_reference, const char *token, int inband)
1261 {
1262         struct oh323_pvt *pvt;
1263
1264         ast_log(LOG_DEBUG, "Received ALERT/PROGRESS message for %s tones\n", (inband ? "inband" : "self-generated"));
1265
1266         pvt = find_call_locked(call_reference, token);
1267         if (!pvt) {
1268                 ast_log(LOG_ERROR, "Private structure not found in progress.\n");
1269                 return -1;
1270         }
1271         if (!pvt->owner) {
1272                 ast_mutex_unlock(&pvt->lock);
1273                 ast_log(LOG_ERROR, "No Asterisk channel associated with private structure.\n");
1274                 return -1;
1275         }
1276         if (update_state(pvt, -1, (inband ? AST_CONTROL_PROGRESS : AST_CONTROL_RINGING)))
1277                 ast_mutex_unlock(&pvt->owner->lock);
1278         ast_mutex_unlock(&pvt->lock);
1279
1280         return 0;
1281 }
1282
1283 /**
1284  *  Call-back function for incoming calls
1285  *
1286  *  Returns 1 on success
1287  */
1288 call_options_t *setup_incoming_call(call_details_t *cd)
1289 {
1290         struct oh323_pvt *pvt;
1291         struct oh323_user *user = NULL;
1292         struct oh323_alias *alias = NULL;
1293         char iabuf[INET_ADDRSTRLEN];
1294
1295         if (h323debug)
1296                 ast_log(LOG_DEBUG, "Setting up incoming call for %s\n", cd->call_token);
1297
1298         /* allocate the call*/
1299         pvt = oh323_alloc(cd->call_reference);
1300
1301         if (!pvt) {
1302                 ast_log(LOG_ERROR, "Unable to allocate private structure, this is bad.\n");
1303                 return NULL;
1304         }
1305
1306         /* Populate the call details in the private structure */
1307         memcpy(&pvt->cd, cd, sizeof(pvt->cd));
1308         memcpy(&pvt->options, &global_options, sizeof(pvt->options));
1309
1310         if (h323debug) {
1311                 ast_verbose(VERBOSE_PREFIX_3 "Setting up Call\n");
1312                 ast_verbose(VERBOSE_PREFIX_3 "\tCall token:  [%s]\n", pvt->cd.call_token);
1313                 ast_verbose(VERBOSE_PREFIX_3 "\tCalling party name:  [%s]\n", pvt->cd.call_source_name);
1314                 ast_verbose(VERBOSE_PREFIX_3 "\tCalling party number:  [%s]\n", pvt->cd.call_source_e164);
1315                 ast_verbose(VERBOSE_PREFIX_3 "\tCalled party name:  [%s]\n", pvt->cd.call_dest_alias);
1316                 ast_verbose(VERBOSE_PREFIX_3 "\tCalled party number:  [%s]\n", pvt->cd.call_dest_e164);
1317         }
1318
1319         /* Decide if we are allowing Gatekeeper routed calls*/
1320         if ((!strcasecmp(cd->sourceIp, gatekeeper)) && (gkroute == -1) && (usingGk)) {
1321                 if (!ast_strlen_zero(cd->call_dest_e164)) {
1322                         strncpy(pvt->exten, cd->call_dest_e164, sizeof(pvt->exten) - 1);
1323                         strncpy(pvt->context, default_context, sizeof(pvt->context) - 1); 
1324                 } else {
1325                         alias = find_alias(cd->call_dest_alias);
1326                         if (!alias) {
1327                                 ast_log(LOG_ERROR, "Call for %s rejected, alias not found\n", cd->call_dest_alias);
1328                                 return NULL;
1329                         }
1330                         strncpy(pvt->exten, alias->name, sizeof(pvt->exten) - 1);
1331                         strncpy(pvt->context, alias->context, sizeof(pvt->context) - 1);
1332                 }
1333         } else {
1334                 /* Either this call is not from the Gatekeeper 
1335                    or we are not allowing gk routed calls */
1336                 user  = find_user(cd);
1337                 if (!user) {
1338                         if (!ast_strlen_zero(pvt->cd.call_dest_e164)) {
1339                                 strncpy(pvt->exten, cd->call_dest_e164, sizeof(pvt->exten) - 1);
1340                         } else {
1341                                 strncpy(pvt->exten, cd->call_dest_alias, sizeof(pvt->exten) - 1);
1342                         }
1343                         if (ast_strlen_zero(default_context)) {
1344                                 ast_log(LOG_ERROR, "Call from '%s' rejected due to no default context\n", pvt->cd.call_source_aliases);
1345                                 return NULL;
1346                         }
1347                         strncpy(pvt->context, default_context, sizeof(pvt->context) - 1);
1348                         ast_log(LOG_DEBUG, "Sending %s to context [%s]\n", cd->call_source_aliases, pvt->context);
1349                         /* XXX: Is it really required??? */
1350 #if 0
1351                         memset(&pvt->options, 0, sizeof(pvt->options));
1352 #endif
1353                 } else {
1354                         if (user->host) {
1355                                 if (strcasecmp(cd->sourceIp, ast_inet_ntoa(iabuf, sizeof(iabuf), user->addr.sin_addr))) {
1356                                         if (ast_strlen_zero(user->context)) {
1357                                                 if (ast_strlen_zero(default_context)) {
1358                                                         ast_log(LOG_ERROR, "Call from '%s' rejected due to non-matching IP address (%s) and no default context\n", user->name, cd->sourceIp);
1359                                                         return NULL;
1360                                                 }
1361                                                 strncpy(pvt->context, default_context, sizeof(pvt->context) - 1);
1362                                         } else {
1363                                                 strncpy(pvt->context, user->context, sizeof(pvt->context) - 1);
1364                                         }
1365                                         pvt->exten[0] = 'i';
1366                                         pvt->exten[1] = '\0';
1367                                         ast_log(LOG_ERROR, "Call from '%s' rejected due to non-matching IP address (%s)s\n", user->name, cd->sourceIp);
1368                                         return NULL;    /* XXX: Hmmm... Why to setup context if we drop connection immediately??? */
1369                                 }
1370                         }
1371                         strncpy(pvt->context, user->context, sizeof(pvt->context) - 1);
1372                         memcpy(&pvt->options, &user->options, sizeof(pvt->options));
1373                         if (!ast_strlen_zero(pvt->cd.call_dest_e164)) {
1374                                 strncpy(pvt->exten, cd->call_dest_e164, sizeof(pvt->exten) - 1);
1375                         } else {
1376                                 strncpy(pvt->exten, cd->call_dest_alias, sizeof(pvt->exten) - 1);
1377                         }
1378                         if (!ast_strlen_zero(user->accountcode)) {
1379                                 strncpy(pvt->accountcode, user->accountcode, sizeof(pvt->accountcode) - 1);
1380                         } 
1381                         if (user->amaflags) {
1382                                 pvt->amaflags = user->amaflags;
1383                         } 
1384                 } 
1385         }
1386         return &pvt->options;
1387 }
1388
1389 /**
1390  * Call-back function to start PBX when OpenH323 ready to serve incoming call
1391  *
1392  * Returns 1 on success
1393  */
1394 static int answer_call(unsigned call_reference, const char *token)
1395 {
1396         struct oh323_pvt *pvt;
1397         struct ast_channel *c = NULL;
1398
1399         if (h323debug)
1400                 ast_log(LOG_DEBUG, "Preparing Asterisk to answer for %s\n", token);
1401
1402         /* Find the call or allocate a private structure if call not found */
1403         pvt = find_call_locked(call_reference, token); 
1404         if (!pvt) {
1405                 ast_log(LOG_ERROR, "Something is wrong: answer_call\n");
1406                 return 0;
1407         }
1408         /* allocate a channel and tell asterisk about it */
1409         c = __oh323_new(pvt, AST_STATE_RINGING, pvt->cd.call_token);
1410
1411         /* And release when done */
1412         ast_mutex_unlock(&pvt->lock);
1413         if (!c) {
1414                 ast_log(LOG_ERROR, "Couldn't create channel. This is bad\n");
1415                 return 0;
1416         }
1417         return 1;
1418 }
1419
1420 /**
1421  * Call-back function to establish an outgoing H.323 call
1422  * 
1423  * Returns 1 on success 
1424  */
1425 int setup_outgoing_call(call_details_t *cd)
1426 {
1427         /* Use argument here or free it immediately */
1428         cleanup_call_details(cd);
1429
1430         return 1;
1431 }
1432
1433 /**
1434   *  Call-back function to signal asterisk that the channel is ringing
1435   *  Returns nothing
1436   */
1437 void chan_ringing(unsigned call_reference, const char *token)
1438 {
1439         struct oh323_pvt *pvt;
1440
1441         if (h323debug)
1442                 ast_log(LOG_DEBUG, "Ringing on %s\n", token);
1443
1444         pvt = find_call_locked(call_reference, token); 
1445         if (!pvt) {
1446                 ast_log(LOG_ERROR, "Something is wrong: ringing\n");
1447                 return;
1448         }
1449         if (!pvt->owner) {
1450                 ast_mutex_unlock(&pvt->lock);
1451                 ast_log(LOG_ERROR, "Channel has no owner\n");
1452                 return;
1453         }
1454         if (update_state(pvt, AST_STATE_RINGING, AST_CONTROL_RINGING))
1455                 ast_mutex_unlock(&pvt->owner->lock);
1456         ast_mutex_unlock(&pvt->lock);
1457         return;
1458 }
1459
1460 /**
1461   * Call-back function to cleanup communication
1462   * Returns nothing,
1463   */
1464 static void cleanup_connection(unsigned call_reference, const char *call_token)
1465 {       
1466         struct oh323_pvt *pvt;
1467
1468         ast_log(LOG_DEBUG, "Cleaning connection to %s\n", call_token);
1469         
1470         while (1) {
1471                 pvt = find_call_locked(call_reference, call_token); 
1472                 if (!pvt) {
1473                         if (h323debug)
1474                                 ast_log(LOG_DEBUG, "No connection for %s\n", call_token);
1475                         return;
1476                 }
1477                 if (!pvt->owner || !ast_mutex_trylock(&pvt->owner->lock))
1478                         break;
1479 #if 1
1480 #ifdef DEBUG_THREADS
1481                 ast_log(LOG_NOTICE, "Avoiding H.323 destory deadlock on %s, locked at %ld/%d by %s (%s:%d)\n", call_token, pvt->owner->lock.thread[0], pvt->owner->lock.reentrancy, pvt->owner->lock.func[0], pvt->owner->lock.file[0], pvt->owner->lock.lineno[0]);
1482 #else
1483                 ast_log(LOG_NOTICE, "Avoiding H.323 destory deadlock on %s\n", call_token);
1484 #endif
1485 #endif
1486                 ast_mutex_unlock(&pvt->lock);
1487                 usleep(1);
1488         }
1489         if (pvt->rtp) {
1490                 /* Immediately stop RTP */
1491                 ast_rtp_destroy(pvt->rtp);
1492                 pvt->rtp = NULL;
1493         }
1494         /* Free dsp used for in-band DTMF detection */
1495         if (pvt->vad) {
1496                 ast_dsp_free(pvt->vad);
1497                 pvt->vad = NULL;
1498         }
1499         cleanup_call_details(&pvt->cd);
1500         pvt->alreadygone = 1;
1501         /* Send hangup */       
1502         if (pvt->owner) {
1503                 pvt->owner->_softhangup |= AST_SOFTHANGUP_DEV;
1504                 ast_queue_hangup(pvt->owner);
1505                 ast_mutex_unlock(&pvt->owner->lock);
1506         }
1507         ast_mutex_unlock(&pvt->lock);
1508         if (h323debug)
1509                 ast_log(LOG_DEBUG, "Connection to %s cleaned\n", call_token);
1510         return; 
1511 }
1512
1513 static void hangup_connection(unsigned int call_reference, const char *token, int cause)
1514 {
1515         struct oh323_pvt *pvt;
1516
1517         ast_log(LOG_DEBUG, "Hanging up connection to %s with cause %d\n", token, cause);
1518         
1519         pvt = find_call_locked(call_reference, token); 
1520         if (!pvt) {
1521                 return;
1522         }
1523         if (pvt->owner && !ast_mutex_trylock(&pvt->owner->lock)) {
1524                 pvt->owner->_softhangup |= AST_SOFTHANGUP_DEV;
1525                 pvt->owner->hangupcause = pvt->hangupcause = cause;
1526                 ast_queue_hangup(pvt->owner);
1527                 ast_mutex_unlock(&pvt->owner->lock);
1528         }
1529         else {
1530                 pvt->needhangup = 1;
1531                 pvt->hangupcause = cause;
1532                 ast_log(LOG_DEBUG, "Hangup for %s is pending\n", token);
1533         }
1534         ast_mutex_unlock(&pvt->lock);
1535 }
1536
1537 void set_dtmf_payload(unsigned call_reference, const char *token, int payload)
1538 {
1539         struct oh323_pvt *pvt;
1540
1541         if (h323debug)
1542                 ast_log(LOG_DEBUG, "Setting DTMF payload to %d on %s\n", payload, token);
1543
1544         pvt = find_call_locked(call_reference, token);
1545         if (!pvt) {
1546                 return;
1547         }
1548         if (pvt->rtp) {
1549                 ast_rtp_set_rtpmap_type(pvt->rtp, payload, "audio", "telephone-event");
1550         }
1551         ast_mutex_unlock(&pvt->lock);
1552         if (h323debug)
1553                 ast_log(LOG_DEBUG, "DTMF payload on %s set to %d\n", token, payload);
1554 }
1555
1556 static void set_local_capabilities(unsigned call_reference, const char *token)
1557 {
1558         struct oh323_pvt *pvt;
1559         int capability, dtmfmode;
1560
1561         if (h323debug)
1562                 ast_log(LOG_DEBUG, "Setting capabilities for connection %s\n", token);
1563
1564         pvt = find_call_locked(call_reference, token);
1565         if (!pvt)
1566                 return;
1567         capability = pvt->options.capability;
1568         dtmfmode = pvt->options.dtmfmode;
1569         ast_mutex_unlock(&pvt->lock);
1570         h323_set_capabilities(token, capability, dtmfmode);
1571
1572         if (h323debug)
1573                 ast_log(LOG_DEBUG, "Capabilities for connection %s is set\n", token);
1574 }
1575
1576 static void *do_monitor(void *data)
1577 {
1578         int res;
1579         int reloading;
1580         struct oh323_pvt *oh323 = NULL;
1581         
1582         for(;;) {
1583                 /* Check for a reload request */
1584                 ast_mutex_lock(&h323_reload_lock);
1585                 reloading = h323_reloading;
1586                 h323_reloading = 0;
1587                 ast_mutex_unlock(&h323_reload_lock);
1588                 if (reloading) {
1589                         if (option_verbose > 0) {
1590                                 ast_verbose(VERBOSE_PREFIX_1 "Reloading H.323\n");
1591                         }
1592                         h323_do_reload();
1593                 }
1594                 /* Check for interfaces needing to be killed */
1595                 ast_mutex_lock(&iflock);
1596 restartsearch:          
1597                 oh323 = iflist;
1598                 while(oh323) {
1599                         if (oh323->needdestroy) {
1600                                 __oh323_destroy(oh323);
1601                                 goto restartsearch;
1602                         }
1603                         oh323 = oh323->next;
1604                 }
1605                 ast_mutex_unlock(&iflock);
1606                 pthread_testcancel();
1607                 /* Wait for sched or io */
1608                 res = ast_sched_wait(sched);
1609                 if ((res < 0) || (res > 1000)) {
1610                         res = 1000;
1611                 }
1612                 res = ast_io_wait(io, res);
1613                 pthread_testcancel();
1614                 ast_mutex_lock(&monlock);
1615                 if (res >= 0) {
1616                         ast_sched_runq(sched);
1617                 }
1618                 ast_mutex_unlock(&monlock);
1619         }
1620         /* Never reached */
1621         return NULL;
1622 }
1623
1624 static int restart_monitor(void)
1625 {
1626         pthread_attr_t attr;
1627         /* If we're supposed to be stopped -- stay stopped */
1628         if (monitor_thread == AST_PTHREADT_STOP) {
1629                 return 0;
1630         }
1631         if (ast_mutex_lock(&monlock)) {
1632                 ast_log(LOG_WARNING, "Unable to lock monitor\n");
1633                 return -1;
1634         }
1635         if (monitor_thread == pthread_self()) {
1636                 ast_mutex_unlock(&monlock);
1637                 ast_log(LOG_WARNING, "Cannot kill myself\n");
1638                 return -1;
1639         }
1640         if (monitor_thread && (monitor_thread != AST_PTHREADT_NULL)) {
1641                 /* Wake up the thread */
1642                 pthread_kill(monitor_thread, SIGURG);
1643         } else {        
1644                 pthread_attr_init(&attr);
1645                 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
1646                 /* Start a new monitor */
1647                 if (ast_pthread_create(&monitor_thread, &attr, do_monitor, NULL) < 0) {
1648                         ast_mutex_unlock(&monlock);
1649                         ast_log(LOG_ERROR, "Unable to start monitor thread.\n");
1650                         return -1;
1651                 }
1652
1653         }
1654         ast_mutex_unlock(&monlock);
1655         return 0;
1656 }
1657
1658 static int h323_do_trace(int fd, int argc, char *argv[])
1659 {
1660         if (argc != 3) {
1661                 return RESULT_SHOWUSAGE;
1662         }
1663         h323_debug(1, atoi(argv[2]));
1664         ast_cli(fd, "H.323 trace set to level %s\n", argv[2]);
1665         return RESULT_SUCCESS;
1666 }
1667
1668 static int h323_no_trace(int fd, int argc, char *argv[])
1669 {
1670         if (argc != 3) {
1671                 return RESULT_SHOWUSAGE;
1672         }
1673         h323_debug(0,0);
1674         ast_cli(fd, "H.323 trace disabled\n");
1675         return RESULT_SUCCESS;
1676 }
1677
1678 static int h323_do_debug(int fd, int argc, char *argv[])
1679 {
1680         if (argc != 2) {
1681                 return RESULT_SHOWUSAGE;
1682         }
1683         h323debug = 1;
1684         ast_cli(fd, "H323 debug enabled\n");
1685         return RESULT_SUCCESS;
1686 }
1687
1688 static int h323_no_debug(int fd, int argc, char *argv[])
1689 {
1690         if (argc != 3) {
1691                 return RESULT_SHOWUSAGE;
1692         }
1693         h323debug = 0;
1694         ast_cli(fd, "H323 Debug disabled\n");
1695         return RESULT_SUCCESS;
1696 }
1697
1698 static int h323_gk_cycle(int fd, int argc, char *argv[])
1699 {
1700 #if 0
1701         if (argc != 3) {
1702                 return RESULT_SHOWUSAGE;
1703         }       
1704         h323_gk_urq();
1705         
1706         /* Possibly register with a GK */
1707         if (!gatekeeper_disable) {
1708                 if (h323_set_gk(gatekeeper_discover, gatekeeper, secret)) {
1709                         ast_log(LOG_ERROR, "Gatekeeper registration failed.\n");
1710                 }
1711         }
1712 #endif
1713         return RESULT_SUCCESS;
1714 }
1715
1716 static int h323_ep_hangup(int fd, int argc, char *argv[])
1717 {
1718         if (argc != 3) {
1719                 return RESULT_SHOWUSAGE;
1720         }
1721         if (h323_soft_hangup(argv[2])) {
1722                 ast_verbose(VERBOSE_PREFIX_3 "Hangup succeeded on %s\n", argv[2]);
1723         } else { 
1724                 ast_verbose(VERBOSE_PREFIX_3 "Hangup failed for %s\n", argv[2]);
1725         }
1726         return RESULT_SUCCESS;
1727 }
1728
1729 static int h323_tokens_show(int fd, int argc, char *argv[])
1730 {
1731         if (argc != 3) {
1732                 return RESULT_SHOWUSAGE;
1733         }
1734         h323_show_tokens();
1735         return RESULT_SUCCESS;
1736 }
1737
1738 static char trace_usage[] = 
1739 "Usage: h.323 trace <level num>\n"
1740 "       Enables H.323 stack tracing for debugging purposes\n";
1741
1742 static char no_trace_usage[] = 
1743 "Usage: h.323 no trace\n"
1744 "       Disables H.323 stack tracing for debugging purposes\n";
1745
1746 static char debug_usage[] = 
1747 "Usage: h.323 debug\n"
1748 "       Enables H.323 debug output\n";
1749
1750 static char no_debug_usage[] = 
1751 "Usage: h.323 no debug\n"
1752 "       Disables H.323 debug output\n";
1753
1754 static char show_codec_usage[] = 
1755 "Usage: h.323 show codec\n"
1756 "       Shows all enabled codecs\n";
1757
1758 static char show_cycle_usage[] = 
1759 "Usage: h.323 gk cycle\n"
1760 "       Manually re-register with the Gatekeper (Currently Disabled)\n";
1761
1762 static char show_hangup_usage[] = 
1763 "Usage: h.323 hangup <token>\n"
1764 "       Manually try to hang up call identified by <token>\n";
1765
1766 static char show_tokens_usage[] = 
1767 "Usage: h.323 show tokens\n"
1768 "       Print out all active call tokens\n";
1769
1770 static char h323_reload_usage[] =
1771 "Usage: h323 reload\n"
1772 "       Reloads H.323 configuration from sip.conf\n";
1773
1774 static struct ast_cli_entry  cli_trace =
1775         { { "h.323", "trace", NULL }, h323_do_trace, "Enable H.323 Stack Tracing", trace_usage };
1776 static struct ast_cli_entry  cli_no_trace =
1777         { { "h.323", "no", "trace", NULL }, h323_no_trace, "Disable H.323 Stack Tracing", no_trace_usage };
1778 static struct ast_cli_entry  cli_debug =
1779         { { "h.323", "debug", NULL }, h323_do_debug, "Enable H.323 debug", debug_usage };
1780 static struct ast_cli_entry  cli_no_debug =
1781         { { "h.323", "no", "debug", NULL }, h323_no_debug, "Disable H.323 debug", no_debug_usage };
1782 static struct ast_cli_entry  cli_show_codecs =
1783         { { "h.323", "show", "codecs", NULL }, h323_show_codec, "Show enabled codecs", show_codec_usage };
1784 static struct ast_cli_entry  cli_gk_cycle =
1785         { { "h.323", "gk", "cycle", NULL }, h323_gk_cycle, "Manually re-register with the Gatekeper", show_cycle_usage };
1786 static struct ast_cli_entry  cli_hangup_call =
1787         { { "h.323", "hangup", NULL }, h323_ep_hangup, "Manually try to hang up a call", show_hangup_usage };
1788 static struct ast_cli_entry  cli_show_tokens =
1789         { { "h.323", "show", "tokens", NULL }, h323_tokens_show, "Show all active call tokens", show_tokens_usage };
1790
1791 static int update_common_options(struct ast_variable *v, struct call_options *options)
1792 {
1793         unsigned int format;
1794         int tmp;
1795
1796         if (!strcasecmp(v->name, "allow")) {
1797                 format = ast_getformatbyname(v->value);
1798                 if (format < 1) 
1799                         ast_log(LOG_WARNING, "Cannot allow unknown format '%s'\n", v->value);
1800                 else
1801                         options->capability |= format;
1802         } else if (!strcasecmp(v->name, "disallow")) {
1803                 format = ast_getformatbyname(v->value);
1804                 if (format < 1) 
1805                         ast_log(LOG_WARNING, "Cannot disallow unknown format '%s'\n", v->value);
1806                 else
1807                         options->capability &= ~format;
1808         } else if (!strcasecmp(v->name, "dtmfmode")) {
1809                 if (!strcasecmp(v->value, "inband")) {
1810                         options->dtmfmode = H323_DTMF_INBAND;
1811                 } else if (!strcasecmp(v->value, "rfc2833")) {
1812                         options->dtmfmode = H323_DTMF_RFC2833;
1813                 } else {
1814                         ast_log(LOG_WARNING, "Unknown dtmf mode '%s', using rfc2833\n", v->value);
1815                         options->dtmfmode = H323_DTMF_RFC2833;
1816                 }
1817         } else if (!strcasecmp(v->name, "dtmfcodec")) {
1818                 tmp = atoi(v->value);
1819                 if (tmp < 96)
1820                         ast_log(LOG_WARNING, "Invalid global dtmfcodec value %s\n", v->value);
1821                 else
1822                         options->dtmfcodec = tmp;
1823         } else if (!strcasecmp(v->name, "bridge")) {
1824                 options->bridge = ast_true(v->value);
1825         } else if (!strcasecmp(v->name, "nat")) {
1826                 options->nat = ast_true(v->value);
1827         } else if (!strcasecmp(v->name, "noFastStart")) {
1828                 options->noFastStart = ast_true(v->value);
1829         } else if (!strcasecmp(v->name, "noH245Tunneling")) {
1830                 options->noH245Tunneling = ast_true(v->value);
1831         } else if (!strcasecmp(v->name, "noSilenceSuppression")) {
1832                 options->noSilenceSuppression = ast_true(v->value);
1833         } else if (!strcasecmp(v->name, "progress_setup")) {
1834                 tmp = atoi(v->value);
1835                 if ((tmp != 0) && (tmp != 1) && (tmp != 3) && (tmp != 8)) {
1836                         ast_log(LOG_WARNING, "Invalid value %d for progress_setup at line %d, assuming 0\n", tmp, v->lineno);
1837                         tmp = 0;
1838                 }
1839                 options->progress_setup = tmp;
1840         } else if (!strcasecmp(v->name, "progress_alert")) {
1841                 tmp = atoi(v->value);
1842                 if ((tmp != 0) && (tmp != 8)) {
1843                         ast_log(LOG_WARNING, "Invalud value %d for progress_alert at line %d, assuming 0\n", tmp, v->lineno);
1844                         tmp = 0;
1845                 }
1846                 options->progress_alert = tmp;
1847         } else if (!strcasecmp(v->name, "progress_audio")) {
1848                 options->progress_audio = ast_true(v->value);
1849         } else
1850                 return 1;
1851
1852         return 0;
1853 }
1854
1855 static struct oh323_alias *build_alias(char *name, struct ast_variable *v)
1856 {
1857         struct oh323_alias *alias;
1858
1859         alias = (struct oh323_alias *)malloc(sizeof(struct oh323_alias));
1860         if (alias) {
1861                 memset(alias, 0, sizeof(struct oh323_alias));
1862                 strncpy(alias->name, name, sizeof(alias->name) - 1);
1863                 while (v) {
1864                         if (!strcasecmp(v->name, "e164")) {
1865                                 strncpy(alias->e164,  v->value, sizeof(alias->e164) - 1);
1866                         } else if (!strcasecmp(v->name, "prefix")) {
1867                                 strncpy(alias->prefix,  v->value, sizeof(alias->prefix) - 1);
1868                         } else if (!strcasecmp(v->name, "context")) {
1869                                 strncpy(alias->context,  v->value, sizeof(alias->context) - 1);
1870                         } else if (!strcasecmp(v->name, "secret")) {
1871                                 strncpy(alias->secret,  v->value, sizeof(alias->secret) - 1);
1872                         } else {
1873                                 if (strcasecmp(v->value, "h323")) {     
1874                                         ast_log(LOG_WARNING, "Keyword %s does not make sense in type=h323\n", v->value);
1875                                 }
1876                         }
1877                         v = v->next;
1878                 }
1879         }
1880         return alias;
1881 }
1882
1883 static struct oh323_user *build_user(char *name, struct ast_variable *v)
1884 {
1885         struct oh323_user *user;
1886         int format;
1887
1888         user = (struct oh323_user *)malloc(sizeof(struct oh323_user));
1889         if (user) {
1890                 memset(user, 0, sizeof(struct oh323_user));
1891                 strncpy(user->name, name, sizeof(user->name) - 1);
1892                 memcpy(&user->options, &global_options, sizeof(user->options));
1893                 /* Set default context */
1894                 strncpy(user->context, default_context, sizeof(user->context) - 1);
1895                 while(v) {
1896                         if (!strcasecmp(v->name, "context")) {
1897                                 strncpy(user->context, v->value, sizeof(user->context) - 1);
1898                         } else if (!update_common_options(v, &user->options)) {
1899                                 /* dummy */
1900                         } else if (!strcasecmp(v->name, "secret")) {
1901                                 strncpy(user->secret, v->value, sizeof(user->secret) - 1);
1902                         } else if (!strcasecmp(v->name, "callerid")) {
1903                                 strncpy(user->callerid, v->value, sizeof(user->callerid) - 1);
1904                         } else if (!strcasecmp(v->name, "accountcode")) {
1905                                 strncpy(user->accountcode, v->value, sizeof(user->accountcode) - 1);
1906                         } else if (!strcasecmp(v->name, "host")) {
1907                                 if (!strcasecmp(v->value, "dynamic")) {
1908                                         ast_log(LOG_ERROR, "A dynamic host on a type=user does not make any sense\n");
1909                                         free(user);
1910                                         return NULL;
1911                                 } else if (ast_get_ip(&user->addr, v->value)) {
1912                                         free(user);
1913                                         return NULL;
1914                                 } 
1915                                 /* Let us know we need to use ip authentication */
1916                                 user->host = 1;
1917                         } else if (!strcasecmp(v->name, "amaflags")) {
1918                                 format = ast_cdr_amaflags2int(v->value);
1919                                 if (format < 0) {
1920                                         ast_log(LOG_WARNING, "Invalid AMA Flags: %s at line %d\n", v->value, v->lineno);
1921                                 } else {
1922                                         user->amaflags = format;
1923                                 }
1924                         }
1925                         v = v->next;
1926                 }
1927         }
1928         return user;
1929 }
1930
1931 static struct oh323_peer *build_peer(char *name, struct ast_variable *v)
1932 {
1933         struct oh323_peer *peer;
1934         struct oh323_peer *prev;
1935         struct ast_ha *oldha = NULL;
1936         int found=0;
1937
1938         prev = NULL;
1939         ast_mutex_lock(&peerl.lock);
1940         peer = peerl.peers;
1941
1942         while(peer) {
1943                 if (!strcasecmp(peer->name, name)) {    
1944                         break;
1945                 }
1946                 prev = peer;
1947                 peer = peer->next;
1948         }
1949
1950         if (peer) {
1951                 found++;
1952                 /* Already in the list, remove it and it will be added back (or FREE'd) */
1953                 if (prev) {
1954                         prev->next = peer->next;
1955                 } else {
1956                         peerl.peers = peer->next;
1957                 }
1958                 ast_mutex_unlock(&peerl.lock);
1959         } else {
1960                 ast_mutex_unlock(&peerl.lock);
1961                 peer = (struct oh323_peer*)malloc(sizeof(struct oh323_peer));
1962                 if (peer)
1963                         memset(peer, 0, sizeof(struct oh323_peer));
1964         }
1965         if (peer) {
1966                 if (!found) {
1967                         strncpy(peer->name, name, sizeof(peer->name) - 1);
1968                         peer->addr.sin_port = htons(h323_signalling_port);
1969                         peer->addr.sin_family = AF_INET;
1970                 }
1971                 oldha = peer->ha;
1972                 peer->ha = NULL;
1973                 peer->addr.sin_family = AF_INET;
1974                 memcpy(&peer->options, &global_options, sizeof(peer->options));
1975
1976                 while(v) {
1977                         if (!update_common_options(v, &peer->options)) {
1978                                 /* dummy */
1979                         } else if (!strcasecmp(v->name, "host")) {
1980                                 if (!strcasecmp(v->value, "dynamic")) {
1981                                         ast_log(LOG_ERROR, "Dynamic host configuration not implemented.\n");
1982                                         free(peer);
1983                                         return NULL;
1984                                 }
1985                                 if (ast_get_ip(&peer->addr, v->value)) {
1986                                                 ast_log(LOG_ERROR, "Could not determine IP for %s\n", v->value);
1987                                                 free(peer);
1988                                                 return NULL;
1989                                 }
1990                         } else if (!strcasecmp(v->name, "port")) {
1991                                 peer->addr.sin_port = htons(atoi(v->value));
1992                         }
1993                         v=v->next;
1994                 }
1995         }
1996         return peer;
1997 }
1998
1999 int reload_config(void)
2000 {       
2001         int format;
2002         struct ast_config *cfg;
2003         struct ast_variable *v;
2004         struct oh323_peer *peer   = NULL;
2005         struct oh323_user *user   = NULL;
2006         struct oh323_alias *alias = NULL;
2007         struct ast_hostent ahp; struct hostent *hp;
2008         char *cat;
2009         char *utype;
2010         
2011         cfg = ast_config_load(config);
2012
2013         /* We *must* have a config file otherwise stop immediately */
2014         if (!cfg) {
2015                 ast_log(LOG_NOTICE, "Unable to load config %s, H.323 disabled\n", config);
2016                 return 1;
2017         }
2018         
2019        /* fire up the H.323 Endpoint */       
2020         if (!h323_end_point_exist()) {
2021                h323_end_point_create();        
2022         }
2023         h323debug = 0;
2024         memset(&bindaddr, 0, sizeof(bindaddr));
2025         memset(&global_options, 0, sizeof(global_options));
2026         global_options.dtmfcodec = 101;
2027         global_options.dtmfmode = H323_DTMF_RFC2833;
2028         global_options.capability = GLOBAL_CAPABILITY;
2029         global_options.bridge = 1;              /* Do native bridging by default */
2030         v = ast_variable_browse(cfg, "general");
2031         while(v) {
2032                 /* Create the interface list */
2033                 if (!strcasecmp(v->name, "port")) {
2034                         h323_signalling_port = (int)strtol(v->value, NULL, 10);
2035                 } else if (!strcasecmp(v->name, "bindaddr")) {
2036                         if (!(hp = ast_gethostbyname(v->value, &ahp))) {
2037                                 ast_log(LOG_WARNING, "Invalid address: %s\n", v->value);
2038                         } else {
2039                                 memcpy(&bindaddr.sin_addr, hp->h_addr, sizeof(bindaddr.sin_addr));
2040                         }
2041                 } else if (!strcasecmp(v->name, "tos")) {
2042                         if (sscanf(v->value, "%d", &format)) {
2043                                 tos = format & 0xff;
2044                         } else if (!strcasecmp(v->value, "lowdelay")) {
2045                                 tos = IPTOS_LOWDELAY;
2046                         } else if (!strcasecmp(v->value, "throughput")) {
2047                                 tos = IPTOS_THROUGHPUT;
2048                         } else if (!strcasecmp(v->value, "reliability")) {
2049                                 tos = IPTOS_RELIABILITY;
2050                         } else if (!strcasecmp(v->value, "mincost")) {
2051                                 tos = IPTOS_MINCOST;
2052                         } else if (!strcasecmp(v->value, "none")) {
2053                                 tos = 0;
2054                         } else {
2055                                 ast_log(LOG_WARNING, "Invalid tos value at line %d, should be 'lowdelay', 'throughput', 'reliability', 'mincost', or 'none'\n", v->lineno);
2056                         }
2057                 } else if (!strcasecmp(v->name, "gatekeeper")) {
2058                         if (!strcasecmp(v->value, "DISABLE")) {
2059                                 gatekeeper_disable = 1;
2060                                 usingGk = 0;
2061                         } else if (!strcasecmp(v->value, "DISCOVER")) {
2062                                 gatekeeper_disable = 0;
2063                                 gatekeeper_discover = 1;
2064                                 usingGk = 1;
2065                         } else {
2066                                 gatekeeper_disable = 0;
2067                                 usingGk = 1;
2068                                 strncpy(gatekeeper, v->value, sizeof(gatekeeper) - 1);
2069                         }
2070                 } else if (!strcasecmp(v->name, "secret")) {
2071                         strncpy(secret, v->value, sizeof(secret) - 1);
2072                 } else if (!strcasecmp(v->name, "AllowGKRouted")) {
2073                         gkroute = ast_true(v->value);
2074                 } else if (!strcasecmp(v->name, "context")) {
2075                         strncpy(default_context, v->value, sizeof(default_context) - 1);
2076                         ast_verbose(VERBOSE_PREFIX_2 "Setting default context to %s\n", default_context);       
2077                 } else if (!strcasecmp(v->name, "UserByAlias")) {
2078                         userbyalias = ast_true(v->value);
2079                 } else if (!update_common_options(v, &global_options)) {
2080                         /* dummy */
2081                 }
2082                 v = v->next;    
2083         }
2084         
2085         cat = ast_category_browse(cfg, NULL);
2086         while(cat) {
2087                 if (strcasecmp(cat, "general")) {
2088                         utype = ast_variable_retrieve(cfg, cat, "type");
2089                         if (utype) {
2090                                 if (!strcasecmp(utype, "user")) {
2091                                         user = build_user(cat, ast_variable_browse(cfg, cat));
2092                                         if (user) {
2093                                                 ast_mutex_lock(&userl.lock);
2094                                                 user->next = userl.users;
2095                                                 userl.users = user;
2096                                                 ast_mutex_unlock(&userl.lock);
2097                                         }
2098                                 }  else if (!strcasecmp(utype, "peer")) {
2099                                         peer = build_peer(cat, ast_variable_browse(cfg, cat));
2100                                         if (peer) {
2101                                                 ast_mutex_lock(&peerl.lock);
2102                                                 peer->next = peerl.peers;
2103                                                 peerl.peers = peer;
2104                                                 ast_mutex_unlock(&peerl.lock);
2105                                         }
2106                                 }  else if (!strcasecmp(utype, "friend")) {
2107                                         user = build_user(cat, ast_variable_browse(cfg, cat));
2108                                         peer = build_peer(cat, ast_variable_browse(cfg, cat));
2109                                         if (user) {
2110                                                 ast_mutex_lock(&userl.lock);
2111                                                 user->next = userl.users;
2112                                                 userl.users = user;
2113                                                 ast_mutex_unlock(&userl.lock);
2114                                         }
2115                                         if (peer) {
2116                                                 ast_mutex_lock(&peerl.lock);
2117                                                 peer->next = peerl.peers;
2118                                                 peerl.peers = peer;
2119                                                 ast_mutex_unlock(&peerl.lock);
2120                                         }
2121                                 }  else if (!strcasecmp(utype, "h323") || !strcasecmp(utype, "alias")) {
2122                                         alias = build_alias(cat, ast_variable_browse(cfg, cat));
2123                                         if (alias) {
2124                                                 ast_mutex_lock(&aliasl.lock);
2125                                                 alias->next = aliasl.aliases;
2126                                                 aliasl.aliases = alias;
2127                                                 ast_mutex_unlock(&aliasl.lock);
2128                                         }
2129                                 } else {
2130                                         ast_log(LOG_WARNING, "Unknown type '%s' for '%s' in %s\n", utype, cat, config);
2131                                 }
2132                         } else {
2133                                 ast_log(LOG_WARNING, "Section '%s' lacks type\n", cat);
2134                         }
2135                 }
2136                 cat = ast_category_browse(cfg, cat);
2137         }
2138         ast_config_destroy(cfg);
2139
2140         /* Register our H.323 aliases if any*/
2141         while (alias) {         
2142                 if (h323_set_alias(alias)) {
2143                         ast_log(LOG_ERROR, "Alias %s rejected by endpoint\n", alias->name);
2144                         return -1;
2145                 }       
2146                 alias = alias->next;
2147         }
2148
2149         return 0;
2150 }
2151
2152 void delete_users(void)
2153 {
2154         struct oh323_user *user, *userlast;
2155         struct oh323_peer *peer;
2156         
2157         /* Delete all users */
2158         ast_mutex_lock(&userl.lock);
2159         for (user=userl.users;user;) {
2160                 userlast = user;
2161                 user=user->next;
2162                 free(userlast);
2163         }
2164         userl.users=NULL;
2165         ast_mutex_unlock(&userl.lock);
2166         ast_mutex_lock(&peerl.lock);
2167         for (peer=peerl.peers;peer;) {
2168                 /* Assume all will be deleted, and we'll find out for sure later */
2169                 peer->delme = 1;
2170                 peer = peer->next;
2171         }
2172         ast_mutex_unlock(&peerl.lock);
2173 }
2174
2175 void delete_aliases(void)
2176 {
2177         struct oh323_alias *alias, *aliaslast;
2178                 
2179         /* Delete all users */
2180         ast_mutex_lock(&aliasl.lock);
2181         for (alias=aliasl.aliases;alias;) {
2182                 aliaslast = alias;
2183                 alias=alias->next;
2184                 free(aliaslast);
2185         }
2186         aliasl.aliases=NULL;
2187         ast_mutex_unlock(&aliasl.lock);
2188 }
2189
2190 void prune_peers(void)
2191 {
2192         /* Prune peers who still are supposed to be deleted */
2193         struct oh323_peer *peer, *peerlast, *peernext;
2194         ast_mutex_lock(&peerl.lock);
2195         peerlast = NULL;
2196         for (peer=peerl.peers;peer;) {
2197                 peernext = peer->next;
2198                 if (peer->delme) {
2199                         free(peer);
2200                         if (peerlast) {
2201                                 peerlast->next = peernext;
2202                         } else {
2203                                 peerl.peers = peernext;
2204                         }
2205                 } else {
2206                         peerlast = peer;
2207                 }
2208                 peer = peernext;
2209         }
2210         ast_mutex_unlock(&peerl.lock);
2211 }
2212
2213 static int h323_reload(int fd, int argc, char *argv[])
2214 {
2215         ast_mutex_lock(&h323_reload_lock);
2216         if (h323_reloading) {
2217                 ast_verbose("Previous H.323 reload not yet done\n");
2218         } else {
2219                 h323_reloading = 1;
2220         }
2221         ast_mutex_unlock(&h323_reload_lock);
2222         restart_monitor();
2223         return 0;
2224 }
2225
2226 static int h323_do_reload(void)
2227 {
2228         delete_users();
2229         delete_aliases();
2230         prune_peers();
2231         reload_config();
2232         restart_monitor();
2233         return 0;
2234 }
2235
2236 int reload(void)
2237 {
2238         return h323_reload(0, 0, NULL);
2239 }
2240
2241 static struct ast_cli_entry  cli_h323_reload =
2242         { { "h.323", "reload", NULL }, h323_reload, "Reload H.323 configuration", h323_reload_usage };
2243
2244 static struct ast_rtp *oh323_get_rtp_peer(struct ast_channel *chan)
2245 {
2246         struct oh323_pvt *pvt;
2247         pvt = (struct oh323_pvt *) chan->tech_pvt;
2248         if (pvt && pvt->rtp && pvt->options.bridge) {
2249                 return pvt->rtp;
2250         }
2251         return NULL;
2252 }
2253
2254 static struct ast_rtp *oh323_get_vrtp_peer(struct ast_channel *chan)
2255 {
2256         return NULL;
2257 }
2258
2259 static char *convertcap(int cap)
2260 {
2261         switch (cap) {
2262         case AST_FORMAT_G723_1:
2263                 return "G.723";
2264         case AST_FORMAT_GSM:
2265                 return "GSM";
2266         case AST_FORMAT_ULAW:
2267                 return "ULAW";
2268         case AST_FORMAT_ALAW:
2269                 return "ALAW";
2270         case AST_FORMAT_ADPCM:
2271                 return "G.728";
2272         case AST_FORMAT_G729A:
2273                 return "G.729";
2274         case AST_FORMAT_SPEEX:
2275                 return "SPEEX";
2276         case AST_FORMAT_ILBC:
2277                 return "ILBC";
2278         default:
2279                 ast_log(LOG_NOTICE, "Don't know how to deal with mode %d\n", cap);
2280                 return NULL;
2281         }
2282 }
2283
2284 static int oh323_set_rtp_peer(struct ast_channel *chan, struct ast_rtp *rtp, struct ast_rtp *vrtp, int codecs, int nat_active)
2285 {
2286         /* XXX Deal with Video */
2287         struct oh323_pvt *pvt;
2288         struct sockaddr_in them;
2289         struct sockaddr_in us;
2290         char *mode;
2291         char iabuf[INET_ADDRSTRLEN];
2292
2293         if (!rtp) {
2294                 return 0;
2295         }
2296
2297         mode = convertcap(chan->writeformat); 
2298         pvt = (struct oh323_pvt *) chan->tech_pvt;
2299         if (!pvt) {
2300                 ast_log(LOG_ERROR, "No Private Structure, this is bad\n");
2301                 return -1;
2302         }
2303         ast_rtp_get_peer(rtp, &them);   
2304         ast_rtp_get_us(rtp, &us);
2305         h323_native_bridge(pvt->cd.call_token, ast_inet_ntoa(iabuf, sizeof(iabuf), them.sin_addr), mode);
2306         return 0;
2307 }
2308
2309 static struct ast_rtp_protocol oh323_rtp = {
2310         .type = "H323",
2311         .get_rtp_info = oh323_get_rtp_peer,
2312         .get_vrtp_info = oh323_get_vrtp_peer,
2313         .set_rtp_peer=  oh323_set_rtp_peer,
2314 };
2315
2316 int load_module()
2317 {
2318         int res;
2319         ast_mutex_init(&userl.lock);
2320         ast_mutex_init(&peerl.lock);
2321         ast_mutex_init(&aliasl.lock);
2322         sched = sched_context_create();
2323         if (!sched) {
2324                 ast_log(LOG_WARNING, "Unable to create schedule context\n");
2325         }
2326         io = io_context_create();
2327         if (!io) {
2328                 ast_log(LOG_WARNING, "Unable to create I/O context\n");
2329         }
2330         res = reload_config();
2331         if (res) {
2332                 return 0;
2333         } else {
2334                 /* Make sure we can register our channel type */
2335                 if (ast_channel_register(&oh323_tech)) {
2336                         ast_log(LOG_ERROR, "Unable to register channel class 'H323'\n");
2337                         h323_end_process();
2338                         return -1;
2339                 }
2340                 ast_cli_register(&cli_debug);
2341                 ast_cli_register(&cli_no_debug);
2342                 ast_cli_register(&cli_trace);
2343                 ast_cli_register(&cli_no_trace);
2344                 ast_cli_register(&cli_show_codecs);
2345                 ast_cli_register(&cli_gk_cycle);
2346                 ast_cli_register(&cli_hangup_call);
2347                 ast_cli_register(&cli_show_tokens);
2348                 ast_cli_register(&cli_h323_reload);
2349
2350                 ast_rtp_proto_register(&oh323_rtp);
2351
2352                 /* Register our callback functions */
2353                 h323_callback_register(setup_incoming_call, 
2354                                                 setup_outgoing_call,                                                     
2355                                                 external_rtp_create, 
2356                                                 setup_rtp_connection, 
2357                                                 cleanup_connection, 
2358                                                 chan_ringing,
2359                                                 connection_made, 
2360                                                 send_digit,
2361                                                 answer_call,
2362                                                 progress,
2363                                                 set_dtmf_payload,
2364                                                 hangup_connection,
2365                                                 set_local_capabilities);
2366                 /* start the h.323 listener */
2367                 if (h323_start_listener(h323_signalling_port, bindaddr)) {
2368                         ast_log(LOG_ERROR, "Unable to create H323 listener.\n");
2369                         return -1;
2370                 }
2371                 /* Possibly register with a GK */
2372                 if (!gatekeeper_disable) {
2373                         if (h323_set_gk(gatekeeper_discover, gatekeeper, secret)) {
2374                                 ast_log(LOG_ERROR, "Gatekeeper registration failed.\n");
2375                                 return 0;
2376                         }
2377                 }
2378                 /* And start the monitor for the first time */
2379                 restart_monitor();
2380         }
2381         return res;
2382 }
2383
2384 int unload_module() 
2385 {
2386         struct oh323_pvt *p, *pl;
2387
2388         /* unregister commands */
2389         ast_cli_unregister(&cli_debug);
2390         ast_cli_unregister(&cli_no_debug);
2391         ast_cli_unregister(&cli_trace);
2392         ast_cli_unregister(&cli_no_trace);   
2393         ast_cli_unregister(&cli_show_codecs);
2394         ast_cli_unregister(&cli_gk_cycle);
2395         ast_cli_unregister(&cli_hangup_call);
2396         ast_cli_unregister(&cli_show_tokens);
2397         ast_cli_unregister(&cli_h323_reload);
2398         ast_rtp_proto_unregister(&oh323_rtp);
2399         ast_channel_unregister(&oh323_tech);
2400                 
2401         if (!ast_mutex_lock(&iflock)) {
2402                 /* hangup all interfaces if they have an owner */
2403                 p = iflist;
2404                 while(p) {
2405                         if (p->owner) {
2406                                 ast_softhangup(p->owner, AST_SOFTHANGUP_APPUNLOAD);
2407                         }
2408                         p = p->next;
2409                 }
2410                 iflist = NULL;
2411                 ast_mutex_unlock(&iflock);
2412         } else {
2413                 ast_log(LOG_WARNING, "Unable to lock the interface list\n");
2414                 return -1;
2415         }
2416         if (!ast_mutex_lock(&monlock)) {
2417                 if (monitor_thread && (monitor_thread != AST_PTHREADT_STOP)) {
2418                         /* this causes a seg, anyone know why? */
2419                         pthread_cancel(monitor_thread);
2420                         pthread_kill(monitor_thread, SIGURG);
2421                         pthread_join(monitor_thread, NULL);
2422                 }
2423                 monitor_thread = AST_PTHREADT_STOP;
2424                 ast_mutex_unlock(&monlock);
2425         } else {
2426                 ast_log(LOG_WARNING, "Unable to lock the monitor\n");
2427                 return -1;
2428         }
2429         if (!ast_mutex_lock(&iflock)) {
2430                 /* destroy all the interfaces and free their memory */
2431                 p = iflist;
2432                 while(p) {
2433                         pl = p;
2434                         p = p->next;
2435                         /* free associated memory */
2436                         ast_mutex_destroy(&pl->lock);
2437                         free(pl);
2438                 }
2439                 iflist = NULL;
2440                 ast_mutex_unlock(&iflock);
2441         } else {
2442                 ast_log(LOG_WARNING, "Unable to lock the interface list\n");
2443                 return -1;
2444         }
2445         h323_gk_urq();
2446         h323_end_process();
2447         io_context_destroy(io);
2448         sched_context_destroy(sched);
2449         delete_users();
2450         delete_aliases();
2451         prune_peers();
2452         ast_mutex_destroy(&aliasl.lock);
2453         ast_mutex_destroy(&userl.lock);
2454         ast_mutex_destroy(&peerl.lock);
2455         return 0; 
2456
2457
2458 int usecount()
2459 {
2460         return usecnt;
2461 }
2462
2463 const char *description()
2464 {
2465         return (char *) desc;
2466 }
2467
2468 const char *key()
2469 {
2470         return ASTERISK_GPL_KEY;
2471 }