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