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