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